File size: 6,683 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
"""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"]