"""One evaluation: the teacher answers every drawn prompt, the king and the challenger read the same tokens, and both are measured against the teacher's next-token distribution on the answer tokens; then the win rule.""" from __future__ import annotations import contextlib import json import math import queue import shutil import threading import time from collections.abc import Callable, Generator, Sequence from concurrent.futures import Future, ThreadPoolExecutor from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any from loguru import logger as log from common.config import settings from eval_service import config, servers, timing from eval_service.dataset import Sample if TYPE_CHECKING: from eval_service.metrics import Sums @dataclass(frozen=True) class Score: """How far a model is from the teacher: the mean KL(teacher ‖ model) of the next-token distributions over the answer tokens of each domain, the domains weighed by their shares of the samples (by_domain).""" kl: float @dataclass(frozen=True) class Duel: challenger: Score king: Score samples: list[dict[str, Any]] = field(default_factory=list) @property def won(self) -> bool: return won(self.challenger, self.king) def needed(king: Score) -> Score: """How much closer on KL a challenger must be than this king.""" return Score(kl=config.KL_MARGIN * king.kl) def won(challenger: Score, king: Score) -> bool: """The challenger must be closer to the teacher on KL by the margin. A model whose score is not finite diverged (inf, NaN, or it left the teacher's answer): a diverged challenger loses, and a diverged king loses to any challenger that did not. NaN compares False, so without this a king that diverges on some inputs could never be beaten.""" if not _finite(challenger): return False if not _finite(king): return True return king.kl - challenger.kl >= needed(king).kl def _finite(s: Score) -> bool: return math.isfinite(s.kl) DIVERGED = Score(kl=math.inf) class LeftAnswer(ValueError): """A model read the teacher's answer and did not reproduce it: the model's own doing.""" def __init__(self, role: str, message: str) -> None: self.role = role super().__init__(message) Scorer = Callable[..., Duel] # (teacher, challenger, king, samples, *, on_progress=None, ...) Progress = Callable[[int], None] Result = tuple[dict[str, "Sums"], dict[str, Any]] # sample index -> the teacher's (answer, states file), answered ahead by a Prefetch Prefetched = dict[int, Future[tuple[list[int], str]]] def duel( teacher_dir: Path, challenger_dir: Path, king_dir: Path, samples: Sequence[Sample], *, on_progress: Progress | None = None, prefetched: Prefetched | None = None, ) -> Duel: """`prefetched` answers (a Prefetch's) are taken instead of asking the teacher.""" models = {"teacher": teacher_dir, "king": king_dir, "challenger": challenger_dir} evaluation = _Evaluation(models, len(samples), on_progress, prefetched) results = evaluation.run(samples) log.info( "eval timing, {} samples scored in {:.0f}s: {}", len(results), timing.stages.elapsed(), timing.stages.line(), ) log.info("eval slowest samples: {}", timing.stages.slowest(5)) return Duel( challenger=evaluation.score(results, "challenger"), king=evaluation.score(results, "king"), samples=[record for _, record in results], ) class _Evaluation: """The servers, tokenizer and comparison GPUs of one duel, and the steps each sample goes through: the teacher's answer, the forced reads of it, and the comparison.""" # metrics needs torch, which only the GPU box installs, so it is imported where it is used def __init__( self, models: dict[str, Path], total: int, on_progress: Progress | None = None, prefetched: Prefetched | None = None, ) -> None: from eval_service import metrics started = time.monotonic() self.groups = servers.serve(models) serving = time.monotonic() self.tokenizer = load_tokenizer(models["teacher"]) self.eos = _eos(models["teacher"]) self.state_bytes = state_bytes_per_token(models["teacher"]) # both readers' GPUs: a gguf reader leaves most of its GPU free readers = (*settings().gpus("king"), *settings().gpus("challenger")) devices = [f"cuda:{gpu}" for gpu in readers] self.heads = metrics.heads(models, devices) log.info( "eval setup: servers ready in {:.0f}s, tokenizer and final heads loaded in {:.0f}s", serving - started, time.monotonic() - serving, ) self.free_devices: queue.Queue[str] = queue.Queue() for dev in devices: self.free_devices.put(dev) # Each thread that touches a GPU gets its own cuBLAS handle and workspace there; one # thread per GPU keeps that to one. self.compare_on = {dev: ThreadPoolExecutor(1) for dev in devices} self.preemptions_at_start = self._preemptions() self.total, self.done, self.lock = total, 0, threading.Lock() self.on_progress = on_progress self.prefetched = prefetched if prefetched is not None else {} self.diverged: set[str] = set() def run(self, samples: Sequence[Sample]) -> list[Result]: """The results of the samples that went through. A sample that fails is logged and left out; more than MAX_FAILED_SAMPLES of them, or none scored at all, ends the eval. A king or challenger that left the teacher's answer is marked diverged (self.diverged): the sample is left out for every role, so a model could otherwise shed the prompts it does worst on, and the king's with them.""" timing.stages.reset() if self.prefetched: # the prefetch was this eval's: its requests are the running eval's from here self.groups["teacher"].promote() pool = ThreadPoolExecutor(config.WORKERS) results: list[Result] = [] failed = 0 stop = threading.Event() try: threading.Thread(target=_report, args=(stop, len(samples)), daemon=True).start() # longest answer budgets first, longest prompts within: a long answer admitted late # runs alone at the end; each keeps its index (its seed), and results stay in order by_size = sorted(range(len(samples)), key=lambda i: _order(samples[i])) started = {i: pool.submit(self._sample, i, samples[i]) for i in by_size} futures = [started[i] for i in range(len(samples))] for sample, future in zip(samples, futures, strict=True): try: results.append(future.result()) except servers.ServerExited: raise # a dead model server ends the eval; main.py blames its GPU's model except Exception as exc: failed += 1 if isinstance(exc, LeftAnswer) and exc.role in ("king", "challenger"): self.diverged.add(exc.role) log.warning("sample {} failed ({} so far): {}", sample.id, failed, exc) if failed > config.MAX_FAILED_SAMPLES: raise RuntimeError(f"{failed} samples failed, the last: {exc}") from exc finally: stop.set() pool.shutdown(cancel_futures=True) for executor in self.compare_on.values(): executor.shutdown() if self._preemptions() != self.preemptions_at_start: raise RuntimeError( "vLLM preempted requests: their answer rows came from a prefill pass" ) if not results: raise RuntimeError("no sample was scored") return results def score(self, results: list[Result], role: str) -> Score: """The role's score over the samples it read; DIVERGED for a role that left the teacher's answer on any sample.""" if role in self.diverged: return DIVERGED return by_domain( [(record["domain"], by_role[role]) for by_role, record in results if role in by_role] ) def _teacher_room(self, prompt: list[int], sample: Sample) -> int: """Booked before the teacher answers: its answer rows at the full budget, and the readers' prompt rows, which their files hold until they are cut to the answer rows.""" teacher = state_bytes(prompt, sample, self.state_bytes, answer_only=True) return teacher + 2 * len(prompt) * self.state_bytes def _reader_room(self, answer: list[int]) -> int: """The readers' answer rows, booked once the answer is known.""" return 2 * len(answer) * self.state_bytes def _sample(self, i: int, sample: Sample) -> Result: paths: dict[str, str] = {} # role -> the hidden-state file its server wrote stack = contextlib.ExitStack() # the sample's room in /dev/shm, given back last started = time.monotonic() try: prompt = _render(self.tokenizer, sample.messages, sample.tools) ahead = self.prefetched.pop(i, None) if ahead is not None: try: with timing.stages.timed("prefetched"): answer, paths["teacher"] = ahead.result() except Exception as exc: log.warning("the answer taken ahead for {} failed: {}", sample.id, exc) ahead = None if ahead is None: with timing.stages.timed("shm wait"): stack.enter_context(ROOM.reserve(self._teacher_room(prompt, sample))) with timing.stages.timed("teacher"): answer, paths["teacher"] = generate( self.groups["teacher"], prompt, i, sample.id, answer_budget(sample), booked_answer(sample), ) stack.enter_context(ROOM.reserve(self._reader_room(answer), wait=False)) with timing.stages.timed("read"): self._read_along(i, sample, prompt, answer, paths) with timing.stages.timed("compare"): sums = self._compare(prompt, answer, paths) timing.stages.sample(sample.id, time.monotonic() - started, len(prompt), len(answer)) return sums, self._record(sample, prompt, answer, sums) finally: self._count() # a failed sample counts too, so progress reaches the total for path in paths.values(): servers.discard(path) stack.close() def _read_along( self, i: int, sample: Sample, prompt: list[int], answer: list[int], paths: dict[str, str] ) -> None: """The king and the challenger read the answer, forced; each must reproduce it token for token.""" readers = {"king": self.groups["king"], "challenger": self.groups["challenger"]} with ThreadPoolExecutor(len(readers)) as pool: futures = { role: pool.submit(group.complete, prompt, len(answer), i, prompt + answer) for role, group in readers.items() } reads, errors = {}, [] # every finished request's file must be discarded, even when another one failed for role, future in futures.items(): try: reads[role], path = future.result() paths[role] = servers.hold(path) except Exception as exc: errors.append(exc) if errors: raise errors[0] for role, read in reads.items(): if read != answer: raise LeftAnswer(role, f"{sample.id}: the {role} left the teacher's answer") def _compare( self, prompt: list[int], answer: list[int], paths: dict[str, str] ) -> dict[str, Sums]: from eval_service import metrics with timing.stages.timed("compare wait"): dev = self.free_devices.get() try: # the last answer token is never fed back in, so no server wrote a row for it with timing.stages.timed("compare load"): states = { role: metrics.load_states(p, prompt + answer[:-1], len(prompt) - 1) for role, p in paths.items() } with timing.stages.timed("compare math"): return ( self.compare_on[dev] .submit(metrics.compare, states, self.heads[dev], answer, dev) .result() ) finally: self.free_devices.put(dev) def _record( self, sample: Sample, prompt: list[int], answer: list[int], sums: dict[str, Sums] ) -> dict[str, Any]: return { "sample_id": sample.id, "domain": sample.domain, "prompt_tokens": len(prompt), "answer_tokens": len(answer), "ended_with_eos": answer[-1] in self.eos, "runs": {role: s.summary() for role, s in sums.items()}, } def _count(self) -> None: with self.lock: self.done += 1 done = self.done if done % 100 == 0: log.info("eval progress: {} of {} samples", done, self.total) chunks = config.PROGRESS_CHUNKS if self.on_progress and done * chunks // self.total > (done - 1) * chunks // self.total: try: self.on_progress(done) except Exception: log.exception("eval progress report failed") def _preemptions(self) -> float: return sum(group.preemptions() for group in self.groups.values()) def by_domain(sums: Sequence[tuple[str, Any]]) -> Score: """Within a domain every answer token weighs the same: the domain's KL is its total KL over its total answer tokens, so a long answer counts for its length and its well-predicted tail does not dilute the tokens that are hard. The domains then weigh by their shares of the samples.""" totals: dict[str, list[float]] = {} for domain, s in sums: t = totals.setdefault(domain, [0.0, 0.0, 0.0]) t[0] += s.kl t[1] += s.predictions t[2] += 1 n = sum(t[2] for t in totals.values()) return Score(kl=sum(t[2] / n * t[0] / max(t[1], 1) for t in totals.values())) def answer_budget(sample: Sample) -> int: return config.DOMAIN_MAX_TOKENS.get(sample.domain, config.MAX_TOKENS) def booked_answer(sample: Sample) -> int: """The answer tokens a teacher request books in its server's cache.""" expected = config.EXPECTED_ANSWER_TOKENS.get(sample.domain, config.MAX_TOKENS) return min(answer_budget(sample), math.ceil(expected * config.BOOKED_MARGIN)) def generate( teacher: servers.Groups, prompt: list[int], seed: int, label: str, budget: int, booked: int, prefetch: bool = False, ) -> tuple[list[int], str]: """The teacher's answer to `prompt`, at most `budget` tokens, and the states file it wrote; `booked` answer tokens are booked in the server's cache.""" room = config.MAX_MODEL_LEN - len(prompt) if room < 1: raise ValueError(f"{label}: a {len(prompt)}-token prompt leaves no room") answer, path = teacher.complete( prompt, min(budget, room), seed, book=len(prompt) + min(booked, room), prefetch=prefetch ) return answer, servers.hold(path) class Prefetch: """The teacher's answers to the samples of an eval that has not started, in the duel's order, each generated once a teacher server has nothing of the running eval left to generate. `result` is the `prefetched` of that eval's duel: the answers as futures, the duel waits for each as it needs it.""" def __init__(self, teacher_dir: Path, samples: Sequence[Sample]) -> None: self.teacher = servers.serve({"teacher": teacher_dir})["teacher"] # the running one self.tokenizer, self.samples = load_tokenizer(teacher_dir), samples self.state_bytes = state_bytes_per_token(teacher_dir) self.pool = ThreadPoolExecutor(config.WORKERS) ahead = sorted(range(len(samples)), key=lambda i: _order(samples[i])) self.futures = {i: self.pool.submit(self._one, i) for i in ahead} def _one(self, i: int) -> tuple[list[int], str]: sample = self.samples[i] prompt = _render(self.tokenizer, sample.messages, sample.tools) remote = isinstance(self.teacher, servers.RemoteGroup) size = state_bytes(prompt, sample, self.state_bytes, answer_only=remote) # held until the file is written; from then on /dev/shm's usage counts it with ROOM.reserve(size): return generate( self.teacher, prompt, i, sample.id, answer_budget(sample), booked_answer(sample), prefetch=True, ) def result(self) -> Prefetched: self.pool.shutdown(wait=False) return dict(self.futures) def load_tokenizer(model_dir: Path) -> Any: from transformers import AutoTokenizer # the GPU box's, like torch return AutoTokenizer.from_pretrained(model_dir) def _render( tokenizer: Any, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None ) -> list[int]: """Prompt token ids with the teacher's chat template and its default thinking mode.""" text = tokenizer.apply_chat_template( messages, tools=tools, tokenize=False, add_generation_prompt=True ) return tokenizer.encode(text, add_special_tokens=False) def fits(tokenizer: Any) -> Callable[[Sample], bool]: """Whether a sample's rendered prompt leaves its domain's whole answer budget, for the draw. A byte-level token covers at least one UTF-8 byte, so a prompt that short in bytes fits without rendering.""" frame = len(_render(tokenizer, [{"role": "user", "content": ""}])) def check(sample: Sample) -> bool: limit = config.MAX_MODEL_LEN - answer_budget(sample) size = sum(len(m["content"].encode()) for m in sample.messages) if size > limit * config.MAX_BYTES_PER_TOKEN: return False # tool schemas and tool calls render outside the contents, so an agent sample is rendered return (not sample.tools and size + frame * len(sample.messages) <= limit) or ( len(_render(tokenizer, sample.messages, sample.tools)) <= limit ) return check def _eos(model_dir: Path) -> set[int]: eos = json.loads((model_dir / "generation_config.json").read_text())["eos_token_id"] return set(eos if isinstance(eos, list) else [eos]) def _size(sample: Sample) -> int: return sum(len(m["content"]) for m in sample.messages) def _order(sample: Sample) -> tuple[int, int]: return (-answer_budget(sample), -_size(sample)) def _report(stop: threading.Event, total: int) -> None: """Every TIMING_REPORT_S until `stop`: the running eval's per-stage timings.""" while not stop.wait(config.TIMING_REPORT_S): try: log.info( "eval timing, {} of {} samples done: {}", timing.stages.done(), total, timing.stages.line(), ) except Exception: log.exception("eval timing report failed") def state_bytes( prompt: list[int], sample: Sample, per_token: int, *, answer_only: bool = False ) -> int: """The size of a states file for `prompt` at its domain's full answer budget; every row of the request, or from the last prompt row only (llama-states, and a remote teacher).""" rows = min(len(prompt) + answer_budget(sample), config.MAX_MODEL_LEN) if answer_only: rows -= len(prompt) - 1 return rows * per_token def state_bytes_per_token(model_dir: Path) -> int: """The size of one token's row in a states file: LAYERS hidden states in bf16.""" cfg = json.loads((model_dir / "config.json").read_text()) return len(config.LAYERS) * cfg.get("text_config", cfg)["hidden_size"] * 2 class _Room: """/dev/shm space promised to the state files of requests in flight. A request starts only when what is already written plus every promise, its own included, fits under SHM_SHARE: the files are written only when a request ends, so the usage alone lets too many start and the servers' writes then fail with ENOSPC. A promise is kept until its files are discarded, so a written file counts twice for a while: the room errs on the safe side.""" def __init__(self) -> None: self.cond, self.promised = threading.Condition(), 0 @contextlib.contextmanager def reserve(self, nbytes: int, wait: bool = True) -> Generator[None]: with self.cond: # with nothing promised no request of ours is in flight to free room by waiting while wait and self.promised and not self._fits(nbytes): self.cond.wait(5) self.promised += nbytes try: yield finally: with self.cond: self.promised -= nbytes self.cond.notify_all() def _fits(self, nbytes: int) -> bool: shm = shutil.disk_usage("/dev/shm") return shm.used + self.promised + nbytes <= config.SHM_SHARE * shm.total ROOM = _Room() # one for the running duel and the next eval's prefetch both