Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Qwen speculation: depth rules behind env switches (cost, online, table, fixed-depth truncation), defaults unchanged; draft logging arm; cache history follows ndt

YanissAmz7d5f3685838c
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 1446476..cc53df6 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -614,6 +614,7 @@ class QwenEngine:
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
torch.set_grad_enabled(False)
self.torch, self.Generator, self.Job = torch, Generator, Job
+ ndt = max(ndt, int(os.environ.get("QWSPEC_MAXD") or 0), int(os.environ.get("QWSPEC_FIXD") or 0)) # buffers fit the deepest draft
self.model_path, self.ctx, self.ndt, self.draft_policy = model_path, ctx, ndt, draft_policy
self.config = Config.from_directory(model_path)
self.tokenizer = Tokenizer.from_config(self.config)
@@ -624,7 +625,7 @@ class QwenEngine:
self.cache_bits = cache_bits
from exllamav3 import CacheLayer_quant
qkw = dict(layer_type=CacheLayer_quant, k_bits=cache_bits, v_bits=cache_bits) if cache_bits else {}
- self.cache = Cache(self.model, max_num_tokens=ctx, max_history=3, **qkw)
+ self.cache = Cache(self.model, max_num_tokens=ctx, max_history=max(3, ndt), **qkw)
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
@@ -635,7 +636,7 @@ class QwenEngine:
self.draft_model = self.draft_cache = None
if draft_policy != "off":
self.draft_model = Model.from_config(self.config, component="mtp")
- self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=3, **qkw)
+ self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx, max_history=max(3, ndt), **qkw)
with Heartbeat("loading MTP drafter"):
self.draft_model.load(progressbar=False)
self.vision = None
@@ -687,8 +688,11 @@ class QwenEngine:
self.generator = self.Generator(**kw)
if spec and self.draft_policy == "mix":
import spec_policy # tools/qwen/spec_policy.py: dynamic length + n-gram lookup, the shipped rule
+ thf, thv, maxd = spec_policy.env_defaults(self.ndt) # 0.6 / 0.3 / ndt unless QWSPEC_THF / THV / MAXD are set
+ fx = os.environ.get("QWSPEC_FIXD")
self.uninstall = spec_policy.install(self.generator, self.draft_model, self.model,
- 0.6, 0.3, self.ndt, (2, 3, 5), {})
+ thf, thv, maxd, (2, 3, 5), {},
+ rule=spec_policy.rule_from_env(thf, thv, maxd), fixed=int(fx) if fx else None)
self.spec_on = spec
if self.slot_store is not None:
self.slot_store.generator = self.generator
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index 9ca9e87..fe59029 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -204,10 +204,131 @@ class SeqFollower:
sid._ng_lw = n
return idx
-def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None):
- """ngram = (nmin, K, lmin) or None. Returns an uninstall function."""
+# ---------------------------------------------------------------------------------------------- depth rules
+# A rule decides, per drafted depth, from the drafter's max token probability p (the "reach" is the running product):
+# step(i, p) -> (keep, more): keep = this depth's token goes to the verify; more = draft one more depth.
+# Greedy verification makes the generated ids independent of the rule; only the speed changes.
+# ProductRule with (0.6, 0.3, maxd) is the shipped rule. CostRule / OnlineRule see a calibrated reach (see rule_from_env).
+class ProductRule:
+ name = "product"
+ def __init__(self, thf=0.6, thv=0.3, maxd=3):
+ self.thf, self.thv, self.maxd = thf, thv, maxd
+ self.reach = 1.0
+ def begin(self): self.reach = 1.0
+ def q(self, i, p):
+ """probability estimate that depths 0..i are all accepted (updates the running reach)"""
+ self.reach *= p
+ return self.reach
+ def step(self, i, p):
+ q = self.q(i, p)
+ if i > 0 and q < self.thv: return False, False
+ return True, not (q < self.thf or i + 1 >= self.maxd)
+ def end_round(self, drafted, accepted): pass
+
+class CostRule(ProductRule):
+ """Same shape, calibrated reach: q = min(1, scale * reach ** gamma). thv = cost of one verify row / ms per token
+ (keep a row when its chance to add a token pays its ~row_ms), thf = the same test one depth ahead (drafting also costs)."""
+ name = "cost"
+ def __init__(self, thf, thv, maxd, gamma=1.0, scale=1.0):
+ super().__init__(thf, thv, maxd); self.gamma, self.scale = gamma, scale
+ self.raw = 1.0
+ def begin(self): self.raw = 1.0
+ def q(self, i, p):
+ self.raw *= p
+ return min(1.0, self.scale * self.raw ** self.gamma)
+
+class OnlineRule(CostRule):
+ """CostRule whose scale follows the running acceptance of the current request: ratio of accepted drafts to the
+ sum of predicted per-depth reach over the last rounds (EMA, clipped), so a request that accepts more than the
+ drafter claims drafts deeper and the reverse. No prompt-class knowledge."""
+ name = "online"
+ def __init__(self, thf, thv, maxd, gamma=1.0, alpha=0.15, lo=0.5, hi=1.6):
+ super().__init__(thf, thv, maxd, gamma, 1.0)
+ self.alpha, self.lo, self.hi = alpha, lo, hi
+ self.pred_ema = None; self.acc_ema = None; self.pred = 0.0
+ def new_request(self): self.pred_ema = None; self.acc_ema = None; self.scale = 1.0
+ def begin(self): self.raw = 1.0; self.pred = 0.0
+ def step(self, i, p):
+ k, more = super().step(i, p)
+ if k: self.pred += self.raw # uncalibrated reach of the KEPT depths: their sum predicts the accepted count
+ return k, more
+ def end_round(self, drafted, accepted):
+ if drafted <= 0: return
+ a = self.alpha
+ self.pred_ema = self.pred if self.pred_ema is None else (1 - a) * self.pred_ema + a * self.pred
+ self.acc_ema = float(accepted) if self.acc_ema is None else (1 - a) * self.acc_ema + a * accepted
+ if self.pred_ema > 1e-6: self.scale = min(self.hi, max(self.lo, self.acc_ema / self.pred_ema))
+
+# measured plain-batch step ms for 1..8 rows (kamel T52) + 3.1 ms per drafted depth + 2 ms of round overhead: cycle ms for D drafts
+CYCLE_MS = [30.3 + 2.0, 41.6 + 3.1 + 2.0, 50.2 + 6.2 + 2.0, 58.6 + 9.3 + 2.0, 68.8 + 12.4 + 2.0, 75.1 + 15.5 + 2.0, 84.7 + 18.6 + 2.0, 92.9 + 21.7 + 2.0]
+
+class TableRule(ProductRule):
+ """Depth chosen BEFORE drafting from the request's own acceptance history; no probability, no per-depth host read.
+ a[d] = EWMA (decay 0.75, prior 0.75) of P(draft d accepted | drafts < d accepted), updated only where observed
+ (rounds stop counting at the first reject). depth = argmax_D (1 + sum_{d<=D} prod_{j<=d} a[j]) / cycle_ms[D], D in 1..cap.
+ A fully accepted round is censored: the next round drafts one deeper (a probe). D = 0 (plain decode) is not used:
+ skipping the drafter would leave a hole in its cache."""
+ name = "table"
+ needs_p = False
+ def __init__(self, maxd, cycle=None, decay=0.75, prior=0.75):
+ super().__init__(1.0, 0.0, maxd)
+ self.cycle = list(cycle or CYCLE_MS); self.decay, self.prior = decay, prior
+ self.new_request()
+ def new_request(self): self.a = [self.prior] * (self.maxd + 1); self.probe = 0
+ def choose(self):
+ best, bd = -1.0, 1; e = 1.0; prod = 1.0
+ for D in range(1, self.maxd + 1):
+ prod *= self.a[D]; e += prod
+ v = e / self.cycle[D]
+ if v > best: best, bd = v, D
+ return max(bd, self.probe)
+ def end_round(self, drafted, accepted):
+ if drafted <= 0: return
+ for d in range(1, min(drafted, accepted + 1) + 1):
+ self.a[d] = self.decay * self.a[d] + (1 - self.decay) * (1.0 if d <= accepted else 0.0)
+ self.probe = drafted + 1 if accepted == drafted and drafted < self.maxd else 0
+
+def _envf(k, d):
+ v = os.environ.get(k)
+ return d if v is None or v == "" else type(d)(v)
+
+def env_defaults(ndt):
+ """(thf, thv, maxd) for install(): today's 0.6 / 0.3 / ndt unless QWSPEC_THF / QWSPEC_THV / QWSPEC_MAXD are set."""
+ return _envf("QWSPEC_THF", 0.6), _envf("QWSPEC_THV", 0.3), _envf("QWSPEC_MAXD", int(ndt))
+
+def rule_from_env(thf, thv, maxd):
+ """QWSPEC_RULE = product (default) | cost | online | table (depth from the request's acceptance history, no probabilities); QWSPEC_GAMMA / QWSPEC_SCALE tune the calibrated reach.
+ QWSPEC_FIXD = N: draft N depths with no host read and truncate once per round (rule applied on the stacked probabilities)."""
+ kind = os.environ.get("QWSPEC_RULE", "product")
+ if kind == "product": r = ProductRule(thf, thv, maxd)
+ elif kind == "cost": r = CostRule(thf, thv, maxd, _envf("QWSPEC_GAMMA", 1.0), _envf("QWSPEC_SCALE", 1.0))
+ elif kind == "table":
+ cyc = os.environ.get("QWSPEC_CYCLE"); r = TableRule(maxd, [float(x) for x in cyc.split(",")] if cyc else None, _envf("QWSPEC_DECAY", 0.75), _envf("QWSPEC_PRIOR", 0.75))
+ elif kind == "online": r = OnlineRule(thf, thv, maxd, _envf("QWSPEC_GAMMA", 1.0), _envf("QWSPEC_ALPHA", 0.15))
+ else: raise ValueError(f"QWSPEC_RULE={kind}")
+ return r
+
+def apply_rule(rule, ps):
+ """Offline / truncation form: rule applied to a list of per-depth max probabilities. Returns keep (0..len(ps))."""
+ rule.begin(); keep = 0
+ for i, p in enumerate(ps):
+ k, more = rule.step(i, p)
+ if k: keep = i + 1
+ if not more: break
+ return keep
+
+def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule=None, fixed=None, log=None, log_depth=7):
+ """ngram = (nmin, K, lmin) or None. Returns an uninstall function.
+ rule: a depth rule (default ProductRule(thf, thv, maxd) = the shipped rule).
+ fixed = N: no host read per depth; N depths are drafted, the max probabilities stay on the device and one read per
+ round feeds the rule, which then truncates (rows kept <= N + 1).
+ log = list: logging arm. Drafts log_depth depths whatever the rule says, appends one dict per round
+ (n, ng, ps, ids, keep) and verifies what `rule` would have kept (the stream is the baseline stream)."""
lm = model.modules[model.logit_layer_idx]
- st = {"i": 0, "reach": 1.0, "stop": False, "keep": None}
+ if rule is None: rule = ProductRule(thf, thv, maxd)
+ maxd = rule.maxd # the rule owns the depth cap
+ st = {"i": 0, "stop": False, "keep": None, "ps": [], "job": None, "n": None, "drafted": 0}
+ if log is not None: fixed = None
orig_draft = type(g).iterate_draftmodel_mtp_gen.__get__(g)
orig_sfs = dm.sample_from_state; orig_fwd = dm.forward; orig_lmf = lm.forward
cap = {}
@@ -228,21 +349,48 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None):
return orig_fwd(*a, **k)
def sfs(state, params):
ids = orig_sfs(state, params)
+ if st["mode"] == "mtp" and not getattr(rule, "needs_p", True):
+ return ids
if st["mode"] == "mtp":
- p = torch.softmax(cap["lg"][..., :model.config.vocab_size].float().reshape(-1, model.config.vocab_size), -1).max().item()
- i = st["i"]; st["reach"] *= p
- if i > 0 and st["reach"] < thv:
+ pt = torch.softmax(cap["lg"][..., :model.config.vocab_size].float().reshape(-1, model.config.vocab_size), -1).max()
+ i = st["i"]
+ if fixed is not None:
+ st["ps"].append(pt); st["i"] = i + 1
+ if st["i"] >= fixed: st["stop"] = True
+ return ids
+ p = pt.item()
+ if log is not None:
+ st["ps"].append(p)
+ if st["keep"] is None:
+ k, more = rule.step(i, p)
+ if not k: st["keep"] = i
+ elif not more: st["keep"] = i + 1
+ st["i"] = i + 1
+ if st["i"] >= log_depth: st["stop"] = True
+ return ids
+ k, more = rule.step(i, p)
+ if not k:
st["keep"] = i; raise StopDraft()
st["i"] = i + 1
- if st["reach"] < thf or st["i"] >= maxd:
+ if not more:
st["stop"] = True; st["keep"] = st["i"]
return ids
+ win = log_depth if log is not None else (fixed if fixed is not None else maxd)
def wrapped(results):
- st.update(i=0, reach=1.0, stop=False, keep=None, mode="mtp")
+ st.update(i=0, stop=False, keep=None, mode="mtp", ps=[])
job = next((j for j in g.active_jobs if j.is_prefill_done()), None)
cont = None
+ n = None
+ if job is not None and len(g.active_jobs) == 1:
+ seq = job.sequences[0]; n = len(seq.sequence_ids)
+ if st["job"] is job and st["n"] is not None and n > st["n"]:
+ rule.end_round(st["drafted"], max(0, min(st["drafted"], n - st["n"] - 1)))
+ elif st["job"] is not job and hasattr(rule, "new_request"):
+ rule.new_request()
+ st["job"] = job; st["n"] = n; st["drafted"] = 0
+ rule.begin() # after end_round above: the online rule reads last round's prediction there
if ngram is not None and job is not None and len(g.active_jobs) == 1:
- seq = job.sequences[0]; n = len(seq.sequence_ids); K = min(ngram[1], maxd)
+ K = min(ngram[1], maxd)
if os.environ.get("QWSPEC_NGRAM_IDX", "1") == "0":
L, c = ngram_match(seq.sequence_ids.torch_slice(0, n).flatten().tolist(), ngram[0], K)
else:
@@ -257,21 +405,35 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None):
if cont is not None:
st["mode"] = "ng"; g.num_draft_tokens = 1
try: out = orig_draft(results)
- finally: g.num_draft_tokens = maxd
+ finally: g.num_draft_tokens = win
if out is None: return None
+ if log is not None: log.append({"n": n, "ng": True, "cont": list(cont)})
if stats is not None: stats["ng"] = stats.get("ng", 0) + 1; stats["rows"] = stats.get("rows", 0) + 1 + len(cont)
return torch.tensor([cont], dtype=torch.long)
- g.num_draft_tokens = maxd
+ w = rule.choose() if hasattr(rule, "choose") else win
+ g.num_draft_tokens = w
try:
out = orig_draft(results)
except StopDraft:
out = g.draft_ids_pinned[:, :st["keep"]]
+ finally:
+ g.num_draft_tokens = win # Job.prepare / reply_room reserve against this value: keep it at the deepest window
if out is None: return None
+ if fixed is not None:
+ ps = torch.stack(st["ps"]).tolist() # the one host read of the round
+ out = out[:, :apply_rule(rule, ps)]
+ elif log is not None:
+ keep = st["keep"] if st["keep"] is not None else log_depth
+ log.append({"n": n, "ng": False, "ps": list(st["ps"]), "ids": out[0, :log_depth].tolist(), "keep": keep})
+ out = out[:, :keep]
+ st["drafted"] = out.shape[-1]
if stats is not None: stats["mtp"] = stats.get("mtp", 0) + 1; stats["rows"] = stats.get("rows", 0) + 1 + out.shape[-1]
return out
lm.forward = lmf; dm.forward = fwd; dm.sample_from_state = sfs
g.iterate_draftmodel_mtp_gen = wrapped
+ ndt0 = g.num_draft_tokens; g.num_draft_tokens = win
def uninstall():
+ g.num_draft_tokens = ndt0
lm.forward = orig_lmf; dm.forward = orig_fwd; dm.sample_from_state = orig_sfs
g.__dict__.pop("iterate_draftmodel_mtp_gen", None); g.__dict__.pop("enqueue", None)
return uninstall
diff --git a/tools/qwen/test_spec_rule.py b/tools/qwen/test_spec_rule.py
new file mode 100644
index 0000000..6ab9926
--- /dev/null
+++ b/tools/qwen/test_spec_rule.py
@@ -0,0 +1,186 @@
+# CPU tests of the depth rules in spec_policy.py (no GPU, no model). python tools/qwen/test_spec_rule.py
+# 1. ProductRule == the pre-change inline rule (reference copy below) on random probability chains
+# 2. apply_rule (truncation form) == early-stop form, for every rule
+# 3. install() on a fake generator: early stop / fixed depth / log arm keep the same drafts; defaults are 0.6 / 0.3 / ndt
+# 4. OnlineRule: scale rises when drafts are accepted more than predicted, falls in the opposite case, stays clipped
+import os, sys, random, unittest
+os.environ.setdefault("HIP_VISIBLE_DEVICES", ""); os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+import torch
+import spec_policy as sp
+
+def ref_keep(ps, thf=0.6, thv=0.3, maxd=3):
+ """the rule exactly as it was inlined in install() before the rule objects: returns (keep, drafted forwards)"""
+ reach = 1.0; i = 0
+ for p in ps:
+ reach *= p
+ if i > 0 and reach < thv: return i, i + 1
+ i += 1
+ if reach < thf or i >= maxd: return i, i
+ return i, i
+
+def early(rule, ps):
+ """early-stop form as used by sfs: returns (keep, forwards run)"""
+ rule.begin(); keep = 0; fw = 0
+ for i, p in enumerate(ps):
+ fw += 1
+ k, more = rule.step(i, p)
+ if k: keep = i + 1
+ if not more: break
+ return keep, fw
+
+class FakeJob:
+ def __init__(self): self.sequences = [type("S", (), {"sequence_ids": []})()]
+ def is_prefill_done(self): return True
+
+class FakeGen:
+ def __init__(self, ndt):
+ self.num_draft_tokens = ndt; self.draft_ids_pinned = torch.zeros((1, 8), dtype=torch.long)
+ self.job = FakeJob(); self.active_jobs = [self.job]; self.chain = []; self.forwards = 0
+ def enqueue(self, job): return None
+ def iterate_draftmodel_mtp_gen(self, results):
+ for idx in range(self.num_draft_tokens):
+ st = self.dm.forward(None, {}); self.lm.forward(None)
+ new = self.dm.sample_from_state(st, {})
+ self.draft_ids_pinned[:1, idx:idx + 1].copy_(new)
+ return self.draft_ids_pinned[:, :self.num_draft_tokens]
+
+class FakeDM:
+ def __init__(self, gen, chain): self.gen, self.chain, self.k = gen, chain, 0
+ def forward(self, ids, params): self.gen.forwards += 1; return torch.zeros(1)
+ def sample_from_state(self, state, params):
+ t = torch.tensor([[100 + self.k]]); self.k += 1; return t
+class FakeLM:
+ def __init__(self, dm): self.dm = dm
+ def forward(self, *a, **k):
+ p = self.dm.chain[self.dm.k]; v = 16
+ lg = torch.full((1, 1, v), -30.0); lg[..., 0] = 0.0
+ lg[..., 1:] = torch.log(torch.tensor((1 - p) / (v - 1)) + 1e-30) - torch.log(torch.tensor(max(p, 1e-9))) # softmax max = p
+ return lg
+class FakeModel:
+ class config: vocab_size = 16
+ def __init__(self, lm): self.modules = [lm]; self.logit_layer_idx = 0
+
+def run_install(ps, rounds=1, grow=None, **kw):
+ g = FakeGen(kw.pop("ndt", 7)); dm = FakeDM(g, ps); lm = FakeLM(dm)
+ g.dm, g.lm = dm, lm; dm.chain = list(ps) + [0.5] * 8
+ model = FakeModel(lm)
+ # wire the fake as the real thing: install wraps these attributes
+ unin = sp.install(g, dm, model, **kw)
+ for r in range(rounds):
+ dm.k = 0
+ out = g.iterate_draftmodel_mtp_gen([])
+ if grow is not None: g.job.sequences[0].sequence_ids.extend([0] * (grow(out.shape[-1]) + 1)) # accepted + 1 new tokens
+ return out, g
+
+class T(unittest.TestCase):
+ def rnd(self, n=3000):
+ r = random.Random(1)
+ for _ in range(n): yield [r.choice([r.random(), 0.99, 0.9, 0.5]) for _ in range(8)]
+
+ def test_product_matches_reference(self):
+ for ps in self.rnd():
+ for (thf, thv, maxd) in [(0.6, 0.3, 3), (0.5, 0.2, 5), (0.8, 0.4, 4), (0.0, 0.0, 7)]:
+ self.assertEqual(early(sp.ProductRule(thf, thv, maxd), ps), ref_keep(ps, thf, thv, maxd))
+
+ def test_truncation_equals_early(self):
+ rules = [lambda: sp.ProductRule(0.6, 0.3, 3), lambda: sp.CostRule(0.5, 0.3, 6, 1.2, 0.9), lambda: sp.OnlineRule(0.5, 0.3, 6)]
+ for ps in self.rnd(1000):
+ for mk in rules:
+ self.assertEqual(sp.apply_rule(mk(), ps), early(mk(), ps)[0])
+
+ def test_install_modes_agree(self):
+ for ps in list(self.rnd(200))[:200]:
+ ref, _ = ref_keep(ps)[0], None
+ out, g = run_install(ps, thf=0.6, thv=0.3, maxd=3, ndt=3)
+ self.assertEqual(out.shape[-1], ref)
+ self.assertEqual(out[0].tolist(), [100 + i for i in range(ref)])
+ self.assertEqual(g.forwards, ref_keep(ps)[1])
+ out, g = run_install(ps, rule=sp.ProductRule(0.6, 0.3, 3), fixed=3, ndt=3)
+ self.assertEqual(out.shape[-1], ref); self.assertEqual(g.forwards, 3)
+ log = []
+ out, g = run_install(ps, rule=sp.ProductRule(0.6, 0.3, 3), log=log, ndt=7)
+ self.assertEqual(out.shape[-1], ref); self.assertEqual(g.forwards, 7)
+ self.assertEqual(log[0]["keep"], ref); self.assertEqual(len(log[0]["ids"]), 7)
+ self.assertEqual(len(log[0]["ps"]), 7)
+
+ def test_env_defaults(self):
+ for k in ("QWSPEC_THF", "QWSPEC_THV", "QWSPEC_MAXD", "QWSPEC_RULE"): os.environ.pop(k, None)
+ self.assertEqual(sp.env_defaults(3), (0.6, 0.3, 3))
+ r = sp.rule_from_env(0.6, 0.3, 3); self.assertEqual((r.name, r.thf, r.thv, r.maxd), ("product", 0.6, 0.3, 3))
+ os.environ["QWSPEC_THF"] = "0.5"; os.environ["QWSPEC_MAXD"] = "5"
+ try: self.assertEqual(sp.env_defaults(3), (0.5, 0.3, 5))
+ finally: del os.environ["QWSPEC_THF"]; del os.environ["QWSPEC_MAXD"]
+
+ def test_online_scale(self):
+ r = sp.OnlineRule(0.5, 0.3, 6)
+ for _ in range(60):
+ r.begin(); r.step(0, 0.7); r.step(1, 0.7); r.end_round(2, 2) # predicted 0.7 + 0.49, got 2
+ self.assertAlmostEqual(r.scale, 1.6) # clipped at hi
+ r.new_request(); self.assertEqual(r.scale, 1.0)
+ for _ in range(60):
+ r.begin(); r.step(0, 0.9); r.step(1, 0.9); r.end_round(2, 0)
+ self.assertAlmostEqual(r.scale, 0.5) # clipped at lo
+
+class TT(unittest.TestCase):
+ def test_table_depth_follows_acceptance(self):
+ r = sp.TableRule(7)
+ d0 = r.choose() # optimistic prior
+ for _ in range(40): r.end_round(d0 if False else 3, 0) # nothing is ever accepted
+ self.assertEqual(r.choose(), 1) # never below one draft
+ r.new_request()
+ for _ in range(40):
+ D = r.choose(); r.end_round(D, D) # everything accepted: drafts as deep as allowed
+ self.assertEqual(r.choose(), 7)
+
+ def test_table_probe_after_full_accept(self):
+ r = sp.TableRule(7); r.a = [0.75] + [0.2] * 7 # low acceptance: best depth 1
+ self.assertEqual(r.choose(), 1)
+ r.end_round(1, 1); self.assertEqual(r.choose(), 2) # censored full accept -> probe one deeper
+ r.end_round(2, 0); self.assertEqual(r.choose(), 1)
+
+ def test_table_install_draws_chosen_depth_without_reading_p(self):
+ out, g = run_install([0.9] * 8, rule=sp.TableRule(5), ndt=5)
+ self.assertEqual(g.forwards, out.shape[-1])
+ self.assertEqual(out.shape[-1], sp.TableRule(5).choose())
+
+class TE(unittest.TestCase):
+ def test_boundaries(self):
+ self.assertEqual(early(sp.ProductRule(0.0, 0.5, 4), [1.0, 0.5, 1.0]), (3, 3)) # reach == thv is kept
+ self.assertEqual(early(sp.ProductRule(0.0, 0.5, 4), [1.0, 0.49, 1.0]), (1, 2)) # below: dropped, its forward ran
+ self.assertEqual(early(sp.ProductRule(0.5, 0.0, 4), [0.5, 1.0]), (2, 2)) # reach == thf keeps drafting
+
+ def test_calibrated_reach(self):
+ self.assertEqual(early(sp.CostRule(0.0, 0.3, 3, gamma=1.0, scale=2.0), [1.0, 0.2, 1.0]), (3, 3)) # 0.4 >= 0.3 with scale 2
+ self.assertEqual(early(sp.CostRule(0.0, 0.3, 3, gamma=1.0, scale=1.0), [1.0, 0.2, 1.0]), (1, 2)) # 0.2 < 0.3
+ self.assertEqual(early(sp.CostRule(0.0, 0.3, 3, gamma=2.0, scale=1.0), [1.0, 0.7, 1.0]), (3, 3)) # 0.49
+ self.assertEqual(early(sp.CostRule(0.0, 0.3, 3, gamma=2.0, scale=1.0), [1.0, 0.5, 1.0]), (1, 2)) # 0.25
+
+ def test_online_pred_counts_kept_depths_only(self):
+ r = sp.OnlineRule(0.0, 0.5, 4); r.begin(); r.step(0, 0.9); r.step(1, 0.4) # second depth dropped
+ self.assertAlmostEqual(r.pred, 0.9)
+
+class TI(unittest.TestCase):
+ def test_online_adapts_through_install(self):
+ rule = sp.OnlineRule(0.5, 0.3, 5)
+ out, g = run_install([0.6] * 8, rounds=30, grow=lambda d: d, rule=rule, ndt=5) # every kept draft is accepted
+ self.assertGreater(rule.scale, 1.2)
+ rule = sp.OnlineRule(0.5, 0.3, 5)
+ out, g = run_install([0.9] * 8, rounds=30, grow=lambda d: 0, rule=rule, ndt=5) # none accepted
+ self.assertLess(rule.scale, 0.8)
+
+ def test_table_adapts_through_install(self):
+ rule = sp.TableRule(7)
+ out, g = run_install([0.9] * 8, rounds=40, grow=lambda d: 0, rule=rule, ndt=7)
+ self.assertEqual(out.shape[-1], 1)
+ rule = sp.TableRule(7)
+ out, g = run_install([0.9] * 8, rounds=40, grow=lambda d: d, rule=rule, ndt=7)
+ self.assertEqual(out.shape[-1], 7)
+
+ def test_num_draft_tokens_restored(self):
+ rule = sp.TableRule(7)
+ out, g = run_install([0.9] * 8, rounds=3, grow=lambda d: 0, rule=rule, ndt=7)
+ self.assertEqual(g.num_draft_tokens, 7)
+ out, g = run_install([0.9] * 8, rule=sp.ProductRule(0.6, 0.3, 3), ndt=3); self.assertEqual(g.num_draft_tokens, 3)
+
+if __name__ == "__main__": unittest.main(verbosity=1)