File size: 4,564 Bytes
b16b327 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | """Job configs (YAML with one-level `base:` inheritance), model profiles, and model references."""
from __future__ import annotations
import copy
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import yaml
PROJECT_DIR = Path(__file__).resolve().parent.parent
CONFIG_DIR = PROJECT_DIR / "configs"
def load_yaml(path: str | Path) -> dict[str, Any]:
with open(path, encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def deep_merge(base: dict[str, Any], over: dict[str, Any]) -> dict[str, Any]:
out = copy.deepcopy(base)
for k, v in over.items():
out[k] = deep_merge(out[k], v) if isinstance(v, dict) and isinstance(out.get(k), dict) else copy.deepcopy(v)
return out
def set_dotted(cfg: dict[str, Any], dotted: str, value: Any) -> None:
keys = dotted.split(".")
node = cfg
for k in keys[:-1]:
node = node.setdefault(k, {})
node[keys[-1]] = value
def substitute(value: Any, names: dict[str, str]) -> Any:
if isinstance(value, str):
for k, v in names.items():
value = value.replace("{" + k + "}", v)
return value
if isinstance(value, dict):
return {k: substitute(v, names) for k, v in value.items()}
if isinstance(value, list):
return [substitute(v, names) for v in value]
return value
def resolve_job_config(config_file: str, overrides: dict[str, Any] | None = None, org: str | None = None,
config_dir: Path = CONFIG_DIR) -> dict[str, Any]:
"""Load configs/jobs/<config_file>, apply its `base:` chain and dotted overrides, and fill in {org}."""
path = config_dir / "jobs" / config_file
cfg = load_yaml(path)
seen = {path.name}
while "base" in cfg:
base_name = cfg.pop("base")
if base_name in seen:
raise ValueError(f"config inheritance loop at {base_name}")
seen.add(base_name)
cfg = deep_merge(load_yaml(config_dir / "jobs" / base_name), cfg)
for k, v in (overrides or {}).items():
set_dotted(cfg, k, v)
missing = [k for k in REQUIRED_KEYS.get(cfg.get("kind"), ()) if k not in cfg]
if cfg.get("kind") not in REQUIRED_KEYS or missing:
raise ValueError(f"{config_file}: kind={cfg.get('kind')!r}, missing keys {missing}")
if "profile" in REQUIRED_KEYS[cfg["kind"]] and cfg.get("profile") not in model_profiles(config_dir):
raise ValueError(f"{config_file}: unknown profile {cfg.get('profile')!r}")
return substitute(cfg, {"org": org}) if org else cfg
_TRAIN = ("student", "profile", "rounds", "lora", "optim")
_SAMPLED = ("pool", "prompts_per_round", "samples_per_prompt", "max_new_tokens")
REQUIRED_KEYS: dict[str, tuple[str, ...]] = {
"opd": (*_TRAIN, *_SAMPLED, "teacher", "teacher_profile"),
"grpo": (*_TRAIN, *_SAMPLED),
"loopfix": (*_TRAIN, *_SAMPLED),
"sft": (*_TRAIN, "data", "examples_per_round"),
"eval": ("model", "profile", "problems"),
"system": ("model", "profile", "problems", "voting"),
"smoke": ("student", "profile", "problems"),
"data": (),
}
@dataclass(frozen=True)
class ModelRef:
"""A model on the Hub or on disk: "repo[@revision][:subfolder]".
A subfolder that holds a LoRA adapter (adapter_config.json) is merged onto the base
named in its base.json when materialized.
"""
repo: str
revision: str | None = None
subfolder: str | None = None
@staticmethod
def parse(text: str) -> ModelRef:
repo, _, sub = text.partition(":") if not _looks_like_windows_path(text) else (text, "", "")
repo, _, rev = repo.partition("@")
return ModelRef(repo, rev or None, sub or None)
def __str__(self) -> str:
s = self.repo + (f"@{self.revision}" if self.revision else "")
return s + (f":{self.subfolder}" if self.subfolder else "")
@property
def is_local(self) -> bool:
return Path(self.repo).exists()
def _looks_like_windows_path(text: str) -> bool:
return len(text) > 2 and text[1] == ":" and text[2] in "\\/"
def model_profiles(config_dir: Path = CONFIG_DIR) -> dict[str, dict[str, Any]]:
return load_yaml(config_dir / "models.yaml")
def profile(name: str, config_dir: Path = CONFIG_DIR) -> dict[str, Any]:
profiles = model_profiles(config_dir)
if name not in profiles:
raise KeyError(f"unknown model profile {name!r}; known: {sorted(profiles)}")
return profiles[name]
|