"""Model clients for the C2 dual-compile (``docs/02`` §7.1). The C2 compiler is injected with one :class:`ModelClient` per role (proposer = Qwen3.5-9B, verifier = Gemma-4-12B-it). The contract is narrow: a client turns a :class:`CompileRequest` into a :class:`ModelResponse` (raw text + content hash + the pinned model identity). Clients are **gated and never fake a call**: the real :class:`HfModelClient` raises :class:`ModelUnavailable` when the pinned snapshot is absent, ``transformers`` is unavailable, or no accelerator is present — it never returns a fabricated program. Tests inject a deterministic fake; the fake lives in the test suite, not here, so no production path silently substitutes a model response. ``HF_TOKEN`` is read from the environment inside the downloader only; this module never places a token on a command line, in a log, or in an exception message. """ from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Any, Protocol from ..hashing import sha256_text from .request import CompileRequest class ModelUnavailable(RuntimeError): """A real model call cannot be made (snapshot missing / no accelerator). Raised — never caught-and-faked — so the caller reports the blocked compile rather than substituting a program (runbook: blocked → skip, never replace). """ @dataclass(frozen=True) class ModelResponse: """One model's raw compile response + its content hash + pinned identity.""" text: str response_sha256: str model_repo_id: str model_revision: str class ModelClient(Protocol): """Turns a compile request into a raw model response (never faked).""" @property def model_repo_id(self) -> str: ... @property def model_revision(self) -> str: ... def compile(self, request: CompileRequest) -> ModelResponse: ... def repair(self, request: CompileRequest, errors: list[str]) -> ModelResponse: """Re-ask with the first-response errors appended (the §7 one repair).""" ... @dataclass(frozen=True) class HfModelClient: """The production client: a pinned Hugging Face snapshot behind a gate. ``local_path`` is the model snapshot directory (under ``EXPLICIT_MODEL_ROOT``). The snapshot's resolved commit must equal ``revision``; a missing or mismatched snapshot raises :class:`ModelUnavailable`. Generation is delegated to ``transformers`` (imported lazily so importing this module never pulls the heavy ML stack); a missing dependency or accelerator raises :class:`ModelUnavailable`. The single allowed repair re-asks with the first-response errors appended to the prompt. """ logical_name: str repo_id: str revision: str local_path: Path temperature: float = 0.0 top_p: float = 1.0 max_new_tokens: int = 1024 @property def model_repo_id(self) -> str: return self.repo_id @property def model_revision(self) -> str: return self.revision # --- availability gate ------------------------------------------------ def _check_snapshot(self) -> None: if not self.local_path.exists() or not self.local_path.is_dir(): raise ModelUnavailable( f"model snapshot absent for {self.logical_name} at {self.local_path}" ) # A snapshot directory with only LFS pointers is not runnable. We do not # fetch here (no network from a compile call); a pointer-only tree is # treated as unavailable so the caller skips rather than fakes. if not any(self.local_path.rglob("config.json")): raise ModelUnavailable( f"model snapshot for {self.logical_name} has no config.json " "(LFS-pointer-only tree or wrong layout)" ) def _load_generator(self) -> dict[str, Any]: try: import torch # noqa: F401 (presence check + accelerator probe) from transformers import AutoModelForCausalLM, AutoTokenizer except Exception as exc: # pragma: no cover - env-dependent raise ModelUnavailable(f"transformers/torch unavailable: {exc!r}") from exc try: device = "cuda" if torch.cuda.is_available() else "cpu" except Exception: # pragma: no cover - env-dependent device = "cpu" try: tokenizer = AutoTokenizer.from_pretrained(str(self.local_path)) model = AutoModelForCausalLM.from_pretrained(str(self.local_path)) model = model.to(device) if hasattr(model, "to") else model except Exception as exc: # pragma: no cover - env-dependent raise ModelUnavailable(f"model load failed for {self.logical_name}: {exc!r}") from exc return {"tokenizer": tokenizer, "model": model, "device": device} # --- contract --------------------------------------------------------- def compile(self, request: CompileRequest) -> ModelResponse: self._check_snapshot() gen = self._load_generator() text = self._generate(gen, request.prompt) return ModelResponse( text=text, response_sha256=sha256_text(text), model_repo_id=self.repo_id, model_revision=self.revision, ) def repair(self, request: CompileRequest, errors: list[str]) -> ModelResponse: hint = request.prompt + "\n\nYour previous response was invalid: " + "; ".join(errors) self._check_snapshot() gen = self._load_generator() text = self._generate(gen, hint) return ModelResponse( text=text, response_sha256=sha256_text(text), model_repo_id=self.repo_id, model_revision=self.revision, ) def _generate(self, gen: dict[str, Any], prompt: str) -> str: tokenizer = gen["tokenizer"] model = gen["model"] device = gen["device"] import torch # local import keeps the heavy stack out of module load inputs = tokenizer(prompt, return_tensors="pt") if device == "cuda": inputs = {k: v.to("cuda") for k, v in inputs.items()} with torch.no_grad(): out = model.generate( **inputs, max_new_tokens=self.max_new_tokens, do_sample=False, temperature=self.temperature, top_p=self.top_p, ) prompt_len = inputs["input_ids"].shape[1] text = tokenizer.decode(out[0][prompt_len:], skip_special_tokens=True) return str(text) __all__ = ["HfModelClient", "ModelClient", "ModelResponse", "ModelUnavailable"]