Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

feat(config): typed, validated configs with clear errors

FareedKhan-dev7554e51f2d56
diff --git a/config/loader.py b/config/loader.py
index 4c1c347..640d827 100644
--- a/config/loader.py
+++ b/config/loader.py
@@ -1,28 +1,46 @@
"""
-JSON config loader for the post-training stages.
+Typed JSON config loader for the post-training stages.
-Industry-standard, learning-friendly: each stage's knobs live in a small editable JSON file
-under ``configs/`` (typed by the dataclasses in :mod:`config.post_training_config`). This
-loader resolves a final dataclass instance by merging four layers, lowest precedence first:
+Each stage's knobs live in a small editable JSON file under ``configs/`` (typed by the
+dataclasses in :mod:`config.post_training_config`). This loader resolves a final dataclass
+instance by merging four layers, lowest precedence first:
1. dataclass field defaults (config.post_training_config.<Stage>Config)
2. configs/base.json (shared model + runtime fields)
3. the stage JSON (configs/sft.json, ...) (that stage's hyperparameters)
4. CLI --field overrides (highest precedence)
-JSON ``null`` maps to Python ``None`` cleanly -- the right way to set ``str | None`` fields
-like ``amp_dtype``. Unknown keys are warned about, not fatal.
+Every value is checked against the type annotation of its field, so mistakes fail early
+and say where they came from:
+
+ ConfigError: configs/dpo.json: loss_type must be one of ['dpo', 'ipo', ...], got 'dop'
+ ConfigError: configs/sft.json: unknown key 'learning_rate' (did you mean 'lr'?)
+
+Conversions are the ones you would expect: JSON ``null`` (or the CLI strings ``none``/``null``)
+becomes ``None`` for optional fields, ``"1e-5"`` becomes a float, ``2000.0`` becomes an int,
+``"true"``/``"false"`` become booleans, and ``$VARS`` in strings are expanded. Keys that start
+with an underscore (``"_comment"``) are ignored, so JSON files can carry notes.
When ``json_path`` lives in a sub-dir with its own ``base.json`` (e.g. ``configs/smoke/sft.json``),
-that sibling ``base.json`` is used automatically -- so the smoke configs shrink the model too.
+that sibling ``base.json`` is used automatically, so the smoke configs shrink the model too.
"""
from __future__ import annotations
+import difflib
import json
import os
+import types
from dataclasses import fields
-from typing import Any
+from typing import Any, Literal, TypeVar, Union, get_args, get_origin, get_type_hints
+
+from config.post_training_config import ConfigError
+
+T = TypeVar("T")
+
+_TRUE = {"true", "1", "yes", "y", "on"}
+_FALSE = {"false", "0", "no", "n", "off"}
+_NONE = {"none", "null"}
def _deep_merge(dst: dict, src: dict) -> dict:
@@ -45,13 +63,83 @@ def _resolve_base(json_path: str | None, base_path: str | None) -> str:
return "configs/base.json"
+def type_name(annotation: Any) -> str:
+ """Short human name of a field type, for help texts and error messages."""
+ if get_origin(annotation) is Literal:
+ return "{" + ",".join(str(a) for a in get_args(annotation)) + "}"
+ if get_origin(annotation) in (Union, types.UnionType):
+ return " | ".join(type_name(a) for a in get_args(annotation))
+ return "None" if annotation is type(None) else getattr(annotation, "__name__", str(annotation))
+
+
+def coerce(value: Any, annotation: Any, name: str = "value") -> Any:
+ """Convert ``value`` to ``annotation`` (bool/int/float/str/None/Literal/unions) or raise."""
+ origin = get_origin(annotation)
+ if origin is Literal:
+ options = get_args(annotation)
+ if value in options:
+ return value
+ raise ConfigError(f"{name} must be one of {list(options)}, got {value!r}")
+ if origin in (Union, types.UnionType):
+ args = get_args(annotation)
+ if type(None) in args and (value is None or (isinstance(value, str) and value.strip().lower() in _NONE)):
+ return None
+ for arg in args:
+ if arg is type(None):
+ continue
+ try:
+ return coerce(value, arg, name)
+ except ConfigError:
+ continue
+ raise ConfigError(f"{name} must be {type_name(annotation)}, got {value!r}")
+ if annotation is bool:
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, str) and value.strip().lower() in _TRUE | _FALSE:
+ return value.strip().lower() in _TRUE
+ raise ConfigError(f"{name} must be true or false, got {value!r}")
+ if annotation is int:
+ if isinstance(value, int) and not isinstance(value, bool):
+ return value
+ if isinstance(value, float) and value.is_integer():
+ return int(value)
+ if isinstance(value, str):
+ try:
+ number = float(value.replace("_", ""))
+ except ValueError:
+ number = float("nan")
+ if number.is_integer():
+ return int(number)
+ raise ConfigError(f"{name} must be an integer, got {value!r}")
+ if annotation is float:
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value.replace("_", ""))
+ except ValueError:
+ pass
+ raise ConfigError(f"{name} must be a number, got {value!r}")
+ if annotation is str:
+ if isinstance(value, str):
+ return os.path.expandvars(value)
+ raise ConfigError(f"{name} must be a string, got {value!r}")
+ return value
+
+
+def field_types(cfg_cls: type) -> dict[str, Any]:
+ """Resolved type of every dataclass field (works with ``from __future__ import annotations``)."""
+ hints = get_type_hints(cfg_cls)
+ return {f.name: hints[f.name] for f in fields(cfg_cls)}
+
+
def load_config(
- cfg_cls,
+ cfg_cls: type[T],
json_path: str | None = None,
overrides: dict[str, Any] | None = None,
*,
base_path: str | None = None,
-):
+) -> T:
"""
Resolve ``cfg_cls`` from ``base.json`` + the stage JSON + CLI overrides.
@@ -64,22 +152,48 @@ def load_config(
``configs/base.json``.
Returns:
- an instance of ``cfg_cls`` with the resolved values.
+ an instance of ``cfg_cls`` with the resolved, type-checked values.
+
+ Raises:
+ ConfigError: unknown key, wrong type, or a value that fails the dataclass checks.
"""
+ types_by_field = field_types(cfg_cls)
base = _resolve_base(json_path, base_path)
merged: dict[str, Any] = {}
+ source: dict[str, str] = {}
for path in (base, json_path):
- if path and os.path.exists(path):
- with open(path) as fh:
- _deep_merge(merged, json.load(fh))
-
- field_names = {f.name for f in fields(cfg_cls)}
- for key in list(merged):
- if key not in field_names:
- print(f"[config] ignoring unknown key '{key}' for {cfg_cls.__name__}")
- merged.pop(key)
-
- if overrides:
- merged.update({k: v for k, v in overrides.items() if k in field_names and v is not None})
-
- return cfg_cls(**merged)
+ if not (path and os.path.exists(path)):
+ continue
+ with open(path, encoding="utf-8") as fh:
+ data = json.load(fh)
+ if not isinstance(data, dict):
+ raise ConfigError(f"{path}: expected a JSON object at the top level")
+ for key, value in data.items():
+ if key.startswith("_"):
+ continue
+ if key not in types_by_field:
+ hint = difflib.get_close_matches(key, types_by_field, n=1)
+ suggestion = f" (did you mean '{hint[0]}'?)" if hint else ""
+ raise ConfigError(f"{path}: unknown key '{key}' for {cfg_cls.__name__}{suggestion}")
+ merged[key] = value
+ source[key] = path
+
+ for key, value in (overrides or {}).items():
+ if value is None:
+ continue
+ if key not in types_by_field:
+ raise ConfigError(f"command line: unknown option --{key} for {cfg_cls.__name__}")
+ merged[key] = value
+ source[key] = "command line"
+
+ values = {}
+ for key, value in merged.items():
+ try:
+ values[key] = coerce(value, types_by_field[key], key)
+ except ConfigError as e:
+ raise ConfigError(f"{source[key]}: {e}") from None
+ try:
+ return cfg_cls(**values)
+ except ConfigError as e:
+ origin = ", ".join(sorted({source[k] for k in values})) or "defaults"
+ raise ConfigError(f"{e} (from {origin})") from None
diff --git a/config/post_training_config.py b/config/post_training_config.py
index 7b655fd..93c5897 100644
--- a/config/post_training_config.py
+++ b/config/post_training_config.py
@@ -1,23 +1,42 @@
"""
-Configuration for the from-scratch post-training suite.
+Configuration for the post-training suite (and the scalable pretraining script).
-Kept entirely separate from ``config/config.py`` (which import-executes for the original
-pretraining path and must stay untouched). Each stage is a frozen-ish dataclass that
-inherits the shared :class:`BaseModelConfig` model/runtime fields and adds its own
-hyperparameters. Construct with overrides, e.g. ``SFTConfig(lr=2e-5, batch_size=16)``.
+Kept separate from ``config/config.py`` (the plain constants of the original pretraining
+path). Each stage is a dataclass that inherits the shared :class:`BaseModelConfig`
+model/runtime fields and adds its own hyperparameters. Construct with overrides, e.g.
+``SFTConfig(lr=2e-5, batch_size=16)``, or load from JSON with :func:`config.loader.load_config`.
+
+The fields are typed (``Literal`` for every choice), and the JSON loader and the CLI check
+values against these types, so a typo such as ``"loss_type": "dop"`` fails at startup with a
+clear message instead of halfway through a run. ``__post_init__`` adds the checks a type
+cannot express (positive sizes, ``n_embed`` divisible by ``n_head``, and so on).
The default base model is ~400M parameters (n_embed=1024, n_head=16, n_blocks=24,
-context_length=1024) -- the "mid" size chosen so real datasets (Alpaca, HH-RLHF, GSM8K)
-give meaningful results while still fitting comfortably on one H100 and training in a
-reasonable time on 2x H100. A tiny ``SMOKE`` variant is provided for fast CPU/1-GPU tests.
+context_length=1024), the "mid" size chosen so real datasets (Alpaca, HH-RLHF, GSM8K) give
+meaningful results while still fitting on one 80GB GPU. A tiny ``SMOKE`` variant is provided
+for fast CPU tests.
"""
from __future__ import annotations
-from dataclasses import dataclass, field, replace
+from dataclasses import dataclass, replace
+from typing import Literal, TypeVar
from config.paths import CKPT_DIR, DATA_DIR, LOG_DIR
+AmpDtype = Literal["bf16", "fp16"]
+PreferenceLoss = Literal["dpo", "orpo", "kto"]
+RewardSource = Literal["verifier", "rm"]
+
+
+class ConfigError(ValueError):
+ """A configuration value is missing, has the wrong type, or is out of range."""
+
+
+def _check(cond: bool, message: str) -> None:
+ if not cond:
+ raise ConfigError(message)
+
@dataclass
class BaseModelConfig:
@@ -29,15 +48,21 @@ class BaseModelConfig:
n_blocks: int = 24
# --- runtime ---
- device: str = "auto" # auto | cuda | mps | cpu
- amp_dtype: str | None = "bf16" # None | "bf16"; bf16 needs no GradScaler on H100
+ device: str = "auto" # auto | cuda | mps | cpu
+ amp_dtype: AmpDtype | None = "bf16" # None | "bf16" | "fp16"; ignored on CPU
seed: int = 1337
- compile: bool = False # torch.compile the model (big speedup, slow 1st step)
+ compile: bool = False # torch.compile the model (big speedup, slow 1st step)
ckpt_dir: str = CKPT_DIR
log_dir: str = LOG_DIR
use_wandb: bool = False
wandb_project: str = "train-llm-from-scratch-posttrain"
+ def __post_init__(self) -> None:
+ for name in ("vocab_size", "context_length", "n_embed", "n_head", "n_blocks"):
+ _check(getattr(self, name) > 0, f"{name} must be positive, got {getattr(self, name)}")
+ _check(self.n_embed % self.n_head == 0,
+ f"n_embed ({self.n_embed}) must be divisible by n_head ({self.n_head})")
+
@dataclass
class PretrainConfig(BaseModelConfig):
@@ -57,6 +82,12 @@ class PretrainConfig(BaseModelConfig):
out_ckpt: str = f"{CKPT_DIR}/base_pretrained.pt"
save_every: int = 2_000
+ def __post_init__(self) -> None:
+ super().__post_init__()
+ _check(self.batch_size > 0 and self.grad_accum > 0, "batch_size and grad_accum must be positive")
+ _check(0 <= self.min_lr <= self.lr, "need 0 <= min_lr <= lr")
+ _check(self.warmup_steps < self.train_steps, "warmup_steps must be smaller than train_steps")
+
@dataclass
class SFTConfig(BaseModelConfig):
@@ -93,6 +124,10 @@ class RewardConfig(BaseModelConfig):
max_len: int = 768
save_every: int = 500
+ def __post_init__(self) -> None:
+ super().__post_init__()
+ _check(16 <= self.max_len <= self.context_length, "max_len must be between 16 and context_length")
+
@dataclass
class DPOConfig(BaseModelConfig):
@@ -100,7 +135,7 @@ class DPOConfig(BaseModelConfig):
pref_path: str = f"{DATA_DIR}/preferences.jsonl"
test_path: str = f"{DATA_DIR}/preferences_test.jsonl"
out_ckpt: str = f"{CKPT_DIR}/dpo.pt"
- loss_type: str = "dpo" # "dpo" | "orpo" | "kto"
+ loss_type: PreferenceLoss = "dpo" # dpo | orpo | kto
beta: float = 0.1
orpo_lambda: float = 1.0 # ORPO odds-ratio weight (loss_type="orpo")
batch_size: int = 8
@@ -113,6 +148,11 @@ class DPOConfig(BaseModelConfig):
max_len: int = 768
save_every: int = 500
+ def __post_init__(self) -> None:
+ super().__post_init__()
+ _check(self.beta > 0, "beta must be positive")
+ _check(16 <= self.max_len <= self.context_length, "max_len must be between 16 and context_length")
+
@dataclass
class PPOConfig(BaseModelConfig):
@@ -121,7 +161,7 @@ class PPOConfig(BaseModelConfig):
prompt_path: str = f"{DATA_DIR}/rl_prompts_train.jsonl"
eval_prompt_path: str = f"{DATA_DIR}/rl_prompts_test.jsonl"
out_ckpt: str = f"{CKPT_DIR}/ppo.pt"
- reward_source: str = "verifier" # "verifier" (GSM8K checker) | "rm" (reward model)
+ reward_source: RewardSource = "verifier" # "verifier" (GSM8K checker) | "rm" (reward model)
iterations: int = 1_000
prompts_per_iter: int = 32 # prompts sampled per PPO iteration (per rank)
rollout_len: int = 300
@@ -164,13 +204,23 @@ class GRPOConfig(BaseModelConfig):
eval_every: int = 50
save_every: int = 100
+ def __post_init__(self) -> None:
+ super().__post_init__()
+ _check(self.group_size >= 2, "group_size must be at least 2 (the group is the baseline)")
+ _check(self.clip > 0, "clip must be positive")
+
# Tiny config for fast smoke tests (CPU or a single GPU, seconds not hours).
SMOKE = dict(
vocab_size=256, context_length=64, n_embed=64, n_head=4, n_blocks=2, device="cpu", amp_dtype=None
)
+C = TypeVar("C", bound=BaseModelConfig)
+
-def smoke(cfg_cls):
+def smoke(cfg_cls: type[C]) -> C:
"""Return an instance of ``cfg_cls`` shrunk to the tiny SMOKE model dims."""
- return replace(cfg_cls(), **SMOKE)
+ overrides: dict[str, object] = dict(SMOKE)
+ if "max_len" in cfg_cls.__dataclass_fields__:
+ overrides["max_len"] = SMOKE["context_length"]
+ return replace(cfg_cls(), **overrides) # type: ignore[arg-type]
diff --git a/src/post_training/cli.py b/src/post_training/cli.py
index ba4f498..7fe8fc4 100644
--- a/src/post_training/cli.py
+++ b/src/post_training/cli.py
@@ -1,32 +1,47 @@
"""
Shared CLI helper: turn any stage config dataclass into ``--field value`` arguments so
every training script can override hyperparameters without bespoke argparse blocks.
+
+Values arrive from the command line as strings and are converted with the same typed rules
+as the JSON files (see :func:`config.loader.coerce`), so ``--n_kv_head 4`` becomes the int 4,
+``--amp_dtype none`` becomes ``None`` and ``--loss_type dop`` is rejected with the valid choices.
"""
from __future__ import annotations
import argparse
import json
-from dataclasses import asdict, fields
+from dataclasses import MISSING, asdict, fields
from types import SimpleNamespace
+from typing import Any, Literal, TypeVar, get_args, get_origin
-from config.loader import load_config
+from config.loader import coerce, field_types, load_config, type_name
+from config.post_training_config import ConfigError
+T = TypeVar("T")
-def _add_typed(p: argparse.ArgumentParser, name: str, type_str) -> None:
- t = str(type_str)
- if "int" in t and "|" not in t:
- p.add_argument(f"--{name}", type=int)
- elif "float" in t:
- p.add_argument(f"--{name}", type=float)
- elif t == "bool" or t == "<class 'bool'>":
- p.add_argument(f"--{name}", type=lambda s: s.lower() in ("1", "true", "yes"))
- else:
- # str, optionals, unions -> accept as string (dataclass keeps None defaults otherwise)
- p.add_argument(f"--{name}", type=str)
+def _build_parser(cfg_cls: type, extra: dict | None) -> argparse.ArgumentParser:
+ p = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
+ types_by_field = field_types(cfg_cls)
+ for f in fields(cfg_cls):
+ annotation = types_by_field[f.name]
+ default = f.default if f.default is not MISSING else None
+ choices = list(get_args(annotation)) if get_origin(annotation) is Literal else None
+ p.add_argument(
+ f"--{f.name}",
+ type=str,
+ default=None,
+ metavar=type_name(annotation) if choices is None else None,
+ choices=[str(c) for c in choices] if choices else None,
+ help=f"default: {default}",
+ )
+ for flag, kwargs in (extra or {}).items():
+ p.add_argument(flag, **kwargs)
+ return p
-def parse_config(cfg_cls, extra: dict | None = None):
+
+def parse_config(cfg_cls: type[T], extra: dict | None = None) -> tuple[T, SimpleNamespace]:
"""
Parse CLI overrides for a config dataclass.
@@ -34,20 +49,21 @@ def parse_config(cfg_cls, extra: dict | None = None):
``--field`` overrides applied, and ``extras`` is a namespace of any non-config args
declared via ``extra`` (mapping ``"--flag" -> dict(argparse kwargs)``).
"""
- p = argparse.ArgumentParser()
- field_names = {f.name for f in fields(cfg_cls)}
- for f in fields(cfg_cls):
- _add_typed(p, f.name, f.type)
- for flag, kwargs in (extra or {}).items():
- p.add_argument(flag, **kwargs)
+ p = _build_parser(cfg_cls, extra)
args = vars(p.parse_args())
-
- overrides = {k: v for k, v in args.items() if k in field_names and v is not None}
- extras = {k: v for k, v in args.items() if k not in field_names}
- return cfg_cls(**overrides), SimpleNamespace(**extras)
+ types_by_field = field_types(cfg_cls)
+ try:
+ overrides = {k: coerce(v, types_by_field[k], k) for k, v in args.items() if k in types_by_field and v is not None}
+ cfg = cfg_cls(**overrides)
+ except ConfigError as e:
+ p.error(str(e))
+ extras = {k: v for k, v in args.items() if k not in types_by_field}
+ return cfg, SimpleNamespace(**extras)
-def parse_config_with_json(cfg_cls, default_json: str, extra: dict | None = None):
+def parse_config_with_json(
+ cfg_cls: type[T], default_json: str, extra: dict | None = None
+) -> tuple[T, SimpleNamespace]:
"""
Like :func:`parse_config`, but resolves the config from a JSON file too.
@@ -60,22 +76,21 @@ def parse_config_with_json(cfg_cls, default_json: str, extra: dict | None = None
Returns ``(cfg, extras)`` exactly like :func:`parse_config`.
"""
- p = argparse.ArgumentParser()
- field_names = {f.name for f in fields(cfg_cls)}
- for f in fields(cfg_cls):
- _add_typed(p, f.name, f.type)
+ p = _build_parser(cfg_cls, extra)
p.add_argument("--config", default=default_json, help="stage JSON config to load")
p.add_argument("--print-config", action="store_true", help="print resolved config and exit")
- for flag, kwargs in (extra or {}).items():
- p.add_argument(flag, **kwargs)
args = vars(p.parse_args())
+ types_by_field = field_types(cfg_cls)
reserved = {"config", "print_config"}
- overrides = {k: v for k, v in args.items() if k in field_names and v is not None}
- extras = {k: v for k, v in args.items() if k not in field_names and k not in reserved}
+ overrides: dict[str, Any] = {k: v for k, v in args.items() if k in types_by_field and v is not None}
+ extras = {k: v for k, v in args.items() if k not in types_by_field and k not in reserved}
- cfg = load_config(cfg_cls, args["config"], overrides)
+ try:
+ cfg = load_config(cfg_cls, args["config"], overrides)
+ except ConfigError as e:
+ p.error(str(e))
if args["print_config"]:
- print(json.dumps(asdict(cfg), indent=2))
+ print(json.dumps(asdict(cfg), indent=2)) # type: ignore[call-overload]
raise SystemExit(0)
return cfg, SimpleNamespace(**extras)
diff --git a/tests/test_config.py b/tests/test_config.py
new file mode 100644
index 0000000..274da25
--- /dev/null
+++ b/tests/test_config.py
@@ -0,0 +1,116 @@
+"""Typed configs: every shipped JSON file loads, and bad values fail early with a clear message."""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from config.loader import coerce, load_config
+from config.post_training_config import (
+ ConfigError,
+ DPOConfig,
+ GRPOConfig,
+ PPOConfig,
+ PretrainConfig,
+ RewardConfig,
+ SFTConfig,
+ smoke,
+)
+from src.post_training.cli import parse_config_with_json
+
+STAGES = {
+ "pretrain": PretrainConfig, "sft": SFTConfig, "reward": RewardConfig,
+ "dpo": DPOConfig, "ppo": PPOConfig, "grpo": GRPOConfig,
+}
+
+
[email protected]("folder", ["configs", "configs/smoke"])
[email protected]("name", list(STAGES))
+def test_every_shipped_config_loads(folder: str, name: str) -> None:
+ cfg = load_config(STAGES[name], f"{folder}/{name}.json")
+ assert isinstance(cfg, STAGES[name])
+ for value in vars(cfg).values(): # no machine-specific absolute paths in the defaults
+ assert not (isinstance(value, str) and value.startswith("/ephemeral"))
+
+
+def test_smoke_configs_never_overwrite_real_checkpoints() -> None:
+ for name, cls in STAGES.items():
+ assert load_config(cls, f"configs/smoke/{name}.json").out_ckpt.startswith("models/smoke/")
+
+
+def _json(tmp_path: Path, data: dict[str, Any]) -> str:
+ path = tmp_path / "stage.json"
+ path.write_text(json.dumps(data), encoding="utf-8")
+ return str(path)
+
+
+def test_unknown_keys_fail_with_a_suggestion(tmp_path: Path) -> None:
+ with pytest.raises(ConfigError, match="did you mean 'batch_size'"):
+ load_config(SFTConfig, _json(tmp_path, {"batchsize": 4}))
+
+
+def test_wrong_values_name_the_field_and_the_file(tmp_path: Path) -> None:
+ with pytest.raises(ConfigError, match=r"loss_type must be one of \["):
+ load_config(DPOConfig, _json(tmp_path, {"loss_type": "dop"}))
+ with pytest.raises(ConfigError, match="stage.json: lr must be a number"):
+ load_config(SFTConfig, _json(tmp_path, {"lr": "fast"}))
+ with pytest.raises(ConfigError, match="divisible"):
+ load_config(SFTConfig, _json(tmp_path, {"n_embed": 30, "n_head": 4}))
+
+
+def test_comment_keys_are_ignored(tmp_path: Path) -> None:
+ cfg = load_config(SFTConfig, _json(tmp_path, {"_comment": "half the default lr", "lr": 5e-6}))
+ assert cfg.lr == 5e-6
+
+
+ ("value", "annotation", "expected"),
+ [
+ ("4", int, 4),
+ (2000.0, int, 2000),
+ ("50_000", int, 50_000),
+ ("1e-5", float, 1e-5),
+ (3, float, 3.0),
+ ("true", bool, True),
+ ("off", bool, False),
+ ("none", int | None, None),
+ ("8", int | None, 8),
+ (None, str | None, None),
+ ],
+)
+def test_coerce_accepts_sensible_spellings(value: Any, annotation: Any, expected: Any) -> None:
+ assert coerce(value, annotation) == expected
+
+
[email protected](("value", "annotation"), [(True, int), (1, bool), ("1.5", int), ("abc", float), (3, str)])
+def test_coerce_rejects_the_rest(value: Any, annotation: Any) -> None:
+ with pytest.raises(ConfigError):
+ coerce(value, annotation)
+
+
+def test_environment_variables_are_expanded(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("BIG_DISK", "/mnt/big")
+ cfg = load_config(SFTConfig, _json(tmp_path, {"out_ckpt": "$BIG_DISK/models/sft.pt"}))
+ assert cfg.out_ckpt == "/mnt/big/models/sft.pt"
+
+
+def test_smoke_shrinks_every_stage() -> None:
+ for cls in STAGES.values():
+ cfg = smoke(cls)
+ assert cfg.context_length == 64 and cfg.device == "cpu"
+ assert smoke(DPOConfig).max_len == 64
+
+
+def test_cli_values_are_converted_like_json(monkeypatch: pytest.MonkeyPatch) -> None:
+ argv = ["train_sft.py", "--config", "configs/smoke/sft.json",
+ "--lr", "2e-5", "--compile", "true", "--amp_dtype", "none", "--max_steps", "3"]
+ monkeypatch.setattr(sys, "argv", argv)
+ cfg, _ = parse_config_with_json(SFTConfig, "configs/sft.json")
+ assert (cfg.lr, cfg.compile, cfg.amp_dtype, cfg.max_steps) == (2e-5, True, None, 3)
+ monkeypatch.setattr(sys, "argv", ["train_dpo.py", "--loss_type", "dop"])
+ with pytest.raises(SystemExit):
+ parse_config_with_json(DPOConfig, "configs/dpo.json")