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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
DFlash2 serving: per-request adaptive draft depth (full block, short block, plain decode with probes) from the measured acceptance; --dflash-adapt on|off
YanissAmzab8f9f8cd65b
diff --git a/exllamav3/generator/draft_depth.py b/exllamav3/generator/draft_depth.pynew file mode 100644index 0000000..a485644--- /dev/null+++ b/exllamav3/generator/draft_depth.py@@ -0,0 +1,69 @@+"""Acceptance-driven draft depth for block drafters (DFlash2): how many drafted tokens a round verifies, 0 = plain decode.++One DraftDepth per request. It keeps an EMA of the drafted tokens a speculative round accepted and picks full depth, a short+block, or off. While off it probes one full round after `probe` plain steps; a failed probe doubles the interval (up to+probe_max), a good one switches speculation back on. Pure Python: no torch, unit-testable without a model.+"""+from __future__ import annotations++import os+++class DraftDepth:++ def __init__(self, full: int, low: int = None, alpha: float = None, off_below: float = None, low_below: float = None,+ full_above: float = None, probe_min: int = None, probe_max: int = None, warm: int = None):+ env = os.environ.get+ self.full = full+ self.low = min(full, low or int(env("EXL3_DFLASH_ADAPT_LOW", "3")))+ self.alpha = alpha or float(env("EXL3_DFLASH_ADAPT_ALPHA", "0.3"))+ self.off_below = off_below if off_below is not None else float(env("EXL3_DFLASH_ADAPT_OFF", "0.45"))+ self.low_below = low_below if low_below is not None else float(env("EXL3_DFLASH_ADAPT_LOW_BELOW", "1.0"))+ self.full_above = full_above if full_above is not None else float(env("EXL3_DFLASH_ADAPT_FULL_ABOVE", "2.2"))+ self.probe_min = probe_min or int(env("EXL3_DFLASH_ADAPT_PROBE", "4"))+ self.probe_max = probe_max or int(env("EXL3_DFLASH_ADAPT_PROBE_MAX", "32"))+ self.warm = warm if warm is not None else int(env("EXL3_DFLASH_ADAPT_WARM", "3")) # rounds at full depth before any cut+ self.ema = None # accepted drafted tokens per speculative round+ self.depth = full+ self.probe = self.probe_min+ self.since_probe = 0+ self.rounds = 0++ def want(self) -> int:+ """Drafted tokens to verify in the next round (0 = plain step)."""+ if self.depth == 0 and self.since_probe >= self.probe:+ return self.full+ return self.depth++ def record(self, drafted: int, accepted: int):+ """Result of one step: `drafted` tokens verified (0 = plain step), `accepted` of them kept."""+ if drafted == 0:+ self.since_probe += 1+ return+ probing = self.depth == 0+ self.rounds += 1+ a = float(accepted)+ if self.ema is None:+ self.ema = a+ else:+ w = 0.5 if probing else self.alpha+ self.ema += w * (a - self.ema)+ if probing:+ self.since_probe = 0+ if self.ema >= self.off_below:+ self.depth = self.full if self.ema >= self.low_below else self.low+ self.probe = self.probe_min+ else:+ self.probe = min(self.probe * 2, self.probe_max)+ return+ if self.rounds < self.warm:+ return+ # a short block caps the accepted count at `low`, so promote on the share of that cap rather than the full-depth figure+ if self.ema < self.off_below:+ self.depth = 0+ self.since_probe = 0+ elif self.depth == self.full:+ if self.ema < self.low_below:+ self.depth = self.low+ elif self.ema >= min(self.full_above, 0.75 * self.low):+ self.depth = self.fulldiff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex 9467afc..6c2c55b 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -13,6 +13,7 @@ from ..cache.cache import Cachefrom ..cache.recurrent import RecurrentCachefrom ..tokenizer.tokenizer import Tokenizerfrom ..constants import PAGE_SIZE+from .draft_depth import DraftDepthfrom ..util import cuda_sync_activelogger = logging.getLogger(__name__)@@ -280,6 +281,10 @@ class Generator:# measured speculative rate would not beat plain decode. Opt-in: EXL3_SPEC_GATE=1self.spec_gate = SpecGate() if (draft_model is not None andos.environ.get("EXL3_SPEC_GATE", "0") != "0") else None+ # acceptance-driven draft depth for the block drafter (per request, see draft_depth.py); EXL3_DFLASH_ADAPT=0 = fixed block+ self.dflash_adapt = (draft_model is not None and draft_model.caps.get("dflash_draft", False)+ and os.environ.get("EXL3_DFLASH_ADAPT", "0") != "0" and self.spec_gate is None)+ self._dflash_window = Nonemax_q_size = max(self.num_draft_tokens + 1, max_q_size)# Chunking/partitioning@@ -913,6 +918,8 @@ class Generator:if self.draft_model:if self.dflash_draft and self.spec_gate is not None:self._iterate_gated(results, self.iterate_draftmodel_dflash_gen)+ elif self.dflash_adapt:+ self._iterate_depth(results, self.iterate_draftmodel_dflash_gen)elif self.mtp_draft and self.spec_gate is not None:self._iterate_gated(results, self.iterate_draftmodel_mtp_gen)elif self.dflash_draft:@@ -1427,6 +1434,34 @@ class Generator:gate.record_plain(dt, produced)+ def _iterate_depth(self, results: list, draft_fn):+ """One decode step with the per-request draft depth: the block is cut to the deepest wish of the active jobs, and no drafter+ forward runs when every job wants plain decode (the drafter's cache catches up from the target's hidden states)."""+ gen_jobs = [j for j in self.active_jobs if j.is_prefill_done()]+ if not gen_jobs:+ self.iterate_gen(results, None)+ return+ for j in gen_jobs:+ if getattr(j, "draft_depth", None) is None:+ j.draft_depth = DraftDepth(self.num_draft_tokens)+ wants = [j.draft_depth.want() for j in gen_jobs]+ window = max(wants)+ n0 = [j.new_tokens for j in gen_jobs]+ self._dflash_window = window+ draft_tokens = draft_fn(results) if window > 0 else None+ self._dflash_window = None+ if draft_tokens is None:+ window = 0+ self.iterate_gen(results, draft_tokens)+ if self._dkv_pending is not None and any(j not in self.active_jobs for j in gen_jobs):+ self._flush_dkv()+ for j, w, n in zip(gen_jobs, wants, n0):+ if w == 0 or window == 0:+ j.draft_depth.record(0, 0)+ else:+ j.draft_depth.record(window, max(0, j.new_tokens - n - 1))++def iterate_draftmodel_dflash_gen(self, results: list):self._draft_conf_round = None@@ -1446,7 +1481,7 @@ class Generator:return None# The diffusion drafter always runs at its fixed block size, dynamic window truncates the drafted block- window = self.num_draft_tokens+ window = self.num_draft_tokens if self._dflash_window is None else min(self.num_draft_tokens, self._dflash_window)# Create block index table for batchmax_pages_batch = (max_seq_len + PAGE_SIZE - 1) // PAGE_SIZEdiff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 7ddfb36..d05adba 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -2266,8 +2266,12 @@ def main() -> None:parser.add_argument("--ndt", type=int, default=7, help="max draft tokens per round (default 7; the rule drafts up to 3 for most rounds, deeper only on confident chains)")parser.add_argument("--draft-policy", choices=("mix", "mtp", "dflash", "off"), default="mix",help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, dflash = DFlash2 block drafter "- "from --dflash-dir (lossless, fixed block), off = plain decode")+ "from --dflash-dir (lossless; see --dflash-adapt), off = plain decode")parser.add_argument("--dflash-dir", default="", help="DFlash2 drafter checkpoint directory (with --draft-policy dflash)")+ parser.add_argument("--dflash-adapt", choices=("on", "off"), default="on",+ help="with --draft-policy dflash: cut the verified block per request from the measured acceptance (full / short / "+ "plain decode with periodic probes, generator/draft_depth.py), so low-acceptance chat never runs slower than plain; "+ "off = always the fixed block. EXL3_DFLASH_ADAPT in the environment wins")parser.add_argument("--no-vision", action="store_true", help="do not load the vision tower (saves memory)")parser.add_argument("--no-uncensor", action="store_true", help="ignore a bundled uncensor_spec.json in the model directory (same as EXL3_ABLIT_RUNTIME=off)")parser.add_argument("--default-temperature", type=float, default=None, help="when a request omits it (default: generation_config.json)")@@ -2290,6 +2294,8 @@ def main() -> None:args = parser.parse_args()if args.draft_policy == "dflash" and not args.dflash_dir:parser.error("--draft-policy dflash needs --dflash-dir")+ if args.draft_policy == "dflash":+ os.environ.setdefault("EXL3_DFLASH_ADAPT", "1" if args.dflash_adapt == "on" else "0")if args.sessions < 1:parser.error("--sessions must be at least 1")# Measured with --ndt 3: greedy output equal to a solo run on two short prompts at 2 sessions with --cache-bits 0; not atdiff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex b857fde..327d990 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -1338,6 +1338,138 @@ class DflashFlagTests(unittest.TestCase):self.assertEqual(cm.exception.code, 2)self.assertIn("--dflash-dir", err.getvalue())+ def _adapt_env(self, *extra, env=None):+ """EXL3_DFLASH_ADAPT as main() leaves it for the engine (load_all stubbed out)."""+ argv = ["serve.py", "--model", "m", "--draft-policy", "dflash", "--dflash-dir", "d", *extra]+ seen = {}++ def fake_load(args):+ seen["adapt"] = os.environ.get("EXL3_DFLASH_ADAPT")+ raise RuntimeError("stop")+ sh = serve.startup_health+ with unittest.mock.patch.dict(os.environ, env or {}), unittest.mock.patch.object(sys, "argv", argv), \+ unittest.mock.patch.object(serve, "load_all", fake_load), \+ unittest.mock.patch.object(sh, "check_model_dir"), unittest.mock.patch.object(sh, "start"), \+ unittest.mock.patch.object(sh, "report_compiler"), unittest.mock.patch.object(sh, "abort"), \+ self.assertRaises(RuntimeError):+ if not env:+ os.environ.pop("EXL3_DFLASH_ADAPT", None)+ serve.main()+ return seen["adapt"]++ def test_adaptive_depth_is_on_by_default(self):+ self.assertEqual(self._adapt_env(), "1")++ def test_adapt_off_flag_selects_the_fixed_block(self):+ self.assertEqual(self._adapt_env("--dflash-adapt", "off"), "0")++ def test_environment_wins_over_the_flag(self):+ self.assertEqual(self._adapt_env("--dflash-adapt", "on", env={"EXL3_DFLASH_ADAPT": "0"}), "0")++ def test_adapt_flag_rejects_other_values(self):+ err = io.StringIO()+ with unittest.mock.patch.object(sys, "argv", ["serve.py", "--model", "m", "--dflash-adapt", "maybe"]), \+ unittest.mock.patch.object(sys, "stderr", err), self.assertRaises(SystemExit) as cm:+ serve.main()+ self.assertEqual(cm.exception.code, 2)+++class DraftDepthTests(unittest.TestCase):+ """exllamav3/generator/draft_depth.py (pure Python, loaded by path so no torch import)."""++ @classmethod+ def setUpClass(cls):+ import importlib.util+ path = Path(__file__).resolve().parents[2] / "exllamav3" / "generator" / "draft_depth.py"+ spec = importlib.util.spec_from_file_location("draft_depth_t", path)+ cls.M = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(cls.M)++ def ctl(self, **kw):+ return self.M.DraftDepth(7, **kw)++ def run_rounds(self, c, accepted, n):+ """n steps; `accepted` is a number or a repeating pattern of accepted counts per speculative round."""+ pat = accepted if isinstance(accepted, (list, tuple)) else (accepted,)+ for i in range(n):+ d = c.want()+ c.record(d, min(pat[i % len(pat)], d) if d else 0)++ def switch_off(self, c):+ while c.depth:+ self.run_rounds(c, 0, 1)++ def test_starts_at_full_depth(self):+ self.assertEqual(self.ctl().want(), 7)++ def test_warm_up_never_cuts(self):+ c = self.ctl()+ self.run_rounds(c, 0, 2)+ self.assertEqual(c.want(), 7)++ def test_high_acceptance_stays_full(self):+ c = self.ctl()+ self.run_rounds(c, 3, 50)+ self.assertEqual(c.want(), 7)++ def test_chat_like_acceptance_switches_off(self):+ c = self.ctl()+ self.run_rounds(c, 0, 8)+ self.assertEqual(c.depth, 0)+ self.assertEqual(c.want(), 0)++ def test_middle_acceptance_gets_the_short_block(self):+ c = self.ctl()+ self.run_rounds(c, (1, 2, 1, 0), 20)+ self.assertEqual(c.depth, 3)+ self.assertEqual(c.want(), 3)++ def test_short_block_returns_to_full_when_acceptance_climbs(self):+ c = self.ctl()+ self.run_rounds(c, (1, 2, 1, 0), 20)+ self.assertEqual(c.depth, 3)+ self.run_rounds(c, 3, 12)+ self.assertEqual(c.depth, 7)++ def test_off_probes_with_a_doubling_interval(self):+ c = self.ctl()+ self.switch_off(c)+ plain = 0+ while c.want() == 0:+ c.record(0, 0)+ plain += 1+ self.assertEqual(plain, 4) # first probe after probe_min plain steps+ c.record(c.want(), 0) # failed probe+ self.assertEqual(c.depth, 0)+ plain = 0+ while c.want() == 0:+ c.record(0, 0)+ plain += 1+ self.assertEqual(plain, 8) # doubled+ for _ in range(10): # capped at probe_max+ c.record(c.want() or 0, 0) if c.want() else None+ while c.want() == 0:+ c.record(0, 0)+ c.record(c.want(), 0)+ self.assertLessEqual(c.probe, 32)++ def test_good_probe_switches_speculation_back_on(self):+ c = self.ctl()+ self.switch_off(c)+ while c.want() == 0:+ c.record(0, 0)+ for _ in range(4): # a request that turned agentic: probes accept the whole block+ c.record(c.want() or 7, 7)+ while c.want() == 0:+ c.record(0, 0)+ self.assertGreater(c.depth, 0)++ def test_env_overrides_the_thresholds(self):+ with unittest.mock.patch.dict(os.environ, {"EXL3_DFLASH_ADAPT_OFF": "5", "EXL3_DFLASH_ADAPT_WARM": "1"}):+ c = self.ctl()+ self.run_rounds(c, 3, 3)+ self.assertEqual(c.depth, 0)+if __name__ == "__main__":unittest.main()