# SPDX-License-Identifier: EUPL-1.2 """Lighteval custom model backend — routes inference through an Ollama (or any OpenAI-compatible) server hosting GGUF models. Pairs with mlx_lm_wrapper.py in the same directory. eval.py picks which wrapper to point lighteval at based on the target's `type` field (`mlx` → mlx_lm_wrapper.py, `gguf` → this file). Usage (CLI, via eval.py): eval.py automatically points lighteval at this file when the target type is `gguf`. Usage (lighteval direct): lighteval custom \\ "hf.co/lthn/lemer:Q4_K_M" \\ /path/to/gguf_wrapper.py \\ "mmlu_pro" \\ --max-samples 10 Endpoint configuration (env vars, both optional): LEM_OLLAMA_URL default: http://localhost:11434/v1 LEM_OLLAMA_API_KEY default: "ollama" (Ollama ignores the value) config.model_name resolution: Passed straight through as the `model` parameter to the OpenAI chat completions endpoint. Use whatever string Ollama expects — for example: hf.co/lthn/lemer:Q4_K_M hf.co/lthn/lemmy:Q4_K_M gemma3:27b Ollama will lazy-pull models it doesn't have yet on first request. The wrapper sends a 1-token probe during __init__ to surface pull failures early rather than mid-eval. Sampling policy (identical to mlx_lm_wrapper.py): Google-calibrated Gemma 4: temp=1.0, top_p=0.95, top_k=64. enable_thinking is signalled via `think: true` in the OpenAI extra_body — Ollama >= 0.3 with a thinking-capable model will respect this; older versions ignore it, so our fork's LEK'd models still want the chat template to set the think-mode anchor server-side (which Ollama modelfiles can do). """ import os import sys from typing import List from lighteval.models.abstract_model import LightevalModel from lighteval.models.model_output import ModelResponse from lighteval.tasks.requests import Doc from lighteval.utils.cache_management import SampleCache DEFAULT_TEMPERATURE = 1.0 DEFAULT_TOP_P = 0.95 DEFAULT_TOP_K = 64 DEFAULT_MAX_TOKENS = 4096 # CoT can run long with enable_thinking=True class GGUFOllamaModel(LightevalModel): """Lighteval custom backend that runs inference via an OpenAI-compatible server (Ollama by default) hosting GGUF quants. The `config.model_name` field is used as the `model` parameter of the chat completions request — so it must be a string Ollama recognises, typically `hf.co//:` or a built-in `family:tag`. """ def __init__(self, config) -> None: self.config = config self.model_name = config.model_name self.base_url = os.environ.get("LEM_OLLAMA_URL", "http://localhost:11434/v1") self.api_key = os.environ.get("LEM_OLLAMA_API_KEY", "ollama") try: from openai import OpenAI except ImportError as e: raise ImportError( "gguf_wrapper requires the `openai` package. Add it to PEP 723 " "dependencies in eval.py or install with `uv pip install openai`." ) from e print(f"[gguf_wrapper] Ollama endpoint: {self.base_url}") print(f"[gguf_wrapper] model: {self.model_name}") self._client = OpenAI(base_url=self.base_url, api_key=self.api_key) # Force-probe: 1-token request to catch pull failures early rather # than mid-eval after lighteval has already queued up work. self._probe() self._cache = SampleCache(config) def _probe(self) -> None: try: _ = self._client.chat.completions.create( model=self.model_name, messages=[{"role": "user", "content": "ping"}], max_tokens=1, temperature=0.0, ) print(f"[gguf_wrapper] probe OK") except Exception as e: print(f"[gguf_wrapper] WARNING: probe failed ({type(e).__name__}: {e})", file=sys.stderr) print(f"[gguf_wrapper] continuing anyway — Ollama may lazy-pull on first real request", file=sys.stderr) @property def tokenizer(self): # OpenAI-compatible endpoints don't expose a tokenizer. Lighteval's # generative path doesn't call this when the metric is extractive # regex-based (our case), so it's safe to return None and let # something downstream complain if it actually needs one. return None def tok_encode(self, text: str): # Not available via the OpenAI API. Return an empty list so # lighteval's length-accounting code doesn't crash. return [] @property def add_special_tokens(self) -> bool: return False @property def max_length(self) -> int: # Gemma 4 E2B/E4B: 128K; 26B MoE / 31B: 256K. Generous default. return 131072 def greedy_until(self, requests: List[Doc]) -> List[ModelResponse]: """Generate text responses via Ollama chat completions. Despite the name, this is sampling (not greedy) — matches mlx_lm_wrapper. Each request can ask for num_samples > 1; we send one request per sample so the server's PRNG produces independent outputs. """ results: List[ModelResponse] = [] for r in requests: max_tokens = r.generation_size or DEFAULT_MAX_TOKENS n_samples = getattr(r, "num_samples", 1) or 1 messages = [{"role": "user", "content": r.query}] samples: List[str] = [] for i in range(n_samples): try: resp = self._client.chat.completions.create( model=self.model_name, messages=messages, max_tokens=max_tokens, temperature=DEFAULT_TEMPERATURE, top_p=DEFAULT_TOP_P, # top_k and think flags aren't in OpenAI's standard # chat schema — pass through extra_body so Ollama # can consume them. Ollama >= 0.3 respects `think` # for thinking-capable models; earlier versions # ignore unknown extras silently. extra_body={ "top_k": DEFAULT_TOP_K, "think": True, }, ) text = resp.choices[0].message.content or "" except Exception as e: print(f"[gguf_wrapper] sample {i + 1}/{n_samples} failed: " f"{type(e).__name__}: {e}", file=sys.stderr) text = "" samples.append(text) results.append(ModelResponse( text=samples, input_tokens=[], output_tokens=[[] for _ in samples], reasonings=[None for _ in samples], logprobs=[], argmax_logits_eq_gold=[], )) return results def loglikelihood(self, requests): raise NotImplementedError( "gguf_wrapper does not implement loglikelihood. " "Ollama's OpenAI endpoint doesn't expose per-token logprobs " "suitable for multiple-choice loglikelihood scoring. Use a " "generative task variant with num_samples + maj_at_k." ) def loglikelihood_rolling(self, requests): raise NotImplementedError( "gguf_wrapper does not implement loglikelihood_rolling. " "Perplexity-based metrics are not in our eval set." )