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
KDA/GDN decode: optional 0-byte speculative rewind (EXL3_STATE_REBASE)
YanissAmza87fffbec904
diff --git a/exllamav3/exllamav3_ext/gdn.cu b/exllamav3/exllamav3_ext/gdn.cuindex 6c29b6e..8b5bb13 100644--- a/exllamav3/exllamav3_ext/gdn.cu+++ b/exllamav3/exllamav3_ext/gdn.cu@@ -454,7 +454,8 @@ void cuda_recurrent_gated_delta_rule_kernelconst float scale,const int* __restrict__ slots, // [bsz]const int history_stride, // max_history + 1- const float* __restrict__ D // [num_v_heads], MAMBA2 only, else nullptr+ const float* __restrict__ D, // [num_v_heads], MAMBA2 only, else nullptr+ const int* __restrict__ state_base // [num_slots], EXL3_STATE_REBASE only, else nullptr){int group = num_v_heads / num_k_heads;@@ -469,6 +470,11 @@ void cuda_recurrent_gated_delta_rule_kernelint state_slot = slots ? slots[bi] : bi;float* slot_state = recurrent_state + (size_t) state_slot * slot_size;float* final_state = slot_state;+ // EXL3_STATE_REBASE: commit index of the slot state. 0 unless a speculative round rewound: the+ // accepted state then lives at history index base without being copied back to index 0. The+ // per-step snapshots are still written to 1..seqlen-1 and the final state to index 0.+ const int state_base_i = state_base ? state_base[state_slot] : 0;+ float* committed_state = slot_state + (size_t) state_base_i * state_size;core_attn_out += bi * seqlen * num_v_heads * v_head_dim;// Indexing@@ -521,13 +527,13 @@ void cuda_recurrent_gated_delta_rule_kernelbool last = (s == seqlen - 1);float* history_r = first ? nullptr : slot_state + (size_t) s * state_size;float* history_w = last ? final_state : slot_state + (size_t) (s + 1) * state_size;- gl_rs_r = first ? final_state + head * (k_head_dim * v_head_dim)- : history_r + head * (k_head_dim * v_head_dim);- gl_rs_w = history_w + head * (k_head_dim * v_head_dim);+ gl_rs_r = first ? committed_state + head * (k_head_dim * v_head_dim)+ : history_r + head * (k_head_dim * v_head_dim);+ gl_rs_w = history_w + head * (k_head_dim * v_head_dim);}else{- gl_rs_r = final_state + head * (k_head_dim * v_head_dim);+ gl_rs_r = committed_state + head * (k_head_dim * v_head_dim);gl_rs_w = gl_rs_r;}@@ -689,7 +695,8 @@ void cuda_recurrent_gated_delta_rule_kernel_128const float scale,const int* __restrict__ slots, // [bsz]const int history_stride, // max_history + 1- const float* __restrict__ D // unused, matches the generic kernel signature+ const float* __restrict__ D, // unused, matches the generic kernel signature+ const int* __restrict__ state_base // [num_slots], EXL3_STATE_REBASE only, else nullptr){#if QWG_ABL_RT@@ -713,6 +720,11 @@ void cuda_recurrent_gated_delta_rule_kernel_128int state_slot = slots ? slots[bi] : bi;float* slot_state = recurrent_state + (size_t) state_slot * slot_size;float* final_state = slot_state;+ // EXL3_STATE_REBASE: commit index of the slot state. 0 unless a speculative round rewound: the+ // accepted state then lives at history index base without being copied back to index 0. The+ // per-step snapshots are still written to 1..seqlen-1 and the final state to index 0.+ const int state_base_i = state_base ? state_base[state_slot] : 0;+ float* committed_state = slot_state + (size_t) state_base_i * state_size;core_attn_out += bi * seqlen * num_v_heads * HEAD_DIM;int t = threadIdx.x;@@ -749,13 +761,13 @@ void cuda_recurrent_gated_delta_rule_kernel_128bool last = (s == seqlen - 1);float* history_r = first ? nullptr : slot_state + (size_t) s * state_size;float* history_w = last ? final_state : slot_state + (size_t) (s + 1) * state_size;- gl_rs_r = first ? final_state + head * HEAD_STATE_SIZE- : history_r + head * HEAD_STATE_SIZE;- gl_rs_w = history_w + head * HEAD_STATE_SIZE;+ gl_rs_r = first ? committed_state + head * HEAD_STATE_SIZE+ : history_r + head * HEAD_STATE_SIZE;+ gl_rs_w = history_w + head * HEAD_STATE_SIZE;}else{- gl_rs_r = final_state + head * HEAD_STATE_SIZE;+ gl_rs_r = committed_state + head * HEAD_STATE_SIZE;gl_rs_w = gl_rs_r;}@@ -893,6 +905,7 @@ void cuda_recurrent_gated_delta_rule_grint v_head_dim,const c10::optional<at::Tensor>& slots,bool history,+ const c10::optional<at::Tensor>& state_base,Graph* graph){@@ -957,6 +970,17 @@ void cuda_recurrent_gated_delta_rule_gr"slots must be on the same device as mixed_qkv");}+ // EXL3_STATE_REBASE: optional per-slot committed-state history index (int32 [num_slots]); nullptr+ // reproduces the pre-rebase read at index 0 exactly.+ TORCH_CHECK_DTYPE_OPT(state_base, kInt);+ const int* state_base_ptr = (const int*) OPTPTR(state_base);+ if (state_base_ptr)+ {+ TORCH_CHECK(state_base.value().dim() == 1, "state_base must be [num_slots]");+ TORCH_CHECK(state_base.value().device() == mixed_qkv.device(),+ "state_base must be on the same device as mixed_qkv");+ }+int v_split = (bsz == 1 && k_head_dim <= 128 && v_head_dim == 128 && num_v_heads <= 64) ? 4 : 1;// KDA (channelwise) decode: v_split 1 by default. With v_split 4 each block reads 128 B slices of 512 B state// rows and only 128 of its 512 threads touch the state: 85 us vs 52 us per layer in scratch/kd3/mb5.py.@@ -996,9 +1020,11 @@ void cuda_recurrent_gated_delta_rule_grscale, \slots_ptr, \history_stride, \- QWG_D_ARG+ QWG_D_ARG, \+ state_base_ptr- // recurrent_state is kernel param 3 and slots is param 12, patched when running in a graph+ // recurrent_state is kernel param 3, slots is param 12 and state_base is param 15, patched when+ // running in a graph#define LAUNCH_RULE(...) \{ \__VA_ARGS__<<<blocks, threads, 0, stream>>>(KERNEL_ARGS); \@@ -1006,6 +1032,7 @@ void cuda_recurrent_gated_delta_rule_gr{ \graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_state, 3); \graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_slots, 12); \+ graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_base, 15); \graph->record_param((void*) &__VA_ARGS__, GP_end, 0); \} \}@@ -1088,12 +1115,13 @@ void cuda_recurrent_gated_delta_ruleint k_head_dim,int v_head_dim,const c10::optional<at::Tensor>& slots,- bool history+ bool history,+ const c10::optional<at::Tensor>& state_base){cuda_recurrent_gated_delta_rule_gr(mixed_qkv, g, beta, recurrent_state, core_attn_out,- num_k_heads, num_v_heads, k_head_dim, v_head_dim, slots, history, nullptr);+ num_k_heads, num_v_heads, k_head_dim, v_head_dim, slots, history, state_base, nullptr);}// Mamba2 decode helper for the BC graph: reads the in_proj output [z, xBC, dt] (float, row@@ -1315,9 +1343,11 @@ void cuda_recurrent_mamba2_grscale, \slots_ptr, \history_stride, \- (const float*) D.data_ptr()+ (const float*) D.data_ptr(), \+ (const int*) nullptr- // recurrent_state is kernel param 3 and slots is param 12, patched when running in a graph+ // recurrent_state is kernel param 3 and slots is param 12, patched when running in a graph;+ // state_base (param 15) is always null here (Mamba2 is out of scope for the rebase)#define LAUNCH_RULE(...) \{ \__VA_ARGS__<<<blocks, threads, 0, stream>>>(KERNEL_ARGS); \@@ -1325,6 +1355,7 @@ void cuda_recurrent_mamba2_gr{ \graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_state, 3); \graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_slots, 12); \+ graph->record_param((void*) &__VA_ARGS__, GP_gdn_rule_base, 15); \graph->record_param((void*) &__VA_ARGS__, GP_end, 0); \} \}diff --git a/exllamav3/exllamav3_ext/gdn.cuh b/exllamav3/exllamav3_ext/gdn.cuhindex 0e916be..289bb3e 100644--- a/exllamav3/exllamav3_ext/gdn.cuh+++ b/exllamav3/exllamav3_ext/gdn.cuh@@ -45,7 +45,8 @@ void cuda_recurrent_gated_delta_ruleint k_head_dim,int v_head_dim,const c10::optional<at::Tensor>& slots,- bool history+ bool history,+ const c10::optional<at::Tensor>& state_base);void cuda_recurrent_gated_delta_rule_gr@@ -61,6 +62,7 @@ void cuda_recurrent_gated_delta_rule_grint v_head_dim,const c10::optional<at::Tensor>& slots,bool history,+ const c10::optional<at::Tensor>& state_base,Graph* graph);diff --git a/exllamav3/exllamav3_ext/graph.cuh b/exllamav3/exllamav3_ext/graph.cuhindex e50f6af..7e40992 100644--- a/exllamav3/exllamav3_ext/graph.cuh+++ b/exllamav3/exllamav3_ext/graph.cuh@@ -70,6 +70,7 @@ enum GraphedParamsGP_conv1d_slots,GP_gdn_rule_state,GP_gdn_rule_slots,+ GP_gdn_rule_base,GP_rope_inv_freq,GP_rope_position,diff --git a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cppindex aaadcac..9125d17 100644--- a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp+++ b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.cpp@@ -55,7 +55,8 @@ void BC_GatedDeltaNet::run_bsz1_bk_head_dim,v_head_dim,c10::nullopt,- false+ false,+ c10::nullopt);norm->run(core_attn_out, core_attn_out_f, z);@@ -219,6 +220,7 @@ void BC_GatedDeltaNetSplit::run_bszN_grat::Tensor& y,at::Tensor& conv_state,at::Tensor& recurrent_state,+ at::Tensor& recurrent_base,const at::Tensor& slots,bool history,Slot& s,@@ -313,6 +315,7 @@ void BC_GatedDeltaNetSplit::run_bszN_grv_head_dim,slots,history,+ recurrent_base,graph);@@ -329,6 +332,7 @@ void BC_GatedDeltaNetSplit::run_bszNat::Tensor& y,at::Tensor& conv_state,at::Tensor& recurrent_state,+ at::Tensor& recurrent_base,const at::Tensor& slots,bool history)@@ -346,7 +350,7 @@ void BC_GatedDeltaNetSplit::run_bszNif (s.graph->disabled || (!s.graph->ready && !s.graph->ready_to_record)){- run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, nullptr);+ run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, nullptr);s.graph->ready_to_record = true;s.graph_state_size = (int) conv_state.size(2);s.graph_hist_stride = (int) recurrent_state.size(1);@@ -359,14 +363,14 @@ void BC_GatedDeltaNetSplit::run_bszNif ((int) conv_state.size(2) != s.graph_state_size ||(int) recurrent_state.size(1) != s.graph_hist_stride){- run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, nullptr);+ run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, nullptr);return;}if (!s.graph->ready){s.graph->capture_begin();- run_bszN_gr(x, y, conv_state, recurrent_state, slots, history, s, s.graph.get());+ run_bszN_gr(x, y, conv_state, recurrent_state, recurrent_base, slots, history, s, s.graph.get());s.graph->capture_end();}@@ -382,6 +386,7 @@ void BC_GatedDeltaNetSplit::run_bszNPPTR(GP_conv1d_slots, (void*) slots.data_ptr()),PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),+ PPTR(GP_gdn_rule_base, (void*) recurrent_base.data_ptr()),PPTR(GP_gemm_C, (void*) y.data_ptr()) // o_proj output};else if (qkvz_ptrs_trellis.has_value() && (int) (x.size(0) * x.size(1)) <= 32)@@ -393,6 +398,7 @@ void BC_GatedDeltaNetSplit::run_bszNPPTR(GP_conv1d_slots, (void*) slots.data_ptr()),PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),+ PPTR(GP_gdn_rule_base, (void*) recurrent_base.data_ptr()),PPTR(GP_gemm_C, (void*) y.data_ptr()) // o_proj output};else@@ -405,6 +411,7 @@ void BC_GatedDeltaNetSplit::run_bszNPPTR(GP_conv1d_slots, (void*) slots.data_ptr()),PPTR(GP_gdn_rule_state, (void*) recurrent_state.data_ptr()),PPTR(GP_gdn_rule_slots, (void*) slots.data_ptr()),+ PPTR(GP_gdn_rule_base, (void*) recurrent_base.data_ptr()),PPTR(GP_gemm_C, (void*) y.data_ptr()) // o_proj output};s.graph->launch(args, stream);diff --git a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.h b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.hindex fd225d8..ab77a00 100644--- a/exllamav3/exllamav3_ext/libtorch/gated_delta_net.h+++ b/exllamav3/exllamav3_ext/libtorch/gated_delta_net.h@@ -333,6 +333,7 @@ struct BC_GatedDeltaNetSplitat::Tensor& y,at::Tensor& conv_state,at::Tensor& recurrent_state,+ at::Tensor& recurrent_base,const at::Tensor& slots,bool history,Slot& s,@@ -345,6 +346,7 @@ struct BC_GatedDeltaNetSplitat::Tensor& y,at::Tensor& conv_state,at::Tensor& recurrent_state,+ at::Tensor& recurrent_base,const at::Tensor& slots,bool history);diff --git a/exllamav3/modules/gated_delta_net.py b/exllamav3/modules/gated_delta_net.pyindex e182db0..0335dda 100644--- a/exllamav3/modules/gated_delta_net.py+++ b/exllamav3/modules/gated_delta_net.py@@ -50,6 +50,24 @@ KDA_KNOBS = {"lr_fused": os.environ.get("EXL3_KDA_DEC_LR_FUSED", "1") != "0",}+# EXL3_STATE_REBASE (default 0): a speculative-round rewind sets a per-slot committed-state history index+# instead of copying the accepted state back to history index 0 (a 0-byte rewind). Read per call so a single+# load can interleave OFF / ON arms. Off: every state_base entry stays 0 and the ext reads index 0 exactly as+# before (the reset below only fires if a previous ON arm left an index set, so the off path stays 0-cost).+def _state_rebase() -> bool:+ return os.environ.get("EXL3_STATE_REBASE", "0") == "1"++# One committed-index tensor shared by every GDN layer of a cache (all layers rewind the same slot by the+# same count, so the index is identical): the rewind then costs ONE tiny write instead of one per layer.+_base_pool = {}+_base_value = {} # (cache_id, slot) -> committed index; the authoritative value behind the shared tensor+def _shared_base(cache_id: int, max_batch_size: int, device):+ t = _base_pool.get(cache_id)+ if t is None or t.device != torch.device(device) or t.numel() != max_batch_size:+ t = torch.zeros((max_batch_size,), dtype = torch.int32, device = device)+ _base_pool[cache_id] = t+ return t+def _collect_rewind_jobs(layers, slot: int, last_history: int, num_tokens: int):"""Split a batch of recurrent-layer states into per-device (conv_jobs, state_jobs) for the@@ -60,8 +78,16 @@ def _collect_rewind_jobs(layers, slot: int, last_history: int, num_tokens: int):batched; any other recurrent-state type sharing the same cache (e.g. SWA, short-conv)falls back to its own .rewind() call, unchanged."""jobs_by_device = {}+ base_done = set()for l in layers:if isinstance(l, GDNLayerState):+ # EXL3_STATE_REBASE: all layers of a cache share one state_base tensor -> set it once per cache+ if l.cache_id not in base_done:+ if _state_rebase():+ l._set_base(slot, (last_history + 1 - num_tokens) if num_tokens > 0 else 0)+ base_done.add(l.cache_id)+ elif _base_value.get((l.cache_id, slot), 0) != 0:+ l._set_base(slot, 0); base_done.add(l.cache_id) # undo an ON arm earlier in a mixed load# l.device may be a plain string ("cuda:0") in some TP contexts rather than a# torch.device, so normalize rather than assume a .index attributedevice_index = torch.device(l.device).index@@ -235,6 +261,15 @@ class GDNLayerState:self.max_history = max_historyself.max_batch_size = max_batch_sizeself.cache_id = cache_id+ # EXL3_STATE_REBASE: per-slot history index of the committed state (shared per cache; _base_value)+ self.state_base = torch.empty((max_batch_size,), dtype = torch.int32, device = "meta")+++ def _set_base(self, slot: int, value: int):+ key = (self.cache_id, slot)+ if _base_value.get(key) != value:+ self.state_base[slot] = value+ _base_value[key] = valuedef get_checkpoint_size(self):@@ -251,6 +286,7 @@ class GDNLayerState:def alloc(self, device):self.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)self.conv_state.zero_()self.recurrent_state.zero_()self.device = device@@ -259,6 +295,7 @@ class GDNLayerState:def free(self):self.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")self.device = None@@ -266,6 +303,7 @@ class GDNLayerState:if self.device is not None:self.conv_state[idx].zero_()self.recurrent_state[idx].zero_()+ self._set_base(idx, 0)def get_state_tensors(self):@@ -277,10 +315,16 @@ class GDNLayerState:def rewind(self, slot: int, last_history: int, num_tokens: int):assert num_tokens <= last_history- if num_tokens > 0:- r_state = self.recurrent_state[slot, 0]- r_state_rewind = self.recurrent_state[slot, last_history + 1 - num_tokens]- r_state.copy_(r_state_rewind)+ if _state_rebase():+ # 0-byte rewind: point the committed state at the accepted history index instead of copying+ self._set_base(slot, (last_history + 1 - num_tokens) if num_tokens > 0 else 0)+ else:+ if _base_value.get((self.cache_id, slot), 0) != 0:+ self._set_base(slot, 0) # a previous ON arm moved the commit index; stock reads index 0+ if num_tokens > 0:+ r_state = self.recurrent_state[slot, 0]+ r_state_rewind = self.recurrent_state[slot, last_history + 1 - num_tokens]+ r_state.copy_(r_state_rewind)cdim = self.module.conv_kernel_sizeif last_history > 0:c_state = self.conv_state[slot, :, :cdim]@@ -309,6 +353,9 @@ class GDNLayerState:def rewind_state_job(self, slot: int, last_history: int, num_tokens: int):"""Job descriptor for the batched recurrent-state rewind kernel (ext.batched_state_rewind),computed without performing any copy. Same gating condition as rewind()'s state branch."""+ if _state_rebase():+ # 0-byte rewind: no copy job; the shared base is set once by _collect_rewind_jobs+ return Noneif num_tokens == 0:return Nonereturn ext.StateRewindJob(@@ -320,8 +367,9 @@ class GDNLayerState:def stash(self, slot, position: int = 0):cdim = self.module.conv_kernel_size+ b = _base_value.get((self.cache_id, slot), 0)return (- self.recurrent_state[slot, :1].cpu(),+ self.recurrent_state[slot, b:b + 1].cpu(),self.conv_state[slot, :, :cdim].cpu())@@ -330,8 +378,9 @@ class GDNLayerState:"""Non-blocking D2H into pinned host tensors, reused from pin_pool ((shape, dtype) -> free list) when given:a pinned allocation costs ~1 ms of host time, more than the blocking copy it replaces."""cdim = self.module.conv_kernel_size+ b = _base_value.get((self.cache_id, slot), 0)out = []- for src in (self.recurrent_state[slot, :1], self.conv_state[slot, :, :cdim]):+ for src in (self.recurrent_state[slot, b:b + 1], self.conv_state[slot, :, :cdim]):free = None if pin_pool is None else pin_pool.get((tuple(src.shape), src.dtype))dst = free.pop() if free else torch.empty(src.shape, dtype = src.dtype, pin_memory = True)dst.copy_(src, non_blocking = True)@@ -343,6 +392,7 @@ class GDNLayerState:cdim = self.module.conv_kernel_sizes, c = stashedself.recurrent_state[slot, :1].copy_(s)+ self._set_base(slot, 0) # restored committed state lands at index 0self.conv_state[slot, :, :cdim].copy_(c)@@ -1438,10 +1488,12 @@ class GatedDeltaNet(Module):else:rsl = rsg[0].cache.get_recurrent_layer(layer_instance)conv_state, recurrent_state = rsl.get_state_tensors()+ recurrent_base = getattr(rsl, "state_base", None)save_state = Trueelse:recurrent_slots = Noneconv_state, recurrent_state = None, None+ recurrent_base = Nonesave_state = Falsesave_history = False # no SD without prior state, for simplicity@@ -1483,7 +1535,7 @@ class GatedDeltaNet(Module):else:self._bc_configure_slot(bsz, seqlen, save_history)y = torch.empty_like(x, dtype = self.out_dtype or torch.half)- self.bc.run_bszN(x, y, conv_state, recurrent_state, recurrent_slots, save_history)+ self.bc.run_bszN(x, y, conv_state, recurrent_state, recurrent_base, recurrent_slots, save_history)if self.tp_reduce:params["backend"].all_reduce(y)return to2(y, out_dtype, self.out_dtype)@@ -1691,6 +1743,7 @@ class GatedDeltaNet(Module):g = g,recurrent_state = recurrent_state,recurrent_slots = recurrent_slots,+ recurrent_base = recurrent_base,history = save_history,save_state = save_state,num_k_heads = self.num_k_heads,diff --git a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.pyindex 6e594d3..0964b00 100644--- a/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py+++ b/exllamav3/modules/gated_delta_net_fn/gated_delta_rule.py@@ -103,6 +103,7 @@ def gated_delta_rule_fn(params: dict = None,channelwise_g: bool = False,g_cumsum: bool = False,+ recurrent_base: torch.Tensor = None,):# g_cumsum: g already holds fla's chunk-local cumsum (EXL3_KDA_G_FUSED); only valid on the chunk pathif params is None:@@ -176,6 +177,7 @@ def gated_delta_rule_fn(v_head_dim,recurrent_slots,history,+ recurrent_base,)return core_attn_out@@ -245,6 +247,7 @@ def gated_delta_rule_fn(v_head_dim,recurrent_slots,history,+ recurrent_base,)return core_attn_out