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
from __future__ import annotations
import json
import logging
import os
import time
import torch
from ..model import cuda_graph as _cuda_graph
try:
from ..modules.moe_fused import check_barrier as _moe_fused_check # fused MoE half-layer grid barrier: raise if it ever timed out
except Exception: # noqa: BLE001
_moe_fused_check = None
from ..model.model import Model
from ..cache.cache import Cache
from ..cache.recurrent import RecurrentCache
from ..tokenizer.tokenizer import Tokenizer
from ..constants import PAGE_SIZE
from .draft_depth import DraftDepth
from ..util import cuda_sync_active
logger = 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_trim
from ..util.disk_store import env_dir as _disk_env_dir
from .pagetable import PageTable, is_content_hash
from .cpu_cache import CPUPageCache
from .draft_confidence import DraftConfidenceCalibrator
from . import chunk_il
from . import prefill_share
from .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
# once the results are handed out; every iterate / cancel / clear_queue runs it first, so later work sees the same cache state in
# the same order (exact by construction). Pays where the stash is a blocking copy (HIP .cpu(), CUDA EXL3_TAIL_PIN=0).
_REPLY_FIRST = os.environ.get("EXL3_REPLY_FIRST", "0") == "1"
_LAG1_DEBUG = os.environ.get("EXL3_LAG1_DEBUG", "0") == "1"
_LAG1 = os.environ.get("EXL3_LAG1", "0") == "1" # lag-1 decode pipeline (see Generator._gen_lag1)
from . import spec_sample
from .filter import Filter
from .row_groups import plan_groups, group_rows_cap, plain_rows_verify, GROUPS as ROW_GROUPS
from ..util.row_inv import ROW_INV
from concurrent.futures import ThreadPoolExecutor
from .sampler import Sampler
from .visualizer import CacheVisualizer
import time
import threading
from ..tokenizer import MMEmbedding
from ..util import profile_opt
from ..ext import exllamav3_ext as ext
from ..modules.gated_delta_net import rewind_batch_begin, rewind_batch_end
# EXL3_MTP_FUSE_CATCHUP: 0 = catch-up draft prefill after each accepted round (old path),
# 1 = fold the catch-up rows into the next draft forward, 2 = same with the R-row union MoE path.
# Unset = auto: 2 when the union MoE is on (EXL3_DEC_MOE_UNION or _DEV), else 0 (1 lost the step 5 A/B).
MTP_FUSE_CATCHUP = None if os.environ.get("EXL3_MTP_FUSE_CATCHUP") is None else \
int(os.environ["EXL3_MTP_FUSE_CATCHUP"])
def _host_lean():
"""EXL3_HOST_LEAN=1: host-side decode-overhead trims (default off). Read per call so one
loaded process can A/B arms at run time. All lean paths keep kernel launches, RNG draw
order and numerics identical; they only batch host readbacks and reuse staging buffers."""
return os.environ.get("EXL3_HOST_LEAN", "0") == "1"
def _lean_verify_job(job, nrows):
"""True when a verify job's per-position sampling inputs are static for the round, so all
positions' sampler kernels can be launched before the first host readback. Restricted to
single-row, single-SS_Argmax (greedy) jobs with no active filters/masks: the RNG draws are
then unused downstream and the consume loop below runs byte-identical bookkeeping."""
if job.forced_ids is not None or job.new_tokens < 0:
return False
if job.device_logit_mask is not None:
return False
if any(getattr(f, "is_active", False) for f in job.filters):
return False
if nrows != 1:
return False
steps = getattr(job.sampler, "steps", None)
return steps is not None and len(steps) == 1 and type(steps[0]).__name__ == "SS_Argmax"
def _mtp_fuse_catchup():
if MTP_FUSE_CATCHUP is not None: return MTP_FUSE_CATCHUP
on = lambda k: os.environ.get(k, "0") != "0"
return 2 if on("EXL3_DEC_MOE_UNION") or on("EXL3_DEC_MOE_UNION_DEV") else 0
def block_table_pages(max_seq_len: int) -> int:
"""Block table width for a batch whose longest sequence reaches max_seq_len tokens: whole pages,
padded to a multiple of 16 so the pinned staging buffers cover a few distinct widths only."""
return ((max_seq_len + PAGE_SIZE - 1) // PAGE_SIZE + 15) // 16 * 16
class Generator:
@staticmethod
def _validate_ngram_drafting_support() -> None:
try:
sam = ext.BC_SAM()
except AttributeError as exc:
raise NotImplementedError(
"N-gram drafting requires the BC_SAM extension binding, which is unavailable on this build."
) from exc
if sam is None:
raise NotImplementedError(
"N-gram drafting requires BC_SAM, which is unavailable on this platform/build."
)
def __init__(
self,
model: Model,
cache: Cache,
tokenizer: Tokenizer,
max_batch_size: int = 256,
max_chunk_size: int | None = None,
max_q_size: int = 8,
draft_model: Model | None = None,
draft_cache: Cache | None = None,
num_draft_tokens: int | None = None,
show_visualizer: bool = False,
enable_defrag: bool = True,
tail_ckpt: int | None = None,
cpu_cache_size: int = 0,
recurrent_cache_size: int = 4 * 1024**3,
recurrent_checkpoint_interval: int = None,
recurrent_checkpoint_interval_pp: int = 32768,
ngram_match_min: int = 0,
dynamic_draft_tokens: bool = False,
draft_confidence: float = 0.4,
record_draft_stats: bool = False,
**kwargs
):
"""
Initialize generator
:param model:
The model (loaded)
:param cache:
Paged cache
:param tokenizer:
Tokenizer
:param max_batch_size:
The maximum number of sequences to process in parallel. The generator will also limit this
dynamically considering the available cache space.
:param max_chunk_size:
Maximum number of tokens to process in parallel during prefill (prompt ingestion). Should not
exceed the model's max_input_len but can be lowered to trade off prompt speed for a shorter
interruption to ongoing jobs when a new job is started. Default: the model's
caps["prefill_chunk_size"] if set, else 2048.
:param max_q_size:
Maximum number of tokens to evaluate per sequence during generation. Leave this at the default
(8) unless there's a good reason to increase it.
:param draft_model:
Draft model. Enables speculative decoding with draft, and must be specified along with
draft_cache. Note that speculative decoding with many parallel jobs is likely not advantageous.
:param draft_cache:
Cache allocated for draft model. Must be same size as main cache.
:param num_draft_tokens:
Number of future tokens to draft. Default is 4 unless the draft model has a preference (e.g.
from DFlash block size)
:param ngram_match_min:
Minimum number of tokens to match for n-gram draft (0 = disabled).
:param dynamic_draft_tokens:
Adapt the per-round draft length to the workload. The draft is cut using drafter confidence
(argmax logit), calibrated online against observed acceptance rates (see draft_confidence). A
DFlash drafter still runs at its fixed diffusion block size and only the verified window shrinks;
AR and MTP drafters stop the drafting loop itself early, saving one drafter forward per pruned
position. The acceptance behavior of the surviving positions is unchanged. Has no effect on n-gram
drafting, whose draft length already adapts through the match length.
:param draft_confidence:
Used with dynamic_draft_tokens and a draft model: target acceptance probability for drafted
positions, evaluated against an online mapping from drafter confidence (argmax logit) to observed
acceptance rates. Scale-free and portable across model pairs. For DFlash (block produced at fixed
cost) the block is cut at the first position whose estimated conditional acceptance drops below
the target. For AR and MTP drafters (one forward per position, and a position only pays off if
everything before it is accepted too) drafting stops when the running product of conditional
estimates - the probability that the next position actually contributes a token - falls below the
target. Lower values keep longer drafts; higher values truncate more aggressively. Ignored for
n-gram drafting.
:param record_draft_stats:
Append (position, window, accepted) per verification round to job.draft_stats, for analysis.
:param show_visualizer:
Open window to render visualization of cache (for debug/demonstration purposes)
:param enable_defrag:
Defragment cache periodically
:param cpu_cache_size:
Size in bytes of a second-tier page cache in pinned system memory, 0 (default) to disable. Complete
K/V pages evicted from the GPU cache are stored there and restored on prompt-cache hits instead of
being recomputed by prefill. Not currently supported in tensor-parallel mode
:param recurrent_cache_size:
Size of recurrent cache, in bytes. Recurrent cache resides in system RAM. Default is 4 GB.
Ignored if model doesn't use recurrent states
:param recurrent_checkpoint_interval:
Minimum number of tokens between recurrent checkpoints in model output and the tail end of
the prompt. Must be a multiple of the page size. Model architecture determines default
:param recurrent_checkpoint_interval_pp]:
Minimum number of tokens between recurrent checkpoints during prompt ingestion. Must be a
multiple of the page size. Default is 32768 tokens
:param kwargs:
"""
self.model = model
self.cache = cache
self.tokenizer = tokenizer
cfg = self.model.config
self.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)
# Paging
self.pagetable = PageTable(self, cache)
# A cache has exactly one owning generator. Record the takeover and refuse to iterate a superseded generator
cache.owner_serial = getattr(cache, "owner_serial", 0) + 1
self.cache_owner_serial = cache.owner_serial
self.max_total_tokens = PAGE_SIZE * self.pagetable.max_pages
self._cache_stats_memo = (None, None)
# Draft model
self.draft_model = draft_model
self.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 head
if draft_model:
assert not ngram_match_min, \
"Cannot use both draft model and n-gram draft."
assert draft_cache is not None, \
"Must supply cache for draft model"
assert draft_cache.max_num_tokens == cache.max_num_tokens, \
"Cache and draft cache must be same size"
assert not draft_model.caps.get("recurrent_states"), \
"Speculative decoding with recurrent draft model not supported."
if num_draft_tokens:
self.num_draft_tokens = num_draft_tokens
else:
self.num_draft_tokens = draft_model.caps.get("default_draft_size", 4)
elif ngram_match_min:
self._validate_ngram_drafting_support()
self.num_draft_tokens = num_draft_tokens if num_draft_tokens is not None else 4
else:
self.num_draft_tokens = 0
self.ngram_match_min = ngram_match_min
self.dynamic_draft = dynamic_draft_tokens and self.num_draft_tokens > 0
self.record_draft_stats = record_draft_stats
# cost-model gate: skip the drafter forward (and the R-row verify) whenever the
# measured speculative rate would not beat plain decode. Opt-in: EXL3_SPEC_GATE=1
self.spec_gate = SpecGate() if (draft_model is not None and
os.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 = None
max_q_size = max(self.num_draft_tokens + 1, max_q_size)
# Chunking/partitioning
self.max_batch_size = max_batch_size
# Default chunk length comes from the model (an architecture may prefer longer chunks when
# its prefill cost is dominated by per-chunk fixed work); EXL3_PREFILL_CHUNK overrides both
if max_chunk_size is None:
max_chunk_size = model.caps.get("prefill_chunk_size", 2048)
if os.environ.get("EXL3_PREFILL_CHUNK"):
max_chunk_size = int(os.environ["EXL3_PREFILL_CHUNK"])
if max_chunk_size > 65535:
raise ValueError(f"prefill chunk of {max_chunk_size} rows is not supported: a forward is limited to 65535 rows (mixer kernel grid.y); lower EXL3_PREFILL_CHUNK / max_chunk_size")
self.max_chunk_size = max_chunk_size
# Constructed chunk size: a caller that lowers max_chunk_size at runtime (decode-priority prefill while other
# jobs decode, e.g. a serving loop) gets exactly that chunk; adaptive big chunks apply only at this size
self.base_chunk_size = max_chunk_size
# Job queues
self.job_serial = 0
self.pending_jobs = []
self.active_jobs = []
self.deferred_jobs = [] # EXL3_REPLY_FIRST: finished jobs not yet released
# Filter threads
self.filter_pool = ThreadPoolExecutor(max_workers = 16)
self.filter_queue = []
# Pinned staging buffer for batched token readback in iterate_gen
self.sample_pinned = None
self.staging_buffers = {}
# Buffers (pinned: the draft loop copies GPU ids here every round, and the
# verify forward re-uploads batch_ids; pageable staging would bounce-copy)
if draft_model or ngram_match_min:
self.draft_input_ids_pinned = torch.empty(
(max_batch_size, 1),
dtype = torch.long,
pin_memory = True
)
self.draft_ids_pinned = torch.empty(
(max_batch_size, self.num_draft_tokens),
dtype = torch.long,
pin_memory = True
)
# CPU page cache tier
self.cpu_page_cache = None
if cpu_cache_size:
tier_caches = [cache] + ([draft_cache] if draft_cache is not None else [])
self.cpu_page_cache = CPUPageCache(tier_caches, cpu_cache_size)
self.cpu_page_cache.attach(self.pagetable)
self.pagetable.cpu_tier = self.cpu_page_cache
# Visualizer
if show_visualizer:
self.visualizer = CacheVisualizer(self.pagetable.max_pages)
else:
self.visualizer = None
# Defrag
self.enable_defrag = enable_defrag
# Exact prompt-end checkpoints (see Job._tail_stash); EXL3_TAIL_CKPT=0 turns them off
self.tail_ckpts = []
# Disk-first default: with the prefix disk tier on (EXL3_PREFIX_DISK_DIR) older checkpoints live on disk, so host RAM
# keeps few tail entries and a recurrent cache of one entry; without it the RAM tier is the only tier (8 / 8 / 4 GiB)
_disk_on = bool(_disk_env_dir())
self.tail_ckpt_max = int(os.environ.get("EXL3_TAIL_CKPT", "2" if _disk_on else "8")) if tail_ckpt is None else int(tail_ckpt)
# Sub-page prompt-tail checkpoints (EXL3_TAIL_SUB, see Job.sub_ckpt_rows): same entry format as tail_ckpts, kept in
# their own list so a long prompt's several entries never push the exact prompt-end checkpoints out. Host memory
# bound = sub_ckpt_max x one checkpoint (142 MiB on the KDA model, 75 MiB on the GDN one), oldest dropped first
self.sub_ckpts = []
self.sub_ckpt_max = max(0, int(os.environ.get("EXL3_TAIL_SUB_MAX", "1" if _disk_on else "8"))) # 0 = keep no sub-page entry
# prompts shorter than this never stash (the stash is 20-40 ms of host copy and 142 MiB per entry)
self.tail_ckpt_min = int(os.environ.get("EXL3_TAIL_MIN", "512"))
# Recurrent cache
# EXL3_RC_GB: host RAM cap of the recurrent checkpoint cache in GiB. Unset = 0 with the disk prefix tier on (the cache
# keeps the entry being stored, evictions spill to disk), else the argument (4 GiB by default). "" = the argument.
_rc_gb = os.environ.get("EXL3_RC_GB")
if _rc_gb is None and _disk_on:
_rc_gb = "0"
if _rc_gb:
recurrent_cache_size = int(float(_rc_gb) * 1024**3)
self.recurrent_cache_size = recurrent_cache_size
if self.model.caps.get("recurrent_states"):
self.recurrent_cache = RecurrentCache(self.model, recurrent_cache_size)
self.recurrent_cache.pagetable = self.pagetable
# The new page table owns every page, so every state slot is ours too
cache.reset_states()
# Limit batch size if cache has recurrent states
self.max_batch_size = min(self.max_batch_size, cache.num_slots)
else:
self.recurrent_cache = None
# Plain-attention model with a bound KVWIN ring: jobs carry a ring-only state (no checkpoints, prefix reuse stays
# page-hash based; a restored prefix has a cold ring that is rebuilt from the quantized pool)
self.ring_states = self.recurrent_cache is None and self.model.kvwin_ring_only() and \
any(getattr(l, "cfg", None) is not None for l in cache.recurrent_layers.values())
if self.ring_states:
cache.reset_states()
self.max_batch_size = min(self.max_batch_size, cache.num_slots)
if recurrent_checkpoint_interval is None:
recurrent_checkpoint_interval = model.caps.get("default_recurrent_checkpoint_interval", 2048)
assert recurrent_checkpoint_interval % PAGE_SIZE == 0 and recurrent_checkpoint_interval % PAGE_SIZE == 0, \
"checkpoint interval must be a multiple of the page size (256)"
def ceil_span(a, b):
return (a + b - 1) // b * b
recurrent_checkpoint_interval = recurrent_checkpoint_interval
self.recurrent_checkpoint_interval = recurrent_checkpoint_interval
self.recurrent_checkpoint_interval_pp = ceil_span(recurrent_checkpoint_interval_pp, self.max_chunk_size)
# Drafting mode
if draft_model is not None and draft_model.caps.get("attach_target"):
draft_model.attach_to(model)
self.dflash_draft = self.draft_model is not None and self.draft_model.caps.get("dflash_draft", False)
self.mtp_draft = self.draft_model is not None and self.draft_model.caps.get("mtp_draft", False)
# Confidence-calibrated draft truncation (draft model + dynamic draft, any mode). For
# DFlash the fixed-size drafted block is truncated before verification; for AR draft
# models and MTP the drafting loop itself stops early, saving drafter forwards. Modes
# whose TP lm_head path returns only the argmax simply never export confidence values,
# leaving the calibrator inert
self.draft_calibrator = None
self._draft_conf_round = None
# Sampled-draft round (spec_sample): (job, sampler params, draft laws per depth) for the next verify
self._spec_round = None
# Lazy drafter KV catch-up: plain 1-row steps do not feed the drafter cache, they park the
# target hidden rows here and the next drafting round (or a flush point) writes them in one pass
self._dkv_pending = None
self.lazy_dkv = os.environ.get("EXL3_LAZY_DKV", "1") == "1"
if self.dynamic_draft and self.draft_model is not None:
self.draft_calibrator = DraftConfidenceCalibrator(draft_confidence)
def wide_prefill_chunks(self) -> tuple[bool, bool]:
"""(attention-only state, fused MoE). attention-only: the recurrent layers are all sliding-window attention rings
(no GDN / KDA state, whose checkpoint cadence the chunk plan protects). fused MoE: CUDA block-sparse MoE layers
with the fused prefill kernel, which gets more rows per expert from wider chunks."""
v = getattr(self, "_wide_prefill_chunks", None)
if v is None:
from ..modules.block_sparse_mlp import BlockSparseMLP
from ..modules.sliding_attn import SlidingAttention
swa_only = all(isinstance(m, SlidingAttention) for m in self.model.get_checkpoint_layers())
moe = not torch.version.hip and any(
isinstance(m, BlockSparseMLP) and getattr(m, "fused_mode_buffers", None) is not None
for m in self.model
)
v = self._wide_prefill_chunks = (swa_only, moe)
return v
def num_remaining_jobs(self):
return len(self.pending_jobs) + len(self.active_jobs)
def num_active_jobs(self):
return len(self.active_jobs)
def num_pending_jobs(self):
return len(self.pending_jobs)
def get_cache_stats(self) -> dict:
"""
Snapshot of cache occupancy and prompt-cache efficiency, intended for status displays.
Returns a dict with:
page_size: tokens per page
max_tokens: total cache capacity, in tokens
used_tokens: tokens in pages referenced by active jobs
cached_tokens: tokens in complete pages that a later or concurrent job could actually reuse: every
page on an unbroken chain down to a root, whether or not an active job currently references it.
Complete pages whose ancestors were evicted (orphans) don't count, since a prefix match walks
the chain from the root
free_tokens: tokens in unreferenced pages holding no reusable content
tier_cached_tokens: reusable tokens held only in the system-memory tier (sysmem K/V cache), by the
same chain rule; 0 without a tier
tier_max_tokens: capacity of the system-memory tier, 0 without one
alloc_pages: cumulative pages claimed by started jobs
alloc_cached_pages: cumulative pages of those that were reused from the prompt cache
alloc_tier_pages: of those, pages restored from the system-memory tier
hit_rate: alloc_cached_pages / alloc_pages, or None before any job has started
tier_hit_rate: alloc_tier_pages / alloc_pages, the part of hit_rate served from the system-memory
tier, or None before any job has started
active_jobs, pending_jobs: current job counts
The chain walk is memoized on a signature of the page tables, so repeated calls between changes are
cheap.
"""
pt = self.pagetable
tier = pt.cpu_tier
# The chain walk is linear in the number of pages, which can be large with a big system-memory
# tier, so it only reruns when something that can change the outcome has moved
signature = (
len(pt.referenced_pages),
len(pt.unreferenced_pages),
sum(1 for h in pt.referenced_pages if is_content_hash(h)),
pt.metrics["alloc_pages"],
pt.metrics["evictions"],
pt.last_defrag_serial,
len(tier) if tier is not None else 0,
(tier.metrics["pushes"], tier.metrics["evictions"]) if tier is not None else None,
)
memo_signature, memo = self._cache_stats_memo
if signature == memo_signature:
return {**memo, "active_jobs": len(self.active_jobs), "pending_jobs": len(self.pending_jobs)}
# prev-hash links of every complete page, per tier
gpu_links = {}
for pages in (pt.referenced_pages, pt.unreferenced_pages):
for h, page in pages.items():
if is_content_hash(h):
gpu_links[h] = page.prev_hash
tier_links = {h: e["prev_hash"] for h, e in tier.entries.items()} if tier is not None else {}
# A page is reusable when its whole chain is present in either tier
resumable = {}
def is_resumable(h):
chain = []
while h is not None and h not in resumable:
chain.append(h)
if h in gpu_links:
h = gpu_links[h]
elif h in tier_links:
h = tier_links[h]
else:
resumable[h] = False
break
result = True if h is None else resumable[h]
for c in chain:
resumable[c] = result
return result
cached = sum(1 for h in gpu_links if is_resumable(h))
tier_cached = sum(1 for h in tier_links if h not in gpu_links and is_resumable(h))
used = len(pt.referenced_pages)
free = sum(1 for h in pt.unreferenced_pages if not is_content_hash(h))
alloc = pt.metrics["alloc_pages"]
alloc_cached = pt.metrics["alloc_cached_pages"]
alloc_tier = pt.metrics["alloc_tier_pages"]
stats = {
"page_size": PAGE_SIZE,
"max_tokens": pt.max_pages * PAGE_SIZE,
"used_tokens": used * PAGE_SIZE,
"cached_tokens": cached * PAGE_SIZE,
"free_tokens": free * PAGE_SIZE,
"tier_cached_tokens": tier_cached * PAGE_SIZE,
"tier_max_tokens": tier.max_slots * PAGE_SIZE if tier is not None else 0,
"alloc_pages": alloc,
"alloc_cached_pages": alloc_cached,
"alloc_tier_pages": alloc_tier,
"hit_rate": alloc_cached / alloc if alloc else None,
"tier_hit_rate": alloc_tier / alloc if alloc else None,
"active_jobs": len(self.active_jobs),
"pending_jobs": len(self.pending_jobs),
}
self._cache_stats_memo = (signature, stats)
return stats
def clear_queue(self):
"""
Abort all active and pending jobs
"""
self.flush_deferred()
num_jobs = self.num_remaining_jobs()
for job in self.active_jobs + self.pending_jobs:
job.deallocate_pages()
self.active_jobs.clear()
self.pending_jobs.clear()
if num_jobs and not self.num_remaining_jobs():
self.on_queue_drained()
def enqueue(
self,
job: Job | list[Job]
) -> int | list[int]:
"""
Adds a job or list of jobs to the queue.
Each job is prepared against this generator before it is appended to the pending queue. Preparation assigns
the current job_serial, hashes prompt pages for later cache lookup, and validates that the request can fit
the configured cache and batch limits. The serial is then incremented and returned to the caller; it is also
included in started, prefill and streaming result dictionaries so clients can correlate events with the
logical request. Requeued jobs keep their original serial number internally so a long generation still
appears as one stream.
returns:
int: (List of) unique serial number(s) for job(s)
"""
if isinstance(job, list):
serials = []
for j in job:
serials.append(self.enqueue(j))
return serials
job.prepare_for_queue(self, self.job_serial)
self.job_serial += 1
self.pending_jobs.append(job)
return job.serial_number
def cancel(
self,
job: Job
):
"""
Cancel a single pending or active job.
Pending jobs are removed before they ever allocate cache pages. Active jobs first release their page
references and recurrent state, then leave active_jobs so future iterations stop sampling them. If the
cancellation drains the generator completely, the page table is defragmented immediately because no active
block tables still depend on the current physical page ordering.
"""
self.flush_deferred()
num_jobs = self.num_remaining_jobs()
if job in self.pending_jobs:
self.pending_jobs.remove(job)
elif job in self.active_jobs:
job.deallocate_pages()
self.active_jobs.remove(job)
if num_jobs and not self.num_remaining_jobs():
self.on_queue_drained()
def flush_deferred(self):
"""
EXL3_REPLY_FIRST: release the jobs that finished in the last iterate() (see _REPLY_FIRST). No-op when none.
"""
if not self.deferred_jobs:
return
jobs, self.deferred_jobs = self.deferred_jobs, []
with torch.inference_mode():
for job in jobs:
job.deallocate_pages()
if not self.num_remaining_jobs():
self.on_queue_drained()
@torch.inference_mode
def iterate(self) -> list[dict]:
self.flush_deferred()
if _TORCH_PROF is not None:
return self._iterate_profiled()
if _CPROF is not None and not _CPROF["done"] and any(j.is_prefill_done() for j in self.active_jobs):
return self._iterate_cprofiled()
results = self._iterate_inner()
if _moe_fused_check is not None:
_moe_fused_check(self.model)
return results
def _iterate_cprofiled(self) -> list[dict]:
"""EXL3_CPROF=SKIP:STEPS:PATH (diagnostic): cProfile of STEPS decode iterations after SKIP of them (host time per function; cuda syncs show where the host waits for the GPU)."""
import cProfile, pstats
st = _CPROF
st["seen"] += 1
if st["seen"] <= st["skip"]:
return self._iterate_inner()
if st["prof"] is None:
st["prof"] = cProfile.Profile(); st["t0"] = time.perf_counter()
st["prof"].enable()
try:
results = self._iterate_inner()
finally:
st["prof"].disable()
st["n"] += 1
if st["n"] == st["steps"]:
wall = time.perf_counter() - st["t0"]
with open(st["path"], "w") as f:
f.write(f"{st['steps']} iterations, wall {wall / st['steps'] * 1000:.2f} ms/iter (profiled-region wall incl. unprofiled gaps)\n")
for key in ("tottime", "cumtime"):
ps = pstats.Stats(st["prof"], stream = f); ps.sort_stats(key).print_stats(45)
st["done"] = True
return results
def _iterate_profiled(self) -> list[dict]:
"""EXL3_TORCH_PROF=JOBS:SKIP:STEPS:PATH (diagnostic): once JOBS requests have been decoding together for SKIP iterations,
profile the next STEPS iterations with the torch profiler and write the kernel table (per iteration) to PATH."""
st = _TORCH_PROF
n = sum(1 for j in self.active_jobs if j.is_prefill_done())
if st["done"] or n != st["jobs"]:
st["seen"] = 0
results = self._iterate_inner()
return results
st["seen"] += 1
if st["seen"] == st["skip"] + 1:
from torch.profiler import profile, ProfilerActivity
st["prof"] = profile(activities = [ProfilerActivity.CPU, ProfilerActivity.CUDA]); st["prof"].__enter__()
st["t0"] = time.perf_counter(); st["n"] = 0
import collections, traceback
st["sites"] = collections.Counter(); st["orig"] = {n: getattr(torch.Tensor, n) for n in ("item", "tolist", "cpu", "numpy")}
def _mk(name, f):
def w(t, *a, **k):
fr = traceback.extract_stack(limit = 2)[0]
st["sites"][f"{name} {os.path.basename(fr.filename)}:{fr.lineno}"] += 1
return f(t, *a, **k)
return w
for _n, _f in st["orig"].items(): setattr(torch.Tensor, _n, _mk(_n, _f))
results = self._iterate_inner()
if st["prof"] is not None:
st["n"] += 1
if st["n"] == st["steps"]:
torch.cuda.synchronize(); wall = time.perf_counter() - st["t0"]; k_ = st["steps"]
st["prof"].__exit__(None, None, None)
if os.environ.get("EXL3_TORCH_PROF_TRACE"): st["prof"].export_chrome_trace(st["path"] + ".trace.json")
for _n, _f in st["orig"].items(): setattr(torch.Tensor, _n, _f)
with open(st["path"] + ".sites", "w") as f:
for site, c in st["sites"].most_common(25): f.write(f"{c / k_:7.1f}/iter {site}\n")
import collections
g = collections.defaultdict(lambda: [0, 0.0])
for e in st["prof"].events():
if e.device_type == torch.autograd.DeviceType.CUDA:
g[e.name[:110]][0] += 1; g[e.name[:110]][1] += e.device_time
busy = sum(v[1] for v in g.values()); k = st["steps"]
with open(st["path"], "w") as f:
f.write(f"jobs={st['jobs']} steps={k} wall {wall / k * 1000:.2f} ms/iter, kernel-sum {busy / k / 1000:.2f} ms/iter, launches/iter {sum(v[0] for v in g.values()) / k:.0f}\n")
for name, (c, t) in sorted(g.items(), key = lambda kv: -kv[1][1])[:40]:
f.write(f"{t / k / 1000:8.3f} ms {c / k:7.1f}/iter {name}\n")
st["prof"] = None; st["done"] = True
return results
def _prefill_profiled(self, job, results):
"""EXL3_PF_PROF=PATH:CALL (diagnostic): torch-profile the CALL-th (0-based) job.prefill() call that ran at least EXL3_PF_PROF_MINROWS (1024) rows
and write the per-kernel table (with the idle gaps between kernels) to PATH, the Chrome trace to PATH.trace.json."""
st = _PF_PROF
k0 = job.sequences[0].kv_position
if st["done"]:
return job.prefill(results)
from torch.profiler import profile, ProfilerActivity
torch.cuda.synchronize()
prof = profile(activities = [ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes = True); prof.__enter__()
from ..ext import exllamav3_ext as _ext
_shapes = []; _orig = _ext.hgemm_recon
def _rec(a, b, c):
_shapes.append((a.numel() // a.shape[-1], a.shape[-1], b.shape[-1], str(c.dtype)))
return _orig(a, b, c)
_ext.hgemm_recon = _rec
t0 = time.perf_counter()
try:
job.prefill(results)
finally:
_ext.hgemm_recon = _orig
torch.cuda.synchronize(); wall = time.perf_counter() - t0
prof.__exit__(None, None, None)
rows = job.sequences[0].kv_position - k0
if rows < int(os.environ.get("EXL3_PF_PROF_MINROWS", "1024")):
return
st["seen"] += 1
if st["seen"] - 1 != st["call"]:
return
st["done"] = True
prof.export_chrome_trace(st["path"] + ".trace.json")
json.dump(_shapes, open(st["path"] + ".shapes.json", "w"))
import collections
g = collections.defaultdict(lambda: [0, 0.0]); ev = []
for e in prof.events():
if e.device_type == torch.autograd.DeviceType.CUDA:
g[e.name[:150]][0] += 1; g[e.name[:150]][1] += e.device_time
busy = sum(v[1] for v in g.values())
with open(st["path"], "w") as f:
f.write(f"rows={rows} kv_start={k0} wall {wall * 1000:.1f} ms, kernel-sum {busy / 1000:.1f} ms, launches {sum(v[0] for v in g.values())}\n")
for name, (c, t) in sorted(g.items(), key = lambda kv: -kv[1][1])[:80]:
f.write(f"{t / 1000:9.3f} ms {c:6d} {name}\n")
def _cil_views(self) -> list:
views = []
for job in self.active_jobs:
seq = job.sequences[0]
done = job.is_prefill_done()
cur = max(seq.kv_position, job.cached_pages * PAGE_SIZE)
if not done and job.time_first_prefill is None:
# no step has run yet: the first one may jump to a tail checkpoint (Job._tail_restore), so a follow-up turn on a
# long cached conversation is SHORT, not "big". Peeked once per job (read-only), else it would be parked for good.
peek = getattr(job, "_cil_peek", None)
if peek is None:
try:
peek = job._tail_peek(seq)
except Exception: # noqa: BLE001
peek = 0
job._cil_peek = peek
cur = max(cur, peek)
left = 0 if done else max(len(seq.sequence_ids) - 1 - cur, 0)
views.append(chunk_il.View(id(job), job.serial_number, left, done,
0 if done else min(left, self.max_chunk_size), seq.kv_position))
return views
def _cil_parked(self) -> list:
"""
EXL3_SCHED_CHUNK_IL=1: chunked-prefill interleave (chunk_il.ChunkPlanner). Returns the jobs that skip their prefill chunk
this step (sets job._cil_skip for the speculation policy, which counts only unparked jobs). Any planner
error switches the interleave off for the process (one warning) and serves as without the flag.
"""
for job in self.active_jobs:
job._cil_skip = False
job._cil_hold = False
base = getattr(self, "base_chunk_size", self.max_chunk_size)
if getattr(self, "_cil_broken", False) or len(self.active_jobs) < 2:
self._cil_plan = None
self.max_chunk_size = base # decode priority lowered it only beside a decode-ready job
if getattr(self, "_cil", None) is not None:
self._cil.solo() # these steps are not interleave time
return []
try:
if getattr(self, "_cil", None) is None:
self._cil = chunk_il.ChunkPlanner()
views = self._cil_views()
self._cil_plan = self._cil.plan_prefill(views)
parked = [j for j in self.active_jobs if id(j) in self._cil_plan.parked and not j.is_prefill_done()]
rows = getattr(self._cil_plan, "chunk_rows", 0)
self.max_chunk_size = min(rows, base) if rows else base # decode priority: a prefill step is short while others decode
except Exception as e: # noqa: BLE001
logging.warning("EXL3_SCHED_CHUNK_IL disabled (%r); serving without it", e)
self._cil_broken, self._cil_plan = True, None
self.max_chunk_size = base
return []
for job in parked:
job._cil_skip = True
return parked
def _cil_hold(self) -> None:
"""Generation round: decode-ready jobs the plan holds this step read as not prefill-done (Job._cil_hold), which every
draft/verify/sample loop already skips. Undone by _cil_release() at the end of iterate()."""
plan = getattr(self, "_cil_plan", None)
if plan is None or plan.mode is None or not chunk_il.chunk_il_enabled():
return
try:
held = self._cil.plan_decode(self._cil_views(), plan)
except Exception as e: # noqa: BLE001
logging.warning("EXL3_SCHED_CHUNK_IL disabled (%r); serving without it", e)
self._cil_broken, self._cil_plan = True, None
return
for job in self.active_jobs:
if id(job) in held:
job._cil_hold = True
job._cil_skip = True
def _cil_release(self) -> None:
if getattr(self, "_cil_plan", None) is None:
return
for job in self.active_jobs:
job._cil_hold = False
def _prefill_round(self, parked, results: list):
"""One prefill chunk for each active job that is not parked. The first token of a job is sampled in the generation round
after this one, so jobs that finish their prefill here all wait for the longest prefill of the step: four sub-agents of one
parent got their first token together, after the sum of the four prefills (4.7 s) instead of one by one (1.4 s for the first).
The round therefore ends at the first job that completes its prefill while other jobs still have chunks to run; the
rest run in the next step (EXL3_PF_FIRST_OUT=0: the whole round every step)."""
stop_early = os.environ.get("EXL3_PF_FIRST_OUT", "1") != "0"
jobs = list(self.active_jobs)
for i, job in enumerate(jobs):
if job in parked:
continue
was_done = job.is_prefill_done()
try:
if _PF_PROF is not None:
self._prefill_profiled(job, results)
else:
job.prefill(results)
except Exception as e:
if os.environ.get("KYO_TURN_TRACE"):
import traceback; traceback.print_exc()
self.reap_failed_job(job, e, results)
continue
if stop_early and not was_done and job.is_prefill_done() and \
any(j in self.active_jobs and j not in parked and not j.is_prefill_done() for j in jobs[i + 1:]):
break
def _iterate_inner(self) -> list[dict]:
"""
Performs inference on available jobs.
:return:
List of dicts:
# Job has started
{
"job": Job - reference to job
"stage": "started"
"identifier": - optional identifier
"serial": int - job serial number
"eos": bool - always False at this stage
}
# Prefill is underway
{
"job": Job - reference to job
"stage": "prefill"
"curr_progress": int - prompt tokens ingested so far
"max_progress": int - total prompt tokens to ingest
"identifier": - optional identifier
"serial": int - job serial number
"eos": bool - always False at this stage
}
# Generation is underway
{
"job": Job - reference to job
"stage": "streaming"
"identifier": - optional identifier
"serial": int - job serial number
"eos": bool - True if stop condition has been met
optional, if eos:
"eos_reason": - one of:
"stop_token" (stop token was reached)
"stop_string" (stop string was completed)
"max_new_tokens" (max_new_tokens reached)
"end_filter" (filter reached end state with eos_after_completed = True)
"loop_detected" (loop detection triggered)
optional, if "eos_reason" == "stop_token":
"eos_triggering_token_id": int
"eos_triggering_token_str": str
optional, if "eos_reason" == "stop_string":
"eos_triggering_string": str
"full_completion": str - full text completion
"new_tokens": int - number of tokens generated
"time_enqueued": float - time from job was enqueued until it started, in seconds
"time_prefill": float - time to first token, in seconds
"time_generate": float - time to last token, in seconds
optional, if SD enabled:
"accepted_draft_tokens": int
"rejected_draft_tokens": int
"text": str - streamed text output. Does not include prefix from healed token, or stop string
"token_ids": torch.Tensor - output tokens, shape (1, n)
"token_probs": torch.Tensor - last sampling probability of output tokens, shape (1, n)
"top_k_tokens": torch.Tensor - shape (1, n, k)
"top_k_probs": torch.Tensor - shape (1, n, k)
"logits": torch.Tensor - shape (1, n, vocab_size)
}
"""
assert self.cache.initialized, \
"Cache tensors were never allocated. Construct the Cache BEFORE calling model.load()"
owner_serial = getattr(self.cache, "owner_serial", None)
if owner_serial is not None and owner_serial != getattr(self, "cache_owner_serial", owner_serial):
# Superseded: drop every job without touching the cache (the new owner may already have
# reused these pages and state slots) and refuse to run
self.pending_jobs.clear()
self.active_jobs.clear()
raise RuntimeError(
"This Generator no longer owns its Cache: a newer Generator was created over the same "
"Cache. Close or discard the old Generator before creating a new one."
)
assert self.draft_cache is None or self.draft_cache.initialized, \
"Draft cache tensors were never allocated. Construct the draft Cache BEFORE calling draft_model.load()"
results = []
_t0 = _ttrace_begin()
self.iterate_start_jobs(results)
_ttrace_end("start_jobs (alloc pages/restore ckpt)", _t0)
# Perform one round of prefill
_t0 = _ttrace_begin()
parked = self._cil_parked() if chunk_il.chunk_il_enabled() else ()
self._prefill_round(parked, results)
_ttrace_end("prefill total", _t0)
# Recurrent checkpoints
_t0 = _ttrace_begin()
if self.recurrent_cache is not None:
self.recurrent_checkpoint()
_ttrace_end("recurrent_checkpoint", _t0)
self._cil_hold()
_t0 = _ttrace_begin()
# Generation with draft model
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:
draft_tokens = self.iterate_draftmodel_dflash_gen(results)
self.iterate_gen(results, draft_tokens)
elif self.mtp_draft and SPEC_PROF:
self._prof_multi_step(results, self.iterate_draftmodel_mtp_gen)
elif self.mtp_draft:
draft_tokens = self.iterate_draftmodel_mtp_gen(results)
self.iterate_gen(results, draft_tokens)
else:
draft_tokens = self.iterate_draftmodel_gen(results)
self.iterate_gen(results, draft_tokens)
# Generation with n-gram draft
elif self.ngram_match_min:
draft_tokens = self.iterate_ngram_gen(results)
self.iterate_gen(results, draft_tokens)
# Regular generation
else:
if not (_LAG1 and self._gen_lag1(results)):
self.iterate_gen(results)
_ttrace_end("generation round", _t0)
# Visualization
if self.visualizer:
self.update_visualizer()
# Finished iteration
self._cil_release()
return results
@torch.inference_mode()
def on_queue_drained(self):
"""
Idle-transition housekeeping: drop recurrent checkpoints stranded by KV eviction, then defragment the
page table (both need/prefer a moment with no active block tables), and return whatever host memory
glibc is retaining from stash/offload churn (issue #277) — sub-threshold residue would otherwise sit
in the arenas for the whole idle period.
"""
if self.recurrent_cache is not None:
self.recurrent_cache.prune_stranded()
self.pagetable.defrag()
# Dynamic expert placement: apply any pending swap sweep now, between generations —
# a placement change perturbs the logits slightly (same expert, different device
# numerics) and must never land mid-stream
from ..modules.block_sparse_mlp_cpu import run_pending_swap_sweeps
run_pending_swap_sweeps(self.model.config.infer_params)
malloc_trim()
def recurrent_checkpoint(self):
for job in self.active_jobs:
job.maybe_stash_recurrent(self.recurrent_cache)
def update_visualizer(self):
chains = []
for job in self.active_jobs:
for seq in job.sequences:
idx = job.serial_number
chain = [page.page_index for page in seq.allocated_pages]
chains.append((idx, chain))
usage = [0] * self.pagetable.max_pages
for page in self.pagetable.all_pages:
usage[page.page_index] = page.kv_position / PAGE_SIZE
self.visualizer.update(chains, usage)
def iterate_draftmodel_gen(self, results: list):
self._draft_conf_round = None
# Get shape of active batch
batch_size = 0
max_seq_len = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
max_seq_len = max(max_seq_len, job.get_max_seq_len() + self.num_draft_tokens + 1)
batch_size += 1
if batch_size == 0:
return None
# Create block index table for batch
max_pages_batch = (max_seq_len + PAGE_SIZE - 1) // PAGE_SIZE
block_index = torch.zeros((batch_size, max_pages_batch), dtype = torch.int32)
cache_seqlens = torch.zeros((batch_size,), dtype = torch.int32)
batch = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
for seq in job.sequences:
seq_block_index = seq.block_index_tensor[:, :max_pages_batch]
block_index[batch:batch+1, :seq_block_index.shape[-1]].copy_(seq_block_index)
cache_seqlens[batch] = seq.kv_position
batch += 1
# Indexed embeddings not supported when drafting
# TODO: Allow multimodal draft model, perhaps with dummy embeddings?
for job in self.active_jobs:
assert not job.embeddings, \
"MM embeddings not supported while using draft model."
# Collect input IDs
input_ids_list = []
for job in self.active_jobs:
if not job.is_prefill_done(): continue
if job.time_first_token is None:
cuda_sync_active()
job.time_first_token = time.time()
job_ids = job.get_input_ids_list()
input_ids_list += job_ids
batch_ids = self.draft_input_ids_pinned[:batch_size, :]
batch_ids.copy_(torch.cat(input_ids_list, dim = 0))
# Greedy sample batched draft tokens. With a confidence calibrator, drafting stops early
window = self.num_draft_tokens
cal = self.draft_calibrator
conf_cols = []
reach = None
for idx in range(window):
batch_logits = self.draft_model.forward(
input_ids = batch_ids,
params = {
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.draft_cache,
"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 piece
if cal is not None:
conf, new_ids = torch.max(batch_logits, dim = -1)
else:
new_ids = torch.argmax(batch_logits, dim = -1)
self.draft_ids_pinned[:batch_size, idx:idx+1].copy_(new_ids)
batch_ids.copy_(new_ids)
cache_seqlens += 1
if cal is not None:
c = conf.float().cpu()
conf_cols.append(c)
est = [cal.estimate(v) for v in c.view(-1).tolist()]
reach = est if reach is None else [r * e for r, e in zip(reach, est)]
if idx + 1 < window and max(reach) < cal.confidence:
window = idx + 1
break
self.draft_model.prefill(
input_ids = batch_ids,
params = {
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.draft_cache,
"cache_seqlens": cache_seqlens
}
)
if conf_cols:
self._draft_conf_round = {
"ids": self.draft_ids_pinned[:batch_size, :window],
"conf": torch.cat(conf_cols, dim = 1),
"window": window,
}
return self.draft_ids_pinned[:, :window]
def clear_prompt_ckpts(self):
"""Drop every prompt-end recurrent checkpoint (host memory, ~142 MiB each)."""
self.tail_ckpts.clear()
self.sub_ckpts.clear()
def _flush_mtp_defer(self, job, with_tail: bool):
"""EXL3_PF_DEFER: run the draft prefill chunks that Job.prefill stashed instead of running them before the first
token. with_tail also writes the draft K/V row of the last prompt token (token L-1 paired with the hidden state
of L-2): the normal first draft round writes that row itself, a deferred first round (plain target step) does not."""
chunks = job.mtp_defer
job.mtp_defer = None
if not chunks:
return
for ids, params in chunks:
self.draft_model.prefill(ids, params)
if with_tail and job.mtp_defer_carry is not None:
seq = job.sequences[0]
pos = job.mtp_defer_end
self.draft_model.prefill(seq.sequence_ids.torch_slice(pos, pos + 1), {
"attn_mode": "flash_attn",
"block_table": seq.prefill_block_table(),
"cache": self.draft_cache,
"cache_seqlens": torch.tensor([pos], dtype = torch.int32),
"target_hidden": job.mtp_defer_carry,
"indexed_embeddings": job.embeddings,
"kv_only": True,
})
def _mtp_defer_gate(self) -> bool:
"""True when the coming round must be a plain target step (first token without the draft prefill).
Otherwise flushes whatever is pending and returns False. Called at the top of the MTP draft round."""
pend = [j for j in self.active_jobs if j.is_prefill_done() and getattr(j, "mtp_defer", None)]
if not pend:
return False
rows = sum(c[0].shape[-1] for j in pend for c in j.mtp_defer)
if len(self.active_jobs) == 1 and not pend[0].mtp_defer_plain and \
rows >= int(os.environ.get("EXL3_PF_DEFER_MIN", "1024")):
pend[0].mtp_defer_plain = True
return True
for j in pend:
self._flush_mtp_defer(j, with_tail = j.mtp_defer_plain)
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
if self._mtp_defer_gate():
return None
self._draft_conf_round = None
# Get shape of active batch
batch_size = 0
max_seq_len = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
max_seq_len = max(max_seq_len, job.get_max_seq_len() + self.num_draft_tokens + 1)
batch_size += 1
if batch_size == 0:
return None
# Create block index table for batch (lean: reuse pinned staging like iterate_gen
# instead of fresh zeros + allocator traffic every round)
max_pages_batch = (max_seq_len + PAGE_SIZE - 1) // PAGE_SIZE
lean_mtp = _host_lean()
if lean_mtp:
block_index = self._staging("draft_block_index", batch_size, max_pages_batch)
block_index.zero_()
cache_seqlens = self._staging("draft_cache_seqlens", batch_size)
cache_seqlens.zero_()
else:
block_index = torch.zeros((batch_size, max_pages_batch), dtype = torch.int32)
cache_seqlens = torch.zeros((batch_size,), dtype = torch.int32)
batch = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
for seq in job.sequences:
seq_block_index = seq.block_index_tensor[:, :max_pages_batch]
block_index[batch:batch+1, :seq_block_index.shape[-1]].copy_(seq_block_index)
cache_seqlens[batch] = seq.kv_position
batch += 1
# Collect input IDs
input_ids_list = []
mtp_hidden_list = []
# EXL3_MTP_FUSE_CATCHUP: a single job's deferred catch-up rows ride in the first draft
# forward (rows K+1..K+A-1, then the new token); batched rounds flush them first
fuse_job = None
for job in self.active_jobs:
if not job.is_prefill_done(): continue
if getattr(job, "mtp_pending", None) is not None:
if batch_size == 1 and job.mtp_last_hidden is not None:
fuse_job = job
else:
self._flush_mtp_pending(job)
for job in self.active_jobs:
if not job.is_prefill_done(): continue
assert len(job.sequences) == 1, "Qwen3.5 MTP drafting does not currently support CFG/multi-sequence jobs"
if job.mtp_last_hidden is None:
# A one-token prompt has no token to prefill before the generation input.
# Run one normal target step first; iterate_gen() will initialize MTP state.
return None
if job.time_first_token is None:
cuda_sync_active()
job.time_first_token = time.time()
job_ids = job.get_input_ids_list()
input_ids_list += job_ids
mtp_hidden_list.append(job.mtp_last_hidden)
batch_ids = self.draft_input_ids_pinned[:batch_size, :]
batch_ids.copy_(torch.cat(input_ids_list, dim = 0))
# Lean: batch_size == 1 is the whole served case; skip a GPU alloc + copy per round.
temp_hidden = mtp_hidden_list[0] if (lean_mtp and len(mtp_hidden_list) == 1) \
else torch.cat(mtp_hidden_list, dim = 0)
n_pend = 0
first_ids = batch_ids
if fuse_job is not None:
pend_ids = fuse_job.mtp_pending[0]
fuse_job.mtp_pending = None
n_pend = pend_ids.shape[-1]
first_ids = torch.cat((pend_ids, batch_ids), dim = 1)
cache_seqlens -= n_pend
# Greedy sample batched draft tokens. As in iterate_draftmodel_gen, drafting stops once
# every row's running product of estimated conditional acceptance probabilities falls
# below the confidence target, keeping the first low-confidence token as the label probe
window = self.num_draft_tokens
cal = self.draft_calibrator
conf_cols = []
reach = None
# A sampled job (T > 0) draws its drafts from the drafter's law under its own sampler (spec_sample)
spec_job = spec_prm = None
if spec_sample.SPEC_SAMPLED and batch_size == 1:
spec_job = next(j for j in self.active_jobs if j.is_prefill_done())
spec_prm = spec_sample.eligible(spec_job)
spec_q = []
if spec_prm is not None:
# Filled depth by depth: a draft policy that stops the loop early (tools/qwen/spec_policy StopDraft) verifies
# a prefix of draft_ids_pinned, whose laws are all recorded by then
self._spec_round = (spec_job, spec_prm, spec_q)
for idx in range(window):
params = {
"target_hidden": temp_hidden,
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.draft_cache,
"cache_seqlens": cache_seqlens,
}
if cal is not None:
params["export_draft_conf"] = True
if spec_prm is not None:
params["export_draft_logits"] = True
if idx == 0 and n_pend and _mtp_fuse_catchup() == 2:
params["dflash_verify"] = True
batch_state = self.draft_model.forward(first_ids if idx == 0 else batch_ids, params)
if idx == 0 and n_pend:
batch_state = batch_state[:, -1:, :]
lm_head = self.model.modules[self.model.logit_layer_idx]
batch_state = lm_head.prepare_for_device(batch_state, params)
new_ids = self.draft_model.sample_from_state(batch_state, params)
if spec_prm is not None:
dl = params.pop("draft_logits", None)
if dl is None:
spec_prm = self._spec_round = None
else:
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)
temp_hidden = batch_state
draft_conf = params.get("draft_conf")
if cal is not None and draft_conf is not None:
c = draft_conf.float().cpu()
conf_cols.append(c)
est = [cal.estimate(v) for v in c.view(-1).tolist()]
reach = est if reach is None else [r * e for r, e in zip(reach, est)]
if idx + 1 < window and max(reach) < cal.confidence:
window = idx + 1
break
if conf_cols and len(conf_cols) == window:
self._draft_conf_round = {
"ids": self.draft_ids_pinned[:batch_size, :window],
"conf": torch.cat(conf_cols, dim = 1),
"window": window,
}
return self.draft_ids_pinned[:, :window]
def _flush_mtp_pending(self, job):
"""Run a deferred MTP catch-up (EXL3_MTP_FUSE_CATCHUP) as its own draft prefill, for rounds
where the next draft forward does not consume it. Restores the exact unfused state."""
pend = getattr(job, "mtp_pending", None)
if pend is None:
return
job.mtp_pending = None
ids, bi, sl = pend
n = ids.shape[-1]
th = job.mtp_last_hidden
if th is None:
return
self.draft_model.prefill(ids, {
"attn_mode": "flash_attn",
"block_table": bi,
"cache": self.draft_cache,
"cache_seqlens": sl,
"target_hidden": th[:, :n, :],
})
job.mtp_last_hidden = th[:, n:n + 1, :].clone()
def _try_defer_dkv(self, draft_tokens, batch_jobs, export_states, cache_seqlens, block_index,
accepted_lengths, completed_jobs, requeuing_jobs, rewound_jobs) -> bool:
if not self.lazy_dkv or draft_tokens is not None or len(batch_jobs) != 1:
return False
job = batch_jobs[0]
if len(job.sequences) != 1 or accepted_lengths != [1] or \
job in completed_jobs or job in requeuing_jobs or id(job) in rewound_jobs:
return False
pend = self._dkv_pending
if pend is not None and pend["job"] != id(job):
self._flush_dkv()
pend = None
rows = [t[:, :1].clone() for t in export_states]
if pend is None:
pend = self._dkv_pending = {"job": id(job), "rows": [[r] for r in rows], "n": 0,
"seqlens": cache_seqlens[:1].clone()}
else:
for acc, r in zip(pend["rows"], rows):
acc.append(r)
pend["n"] += 1
pend["block_table"] = block_index[:1].clone()
if pend["n"] >= 64:
self._flush_dkv()
return True
def _flush_dkv(self):
pend = self._dkv_pending
if pend is None:
return
self._dkv_pending = None
hidden = [torch.cat(acc, dim = 1) for acc in pend["rows"]]
self.draft_model.update_kv_from_target(
target_hidden = hidden,
cache = self.draft_cache,
lengths = [pend["n"]],
params = {"block_table": pend["block_table"], "cache_seqlens": pend["seqlens"]},
)
def _prof_multi_step(self, results: list, draft_fn):
"""EXL3_SPEC_PROF=1: one decode step with a synced record (jobs, drafted width, per-phase seconds, tokens produced); EXL3_SPEC_PROF_FILE appends it as a JSON line."""
gen_jobs = [j for j in self.active_jobs if j.is_prefill_done()]
n0 = [j.new_tokens for j in gen_jobs]
cuda_sync_active()
t0 = time.perf_counter()
_PROF_CUR.clear()
draft_tokens = draft_fn(results)
_PROF_CUR["t_draft_h"] = time.perf_counter() - t0
self.iterate_gen(results, draft_tokens)
cuda_sync_active()
_PROF_CUR.update(t_step = time.perf_counter() - t0, jobs = len(gen_jobs), spec = draft_tokens is not None,
drafted = 0 if draft_tokens is None else int(draft_tokens.shape[-1]),
produced = sum(j.new_tokens - n for j, n in zip(gen_jobs, n0)))
SPEC_PROF_REC.append(dict(_PROF_CUR))
if SPEC_PROF_FILE:
with open(SPEC_PROF_FILE, "a") as f:
f.write(json.dumps(_PROF_CUR) + "\n")
# TODO: Refactor, share code with other draft fns
def _iterate_gated(self, results: list, draft_fn):
"""One decode step under the spec gate: speculative round (drafter + R-row verify) or a plain
batch-1 step. The drafter's context does not depend on it having run: iterate_gen always
exports the target hidden states and update_kv_from_target consumes them, so a skipped
drafter forward costs nothing to catch up. Timed per step (wall clock, synced) so the gate
calibrates itself to the box, the model and the context depth."""
gen_jobs = [j for j in self.active_jobs if j.is_prefill_done()]
gate = self.spec_gate
if self._dkv_pending is not None and (len(gen_jobs) != 1 or id(gen_jobs[0]) != self._dkv_pending["job"]):
self._flush_dkv()
if len(gen_jobs) != 1:
# Batched decode or nothing to decode: keep the old behaviour, no timing
if SPEC_PROF and gen_jobs:
self._prof_multi_step(results, draft_fn)
return
draft_tokens = draft_fn(results) if gen_jobs else None
self.iterate_gen(results, draft_tokens)
return
job = gen_jobs[0]
spec = gate.want_spec()
n0 = job.new_tokens
cuda_sync_active()
t0 = time.perf_counter()
_PROF_CUR.clear()
draft_tokens = draft_fn(results) if spec else None
self.iterate_gen(results, draft_tokens)
cuda_sync_active()
dt = time.perf_counter() - t0
produced = job.new_tokens - n0
if self._dkv_pending is not None and job not in self.active_jobs:
self._flush_dkv()
if SPEC_PROF:
_PROF_CUR.update(t_step = dt, produced = produced, spec = bool(spec),
drafted = 0 if draft_tokens is None else int(draft_tokens.shape[-1]))
SPEC_PROF_REC.append(dict(_PROF_CUR))
if SPEC_PROF_FILE:
with open(SPEC_PROF_FILE, "a") as f:
f.write(json.dumps(dict(_PROF_CUR, jobs = 1)) + "\n")
if spec:
# includes rounds where the drafter ran but -dds truncated the window to nothing
gate.record_spec(dt, produced)
else:
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
# Get shape of active batch
batch_size = 0
max_seq_len = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
max_seq_len = max(
max_seq_len,
job.get_max_seq_len() + self.num_draft_tokens + 1,
job.get_max_seq_len() + self.draft_model.config.block_size + 1
)
batch_size += 1
if batch_size == 0:
return None
# The diffusion drafter always runs at its fixed block size, dynamic window truncates the drafted block
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 batch
max_pages_batch = (max_seq_len + PAGE_SIZE - 1) // PAGE_SIZE
block_index = torch.zeros((batch_size, max_pages_batch), dtype = torch.int32)
cache_seqlens = torch.zeros((batch_size,), dtype = torch.int32)
batch = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
for seq in job.sequences:
seq_block_index = seq.block_index_tensor[:, :max_pages_batch]
block_index[batch:batch+1, :seq_block_index.shape[-1]].copy_(seq_block_index)
cache_seqlens[batch] = seq.kv_position
batch += 1
# Collect input IDs
input_ids_list = []
for job in self.active_jobs:
if not job.is_prefill_done(): continue
if job.time_first_token is None:
cuda_sync_active()
job.time_first_token = time.time()
job_ids = job.get_input_ids_list()
input_ids_list += job_ids
batch_ids = self.draft_input_ids_pinned[:batch_size, :]
batch_ids.copy_(torch.cat(input_ids_list, dim = 0))
# Run draft model
params = {
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.draft_cache,
"cache_seqlens": cache_seqlens,
}
if self.draft_calibrator is not None:
params["export_draft_conf"] = True
self._flush_dkv()
_t0 = _pt()
out_state = self.draft_model.forward(
input_ids = batch_ids,
params = params,
)
_t1 = _pt()
new_ids = self.draft_model.sample_from_state(out_state, params)
_t2 = _pt()
if SPEC_PROF:
_PROF_CUR["t_dfwd"] = _t1 - _t0
_PROF_CUR["t_dsamp"] = _t2 - _t1
# Draft models with a confidence head cap the usable draft length per round;
# 0 means no draft position cleared the threshold, so skip drafting entirely
conf_len = params.get("draft_confidence_len")
if conf_len is not None:
if conf_len == 0:
return None
window = min(window, conf_len)
# Crop out the first token after sampling to keep batch contiguous for lm_head
new_ids = new_ids[:, 1:]
# Confidence-calibrated truncation: cut the batch window at the first position whose
# drafter confidence falls below the calibrated threshold, taking the longest cut across
# rows (jobs wanting less just reject earlier). The full block and
# its scores are kept so iterate_gen can label the verified positions afterwards
draft_conf = params.get("draft_conf")
if self.draft_calibrator is not None and draft_conf is not None:
conf = draft_conf[:batch_size, 1:].float().cpu()
ids_full = new_ids[:batch_size, :].cpu()
thr = self.draft_calibrator.threshold()
below = conf[:, :window] < thr
any_below = below.any(dim = 1)
first_below = below.int().argmax(dim = 1)
cuts = torch.where(any_below, first_below, torch.full_like(first_below, window))
w_used = int(cuts.max().item())
self._draft_conf_round = {"ids": ids_full, "conf": conf, "window": w_used}
if w_used == 0:
return None
window = w_used
self.draft_ids_pinned[:batch_size, :window].copy_(self._bound_draft_ids(new_ids[:batch_size, :window]))
return self.draft_ids_pinned[:, :window]
def iterate_ngram_gen(self, results: list):
# Get shape of active batch
batch_size = 0
max_seq_len = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
max_seq_len = max(max_seq_len, job.get_max_seq_len() + self.num_draft_tokens + 1)
batch_size += 1
if batch_size == 0:
return None
# Generate draft
window = self.num_draft_tokens
draft_ids = []
min_len = window
for job in self.active_jobs:
if not job.is_prefill_done(): continue
d = job.get_ngram_draft(window)
min_len = min(min_len, d.shape[-1])
draft_ids.append(d)
if min_len == 0:
return None
# Trim to minimum length in batch
draft_ids = torch.cat([d[:, :min_len] for d in draft_ids], dim = 0)
return draft_ids
def _staging(self, name, rows: int, width: int | None = None, dtype = torch.int32):
"""
Reusable pinned staging buffer, keyed by name and row width, grown by rows on demand.
"""
key = (name, width)
buf = self.staging_buffers.get(key)
if buf is None or buf.shape[0] < rows:
alloc_rows = max(rows, 32)
shape = (alloc_rows,) if width is None else (alloc_rows, width)
buf = torch.zeros(shape, dtype = dtype, pin_memory = True)
self.staging_buffers[key] = buf
return buf[:rows]
def _row_groups(self, batch_jobs: list, width: int) -> list[tuple[int, int]]:
"""Job ranges of the forwards that carry one multi-job decode step (see row_groups.py). Every range holds at
most the exact-path row count, so each row gets the bits it would get decoded alone."""
return plan_groups([len(job.sequences) for job in batch_jobs], width, group_rows_cap())
def _forward_groups(self, batch_ids: torch.Tensor, params: dict, batch_jobs: list,
groups: list[tuple[int, int]], own_pages: list | None) -> torch.Tensor:
"""One model forward per job group, concatenated in batch order. A group of several rows runs the verify
kernels (params["dflash_verify"]) also when nothing is drafted: the R-row exact paths give each row the bits
of the one-row launch. params["export_states"] of the whole step is rebuilt from the groups' lists."""
logits = []
exports = []
r0 = 0
for j0, j1 in groups:
r1 = r0 + sum(len(job.sequences) for job in batch_jobs[j0:j1])
p = dict(params)
p["block_table"] = params["block_table"][r0:r1]
p["cache_seqlens"] = params["cache_seqlens"][r0:r1]
if params.get("positions") is not None:
p["positions"] = params["positions"][r0:r1]
if params.get("recurrent_states") is not None:
p["recurrent_states"] = params["recurrent_states"][j0:j1]
if own_pages is not None:
p["dflash_table_pages"] = own_pages[r0:r1]
if (r1 - r0) * batch_ids.shape[-1] > 1:
p["dflash_verify"] = True
if r1 - r0 > 1:
p["row_inv_per_seq"] = True # the attention layers run each sequence on its own (Attention.forward)
if len(groups) > 1:
# The reused pinned staging of the embedding upload (modules/embedding.py) is only safe with a sync point
# between two forwards; the forwards of one step follow each other with none, and the next group would
# overwrite the rows the previous one has not copied yet
p["pinned_staging"] = False
logits.append(self.model.forward(input_ids = batch_ids[r0:r1], params = p))
if "export_states" in p:
exports.append(p["export_states"])
r0 = r1
if exports:
params["export_states"] = [torch.cat(parts, dim = 0) for parts in zip(*exports)]
return torch.cat(logits, dim = 0)
# ---------------------------------------------------------------------------------------------------------------------
# Lag-1 decode pipeline (EXL3_LAG1=1). Plain decode (no draft) normally pays one host round trip per step: sample on the
# device -> read the token -> host bookkeeping -> build the next step's inputs -> launch. Here the next step is launched
# from the DEVICE token right after the sampler, before the host reads token k, so the GPU runs step k+1 while the host
# processes token k (one step of lag). The step in flight is adopted by the next call.
# Recurrent (GDN) caches: the step in flight advances every row's recurrent slot in place, in stream order behind the
# sampler of step k. A job that ends at token k leaves a wasted row in that step: its KV write lands in its own pages and its
# slot advances once more, both in stream order ahead of any later reuse (a new job clears / unstashes its slot on the same
# stream; no one reads the finished job's state: the reply-end checkpoint is the only reader and EXL3_TAIL_REPLY keeps the
# regular loop). Checkpoint / stash positions (page boundaries) are kept out of the window where a step is in flight
# (see `ahead` below); prompt-end (EXL3_TAIL_CKPT) and branch (EXL3_BRANCH_CKPT) checkpoints are taken during prefill, which
# always runs the regular loop. MRoPE models (the vision config) stage explicit positions. Row-invariant job groups
# (EXL3_ROW_INV_GROUPS) are cut exactly as iterate_gen cuts them (_lag1_forward).
# The wasted row is not free of numerics: the step carries one row more than the regular loop would, so on kernels that are
# not row-count invariant the other rows of that ONE step can differ in the last bits from the regular loop (identical to the
# regular loop run with that row kept alive for one more step). Jobs ending on a token limit never waste a row.
# Whatever the pipeline cannot do (filters, penalties, forced tokens, healing, banned strings, probs, drafts, EXL3_TAIL_REPLY,
# a job about to hit a token limit, waiting/prefilling jobs, a page boundary, no GPU embedding table) takes the regular loop.
# Needs the whole-forward CUDA graph with the GPU embedding table (cuda_graph.py, EXL3_GPU_EMB) or the eager table (lag_table).
_lag = None
_lag_par = 0
def _lag1_job_ok(self, job) -> bool:
if len(job.sequences) != 1 or job.filters or job.embeddings or job.forced_ids is not None:
return False
if job.new_tokens < 0 or job.checkpoint is not None or job.banned_strings:
return False
if job.return_probs or job.return_top_tokens > 0 or job.sampler.reqs_past_ids:
return False
return True
def _lag1_why(self, why: str) -> bool:
"""Debug (EXL3_LAG1_DEBUG=1): count why a round took the regular loop; always False."""
if _LAG1_DEBUG:
w = self.__dict__.setdefault("_lag_why_n", {})
w[why] = w.get(why, 0) + 1
if sum(w.values()) % 200 == 1:
print(f"[lag1] regular-loop reasons {w}", flush = True)
return False
def _lag1_ready(self) -> bool:
if self.draft_model or self.ngram_match_min or self.visualizer or _TAIL_REPLY_GEN:
return self._lag1_why("draft/ngram/vis/tail_reply_gen")
if self.num_draft_tokens:
return self._lag1_why("draft_tokens")
if _cuda_graph.CUDA_GRAPH_ENABLED and not torch.version.hip:
runner = self.model.__dict__.get("_cuda_graph_runner")
g = getattr(runner, "_gemb", None) if runner is not None else None
return g is not None and g is not False or self._lag1_why("no gpu emb table")
return self.model.lag_table() is not None or self._lag1_why("no lag table")
def _lag1_params(self, jobs, rows_ids_shape, nxt: int):
"""Inputs of the step `nxt` positions after the current host state (0 = now, 1 = the step after the token in flight)."""
par = self._lag_par = self._lag_par ^ 1
n = len(jobs)
max_seq_len = max(job.get_max_seq_len() for job in jobs) + nxt
max_pages_batch = block_table_pages(max_seq_len)
block_index = self._staging(f"block_index_l{par}", n, max_pages_batch)
block_index.zero_()
cache_seqlens = self._staging(f"cache_seqlens_l{par}", n)
for b, job in enumerate(jobs):
seq = job.sequences[0]
bi = seq.block_index_tensor[:, :max_pages_batch]
block_index[b:b + 1, :bi.shape[-1]].copy_(bi)
cache_seqlens[b] = seq.kv_position + nxt
# MRoPE models (the vision config of the Qwen 3.5 family) pass explicit positions; a text-only decode is cache length + the
# job's rope offset, exactly what iterate_gen stages
positions = None
if "mrope" in self.model.caps:
positions = self._staging(f"positions_l{par}", n)
for b, job in enumerate(jobs):
positions[b] = job.sequences[0].kv_position + nxt + job.alt_rope_offset
params = {
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.cache,
"cache_seqlens": cache_seqlens,
"recurrent_states": [job.recurrent_state for job in jobs] if (self.ring_states or self.recurrent_cache is not None) else None,
"indexed_embeddings": [],
"positions": positions,
"recurrent_history": False,
"pinned_staging": True,
"dflash_verify": plain_rows_verify(n, False),
}
return params
def _lag1_forward(self, jobs, ids, params: dict, dev: bool):
"""One decode forward of the lag-1 pipeline. The row-invariant job groups (row_groups.py) are cut exactly as iterate_gen
cuts them: one forward per group, each with its own slice of the step (block table, lengths, positions, recurrent states).
dev: ids is a device tensor (forward_dev, None = the graph declined), else host ids (regular forward)."""
fwd = self.model.forward_dev if dev else (lambda i, p: self.model.forward(input_ids = i, params = p))
if not (len(jobs) > 1 and ROW_GROUPS["on"] and ROW_INV["on"] and self.model.caps.get("row_inv_groups")):
return fwd(ids, params)
groups = self._row_groups(jobs, 1)
logits = []
for j0, j1 in groups:
p = dict(params)
p["block_table"] = params["block_table"][j0:j1]
p["cache_seqlens"] = params["cache_seqlens"][j0:j1]
if params.get("positions") is not None:
p["positions"] = params["positions"][j0:j1]
if params.get("recurrent_states") is not None:
p["recurrent_states"] = params["recurrent_states"][j0:j1]
if j1 - j0 > 1:
p["dflash_verify"] = True
p["row_inv_per_seq"] = True
if len(groups) > 1:
p["pinned_staging"] = False
y = fwd(ids[j0:j1], p)
if y is None:
return None
logits.append(y)
return logits[0] if len(logits) == 1 else torch.cat(logits, dim = 0)
def _gen_lag1(self, results: list) -> bool:
"""One pipelined decode round. Returns False (nothing done) when the regular loop must run this round."""
st = self._lag
if st is None:
if not self._lag1_ready():
return False
jobs = [j for j in self.active_jobs if j.is_prefill_done()]
if not jobs or len(jobs) != len(self.active_jobs) or self.pending_jobs:
return self._lag1_why("no jobs / prefilling / pending")
if not all(self._lag1_job_ok(j) for j in jobs):
return self._lag1_why("job not ok")
# step k from host ids (regular forward; the cuda graph runner takes the ids through its GPU table)
_first = [j for j in jobs if j.time_first_token is None]
if _first:
cuda_sync_active()
for j in _first: j.time_first_token = time.time()
ids_list = []
for job in jobs:
ids_list += job.get_input_ids_list(None, len(ids_list), add_to_cache = True)
batch_ids = torch.cat(ids_list, dim = 0)
if batch_ids.shape[-1] != 1:
return False
params = self._lag1_params(jobs, batch_ids.shape, 0)
logits = self._lag1_forward(jobs, batch_ids, params, False)
else:
self._lag = None
jobs, logits = st["jobs"], st["logits"]
for job in jobs:
if job in self.active_jobs:
job.get_input_ids_list(None, 0, add_to_cache = True) # the token that was fed from the device is on the host now
live = [(i, job) for i, job in enumerate(jobs) if job in self.active_jobs]
if not live:
return True
n_live = len(live)
pinned = self.sample_pinned
if pinned is None or pinned.shape[0] < n_live:
self.sample_pinned = pinned = torch.empty((max(n_live, 32), 1), dtype = torch.long, pin_memory = True)
launched = []
dev_tokens = []
for k, (i, job) in enumerate(live):
job.prepare_logit_mask()
job.prepare_sampling_past_ids()
tl = logits[i:i + 1, :, :]
sampled = job.receive_logits(tl)
nt = sampled[0]
dev_tokens.append(nt.view(1, 1))
pinned[k:k + 1].copy_(nt.view(1, 1), non_blocking = True)
launched.append((job, tl, (pinned[k:k + 1],) + sampled[1:]))
ev = torch.cuda.Event()
ev.record()
# launch the next step from the device tokens, unless something needs the host first
nxt = None
live_jobs = [job for _, job in live]
ahead = (
self._lag1_ready() and not self.pending_jobs and len(live_jobs) == len(self.active_jobs) and
all(self._lag1_job_ok(j) for j in live_jobs)
)
# a step in flight is one launch: with several row groups a group could be declined by the graph after an earlier one
# already advanced its recurrent states, so the pipeline only launches ahead when the step is a single group
if ahead and len(live_jobs) > 1 and ROW_GROUPS["on"] and ROW_INV["on"] and self.model.caps.get("row_inv_groups") and \
len(self._row_groups(live_jobs, 1)) > 1:
ahead = self._lag1_why("several row groups")
if ahead:
for job in live_jobs:
seq = job.sequences[0]
lim = job.max_new_tokens
if (lim is not None and job.new_tokens + 2 > lim) or job.new_tokens + 2 > job.max_rq_tokens:
ahead = False; break
# a recurrent state with a token in flight is one position ahead of the host: keep checkpoint / stash positions
# (page boundaries) out of the window where the next iterate would read it
if self.recurrent_cache is not None and not 3 <= seq.kv_position % PAGE_SIZE <= PAGE_SIZE - 4:
ahead = False; break
if (seq.kv_position + 1) // PAGE_SIZE >= len(seq.allocated_pages) or \
seq.allocated_pages[(seq.kv_position + 1) // PAGE_SIZE].ref_count != 1:
ahead = False; break
if ahead:
ids_dev = torch.cat(dev_tokens, dim = 0).to(torch.long)
params = self._lag1_params(live_jobs, ids_dev.shape, 1)
nlogits = self._lag1_forward(live_jobs, ids_dev, params, True)
if nlogits is not None:
nxt = {"jobs": live_jobs, "logits": nlogits}
ev.synchronize()
completed_jobs = []
requeuing_jobs = []
for job, token_logits, (next_token, next_k_tokens, next_k_probs, next_prob) in launched:
eos, sampled_token, rq = job.receive_sample(token_logits, next_token, next_k_tokens, next_k_probs, next_prob, results)
if job.checkpoint_rewound:
job.checkpoint_rewound = False
if len(job.sequences) == 1 and rq:
requeuing_jobs.append(job)
elif eos:
completed_jobs.append(job)
num_jobs = self.num_remaining_jobs()
for job in completed_jobs + requeuing_jobs:
if _REPLY_FIRST and job not in requeuing_jobs:
self.deferred_jobs.append(job)
else:
job.deallocate_pages()
self.active_jobs.remove(job)
for job in requeuing_jobs:
rq_job = job.prepare_for_requeue()
self.pending_jobs.insert(0, rq_job)
if num_jobs and not self.num_remaining_jobs() and not self.deferred_jobs:
self.on_queue_drained()
self._lag = nxt if self.active_jobs else None
if _LAG1_DEBUG:
c = self._lag_stats = getattr(self, "_lag_stats", [0, 0, 0])
c[0] += 1; c[1] += int(nxt is not None); c[2] += int(st is not None)
if c[0] % 100 == 0:
print(f"[lag1] rounds {c[0]} launched-ahead {c[1]} adopted {c[2]}", flush = True)
return True
def iterate_gen(self, results: list, draft_tokens: torch.Tensor | None = None):
_HP0[0] = time.perf_counter()
# Get shape of active batch
# Only jobs that have finished prefill can participate in token generation. The maximum sequence length
# determines how many cache pages the temporary block table needs for this iteration.
batch_size = 0
max_seq_len = 0
for job in self.active_jobs:
if not job.is_prefill_done(): continue
max_seq_len = max(max_seq_len, job.get_max_seq_len() + self.num_draft_tokens)
batch_size += len(job.sequences)
if batch_size == 0:
return
if draft_tokens is not None:
max_seq_len += draft_tokens.shape[-1]
# Create block index table for batch
# The model sees a compact batch, so build per-row mappings from logical page positions to physical cache
# page indices, along with current cache lengths and optional MRoPE position offsets.
# Block-table width is padded to a multiple of 16 pages so the pinned staging buffers
# cover a few distinct widths only; the extra (zeroed) columns are never dereferenced
# since the kernels bound their reads by the cache lengths
max_pages_batch = block_table_pages(max_seq_len)
block_index = self._staging("block_index", batch_size, max_pages_batch)
block_index.zero_()
cache_seqlens = self._staging("cache_seqlens", batch_size)
# Verify forwards: the block table width each sequence would have if its job ran alone (the MLA
# decode kernel's KV split follows the table width, so a row must not see its neighbour's)
own_pages = None
if draft_tokens is not None:
own_pages = []
for job in self.active_jobs:
if not job.is_prefill_done(): continue
own = block_table_pages(job.get_max_seq_len() + self.num_draft_tokens + draft_tokens.shape[-1])
own_pages += [own] * len(job.sequences)
batch = 0
use_offsets = "mrope" in self.model.caps
positions = self._staging("positions", batch_size) if use_offsets else None
for job in self.active_jobs:
if not job.is_prefill_done(): continue
for seq in job.sequences:
seq_block_index = seq.block_index_tensor[:, :max_pages_batch]
block_index[batch:batch+1, :seq_block_index.shape[-1]].copy_(seq_block_index)
cache_seqlens[batch] = seq.kv_position
if use_offsets:
positions[batch] = seq.kv_position + job.alt_rope_offset
batch += 1
# Collect input IDs and indexed embeddings
# Jobs may contribute multiple sequence rows. logit_mapping records the slice of the model output that
# belongs to each active job, while batch_jobs keeps the corresponding Job objects in compact-batch order.
input_ids_list = []
active_embeddings = []
logit_mapping = []
batch_jobs = []
for job in self.active_jobs:
logit_mapping.append(len(input_ids_list))
if not job.is_prefill_done(): continue
if job.time_first_token is None:
cuda_sync_active()
job.time_first_token = time.time()
job_ids = job.get_input_ids_list(draft_tokens, len(input_ids_list), add_to_cache = True)
input_ids_list += job_ids
batch_jobs.append(job)
active_embeddings += job.embeddings
logit_mapping.append(len(input_ids_list))
ids_width = input_ids_list[0].shape[-1]
if all(ids.shape[-1] == ids_width for ids in input_ids_list):
ids_staging = self._staging("batch_ids", len(input_ids_list), ids_width, torch.long)
batch_ids = torch.cat(input_ids_list, dim = 0, out = ids_staging)
else:
batch_ids = torch.cat(input_ids_list, dim = 0)
# Collect recurrent states for batch
# Recurrent models carry mutable state beside the K/V cache; pass one state object per compact batch job so
# the model can advance or rewind it consistently with accepted draft tokens.
batch_states = None
if self.recurrent_cache is not None or self.ring_states:
batch_states = [job.recurrent_state for job in batch_jobs]
# GPU workload is scheduled here, so launch any sampling filters that can run in the background
for job in batch_jobs:
if job.new_tokens < 0: continue
assert len(job.filter_futures) == 0
for f in job.filters:
if not f.is_active: continue
if f.use_background_worker():
job.filter_futures.append(self.filter_pool.submit(f.get_next_logit_mask))
else:
job.filter_futures.append(None)
# Get logit batch from model. Forward writes new K/V entries into the cache for the supplied positions and
# returns logits for either one target token or a target-plus-draft verification window.
params = {
"attn_mode": "flash_attn",
"block_table": block_index,
"cache": self.cache,
"cache_seqlens": cache_seqlens,
"recurrent_states": batch_states,
"indexed_embeddings": active_embeddings,
"positions": positions,
"recurrent_history": draft_tokens is not None,
"pinned_staging": True,
# marks a real DFlash verify forward (R rows, target model), as opposed to
# any other multi-row call with rows in the same 2..MAX_BSZN range -- prefill routes
# 2-8 tokens to plenty of individual MoE experts, and the draft model's own forward
# has draft_tokens is None too. The four R-row fast paths (block_sparse_mlp.py's MoE
# union branch and dec_norm_route_r's R>1 branch, quant/exl3.py's dec_gemv_r branch,
# sliding_attn.py's qkv gemv_r_multi branch) all require this marker in addition to
# the row-count bound, so they only ever fire on the one call they were verified
# bit-exact against.
"dflash_verify": draft_tokens is not None or plain_rows_verify(batch_ids.shape[0] * batch_ids.shape[1], False),
}
if own_pages is not None:
params["dflash_table_pages"] = own_pages
if self.draft_model:
params.update(self.draft_model.draft_verifier_params)
_tv0 = _pt()
_PROF_CUR["t_pre_h"] = time.perf_counter() - _HP0[0] if SPEC_PROF else 0
groups = None
if len(batch_jobs) > 1 and ROW_GROUPS["on"] and ROW_INV["on"] and self.model.caps.get("row_inv_groups") and not active_embeddings:
groups = self._row_groups(batch_jobs, batch_ids.shape[-1])
if groups is None:
batch_logits = self.model.forward(
input_ids = batch_ids,
params = params,
)
else:
batch_logits = self._forward_groups(batch_ids, params, batch_jobs, groups, own_pages)
_tv1 = _pt()
_HP0[1] = time.perf_counter()
if SPEC_PROF:
_PROF_CUR["t_verify"] = _tv1 - _tv0
_PROF_CUR["R"] = batch_ids.shape[-1]
# Keep only the fields needed below for draft-cache updates and drop the params dict so it cannot extend
# references to recurrent state objects past this iteration.
p_export_states = params.get("export_states")
p_cache_seqlens = params.get("cache_seqlens")
params = None
# Background filters were launched before forward(); synchronous filters run now to overlap CPU work with
# queued GPU execution as much as possible.
for job in batch_jobs:
if job.new_tokens < 0: continue
assert len(job.logit_masks) == 0
for f in job.filters:
if not f.is_active: continue
if f.use_background_worker():
job.logit_masks.append(None)
else:
job.logit_masks.append(f.get_next_logit_mask())
# Prepare past IDs (for sequences that need them for repetition penalty etc.) and logit masks where needed
for job in batch_jobs:
job.prepare_logit_mask()
job.prepare_sampling_past_ids()
# TODO: Batch sampling
# Pass to jobs to sample
# Sampling is still job-by-job. Each accepted token updates job state, may emit a stream result, may finish
# the job, or may request requeueing once the configured per-job token budget is reached.
completed_jobs = []
requeuing_jobs = []
accepted_lengths = []
rewound_jobs = set()
j = 0
# Reject the trailing draft positions after the last accepted token at index i: count them, roll back the
# job's recurrent state and return cache pages to the accepted position
def reject_remainder(job_, j_, i_, batch_states_):
num_rejected = batch_logits.shape[1] - 1 - i_
if num_rejected == 0:
return 0
job_.rejected_draft_tokens += num_rejected
# Rewind recurrent states
if batch_states_ is not None:
_hr = time.perf_counter()
batch_states_[j_].rewind(num_rejected)
_hacc("t_rew_h", _hr)
# Rewind cache position (draft model cache layout is always the same as target)
for seq_ in job_.sequences:
r = num_rejected
while r:
pos = seq_.kv_position + r
page = seq_.allocated_pages[(pos - 1) // PAGE_SIZE]
rp = min(page.kv_position, r)
page.kv_position -= rp
r -= rp
return num_rejected
# The rewinds of all users of this round are launched together after the sampling loop (modules/gated_delta_net.py rewind_batch_begin)
rewind_batch_begin()
try:
# Without a draft, each job samples exactly one independent token, so all sampler chains
# are launched first and the results collected in a second pass: the first collect
# absorbs the whole GPU tail and the remaining reads are cheap, instead of one full
# launch-to-readback round trip per job. Sampler launch order (and with it each job's
# RNG draw) matches the serial loop exactly. Per-job constraints (filters, penalties)
# are unaffected because no job's token depends on another job's result.
if draft_tokens is None and batch_logits.shape[1] == 1:
# Single-token results stage through one pinned buffer and one synchronize, so the
# batch pays one launch-to-readback round trip instead of one per job
pinned = self.sample_pinned
if pinned is None or pinned.shape[0] < batch_size:
self.sample_pinned = pinned = torch.empty(
(max(batch_size, 32), 1), dtype = torch.long, pin_memory = True
)
launched = []
for job, a, b in zip(self.active_jobs, logit_mapping[:-1], logit_mapping[1:]):
if a == b: continue
token_logits = batch_logits[a:b, :, :]
sampled = job.receive_logits(token_logits)
next_token = sampled[0]
if next_token.is_cuda and next_token.numel() == 1:
k = len(launched)
pinned[k:k + 1].copy_(next_token.view(1, 1), non_blocking = True)
sampled = (pinned[k:k + 1],) + sampled[1:]
launched.append((job, token_logits, sampled))
if launched:
torch.cuda.synchronize(batch_logits.device)
for job, token_logits, (next_token, next_k_tokens, next_k_probs, next_prob) in launched:
eos, sampled_token, rq = job.receive_sample(
token_logits,
next_token,
next_k_tokens,
next_k_probs,
next_prob,
results,
)
# Single-token rewinds need no batch cleanup, but the post-batch draft carry update must still be
# suppressed so it doesn't resurrect a stale MTP state
if job.checkpoint_rewound:
job.checkpoint_rewound = False
rewound_jobs.add(id(job))
# Requeue. Requeueing is only supported for single-sequence jobs because the replacement job
# uses the full sequence generated so far as its next prompt.
if len(job.sequences) == 1 and rq:
requeuing_jobs.append(job)
elif eos:
completed_jobs.append(job)
accepted_lengths.append(1)
# With a draft, positions within a job are consumed strictly serially: acceptance of
# position n gates position n+1, and constrained-decoding masks and sampling past IDs
# must advance between positions.
else:
for idx, (job, a, b) in enumerate(zip(self.active_jobs, logit_mapping[:-1], logit_mapping[1:])):
if a == b: continue
job_logits = batch_logits[a:b, :, :]
accepted_length = 1
rejected = 0
if os.environ.get("DFLASH_DEBUG") and draft_tokens is not None:
print(f"[dflash_debug] job.new_tokens={job.new_tokens} j={j} "
f"draft_row={draft_tokens[j].tolist()}")
# Lean: all positions' argmax kernels are independent slices of the already
# computed verify logits, so launch them all before the first host readback.
# One bulk D2H + one synchronize replaces one sync per position; the consume
# loop below is unchanged, so RNG order, accept logic and ids are identical.
npos = batch_logits.shape[1]
# Sampled-draft round: the draft positions take the spec_sample keep / residual rule, only the last
# (bonus) position samples from the target as usual. Applies only to drafts read from the drafter's own
# buffer, for which this round recorded a law per position (a lookup round brings its own tensor of
# copied tokens: a deterministic draft keeps the argmax rule)
spec = None
sr = self._spec_round
if sr is not None and sr[0] is job and draft_tokens is not None and len(sr[2]) >= npos - 1 and \
draft_tokens.data_ptr() == self.draft_ids_pinned.data_ptr():
spec = [(spec_sample.verify(job_logits[0, pi, :], sr[2][pi], int(draft_tokens[j, pi]), sr[1], job.rng),
None, None, None) for pi in range(npos - 1)]
pre = None
if draft_tokens is not None and _host_lean() and _lean_verify_job(job, b - a):
_hs = time.perf_counter()
launched = []
for pi in range(npos):
launched.append(spec[pi] if spec is not None and pi < npos - 1 else
job.receive_logits(job_logits[:, pi:pi + 1, :]))
n_dev = sum(1 for s in launched
if s[0] is not None and s[0].is_cuda and s[0].numel() == 1)
if n_dev == len(launched):
stage = self._staging("verify_sample", n_dev, 1, torch.long)
for k, s in enumerate(launched):
stage[k:k + 1].copy_(s[0].view(1, 1), non_blocking = True)
torch.cuda.synchronize(batch_logits.device)
# Clone: the staging rows are reused next round, but the job
# keeps references (sequence_ids / held_tokens) to sampled tokens.
pre = [(stage[k:k + 1].clone(),) + s[1:] for k, s in enumerate(launched)]
else:
pre = None
_hacc("t_samp_h", _hs)
typ = None
# EXL3_SPEC_TYPICAL_LOOKUP: arm "0" keeps copied drafts exact; default "rep" refuses the relaxed rule (rep_refused, below) for a draft that
# completes an n-gram the job already repeated in its own output. The probe still logs every draft.
typ_relax = draft_tokens is not None and spec_sample.relax_allowed(self, draft_tokens, j) \
and not (spec_sample.phase_answer_only() and spec_sample.in_think(self, job))
if draft_tokens is not None and spec is None and (spec_sample.typical_on() or spec_sample.PTAP) \
and npos > 1 and not self.dflash_draft:
_tp = spec_sample.eligible(job)
if _tp is not None:
_dr = [int(draft_tokens[j, pi]) for pi in range(npos - 1)]
typ = (spec_sample.typical_rows(job_logits[0, :npos - 1, :], _dr, _tp, spec_sample.TYP_EPS, spec_sample.TYP_DELTA), _dr)
if spec_sample.PTAP:
import json as _json
with open(spec_sample.PTAP, "a") as _f:
_f.write(_json.dumps({"src": "mtp", "p_draft": typ[0][0], "entropy": typ[0][1]}) + "\n")
for i in range(batch_logits.shape[1]):
token_logits = job_logits[:, i:i + 1, :]
if pre is not None:
next_token, next_k_tokens, next_k_probs, next_prob = pre[i]
elif spec is not None and i < npos - 1:
next_token, next_k_tokens, next_k_probs, next_prob = spec[i]
else:
next_token, next_k_tokens, next_k_probs, next_prob = job.receive_logits(
token_logits,
)
if typ is not None and typ_relax and spec_sample.typical_on() and i < npos - 1 and typ[0][2][i] and int(next_token.view(-1)[0]) != typ[1][i] \
and not spec_sample.cd_armed(job) and not spec_sample.rep_refused(job, typ[1][i]):
next_token = torch.full_like(next_token, typ[1][i])
eos, sampled_token, rq = job.receive_sample(
token_logits,
next_token,
next_k_tokens,
next_k_probs,
next_prob,
results,
)
if os.environ.get("DFLASH_DEBUG") and draft_tokens is not None:
dt = draft_tokens[j, i].item() if i < draft_tokens.shape[-1] else None
print(f"[dflash_debug] i={i} sampled={sampled_token.item()} draft_tok={dt}")
# Requeue. Requeueing is only supported for single-sequence jobs because the replacement job
# uses the full sequence generated so far as its next prompt. Unconsumed draft positions must
# be rejected here so the recurrent state and page positions match the accepted sequence
# before the requeue stash.
if len(job.sequences) == 1 and rq:
if draft_tokens is not None:
rejected = reject_remainder(job, j, i, batch_states)
requeuing_jobs.append(job)
break
# EOS. Stop sampling this job immediately once a stop condition, filter condition or max
# token limit produces an EOS event. Draft positions from the EOS position onward were fed
# to verification but never resolved; count them as rejected so accepted + rejected equals
# the number of drafted positions (no cache/state rollback needed, the pages are released).
# The EOS stream event was already built inside receive_sample, so patch its counter too
if eos:
num_unresolved = batch_logits.shape[1] - 1 - i if draft_tokens is not None else 0
# EXL3_TAIL_REPLY: roll the recurrent state and page positions back to the accepted
# position (as a rejection would) so the finished job can stash an exact reply-end tail
if _TAIL_REPLY_GEN and draft_tokens is not None and batch_states is not None \
and len(job.sequences) == 1:
batch_states[j].rewind(num_unresolved) # rewind(0) too: it normalises the per-token history
r_ = num_unresolved
seq_ = job.sequences[0]
while r_:
page = seq_.allocated_pages[(seq_.kv_position + r_ - 1) // PAGE_SIZE]
rp = min(page.kv_position, r_)
page.kv_position -= rp
r_ -= rp
if num_unresolved:
job.rejected_draft_tokens += num_unresolved
for r_ in reversed(results):
if r_.get("eos") and r_["job"] is job:
if "rejected_draft_tokens" in r_:
r_["rejected_draft_tokens"] = job.rejected_draft_tokens
break
completed_jobs.append(job)
break
# A banned-string match inside receive_sample just rewound the job, resetting cache pages and
# rolling back or replacing any recurrent state. The remaining logit positions extend a
# sequence that no longer exists, so abandon them; everything is already consistent, and the
# usual rejection rollback and state normalization must not run on top of the rewind.
if job.checkpoint_rewound:
job.checkpoint_rewound = False
rewound_jobs.add(id(job))
if draft_tokens is not None:
job.rejected_draft_tokens += batch_logits.shape[1] - 1 - i
rejected = -1
break
# Continue sampling from logit batch as long as result matches draft, unless hitting
# checkpoint mark. For speculative decoding, consume additional logits only while the
# sampled target token matches the draft token. A recurrent checkpoint boundary also stops
# draft acceptance so state can be stashed at an exact page boundary.
if draft_tokens is not None and i < batch_logits.shape[1] - 1:
cp_boundary = batch_states is not None and job.is_checkpoint_boundary()
if draft_tokens[j, i].item() != sampled_token.item() or cp_boundary:
rejected = reject_remainder(job, j, i, batch_states)
break
# Accept draft token
else:
job.accepted_draft_tokens += 1
accepted_length += 1
# Advance filters
for f in job.filters:
if not f.is_active: continue
if f.use_background_worker():
job.filter_futures.append(self.filter_pool.submit(f.get_next_logit_mask))
else:
job.logit_masks.append(f.get_next_logit_mask())
job.filter_futures.append(None)
# Update masks and past IDs
job.prepare_logit_mask()
job.prepare_sampling_past_ids()
# Make sure outgoing state is valid if entire draft was accepted
if batch_states and draft_tokens is not None and rejected == 0:
_hr = time.perf_counter()
batch_states[j].rewind(0)
_hacc("t_rew_h", _hr)
# Record per-round draft stats. Skip abandoned windows (banned-string rewind);
# checkpoint-boundary truncations are rare enough to count as ordinary rejections.
if draft_tokens is not None and rejected != -1:
if self.record_draft_stats:
job.draft_stats.append((
job.new_tokens,
draft_tokens.shape[-1],
accepted_length - 1,
))
accepted_lengths.append(accepted_length)
j += 1
finally:
rewind_batch_end()
# Update the draft-confidence calibration with this round's verification outcomes (any
# draft-model mode)
if self.draft_calibrator is not None and self._draft_conf_round is not None:
st = self._draft_conf_round
self._draft_conf_round = None
cal = self.draft_calibrator
row = 0
for job, a_idx, b_idx in zip(self.active_jobs, logit_mapping[:-1], logit_mapping[1:]):
if a_idx == b_idx: continue
accepted_length = accepted_lengths[row]
conf = st["conf"][row]
ids_full = st["ids"][row]
row += 1
if id(job) in rewound_jobs:
continue
a = accepted_length - 1
for i in range(a):
cal.add_label(conf[i].item(), True)
if a < conf.shape[-1]:
seq = job.sequences[0]
n = len(seq.sequence_ids)
tail = seq.sequence_ids.torch_slice(n - 1, n).item()
cal.add_label(conf[a].item(), ids_full[a].item() == tail)
cal.decay_step()
# Accept new target_hidden if DFlash. DFlash draft models can update their cache from target-model hidden
# states for the tokens accepted above, keeping draft and target cache layouts aligned.
_tk0 = _pt()
if SPEC_PROF: _PROF_CUR["t_post_h"] = time.perf_counter() - _HP0[1]
_hm = time.perf_counter()
if self.dflash_draft and self._try_defer_dkv(
draft_tokens, batch_jobs, p_export_states, p_cache_seqlens, block_index,
accepted_lengths, completed_jobs, requeuing_jobs, rewound_jobs):
pass
elif self.dflash_draft:
self._flush_dkv()
self.draft_model.update_kv_from_target(
target_hidden = p_export_states,
cache = self.draft_cache,
lengths = accepted_lengths,
params = {
"block_table": block_index,
"cache_seqlens": p_cache_seqlens,
}
)
if SPEC_PROF:
_PROF_CUR["t_kvup"] = _pt() - _tk0
_PROF_CUR["t_post"] = _tk0 - _tv1
# Accept new target_hidden if MTP. MTP draft models can update their cache from target-model hidden
# states for the tokens accepted above, keeping draft and target cache layouts aligned.
if self.mtp_draft:
target_hidden = p_export_states[-1]
accepted_idx = 0
for job in batch_jobs:
self._flush_mtp_pending(job)
for job, a_idx, b_idx in zip(self.active_jobs, logit_mapping[:-1], logit_mapping[1:]):
if a_idx == b_idx:
continue
accepted_length = accepted_lengths[accepted_idx]
accepted_idx += 1
# A banned-string rewind invalidated this job's carry; leave it unset so drafting pauses until the
# next target forward provides a fresh one, and don't propagate hidden states from the abandoned
# window into the draft cache
if id(job) in rewound_jobs:
continue
# Position K was drafted from the last target state already. Replace accepted
# speculative positions K+1..K+A-1 with the corresponding target-state inputs.
# EXL3_MTP_FUSE_CATCHUP: defer these rows into the next draft forward (one R=A
# draft-head pass instead of a catch-up prefill plus a 1-row draft pass). Only the
# draft cache and draft ids depend on it; target ids are unaffected.
if accepted_length > 1 and _mtp_fuse_catchup() and len(job.sequences) == 1 and \
job not in completed_jobs and job not in requeuing_jobs:
job.mtp_pending = (
batch_ids[a_idx:b_idx, 1:accepted_length].clone(),
block_index[a_idx:b_idx].clone(),
p_cache_seqlens[a_idx:b_idx] + 1,
)
job.mtp_last_hidden = target_hidden[a_idx:b_idx, :accepted_length, :].clone()
continue
if accepted_length > 1:
self.draft_model.prefill(
batch_ids[a_idx:b_idx, 1:accepted_length],
{
"attn_mode": "flash_attn",
"block_table": block_index[a_idx:b_idx],
"cache": self.draft_cache,
"cache_seqlens": p_cache_seqlens[a_idx:b_idx] + 1,
"target_hidden": target_hidden[a_idx:b_idx, :accepted_length - 1, :],
},
)
# The next unprocessed token is paired with the preceding target hidden state.
job.mtp_last_hidden = target_hidden[
a_idx:b_idx, accepted_length - 1:accepted_length, :
].clone()
_hacc("t_mtp_h", _hm)
# Release pages for completed jobs. Finished and requeued jobs no longer need their active page references.
# Requeued recurrent jobs may stash the last checkpoint first so the next queued job can resume from cached
# recurrent state.
num_jobs = self.num_remaining_jobs()
for job in completed_jobs + requeuing_jobs:
if job in requeuing_jobs and self.recurrent_cache is not None:
job.maybe_stash_recurrent(self.recurrent_cache, PAGE_SIZE)
if _REPLY_FIRST and job not in requeuing_jobs:
self.deferred_jobs.append(job) # released by flush_deferred() after the results are out
else:
job.deallocate_pages()
self.active_jobs.remove(job)
# Requeue jobs. Puts replacement jobs at the front so long generations continue promptly after they yield
# their cache pages.
for job in requeuing_jobs:
rq_job = job.prepare_for_requeue()
self.pending_jobs.insert(0, rq_job)
# Defrag. Physical page indices can only be compacted when no active block tables are using them.
if num_jobs and not self.num_remaining_jobs() and not self.deferred_jobs:
self.on_queue_drained()
def reap_failed_job(self, job, error, results: list):
"""
Contain a per-job failure so the generator stays usable for other jobs: release the
failed job's pages and recurrent state, drop it from the active set, and append an
error result carrying the standard serial/stage/eos fields. The async wrapper
delivers the raw exception to that job's consumer only (AsyncJob.__aiter__ re-raises
queued exceptions) and the sync generate() API raises it, instead of the failure
escaping to _run_iteration, which latches AsyncGenerator.error permanently and kills
the iteration task for every job.
"""
try:
job.deallocate_pages()
except Exception:
logger.error(
"reap_failed_job: deallocate_pages() raised while cleaning up failed "
"job %s; pages or recurrent state may be stranded",
job,
exc_info = True,
)
if job in self.active_jobs:
self.active_jobs.remove(job)
results.append({
"job": job,
"serial": job.serial_number,
"stage": "error",
"eos": True,
"error": error,
})
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.
Jobs are considered in queue order, but a job can be skipped temporarily if it would exceed max_batch_size
or needs more fresh pages than are currently unreferenced. Later jobs may start if they fit, which improves
utilization, but each skipped job accumulates a skip count; once any skipped job reaches max_skips, startup
stops for this iteration to preserve approximate queue fairness. Started jobs allocate their cache pages
immediately and emit a "started" event.
"""
# Get current max batch
current_max_batch = 0
for job in self.active_jobs:
current_max_batch += len(job.sequences)
# Start new jobs if possible
if (self.pagetable.num_unreferenced_pages() and
len(self.pending_jobs) and
current_max_batch < self.max_batch_size):
skipped_jobs = []
for job in self.pending_jobs.copy():
if (len(job.sequences) + current_max_batch > self.max_batch_size or
job.current_new_pages_required() > self.pagetable.num_unreferenced_pages()):
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 times
for j in skipped_jobs:
if j.skips >= j.max_skips:
return
for j in skipped_jobs:
j.skips += 1
# Serving hook (the prefix disk restore): the job fits, its pages are allocated right after
hook = getattr(self, "pre_start_hook", None)
if hook is not None:
hook(job)
# Add job to active list
self.pending_jobs.remove(job)
self.active_jobs.append(job)
job.activate()
# Allocate pages for job
try:
job.allocate_pages()
except Exception as e:
self.reap_failed_job(job, e, results)
continue
current_max_batch += len(job.sequences)
r = {
"job": job,
"stage": "started",
"eos": False,
"serial": job.serial_number,
}
if job.identifier is not None:
r.update({ "identifier": job.identifier })
results.append(r)
def generate(
self,
prompt: list[tuple] | list[str] | tuple | str,
max_new_tokens: int | None = None,
min_new_tokens: int = 0,
seed: int | None = None,
sampler: Sampler | list[Sampler] | None = None,
token_healing: bool = False,
encode_special_tokens: bool = False,
decode_special_tokens: bool = False,
stop_conditions: list[int | str] | None = None,
add_bos: bool = False,
abort_event: threading.Event | None = None,
completion_only: bool = False,
filters: list[list[Filter]] | list[Filter] | None = None,
return_last_results: bool = False,
embeddings: list[MMEmbedding] | list[list[MMEmbedding]] | None = None,
max_rq_tokens: int | None = None,
stop_on_loop: tuple[int, int] = None,
**kwargs
):
"""
This is a utility function for easily generating one or more completions from one or more prompt strings. For
more versatility and streaming functionality, use the async wrapper or create Job objects directly, enqueue()
them and call iterate() to receive one token at a time
:param prompt:
If this argument is a list, its length determines the batch size, and the output will be a list of strings
as well. Each prompt is either a string or a pair of prompts for CFG sampling. If CFG is used, sampler
settings must contain cfg_scale.
:param sampler:
Sampler stack settings for all prompts in batch or list of samplers for each prompt.
:param max_new_tokens:
Max number of tokens to generate.
:param min_new_tokens:
Minimum number of tokens to generate before stop tokens become active. Until this number have been
sampled, stop tokens are suppressed but stop strings will still end response.
:param seed:
Seed for the sampling RNG. Doesn't guarantee perfect determinism from the implementation.
:param token_healing:
Apply token healing by regenerating the last token of the input sequence with prefix
constraint.
:param encode_special_tokens:
Encode special tokens (BOS etc.) represented as text in the input. If False, special tokens are
interpreted as text by the tokenizer.
:param decode_special_tokens:
Decode special tokens output by the model. If False, tokens marked as special in the tokenizer
are decoded as empty strings.
:param stop_conditions:
List of strings and/or token IDs that will end generation. The stop condition is not included
in the output.
:param add_bos:
Prepend the tokenizer's specified BOS token to the input.
:param abort_event:
Forwarded to the model during generation. Will abort prefill/context ingestion if triggered.
:param completion_only:
Only return completion. If False, returned string will include the input prompt.
:param filters:
(List of) list of Filters to apply during generation. Each prompt in a batch needs
its own filter list, or a value of None to disable filters for individual prompts.
:param return_last_results:
If True, returns the last results dict for each job
:param embeddings:
Optional list of MMEmbeddings to use for, or list of lists for batched generation
:param max_rq_tokens:
Maximum number of tokens before job is requeued. Rounded to nearest page boundary. This limits how
many new pages are allocated in the cache for the job in any one round and allows a single job to use
the full cache size without limiting concurrency for other jobs.
:param stop_on_loop:
Tuple of (window_size: int, min_reps: int), or None. If enabled, generation will end if the last
window_size tokens sampled make up >= min_reps consecutive instances of a looping string.
:return:
Completion(s): (str or list[str] depending on the type of the input prompt argument)
Optionally, last results: (dict or list[dict] depending on the type of the input prompt argument)
"""
order = {}
if isinstance(prompt, list):
prompts = prompt
else:
prompts = [prompt]
filters = [filters]
embeddings = [embeddings]
if not filters:
filters = [None] * len(prompts)
else:
assert len(filters) == len(prompts) and \
all((f is None or isinstance(f, list)) for f in filters), \
"If using filters, must provide one filter list (or None-value) per prompt."
if not embeddings:
embeddings = [None] * len(prompts)
else:
assert len(embeddings) == len(prompts) and all((isinstance(f, list) or not f) for f in embeddings), \
"Must provide one list of embeddings per prompt."
prompts = prompt if isinstance(prompt, list) else [prompt]
batch_size = len(prompts)
for idx, p in enumerate(prompts):
if isinstance(p, str):
input_ids = self.tokenizer.encode(
p,
encode_special_tokens = encode_special_tokens,
add_bos = add_bos,
embeddings = embeddings[idx]
)
elif isinstance(p, tuple):
input_ids = [self.tokenizer.encode(
p_,
encode_special_tokens = encode_special_tokens,
add_bos = add_bos,
embeddings = embeddings[idx]
) for p_ in p]
else:
assert False, "Unexpected type in prompt"
if sampler is None or isinstance(sampler, Sampler):
p_sampler = sampler
elif isinstance(sampler, list):
assert len(sampler) == len(prompts)
p_sampler = sampler[idx]
else:
assert False, "Unexpected sampler type"
job = Job(
input_ids = input_ids,
max_new_tokens = max_new_tokens,
min_new_tokens = min_new_tokens,
seed = seed,
stop_conditions = stop_conditions,
sampler = p_sampler,
filters = filters[idx] or [],
token_healing = token_healing,
decode_special_tokens = decode_special_tokens,
embeddings = embeddings[idx] or [],
max_rq_tokens = max_rq_tokens,
stop_on_loop = stop_on_loop,
)
if seed is not None: seed += 1
serial = self.enqueue(job)
order[serial] = idx
# Collect outputs until all jobs finish
completions = [""] * batch_size
last_results = [None] * batch_size
while self.num_remaining_jobs():
results = self.iterate()
for r in results:
idx = order[r["serial"]]
if r["stage"] == "error":
# A per-job failure was contained by reap_failed_job; surface the
# original exception to this caller rather than returning a silently
# truncated completion. Jobs from the same batch that are still in
# flight are left to the generator's normal queue handling.
raise r["error"]
if r["stage"] == "streaming":
text = r.get("text", "")
completions[idx] += text
if r["eos"]:
last_results[idx] = r
if abort_event is not None and abort_event.is_set():
self.clear_queue()
return None
# Return results
if not completion_only:
completions = [(p if isinstance(p, str) else p[0]) + c for p, c in zip(prompts, completions)]
if not isinstance(prompt, list):
completions = completions[0]
last_results = last_results[0]
if return_last_results:
return completions, last_results
else:
return completions
_PF_PROF = None
if os.environ.get("EXL3_PF_PROF"):
_pa = os.environ["EXL3_PF_PROF"].rsplit(":", 1)
_PF_PROF = dict(path = _pa[0], call = int(_pa[1]), seen = 0, done = False)
_CPROF = None
if os.environ.get("EXL3_CPROF"):
_cp = os.environ["EXL3_CPROF"].split(":", 2)
_CPROF = dict(skip = int(_cp[0]), steps = int(_cp[1]), path = _cp[2], seen = 0, n = 0, prof = None, done = False)
_TORCH_PROF = None
if os.environ.get("EXL3_TORCH_PROF"):
_a = os.environ["EXL3_TORCH_PROF"].split(":", 3)
_TORCH_PROF = dict(jobs = int(_a[0]), skip = int(_a[1]), steps = int(_a[2]), path = _a[3], seen = 0, done = False, prof = None)
SPEC_PROF = os.environ.get("EXL3_SPEC_PROF") == "1"
SPEC_PROF_REC: list = []
SPEC_PROF_FILE = os.environ.get("EXL3_SPEC_PROF_FILE", "") # multi-job step records, one JSON line each
_PROF_CUR: dict = {}
# host-side phase stamps for EXL3_SPEC_PROF records (t_pre_h / t_post_h / t_rew_h / t_samp_h / t_mtp_h / t_draft_h, wall ms of the host code, no device sync)
_HP0 = [0.0, 0.0]
def _hacc(k, t0):
if SPEC_PROF: _PROF_CUR[k] = _PROF_CUR.get(k, 0.0) + time.perf_counter() - t0
def _pt():
if not SPEC_PROF:
return 0.0
cuda_sync_active()
return time.perf_counter()
class SpecGate:
"""
Cost-model gate for speculative decoding. Keeps EMAs of the plain step time, the
speculative round time and the tokens a round yields, and speculates only while
tokens_per_round / t_round >= 1 / t_plain. In plain mode it probes one speculative round after
`probe` plain steps; a failed probe doubles the interval (up to probe_max), a successful one
switches back to speculation. The first steps measure both arms once.
"""
def __init__(self, alpha: float = None, probe_min: int = None, probe_max: int = None, margin: float = None):
env = os.environ.get
self.alpha = alpha or float(env("EXL3_SPEC_GATE_ALPHA", "0.3"))
self.probe_min = probe_min or int(env("EXL3_SPEC_GATE_PROBE", "4"))
self.probe_max = probe_max or int(env("EXL3_SPEC_GATE_PROBE_MAX", "32"))
self.margin = margin or float(env("EXL3_SPEC_GATE_MARGIN", "1.0"))
self.t_plain = None
self.t_spec = None
self.tok_round = None
self.mode_spec = True
self.probe = self.probe_min
self.since_probe = 0
self.n_spec = 0
self.n_plain = 0
def _ema(self, old, new):
return new if old is None else old + self.alpha * (new - old)
def spec_pays(self) -> bool:
if self.t_plain is None or self.t_spec is None or self.tok_round is None:
return True
return self.tok_round / self.t_spec >= self.margin / self.t_plain
def want_spec(self) -> bool:
if self.t_spec is None:
return True
if self.t_plain is None:
return False
if self.mode_spec:
return True
return self.since_probe >= self.probe
def record_spec(self, dt: float, produced: int):
self.n_spec += 1
if produced <= 0:
return
self.t_spec = self._ema(self.t_spec, dt)
was_probe = not self.mode_spec
self.tok_round = self._ema(self.tok_round, float(produced)) if not was_probe else \
0.5 * (self.tok_round or produced) + 0.5 * produced
pays = self.spec_pays()
if was_probe:
self.since_probe = 0
if pays:
self.mode_spec = True
self.probe = self.probe_min
else:
self.probe = min(self.probe * 2, self.probe_max)
else:
self.mode_spec = pays
def record_plain(self, dt: float, produced: int):
self.n_plain += 1
if produced != 1:
return
self.t_plain = self._ema(self.t_plain, dt)
self.since_probe += 1