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
Keep padded vocabulary ids out of drafts and sampled tokens, and stop an unknown id from killing the server
YanissAmzbcf036c45050
diff --git a/exllamav3/architecture/glm5_next_mtp.py b/exllamav3/architecture/glm5_next_mtp.pyindex 7880d4f..4fb5826 100644--- a/exllamav3/architecture/glm5_next_mtp.py+++ b/exllamav3/architecture/glm5_next_mtp.py@@ -294,7 +294,10 @@ class Glm5NextMTPModel(Model):return ids.clone().view(lead)logits = lm.forward(logits, params)if params.get("export_draft_logits"):- params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs+ params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs (it zeroes the padding itself)+ lim = getattr(self, "vocab_limit", None) # set by the Generator: the tokenizer's piece count when the head is padded+ if lim is not None:+ logits = logits[..., :lim] # the padding columns have no piece: a draft there is rejected for sureif params.get("export_draft_conf"):# Per-position confidence for the generator's draft truncation: the argmax logit# value, over the unpadded vocabularydiff --git a/exllamav3/architecture/qwen3_5_mtp.py b/exllamav3/architecture/qwen3_5_mtp.pyindex 6099784..b243697 100644--- a/exllamav3/architecture/qwen3_5_mtp.py+++ b/exllamav3/architecture/qwen3_5_mtp.py@@ -286,6 +286,9 @@ class Qwen3_5MTPModel(Model):params["draft_conf"] = confreturn idslogits = lm.forward(logits, params)+ lim = getattr(self, "vocab_limit", None) # set by the Generator: the tokenizer's piece count when the head is padded+ if lim is not None:+ logits = logits[..., :lim] # the padding columns have no piece: a draft there is rejected for sureif params.get("export_draft_conf"):# Per-position confidence for the generator's draft truncation: the argmax logit# value, over the unpadded vocabularydiff --git a/exllamav3/architecture/qwen4_exp_mtp.py b/exllamav3/architecture/qwen4_exp_mtp.pyindex 273f82a..281af0a 100644--- a/exllamav3/architecture/qwen4_exp_mtp.py+++ b/exllamav3/architecture/qwen4_exp_mtp.py@@ -190,7 +190,10 @@ class Qwen4ExpMTPModel(Model):return ids.clone().view(bsz, seq)logits = lm.forward(logits, params)if params.get("export_draft_logits"):- params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs+ params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs (it zeroes the padding itself)+ lim = getattr(self, "vocab_limit", None) # set by the Generator: the tokenizer's piece count when the head is padded+ if lim is not None:+ logits = logits[..., :lim] # the padding columns have no piece: a draft there is rejected for sureif params.get("export_draft_conf"):logits = logits[..., :self.attached_model().config.vocab_size]conf, ids = torch.max(logits, dim = -1)diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex 162d7d1..00ebd59 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -15,6 +15,21 @@ from ..constants import PAGE_SIZEfrom ..util import cuda_sync_activelogger = logging.getLogger(__name__)+_PADDED_VOCAB_LOGGED = set()+++def _log_padded_vocab(model_vocab: int, piece_count: int):+ """One start-up line per process and vocabulary shape: the head is wider than the tokenizer's table."""+ if (model_vocab, piece_count) in _PADDED_VOCAB_LOGGED:+ return+ _PADDED_VOCAB_LOGGED.add((model_vocab, piece_count))+ logger.warning(+ "vocabulary: the model head has %d columns but the tokenizer defines %d pieces; ids %d..%d are padding. "+ "They are masked at sampling and in the drafters; a padding id that still got through decodes to empty text",+ model_vocab, piece_count, piece_count, model_vocab - 1+ )++from ..util.memory import malloc_trimfrom .pagetable import PageTable, is_content_hashfrom .cpu_cache import CPUPageCache@@ -213,6 +228,16 @@ class Generator:cfg = self.model.configself.padded_vocab_size = ((cfg.vocab_size + 31) // 32) * 32+ # Padded head: the logits (and the embedding table) can be wider than the vocabulary the tokenizer defines, and the+ # ids in between have no piece. CustomSampler masks them, the drafters are bounded to vocab_limit (_bound_draft_ids)+ # and Job.receive_sample decodes an unknown id to empty text (note_unknown_token logs the first one)+ self.vocab_limit = None+ self._unknown_token_seen = False+ piece_count = getattr(tokenizer, "actual_vocab_size", None)+ if isinstance(piece_count, int) and 0 < piece_count < cfg.vocab_size:+ self.vocab_limit = piece_count+ _log_padded_vocab(cfg.vocab_size, piece_count)+# Pagingself.pagetable = PageTable(self, cache)# A cache has exactly one owning generator. Record the takeover and refuse to iterate a superseded generator@@ -224,6 +249,8 @@ class Generator:# Draft modelself.draft_model = draft_modelself.draft_cache = draft_cache+ if draft_model is not None:+ draft_model.vocab_limit = self.vocab_limit # read by the MTP heads (sample_from_state); None = whole headif draft_model:assert not ngram_match_min, \"Cannot use both draft model and n-gram draft."@@ -897,6 +924,8 @@ class Generator:"cache_seqlens": cache_seqlens,})+ if self.vocab_limit is not None:+ batch_logits = batch_logits[..., :self.vocab_limit] # the draft head's padding columns have no pieceif cal is not None:conf, new_ids = torch.max(batch_logits, dim = -1)else:@@ -979,6 +1008,31 @@ class Generator:return False+ def _bound_draft_ids(self, ids: torch.Tensor) -> torch.Tensor:+ """+ Draft proposals come from a head as wide as the embedding table, whose last columns are padding (no piece in the+ tokenizer). Such a draft can never be accepted, because the sampler never returns a padding id, and fed back to+ the drafter it reads a meaningless embedding row. Replace it by id 0: the round verifies that position as a+ rejection exactly as it would have, and accepted tokens do not change. The drafters that know vocab_limit already+ search the bounded head, so this only guards the rest. No host sync.+ """+ if self.vocab_limit is None:+ return ids+ return torch.where(ids < self.vocab_limit, ids, torch.zeros_like(ids))+++ def note_unknown_token(self, token_id: int, piece_count: int):+ """A sampled id without a piece reached Job.receive_sample. It decodes to empty text; the first one is logged."""+ if self._unknown_token_seen:+ return+ self._unknown_token_seen = True+ logger.error(+ "sampled token id %d has no piece (the tokenizer defines %d, the model head has %d columns); decoded as empty "+ "text. Logged once per generator",+ token_id, piece_count, self.model.config.vocab_size+ )++def iterate_draftmodel_mtp_gen(self, results: list):self._spec_round = None@@ -1102,6 +1156,7 @@ class Generator:q = spec_sample.law(dl[0, -1, :], spec_prm)spec_q.append(q)new_ids = spec_sample.draw(q, spec_job.rng.random()).view(1, 1)+ new_ids = self._bound_draft_ids(new_ids)self.draft_ids_pinned[:batch_size, idx:idx+1].copy_(new_ids)batch_ids.copy_(new_ids)cache_seqlens += 1 + (n_pend if idx == 0 else 0)@@ -1326,7 +1381,7 @@ class Generator:return Nonewindow = w_used- self.draft_ids_pinned[:batch_size, :window].copy_(new_ids[:batch_size, :window])+ self.draft_ids_pinned[:batch_size, :window].copy_(self._bound_draft_ids(new_ids[:batch_size, :window]))return self.draft_ids_pinned[:, :window]diff --git a/exllamav3/generator/job.py b/exllamav3/generator/job.pyindex f4ea0b9..6618aca 100644--- a/exllamav3/generator/job.py+++ b/exllamav3/generator/job.py@@ -878,7 +878,13 @@ class Job:# Decode and buffer outputid_to_piece = self.generator.tokenizer.get_id_to_piece_list(self.decode_special_tokens)- new_text = id_to_piece[next_token.item()]+ if 0 <= next_token_i < len(id_to_piece):+ new_text = id_to_piece[next_token_i]+ else:+ # An id the tokenizer has no piece for (the padded rows of the head, or worse) must never kill the process:+ # it decodes to nothing and the first one is logged. The sampler and the drafters mask these ids already+ new_text = ""+ self.generator.note_unknown_token(next_token_i, len(id_to_piece))if self.new_tokens == 0:unhealed = id_to_piece[self.prefix_token[0].item()]diff --git a/exllamav3/generator/spec_sample.py b/exllamav3/generator/spec_sample.pyindex 468472f..b7d7151 100644--- a/exllamav3/generator/spec_sample.py+++ b/exllamav3/generator/spec_sample.py@@ -98,10 +98,18 @@ def fused_law(logits: torch.Tensor, prm: tuple) -> torch.Tensor:def draw(p: torch.Tensor, u: float) -> torch.Tensor:- """Inverse-CDF draw from a dense (unnormalized) law with a uniform u in [0, 1); never returns a zero-mass index."""+ """+ Inverse-CDF draw from a dense (unnormalized) law with a uniform u in [0, 1); never returns a zero-mass index, so+ never an id of the padded vocabulary (a law is zero there). The search is bounded by the last index that holds mass:+ that is where the running sum first reaches its total. It matters when u * total rounds up to total in fp32 (the+ search then runs off the end), and for a law without mass (all zero, or NaN from a broken row), which used to end on+ the last column of the row, a padded id. Such a law yields index 0, a real token. No host sync.+ """cs = torch.cumsum(p, 0)- idx = torch.searchsorted(cs, (cs[-1:] * u), right = True)- return idx.clamp(max = p.numel() - 1)+ total = cs[-1:]+ idx = torch.searchsorted(cs, total * u, right = True)+ last = (cs < total).sum()+ return torch.minimum(idx, last.view(1))def verify(logits: torch.Tensor, q: torch.Tensor, d: int, prm: tuple, rng) -> torch.Tensor:@@ -112,5 +120,6 @@ def verify(logits: torch.Tensor, q: torch.Tensor, d: int, prm: tuple, rng) -> top = law(logits, prm)u1, u2 = rng.random(), rng.random()keep = u1 * q[d] < p[d]- r = draw((p - q).clamp_(min = 0.0), u2)+ res = (p - q).clamp_(min = 0.0)+ r = draw(torch.where(res.sum() > 0, res, p), u2) # p == q leaves no residual: draw from p then (keep is true but for rounding)return torch.where(keep, torch.full_like(r, d), r).view(1, 1)diff --git a/tests/test_padded_vocab.py b/tests/test_padded_vocab.pynew file mode 100644index 0000000..1f25f6c--- /dev/null+++ b/tests/test_padded_vocab.py@@ -0,0 +1,205 @@+"""+Padded vocabulary (GitHub issue 116): the model head is wider than the tokenizer's piece table (GLM-5.3: 154880 logit columns,+154856 pieces). No path may emit an id the tokenizer has no piece for, and an id that slips through must never kill the server.+CPU tests, no model; the sampler tests on the GPU run only where one is present. pytest tests/test_padded_vocab.py+"""+import os, sys, unittest+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+import torch+from exllamav3.generator import spec_sample+from exllamav3.generator.generator import Generator+from exllamav3.generator.job import Job+from exllamav3.generator.sampler import custom, ArgmaxSampler, ComboSampler, CategoricalSampler+from exllamav3.util.tensor import SeqTensor++V, VS = 154880, 154856 # head columns, pieces+++class StubTokenizer:+ actual_vocab_size = VS+ extended_id_to_piece = {}++ def get_id_to_piece_list(self, include_special_tokens = False):+ return [f"t{i}" for i in range(VS)]+++class StubRng:+ def __init__(self, *u):+ self.u = list(u)++ def random(self):+ return self.u.pop(0)+++def padded_law(seed = 0, spiky = False):+ g = torch.Generator().manual_seed(seed)+ logits = torch.randn(V, generator = g) * (6.0 if spiky else 2.0)+ prm = ("fused", (1.0, 1.0, 0, 0, 1.0), VS)+ return logits, prm, spec_sample.law(logits, prm)+++class TestSpecSamplePadding(unittest.TestCase):++ def test_law_is_zero_on_padding(self):+ _, _, p = padded_law()+ self.assertEqual(p.numel(), V)+ self.assertEqual(float(p[VS:].sum()), 0.0)+ self.assertAlmostEqual(float(p.sum()), 1.0, places = 5)++ def test_draw_never_returns_padding(self):+ _, _, p = padded_law()+ # u so close to 1 that total * u rounds up to total in fp32: the search used to run off the end of the row and the+ # clamp landed on the last column, a padded id+ for u in (0.0, 0.5, 1.0 - 2.0 ** -24, 1.0 - 1e-9):+ t = int(spec_sample.draw(p, u))+ self.assertLess(t, VS, f"u={u}")+ self.assertGreater(float(p[t]), 0.0, f"u={u}: drew a zero-mass index")++ def test_draw_without_mass_stays_in_vocabulary(self):+ # an all-zero law, and a NaN law (a broken row), used to end on the last column too+ for name, p in (("zero", torch.zeros(V)), ("nan", torch.full((V,), float("nan")))):+ for u in (0.0, 0.5, 0.999999):+ self.assertLess(int(spec_sample.draw(p, u)), VS, f"{name} u={u}")++ def test_draw_unchanged_on_normal_laws(self):+ _, _, p = padded_law(3, spiky = True)+ cs = torch.cumsum(p, 0)+ for u in (0.0, 0.1, 0.37, 0.5, 0.9, 0.99999):+ ref = int(torch.searchsorted(cs, cs[-1:] * u, right = True).clamp(max = V - 1)) # the draw as it was+ self.assertEqual(int(spec_sample.draw(p, u)), ref, f"u={u}")++ def test_verify_with_no_residual(self):+ # p == q leaves no residual mass; when the keep test fails by rounding (u1 ~ 1) the resample used to be the last column+ logits, prm, p = padded_law()+ d = int(torch.argmax(p))+ for u1 in (1.0 - 1e-12, 0.3):+ out = spec_sample.verify(logits, p.clone(), d, prm, StubRng(u1, 0.5))+ t = int(out)+ self.assertLess(t, VS)+ self.assertGreater(float(p[t]), 0.0)++ def test_verify_keeps_and_resamples_as_before(self):+ logits, prm, p = padded_law(1, spiky = True)+ q = padded_law(2, spiky = True)[2]+ d = int(torch.multinomial(q, 1))+ for u1, u2 in ((0.01, 0.2), (0.99, 0.2), (0.99, 0.8)):+ out = int(spec_sample.verify(logits, q, d, prm, StubRng(u1, u2)))+ keep = u1 * float(q[d]) < float(p[d])+ if keep:+ self.assertEqual(out, d)+ else:+ res = (p - q).clamp(min = 0.0)+ cs = torch.cumsum(res, 0)+ self.assertEqual(out, int(torch.searchsorted(cs, cs[-1:] * u2, right = True).clamp(max = V - 1)))+++class TestSamplerMask(unittest.TestCase):++ def run_cpu_argmax(self, pos):+ saved = custom.fused_sampler_enable+ custom.fused_sampler_enable = False # the fused kernel is CUDA only+ try:+ s = ArgmaxSampler()+ finally:+ custom.fused_sampler_enable = saved+ logits = torch.randn(1, 1, V)+ logits[..., pos] = 1e4+ return int(s.forward(logits, tokenizer = StubTokenizer()))++ def test_argmax_masks_padding_cpu(self):+ for pos in (VS, VS + 7, V - 1):+ self.assertLess(self.run_cpu_argmax(pos), VS)++ @unittest.skipUnless(torch.cuda.is_available(), "needs a GPU")+ def test_every_sampler_masks_padding_gpu(self):+ dev = "cuda:0"+ past = torch.randint(0, 1000, (1, 64), dtype = torch.long, device = dev)+ makers = [+ lambda: ArgmaxSampler(),+ lambda: ComboSampler(temperature = 0.0),+ lambda: ComboSampler(temperature = 0.0, rep_p = 1.1),+ lambda: ComboSampler(temperature = 0.7, top_p = 0.95),+ lambda: ComboSampler(temperature = 1.0, min_p = 0.05, top_k = 40),+ lambda: ComboSampler(temperature = 0.7, top_p = 0.9, rep_p = 1.1, pres_p = 0.1),+ lambda: ComboSampler(temperature = 0.7, top_p = 0.9, dry_multiplier = 0.8),+ lambda: ComboSampler(temperature = 0.7, adaptive_target = 0.5),+ lambda: CategoricalSampler(0.8),+ ]+ for mk in makers:+ for pos in (VS, VS + 13, V - 1):+ for dt in (torch.half, torch.float):+ s = mk()+ logits = torch.randn(1, 1, V, device = dev).to(dt)+ logits[..., pos] = 60.0 if dt == torch.half else 1e4+ try:+ t = int(s.forward(logits, past if s.reqs_past_ids else None, 1234, StubTokenizer()))+ except RuntimeError: # a stack the kernels do not take for this dtype+ continue+ self.assertLess(t, VS, f"{type(s).__name__} {s.steps} pos={pos} {dt}")+++class TestDraftBound(unittest.TestCase):++ def test_bound_draft_ids(self):+ g = type("G", (), {"vocab_limit": VS})()+ ids = torch.tensor([[5, VS - 1, VS, V - 1]])+ out = Generator._bound_draft_ids(g, ids)+ self.assertEqual(out.tolist(), [[5, VS - 1, 0, 0]])++ def test_no_limit_is_identity(self):+ g = type("G", (), {"vocab_limit": None})()+ ids = torch.tensor([[5, VS, V - 1]])+ self.assertIs(Generator._bound_draft_ids(g, ids), ids)+++class FakeGenerator:+ num_draft_tokens = 0+ tokenizer = StubTokenizer()++ def __init__(self):+ self.unknown = []++ note_unknown_token = Generator.note_unknown_token++ _unknown_token_seen = False++ class model:+ class config:+ vocab_size = V+++def bare_job(gen):+ job = Job(input_ids = torch.tensor([[1, 2, 3]]), max_new_tokens = 50, sampler = ArgmaxSampler(), stop_conditions = [])+ job.generator = gen+ job.sequences[0].sequence_ids = SeqTensor.from_tensor(torch.tensor([[1, 2, 3]]), 1)+ job.sequences[0].kv_position = 3+ job.new_tokens = 0+ job.max_rq_tokens = 10 ** 6+ job.held_tokens = SeqTensor((1, 0), dtype = torch.long, seq_dim = -1)+ return job+++class TestReceiveSampleGuard(unittest.TestCase):++ def test_unknown_ids_decode_to_empty_text(self):+ gen = FakeGenerator()+ job = bare_job(gen)+ results = []+ for t in (7, VS, V - 1, 10 ** 9, -1):+ eos, tok, rq = job.receive_sample(None, torch.tensor([[t]]), None, None, None, results)+ self.assertFalse(eos)+ self.assertEqual("".join(r.get("text", "") for r in results), "t7") # only the known id contributed text+ self.assertEqual(job.new_tokens, 5)++ def test_first_unknown_id_is_logged_once(self):+ gen = FakeGenerator()+ job = bare_job(gen)+ with self.assertLogs("exllamav3.generator.generator", level = "ERROR") as cm:+ for t in (VS, VS + 1, 10 ** 9):+ job.receive_sample(None, torch.tensor([[t]]), None, None, None, [])+ self.assertEqual(len(cm.output), 1)+ self.assertIn(str(VS), cm.output[0])+++if __name__ == "__main__":+ unittest.main()