@@ -0,0 +1,160 @@ |
| 1 | +"""In-memory backend for unit tests. |
| 2 | + |
| 3 | +Deterministic, torchless, and trivially fast. Tests pass canned responses |
| 4 | +and canned score tables keyed by ``(mode, prompt, completion)``. The same |
| 5 | +backend instance serves as both ``as_base`` and ``as_finetuned`` — it |
| 6 | +switches an internal mode flag. |
| 7 | + |
| 8 | +Use it to drive every probe's unit test without loading a real model. |
| 9 | +For integration tests against a real PEFT adapter, see |
| 10 | +:class:`~dlm_sway.backends.hf.HuggingFaceDifferentialBackend`. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import math |
| 16 | +from collections.abc import Iterator |
| 17 | +from contextlib import contextmanager |
| 18 | +from dataclasses import dataclass, field |
| 19 | +from typing import Literal |
| 20 | + |
| 21 | +import numpy as np |
| 22 | + |
| 23 | +from dlm_sway.core.scoring import RollingLogprob, TokenDist |
| 24 | + |
| 25 | +Mode = Literal["base", "ft"] |
| 26 | + |
| 27 | + |
| 28 | +@dataclass(slots=True) |
| 29 | +class DummyResponses: |
| 30 | + """Canned data for one mode (base or ft). |
| 31 | + |
| 32 | + Callers populate one of these per mode and hand both to |
| 33 | + :class:`DummyDifferentialBackend`. |
| 34 | + """ |
| 35 | + |
| 36 | + generations: dict[str, str] = field(default_factory=dict) |
| 37 | + """Prompt → canned completion. Lookup is exact-match.""" |
| 38 | + logprobs: dict[tuple[str, str], float] = field(default_factory=dict) |
| 39 | + """``(prompt, completion) → sum logprob``. Default ``-10.0`` if missing.""" |
| 40 | + rolling: dict[str, RollingLogprob] = field(default_factory=dict) |
| 41 | + """Text → canned :class:`RollingLogprob`.""" |
| 42 | + token_dists: dict[str, TokenDist] = field(default_factory=dict) |
| 43 | + """Prompt → canned :class:`TokenDist`.""" |
| 44 | + |
| 45 | + |
| 46 | +class _DummyView: |
| 47 | + """The per-mode view yielded by ``as_base`` / ``as_finetuned``. |
| 48 | + |
| 49 | + Implements :class:`~dlm_sway.core.model.Model` *and* |
| 50 | + :class:`~dlm_sway.core.scoring.ScoringBackend` — i.e. the |
| 51 | + ``ScoringModel`` intersection. |
| 52 | + """ |
| 53 | + |
| 54 | + def __init__(self, mode: Mode, responses: DummyResponses) -> None: |
| 55 | + self.id = mode |
| 56 | + self._mode: Mode = mode |
| 57 | + self._r = responses |
| 58 | + |
| 59 | + # -- Model --------------------------------------------------------- |
| 60 | + def generate( |
| 61 | + self, |
| 62 | + prompt: str, |
| 63 | + *, |
| 64 | + max_new_tokens: int, |
| 65 | + temperature: float = 0.0, |
| 66 | + top_p: float = 1.0, |
| 67 | + seed: int = 0, |
| 68 | + ) -> str: |
| 69 | + del max_new_tokens, temperature, top_p, seed # canned; decoding is trivial. |
| 70 | + try: |
| 71 | + return self._r.generations[prompt] |
| 72 | + except KeyError as exc: |
| 73 | + raise KeyError( |
| 74 | + f"dummy backend ({self._mode}): no canned generation for prompt {prompt!r}" |
| 75 | + ) from exc |
| 76 | + |
| 77 | + def close(self) -> None: |
| 78 | + return None |
| 79 | + |
| 80 | + # -- ScoringBackend ------------------------------------------------ |
| 81 | + def logprob_of(self, prompt: str, completion: str) -> float: |
| 82 | + return self._r.logprobs.get((prompt, completion), -10.0) |
| 83 | + |
| 84 | + def rolling_logprob(self, text: str) -> RollingLogprob: |
| 85 | + if text in self._r.rolling: |
| 86 | + return self._r.rolling[text] |
| 87 | + # Synthesize a plausible rolling logprob so probes that just |
| 88 | + # want a non-trivial value work without per-text configuration. |
| 89 | + tokens = text.split() |
| 90 | + n = max(len(tokens), 1) |
| 91 | + per_tok = -2.0 if self._mode == "base" else -1.5 |
| 92 | + return RollingLogprob( |
| 93 | + token_ids=np.arange(n, dtype=np.int64), |
| 94 | + logprobs=np.full(max(n - 1, 0), per_tok, dtype=np.float32), |
| 95 | + num_tokens=n, |
| 96 | + total_logprob=per_tok * max(n - 1, 0), |
| 97 | + ) |
| 98 | + |
| 99 | + def next_token_dist(self, prompt: str, *, top_k: int = 256) -> TokenDist: |
| 100 | + del top_k |
| 101 | + if prompt in self._r.token_dists: |
| 102 | + return self._r.token_dists[prompt] |
| 103 | + # Synthesize a sharp base / broad ft distribution so divergence |
| 104 | + # probes see a non-zero signal without hand-rolled data. |
| 105 | + vocab = 1000 |
| 106 | + k = 8 |
| 107 | + if self._mode == "base": |
| 108 | + lp = np.array([-0.1] + [-5.0] * (k - 1), dtype=np.float32) |
| 109 | + else: |
| 110 | + # More uniform mass across the top-k tokens. |
| 111 | + lp = np.full(k, -math.log(k), dtype=np.float32) |
| 112 | + return TokenDist( |
| 113 | + token_ids=np.arange(k, dtype=np.int64), |
| 114 | + logprobs=lp, |
| 115 | + vocab_size=vocab, |
| 116 | + tail_logprob=math.log1p(-float(np.exp(lp).sum())) if np.exp(lp).sum() < 1 else 0.0, |
| 117 | + ) |
| 118 | + |
| 119 | + |
| 120 | +class DummyDifferentialBackend: |
| 121 | + """Dummy implementation of |
| 122 | + :class:`~dlm_sway.core.scoring.DifferentialBackend`. |
| 123 | + |
| 124 | + Construction takes one :class:`DummyResponses` per mode. The two |
| 125 | + modes are mutually exclusive — the backend enforces that callers |
| 126 | + exit one view before entering the other, catching bugs in probes |
| 127 | + that hold a stale view across a toggle. |
| 128 | + """ |
| 129 | + |
| 130 | + def __init__(self, *, base: DummyResponses, ft: DummyResponses) -> None: |
| 131 | + self._base = _DummyView("base", base) |
| 132 | + self._ft = _DummyView("ft", ft) |
| 133 | + self._active: Mode | None = None |
| 134 | + |
| 135 | + @contextmanager |
| 136 | + def as_base(self) -> Iterator[_DummyView]: |
| 137 | + self._enter("base") |
| 138 | + try: |
| 139 | + yield self._base |
| 140 | + finally: |
| 141 | + self._exit() |
| 142 | + |
| 143 | + @contextmanager |
| 144 | + def as_finetuned(self) -> Iterator[_DummyView]: |
| 145 | + self._enter("ft") |
| 146 | + try: |
| 147 | + yield self._ft |
| 148 | + finally: |
| 149 | + self._exit() |
| 150 | + |
| 151 | + def _enter(self, mode: Mode) -> None: |
| 152 | + if self._active is not None: |
| 153 | + raise RuntimeError( |
| 154 | + f"DifferentialBackend view already active ({self._active!r}); " |
| 155 | + f"exit the current view before entering {mode!r}." |
| 156 | + ) |
| 157 | + self._active = mode |
| 158 | + |
| 159 | + def _exit(self) -> None: |
| 160 | + self._active = None |