Skip to content

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.

Attention: share the projections of the sequences in the row-invariant multi-job step

YanissAmz0dfdc38d6700
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index 22abca6..918fd0d 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -17,6 +17,9 @@ from .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_at
# Sliced Q/K/V(/G) projection bundle at decode (one mgemm over equal-width column slices);
# EXL3_QKV_SLICE=0 falls back to the pairwise K/V and Q/G bundles
_qkv_slice_enable = os.environ.get("EXL3_QKV_SLICE", "1") != "0"
+_shared_proj = os.environ.get("EXL3_ATTN_SHARED_PROJ", "1") != "0"
+_shared_check = os.environ.get("EXL3_ATTN_SHARED_CHECK", "0") != "0"
+_SHARED_STATS = [0, 0]
_QKV_IG_MULTI = os.environ.get("EXL3_ATTN_QKV_IG_MULTI", "1") != "0" # (q|gate, k, v one launch)
@@ -681,7 +684,21 @@ class Attention(Module):
seq_params = params.get("row_inv_seq_params")
if seq_params is None:
seq_params = params["row_inv_seq_params"] = split_params_by_sequence(params, bsz)
- x = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
+ if self.shared_proj_ok(params):
+ xs = self.decode_flash_attn_shared(x, bsz, seqlen, params, seq_params)
+ if _shared_check: # debug: the per-sequence blocks as reference, bitwise
+ xr = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
+ _SHARED_STATS[0] += 1
+ if _SHARED_STATS[0] == 1: print("shared-proj check: first call", flush=True)
+ if not torch.equal(xs, xr):
+ _SHARED_STATS[1] += 1
+ if _SHARED_STATS[1] <= 5:
+ print(f"shared-proj MISMATCH layer {self.layer_idx} bsz {bsz} q_len {seqlen} maxdiff {(xs.float() - xr.float()).abs().max().item()}", flush=True)
+ if _SHARED_STATS[0] % 500 == 0:
+ print(f"shared-proj check: {_SHARED_STATS[1]} mismatching of {_SHARED_STATS[0]} calls", flush=True)
+ x = xs
+ else:
+ x = torch.cat([self.decode_flash_attn(x[b:b + 1], 1, seqlen, seq_params[b]) for b in range(bsz)], dim = 0)
else:
x = self.decode_flash_attn(x, bsz, seqlen, params)
case "flash_attn_nc":
@@ -1416,6 +1433,105 @@ class Attention(Module):
return o
+ def shared_proj_ok(self, params: dict) -> bool:
+ """EXL3_ATTN_SHARED_PROJ (default on, ROCm): the row-invariant multi-job step runs the q/k/v and o projections of all
+ sequences in one launch and only the cache update + attention per sequence (decode_flash_attn_shared). CUDA keeps the
+ graph-captured per-sequence block (BC_Attention)."""
+ return (
+ _shared_proj and torch.version.hip is not None and self.num_kv_heads > 0 and
+ params.get("non_causal_spans") is None and not params.get("sim_kvq") and not params.get("kv_only") and
+ params.get("position_ids") is None and not self.tp_reduce
+ )
+
+
+ def decode_flash_attn_shared(self, x: torch.Tensor, bsz: int, seqlen: int, params: dict, seq_params: list):
+ """decode_flash_attn for a row-invariant multi-job step (params["row_inv_per_seq"]) with the projections shared by the
+ sequences. The kernels of the projections, head norms, rope and gates give each row the bits of the one-row launch
+ whatever the row count (util/row_inv.py), so those run once over the bsz * seqlen rows; the parts whose plan follows
+ the batch (the QSA plane update and selection, the paged attention split plan) run once per sequence on one-row
+ slices, exactly as decode_flash_attn(x[b:b+1], ...) does."""
+ cache = params.get("cache")
+ block_table = get_for_device(params, "block_table", self.device)
+ cache_seqlens = get_for_device(params, "cache_seqlens", self.device)
+ position = params.get("position", 0)
+ positions = get_for_device(params, "positions", self.device, None)
+ inv_freq = get_for_device(params, "inv_freq", self.device, None)
+ causal = params.get("causal", True)
+ qsa_layer = qsa_cpu = None
+ if self.qsa_indexer is not None:
+ from ..cache import CacheLayer as _CL
+ qsa_layer = cache if isinstance(cache, _CL) else cache.layers[self.layer_idx, params.get("layer_instance") or 0]
+ qsa_cpu = get_for_device(params, "cache_seqlens", "cpu")
+
+ q, k, v, g = self.project_qkv(x, params)
+ if self.q_norm:
+ if self.tp_span_heads_norm:
+ q, k = self.apply_qk_norms_tp(q, k, params)
+ elif not self.rope or self.q_norm_tensor is None:
+ q = self.q_norm.forward(q, params, out_dtype = torch.half)
+ k = self.k_norm.forward(k, params, out_dtype = torch.half)
+ if self.rope:
+ q, k = self.rope.apply(
+ q, k, position, positions, None, True,
+ self.q_norm_tensor if not self.tp_span_heads_norm else None,
+ self.k_norm_tensor if not self.tp_span_heads_norm else None,
+ self.norm_eps, self.norm_constant_bias, inv_freq,
+ )
+
+ outs = []
+ for b in range(bsz):
+ sl = slice(b, b + 1)
+ bt_b, cs_b = block_table[sl], cache_seqlens[sl]
+ if qsa_cpu is not None:
+ cpu_b = qsa_cpu[sl]
+ sparse = int(cpu_b.max().item()) + seqlen > self.qsa_indexer.sparse_threshold()
+ q_idx = self.qsa_indexer.update_planes(qsa_layer, x[sl], self.rope, bt_b, cpu_b, seq_params[b])
+ else:
+ cpu_b, sparse = None, False
+ if sparse:
+ qsa_layer.update_kv_direct(cs_b, bt_b, k[sl], v[sl], seqlen)
+ outs.append(self.qsa_indexer.sparse_attend_verify(qsa_layer, self, q[sl], q_idx, bt_b, cpu_b))
+ else:
+ max_kv_len = int(cpu_b.max().item()) if cpu_b is not None else None
+ if max_kv_len is None and seqlen > 16 and not torch.version.hip:
+ max_kv_len = int(params["cache_seqlens"][sl].max())
+ # EXL3_VERIFY_ATTN_LOOP: the R-row paged decode as R one-row calls, as decode_flash_attn does
+ rows = range(seqlen) if 1 < seqlen <= MAX_BSZN_GEMV_R and os.environ.get("EXL3_VERIFY_ATTN_LOOP", "0") != "0" else None
+ def call(qq, kk, vv, cs):
+ return attn_dispatch(
+ q = qq, k = kk, v = vv,
+ cache = cache, cache_idx = self.layer_idx, cache_instance = params.get("layer_instance"),
+ block_table = bt_b, cache_seqlens = cs, causal = causal, sm_scale = self.sm_scale,
+ window_size = self.window_arg(), softcap = self.logit_softcapping, non_causal_spans = None,
+ sinks = self.sinks, dispatch_cache = self.dispatch_cache, max_kv_len = max_kv_len,
+ v_dim = self.v_head_dim if self.v_head_dim != self.head_dim else None,
+ )
+ if rows is None:
+ outs.append(call(q[sl], k[sl], v[sl], cs_b))
+ else:
+ outs.append(torch.cat([call(q[sl][:, i:i + 1].contiguous(), k[sl][:, i:i + 1].contiguous(),
+ v[sl][:, i:i + 1].contiguous(), cs_b + i) for i in rows], dim = 1))
+ o = torch.cat(outs, dim = 0)
+
+ if self.headwise_gate:
+ if self.gate_softplus: ext.mul_softplus_broadcast_(o, g)
+ else: ext.mul_sigmoid_broadcast_(o, g)
+ o = o.reshape((bsz, seqlen, self.num_q_heads * self.head_dim))
+ pitch = 0
+ if (self.full_gate or self.interleaved_gate) and self.v_head_dim == self.head_dim and not self.headwise_gate and \
+ o.dtype == torch.half and g.dtype == torch.half and o.is_contiguous() and g.is_contiguous() and \
+ getattr(ext, "mul_sigmoid_pad", None) is not None:
+ pitch = row_pad_pitch(self.o_proj, o.shape[-1], o.numel() // o.shape[-1], params)
+ if pitch:
+ o2 = torch.empty((o.numel() // o.shape[-1], pitch), dtype = torch.half, device = o.device)[:, :o.shape[-1]].view(o.shape)
+ ext.mul_sigmoid_pad(o, g, o2, pitch)
+ o = o2
+ elif self.full_gate or self.interleaved_gate:
+ ext.mul_sigmoid_(o, g)
+
+ return self.project_o(o, bsz, seqlen, params)
+
+
def window_arg(self):
"""window_size argument for attn_dispatch: an int (left window, right bound 0) or an
explicit (left, right) pair when window_right is set."""