Skip to content
Merged
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
185 changes: 142 additions & 43 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,35 @@ 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 resolved_inference_section(config):
"""The resolved `[inference]` section: `config.resolved_inference()` after prime-rl#4928,
else `config.inference`."""
resolver = getattr(config, "resolved_inference", None)
if resolver is not None:
return resolver()
return config.inference


def legacy_inference(config):
"""The inference component of pre-v0.12 builds, served with `--router None`."""
section = resolved_inference_section(config)
inference = section.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 @@ -128,9 +158,9 @@ def reject_unsupported_hosted_settings(config):
)


def supervised_online_eval(model, data):
"""Trainer, eval process and inference components for a supervised run's
online evals, split as prime-rl's launcher does.
def supervised_online_eval(model, data, serialization):
"""Trainer, eval process, inference and optional router components for a
supervised run's online evals, split as prime-rl's launcher does.

The eval sources need environment plugins, so they are lifted out while
the rest validates: prime-rl's own online-eval setup (inference sizing,
Expand Down Expand Up @@ -162,8 +192,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,25 +215,62 @@ 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
}
if hasattr(config, "weight_broadcast_config"):
trainer["weight_broadcast"] = config.weight_broadcast_config(
"0.0.0.0" if multi else "localhost"
)
# The trainer schedules its weight broadcasts from the eval sources.
trainer["eval"]["source"] = sources
evals = config.eval.model_dump(mode="json")
eval_wb = (
config.weight_broadcast_config()
if hasattr(config, "weight_broadcast_config")
else (config.weight_broadcast and config.weight_broadcast.model_dump(mode="json"))
)
evals.update(
source=sources,
model=config.model.name,
max_steps=config.max_steps,
log={"level": config.log.level, "json_logging": config.log.json_logging},
weight_broadcast=config.weight_broadcast
and config.weight_broadcast.model_dump(mode="json"),
weight_broadcast=eval_wb,
)
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}
eval_component = component_class(model, "online_eval_config") or type(config.eval)
if "monitors" in eval_component.model_fields:
evals["monitors"] = eval_monitors(config, eval_component)
if "resume" in eval_component.model_fields:
evals["resume"] = config.resume.model_dump(mode="json") if config.resume else None
if "ckpt_output_dir" in eval_component.model_fields:
ckpt = getattr(config, "ckpt", None)
ckpt_dir = getattr(ckpt, "output_dir", None) if ckpt is not None else None
evals["ckpt_output_dir"] = str(ckpt_dir or config.run_dir)
if (
not multi
and isinstance(evals.get("client"), dict)
and evals["client"].get("admin_base_url") is None
and getattr(config.inference, "router", None) is not None
and getattr(config.inference, "backend_port", None) is not None
):
host = config.inference.server.host or "localhost"
evals["client"]["admin_base_url"] = [f"http://{host}:{config.inference.backend_port}/v1"]

components = {"trainer": trainer, "orchestrator": evals}
if hasattr(serialization, "dump_components") and hasattr(config, "engine_configs"):
engines = config.engine_configs()
if "engine" in engines:
components["inference"] = engines["engine"].model_dump(mode="json")
else:
components["inference"] = legacy_inference(config)
router = config.router_config() if hasattr(config, "router_config") else None
if router is not None:
components["router"] = router.model_dump(mode="json")
else:
components["inference"] = legacy_inference(config)
return config, components


def reject_unsupported_online_eval_settings(config):
Expand All @@ -218,11 +293,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 +308,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 +342,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 +364,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 @@ -281,7 +375,7 @@ def normalize(request):
# older ones validate the deferred blocks themselves.
components_supported = mode != "rl" and request.get("online_eval_components")
if components_supported and isinstance(data.get("eval"), dict):
config, components = supervised_online_eval(model, data)
config, components = supervised_online_eval(model, data, serialization)
elif components_supported:
stray = [key for key in ("inference", "weight_broadcast") if data.get(key) is not None]
if stray:
Expand All @@ -291,33 +385,38 @@ 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", "router") if key in built
}
if "engine" in built:
components["inference"] = built["engine"]
elif 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
Loading
Loading