Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 90 additions & 37 deletions packages/prime/src/prime_cli/utils/training_schema_worker.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import importlib
import json
import re
import sys
from copy import deepcopy
from importlib import metadata
from typing import Any, get_args
from typing import Any, get_args, get_type_hints


def defer_environments(orch):
Expand All @@ -24,6 +25,25 @@ def model_class(annotation, attribute):
)


def component_class(model, builder):
"""The component config class that `model.<builder>()` returns, on prime-rl builds that
build their components from the entrypoint config."""
method = getattr(model, builder, None)
if method is None:
return None
return model_class(get_type_hints(method).get("return"), "model_fields")


def legacy_inference(config):
"""The inference component of contract 4, which the platform serves with `--router None`."""
inference = config.inference.model_dump(
mode="json", exclude={"deployment", "slurm", "output_dir", "dry_run"}
)
if config.deployment.type == "multi_node":
inference["router"] = None
return inference


def inherit_group_defaults(model, orch, saved):
"""Fill deferred sources with their group's defaults, as prime-rl's validation does."""
from pydantic import TypeAdapter
Expand Down Expand Up @@ -162,8 +182,16 @@ class EvalWithoutSources(evaluation):
def validate_non_empty_sources(self):
return self

validators = {}
if hasattr(model, "components"):
# prime-rl builds every component while it validates, and the online evals need their
# sources: the cluster's launch builds them.
validators["validate_components"] = model_validator(mode="after")(lambda self: self)
hosted = create_model(
f"Hosted{model.__name__}", __base__=model, eval=(EvalWithoutSources | None, None)
f"Hosted{model.__name__}",
__base__=model,
__validators__=validators,
eval=(EvalWithoutSources | None, None),
)
config = hosted.model_validate({**data, "eval": {**data["eval"], "source": []}})
group = model_class(model.model_fields["eval"].annotation, "inherit_group_defaults")
Expand All @@ -177,6 +205,11 @@ def validate_non_empty_sources(self):
mode="json",
exclude={"inference"} | ({"deployment", "slurm", "dry_run", "clean"} if multi else set()),
)
trainer_class = component_class(model, "trainer_config")
if trainer_class is not None:
trainer = {
key: value for key, value in trainer.items() if key in trainer_class.model_fields
}
# The trainer schedules its weight broadcasts from the eval sources.
trainer["eval"]["source"] = sources
evals = config.eval.model_dump(mode="json")
Expand All @@ -188,14 +221,14 @@ def validate_non_empty_sources(self):
weight_broadcast=config.weight_broadcast
and config.weight_broadcast.model_dump(mode="json"),
)
if "monitors" in type(config.eval).model_fields:
evals["monitors"] = eval_monitors(config)
inference = config.inference.model_dump(
mode="json", exclude={"deployment", "slurm", "output_dir", "dry_run"}
)
if multi:
inference["router"] = None
return config, {"trainer": trainer, "orchestrator": evals, "inference": inference}
evaluation = component_class(model, "online_eval_config") or type(config.eval)
if "monitors" in evaluation.model_fields:
evals["monitors"] = eval_monitors(config, evaluation)
return config, {
"trainer": trainer,
"orchestrator": evals,
"inference": legacy_inference(config),
}


def reject_unsupported_online_eval_settings(config):
Expand All @@ -218,11 +251,11 @@ def reject_unsupported_online_eval_settings(config):
)


def eval_monitors(config):
def eval_monitors(config, evaluation):
"""The eval process reports to the trainer's monitors. Schemas before the
shared monitors config give it its own, whose platform monitor only names
the run."""
monitors = model_class(type(config.eval).model_fields["monitors"].annotation, "model_fields")
monitors = model_class(evaluation.model_fields["monitors"].annotation, "model_fields")
if monitors is not None and isinstance(config.monitors, monitors):
return config.monitors.model_dump(mode="json")
prime = config.monitors.prime
Expand All @@ -233,6 +266,27 @@ def eval_monitors(config):
}


def component_serialization():
"""The prime-rl module that dumps component configs: configs.base, or utils.config before it."""
for module in ("prime_rl.configs.base", "prime_rl.utils.config"):
try:
serialization = importlib.import_module(module)
except ModuleNotFoundError as error:
if not module.startswith(error.name or "-"):
raise
continue
if hasattr(serialization, "dump_components"):
return serialization
return serialization


def trainer_component(config, serialization):
"""The trainer's config: built by prime-rl when it builds components, else the whole config."""
if hasattr(serialization, "dump_components"):
return serialization.dump_components(config)["trainer"]
return config.model_dump(mode="json")


def installed_commit(install):
if "vcs_info" in install:
return install["vcs_info"].get("commit_id")
Expand All @@ -246,21 +300,19 @@ def installed_commit(install):


def config_class(mode):
if mode == "rl":
from prime_rl.configs.rl import RLConfig

return RLConfig
if mode == "sft":
from prime_rl.configs.sft import SFTConfig

return SFTConfig
try:
from prime_rl.configs.pretrain import PretrainConfig
except ImportError as error:
"""The entrypoint config of `mode`, after or before prime-rl moved it to configs.entrypoints."""
name = {"rl": "RLConfig", "sft": "SFTConfig", "pretrain": "PretrainConfig"}[mode]
for module in (f"prime_rl.configs.entrypoints.{mode}", f"prime_rl.configs.{mode}"):
try:
return getattr(importlib.import_module(module), name)
except ModuleNotFoundError as error:
if not module.startswith(error.name or "-"):
raise
if mode == "pretrain":
raise ValueError(
"This prime-rl build has no pretrain mode: pick a newer image with --image-tag."
) from error
return PretrainConfig
)
raise ValueError(f"This prime-rl build has no {mode} config.")


def normalize(request):
Expand All @@ -270,7 +322,7 @@ def normalize(request):
"[k8s] is not supported for hosted runs: Platform manages deployment settings. "
"Remove the [k8s] table."
)
from prime_rl.utils import config as serialization
serialization = component_serialization()

mode = request["mode"]
model = config_class(mode)
Expand All @@ -291,33 +343,34 @@ def normalize(request):
f"[eval] block, or remove {'them' if len(stray) > 1 else 'it'}."
)
config = model.model_validate(data)
components = {"trainer": config.model_dump(mode="json")}
components = {"trainer": trainer_component(config, serialization)}
elif mode != "rl":
deferred = {key: data.pop(key) for key in request["sft_online_eval_keys"] if key in data}
config = model.model_validate(data)
check_deferred_settings(model, data, deferred, mode)
components = {"trainer": config.model_dump(mode="json") | deferred}
components = {"trainer": trainer_component(config, serialization) | deferred}
else:
deferred = defer_environments(data.get("orchestrator") or {})
config = model.model_validate(data)
reject_unsupported_hosted_settings(config)
check_deferred_settings(model, data, deferred, mode)
dump = getattr(serialization, "dump_rl_components", None)
if dump is not None:
components = dump(config)
if hasattr(serialization, "dump_components"):
built = serialization.dump_components(config)
components = {key: built[key] for key in ("trainer", "orchestrator") if key in built}
if config.inference is not None:
components["inference"] = legacy_inference(config)
elif hasattr(serialization, "dump_rl_components"):
components = serialization.dump_rl_components(config)
else:
components = {
"trainer": config.trainer.model_dump(mode="json"),
"orchestrator": config.orchestrator.model_dump(mode="json"),
}
if config.inference is not None:
components["inference"] = config.inference.model_dump(
mode="json", exclude={"deployment", "slurm", "output_dir", "dry_run"}
)
if config.deployment.type == "multi_node":
components["inference"]["router"] = None
components["inference"] = legacy_inference(config)
inherit_group_defaults(model, data.get("orchestrator") or {}, deferred)
restore_environments(components["orchestrator"], deferred)
if "orchestrator" in components:
restore_environments(components["orchestrator"], deferred)
return {
"contract_version": 4,
"mode": mode,
Expand Down
84 changes: 83 additions & 1 deletion packages/prime/tests/test_training_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,88 @@ def dump(config):
assert len(calls) == (1 if shared_serializer else 0)


@pytest.mark.parametrize("serializer", ["prime_rl.utils.config", "prime_rl.configs.base"])
def test_rl_components_come_from_prime_rls_builders(fake_schema, monkeypatch, serializer):
"""prime-rl builds every process config from the entrypoint; contract 4 keeps the trainer,
the orchestrator and the inference config the platform serves."""
from types import ModuleType

from prime_cli.utils import training_schema_worker as worker

entrypoints = ModuleType("prime_rl.configs.entrypoints.rl")
entrypoints.RLConfig = sys.modules["prime_rl.configs.rl"].RLConfig
monkeypatch.setitem(sys.modules, "prime_rl.configs.entrypoints", ModuleType("entrypoints"))
monkeypatch.setitem(sys.modules, "prime_rl.configs.entrypoints.rl", entrypoints)
monkeypatch.setitem(sys.modules, "prime_rl.configs.rl", None)
if serializer == "prime_rl.configs.base":
fake_schema = ModuleType(serializer)
monkeypatch.setitem(sys.modules, serializer, fake_schema)
monkeypatch.setattr(sys.modules["prime_rl.configs"], "base", fake_schema, raising=False)
fake_schema.dump_components = lambda config: {
"trainer": {"output_dir": "/data/outputs/run"},
"orchestrator": {"output_dir": "/data/outputs/run"},
"engine": {"server": {"port": 8100}},
"router": {"port": 8000},
}

artifact = worker.normalize({"config": {}, "mode": "rl", "schema_commit": "a" * 40})

assert artifact["components"] == {
"trainer": {"output_dir": "/data/outputs/run"},
"orchestrator": {"output_dir": "/data/outputs/run"},
"inference": {"resume": None, "new_option": {"disabled": None}, "router": None},
}


def test_supervised_online_evals_build_components_without_their_sources(fake_schema):
"""prime-rl builds the components while it validates. The hosted check removes the eval
sources, so it skips that build and keeps only the trainer's own fields."""
from prime_cli.utils import training_schema_worker as worker
from pydantic import BaseModel, ConfigDict, model_validator

base = _supervised_eval_schema(False)
eval_section = base.model_fields["eval"].annotation.__args__[0]
shared_monitors = base.model_fields["monitors"].annotation

class Trainer(BaseModel):
model_config = ConfigDict(extra="forbid")
model: dict
max_steps: int
log: dict
monitors: dict
eval: dict | None
weight_broadcast: dict | None
deployment: dict

class OnlineEval(eval_section):
model: str | None = None
monitors: shared_monitors | None = None

class SFT(base):
def trainer_config(self) -> Trainer:
raise AssertionError("the hosted check builds no components")

def online_eval_config(self) -> OnlineEval | None:
raise AssertionError("the hosted check builds no components")

def components(self):
raise AssertionError("the hosted check builds no components")

@model_validator(mode="after")
def validate_components(self):
self.components()
return self

sys.modules["prime_rl.configs.sft"].SFTConfig = SFT
request = {"mode": "sft", "schema_commit": "a" * 40, "online_eval_components": True}
config = {"eval": {"source": [{"env": {"id": "a"}}]}, "inference": {"vllm": {}}}

components = worker.normalize({**request, "config": config})["components"]

assert components["trainer"].keys() == Trainer.model_fields.keys()
assert components["orchestrator"]["monitors"]["prime"] == {"name": "run", "upload": True}


@pytest.mark.parametrize(
("config", "message"),
[
Expand Down Expand Up @@ -1296,7 +1378,7 @@ def test_worker_imports_only_what_the_schema_interpreter_provides():
node.module for node in ast.walk(tree) if isinstance(node, ast.ImportFrom) and node.level
]
assert relative == []
assert imported - sys.stdlib_module_names == {"prime_rl", "pydantic"}
assert imported - sys.stdlib_module_names <= {"prime_rl", "pydantic"}


def test_deferred_eval_settings_are_checked_without_their_sources(fake_schema):
Expand Down
Loading