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
Scheduler: a job waits for the active job that is prefilling its shared prefix
YanissAmzac1ee223cdb0
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex 8bf021c..84cea04 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -36,6 +36,7 @@ from .pagetable import PageTable, is_content_hashfrom .cpu_cache import CPUPageCachefrom .draft_confidence import DraftConfidenceCalibratorfrom . import chunk_il+from . import prefill_sharefrom .job import Job, _ttrace_begin, _ttrace_end, _TAIL_REPLY as _TAIL_REPLY_GEN# EXL3_REPLY_FIRST=1 (default off): a job that finishes inside iterate() is released (deallocate_pages: reply-end tail# stash, draft flush, page / slot release) by flush_deferred() AFTER its last results are returned, not before. The server calls it@@ -2104,6 +2105,14 @@ class Generator:})+ def _prefill_leader(self, job):+ """The active job that is still prefilling the leading pages `job` shares with it (prefill_share), or None."""+ if not prefill_share.share_enabled() or len(job.sequences) != 1 or not job.sequences[0].page_hashes:+ return None+ busy = [(a.sequences[0].page_hashes, a.sequences[0].kv_position, id(a)) for a in self.active_jobs+ if len(a.sequences) == 1 and a.sequences[0].page_hashes and not a.is_prefill_done()]+ return prefill_share.find_leader(job.sequences[0].page_hashes, busy, PAGE_SIZE)+def iterate_start_jobs(self, results: list):"""Move pending jobs into the active set when batch and cache capacity allow.@@ -2133,6 +2142,11 @@ class Generator:skipped_jobs.append(job)continue+ # A job on a prefix another active job is still prefilling waits for it instead of prefilling the same pages+ # again (not a skip: the wait ends when the leader passes the shared run, and it holds no one else back)+ if self._prefill_leader(job) is not None:+ continue+# Make sure the job we're about to add doesn't skip a job that's been skipped too many timesfor j in skipped_jobs:if j.skips >= j.max_skips:diff --git a/exllamav3/generator/prefill_share.py b/exllamav3/generator/prefill_share.pynew file mode 100644index 0000000..989b826--- /dev/null+++ b/exllamav3/generator/prefill_share.py@@ -0,0 +1,41 @@+"""Concurrent prefill of one shared prefix. Pure python (no torch), importable without a GPU.++A page is shared by hash as soon as a job allocates it, but it only counts as cached once its K/V is complete. Jobs that start+together on one prompt prefix (an agent and the sub-agents it spawns: same system + tools + parent context) therefore each+prefill the whole prefix themselves: N-fold work, N-fold wall time, and every one of them writes the same pages. The leader is+the active job that is still prefilling the longest shared run of leading pages; a pending job waits for it to pass that run, then+starts on pages (and recurrent checkpoints) that are cached. EXL3_PF_SHARE=0 turns it off; EXL3_PF_SHARE_MIN_PAGES (default 4)+is the shortest shared run worth waiting for.+"""+from __future__ import annotations++import os+++def share_enabled() -> bool:+ return os.environ.get("EXL3_PF_SHARE", "1") != "0"+++def min_pages() -> int:+ return int(os.environ.get("EXL3_PF_SHARE_MIN_PAGES", "4"))+++def common_pages(a: list, b: list) -> int:+ n = 0+ for x, y in zip(a, b):+ if x != y:+ break+ n += 1+ return n+++def find_leader(hashes: list, prefilling: list, page: int, min_run: int | None = None):+ """The entry of `prefilling` (page_hashes, kv_position, key) that has not yet prefilled the leading pages it shares with+ `hashes`, or None. Longest shared run first, so a job waits for the one that unlocks the most."""+ need = min_pages() if min_run is None else min_run+ best, best_k = None, 0+ for ph, kv, key in prefilling:+ k = common_pages(hashes, ph)+ if k >= need and k > best_k and kv < k * page:+ best, best_k = key, k+ return bestdiff --git a/tools/qwen/test_prefill_share.py b/tools/qwen/test_prefill_share.pynew file mode 100644index 0000000..83be0ab--- /dev/null+++ b/tools/qwen/test_prefill_share.py@@ -0,0 +1,129 @@+#!/usr/bin/env python3+"""Concurrent prefill of one shared prefix (exllamav3/generator/prefill_share.py + Generator._prefill_leader / iterate_start_jobs).+Pure python: the real helper and the real Generator glue (loaded by ast) on fake jobs. Proves: four jobs starting together on one+prefix start one leader and park three followers; a follower starts once the leader has prefilled the shared run (not before); a+job on another prefix or with a short shared run is never held; a finished leader releases everyone; EXL3_PF_SHARE=0 is the old+behaviour (all four start at once)."""+from __future__ import annotations++import ast+import importlib.util+import os+import sys+import textwrap+import types+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+spec = importlib.util.spec_from_file_location("prefill_share", ROOT / "exllamav3" / "generator" / "prefill_share.py")+prefill_share = importlib.util.module_from_spec(spec)+sys.modules["prefill_share"] = prefill_share+spec.loader.exec_module(prefill_share)+PAGE = 256+++def glue():+ src = (ROOT / "exllamav3" / "generator" / "generator.py").read_text()+ ns = {"os": os, "prefill_share": prefill_share, "PAGE_SIZE": PAGE}+ for n in ast.walk(ast.parse(src)):+ if isinstance(n, ast.FunctionDef) and n.name in ("_prefill_leader", "iterate_start_jobs"):+ exec(textwrap.dedent(ast.get_source_segment(src, n)), ns)+ return ns["_prefill_leader"], ns["iterate_start_jobs"]+++class Seq:+ def __init__(self, hashes, kv=0):+ self.page_hashes, self.kv_position = hashes, kv+++class FakeJob:+ skips, max_skips = 0, 4++ def __init__(self, hashes, kv=0):+ self.sequences = [Seq(hashes, kv)]+ self.done = False++ def is_prefill_done(self):+ return self.done++ def current_new_pages_required(self):+ return 1++ def activate(self):+ pass++ def allocate_pages(self):+ pass++ serial_number, identifier = 0, None+++class FakeGen:+ max_batch_size = 8++ def __init__(self, pending):+ self.pending_jobs, self.active_jobs = list(pending), []+ self.pagetable = types.SimpleNamespace(num_unreferenced_pages=lambda: 100)++ _prefill_leader, iterate_start_jobs = glue()+++def chain(n, tag="p"):+ return [f"{tag}{i}" for i in range(n)]+++class T(unittest.TestCase):+ def setUp(self):+ os.environ.pop("EXL3_PF_SHARE", None)++ def test_four_on_one_prefix_start_one_leader(self):+ pre = chain(90)+ g = FakeGen([FakeJob(pre + [f"t{i}"]) for i in range(4)])+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 1)+ self.assertEqual(len(g.pending_jobs), 3)++ def test_follower_starts_when_leader_passed_the_shared_run(self):+ pre = chain(90)+ g = FakeGen([FakeJob(pre + ["a"] * 3), FakeJob(pre + ["b"] * 3)])+ g.iterate_start_jobs([])+ lead = g.active_jobs[0]+ lead.sequences[0].kv_position = 89 * PAGE+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 1)+ lead.sequences[0].kv_position = 90 * PAGE+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 2)++ def test_unrelated_and_short_runs_are_not_held(self):+ pre = chain(90)+ g = FakeGen([FakeJob(pre + ["a"]), FakeJob(chain(90, "q")), FakeJob(pre[:3] + ["z"] * 5)])+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 3)++ def test_finished_leader_releases(self):+ pre = chain(90)+ g = FakeGen([FakeJob(pre + ["a"]), FakeJob(pre + ["b"])])+ g.iterate_start_jobs([])+ g.active_jobs[0].done = True+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 2)++ def test_off_switch(self):+ os.environ["EXL3_PF_SHARE"] = "0"+ pre = chain(90)+ g = FakeGen([FakeJob(pre + [f"t{i}"]) for i in range(4)])+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 4)++ def test_follower_does_not_block_unrelated_job_behind_it(self):+ pre = chain(90)+ g = FakeGen([FakeJob(pre + ["a"]), FakeJob(pre + ["b"]), FakeJob(chain(10, "q"))])+ g.iterate_start_jobs([])+ self.assertEqual(len(g.active_jobs), 2)+ self.assertEqual(g.active_jobs[1].sequences[0].page_hashes[0], "q0")+++if __name__ == "__main__":+ unittest.main()