"""Pure-Python admission checks for the common SFT LoRA adapter. These checks deliberately run before importing PEFT or allocating a model. An RL plan may only consume the exact adapter shape frozen by the experiment protocol, and a loaded model may only expose LoRA parameters as trainable. """ from __future__ import annotations import json from collections.abc import Mapping from pathlib import Path from typing import Any from ..hashing import canonical_json_hash def adapter_checkpoint_errors( checkpoint: str | Path, runtime: Mapping[str, Any], ) -> list[str]: """Return semantic errors for a frozen PEFT adapter checkpoint.""" root = Path(checkpoint) if not root.is_dir(): return [f"initial checkpoint is not a directory: {root}"] config_path = root / "adapter_config.json" try: config = json.loads(config_path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: return [f"cannot read PEFT adapter_config.json: {exc}"] if not isinstance(config, dict): return ["PEFT adapter_config.json must be an object"] errors: list[str] = [] expected = { "r": int(runtime["lora_rank"]), "lora_alpha": int(runtime["lora_alpha"]), "lora_dropout": float(runtime["lora_dropout"]), "bias": "none", "peft_type": "LORA", "task_type": "CAUSAL_LM", } for field, wanted in expected.items(): if config.get(field) != wanted: errors.append(f"PEFT adapter {field}={config.get(field)!r}, expected {wanted!r}") targets = config.get("target_modules") if isinstance(targets, str): target_names = [targets] elif isinstance(targets, list) and all(isinstance(item, str) and item for item in targets): target_names = list(targets) else: target_names = [] if not target_names: errors.append("PEFT adapter target_modules is empty or malformed") forbidden = [ name for name in target_names if "embed" in name.lower() or "lm_head" in name.lower() ] if forbidden: errors.append(f"PEFT adapter targets forbidden modules: {sorted(forbidden)}") if config.get("modules_to_save") not in (None, []): errors.append("PEFT adapter modules_to_save must be empty") if config.get("rank_pattern") not in (None, {}): errors.append("PEFT adapter rank_pattern must be empty") if bool(config.get("use_dora", False)): errors.append("PEFT adapter use_dora must be false") base = str(config.get("base_model_name_or_path", "")) allowed_bases = { str(runtime.get("model_path", "")), str(Path(str(runtime.get("model_path", ""))).resolve()), "Qwen/Qwen3.5-2B", } if base not in allowed_bases: errors.append("PEFT adapter base_model_name_or_path is not the frozen base model") excludes = config.get("exclude_modules") if not isinstance(excludes, list) or "lm_head" not in excludes: errors.append("PEFT adapter exclude_modules must include lm_head") weight_candidates = ( root / "adapter_model.safetensors", root / "adapter_model.bin", ) if not any(path.is_file() and path.stat().st_size > 0 for path in weight_candidates): errors.append("PEFT adapter has no non-empty adapter_model weights") return errors def trainable_parameter_manifest(model: Any) -> tuple[list[dict[str, Any]], str]: """Return the canonical manifest and SHA of every trainable parameter.""" rows: list[dict[str, Any]] = [] for name, parameter in model.named_parameters(): if not bool(getattr(parameter, "requires_grad", False)): continue shape = [int(value) for value in getattr(parameter, "shape", ())] rows.append( { "name": str(name), "shape": shape, "dtype": str(getattr(parameter, "dtype", "")), } ) rows.sort(key=lambda row: row["name"]) return rows, canonical_json_hash(rows) def trainable_parameter_errors(model: Any) -> list[str]: """Reject a loaded adapter unless only non-embedding LoRA weights train.""" rows, _ = trainable_parameter_manifest(model) if not rows: return ["model has no trainable parameters"] errors: list[str] = [] non_lora = [row["name"] for row in rows if "lora_" not in row["name"].lower()] if non_lora: errors.append(f"non-LoRA parameters are trainable: {non_lora[:8]}") forbidden = [ row["name"] for row in rows if "embed" in row["name"].lower() or "lm_head" in row["name"].lower() ] if forbidden: errors.append(f"forbidden embedding/lm_head parameters are trainable: {forbidden[:8]}") return errors