Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd1a68d559 | ||
|
|
11880cea13 | ||
|
|
9615fe7769 | ||
|
|
07eb6464e0 |
@@ -21,6 +21,16 @@ id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 50
|
||||
|
||||
[[orchestrator.eval.env]]
|
||||
id = "alphabet-sort"
|
||||
name = "alphabet-sort"
|
||||
num_examples = 50
|
||||
rollouts_per_example = 4
|
||||
args = { min_turns = 2, max_turns = 2 }
|
||||
|
||||
[trainer]
|
||||
|
||||
[inference]
|
||||
@@ -8,11 +8,14 @@ name = "PrimeIntellect/Qwen3-0.6B-Reverse-Text-SFT"
|
||||
batch_size = 128
|
||||
rollouts_per_example = 16
|
||||
|
||||
# -- train envs --
|
||||
|
||||
[orchestrator.train.sampling]
|
||||
max_completion_tokens = 128
|
||||
|
||||
[[orchestrator.train.env]]
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-1"
|
||||
|
||||
[orchestrator.train.env.sampling]
|
||||
max_completion_tokens = 127
|
||||
@@ -21,6 +24,8 @@ max_completion_tokens = 127
|
||||
id = "reverse-text"
|
||||
name = "reverse-text-2"
|
||||
|
||||
# -- eval envs --
|
||||
|
||||
[orchestrator.eval]
|
||||
interval = 5
|
||||
|
||||
@@ -38,6 +43,7 @@ id = "reverse-text"
|
||||
name = "eval-custom"
|
||||
num_examples = 16
|
||||
rollouts_per_example = 2
|
||||
interval = 10
|
||||
|
||||
[orchestrator.eval.env.sampling]
|
||||
max_completion_tokens = 256
|
||||
|
||||
@@ -382,6 +382,14 @@ class EvalEnvConfig(EnvConfig):
|
||||
),
|
||||
] = 1
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
ge=1,
|
||||
description="Per-env eval interval. If unset, inherits from the group-level eval interval.",
|
||||
),
|
||||
] = 100
|
||||
|
||||
|
||||
class TrainConfig(BaseConfig):
|
||||
"""Configures training environments and their shared sampling settings."""
|
||||
@@ -390,17 +398,32 @@ class TrainConfig(BaseConfig):
|
||||
|
||||
sampling: TrainSamplingConfig = TrainSamplingConfig()
|
||||
|
||||
num_workers: Annotated[
|
||||
int | Literal["auto"],
|
||||
Field(
|
||||
description="Default number of worker processes for env servers. Can be overridden per env.",
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(ge=0, description="Default number of retries for failed rollouts. Can be overridden per env."),
|
||||
] = 0
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_sampling(self):
|
||||
"""Resolve each env's sampling by merging group defaults with per-env overrides."""
|
||||
group = self.sampling.model_dump()
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, and max_retries."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = TrainSamplingConfig(**group)
|
||||
env.sampling = TrainSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group.copy()
|
||||
merged.update(env.sampling.model_dump(exclude_unset=True))
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = TrainSamplingConfig(**merged)
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
@@ -445,6 +468,18 @@ class EvalConfig(BaseConfig):
|
||||
Field(ge=1, description="Default number of rollouts per example. Can be overridden per env."),
|
||||
] = 1
|
||||
|
||||
num_workers: Annotated[
|
||||
int | Literal["auto"],
|
||||
Field(
|
||||
description="Default number of worker processes for env servers. Can be overridden per env.",
|
||||
),
|
||||
] = "auto"
|
||||
|
||||
max_retries: Annotated[
|
||||
int,
|
||||
Field(ge=0, description="Default number of retries for failed rollouts. Can be overridden per env."),
|
||||
] = 0
|
||||
|
||||
interval: Annotated[
|
||||
int,
|
||||
Field(
|
||||
@@ -454,27 +489,26 @@ class EvalConfig(BaseConfig):
|
||||
] = 100
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_sampling(self):
|
||||
"""Resolve each env's sampling by merging group defaults with per-env overrides."""
|
||||
group = self.sampling.model_dump()
|
||||
def resolve_env_defaults(self):
|
||||
"""Resolve per-env overrides: inherit group-level sampling, num_workers, max_retries, num_examples, rollouts_per_example, and interval. Then resolve auto num_workers."""
|
||||
group_sampling = self.sampling.model_dump()
|
||||
for env in self.env:
|
||||
if "sampling" not in env.model_fields_set:
|
||||
env.sampling = EvalSamplingConfig(**group)
|
||||
env.sampling = EvalSamplingConfig(**group_sampling)
|
||||
else:
|
||||
merged = group.copy()
|
||||
merged.update(env.sampling.model_dump(exclude_unset=True))
|
||||
merged = group_sampling | env.sampling.model_dump(exclude_unset=True)
|
||||
env.sampling = EvalSamplingConfig(**merged)
|
||||
return self
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_env_defaults(self):
|
||||
"""Fill per-env num_examples and rollouts_per_example from group defaults, then resolve num_workers."""
|
||||
for env in self.env:
|
||||
if "num_examples" not in env.model_fields_set:
|
||||
env.num_examples = self.num_examples
|
||||
if "rollouts_per_example" not in env.model_fields_set:
|
||||
env.rollouts_per_example = self.rollouts_per_example
|
||||
# Resolve num_workers now that num_examples and rollouts_per_example are set
|
||||
if "interval" not in env.model_fields_set:
|
||||
env.interval = self.interval
|
||||
if "num_workers" not in env.model_fields_set:
|
||||
env.num_workers = self.num_workers
|
||||
if "max_retries" not in env.model_fields_set:
|
||||
env.max_retries = self.max_retries
|
||||
# Resolve auto num_workers now that num_examples and rollouts_per_example are set
|
||||
if env.num_workers == "auto":
|
||||
if env.num_examples == -1:
|
||||
env.num_workers = 4
|
||||
|
||||
@@ -203,6 +203,19 @@ class SFTConfig(BaseConfig):
|
||||
),
|
||||
] = False
|
||||
|
||||
matmul_precision: Annotated[
|
||||
Literal["highest", "high", "medium"],
|
||||
Field(
|
||||
description=(
|
||||
"Precision for float32 matrix multiplications. "
|
||||
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
|
||||
"catastrophic precision loss in softmax over large vocabularies). "
|
||||
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
|
||||
"precision tradeoff. See torch.set_float32_matmul_precision docs."
|
||||
),
|
||||
),
|
||||
] = "high"
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(description="Maximum number of steps to run training for. If None, will run indefinitely."),
|
||||
|
||||
@@ -760,6 +760,19 @@ class TrainerConfig(BaseConfig):
|
||||
),
|
||||
] = Path("outputs")
|
||||
|
||||
matmul_precision: Annotated[
|
||||
Literal["highest", "high", "medium"],
|
||||
Field(
|
||||
description=(
|
||||
"Precision for float32 matrix multiplications. "
|
||||
"Use 'highest' for full FP32 (required on ROCm/AMD GPUs to avoid "
|
||||
"catastrophic precision loss in softmax over large vocabularies). "
|
||||
"Use 'high' to enable TF32 on NVIDIA GPUs for a speedup with minor "
|
||||
"precision tradeoff. See torch.set_float32_matmul_precision docs."
|
||||
),
|
||||
),
|
||||
] = "high"
|
||||
|
||||
max_steps: Annotated[
|
||||
int | None,
|
||||
Field(
|
||||
|
||||
@@ -36,7 +36,7 @@ from transformers import AutoProcessor, AutoTokenizer
|
||||
from prime_rl.configs.orchestrator import OrchestratorConfig
|
||||
from prime_rl.orchestrator.buffer import Buffer
|
||||
from prime_rl.orchestrator.ckpt import Progress, setup_ckpt_manager
|
||||
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.envs import EvalEnv, EvalEnvs, TrainEnvs
|
||||
from prime_rl.orchestrator.filters import apply_filters, setup_filters
|
||||
from prime_rl.orchestrator.scheduler import Scheduler
|
||||
from prime_rl.orchestrator.utils import (
|
||||
@@ -110,14 +110,12 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
# Setup rollout inference pool (handles both static and elastic modes)
|
||||
rollout_client_config, rollout_model_name, enable_policy_updates = setup_external_rollout_model(config, logger)
|
||||
|
||||
client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
if config.use_token_client:
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled. Only use this if your environment has a linear "
|
||||
"history and the chat template has the extension property."
|
||||
)
|
||||
train_client_type = "openai_chat_completions_token" if config.use_token_client else "openai_chat_completions"
|
||||
inference_pool = await setup_inference_pool(
|
||||
rollout_client_config, model_name=rollout_model_name, client_type=client_type
|
||||
rollout_client_config,
|
||||
model_name=rollout_model_name,
|
||||
train_client_type=train_client_type,
|
||||
eval_client_type="openai_chat_completions",
|
||||
)
|
||||
|
||||
# Setup teacher inference pool if configured
|
||||
@@ -127,7 +125,9 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
f"model={config.teacher_model.model.name})"
|
||||
)
|
||||
teacher_inference_pool = await setup_inference_pool(
|
||||
config.teacher_model.client, model_name=config.teacher_model.model.name
|
||||
config.teacher_model.client,
|
||||
model_name=config.teacher_model.model.name,
|
||||
train_client_type="openai_chat_completions",
|
||||
)
|
||||
else:
|
||||
teacher_inference_pool = None
|
||||
@@ -273,8 +273,8 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Initializing training batch sender ({config.rollout_transport})")
|
||||
training_batch_sender = setup_training_batch_sender(config.output_dir, config.rollout_transport)
|
||||
|
||||
# Track last online eval checkpoint step for this process
|
||||
last_eval_step = -1
|
||||
# Track last online eval checkpoint step per eval env
|
||||
last_eval_steps: dict[str, int] = {env.name: -1 for env in eval_envs} if eval_envs else {}
|
||||
# Track previous ckpt_step to detect when ckpt_step jumps over eval interval boundaries
|
||||
prev_ckpt_step = -1
|
||||
|
||||
@@ -287,7 +287,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
scheduler.ckpt_step = progress.step # Always resume from the latest checkpoint
|
||||
if config.eval and config.eval.skip_eval_on_resume:
|
||||
prev_ckpt_step = scheduler.ckpt_step
|
||||
last_eval_step = scheduler.ckpt_step
|
||||
last_eval_steps = {name: scheduler.ckpt_step for name in last_eval_steps}
|
||||
logger.info(f"Skipping online eval on resume (ckpt_step={scheduler.ckpt_step})")
|
||||
else:
|
||||
# Allow eval at resumed step by setting prev_ckpt_step one behind
|
||||
@@ -346,24 +346,25 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
|
||||
# Run evals BEFORE training (blocking). Weight updates are paused via
|
||||
# scheduler.checkpoint_ready during eval to ensure consistent weights.
|
||||
# Use range check to handle ckpt_step jumping over interval boundaries.
|
||||
eval_ckpt_step = None
|
||||
# Each eval env has its own interval, so we check each independently.
|
||||
envs_to_eval: list[EvalEnv] = []
|
||||
if config.eval:
|
||||
assert eval_envs is not None
|
||||
eval_ckpt_step = compute_eval_ckpt_step(
|
||||
ckpt_step=ckpt_step,
|
||||
prev_ckpt_step=prev_ckpt_step,
|
||||
last_eval_step=last_eval_step,
|
||||
interval=config.eval.interval,
|
||||
eval_base_model=config.eval.eval_base_model,
|
||||
)
|
||||
for eval_env in eval_envs:
|
||||
eval_ckpt_step = compute_eval_ckpt_step(
|
||||
ckpt_step=ckpt_step,
|
||||
prev_ckpt_step=prev_ckpt_step,
|
||||
last_eval_step=last_eval_steps[eval_env.name],
|
||||
interval=eval_env.config.interval,
|
||||
eval_base_model=config.eval.eval_base_model,
|
||||
)
|
||||
if eval_ckpt_step is not None:
|
||||
last_eval_steps[eval_env.name] = ckpt_step
|
||||
envs_to_eval.append(eval_env)
|
||||
|
||||
if eval_ckpt_step is not None:
|
||||
last_eval_step = ckpt_step
|
||||
if eval_ckpt_step != ckpt_step:
|
||||
logger.info(f"Running evals for interval step {eval_ckpt_step} (current ckpt_step={ckpt_step})")
|
||||
else:
|
||||
logger.info(f"Running evals for checkpoint step {ckpt_step}")
|
||||
if envs_to_eval:
|
||||
env_names = ", ".join(e.name for e in envs_to_eval)
|
||||
logger.info(f"Running evals at {ckpt_step=} for {env_names}")
|
||||
|
||||
# Pause weight updates and re-scheduling of training rollouts during eval
|
||||
# to avoid evaluating across different checkpoints and avoid congestion
|
||||
@@ -378,11 +379,11 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_next_client,
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
for eval_env in eval_envs
|
||||
for eval_env in envs_to_eval
|
||||
]
|
||||
)
|
||||
|
||||
@@ -496,7 +497,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Computing teacher logprobs for {len(train_examples)} training examples")
|
||||
teacher_logprobs_start_time = time.perf_counter()
|
||||
teacher_logprobs_list = await compute_teacher_logprobs(
|
||||
clients=teacher_inference_pool.clients,
|
||||
clients=teacher_inference_pool.train_clients,
|
||||
model_name=config.teacher_model.model.name,
|
||||
samples=train_examples,
|
||||
)
|
||||
@@ -703,7 +704,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
*[
|
||||
eval_env.evaluate(
|
||||
model_name=scheduler.model_name,
|
||||
get_client=inference_pool.get_next_client,
|
||||
get_client=inference_pool.get_eval_client,
|
||||
ckpt_step=ckpt_step,
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
@@ -156,10 +156,10 @@ class Scheduler:
|
||||
Uses (api_base_url, dp_rank) as identity rather than client_idx so that
|
||||
load tracking survives elastic pool refreshes (which reassign indices).
|
||||
"""
|
||||
clients = self.inference_pool.clients
|
||||
clients = self.inference_pool.train_clients
|
||||
while not clients:
|
||||
await asyncio.sleep(1)
|
||||
clients = self.inference_pool.clients
|
||||
clients = self.inference_pool.train_clients
|
||||
inflight = Counter(self._client_identity(info.client_config) for info in self.inflight_requests.values())
|
||||
return min(clients, key=lambda c: inflight[self._client_identity(c)])
|
||||
|
||||
|
||||
@@ -109,7 +109,10 @@ def train(config: TrainerConfig):
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
|
||||
)
|
||||
torch.set_float32_matmul_precision("high")
|
||||
# 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.
|
||||
torch.set_float32_matmul_precision(config.matmul_precision)
|
||||
|
||||
# Setup multi run manager and offsets (including LoRA validation/scaling hooks if applicable)
|
||||
multi_run_manager = setup_multi_run_manager(
|
||||
|
||||
@@ -84,7 +84,10 @@ def train(config: SFTConfig):
|
||||
setup_torch_distributed(
|
||||
timeout=timedelta(seconds=config.dist_timeout_seconds), enable_gloo=config.model.fsdp_cpu_offload
|
||||
)
|
||||
torch.set_float32_matmul_precision("high")
|
||||
# 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.
|
||||
torch.set_float32_matmul_precision(config.matmul_precision)
|
||||
|
||||
if config.model.lora is not None:
|
||||
setup_multi_run_manager(config.output_dir, 1, torch.device("cuda", world.local_rank), config.model.lora)
|
||||
|
||||
@@ -21,7 +21,7 @@ class InferencePool(Protocol):
|
||||
"""Protocol for inference pools (static or elastic)."""
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
"""Get inference clients."""
|
||||
...
|
||||
|
||||
@@ -34,8 +34,8 @@ class InferencePool(Protocol):
|
||||
"""Update the model name."""
|
||||
...
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
"""Get next eval client in round-robin fashion."""
|
||||
...
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
@@ -59,18 +59,22 @@ class StaticInferencePool:
|
||||
"""Static inference pool with fixed client list."""
|
||||
|
||||
def __init__(
|
||||
self, clients: list[vf.ClientConfig], admin_clients: list[AsyncClient], skip_model_check: bool = False
|
||||
self,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self._clients = clients
|
||||
self._admin_clients = admin_clients
|
||||
self._skip_model_check = skip_model_check
|
||||
self._idx_to_client = {client.client_idx: client for client in clients}
|
||||
self._client_cycle = cycle(clients)
|
||||
self.model_name = None # unused
|
||||
self._train_clients = setup_clients(client_config, client_type=train_client_type)
|
||||
self._eval_clients = setup_clients(client_config, client_type=eval_client_type)
|
||||
self._admin_clients = setup_admin_clients(client_config)
|
||||
self._skip_model_check = client_config.skip_model_check
|
||||
self._eval_cycle = cycle(self._eval_clients)
|
||||
self.model_name = model_name
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
return self._clients
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
return self._train_clients
|
||||
|
||||
@property
|
||||
def admin_clients(self) -> list[AsyncClient]:
|
||||
@@ -79,8 +83,12 @@ class StaticInferencePool:
|
||||
def update_model_name(self, model_name: str) -> None:
|
||||
self.model_name = model_name
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
return next(self._client_cycle)
|
||||
@property
|
||||
def eval_clients(self) -> list[vf.ClientConfig]:
|
||||
return self._eval_clients
|
||||
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
return next(self._eval_cycle)
|
||||
|
||||
async def wait_for_ready(self, model_name: str, timeout: int = 1800) -> None:
|
||||
await check_health(self._admin_clients, timeout=timeout)
|
||||
@@ -97,15 +105,27 @@ class StaticInferencePool:
|
||||
|
||||
|
||||
async def setup_inference_pool(
|
||||
client_config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
) -> InferencePool:
|
||||
"""Create an inference pool from config (static or elastic)."""
|
||||
logger = get_logger()
|
||||
|
||||
if train_client_type == "openai_chat_completions_token":
|
||||
logger.warning(
|
||||
"Token-in-token-out (TITO) client is enabled for training. Only use "
|
||||
"this if your environment has a linear history and the chat "
|
||||
"template has the extension property."
|
||||
)
|
||||
|
||||
if client_config.is_elastic:
|
||||
from prime_rl.utils.elastic import ElasticInferencePool
|
||||
|
||||
return await ElasticInferencePool.from_config(client_config, model_name=model_name, client_type=client_type)
|
||||
return await ElasticInferencePool.from_config(
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Initializing static inference pool (base_url={', '.join(client_config.base_url)}, "
|
||||
@@ -113,9 +133,7 @@ async def setup_inference_pool(
|
||||
f"api_key_var={client_config.api_key_var}, headers={client_config.headers})"
|
||||
)
|
||||
return StaticInferencePool(
|
||||
clients=setup_clients(client_config, client_type=client_type),
|
||||
admin_clients=setup_admin_clients(client_config),
|
||||
skip_model_check=client_config.skip_model_check,
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -102,50 +102,48 @@ class ElasticInferencePool:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hostname: str,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
port: int = 8000,
|
||||
sync_interval: float = 5.0,
|
||||
client_type: str = "openai_chat_completions",
|
||||
router_url: str | None = None,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
):
|
||||
self.logger = get_logger()
|
||||
self.hostname = hostname
|
||||
self.client_config = client_config
|
||||
self.model_name = model_name
|
||||
self.base_model_name = model_name # Keep original for health checks
|
||||
self.port = port
|
||||
self.sync_interval = sync_interval
|
||||
self.client_type = client_type
|
||||
self.router_url = router_url
|
||||
self.hostname = client_config.elastic.hostname
|
||||
self.port = client_config.elastic.port
|
||||
self.sync_interval = client_config.elastic.sync_interval
|
||||
self.train_client_type = train_client_type
|
||||
self.eval_client_type = eval_client_type
|
||||
self.router_url = client_config.router_url
|
||||
|
||||
self._servers: dict[str, ServerState] = {}
|
||||
self._admin_clients: dict[str, AsyncClient] = {}
|
||||
self._lock = asyncio.Lock()
|
||||
self._desired: AdapterState = AdapterState()
|
||||
|
||||
self._clients: list[vf.ClientConfig] = []
|
||||
self._train_clients: list[vf.ClientConfig] = []
|
||||
self._eval_clients: list[vf.ClientConfig] = []
|
||||
self._client_urls: list[str] = []
|
||||
self._client_index = 0
|
||||
|
||||
self._eval_index = 0
|
||||
|
||||
self._sync_task: asyncio.Task | None = None
|
||||
self._started = False
|
||||
|
||||
@classmethod
|
||||
async def from_config(
|
||||
cls, config: ClientConfig, model_name: str, client_type: str = "openai_chat_completions"
|
||||
cls,
|
||||
client_config: ClientConfig,
|
||||
model_name: str,
|
||||
train_client_type: str = "openai_chat_completions_token",
|
||||
eval_client_type: str = "openai_chat_completions",
|
||||
) -> ElasticInferencePool:
|
||||
if config.elastic is None:
|
||||
if client_config.elastic is None:
|
||||
raise ValueError("Elastic inference pool requires elastic config")
|
||||
pool = cls(
|
||||
hostname=config.elastic.hostname,
|
||||
client_config=config,
|
||||
model_name=model_name,
|
||||
port=config.elastic.port,
|
||||
sync_interval=config.elastic.sync_interval,
|
||||
client_type=client_type,
|
||||
router_url=config.router_url,
|
||||
client_config, model_name=model_name, train_client_type=train_client_type, eval_client_type=eval_client_type
|
||||
)
|
||||
await pool.start()
|
||||
return pool
|
||||
@@ -163,8 +161,8 @@ class ElasticInferencePool:
|
||||
def ready_urls(self) -> list[str]:
|
||||
return [self._build_inference_url(ip) for ip, s in self._servers.items() if s.status == "ready"]
|
||||
|
||||
@property
|
||||
def clients(self) -> list[vf.ClientConfig]:
|
||||
def _rebuild_clients(self) -> None:
|
||||
"""Rebuild inference clients when the set of ready URLs changes."""
|
||||
# When a router URL is configured, route inference requests through it
|
||||
# instead of directly to discovered pods. Admin operations still use
|
||||
# individual pod IPs via admin_clients.
|
||||
@@ -176,34 +174,35 @@ class ElasticInferencePool:
|
||||
urls = self.ready_urls
|
||||
if set(urls) != set(self._client_urls):
|
||||
self._client_urls = urls
|
||||
self._client_index = 0
|
||||
self._clients = (
|
||||
setup_clients(
|
||||
ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
connect_timeout=self.client_config.connect_timeout,
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
),
|
||||
client_type=self.client_type,
|
||||
)
|
||||
if urls
|
||||
else []
|
||||
|
||||
self._eval_index = 0
|
||||
url_config = ClientConfig(
|
||||
timeout=self.client_config.timeout,
|
||||
connect_timeout=self.client_config.connect_timeout,
|
||||
base_url=urls,
|
||||
api_key_var=self.client_config.api_key_var,
|
||||
headers=self.client_config.headers,
|
||||
dp_rank_count=self.client_config.dp_rank_count,
|
||||
)
|
||||
return self._clients
|
||||
self._train_clients = setup_clients(url_config, client_type=self.train_client_type) if urls else []
|
||||
self._eval_clients = setup_clients(url_config, client_type=self.eval_client_type) if urls else []
|
||||
|
||||
@property
|
||||
def has_clients(self) -> bool:
|
||||
return len(self.clients) > 0
|
||||
def train_clients(self) -> list[vf.ClientConfig]:
|
||||
self._rebuild_clients()
|
||||
return self._train_clients
|
||||
|
||||
async def get_next_client(self) -> vf.ClientConfig:
|
||||
"""Get next client in round-robin fashion."""
|
||||
while not self.has_clients:
|
||||
@property
|
||||
def eval_clients(self) -> list[vf.ClientConfig]:
|
||||
self._rebuild_clients()
|
||||
return self._eval_clients
|
||||
|
||||
async def get_eval_client(self) -> vf.ClientConfig:
|
||||
"""Get next eval client in round-robin fashion."""
|
||||
while not self.eval_clients:
|
||||
await asyncio.sleep(self.sync_interval)
|
||||
client = self._clients[self._client_index % len(self._clients)]
|
||||
self._client_index += 1
|
||||
client = self._eval_clients[self._eval_index % len(self._eval_clients)]
|
||||
self._eval_index += 1
|
||||
return client
|
||||
|
||||
@property
|
||||
@@ -439,7 +438,8 @@ class ElasticInferencePool:
|
||||
for ip in list(self._servers.keys()):
|
||||
await self._remove_server(ip)
|
||||
|
||||
self._clients = []
|
||||
self._train_clients = []
|
||||
self._eval_clients = []
|
||||
self._client_urls = []
|
||||
self._started = False
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from wandb.errors import CommError
|
||||
|
||||
from prime_rl.configs.shared import WandbConfig, WandbWithExtrasConfig
|
||||
from prime_rl.utils.chat_template import deserialize_tool_calls
|
||||
from prime_rl.utils.config import BaseConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.monitor.base import Monitor, sample_items_for_logging
|
||||
@@ -195,7 +196,10 @@ class WandbMonitor(Monitor):
|
||||
if not completion:
|
||||
continue
|
||||
if isinstance(completion, list):
|
||||
completion = self.tokenizer.apply_chat_template(completion, tokenize=False)
|
||||
try:
|
||||
completion = self.tokenizer.apply_chat_template(deserialize_tool_calls(completion), tokenize=False)
|
||||
except Exception:
|
||||
completion = str(completion)
|
||||
sample = {
|
||||
"step": step,
|
||||
"env": env_name,
|
||||
|
||||
@@ -185,12 +185,12 @@ def test_adapter_state_creation():
|
||||
|
||||
def test_adapter_matches_when_no_adapter_desired():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
# No adapter desired (base model inference)
|
||||
assert pool._adapter_matches_desired(None) is True
|
||||
assert pool._adapter_matches_desired(AdapterState("x", Path("/x"), 0)) is True
|
||||
@@ -198,12 +198,12 @@ def test_adapter_matches_when_no_adapter_desired():
|
||||
|
||||
def test_adapter_matches_by_path():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -216,12 +216,12 @@ def test_adapter_matches_by_path():
|
||||
|
||||
def test_adapter_matches_by_step_when_nonzero():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -232,12 +232,12 @@ def test_adapter_matches_by_step_when_nonzero():
|
||||
|
||||
def test_adapter_does_not_match_by_zero_step():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_0")
|
||||
pool._desired.step = 0
|
||||
|
||||
@@ -248,12 +248,12 @@ def test_adapter_does_not_match_by_zero_step():
|
||||
|
||||
def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
pool._desired.path = Path("/weights/step_100")
|
||||
pool._desired.step = 100
|
||||
|
||||
@@ -266,12 +266,12 @@ def test_adapter_returns_false_when_no_adapter_loaded():
|
||||
def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
|
||||
"""Test that _get_loaded_adapter returns the adapter matching desired name, not the first one."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
# Set the desired adapter name
|
||||
pool._desired.name = "rft-target-run"
|
||||
@@ -317,12 +317,12 @@ def test_get_loaded_adapter_finds_correct_adapter_when_multiple_loaded():
|
||||
def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
|
||||
"""Test that _get_loaded_adapter returns None when desired adapter is not in the list."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "rft-missing-run"
|
||||
pool._desired.path = Path("/data/outputs/missing_run/broadcasts/step_5")
|
||||
@@ -348,12 +348,12 @@ def test_get_loaded_adapter_returns_none_when_desired_adapter_not_found():
|
||||
def test_get_loaded_adapter_parses_step_from_path():
|
||||
"""Test that _get_loaded_adapter correctly parses step number from path."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "my-lora"
|
||||
|
||||
@@ -377,12 +377,12 @@ def test_get_loaded_adapter_parses_step_from_path():
|
||||
def test_get_loaded_adapter_handles_step_dash_format():
|
||||
"""Test that _get_loaded_adapter parses step-N format (with dash)."""
|
||||
with patch("prime_rl.utils.elastic.get_logger"):
|
||||
pool = ElasticInferencePool(
|
||||
hostname="test.hostname",
|
||||
client_config=MagicMock(),
|
||||
model_name="base-model",
|
||||
port=8000,
|
||||
)
|
||||
mock_config = MagicMock()
|
||||
mock_config.elastic.hostname = "test.hostname"
|
||||
mock_config.elastic.port = 8000
|
||||
mock_config.elastic.sync_interval = 5.0
|
||||
mock_config.router_url = None
|
||||
pool = ElasticInferencePool(client_config=mock_config, model_name="base-model")
|
||||
|
||||
pool._desired.name = "my-lora"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user