Verdin-4B / verdin /engine.py
victorbennett's picture
Verdin-4B weights, Verdin engine and model card
f35e9c1 verified
Raw History Blame Contribute Delete
13.3 kB
"""Backend-independent execution plan: requests -> sweeps -> flat token layouts (plain Python, no torch).
Every backend (torch, MLX) runs the same plans; it only implements `BaseEngine.execute(layout)` (one pass over
the layers for one Layout, returning the readout logits) and a few hooks. Shared here:
- the prefix state of a request (per-layer tensors live in it, whatever the backend's tensor type),
- the prefix cache (LRU across requests) and de-duplication of identical states inside a batch,
- sweep planning: prefill segments (long states split into prefill_chunk pieces, one piece per state per sweep)
and branch rows packed into passes of at most max_tokens tokens / max_rows rows,
- the flat layout of a sweep: token ids and positions, varlen boundaries, the causal-conv gather indices (each row
sees its request's last 3 pre-conv state tokens), readout indices,
- state lifetime (freed after its last sweep unless the cache keeps it) and the out-of-memory policy (retry one by
one; refuse only a request that does not fit alone).
"""
from __future__ import annotations
import hashlib
from array import array
from collections import OrderedDict
from dataclasses import dataclass, field
from .render import Encoded, Unsupported
class PrefixState:
"""Everything the branches of one state need, per layer index: attention K/V, DeltaNet recurrent state, conv tail
(backend tensors). `n` = state tokens, `done` = state tokens processed so far."""
def __init__(self, n):
self.n, self.done = n, 0
self.kv, self.rec, self.tail = {}, {}, {}
def clear(self):
self.kv.clear(); self.rec.clear(); self.tail.clear()
class Req:
def __init__(self, enc: Encoded):
self.enc = enc
self.state = None
self.prefill = True # False: the state comes from the cache or from a duplicate earlier in the batch
self.key = None
self.hit = False
self.logits = [None] * len(enc.rows)
self.unknown = [None] * len(enc.rows)
@dataclass
class RunResult:
logits: list | None # per question: raw option logits (temperature 1)
unknown: list | None # per question: raw unknown logit, if the head has one
cache_hit: bool = False
error: Exception | None = None # set (logits None) when this request alone does not fit the device
class Sweep:
def __init__(self):
self.prefill, self.rows, self.tokens, self.n_rows, self.with_pre = [], [], 0, 0, set()
self.index, self.last_use = 0, {}
@dataclass
class Layout:
"""One sweep as flat lists. Token order: every prefill segment, then every branch row (rows of a request
contiguous). `src` indices refer to [carried tails of the involved states (3 per state) ; the sweep's tokens]."""
ids: list = field(default_factory=list)
pos: list = field(default_factory=list)
involved: list = field(default_factory=list) # PrefixStates touched (requests sharing a state share one)
all_fresh: bool = True # every involved state starts in this sweep (zero history)
persist: dict = field(default_factory=dict) # id(state) -> must outlive this sweep (later sweep or cache)
pre_segs: list = field(default_factory=list) # (state, a, b, flat start)
pre_states: list = field(default_factory=list)
pre_fresh: list = field(default_factory=list)
involved_is_pre: bool = False # involved == pre_states (rows can take the prefill's final states)
n_pre: int = 0
cu_pre: list = field(default_factory=lambda: [0])
tail_idx: list = field(default_factory=list) # src indices of each prefill state's new conv tail (3 each)
row_blocks: list = field(default_factory=list) # (state, flat start, [row lengths])
cu_rows: list = field(default_factory=lambda: [0])
row_inv: list = field(default_factory=list) # per row: index into `involved`
conv: list = field(default_factory=list) # conv[j]: src index of tap j for each token (token t - (k-1-j))
ext: list = field(default_factory=list) # [history ; tokens] per segment / row (fused-conv kernels)
ext_out: list = field(default_factory=list) # position in `ext` of each token
dec: list = field(default_factory=list) # flat index of each row's <decide>
opt: list = field(default_factory=list) # flat index of each option's </opt>
opt_row: list = field(default_factory=list) # row of each option
row_refs: list = field(default_factory=list) # (Req, question index, n options) per row
def state_key(ids):
return hashlib.blake2b(array("i", ids).tobytes(), digest_size=16).digest()
def plan_sweeps(reqs, prefill_chunk, max_tokens, max_rows):
sweeps, cur = [], Sweep()
def flush():
nonlocal cur
if cur.prefill or cur.rows:
sweeps.append(cur)
cur = Sweep()
for r in reqs:
if r.prefill:
a, n = r.state.done, r.enc.n_state
while a < n:
b = min(n, a + prefill_chunk)
if id(r.state) in cur.with_pre or (cur.tokens and cur.tokens + (b - a) > max_tokens):
flush()
cur.prefill.append((r, a, b)); cur.tokens += b - a; cur.with_pre.add(id(r.state))
a = b
for qi, row in enumerate(r.enc.rows):
if cur.tokens and (cur.tokens + len(row.ids) > max_tokens or cur.n_rows + 1 > max_rows):
flush()
cur.rows.append((r, qi)); cur.tokens += len(row.ids); cur.n_rows += 1
flush()
last = {}
for k, sw in enumerate(sweeps):
for r, _, _ in sw.prefill: last[id(r.state)] = k
for r, _ in sw.rows: last[id(r.state)] = k
for k, sw in enumerate(sweeps):
sw.index, sw.last_use = k, last
return sweeps
def build_layout(sw: Sweep, kconv: int, keep=frozenset()) -> Layout:
L = Layout()
inv = {}
for r, _, _ in sw.prefill:
if id(r.state) not in inv: inv[id(r.state)] = len(L.involved); L.involved.append(r.state)
for r, _ in sw.rows:
if id(r.state) not in inv: inv[id(r.state)] = len(L.involved); L.involved.append(r.state)
L.all_fresh = all(st.done == 0 for st in L.involved)
L.persist = {id(st): id(st) in keep or sw.last_use[id(st)] > sw.index for st in L.involved}
km1 = kconv - 1
T0 = km1 * len(L.involved)
hist = {j: list(range(km1 * j, km1 * (j + 1))) for j in range(len(L.involved))}
L.conv = [[] for _ in range(kconv)]
def add_segment(H, f0, n):
toks = list(range(T0 + f0, T0 + f0 + n))
e = H[-km1:] + toks
for j in range(kconv):
L.conv[j].extend(e[j: j + n])
base = len(L.ext)
L.ext.extend(e); L.ext_out.extend(range(base + km1, base + km1 + n))
return toks
for r, a, b in sw.prefill:
j = inv[id(r.state)]; f0 = len(L.ids)
L.ids.extend(r.enc.state_ids[a:b]); L.pos.extend(range(a, b))
toks = add_segment(hist[j], f0, b - a)
hist[j] = (hist[j] + toks)[-km1:]
L.pre_segs.append((r.state, a, b, f0)); L.pre_states.append(r.state); L.pre_fresh.append(a == 0)
L.cu_pre.append(L.cu_pre[-1] + b - a)
L.n_pre = len(L.ids)
L.involved_is_pre = len(L.pre_states) == len(L.involved)
L.tail_idx = [x for st in L.pre_states for x in hist[inv[id(st)]]]
for r, qi in sw.rows:
row = r.enc.rows[qi]; f0 = len(L.ids); n = len(row.ids)
if not L.row_blocks or L.row_blocks[-1][0] is not r.state or L.row_blocks[-1][3] is not r:
L.row_blocks.append([r.state, f0, [], r])
L.row_blocks[-1][2].append(n)
L.ids.extend(row.ids); L.pos.extend(range(r.enc.n_state, r.enc.n_state + n))
add_segment(hist[inv[id(r.state)]], f0, n)
L.row_inv.append(inv[id(r.state)]); L.cu_rows.append(L.cu_rows[-1] + n)
L.dec.append(f0 + row.decide)
L.opt.extend(f0 + o for o in row.opts); L.opt_row.extend([len(L.row_refs)] * len(row.opts))
L.row_refs.append((r, qi, len(row.opts)))
L.row_blocks = [(st, f0, lens) for st, f0, lens, _ in L.row_blocks]
return L
class BaseEngine:
"""Batches of Encoded requests -> raw logits. A backend implements execute(layout) -> (option logits flat list,
unknown logits per row or None), plus prefill_chunk / max_tokens / max_rows / kconv / unknown attributes, and may
override oom_errors, on_oom(), sync(), describe_backend(). Single-threaded: the server's batcher thread owns it."""
oom_errors: tuple = ()
def __init__(self, prefix_cache=4, prefix_cache_min_tokens=384, prefix_cache_max_tokens=262144):
self.cache = OrderedDict()
self.cache_tokens = 0
self.hits = self.misses = 0
self.cache_size, self.cache_min, self.cache_max = prefix_cache, prefix_cache_min_tokens, prefix_cache_max_tokens
# -- backend hooks --------------------------------------------------------------------------------------------
def execute(self, layout: Layout):
raise NotImplementedError
def on_oom(self):
pass
def sync(self):
pass
def describe_backend(self) -> dict:
return {}
# -- shared ---------------------------------------------------------------------------------------------------
def describe(self):
return {**self.describe_backend(), "prefix_cache": {"size": self.cache_size, "min_state_tokens": self.cache_min,
"max_tokens": self.cache_max, "cached_states": len(self.cache),
"hits": self.hits, "misses": self.misses}}
def _run(self, reqs, keep):
for sw in plan_sweeps(reqs, self.prefill_chunk, self.max_tokens, self.max_rows):
layout = build_layout(sw, self.kconv, keep)
z, zu = self.execute(layout)
for r, a, b in sw.prefill:
r.state.done = b
for st in layout.involved: # free what no later sweep and no cache entry needs
if not layout.persist[id(st)]:
st.clear()
if z is None:
continue
k = 0
for j, (r, qi, K) in enumerate(layout.row_refs):
r.logits[qi] = z[k:k + K]; k += K
if zu is not None:
r.unknown[qi] = zu[j]
def run(self, encs: list[Encoded]) -> list[RunResult]:
reqs = [Req(e) for e in encs]
fresh = {}
for r in reqs:
r.key = key = state_key(r.enc.state_ids)
if key in self.cache:
st = self.cache.pop(key); self.cache[key] = st # LRU touch
r.state, r.prefill, r.hit = st, False, True; self.hits += 1
elif key in fresh:
r.state, r.prefill = fresh[key], False # same state earlier in this batch
else:
r.state = PrefixState(r.enc.n_state); fresh[key] = r.state
self.misses += 1
keep = frozenset(id(st) for st in fresh.values() if self.cache_size and self.cache_min <= st.n <= self.cache_max)
# a state taken from the cache must survive this batch too: _run frees every involved state whose last use is
# over unless it is in `keep`, and a cached state is never in `fresh` - without this its tensors were cleared
# while it stayed in the cache, and the next hit on it failed with KeyError in the first layer
keep |= frozenset(id(r.state) for r in reqs if r.hit)
try:
self._run(reqs, keep)
except self.oom_errors:
for r in reqs:
r.state = None
fresh.clear()
self.on_oom()
if len(encs) > 1: # retry one by one: only the request(s) that do not fit alone are refused
return [self.run([e])[0] for e in encs]
e = encs[0]
return [RunResult(None, None, False, Unsupported(f"request exceeds this device's memory ({e.n_tokens} tokens; state {e.n_state})"))]
if self.cache_size:
for key, st in fresh.items():
if id(st) in keep and st.done == st.n:
self.cache[key] = st; self.cache_tokens += st.n
while self.cache and (len(self.cache) > self.cache_size or self.cache_tokens > self.cache_max):
_, st = self.cache.popitem(last=False); self.cache_tokens -= st.n
return [RunResult(r.logits, r.unknown if self.unknown else None, r.hit) for r in reqs]
def warmup(self):
"""Exercise the kernels on a few shapes (Triton kernels compile/autotune on first use)."""
from .render import Row
rows = [Row(list(range(2000, 2012)), 11, [3, 7]), Row(list(range(3000, 3009)), 8, [2, 5])]
for n in (17, 300, self.prefill_chunk + 64): # short, medium, and a two-chunk prefill (carried states)
e = Encoded([1000 + (t % 5000) for t in range(n)], rows)
self.run([e, e] if n < 1000 else [e])
self.cache.clear(); self.cache_tokens = 0; self.hits = self.misses = 0
self.sync()