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
GDN rewind: one batched launch per round for all users, memoized job descriptors
YanissAmz180d01293ad6
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex 7965c6d..3e86642 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -55,6 +55,7 @@ import threadingfrom ..tokenizer import MMEmbeddingfrom ..util import profile_optfrom ..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.@@ -1761,115 +1762,38 @@ class Generator:r -= rpreturn num_rejected- # 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)- 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,- )+ # 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,@@ -1878,107 +1802,189 @@ class Generator: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}")+ # 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. Unconsumed draft positions must- # be rejected here so the recurrent state and page positions match the accepted sequence- # before the requeue stash.+ # uses the full sequence generated so far as its next prompt.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+ elif eos:completed_jobs.append(job)- break+ accepted_lengths.append(1)- # 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+ # 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- # Accept draft token+ 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:- 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+ pre = None+ _hacc("t_samp_h", _hs)+ 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,+ )+ 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)diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.pyindex 61117b1..4910e88 100644--- a/exllamav3/modules/gated_delta_net.py+++ b/exllamav3/modules/gated_delta_net.py@@ -103,6 +103,23 @@ def _collect_rewind_jobs(layers, slot: int, last_history: int, num_tokens: int):return jobs_by_device+# Rewind batching across the jobs of one speculative round (Generator.iterate_gen): while a round collects, GDNState.rewind() parks its+# job descriptors here instead of launching them, and rewind_batch_end() launches ONE batched conv rewind (and state rewind) for every+# user. The jobs touch disjoint slots and nothing reads a slot between its rewind and the end of the round's sampling loop.+_rw_defer = None+def rewind_batch_begin():+ global _rw_defer+ _rw_defer = {}++def rewind_batch_end():+ global _rw_defer+ d, _rw_defer = _rw_defer, None+ if d: _dispatch_rewind_jobs(d)++# Bumped whenever a layer state (re)allocates or frees its tensors: the memoized rewind job pointers below belong to one allocation+_alloc_epoch = 0++def _dispatch_rewind_jobs(jobs_by_device):for device_index, (conv_jobs, state_jobs) in jobs_by_device.items():if conv_jobs:@@ -167,11 +184,39 @@ class GDNState:self.cache.release_state(self)+ def _rewind_jobs(self, num_tokens: int):+ """The jobs of rewind(num_tokens) for this slot. A cache of GDN layers only has pointer-only job descriptors that depend on+ (slot, last_history, num_tokens, rebase) and the allocation, so they are built once per key and reused (48 layers x 2 tensor+ views x every user and round otherwise); the shared state_base index is still set on every call. Other state classes in the+ cache (and the first call of a key) go through _collect_rewind_jobs."""+ layers = self.cache.get_all_recurrent_layers()+ rebase = _state_rebase()+ key = (self.slot, self.last_history, num_tokens, rebase)+ memo = self.cache.__dict__.setdefault("_rewind_memo", {})+ ent = memo.get(key)+ if ent is not None and ent[0] == _alloc_epoch:+ for l in ent[2]:+ if rebase:+ l._set_base(self.slot, (self.last_history + 1 - num_tokens) if num_tokens > 0 else 0)+ elif _base_value.get((l.cache_id, self.slot), 0) != 0:+ l._set_base(self.slot, 0)+ return ent[1]+ jobs = _collect_rewind_jobs(layers.values(), self.slot, self.last_history, num_tokens)+ if all(isinstance(l, GDNLayerState) for l in layers.values()):+ reps = {}+ for l in layers.values(): reps.setdefault(l.cache_id, l)+ memo[key] = (_alloc_epoch, jobs, list(reps.values()))+ return jobs+def rewind(self, num_tokens: int):if not self.cache.model.loaded_tp:- _dispatch_rewind_jobs(_collect_rewind_jobs(- self.cache.get_all_recurrent_layers().values(), self.slot, self.last_history, num_tokens- ))+ jobs = self._rewind_jobs(num_tokens)+ if _rw_defer is None:+ _dispatch_rewind_jobs(jobs)+ else:+ for dev, (cj, sj) in jobs.items():+ d = _rw_defer.setdefault(dev, ([], []))+ d[0].extend(cj); d[1].extend(sj)else:self.cache.model.tp_dispatch_all(mp_cache_recurrent_rewind, (id(self.cache), self.slot, self.last_history, num_tokens))self.position -= num_tokens@@ -284,6 +329,8 @@ class GDNLayerState:def alloc(self, device):+ global _alloc_epoch+ _alloc_epoch += 1self.conv_state = torch.empty_like(self.conv_state, device = device)self.recurrent_state = torch.empty_like(self.recurrent_state, device = device)self.state_base = _shared_base(self.cache_id, self.max_batch_size, device)@@ -293,6 +340,8 @@ class GDNLayerState:def free(self):+ global _alloc_epoch+ _alloc_epoch += 1self.conv_state = torch.empty_like(self.conv_state, device = "meta")self.recurrent_state = torch.empty_like(self.recurrent_state, device = "meta")self.state_base = torch.empty_like(self.state_base, device = "meta")diff --git a/tests/test_gdn_rewind_batch_.py b/tests/test_gdn_rewind_batch_.pynew file mode 100644index 0000000..f01d2fb--- /dev/null+++ b/tests/test_gdn_rewind_batch_.py@@ -0,0 +1,64 @@+"""+GDN speculative rewind: the batched per-round dispatch (rewind_batch_begin / rewind_batch_end) and the memoized job+descriptors give the same conv and recurrent state, bit for bit, as the per-layer GDNLayerState.rewind() reference,+with the zero-copy rebase on and off. Needs a CUDA device.+"""+import os, sys+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+from types import SimpleNamespace+import torch+from exllamav3.modules import gated_delta_net as gdn++dev = torch.device("cuda:0")+L, SLOTS, HIST, CD = 6, 4, 5, 4+mod = SimpleNamespace(fdim_qkv = 256, conv_kernel_size = CD, num_v_heads = 4, k_head_dim = 32, v_head_dim = 32)++def build(seed):+ g = torch.Generator(device = dev).manual_seed(seed)+ layers = {}+ for i in range(L):+ l = gdn.GDNLayerState(mod, SLOTS, HIST, cache_id = 1000 + seed)+ l.alloc(dev)+ l.conv_state.copy_(torch.randn(l.conv_state.shape, device = dev, generator = g).bfloat16())+ l.recurrent_state.copy_(torch.randn(l.recurrent_state.shape, device = dev, generator = g))+ layers[i] = l+ cache = SimpleNamespace(model = SimpleNamespace(loaded_tp = False), get_all_recurrent_layers = lambda: layers,+ __dict__ = {})+ cache.get_all_recurrent_layers = lambda: layers+ return cache, layers++def snap(layers):+ return [(l.conv_state.clone(), l.recurrent_state.clone(), l.state_base.clone()) for l in layers.values()]++# (slot, last_history, num_tokens) per user of one round; the second round repeats keys to hit the memo+rounds = [[(0, 4, 2), (1, 4, 0), (2, 3, 3)], [(0, 4, 2), (1, 4, 1), (3, 2, 1)], [(0, 4, 2), (1, 4, 0), (2, 3, 3)]]++for rebase in ("0", "1"):+ os.environ["EXL3_STATE_REBASE"] = rebase+ gdn._base_value.clear()+ ref_cache, ref_layers = build(1)+ new_cache, new_layers = build(1)+ for r, users in enumerate(rounds):+ for slot, lh, nt in users: # reference: the per-layer rewind of each user, immediately+ for l in ref_layers.values(): l.rewind(slot, lh, nt)+ # new: GDNState.rewind() deferred to one dispatch, run twice per key to take the memoized path+ gdn.rewind_batch_begin()+ for slot, lh, nt in users:+ st = gdn.GDNState(new_cache, slot, 10, clear = False, test_state = True)+ st.last_history = lh+ st.rewind(nt)+ assert st.position == 10 - nt and st.last_history == 0+ gdn.rewind_batch_end()+ torch.cuda.synchronize()+ for (c0, s0, b0), (c1, s1, b1) in zip(snap(ref_layers), snap(new_layers)):+ assert torch.equal(c0, c1), (rebase, r, "conv")+ assert torch.equal(b0, b1), (rebase, r, "base")+ if rebase == "0":+ assert torch.equal(s0, s1), (rebase, r, "state")+ else: # rebase: the copy is skipped, the committed index moves; compare the committed state of every slot+ for slot in range(SLOTS):+ assert torch.equal(s0[slot, int(b0[slot])], s1[slot, int(b1[slot])]), (rebase, r, slot)+ # immediate dispatch (no batch open) and a changed allocation (epoch) still agree+ for l in new_layers.values(): l.free(); l.alloc(dev)+ assert gdn._rw_defer is None+print("gdn rewind batch: ok")