"""Checkpoint configuration: ``r2_config.json`` next to the weights.""" from __future__ import annotations import json import math from dataclasses import dataclass from pathlib import Path CONFIG_FILE = "r2_config.json" READOUTS = ("softmax", "rcr") KNOWN_FIELDS = {"adapter", "input_format", "head", "pooling", "chat_template_sha256", "attention_mode", "temperature", "readout"} @dataclass(frozen=True) class HeadConfig: temperature: float = 1.0 readout: str = "softmax" # softmax(z/T), or rcr: sigmoid(z/T) normalised over a question's options def load_config(source: Path) -> HeadConfig: """Read and validate ``r2_config.json``; this package scores exactly one layout (see ``prompt``).""" path = source / CONFIG_FILE if not path.exists(): raise ValueError(f"{source} has no {CONFIG_FILE}: not a DeepEdu-Decision checkpoint") try: config = json.loads(path.read_text(encoding="utf-8")) except ValueError as exc: raise ValueError(f"{path} is not valid JSON: {exc}") from exc if not isinstance(config, dict): raise ValueError(f"{path}: expected a JSON object") expected = {"adapter": "r2", "input_format": "chat", "head": "mlp", "pooling": "branch_last", "attention_mode": "causal"} for key, value in expected.items(): if config.get(key) != value: raise ValueError(f"{path}: field {key!r} is {config.get(key)!r}, this package supports {value!r}") unknown = config.keys() - KNOWN_FIELDS if unknown: raise ValueError(f"{path}: unsupported field {sorted(unknown)[0]!r}") temperature = config.get("temperature", 1.0) if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) \ or not math.isfinite(temperature) or temperature <= 0: raise ValueError(f"{path}: invalid temperature {temperature!r}") readout = config.get("readout", "softmax") if readout not in READOUTS: raise ValueError(f"{path}: readout must be one of {list(READOUTS)}, got {readout!r}") return HeadConfig(float(temperature), readout)