"""Model backends. Every backend implements `complete(prompt) -> str`. The harness treats a raised exception as a failed case rather than aborting the run, so a single flaky response cannot destroy a multi-hour evaluation. """ from __future__ import annotations import json import urllib.error import urllib.request from dataclasses import dataclass from typing import Any, Mapping, Sequence from .prompts import render_call from .schema import Case, ExpectCall, ExpectNoCall, Protocol @dataclass(frozen=True) class Prompt: case: Case protocol: Protocol messages: tuple[Mapping[str, str], ...] class Runner: name: str = "runner" def complete(self, prompt: Prompt) -> str: # pragma: no cover - interface raise NotImplementedError def complete_many(self, prompts: Sequence[Prompt]) -> list[str]: """Default: sequential. Backends that can batch override this.""" return [self.complete(prompt) for prompt in prompts] @dataclass(frozen=True) class BatchOutput: text: str | None = None error: str = "" def run_batch(runner: Runner, prompts: Sequence[Prompt], batch_size: int) -> list[BatchOutput]: """Run a chunk, degrading to one-by-one if the backend refuses the batch.""" if batch_size > 1: try: return [BatchOutput(text=text) for text in runner.complete_many(prompts)] except Exception: # noqa: BLE001 - a poisoned batch must not lose its neighbours pass outputs: list[BatchOutput] = [] for prompt in prompts: try: outputs.append(BatchOutput(text=runner.complete(prompt))) except Exception as error: # noqa: BLE001 outputs.append(BatchOutput(error=f"runner error: {type(error).__name__}: {error}")) return outputs class OracleRunner(Runner): """Emits exactly what the corpus expects. Used to validate the grader itself.""" name = "oracle" def complete(self, prompt: Prompt) -> str: expect = prompt.case.expect if isinstance(expect, ExpectCall): return render_call(expect.name, expect.args, prompt.protocol) needles: list[str] = list(expect.answer_contains_all) needles.extend(group[0] for group in expect.answer_contains_any if group) if needles: return "Here is the answer: " + ", ".join(needles) + "." return "I can answer that from what I already know." class NullRunner(Runner): """Answers politely and never calls a tool.""" name = "null" def complete(self, prompt: Prompt) -> str: return "I am not sure about that." class FencedRunner(OracleRunner): """Wraps every call in a markdown fence behind a sentence of prose.""" name = "fenced" def complete(self, prompt: Prompt) -> str: raw = super().complete(prompt) if isinstance(prompt.case.expect, ExpectCall): fence = "json" if prompt.protocol == "json" else "text" return f"Sure, calling the tool now.\n\n```{fence}\n{raw}\n```\n" return raw class ThinkingRunner(OracleRunner): """Prefixes every call with a reasoning block, the way a thinking model does.""" name = "thinking" def complete(self, prompt: Prompt) -> str: raw = super().complete(prompt) if isinstance(prompt.case.expect, ExpectCall): return f"\nThe user wants a tool call. Pick {prompt.case.expect.name}.\n\n{raw}" return f"No tool applies here.\n{raw}" class ScriptedRunner(Runner): """Deterministic per-case overrides, for unit tests and demos.""" name = "scripted" def __init__(self, overrides: Mapping[str, str], default: str = ""): self._overrides = dict(overrides) self._default = default def complete(self, prompt: Prompt) -> str: return self._overrides.get(prompt.case.id, self._default) class OpenAICompatibleRunner(Runner): """Any `/chat/completions` endpoint: vLLM, llama.cpp server, Ollama, OpenAI, OpenRouter.""" def __init__( self, model: str, base_url: str = "https://api.openai.com/v1", api_key: str = "", max_tokens: int = 256, temperature: float = 0.0, timeout: float = 120.0, name: str | None = None, ): self.model = model self.base_url = base_url.rstrip("/") self.api_key = api_key self.max_tokens = max_tokens self.temperature = temperature self.timeout = timeout self.name = name or model def complete(self, prompt: Prompt) -> str: body = json.dumps( { "model": self.model, "messages": [dict(message) for message in prompt.messages], "max_tokens": self.max_tokens, "temperature": self.temperature, "stream": False, } ).encode("utf-8") request = urllib.request.Request( f"{self.base_url}/chat/completions", data=body, method="POST", headers={ "Content-Type": "application/json", **({"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}), }, ) try: with urllib.request.urlopen(request, timeout=self.timeout) as response: payload = json.loads(response.read().decode("utf-8")) except urllib.error.HTTPError as error: detail = error.read().decode("utf-8", "replace")[:400] raise RuntimeError(f"HTTP {error.code}: {detail}") from error choices = payload.get("choices") or [] if not choices: return "" message = choices[0].get("message") or {} content = message.get("content") if isinstance(content, list): return "".join(part.get("text", "") for part in content if isinstance(part, Mapping)) return content or message.get("reasoning_content") or "" class TransformersRunner(Runner): """Local HF checkpoint, greedy decoding. Handles three realities of modern checkpoints: vision-capable conditional generation architectures (`AutoModelForImageTextToText`), the `dtype` rename, and chat templates with a reasoning switch that must be turned off for tool calls to be emitted instead of a thinking trace. """ def __init__( self, model_id: str, max_new_tokens: int = 256, dtype: str = "auto", device_map: str = "auto", trust_remote_code: bool = True, revision: str | None = None, system_override: str | None = None, disable_thinking: bool = True, ): import torch self._torch = torch self.name = model_id self.model_id = model_id self.max_new_tokens = max_new_tokens self.system_override = system_override self.disable_thinking = disable_thinking self.tokenizer = _load_processor(model_id, trust_remote_code, revision) if getattr(self.tokenizer, "pad_token", None) is None: self.tokenizer.pad_token = self.tokenizer.eos_token self.model, self.load_info = _load_model(model_id, dtype, device_map, trust_remote_code, revision) self.model.eval() self._eos_ids = _end_of_turn_ids(self.model, self.tokenizer) def _render(self, messages: Sequence[Mapping[str, str]]) -> str: kwargs: dict[str, Any] = {"tokenize": False, "add_generation_prompt": True} if self.disable_thinking: kwargs["enable_thinking"] = False try: return self.tokenizer.apply_chat_template(messages, **kwargs) except TypeError: kwargs.pop("enable_thinking", None) return self.tokenizer.apply_chat_template(messages, **kwargs) def _prepare(self, prompt: Prompt) -> str: messages = [dict(message) for message in prompt.messages] if self.system_override and messages and messages[0]["role"] == "system": messages[0]["content"] = self.system_override return self._render(messages) def _inputs(self, texts: Sequence[str], padding: bool) -> dict[str, Any]: previous_side = getattr(self.tokenizer, "padding_side", "right") if padding: # Decoder-only generation must continue after the padded prefix, so the # padding belongs on the left; the slice below then trims uniformly. self.tokenizer.padding_side = "left" try: try: inputs = self.tokenizer(text=list(texts), return_tensors="pt", padding=padding) except TypeError: inputs = self.tokenizer(list(texts), return_tensors="pt", padding=padding) finally: self.tokenizer.padding_side = previous_side if hasattr(inputs, "to"): inputs = inputs.to(self.model.device) return {key: value for key, value in dict(inputs).items()} def _generate(self, inputs: dict[str, Any]) -> list[str]: input_length = inputs["input_ids"].shape[-1] with self._torch.inference_mode(): generated = self.model.generate( **inputs, max_new_tokens=self.max_new_tokens, do_sample=False, pad_token_id=self.tokenizer.pad_token_id or self.tokenizer.eos_token_id, eos_token_id=self._eos_ids, ) return [self.tokenizer.decode(row[input_length:], skip_special_tokens=True) for row in generated] def complete(self, prompt: Prompt) -> str: return self._generate(self._inputs([self._prepare(prompt)], padding=False))[0] def complete_many(self, prompts: Sequence[Prompt]) -> list[str]: """One padded `generate` call per batch. Memory is not the constraint here — a 0.8B model in bfloat16 leaves several gigabytes free on a 6 GB card — GPU *utilisation* is. Batching turns a decode loop that idles between kernel launches into a saturated one. """ if not prompts: return [] if len(prompts) == 1: return self.complete(prompts[0]) return self._generate(self._inputs([self._prepare(prompt) for prompt in prompts], padding=True)) def _load_processor(model_id: str, trust_remote_code: bool, revision: str | None): from transformers import AutoProcessor, AutoTokenizer errors: list[str] = [] for loader in (AutoTokenizer, AutoProcessor): try: return loader.from_pretrained(model_id, trust_remote_code=trust_remote_code, revision=revision) except Exception as error: # noqa: BLE001 errors.append(f"{loader.__name__}: {type(error).__name__}: {error}") raise RuntimeError("could not load a tokenizer/processor for " + model_id + "\n" + "\n".join(errors)) LOAD_CANDIDATES: tuple[str, ...] = ("AutoModelForCausalLM", "AutoModelForImageTextToText", "AutoModel") _IGNORABLE_MISSING: tuple[str, ...] = ( "inv_freq", "rotary", "causal_mask", "position_ids", "mtp.", "logit_scale", "temperature", ) def _core_missing(missing: Sequence[str]) -> list[str]: return [key for key in missing if not any(token in key for token in _IGNORABLE_MISSING)] def _end_of_turn_ids(model: Any, tokenizer: Any) -> list[int]: """Every token that legitimately ends an assistant turn. Chat checkpoints ship two of them: `<|im_end|>` closes the message, while the model configuration frequently keeps a pre-training `<|endoftext|>` as the single `eos_token_id`. Stopping on only one of the two makes an otherwise correct answer run to `max_new_tokens` and emit the same call over and over, which the grader then scores as several calls in one turn. The union is what the template actually means, so that is what decoding stops on. """ ids: set[int] = set() for source in ( getattr(tokenizer, "eos_token_id", None), getattr(getattr(model, "generation_config", None), "eos_token_id", None), getattr(getattr(model, "config", None), "eos_token_id", None), ): if isinstance(source, int): ids.add(source) elif isinstance(source, (list, tuple)): ids.update(int(value) for value in source if isinstance(value, int)) return sorted(ids) def _load_model( model_id: str, dtype: str, device_map: str, trust_remote_code: bool, revision: str | None, ): """Load the first architecture whose weights actually match the checkpoint. `from_pretrained` emits a warning, not an error, when a class expects keys the checkpoint does not contain — the result is a randomly initialised model that still produces fluent-looking text. Nova ships text-only keys (`model.layers.*`) and also carries a vision tower, so the vision wrapper loads "successfully" and generates noise. Every candidate is therefore verified against its loading report before it is accepted, and the caller is told how it was loaded. """ import transformers errors: list[str] = [] for name in LOAD_CANDIDATES: loader = getattr(transformers, name, None) if loader is None: continue for dtype_kwarg in ("dtype", "torch_dtype"): try: model, info = loader.from_pretrained( model_id, trust_remote_code=trust_remote_code, revision=revision, device_map=device_map, output_loading_info=True, **{dtype_kwarg: dtype}, ) except Exception as error: # noqa: BLE001 errors.append(f"{name}.{dtype_kwarg}: {type(error).__name__}: {error}") continue missing = _core_missing(list(info.get("missing_keys") or [])) if missing: errors.append( f"{name}: {len(missing)} checkpoint weights missing, e.g. {missing[0]} — refusing a random model" ) del model continue unexpected = len(list(info.get("unexpected_keys") or [])) note = f"{name} ({dtype_kwarg}={dtype})" + (f", {unexpected} extra keys ignored" if unexpected else "") return model, note raise RuntimeError("could not load " + model_id + ":\n" + "\n".join(errors)) class ScriptedFileRunner(ScriptedRunner): """Loads `{"case_id": "output"}` from a JSON file — hand-graded runs, ablations.""" @staticmethod def from_file(path: str, default: str = "") -> "ScriptedFileRunner": with open(path, encoding="utf-8") as handle: payload: dict[str, Any] = json.load(handle) return ScriptedFileRunner({str(key): str(value) for key, value in payload.items()}, default=default) def build_runner(backend: str, **kwargs: Any) -> Runner: if backend == "oracle": return OracleRunner() if backend == "null": return NullRunner() if backend == "fenced": return FencedRunner() if backend == "thinking": return ThinkingRunner() if backend in ("transformers", "local"): return TransformersRunner( model_id=kwargs["model"], max_new_tokens=kwargs.get("max_new_tokens", 256), dtype=kwargs.get("dtype", "auto"), revision=kwargs.get("revision"), disable_thinking=kwargs.get("disable_thinking", True), ) if backend in ("openai", "vllm", "ollama", "llamacpp"): return OpenAICompatibleRunner( model=kwargs["model"], base_url=kwargs.get("base_url", "http://localhost:8000/v1"), api_key=kwargs.get("api_key", ""), max_tokens=kwargs.get("max_new_tokens", 256), ) if backend == "scripted": return ScriptedFileRunner.from_file(kwargs["scripted_file"]) raise ValueError(f"unknown backend: {backend}") def rendered_calls(expect: Any, protocol: Protocol) -> Sequence[str]: if isinstance(expect, ExpectCall): return (render_call(expect.name, expect.args, protocol),) if isinstance(expect, ExpectNoCall): return () return ()