"""CPU test of specdec.py's rollback logic, using numpy as a stand-in for mlx.core. A toy "hybrid" LM (one recurrent, non-trimmable layer + one trimmable KV-like layer) is decoded greedily token by token, then with speculative decoding against a noisy copy of itself as the draft. Greedy speculative output must equal plain greedy output exactly for every k. Run: python test_specdec.py """ import sys import types from contextlib import nullcontext import numpy as np # ---- numpy stand-in for the handful of mlx.core functions specdec uses ------------------- fake = types.ModuleType("mlx.core") fake.uint32 = np.uint32 fake.array = lambda x, dtype=None: np.array(x, dtype=dtype) fake.concatenate = lambda xs, axis=0: np.concatenate(xs, axis=axis) fake.eval = lambda *a, **k: None fake.async_eval = lambda *a, **k: None fake.stream = lambda s: nullcontext() def _logsumexp(x, axis=-1, keepdims=False): m = x.max(axis=axis, keepdims=True) out = m + np.log(np.exp(x - m).sum(axis=axis, keepdims=True)) return out if keepdims else out.squeeze(axis) fake.logsumexp = _logsumexp sys.modules["mlx"] = types.ModuleType("mlx") sys.modules["mlx.core"] = fake sys.modules["mlx"].core = fake import specdec # noqa: E402 V, H = 23, 8 class RecurrentCache: # like mlx_lm ArraysCache: not trimmable def __init__(self): self.state = [np.zeros(H)] def is_trimmable(self): return False class KVLikeCache: # like mlx_lm KVCache: trimmable def __init__(self): self.tokens = [] @property def state(self): return [np.array(self.tokens)] def is_trimmable(self): return True def trim(self, n): n = min(n, len(self.tokens)) del self.tokens[len(self.tokens) - n:] return n class ToyLM: def __init__(self, seed, noise=0.0, hybrid=True): r = np.random.default_rng(seed) self.A = r.normal(size=(H, H)) * 0.5 self.E = r.normal(size=(V, H)) self.W = r.normal(size=(V, H)) + noise * np.random.default_rng(seed + 99).normal(size=(V, H)) self.P = r.normal(size=(V, V)) * 0.3 + noise * np.random.default_rng(seed + 7).normal(size=(V, V)) self.hybrid = hybrid self.calls = 0 def make_cache(self): return [RecurrentCache(), KVLikeCache()] if self.hybrid else [KVLikeCache()] def __call__(self, x, cache): self.calls += 1 out = [] for tok in x[0].tolist(): if self.hybrid: s = np.tanh(self.A @ cache[0].state[0] + self.E[tok]) cache[0].state = [s] # new array, never mutated in place (like MLX) kv = cache[-1] kv.tokens.append(tok) hist = np.bincount(kv.tokens[-4:], minlength=V) @ self.P out.append((self.W @ s if self.hybrid else 0) + hist + 0.01 * len(kv.tokens) * self.E[tok][0]) return np.array(out)[None] def greedy(lp): return np.argmax(lp, axis=-1).astype(np.uint32) def baseline(model, prompt, n): cache = model.make_cache() logits = model(np.array(prompt)[None], cache) out = [] for _ in range(n): t = int(np.argmax(logits[0, -1])) out.append(t) logits = model(np.array([t])[None], cache) return out def run_spec(target, draft, prompt, n, k): stats = {} gen = specdec.speculative_generate( np.array(prompt), target, draft, target.make_cache(), draft.make_cache(), num_draft_tokens=k, max_tokens=n, sampler=greedy, stats=stats) toks = list(gen) return [t for t, _ in toks], sum(f for _, f in toks), stats def main(): prompt, n = [1, 5, 7, 2, 9, 4], 200 failures = 0 # perfect draft must accept everything; bad draft must exercise the rollback paths for hybrid in (True, False): target = ToyLM(0, hybrid=hybrid) ref = baseline(target, prompt, n) for noise, label in ((0.0, "perfect draft"), (0.6, "noisy draft"), (3.0, "bad draft")): for k in (1, 2, 3, 4, 6): draft = ToyLM(0, noise=noise, hybrid=hybrid) toks, n_from_draft, st = run_spec(target, draft, prompt, n, k) ok = toks == ref and len(toks) == n and n_from_draft == st["accepted"] if noise == 0.0: ok = ok and st["accepted"] == st["proposed"] if noise == 3.0: ok = ok and st["rejections"] > 0 failures += not ok print(f"{'hybrid' if hybrid else 'kv-only':7s} {label:13s} k={k}: " f"identical={toks == ref} len={len(toks)} accept={st['accepted']}/{st['proposed']} " f"rejections={st['rejections']} reforwards={st['target_reforwards']} " f"{'OK' if ok else 'FAIL'}") print("FAILURES:", failures) return 1 if failures else 0 if __name__ == "__main__": sys.exit(main())