Compare commits

...
Author SHA1 Message Date
faresobeidandGitHub c8af127357 chore: remove legacy config options (#3770)
Removes legacy config options and their code paths. They have had no
changes of their own in 4+ months.

## Removed
- **SGD optimizer** (`optim.type = "sgd"`): `SGDConfig`, its union
member, and the `torch.optim.SGD` branch in `trainer/optim`. AdamW,
Muon, and SignSGD stay.
- **`ckpt.skip_progress`** (orchestrator and trainer ckpt configs):
resume now always restores progress. This affects the orchestrator ckpt
loading and SFT resume.
- **`Jackmin108/` model-name special case** in
`validate_shared_model_name`. Trainer and orchestrator model names now
must always match when no inference config is given.

## Kept
- **`orchestrator.collect_inference_metrics`** stays, unchanged from
main. Hosted training uses Grafana for inference metrics and sets it to
`false` to turn off W&B mirroring. The `/metrics` poll for the
concurrency controller always runs either way.

## Also included (#3774, merged into this branch)
- `RLConfig`: top-level shared fields (including `resume`) go through
`propagate_shared_fields` only. The old `validate_shared_*` helpers in
`validation.py` are replaced by inline cross-component checks in
`RLConfig.validate_shared_configs`.

## Breaking changes
TOMLs/CLI args that set any of these now fail validation:
- `trainer.optim.type = "sgd"` (and `optim.momentum`, `optim.nesterov`)
- `orchestrator.ckpt.skip_progress`, `trainer.ckpt.skip_progress` (SFT
`ckpt.skip_progress`)

No configs, examples, docs, or skills in the repo reference these
options.

## Validation
- `pytest tests/unit -m "not gpu"` (excluding
`tests/unit/train/test_cpu_adam.py`, which needs `ninja` to build a C++
extension on this machine): 651 passed
- `ruff check .` and `ruff format --check .` (only `docs/algorithms.md`
is flagged, same as on main)
- GPU/integration tests were not run (no GPU on this machine).

Rebased on main f42630873; resolved conflicts in `configs/rl.py` and
`utils/validation.py` (main's #3788 already removed
`validate_shared_weight_broadcast`; kept that and this PR's removal of
the other `validate_shared_*` helpers).

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Breaking config validation for old TOMLs/CLI flags and stricter
cross-component model/resume rules; resume behavior changes if anything
relied on skipping progress restore.
> 
> **Overview**
> Removes **legacy config knobs** that are no longer supported:
**`optim.type = "sgd"`** (config type + `torch.optim.SGD` factory), and
**`ckpt.skip_progress`** on trainer/orchestrator checkpoints. Resume now
**always** restores orchestrator progress/curriculum state and SFT
training progress (step counter always advances after load).
> 
> **RL config validation** is consolidated: shared-field helpers in
`validation.py` are deleted in favor of
**`RLConfig.validate_shared_configs`** using a generic `require_equal`
check (model name, chat template, `max_steps`, `resume`, ckpt/W&B
parity, seq_len bound). Top-level **`resume`** is propagated via
**`propagate_shared_fields`** instead of a separate `auto_setup_resume`
validator; the **`Jackmin108/`** trainer/orchestrator model-name
exemption is gone.
> 
> CI slim-install smoke test imports **`propagate_shared_fields`** only.
Unit tests drop SGD from full-offload optimizer coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1df3854c75fc652e2b0a5dbd7d019555e73736ba. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-10-05 11:53:03 +01:00
10 changed files with 87 additions and 193 deletions
+1 -1
View File
@@ -75,7 +75,7 @@ jobs:
from prime_rl.configs.trainer import TrainerConfig
from prime_rl.configs.env_server import EnvServerConfig
from prime_rl.utils.config import BaseConfig, find_package_resource, rgetattr, rsetattr
from prime_rl.utils.validation import validate_shared_ckpt_config
from prime_rl.utils.validation import propagate_shared_fields
# `verifiers` (+ its `datasets` dep) is a declared slim dep: the v1 config types
# (EnvConfig, Task, ...) extend verifiers.v1, which is pure-pydantic and pulls no
@@ -481,9 +481,6 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
class ConcurrencyConfig(BaseConfig):
"""Adaptive in-flight concurrency control. The orchestrator sizes the
@@ -25,15 +25,7 @@ from prime_rl.configs.trainer import (
TrainerConfig,
)
from prime_rl.utils.config import BaseConfig, default_output_dir, find_package_resource
from prime_rl.utils.validation import (
propagate_shared_fields,
validate_shared_ckpt_config,
validate_shared_max_steps,
validate_shared_model_name,
validate_shared_seq_len,
validate_shared_tokenizer,
validate_shared_wandb_config,
)
from prime_rl.utils.validation import propagate_shared_fields
class SharedLogConfig(BaseConfig):
@@ -333,15 +325,6 @@ class RLConfig(BaseConfig):
sub.output_dir = run_dir
return self
@model_validator(mode="after")
def auto_setup_resume(self):
"""Propagate the top-level resume onto the sub-configs."""
if self.resume is None:
return self
self.trainer.resume = self.resume.model_copy()
self.orchestrator.resume = self.resume.model_copy()
return self
@model_validator(mode="after")
def auto_setup_run_identity(self):
"""Default the W&B and Prime platform run names to ``run.name``.
@@ -365,13 +348,70 @@ class RLConfig(BaseConfig):
@model_validator(mode="after")
def validate_shared_configs(self):
"""Validate consistency of shared configs across trainer, orchestrator, and inference."""
validate_shared_model_name(self.trainer, self.orchestrator, self.inference)
validate_shared_tokenizer(self.trainer, self.orchestrator, self.inference)
validate_shared_max_steps(self.trainer, self.orchestrator)
validate_shared_seq_len(self.trainer, self.orchestrator)
validate_shared_ckpt_config(self.trainer, self.orchestrator)
validate_shared_wandb_config(self.trainer, self.orchestrator)
"""Cross-component constraints for values set per sub-config rather than through the
shared fields (``propagate_shared_fields`` already rejects shared vs sub-config conflicts)."""
trainer, orchestrator, inference = self.trainer, self.orchestrator, self.inference
def require_equal(name: str, values: dict[str, Any]) -> None:
if len({repr(v) for v in values.values()}) > 1:
found = ", ".join(f"{path}={value!r}" for path, value in values.items())
raise ValueError(f"{name} must match across components ({found}). Set the shared [{name}] instead.")
# The orchestrator queries the inference server it is paired with; without one, it
# must match the trainer whose weights the external server receives.
if inference is not None:
require_equal(
"model.name",
{"inference.vllm.model": inference.vllm.model, "orchestrator.model.name": orchestrator.model.name},
)
else:
require_equal(
"model.name",
{"trainer.model.name": trainer.model.name, "orchestrator.model.name": orchestrator.model.name},
)
# ``tokenizer.name`` / ``trust_remote_code`` may differ (e.g. FP8-quantized inference variants).
chat_templates = {
"trainer.tokenizer.chat_template": trainer.tokenizer.chat_template,
"orchestrator.tokenizer.chat_template": orchestrator.tokenizer.chat_template,
}
if inference is not None:
chat_templates["inference.vllm.chat_template"] = inference.vllm.chat_template
require_equal("tokenizer.chat_template", chat_templates)
require_equal(
"max_steps", {"trainer.max_steps": trainer.max_steps, "orchestrator.max_steps": orchestrator.max_steps}
)
require_equal("resume", {"trainer.resume": trainer.resume, "orchestrator.resume": orchestrator.resume})
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"trainer.model.seq_len ({trainer.model.seq_len}) must be >= orchestrator.seq_len "
f"({orchestrator.seq_len}) so the trainer can handle every sequence the orchestrator produces."
)
if (trainer.ckpt is None) != (orchestrator.ckpt is None):
raise ValueError(
"Checkpointing must be configured on both trainer and orchestrator. Use the shared [ckpt]."
)
if trainer.ckpt and orchestrator.ckpt:
require_equal(
"ckpt.interval",
{
"trainer.ckpt.interval": trainer.ckpt.interval,
"orchestrator.ckpt.interval": orchestrator.ckpt.interval,
},
)
trainer_wandb, orchestrator_wandb = trainer.monitors.wandb, orchestrator.monitors.wandb
if (trainer_wandb is None) != (orchestrator_wandb is None):
raise ValueError(
"W&B must be configured on both trainer and orchestrator, otherwise only one side's "
"metrics are logged. Use the shared [monitors.wandb]."
)
if trainer_wandb and orchestrator_wandb:
require_equal(
"monitors.wandb.project",
{
"trainer.monitors.wandb.project": trainer_wandb.project,
"orchestrator.monitors.wandb.project": orchestrator_wandb.project,
},
)
return self
@model_validator(mode="after")
@@ -466,16 +466,6 @@ class BaseOptimizerConfig(BaseConfig):
"""Maximum gradient norm to clip to. If None, gradient clipping is disabled."""
class SGDConfig(BaseOptimizerConfig):
type: Literal["sgd"] = "sgd"
nesterov: bool = True
"""Use Nesterov momentum."""
momentum: float = 0.9
"""SGD momentum factor."""
class AdamWConfig(BaseOptimizerConfig):
type: Literal["adamw"] = "adamw"
@@ -503,9 +493,7 @@ class SignSGDConfig(BaseOptimizerConfig):
type: Literal["sign_sgd"] = "sign_sgd"
OptimizerConfig: TypeAlias = Annotated[
SGDConfig | AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")
]
OptimizerConfig: TypeAlias = Annotated[AdamWConfig | MuonConfig | SignSGDConfig, Field(discriminator="type")]
class CheckpointConfig(BaseConfig):
@@ -521,9 +509,6 @@ class CheckpointConfig(BaseConfig):
keep_interval: int | None = Field(None, ge=1)
"""Keep checkpoints at every N steps permanently (e.g. ``keep_interval=100`` keeps step 100, 200, ...). If None, no interval-based keeping."""
skip_progress: bool = False
"""Skip loading the progress from checkpoint."""
skip_scheduler: bool = False
"""Skip loading the scheduler from checkpoint."""
@@ -1,10 +1,6 @@
from __future__ import annotations
from typing import Any, Optional
from prime_rl.configs.inference import InferenceConfig
from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.configs.trainer import TrainerConfig
from typing import Any
def propagate_shared_fields(data: Any) -> Any:
@@ -128,6 +124,8 @@ def propagate_shared_fields(data: Any) -> Any:
"inference.vllm.chat_template",
)
propagate("resume", "trainer.resume", "orchestrator.resume")
# [rollout_transport] → both sub-configs (host is launcher-injected for zmq multi-node).
propagate("rollout_transport", "trainer.rollout_transport", "orchestrator.rollout_transport")
@@ -147,7 +145,7 @@ def propagate_shared_fields(data: Any) -> Any:
# - shared ``[tokenizer] chat_template`` (already filled all three above,
# this re-fill is a no-op via fill-if-absent), and
# - ``[trainer.tokenizer] chat_template`` set directly without shared
# (only path that reaches inference; ``validate_shared_tokenizer``
# (only path that reaches inference; ``RLConfig.validate_shared_configs``
# would otherwise complain about the missing inference value).
trainer_chat_template = get("trainer.tokenizer.chat_template")
if trainer_chat_template is not None:
@@ -190,115 +188,3 @@ def propagate_shared_fields(data: Any) -> Any:
raise ValueError("\n".join(lines))
return data
def validate_shared_ckpt_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.ckpt and not orchestrator.ckpt:
raise ValueError(
"Trainer checkpoint config is specified, but orchestrator checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if orchestrator.ckpt and not trainer.ckpt:
raise ValueError(
"Orchestrator checkpoint config is specified, but trainer checkpoint config is not. Please setup checkpointing on both for checkpointing to work properly."
)
if trainer.ckpt and orchestrator.ckpt and trainer.ckpt.interval != orchestrator.ckpt.interval:
raise ValueError(
f"Trainer checkpoint interval ({trainer.ckpt.interval}) and orchestrator checkpoint interval ({orchestrator.ckpt.interval}) are not the same. Please specify the same checkpoint interval for both."
)
if trainer.resume != orchestrator.resume:
raise ValueError(
f"Trainer resume ({trainer.resume}) and orchestrator resume ({orchestrator.resume}) are not the same. Please specify the same resume config for both."
)
def validate_shared_model_name(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Orchestrator must match inference (it queries the inference server)
if inference is not None:
if inference.vllm.model != orchestrator.model.name:
raise ValueError(
f"Inference model name ({inference.vllm.model}) and orchestrator model name ({orchestrator.model.name}) are not the same. "
"The orchestrator queries the inference server and must use the same model name."
)
return
if trainer.model.name.startswith("Jackmin108/"): # The TT MoE models will have a different name on the orchestrator
return
if trainer.model.name != orchestrator.model.name:
raise ValueError(
f"Trainer model name ({trainer.model.name}) and orchestrator model name ({orchestrator.model.name}) are not the same. Please specify the same model name for both."
)
def validate_shared_wandb_config(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.monitors.wandb and not orchestrator.monitors.wandb:
raise ValueError(
"Trainer W&B config is specified, but orchestrator W&B config is not. "
"This means only trainer metrics will be logged. Please specify [orchestrator.monitors.wandb] to log orchestrator metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if orchestrator.monitors.wandb and not trainer.monitors.wandb:
raise ValueError(
"Orchestrator W&B config is specified, but trainer W&B config is not. "
"This means only orchestrator metrics will be logged. Please specify [trainer.monitors.wandb] to log trainer metrics as well, "
"or use [monitors.wandb] to configure both at once."
)
if trainer.monitors.wandb and orchestrator.monitors.wandb:
if trainer.monitors.wandb.project != orchestrator.monitors.wandb.project:
raise ValueError(
f"Trainer W&B project ({trainer.monitors.wandb.project}) and orchestrator W&B project ({orchestrator.monitors.wandb.project}) are not the same. Please specify the same W&B project for both."
)
def validate_shared_max_steps(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.max_steps != orchestrator.max_steps:
raise ValueError(
f"Trainer max steps ({trainer.max_steps}) and orchestrator max steps ({orchestrator.max_steps}) are not the same. Please specify the same max steps for both."
)
def validate_shared_seq_len(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
) -> None:
if trainer.model.seq_len < orchestrator.seq_len:
raise ValueError(
f"Trainer model seq_len ({trainer.model.seq_len}) must be >= orchestrator seq_len ({orchestrator.seq_len}). "
f"The trainer needs to be able to handle sequences at least as long as those produced by the orchestrator."
)
def validate_shared_tokenizer(
trainer: TrainerConfig,
orchestrator: OrchestratorConfig,
inference: Optional[InferenceConfig] = None,
) -> None:
# Validate chat_template is consistent across all components.
# We only check chat_template (not name/trust_remote_code) because those
# are auto-derived from model names which may legitimately differ (e.g.
# when inference uses an FP8 quantized variant of the same model).
if trainer.tokenizer.chat_template != orchestrator.tokenizer.chat_template:
raise ValueError(
f"Trainer chat_template ({trainer.tokenizer.chat_template!r}) and orchestrator "
f"chat_template ({orchestrator.tokenizer.chat_template!r}) do not match. "
f"Use the shared [tokenizer] config to set chat_template for both."
)
if inference is not None:
if trainer.tokenizer.chat_template != inference.vllm.chat_template:
raise ValueError(
f"Inference chat_template ({inference.vllm.chat_template!r}) does not match "
f"the shared tokenizer chat_template ({trainer.tokenizer.chat_template!r}). "
f"Use the shared [tokenizer] config to set chat_template for all components."
)
+10 -13
View File
@@ -55,19 +55,16 @@ class CheckpointManager:
raise FileNotFoundError(f"Orchestrator checkpoint not found at {state_file}")
get_logger().debug(f"Loading checkpoint from {state_file}")
start = time.perf_counter()
if self.config.skip_progress:
get_logger().info("Skipping progress and train source loading from checkpoint")
else:
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
with open(state_file, "rb") as f:
state = torch.load(f, weights_only=False)
saved: Progress = state["progress"]
for key, value in asdict(saved).items():
if hasattr(progress, key):
setattr(progress, key, value)
train_source.load_state_dict(state["train_source"])
for name in state["train_source"]["envs"]:
if name in train_source.curricula:
get_logger().info(f"Resumed curriculum state for env {name}")
get_logger().debug(f"Orchestrator checkpoint loaded in {format_time(time.perf_counter() - start)}")
+1 -2
View File
@@ -242,8 +242,7 @@ class Orchestrator:
# The checkpoint finished step ``resume_step``; resume at the next step. Derive the step
# from ``resume_step`` (not the loaded progress.step) so it stays coordinated with the
# trainer even when ``ckpt.skip_progress`` leaves the counter unrestored. The curricula
# themselves are restored below, once the envs are loaded.
# trainer. The curricula themselves are restored below, once the envs are loaded.
if self.resume_step is not None:
self.progress.step = self.resume_step + 1
get_logger().info(f"Resuming from step {self.resume_step}")
+1 -9
View File
@@ -3,7 +3,7 @@ import torch.distributed as dist
from dion import Muon
from torch import nn
from torch.distributed.device_mesh import DeviceMesh
from torch.optim import SGD, AdamW, Optimizer
from torch.optim import AdamW, Optimizer
from prime_rl.configs.trainer import OptimizerConfig, OptimizerInBackwardOffloadConfig
from prime_rl.trainer.models.fusions import get_model_packed_parameters
@@ -117,14 +117,6 @@ def _create_optimizer(
# param at load time, mismatching the saved state). Muon filters internally below.
trainable_params = [p for _, p in named_params if p.requires_grad]
match config.type:
case "sgd":
return SGD(
params=trainable_params,
lr=lr,
weight_decay=config.weight_decay,
momentum=config.momentum,
nesterov=config.nesterov,
)
case "adamw":
return AdamW(
params=trainable_params,
+2 -3
View File
@@ -210,13 +210,12 @@ def train(config: SFTConfig):
model,
[optimizer],
scheduler if not skip.skip_scheduler else None,
progress if not skip.skip_progress else None,
progress,
dataloader=dataloader if not skip.skip_dataloader else None,
path=resume_dir / "trainer" if resume_dir is not None else None,
)
# The checkpoint finished step ``checkpoint_step``; resume training at the next step.
if not skip.skip_progress:
progress.step += 1
progress.step += 1
# This redundant setup is necessary because loading the optimizer's state has side effects on the scheduler state dict
if skip.skip_scheduler:
scheduler = setup_scheduler(optimizer, config.scheduler, scheduler_steps, config.optim.lr)
+2 -3
View File
@@ -354,13 +354,12 @@ def test_full_optimizer_offload_disables_gradient_clipping(config_cls):
@pytest.mark.parametrize("config_cls", [TrainerConfig, SFTConfig])
@pytest.mark.parametrize("optimizer_type", ["sgd", "muon"])
def test_full_optimizer_offload_requires_supported_optimizer(config_cls, optimizer_type):
def test_full_optimizer_offload_requires_supported_optimizer(config_cls):
with pytest.raises(ValidationError, match="Full optimizer offload only supports AdamW and SignSGD"):
config_cls.model_validate(
{
"model": {"optim_cpu_offload": False, "full_offload": True},
"optim": {"type": optimizer_type, "max_norm": None},
"optim": {"type": "muon", "max_norm": None},
}
)