Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

feat: W4A8 ARK XPU MoE kernel (int4 weight / int8 compute) with prefill + decode (#2143)

Copilot80b5f874b779
diff --git a/auto_round_extension/ark/auto_round_kernel/__init__.py b/auto_round_extension/ark/auto_round_kernel/__init__.py
index 7d484963d..93be8cba7 100644
--- a/auto_round_extension/ark/auto_round_kernel/__init__.py
+++ b/auto_round_extension/ark/auto_round_kernel/__init__.py
@@ -3488,6 +3488,541 @@ def clear_moe_prefill_workspace_cache() -> None:
_MOE_PREFILL_WORKSPACE_CACHE.clear()
+# ---------------------------------------------------------------------------
+# W4A8 MoE: int4 weights, int8 DPAS compute, dynamically quantized int8
+# activations.
+#
+# The int4 weights are converted ONCE into int8 using ARK's `AUTO_S8` re-scale
+# rule (see `sycl_tla_moe_w4a8.hpp`):
+#
+# sxt[e][n][j] = max_{g in block j} |s[e][n][g]| * 8 / 127
+# w8[e][n][k] = round(w4[e][n][k] * s[e][n][k // group_size] / sxt[...])
+#
+# With the default block (`rescale_group_size=-1`, one scale per output
+# channel) the GEMM runs a single full-K `s8 x s8 -> s32` accumulation with one
+# scalar multiply in the epilogue -- the shape the DPAS pipeline is happiest
+# with. Coarser-than-group blocks are what makes this profitable: an int4
+# group=32 checkpoint would otherwise force an accumulator fold every 32 K
+# elements.
+#
+# `moe_w4a8` keeps the conversion result in a module-level cache keyed on the
+# source tensor identity plus the layout / mutation state and the resolved
+# AUTO_S8 block, so repeated forward passes over the same expert weights pay
+# for it only once. Callers that manage their own storage should use
+# `moe_w4a8_prepack` + `moe_gemm_w4a8` directly.
+#
+# Cache entries are `(weights_s8, wscales, block, weights, scales)`: the source
+# tensors are pinned in the entry because the address half of the key is
+# pointer identity, and a freed-then-reallocated buffer can otherwise land on
+# the same address. Every MoE layer's expert weights share shape / dtype /
+# group_size, so no other key component would catch such a collision.
+# ---------------------------------------------------------------------------
+
+_MOE_W4A8_PREPACK_CACHE: "dict[tuple, tuple]" = {}
+_MOE_W4A8_MAX_ACCUM_K = (2**31 - 1) // (127 * 127)
+
+
+def moe_w4a8_rescale_block_size(K: int, group_size: int, rescale_group_size: int = -1) -> int:
+ """Return the effective AUTO_S8 re-scale block size used by the W4A8 path.
+
+ ``rescale_group_size <= 0`` (the ``group=-1`` spelling) selects one scale
+ per output channel, i.e. a block spanning the whole K axis. Any value that
+ is not a multiple of both ``group_size`` and 64, or that does not divide
+ ``K``, also falls back to ``K``. ``ARK_MOE_W4A8_AUTO_S8`` overrides the
+ argument.
+
+ The result is the divisor of the ``wscales`` last dimension
+ (``K // block``), so callers must use it to size that tensor.
+ """
+ lib = xpu_lib
+ if lib is not None and hasattr(lib, "moe_w4a8_rescale_block_size"):
+ return int(lib.moe_w4a8_rescale_block_size(int(K), int(group_size), int(rescale_group_size)))
+ # Pure-Python mirror of `ark::moe_w4a8::moe_w4a8_rescale_block_size` so the
+ # shape math is available without a loaded extension (tests, docs, CPU).
+ env = os.environ.get("ARK_MOE_W4A8_AUTO_S8")
+ value = int(rescale_group_size)
+ if env is not None:
+ try:
+ value = int(env.strip())
+ except ValueError:
+ pass
+ if K <= 0:
+ return K
+ if value <= 0 or value >= K:
+ return K
+ if group_size > 0 and (value < group_size or value % group_size != 0):
+ return K
+ if K % value != 0 or value % 64 != 0:
+ return K
+ return value
+
+
+def _synchronize_xpu_device(device: torch.device) -> None:
+ if device.type != "xpu":
+ return
+ if device.index is None:
+ torch.xpu.synchronize()
+ else:
+ torch.xpu.synchronize(device.index)
+
+
+def _validate_moe_w4a8_k(K: int, api_name: str) -> None:
+ if K > _MOE_W4A8_MAX_ACCUM_K:
+ raise ValueError(
+ f"{api_name}: K must be <= {_MOE_W4A8_MAX_ACCUM_K} to avoid int32 accumulator overflow (got {K})"
+ )
+
+
+def _require_same_device(tensor: torch.Tensor, reference: torch.Tensor, tensor_name: str, api_name: str) -> None:
+ if tensor.device != reference.device:
+ raise ValueError(f"{api_name}: {tensor_name} must be on {reference.device}, got {tensor.device}")
+
+
+def clear_moe_w4a8_prepack_cache() -> None:
+ """Release every int8 weight/scale pair cached by :func:`moe_w4a8`.
+
+ Synchronizes the cached XPU devices first so queued kernels cannot outlive
+ the cached tensors they still read.
+ """
+ synced = set()
+ for entry in _MOE_W4A8_PREPACK_CACHE.values():
+ device = entry[0].device
+ if device.type != "xpu":
+ continue
+ key = (device.type, device.index)
+ if key in synced:
+ continue
+ _synchronize_xpu_device(device)
+ synced.add(key)
+ _MOE_W4A8_PREPACK_CACHE.clear()
+
+
+def _validate_moe_w4a8_shape(N: int, K: int, group_size: int, api_name: str) -> None:
+ if N % 16 != 0:
+ raise ValueError(f"{api_name}: N must be a multiple of 16 (got {N})")
+ if K % 64 != 0:
+ raise ValueError(f"{api_name}: K must be a multiple of 64 (got {K})")
+ _validate_moe_w4a8_k(K, api_name)
+ if group_size <= 0 or group_size % 8 != 0:
+ raise ValueError(f"{api_name}: group_size must be a positive multiple of 8 (got {group_size})")
+ if K % group_size != 0:
+ raise ValueError(f"{api_name}: K must be a multiple of group_size")
+
+
+def moe_w4a8_prepack(
+ weights: torch.Tensor,
+ scales: torch.Tensor,
+ *,
+ group_size: int = 128,
+ rescale_group_size: int = -1,
+) -> "tuple[torch.Tensor, torch.Tensor, int]":
+ """Convert packed int4-sym MoE weights into the W4A8 int8 representation.
+
+ Applies ARK's ``AUTO_S8`` re-scale on device, producing weights the int8
+ DPAS grouped GEMM / GEMV can consume without any per-K-group fold.
+
+ Args:
+ weights: ``[E, N, K // 2]`` ``torch.uint8``, two signed nibbles per
+ byte (auto-round's int4-sym packing: K index ``2i`` in the low
+ nibble, ``2i + 1`` in the high nibble).
+ scales: ``[E, N, K // group_size]`` in fp16 or bf16.
+ group_size: quantization group along K of the int4 weights.
+ rescale_group_size: AUTO_S8 block size; ``-1`` (default) means one
+ scale per output channel -- the fastest configuration.
+
+ Returns:
+ ``(weights_s8, wscales, rescale_block_size)`` where ``weights_s8`` is
+ ``[E, N, K]`` ``torch.int8``, ``wscales`` is
+ ``[E, N, K // rescale_block_size]`` ``torch.float32``, and
+ ``rescale_block_size`` is the resolved block size (pass it to
+ :func:`moe_gemm_w4a8`).
+ """
+ if weights.device.type != "xpu":
+ raise NotImplementedError("moe_w4a8_prepack is only supported on XPU")
+ if weights.dtype != torch.uint8:
+ raise ValueError(f"moe_w4a8_prepack: weights must be torch.uint8, got {weights.dtype}")
+ if weights.ndim != 3:
+ raise ValueError("moe_w4a8_prepack: weights must be 3D [E, N, K // 2]")
+ if scales.ndim != 3:
+ raise ValueError("moe_w4a8_prepack: scales must be 3D [E, N, K // group_size]")
+ if scales.dtype not in (torch.float16, torch.bfloat16):
+ raise ValueError(f"moe_w4a8_prepack: scales must be fp16/bf16, got {scales.dtype}")
+ if scales.device != weights.device:
+ raise ValueError("moe_w4a8_prepack: weights and scales must be on the same device")
+
+ E, N, k_packed = weights.shape
+ K = k_packed * 2
+ _validate_moe_w4a8_shape(N, K, group_size, "moe_w4a8_prepack")
+ expected_scale_shape = (E, N, K // group_size)
+ if tuple(scales.shape) != expected_scale_shape:
+ raise ValueError(f"moe_w4a8_prepack: scales shape {tuple(scales.shape)} != expected {expected_scale_shape}")
+
+ weights = weights.contiguous()
+ scales = scales.contiguous()
+
+ block = moe_w4a8_rescale_block_size(K, group_size, rescale_group_size)
+ nblk = K // block
+
+ weights_s8 = torch.empty((E, N, K), device=weights.device, dtype=torch.int8)
+ wscales = torch.empty((E, N, nblk), device=weights.device, dtype=torch.float32)
+
+ lib = get_lib(weights)
+ stream = get_stream(weights)
+ lib.moe_w4a8_prepack(
+ stream,
+ weights.data_ptr(),
+ scales.data_ptr(),
+ weights_s8.data_ptr(),
+ wscales.data_ptr(),
+ cvt_dtype(scales.dtype),
+ E,
+ N,
+ K,
+ group_size,
+ rescale_group_size,
+ )
+ return weights_s8, wscales, block
+
+
+def moe_gemm_w4a8(
+ activations: torch.Tensor,
+ weights_s8: torch.Tensor,
+ wscales: torch.Tensor,
+ num_tokens_per_expert: torch.Tensor,
+ *,
+ rescale_block_size: int | None = None,
+ phase: str = "auto",
+ activation_scale: torch.Tensor | None = None,
+ out_dtype: torch.dtype | None = None,
+ row_to_token: torch.Tensor | None = None,
+ routing_weights: torch.Tensor | None = None,
+ output_rows: int | None = None,
+) -> torch.Tensor:
+ """W4A8 MoE GEMM: int4 weights (pre-converted to int8), int8 compute.
+
+ Activations are dynamically quantized to int8 per token inside the kernel
+ (per-row absmax), then multiplied against the ``AUTO_S8`` int8 weights with
+ the ``s8 x s8 -> s32`` DPAS atom. The output is
+ ``acc * act_scale[token] * weight_scale[n, block]``.
+
+ Two optional contracts cut DRAM traffic by moving work across the call
+ boundary; both default off and change nothing when unused.
+
+ *Pre-quantized activations.* Pass an ``int8`` ``activations`` together with
+ ``activation_scale`` and the in-call quantization pass is skipped: the
+ kernel then never reads the 16-bit activations, never writes the int8 copy
+ and never reads it back (``4 * T * K`` bytes, 27% of the qwen3
+ down-projection's traffic). The producer of the activations -- typically
+ the SiLU/gate elementwise kernel, which already writes ``[T, K]`` once --
+ can emit that int8 and its per-row scale directly.
+
+ *Fused top-k reduction.* Pass ``row_to_token``, ``routing_weights`` and
+ ``output_rows`` and the epilogue scales each routed row by its routing
+ weight and accumulates it into ``out[row_to_token[row]]`` of a
+ ``[output_rows, N]`` fp32 tensor, instead of writing the ``[T, N]``
+ unreduced result for the caller to reduce afterwards. That replaces
+ ``T * N`` written + ``T * N`` read + ``batch * N`` written with a
+ ``batch * N`` read-modify-write, and removes the caller's reduction kernel.
+ The combiner is a device-scope fp32 atomic add, so the summation order is
+ not deterministic and the result is *not* bit-identical to reducing the
+ unfused output. Prefill only.
+
+ Args:
+ activations: ``[total_tokens, K]`` fp16/bf16, rows sorted by expert, or
+ ``[total_tokens, K]`` int8 when ``activation_scale`` is given.
+ weights_s8: ``[E, N, K]`` ``torch.int8`` from :func:`moe_w4a8_prepack`.
+ wscales: ``[E, N, K // rescale_block_size]`` fp32 from
+ :func:`moe_w4a8_prepack`.
+ num_tokens_per_expert: ``[E]`` int32; sum must equal ``total_tokens``.
+ rescale_block_size: block size the scales were built with. Defaults to
+ ``K // wscales.shape[2]``.
+ phase: ``"auto"`` (GEMV for small batches, grouped GEMM otherwise),
+ ``"decode"`` (force GEMV) or ``"prefill"`` (force grouped GEMM).
+ activation_scale: ``[total_tokens]`` fp32 per-row scales
+ (``absmax / 127``) for pre-quantized int8 activations.
+ out_dtype: output dtype for pre-quantized activations, which carry no
+ floating dtype of their own. Defaults to ``torch.bfloat16``.
+ row_to_token: ``[total_tokens]`` int32, routed row -> model token.
+ routing_weights: ``[total_tokens]`` fp32, the top-k weight of each row.
+ output_rows: number of model tokens, i.e. rows of the fused output.
+
+ Returns:
+ ``[total_tokens, N]`` in the activations dtype, or ``[output_rows, N]``
+ fp32 when the fused reduction is used.
+ """
+ if phase not in _MOE_VALID_PHASES:
+ raise ValueError(f"phase must be one of {_MOE_VALID_PHASES}, got {phase!r}")
+ if activations.device.type != "xpu":
+ raise NotImplementedError("moe_gemm_w4a8 is only supported on XPU")
+
+ prequantized = activation_scale is not None or activations.dtype == torch.int8
+ if prequantized:
+ if activations.dtype != torch.int8:
+ raise ValueError(f"pre-quantized activations must be int8, got {activations.dtype}")
+ if activation_scale is None:
+ raise ValueError("int8 activations require activation_scale")
+ if activation_scale.dtype != torch.float32:
+ raise ValueError(f"activation_scale must be fp32, got {activation_scale.dtype}")
+ if activation_scale.numel() != activations.shape[0]:
+ raise ValueError(
+ f"activation_scale has {activation_scale.numel()} entries, expected {activations.shape[0]}"
+ )
+ act_dtype = torch.bfloat16 if out_dtype is None else out_dtype
+ if act_dtype not in (torch.float16, torch.bfloat16):
+ raise ValueError(f"out_dtype must be fp16/bf16, got {act_dtype}")
+ elif activations.dtype not in (torch.float16, torch.bfloat16):
+ raise ValueError(f"activations must be fp16/bf16, got {activations.dtype}")
+ else:
+ act_dtype = activations.dtype
+ if activations.ndim != 2:
+ raise ValueError("activations must be 2D [total_tokens, K]")
+ if weights_s8.ndim != 3 or weights_s8.dtype != torch.int8:
+ raise ValueError("weights_s8 must be a 3D torch.int8 tensor [E, N, K]")
+ if wscales.ndim != 3 or wscales.dtype != torch.float32:
+ raise ValueError("wscales must be a 3D torch.float32 tensor [E, N, K // block]")
+ _require_same_device(weights_s8, activations, "weights_s8", "moe_gemm_w4a8")
+ _require_same_device(wscales, activations, "wscales", "moe_gemm_w4a8")
+ _require_same_device(num_tokens_per_expert, activations, "num_tokens_per_expert", "moe_gemm_w4a8")
+ if prequantized:
+ _require_same_device(activation_scale, activations, "activation_scale", "moe_gemm_w4a8")
+
+ activations = activations.contiguous()
+ weights_s8 = weights_s8.contiguous()
+ wscales = wscales.contiguous()
+ if prequantized:
+ activation_scale = activation_scale.contiguous()
+
+ total_tokens, K = activations.shape
+ num_experts, N, weight_K = weights_s8.shape
+ if weight_K != K:
+ raise ValueError(f"weights_s8 K dim {weight_K} != activations K {K}")
+ if wscales.shape[0] != num_experts or wscales.shape[1] != N:
+ raise ValueError(f"wscales shape {tuple(wscales.shape)} incompatible with weights {tuple(weights_s8.shape)}")
+ if N % 16 != 0:
+ raise ValueError(f"N must be a multiple of 16 (got {N})")
+ if K % 64 != 0:
+ raise ValueError(f"K must be a multiple of 64 (got {K})")
+ _validate_moe_w4a8_k(K, "moe_gemm_w4a8")
+
+ nblk = wscales.shape[2]
+ if nblk <= 0 or K % nblk != 0:
+ raise ValueError(f"wscales last dim {nblk} must divide K ({K})")
+ block = K // nblk if rescale_block_size is None else int(rescale_block_size)
+ if block * nblk != K:
+ raise ValueError(f"rescale_block_size {block} is inconsistent with wscales last dim {nblk} and K {K}")
+
+ if num_tokens_per_expert.dtype != torch.int32:
+ num_tokens_per_expert = num_tokens_per_expert.to(torch.int32)
+ if not num_tokens_per_expert.is_contiguous():
+ num_tokens_per_expert = num_tokens_per_expert.contiguous()
+ if num_tokens_per_expert.shape[0] != num_experts:
+ raise ValueError(f"num_tokens_per_expert length {num_tokens_per_expert.shape[0]} != num_experts {num_experts}")
+ _check_routing_total(num_tokens_per_expert, total_tokens)
+
+ fused = row_to_token is not None or routing_weights is not None or output_rows is not None
+ if fused:
+ if row_to_token is None or routing_weights is None or output_rows is None:
+ raise ValueError("the fused top-k reduction needs row_to_token, routing_weights and output_rows")
+ if phase != "prefill":
+ raise ValueError("the fused top-k reduction is prefill-only; pass phase='prefill'")
+ if int(output_rows) <= 0:
+ raise ValueError(f"output_rows must be positive (got {output_rows})")
+ _require_same_device(row_to_token, activations, "row_to_token", "moe_gemm_w4a8")
+ _require_same_device(routing_weights, activations, "routing_weights", "moe_gemm_w4a8")
+ if row_to_token.dtype != torch.int32:
+ row_to_token = row_to_token.to(torch.int32)
+ if routing_weights.dtype != torch.float32:
+ routing_weights = routing_weights.to(torch.float32)
+ row_to_token = row_to_token.contiguous()
+ routing_weights = routing_weights.contiguous()
+ if row_to_token.numel() != total_tokens or routing_weights.numel() != total_tokens:
+ raise ValueError(
+ f"row_to_token / routing_weights must have {total_tokens} entries, got "
+ f"{row_to_token.numel()} / {routing_weights.numel()}"
+ )
+ # The epilogue accumulates into this buffer with atomics, so it starts
+ # at zero and is fp32 regardless of the activation dtype.
+ outputs = torch.zeros((int(output_rows), N), device=activations.device, dtype=torch.float32)
+ else:
+ outputs = torch.empty((total_tokens, N), device=activations.device, dtype=act_dtype)
+ if total_tokens == 0:
+ return outputs
+
+ lib = get_lib(activations)
+ stream = get_stream(activations)
+ lib.moe_gemm_w4a8(
+ stream,
+ 0 if prequantized else activations.data_ptr(),
+ weights_s8.data_ptr(),
+ wscales.data_ptr(),
+ 0 if fused else outputs.data_ptr(),
+ cvt_dtype(act_dtype),
+ N,
+ K,
+ block,
+ num_tokens_per_expert.data_ptr(),
+ num_experts,
+ total_tokens,
+ _MOE_VALID_PHASES.index(phase),
+ activations.data_ptr() if prequantized else 0,
+ activation_scale.data_ptr() if prequantized else 0,
+ row_to_token.data_ptr() if fused else 0,
+ routing_weights.data_ptr() if fused else 0,
+ outputs.data_ptr() if fused else 0,
+ int(output_rows) if fused else 0,
+ )
+ return outputs
+
+
+def moe_w4a8_quant_act(activations: torch.Tensor) -> "tuple[torch.Tensor, torch.Tensor]":
+ """Quantize activations per token the way :func:`moe_gemm_w4a8` does.
+
+ This is the call's own quantization pass, on its own. Two uses:
+
+ * **Pre-quantization.** The returned pair is exactly what
+ ``moe_gemm_w4a8(..., activation_scale=...)`` accepts, so a caller that
+ routes the same rows through several experts, or that can produce int8
+ upstream, can pay for the pass once instead of once per call.
+ * **Measurement.** The pass had no standalone entry point, so its cost
+ could only be priced by differencing a 16-bit-input call against a
+ pre-quantized one -- two GEMM timings subtracted, with the noise of both
+ landing on a number a fraction of their size.
+
+ Args:
+ activations: ``[T, K]`` fp16 or bf16 on XPU, ``K % 64 == 0``.
+
+ Returns:
+ ``(qact, ascale)``: ``[T, K]`` ``torch.int8`` and ``[T]``
+ ``torch.float32`` row scales, ``absmax / 127`` (a row that is entirely
+ zero gets scale 0 and quantizes to zeros).
+ """
+ if activations.device.type != "xpu":
+ raise NotImplementedError("moe_w4a8_quant_act is only supported on XPU")
+ if activations.dtype not in (torch.float16, torch.bfloat16):
+ raise ValueError(f"moe_w4a8_quant_act: activations must be fp16/bf16, got {activations.dtype}")
+ if activations.ndim != 2:
+ raise ValueError("moe_w4a8_quant_act: activations must be 2D [T, K]")
+
+ total_tokens, K = activations.shape
+ if K % 64 != 0:
+ raise ValueError(f"moe_w4a8_quant_act: K must be a multiple of 64 (got {K})")
+
+ activations = activations.contiguous()
+ qact = torch.empty((total_tokens, K), device=activations.device, dtype=torch.int8)
+ ascale = torch.empty((total_tokens,), device=activations.device, dtype=torch.float32)
+ if total_tokens == 0:
+ return qact, ascale
+
+ lib = get_lib(activations)
+ lib.moe_w4a8_quant_act(
+ get_stream(activations),
+ activations.data_ptr(),
+ qact.data_ptr(),
+ ascale.data_ptr(),
+ cvt_dtype(activations.dtype),
+ total_tokens,
+ K,
+ )
+ return qact, ascale
+
+
+def moe_w4a8(
+ activations: torch.Tensor,
+ weights: torch.Tensor,
+ num_tokens_per_expert: torch.Tensor,
+ *,
+ scales: torch.Tensor | None = None,
+ group_size: int = 128,
+ rescale_group_size: int = -1,
+ phase: str = "auto",
+ cache_prepack: bool = True,
+) -> torch.Tensor:
+ """W4A8 MoE from auto-round's packed int4-sym weights (prefill + decode).
+
+ Convenience wrapper that runs :func:`moe_w4a8_prepack` (cached on the
+ source tensor identity plus layout / mutation state and the resolved
+ AUTO_S8 block) and then :func:`moe_gemm_w4a8`. It is a drop-in replacement
+ for :func:`moe` on int4-sym weights, trading a small amount of extra
+ quantization error on the activations for the int8 DPAS throughput.
+
+ Args:
+ activations: ``[total_tokens, K]`` fp16/bf16, rows sorted by expert.
+ weights: ``[E, N, K // 2]`` ``torch.uint8`` packed int4-sym weights.
+ num_tokens_per_expert: ``[E]`` int32.
+ scales: ``[E, N, K // group_size]`` in the activations dtype.
+ group_size: quantization group along K (default 128).
+ rescale_group_size: AUTO_S8 block size, ``-1`` = per output channel.
+ phase: ``"auto"``, ``"decode"`` or ``"prefill"``.
+ cache_prepack: keep the converted int8 weights in a module-level cache
+ keyed on source identity, layout, mutation version and the resolved
+ block size. The cache entry holds strong references to ``weights`` /
+ ``scales`` so their addresses cannot be recycled by another tensor
+ while the entry lives (see :data:`_MOE_W4A8_PREPACK_CACHE`). Set to
+ ``False`` for one-shot use so the (large) int8 copy is released as
+ soon as the queued work completes.
+
+ Returns:
+ ``[total_tokens, N]`` in the activations dtype.
+ """
+ if scales is None:
+ raise ValueError("moe_w4a8: scales is required for int4 weights")
+ if scales.dtype != activations.dtype:
+ raise ValueError("moe_w4a8: scales dtype must match activations dtype")
+
+ key = None
+ entry = None
+ block = None
+ if cache_prepack:
+ if weights.ndim == 3:
+ block = moe_w4a8_rescale_block_size(weights.shape[2] * 2, group_size, rescale_group_size)
+ device = weights.device
+ key = (
+ device.type,
+ device.index,
+ weights.data_ptr(),
+ scales.data_ptr(),
+ tuple(weights.shape),
+ tuple(scales.shape),
+ tuple(weights.stride()),
+ tuple(scales.stride()),
+ int(weights._version),
+ int(scales._version),
+ int(group_size),
+ int(block) if block is not None else None,
+ str(scales.dtype),
+ )
+ entry = _MOE_W4A8_PREPACK_CACHE.get(key)
+ if entry is None:
+ weights_s8, wscales, block = moe_w4a8_prepack(
+ weights,
+ scales,
+ group_size=group_size,
+ rescale_group_size=rescale_group_size,
+ )
+ # Pin the source tensors in the entry: the address half of the key is
+ # pointer identity, and a freed-then-reallocated buffer can land on the
+ # same address (every MoE layer's expert weights share shape/dtype/
+ # group_size, so nothing else in the key would discriminate). Holding a
+ # reference keeps the allocator from handing the address to a different
+ # tensor for as long as the entry is cached.
+ entry = (weights_s8, wscales, block, weights, scales)
+ if cache_prepack:
+ _MOE_W4A8_PREPACK_CACHE[key] = entry
+
+ weights_s8, wscales, block = entry[0], entry[1], entry[2]
+ outputs = moe_gemm_w4a8(
+ activations,
+ weights_s8,
+ wscales,
+ num_tokens_per_expert,
+ rescale_block_size=block,
+ phase=phase,
+ )
+ if not cache_prepack:
+ _synchronize_xpu_device(activations.device)
+ return outputs
+
+
# ---------------------------------------------------------------------------
# Native FP8 prefill opt-in.
#
diff --git a/auto_round_extension/ark/auto_round_kernel/ark.cpp b/auto_round_extension/ark/auto_round_kernel/ark.cpp
index 9a76d238b..1e72ee91a 100755
--- a/auto_round_extension/ark/auto_round_kernel/ark.cpp
+++ b/auto_round_extension/ark/auto_round_kernel/ark.cpp
@@ -677,6 +677,42 @@ static void moe_gemm_prefill_int_dpas_wrapper(torch_ptr stream, torch_ptr activa
(int*)num_tokens_per_expert, num_experts, total_tokens);
}
+// W4A8 MoE: int4 weights re-scaled to int8 (AUTO_S8), int8 DPAS compute,
+// per-token dynamically quantized int8 activations. `weights_s8` is
+// [E, N, K] int8 and `wscales` is [E, N, K/rescale_block] FP32, both produced
+// by `moe_w4a8_prepack`. STATUS: NEEDS-HARDWARE-VALIDATION.
+static void moe_w4a8_prepack_wrapper(torch_ptr stream, torch_ptr weights_s4, torch_ptr scales,
+ torch_ptr weights_s8, torch_ptr wscales, int act_dtype, int num_experts,
+ int N, int K, int group_size, int rescale_group_size) {
+ ark::moe_w4a8_prepack((sycl::queue*)stream, (void*)weights_s4, (void*)scales, (void*)weights_s8,
+ (void*)wscales, (BTLA_DTYPE)(act_dtype), num_experts, N, K, group_size,
+ rescale_group_size);
+}
+
+// `qact`/`ascale` are optional pre-quantized activations (0 = quantize in the
+// call); `row_to_token`/`routing_weights`/`fused_out` are the optional fused
+// top-k reduction (0 = write the unreduced `[T, N]` output).
+static void moe_gemm_w4a8_wrapper(torch_ptr stream, torch_ptr activations, torch_ptr weights_s8,
+ torch_ptr wscales, torch_ptr outputs, int act_dtype, int N, int K,
+ int rescale_block_size, torch_ptr num_tokens_per_expert, int num_experts,
+ int total_tokens, int phase, torch_ptr qact, torch_ptr ascale,
+ torch_ptr row_to_token, torch_ptr routing_weights, torch_ptr fused_out,
+ int fused_batch) {
+ ark::moe_gemm_w4a8((sycl::queue*)stream, (void*)activations, (void*)weights_s8, (void*)wscales, (void*)outputs,
+ (BTLA_DTYPE)(act_dtype), N, K, rescale_block_size, (int*)num_tokens_per_expert, num_experts,
+ total_tokens, phase, (const void*)qact, (const float*)ascale, (const int*)row_to_token,
+ (const float*)routing_weights, (float*)fused_out, fused_batch);
+}
+
+// Standalone per-token activation quantization -- the pass `moe_gemm_w4a8`
+// runs internally, exposed so it can be timed on its own and so a caller can
+// pre-quantize once and hand the result back as `qact`/`ascale`.
+static void moe_w4a8_quant_act_wrapper(torch_ptr stream, torch_ptr activations, torch_ptr qact, torch_ptr ascale,
+ int act_dtype, int total_tokens, int K) {
+ ark::moe_w4a8_quant_act((sycl::queue*)stream, (const void*)activations, (void*)qact, (void*)ascale,
+ (BTLA_DTYPE)(act_dtype), total_tokens, K);
+}
+
static void sage_dynamic_quant(torch_ptr stream, torch_ptr input, torch_ptr bias, torch_ptr output, torch_ptr scale_out,
int num_rows, int head_dim, int block_size) {
auto* q = (sycl::queue*)stream;
@@ -1668,6 +1704,10 @@ PYBIND11_MODULE(PY_NAME, m) {
m.def("moe_gemm_prefill", &ark::moe_gemm_prefill_wrapper);
m.def("moe_gemm_prefill_fp8_dpas", &ark::moe_gemm_prefill_fp8_dpas_wrapper);
m.def("moe_gemm_prefill_int_dpas", &ark::moe_gemm_prefill_int_dpas_wrapper);
+ m.def("moe_w4a8_prepack", &ark::moe_w4a8_prepack_wrapper);
+ m.def("moe_gemm_w4a8", &ark::moe_gemm_w4a8_wrapper);
+ m.def("moe_w4a8_quant_act", &ark::moe_w4a8_quant_act_wrapper);
+ m.def("moe_w4a8_rescale_block_size", &ark::moe_w4a8_rescale_block_size);
m.def("matmul_sycl_tla", &ark::matmul_sycl_tla);
#endif // ARK_SYCL_TLA
#if !defined(ARK_XPU)
diff --git a/auto_round_extension/ark/auto_round_kernel/sycl_tla_generation.cmake b/auto_round_extension/ark/auto_round_kernel/sycl_tla_generation.cmake
index ce2aa3967..6eb6095d7 100644
--- a/auto_round_extension/ark/auto_round_kernel/sycl_tla_generation.cmake
+++ b/auto_round_extension/ark/auto_round_kernel/sycl_tla_generation.cmake
@@ -471,6 +471,68 @@ set(MOE_SOURCE_MODE 16)
generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_prefill_s4.cpp)
set(MOE_SOURCE_MODE 17)
generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_prefill_native_fp8.cpp)
+# W4A8 (int4 weights re-scaled to int8, int8 activations) prepack + GEMM.
+#
+# This used to be a single `sycl_tla_moe_w4a8.cpp`, which instantiated all 52
+# W4A8 kernels -- 12 grouped DPAS GEMMs, 14 decode GEMVs, 22 activation-quant
+# and 4 prepack kernels -- and peaked at ~4.2 GB of compiler RSS. It is now
+# fanned out the same way the S4 prefill is (see MOE_SOURCE_MODE 8): one TU per
+# variant, with the dispatcher left holding no kernels at all.
+#
+# mode 21 dispatcher 0 kernels, cutlass-free
+# mode 22 prefill, dtype x tile 1 DPAS kernel each (12 TUs)
+# mode 23 decode, dtype 7 kernels each (2 TUs, cutlass-free)
+# mode 24 act quant, dtype 11 kernels each (2 TUs, cutlass-free)
+# mode 25 prepack, dtype 2 kernels each (2 TUs, cutlass-free)
+#
+# Only the 12 prefill TUs include the CuTe stack; the other seven take
+# `sycl_tla_moe_w4a8_kernels.hpp` / `..._helpers.hpp`, which stop at plain SYCL.
+set(MOE_SOURCE_MODE 21)
+generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_w4a8.cpp)
+
+# Prefill tile ladder: the policy names must match `W4A8PrefillTile` /
+# `moe_w4a8_prefill_select_tile` in `sycl_tla_moe_w4a8_helpers.hpp`, and the
+# function names the `prefill_*` declarations there.
+set(_w4a8_tiles m8 m64 m128 m128n256 m256n128 large)
+foreach(_w4a8_dtype IN ITEMS f16 bf16)
+ if(_w4a8_dtype STREQUAL "f16")
+ set(MOE_SCALAR_TYPE sycl::half)
+ else()
+ set(MOE_SCALAR_TYPE sycl::ext::oneapi::bfloat16)
+ endif()
+
+ set(MOE_SOURCE_MODE 22)
+ foreach(_w4a8_tile IN LISTS _w4a8_tiles)
+ if(_w4a8_tile STREQUAL "m8")
+ set(MOE_POLICY_NAME w4a8_policy_m_8)
+ elseif(_w4a8_tile STREQUAL "m64")
+ set(MOE_POLICY_NAME w4a8_policy_m_64)
+ elseif(_w4a8_tile STREQUAL "m128")
+ set(MOE_POLICY_NAME w4a8_policy_m_128)
+ elseif(_w4a8_tile STREQUAL "m128n256")
+ set(MOE_POLICY_NAME w4a8_policy_m_128_n256)
+ elseif(_w4a8_tile STREQUAL "m256n128")
+ set(MOE_POLICY_NAME w4a8_policy_m_256_n128)
+ else()
+ set(MOE_POLICY_NAME w4a8_policy_large)
+ endif()
+ set(MOE_FUNCTION_NAME prefill_${_w4a8_dtype}_${_w4a8_tile})
+ generate_sycl_tla_source(sycl_tla_moe.cpp.in
+ sycl_tla_moe_w4a8_prefill_${_w4a8_dtype}_${_w4a8_tile}.cpp)
+ endforeach()
+
+ set(MOE_SOURCE_MODE 23)
+ set(MOE_FUNCTION_NAME decode_${_w4a8_dtype})
+ generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_w4a8_decode_${_w4a8_dtype}.cpp)
+
+ set(MOE_SOURCE_MODE 24)
+ set(MOE_FUNCTION_NAME quant_${_w4a8_dtype})
+ generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_w4a8_quant_${_w4a8_dtype}.cpp)
+
+ set(MOE_SOURCE_MODE 25)
+ set(MOE_FUNCTION_NAME prepack_${_w4a8_dtype})
+ generate_sycl_tla_source(sycl_tla_moe.cpp.in sycl_tla_moe_w4a8_prepack_${_w4a8_dtype}.cpp)
+endforeach()
foreach(_moe_dtype IN ITEMS f16 bf16)
if(_moe_dtype STREQUAL "f16")
diff --git a/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe.cpp.in b/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe.cpp.in
index b4e46d69b..5ab8af8d0 100644
--- a/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe.cpp.in
+++ b/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe.cpp.in
@@ -1040,6 +1040,114 @@ void dispatch_@MOE_DISPATCH_DTYPE@_@MOE_TILE_SUFFIX@(sycl::queue* q, const void*
} // namespace moe_gemm_detail
} // namespace ark
+#elif @MOE_SOURCE_MODE@ == 21
+
+// W4A8 dispatcher. Deliberately includes only the cutlass-free front end: the
+// tile choice and the public entry points are host code, and every kernel
+// lives in one of the per-variant TUs generated by modes 22-25. This TU
+// therefore instantiates no kernels at all.
+#include "sycl_tla_common.hpp"
+#include "sycl_tla_moe_w4a8_helpers.hpp"
+
+namespace ark {
+
+void moe_w4a8_prepack(sycl::queue* q, void* weights_s4, void* scales, void* weights_s8, void* wscales,
+ BTLA_DTYPE act_dtype, int num_experts, int N, int K, int group_size,
+ int rescale_group_size) {
+ moe_w4a8_detail::moe_w4a8_prepack(q, weights_s4, scales, weights_s8, wscales, act_dtype, num_experts, N, K,
+ group_size, rescale_group_size);
+}
+
+void moe_gemm_w4a8(sycl::queue* q, void* activations, void* weights_s8, void* wscales, void* outputs,
+ BTLA_DTYPE act_dtype, int N, int K, int rescale_block_size, int* num_tokens_per_expert,
+ int num_experts, int total_tokens, int phase, const void* qact_in, const float* ascale_in,
+ const int* row_to_token, const float* routing_weights, float* fused_out, int fused_batch) {
+ moe_w4a8_detail::moe_gemm_w4a8(q, activations, weights_s8, wscales, outputs, act_dtype, N, K, rescale_block_size,
+ num_tokens_per_expert, num_experts, total_tokens, phase, qact_in, ascale_in,
+ row_to_token, routing_weights, fused_out, fused_batch);
+}
+
+int moe_w4a8_rescale_block_size(int K, int group_size, int rescale_group_size) {
+ return moe_w4a8_detail::moe_w4a8_rescale_block_size(K, group_size, rescale_group_size);
+}
+
+void moe_w4a8_quant_act(sycl::queue* q, const void* activations, void* qact, void* ascale, BTLA_DTYPE act_dtype,
+ int total_tokens, int K) {
+ moe_w4a8_detail::moe_w4a8_quant_act(q, activations, qact, ascale, act_dtype, total_tokens, K);
+}
+
+} // namespace ark
+
+#elif @MOE_SOURCE_MODE@ == 22
+
+// W4A8 prefill, one DPAS policy per translation unit.
+//
+// The single TU this replaced instantiated 52 kernels -- 12 of them grouped
+// DPAS GEMMs -- and peaked at ~4.2 GB of compiler RSS. Fanning the tile ladder
+// out over (dtype x tile) leaves exactly one DPAS kernel here, mirroring how
+// `sycl_tla_moe_prefill_s4_*.cpp` splits the S4 prefill.
+#include "sycl_tla_moe_w4a8.hpp"
+
+namespace ark {
+namespace moe_w4a8_detail {
+
+void @MOE_FUNCTION_NAME@(const W4A8PrefillParams& params) {
+ moe_w4a8::moe_w4a8_prefill_launch<moe_w4a8::@MOE_POLICY_NAME@, @MOE_SCALAR_TYPE@>(params);
+}
+
+} // namespace moe_w4a8_detail
+} // namespace ark
+
+#elif @MOE_SOURCE_MODE@ == 23
+
+// W4A8 decode GEMV, one dtype per translation unit (7 kernels: the legacy
+// GEMV plus the six K-split (NCOLS, CH) specializations). Takes the
+// cutlass-free kernel header, so this TU never parses CuTe.
+#include "sycl_tla_moe_w4a8_kernels.hpp"
+
+namespace ark {
+namespace moe_w4a8_detail {
+
+void @MOE_FUNCTION_NAME@(const W4A8DecodeParams& params) {
+ moe_w4a8::moe_w4a8_decode_launch<@MOE_SCALAR_TYPE@>(params);
+}
+
+} // namespace moe_w4a8_detail
+} // namespace ark
+
+#elif @MOE_SOURCE_MODE@ == 24
+
+// W4A8 per-token activation quantization, one dtype per translation unit
+// (11 kernels: the message-width x unroll grid, the single-pass variants and
+// the scalar fallback). Cutlass-free.
+#include "sycl_tla_moe_w4a8_kernels.hpp"
+
+namespace ark {
+namespace moe_w4a8_detail {
+
+void @MOE_FUNCTION_NAME@(const W4A8QuantParams& params) {
+ moe_w4a8::moe_w4a8_quant_launch<@MOE_SCALAR_TYPE@>(params);
+}
+
+} // namespace moe_w4a8_detail
+} // namespace ark
+
+#elif @MOE_SOURCE_MODE@ == 25
+
+// W4A8 one-shot AUTO_S8 prepack, one dtype per translation unit (2 kernels:
+// the per-block scale reduction and the int4 -> int8 re-scale). Cutlass-free.
+#include "sycl_tla_moe_w4a8_kernels.hpp"
+
+namespace ark {
+namespace moe_w4a8_detail {
+
+void @MOE_FUNCTION_NAME@(const W4A8PrepackParams& params) {
+ moe_w4a8::moe_w4a8_prepack_launch<@MOE_SCALAR_TYPE@>(params);
+}
+
+} // namespace moe_w4a8_detail
+} // namespace ark
+
#endif
#endif // ARK_XPU && ARK_SYCL_TLA
\ No newline at end of file
diff --git a/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe_w4a8_scratch.cpp b/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe_w4a8_scratch.cpp
new file mode 100644
index 000000000..e25b56285
--- /dev/null
+++ b/auto_round_extension/ark/auto_round_kernel/sycl_tla_moe_w4a8_scratch.cpp
@@ -0,0 +1,59 @@
+// Access the extension-wide device scratch pool for the W4A8 MoE path.
+//
+// Keep `utils.hpp` (and the bestla JIT headers behind it) out of the
+// cutlass-free W4A8 translation units. Allocation, growth and synchronization
+// of the pool's bookkeeping are handled by DeviceMemoryPool itself.
+//
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#include "sycl_tla_moe_w4a8_scratch.hpp"
+
+#if defined(ARK_XPU) && defined(ARK_SYCL_TLA)
+
+#include <stdexcept>
+
+#include "utils.hpp"
+
+namespace ark {
+namespace moe_w4a8 {
+
+namespace {
+
+// Acquire a slab from the shared pool.
+//
+// Growth goes through `DeviceMemoryPool::get_scratch_mem`, which already uses
+// the pool's non-blocking per-queue replacement path: it must not host-wait
+// here because that breaks XPU graph capture (see `utils.hpp`).
+void* acquire_w4a8_slab(sycl::queue* q, size_t bytes, size_t buf_loc) {
+ if (q == nullptr) {
+ throw std::invalid_argument("moe_gemm_w4a8: device scratch requires a non-null SYCL queue");
+ }
+ if (bytes == 0) return nullptr;
+ auto* pool = DeviceMemoryPool::Instance();
+ void* ptr = pool->get_scratch_mem(bytes, buf_loc, q);
+ if (ptr == nullptr) {
+ // The pool records the slot before checking the result, so a failed
+ // allocation leaves a {bytes, nullptr} entry behind that would satisfy
+ // every later request of this size or smaller without ever retrying.
+ // Drop it so the next call allocates again.
+ pool->detach_scratch_mem(buf_loc, q);
+ throw std::runtime_error("moe_gemm_w4a8: failed to allocate device scratch buffer");
+ }
+ return ptr;
+}
+
+} // namespace
+
+uint8_t* acquire_qact_scratch(sycl::queue* q, size_t bytes) {
+ return static_cast<uint8_t*>(acquire_w4a8_slab(q, bytes, kW4A8QactScratchLoc));
+}
+
+int* acquire_expert_map_scratch(sycl::queue* q, size_t bytes) {
+ return static_cast<int*>(acquire_w4a8_slab(q, bytes, kW4A8ExpertMapScratchLoc));
+}
+
+} // namespace moe_w4a8
+} // namespace ark
+
+#endif // ARK_XPU && ARK_SYCL_TLA
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_common.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_common.hpp
index cea890b5d..196479bd1 100644
--- a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_common.hpp
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_common.hpp
@@ -220,6 +220,91 @@ void moe_gemm_prefill_int_dpas(sycl::queue* q, void* activations, void* weights,
BTLA_DTYPE act_dtype, BTLA_DTYPE weight_dtype, int N, int K,
int* num_tokens_per_expert, int num_experts, int total_tokens);
+/**
+ * @brief W4A8 MoE -- one-shot AUTO_S8 weight prepack.
+ *
+ * Converts auto-round's packed int4-sym MoE weights `[E, N, K/2]` (uint8, two
+ * nibbles per byte) plus per-group scales `[E, N, K/group_size]` (act dtype)
+ * into int8 weights `[E, N, K]` and FP32 block scales
+ * `[E, N, K/rescale_block]`, using ARK's `AUTO_S8` re-scale formula
+ * (`xpu_wrapper.hpp`): `sxt = max|s| * 8 / 127`, `w8 = round(w4 * s / sxt)`.
+ *
+ * `rescale_group_size <= 0` (the `group=-1` spelling) selects one scale per
+ * output channel, which lets the GEMM run a single full-K int32 accumulation.
+ * Use `moe_w4a8_rescale_block_size` to resolve the effective block size (and
+ * therefore the `wscales` shape) before allocating.
+ *
+ * STATUS: NEEDS-HARDWARE-VALIDATION. These `ark::` entry points are emitted by
+ * the generated `sycl_tla_moe_w4a8.cpp` translation unit (MOE_SOURCE_MODE 21),
+ * which forwards to the inline front end in `sycl_tla_moe_w4a8_helpers.hpp`
+ * (namespace `moe_w4a8_detail`). The kernels themselves are split across the
+ * per-variant TUs generated by MOE_SOURCE_MODE 22-25 so that no single
+ * translation unit instantiates more than a handful of them; see
+ * `sycl_tla_generation.cmake`.
+ */
+void moe_w4a8_prepack(sycl::queue* q, void* weights_s4, void* scales, void* weights_s8, void* wscales,
+ BTLA_DTYPE act_dtype, int num_experts, int N, int K, int group_size,
+ int rescale_group_size);
+
+/**
+ * @brief W4A8 MoE GEMM -- int4 weights, int8 compute, dynamically quantized
+ * int8 activations. Covers both the prefill (grouped GEMM, `s8 x s8 -> s32`
+ * DPAS) and decode (GEMV) phases.
+ *
+ * Activations `[total_tokens, K]` in `act_dtype` are quantized per token to
+ * int8 on entry; `weights_s8` / `wscales` come from `moe_w4a8_prepack`.
+ *
+ * - activations : [total_tokens, K] act dtype (sorted by expert)
+ * - weights_s8 : [num_experts, N, K] int8
+ * - wscales : [num_experts, N, K/rescale_block] float
+ * - outputs : [total_tokens, N] act dtype
+ *
+ * @param rescale_block_size Effective AUTO_S8 block size (see
+ * `moe_w4a8_rescale_block_size`); must be a multiple of 64 dividing K.
+ * @param phase 0 = auto (decode when the batch is small), 1 = force decode,
+ * 2 = force prefill.
+ * @param qact_in Optional `[total_tokens, K]` int8 activations already
+ * quantized by the caller, with `ascale_in` their `[total_tokens]` fp32
+ * per-row scales (`absmax / 127`). Supplying both skips the internal
+ * quantization pass and `activations` is then unused; neither may be
+ * given without the other.
+ * @param row_to_token / routing_weights / fused_out / fused_batch Optional
+ * fused top-k reduction: the epilogue scales each row and scatter-adds
+ * it into the zeroed `[fused_batch, N]` fp32 `fused_out` instead of
+ * writing the unreduced `[total_tokens, N]` to `outputs`. Prefill only,
+ * and all four must be given together.
+ *
+ * STATUS: NEEDS-HARDWARE-VALIDATION. The kernels live in
+ * `sycl_tla_moe_w4a8.hpp` (namespace `moe_w4a8_detail`), which is also where
+ * the trailing optional parameters get their defaults; every caller of this
+ * `ark::` entry point passes all of them explicitly.
+ */
+void moe_gemm_w4a8(sycl::queue* q, void* activations, void* weights_s8, void* wscales, void* outputs,
+ BTLA_DTYPE act_dtype, int N, int K, int rescale_block_size, int* num_tokens_per_expert,
+ int num_experts, int total_tokens, int phase, const void* qact_in, const float* ascale_in,
+ const int* row_to_token, const float* routing_weights, float* fused_out, int fused_batch);
+
+/**
+ * @brief W4A8 per-token activation quantization on its own -- the same pass
+ * `moe_gemm_w4a8` runs internally, exposed so it can be timed directly and so
+ * a caller can pre-quantize once and reuse the result across calls.
+ *
+ * Quantizes `[total_tokens, K]` `act_dtype` activations to `[total_tokens, K]`
+ * int8 plus `[total_tokens]` fp32 row scales (`absmax / 127`) -- exactly the
+ * pair `moe_gemm_w4a8` accepts as `qact_in` / `ascale_in`.
+ *
+ * STATUS: NEEDS-HARDWARE-VALIDATION.
+ */
+void moe_w4a8_quant_act(sycl::queue* q, const void* activations, void* qact, void* ascale, BTLA_DTYPE act_dtype,
+ int total_tokens, int K);
+
+/**
+ * @brief Resolve the effective W4A8 AUTO_S8 re-scale block size for a given
+ * K / group_size, honouring `ARK_MOE_W4A8_AUTO_S8`. Returns K (one scale per
+ * output channel) for `rescale_group_size <= 0` or any unusable value.
+ */
+int moe_w4a8_rescale_block_size(int K, int group_size, int rescale_group_size);
+
void sycl_tla_dense_gemm(sycl::queue* q, int m, int n, int k, const void* a, BTLA_DTYPE at, const void* b,
BTLA_DTYPE bt, void* c, BTLA_DTYPE ct, const void* bias, bool BT);
void sycl_tla_dense_gemm_f32(sycl::queue* q, int m, int n, int k, const void* a, const void* b, void* c,
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_prefill_fp8_dpas.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_prefill_fp8_dpas.hpp
index 280a9cad4..3094ea81f 100644
--- a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_prefill_fp8_dpas.hpp
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_prefill_fp8_dpas.hpp
@@ -191,6 +191,13 @@ using cute_scalar_t = typename cute_scalar<ScalarT>::type;
// entirely on the in-kernel `atm.store(0)` above. That was already true with
// `sycl::malloc_device`, whose contents are equally undefined -- the reuse
// changes what the pre-store garbage looks like, not whether it matters.
+//
+// The W4A8 launcher is the exception: it zeroes the slot on the host and makes
+// its kernel depend on that fill (see `MoEGEMMLauncher_w4a8`), because it
+// claims the next tile *before* computing the current one and so cannot rely on
+// group 0 winning a race it would otherwise have won by microseconds. Sharing
+// the slot with the self-initialising paths stays safe -- every launcher is
+// synchronous, so only one of them is ever in flight.
// ---------------------------------------------------------------------------
// Scratch-pool slot dedicated to the work-group counter. Slots 0-7 are already
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8.hpp
new file mode 100644
index 000000000..70d86f419
--- /dev/null
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8.hpp
@@ -0,0 +1,1190 @@
+// SYCL MoE W4A8 -- INT4 weights / INT8 compute (prefill + decode)
+//
+// STATUS: PARTIALLY HARDWARE-VALIDATED -- every perf sweep in
+// `test_moe_w4a8_perf.py` (`test_perf_prefill_tile_sweep`,
+// `test_perf_prefill_tile_sweep_long_seq`, `test_perf_prefill_act_quant_-
+// sweep`, `..._unroll_sweep`, `..._single_pass_sweep`,
+// `test_perf_prefill_store_sweep`, `test_perf_prefill_epilogue_sweep`,
+// `test_perf_decode_config_sweep`) and
+// every cross-configuration equivalence test (`test_act_quant_vec_matches_-
+// scalar`, `test_act_quant_unroll_matches`, `test_act_quant_single_pass_-
+// matches`, `test_full_tile_epilogue_matches_predicated`,
+// `test_prefill_2d_store_matches_scalar`, `test_decode_ksplit_matches_legacy`)
+// has been run on an Intel Arc Pro B60
+// (Battlemage, BMG-G21 -- 20 Xe2 cores / 160 XVEs at ~2.4 GHz, ~197 int8 TOPS,
+// 24 GB GDDR6 at 456 GB/s), so both phases compile and run and **every**
+// dispatch default -- tile ladder, activation-quant message width / unroll /
+// single-pass, interior-tile epilogue, 2D block store, decode CH / NCOLS --
+// comes from those measurements at the compute-bound batch (384 rows/expert),
+// with the tile ladder measured at the 8K-prompt routing (512 / 341
+// rows/expert) as well, and each configuration checked numerically against the
+// others before it was
+// timed. The accuracy gates against the fp32 reference still need a device
+// run. The authoring environment has no XPU and no SYCL compiler, so anything
+// added *since* that run follows the porting conventions of its siblings
+// `sycl_tla_moe_prefill_int_dpas.hpp` /
+// `sycl_tla_moe_prefill_fp8_dpas.hpp`; nothing is currently in that state.
+// ---------------------------------------------------------------------------
+//
+// File layout
+// -----------
+// The W4A8 path is spread over four headers so that no translation unit pays
+// for more than it uses:
+//
+// sycl_tla_moe_w4a8_scratch.hpp device scratch slabs; declarations only, so
+// that `utils.hpp` (and bestla's JIT headers
+// behind it) stay out of the light TUs
+// sycl_tla_moe_w4a8_helpers.hpp declarations, host helpers, tile ladder
+// (cutlass-free; what the dispatcher sees)
+// sycl_tla_moe_w4a8_kernels.hpp activation quant, AUTO_S8 prepack, decode
+// GEMV (cutlass-free, plain SYCL)
+// sycl_tla_moe_w4a8.hpp this file: DPAS tile policies, the grouped
+// prefill GEMM and its launcher (needs CuTe)
+//
+// `sycl_tla_generation.cmake` then emits one translation unit per variant, so
+// the twelve (dtype x tile) prefill instantiations compile separately rather
+// than all landing in one 4.2 GB TU. The design notes below cover the path as
+// a whole.
+//
+// What this file implements
+// -------------------------
+// A W4A8 MoE path: **weights are stored as int4** (auto-round's packed
+// `[E, N, K/2]` nibble layout with `[E, N, K/group_size]` per-group scales),
+// **the DPAS compute dtype is int8**, and **activations are dynamically
+// quantized to int8** (per-token absmax) on the fly.
+//
+// It covers both MoE phases:
+// * prefill -- persistent grouped GEMM over experts, `XE_DPAS_TT<8, int32_t,
+// int8_t, int8_t>` (`s8 x s8 -> s32`), modelled on the W4A8 weight-only
+// GEMM in `sycl_tla_s8_gemm.hpp` (`sycl_tla_igemm_s8s8_dequant`) and the
+// grouped scheduler in `sycl_tla_moe_prefill_int_dpas.hpp`.
+// * decode -- int8 GEMV. The default mapping splits K across the sub-group
+// lanes (coalesced 256-byte weight reads, `NCOLS` output columns per
+// sub-group), mirroring `moe_decode_detail::launch_fp8_ksplit`;
+// `ARK_MOE_W4A8_DECODE_KSPLIT=0` restores the original one-lane-per-output
+// mapping modelled on `moe_decode_detail::launch_int8`.
+//
+// The AUTO_S8 re-scale trick
+// --------------------------
+// ARK's weight-only GEMM has an `AUTO_S8` option (`ARK_AUTO_S8` /
+// `env_params::auto_s8`, see `xpu_wrapper.hpp`): rather than feeding the int8
+// mainloop a per-K-group scale (which forces a partial-accumulator fold at
+// every group boundary), it *re-scales* the int4 weights into int8 with a
+// coarser block size -- typically `group=-1`, i.e. one scale per output
+// channel spanning the whole K axis. The int8 GEMM then runs a single
+// full-K int32 accumulation with one scalar multiply in the epilogue, which
+// is the most efficient shape for DPAS.
+//
+// The conversion is exactly the one `packscale` + `unpackq(S8, ...)` perform
+// in `xpu_wrapper.hpp`:
+//
+// sxt[e][n][j] = max_{g in block j} |s[e][n][g]| * fullrange / 127
+// w8[e][n][k] = round(w4[e][n][k] * s[e][n][k/group_size] / sxt[e][n][j])
+//
+// with `fullrange = 2^(bits-1) = 8` for int4. Because `|w4| <= 8` and
+// `s <= sxt * 127 / 8` inside the block, `|w8| <= 127`: the re-scaled weight
+// always fits in int8 without clipping, and the dequantized value
+// `w8 * sxt` reproduces `w4 * s` up to the int8 rounding step.
+//
+// The block size is `rescale_group_size` (`-1` / `K` == per output channel ==
+// the `group=-1` maximum-efficiency case). It can be overridden per-process
+// with `ARK_MOE_W4A8_AUTO_S8` (`-1` or a multiple of both `group_size` and 64
+// that divides K). Any invalid value falls back to per-channel.
+//
+// Because the conversion only depends on the checkpoint it is exposed as a
+// separate one-shot entry point (`moe_w4a8_prepack`) so callers can run it at
+// load time and keep the int8 weights + FP32 block scales resident, instead of
+// paying for it on every forward.
+//
+// Numerics
+// --------
+// out[t][n] = (Σ_j sxt[e][n][j] * Σ_{k in block j} qa[t][k] * w8[e][n][k])
+// * sa[t]
+// with `qa = round(a / sa)`, `sa = max_k |a[t][k]| / 127`. The activation
+// scale is per token (row), the weight scale is per (output channel, block),
+// mirroring `sycl_tla_igemm_s8s8_dequant`'s `scale_a[row] * scale_b[col]`
+// epilogue.
+//
+// Layout convention (identical to `moe_gemm_decode` / `moe_gemm_prefill`)
+// ----------------------------------------------------------------------
+// activations : [total_tokens, K] act dtype (tokens pre-sorted by expert)
+// weights_s4 : [E, N, K/2] uint8, two nibbles per byte (sym)
+// scales : [E, N, K/group_size] act dtype
+// weights_s8 : [E, N, K] int8 (prepack output)
+// wscales : [E, N, K/rescale_block] float (prepack output)
+// outputs : [total_tokens, N] act dtype
+//
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <map>
+#include <mutex>
+#include <stdexcept>
+#include <type_traits>
+#include <utility>
+#include <vector>
+
+#ifdef ARK_XPU
+#include <sycl/sycl.hpp>
+#endif
+
+#if defined(ARK_XPU) && defined(ARK_SYCL_TLA)
+
+// Pulls in the cutlass-sycl / CuTe include set, the `dpas_policy_base` policy
+// root, `make_moe_tensor`, and `get_atomic_scratch_buffer` (via the FP8
+// header it includes). This is the expensive include, so only the generated
+// per-tile prefill TUs see this header at all -- the decode / quant / prepack
+// TUs take `sycl_tla_moe_w4a8_kernels.hpp` and the dispatcher TU takes
+// `sycl_tla_moe_w4a8_helpers.hpp`, neither of which reaches cutlass.
+#include "sycl_tla_moe_prefill_int_dpas.hpp"
+// The cutlass-free half: activation quant, AUTO_S8 prepack and decode GEMV,
+// plus the scratch pools and parameter structs they share with the prefill.
+#include "sycl_tla_moe_w4a8_kernels.hpp"
+
+namespace ark {
+namespace moe_w4a8 {
+
+using namespace cute;
+
+// Kernel name tag for the grouped prefill GEMM (the other tags live in
+// `sycl_tla_moe_w4a8_kernels.hpp`). The GRF budget is part of the name: the two
+// budgets are two distinct kernels built from the same source, and a SYCL
+// kernel name may only name one of them.
+template <class Policy, typename ElementD, int GrfSize>
+class MoEW4A8GemmName;
+
+// ---------------------------------------------------------------------------
+// Tile policies.
+//
+// `WGTile`'s K extent is 64 -- the int8 DPAS atom's K granularity, matching
+// `sycl_tla_s8_gemm.hpp`'s `Shape<Int<TileM>, Int<TileN>, _64>`. The M/N
+// shapes and sub-group layouts are the reference GEMM's tile ladder
+// (`SmallTileSG` / `SmallMidTileSG` / `MediumTileSG` / `LargeTileSG`), which
+// keeps `size(mma)` at 64 / 128 / 256 / 512 threads -- all divisors of the 512
+// threads-per-SM budget the persistent scheduler assumes.
+//
+// Tile shape *is* the prefill bandwidth knob. A `TileM x TileN` tile reads its
+// own A and B slabs, so the bytes a whole expert pulls through L2/DRAM are
+//
+// M*K * ceil(N/TileN) + N*K * ceil(M/TileM) ~= M*N*K * (1/TileN + 1/TileM)
+//
+// i.e. A is re-read once per N tile and B once per M tile. Both halvings are
+// real, and both are cancelled by *padding*: an expert launches
+// `ceil(M/TileM) * ceil(N/TileN)` full tiles, so a `TileM` that does not
+// divide the rows/expert pays for rows that do not exist.
+//
+// `test_perf_prefill_tile_sweep` on BMG at the compute-bound batch the suite
+// runs (384 rows/expert, bf16 act), with the 2D block store and the
+// single-pass activation quantizer in:
+//
+// shape auto 128x128 128x256 256x128 256x256
+// qwen3 up 3.540 ms 3.518 ms 3.585 ms 4.404 ms 3.970 ms
+// qwen3 down 2.472 ms 2.473 ms 2.432 ms 2.696 ms 2.547 ms
+// minimax up 6.976 ms 6.823 ms 6.878 ms 8.899 ms 8.019 ms
+// minimax down 6.749 ms 7.227 ms 6.874 ms 9.096 ms 7.823 ms
+//
+// and `test_perf_prefill_tile_sweep_long_seq`, the same sweep at one 8K prompt
+// -- 512 rows/expert on qwen3 (128 experts), 341 on minimax (192):
+//
+// shape auto 128x128 128x256 256x128 256x256
+// qwen3 up 4.371 ms 4.382 ms 4.393 ms 4.468 ms 4.394 ms
+// qwen3 down 3.075 ms 3.030 ms 2.903 ms 3.025 ms 3.059 ms
+// minimax up 6.564 ms 6.673 ms 6.449 ms 9.057 ms 7.744 ms
+// minimax down 6.466 ms 6.725 ms 6.450 ms 9.373 ms 7.307 ms
+//
+// M: `TileM = 256` never pays. At 384 and 341 rows/expert it is 1.05-1.45x
+// *behind*, and that part is arithmetic rather than a register effect: 384
+// rows take `ceil(384/256) = 2` 256-row tiles -- 512 rows scheduled for 384
+// rows of data, a third of the MACs spent on padding -- against exactly 3 full
+// 128-row tiles, and the like-for-like ratio on the long-K shapes, where the
+// mainloop dominates, is that padding ratio (512/384 = 1.33) to within noise
+// (1.25x qwen3 up, 1.30x minimax up, both at `TileN = 128`).
+// The 8K prompt is the case where that argument does *not* apply: 512 rows per
+// expert is an exact multiple of 256, so both tiles schedule the same rows.
+// The 256-row tile is still not ahead there. Like for like on `TileN` it reads
+// -2.0% / 0.0% (qwen3 up at `TileN` 128 / 256) and +0.2% / -5.4% (qwen3 down),
+// i.e. never better than a tie and 5.4% behind on the shape with the shortest
+// mainloop -- so halving how often B is pulled per M tile buys nothing that the
+// larger work-group (512 threads, one per Xe core) does not give back in
+// scheduling granularity. The only reading ever in its favour is an older run
+// at 256 rows/expert, 1.3-3.9% ahead, inside the noise floor. The ladder
+// therefore stops taking it (see `moe_w4a8_prefill_launch`): it has no
+// measured upside, and a routing skewed around the average the ladder sees
+// puts individual experts back on the padding cliff.
+//
+// N: the 256-wide tile is ahead or level everywhere the tables can compare it
+// -- at 384 rows/expert it takes minimax down by 1.05x and qwen3 down by 1.02x
+// and is 0.8-1.9% behind on the other two, and at the 8K prompt it takes three
+// of four by 3.5-4.4% and ties qwen3 up (0.3%). The 35-50% cliff the first
+// sweep saw on every 256-wide N tile is gone -- it was the float C shadow the
+// mainloop used to keep live (see `xe_gemm_w4a8`), which doubled the per-lane
+// C footprint and made `TileN = 256` ask for the entire 256-register large-GRF
+// file -- and what remained of it in the second sweep (0-8% behind on three
+// shapes, measured with the *scalar* epilogue store) is gone too, now that a
+// 32x64 fragment goes out in a handful of block messages instead of 128 scalar
+// ones. So the ladder is 256 wide in N wherever N divides into it.
+//
+// Noise floor for reading all of this: the `auto` column is not an independent
+// measurement -- it launches whichever explicit tile the ladder picks, so each
+// row above contains one *duplicate* pair (`128x256` at 384 rows/expert and at
+// the minimax 8K point, `256x256` at the qwen3 8K point). Across the eight
+// pairs the two readings of the same kernel differ by 0.2-1.9%, which is the
+// run-to-run floor for these tables; the padding effect reaches 45%.
+//
+// Every policy stays reachable through `ARK_MOE_W4A8_PREFILL_TILE` for a
+// re-sweep on a device with a different register budget.
+//
+// `kSmallGrfOk`: the register budget is a property of the tile
+// ------------------------------------------------------------
+// The ladder above was swept with `grf_size<256>` hardwired into the launcher,
+// which pins *every* rung at 4 hardware threads per vector engine -- 512
+// work-items per Xe-core, which is exactly the `MaxThreadsPerSM` the persistent
+// grid is sized from. The small tiles are in the ladder because they ask for
+// fewer registers, and the payoff for asking for fewer registers is that more
+// work-groups fit on an Xe-core; at a fixed `grf_size<256>` they paid the cost
+// and never collected. So none of them has ever been measured at the occupancy
+// that is their reason to exist.
+//
+// What a lane actually holds for the whole mainloop is the C fragment, which is
+// the WG tile divided by the sub-group count (`blks == 1` keeps only the int32
+// accumulator -- see the register-file argument on `xe_gemm_w4a8` below):
+//
+// policy WG tile SGs SG C fragment int32 regs/lane
+// m_8 8x128 4 8 x 32 16
+// m_64 64x128 8 32 x 32 64
+// m_128 128x128 16 32 x 32 64
+// m_128_n256 128x256 16 32 x 64 128
+// m_256_n128 256x128 32 32 x 32 64
+// large 256x256 32 32 x 64 128
+//
+// At `grf_size<128>` a lane has 128 registers, so the 64-register tiles keep
+// half the file for the staged A/B tiles and their addresses, and the 128-
+// register ones would have *nothing* left -- their accumulator alone is the
+// whole file. Hence the flag splits the ladder exactly along the N dimension:
+// 128-wide N can double its occupancy, 256-wide N cannot be asked to.
+//
+// This is a request, not a guarantee: if the halved budget does not hold the
+// staged tiles the compiler spills, which costs time but not correctness.
+//
+// **Measured on B70, it spills.** Forcing `128x128` and halving the budget cost
+// 1.56-1.60x on qwen3 up and 1.16-1.20x on down -- the occupancy doubled and the
+// tile stopped fitting. The penalty tracks `K` rather than tile count, putting
+// it in the mainloop, on exactly the staged fragments this paragraph worried
+// about. So `ARK_MOE_W4A8_PREFILL_SMALL_GRF` defaults to off and the ladder
+// keeps the large budget; `kSmallGrfOk` remains only so the question can be
+// re-asked on a part with a different register file. Full numbers are in the
+// launch-time comment on `moe_w4a8_prefill_launch`.
+// ---------------------------------------------------------------------------
+class w4a8_policy_m_8 : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_8, _128, _64>;
+ using SGLayout = Layout<Shape<_1, _4, _1>, Stride<_0, _1, _0>>;
+ static constexpr bool kSmallGrfOk = true;
+};
+
+class w4a8_policy_m_64 : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_64, _128, _64>;
+ using SGLayout = Layout<Shape<_2, _4, _1>, Stride<_4, _1, _0>>;
+ static constexpr bool kSmallGrfOk = true;
+};
+
+class w4a8_policy_m_128 : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_128, _128, _64>;
+ using SGLayout = Layout<Shape<_4, _4, _1>, Stride<_4, _1, _0>>;
+ static constexpr bool kSmallGrfOk = true;
+};
+
+class w4a8_policy_m_128_n256 : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_128, _256, _64>;
+ using SGLayout = Layout<Shape<_4, _4, _1>, Stride<_4, _1, _0>>;
+ static constexpr bool kSmallGrfOk = false;
+};
+
+class w4a8_policy_m_256_n128 : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_256, _128, _64>;
+ using SGLayout = Layout<Shape<_8, _4, _1>, Stride<_4, _1, _0>>;
+ static constexpr bool kSmallGrfOk = true;
+};
+
+class w4a8_policy_large : public moe_dpas_fp8::dpas_policy_base {
+ public:
+ using WGTile = Shape<_256, _256, _64>;
+ using SGLayout = Layout<Shape<_8, _4, _1>, Stride<_4, _1, _0>>;
+ static constexpr bool kSmallGrfOk = false;
+};
+
+// ---------------------------------------------------------------------------
+// Optional fused top-k reduction (prefill only).
+//
+// The grouped GEMM's natural output is `[T, N]`, one row per *routed* row, and
+// every caller immediately reduces it: a token's `top_k` rows are scaled by
+// their routing weights and summed into one `[batch, N]` row. That reduction
+// reads `T*N` and writes `batch*N`, and the GEMM wrote `T*N` for it to read --
+// so the unfused contract moves `2*T*N + batch*N` elements where the fused one
+// moves `2*batch*N` (a read-modify-write of the accumulator).
+//
+// It is the largest lever on the down-projection shapes, where D is a third of
+// the call's traffic: at qwen3's routing (`top_k = 8`) it takes D from
+// `T*N*sizeof(ElementD)` to `batch*N*4*2`, i.e. 192 MB -> 48 MB at 384
+// rows/expert, and deletes the caller's reduction kernel outright.
+//
+// The accumulator is fp32 and the caller must zero it: rows of the same token
+// land on different experts, hence on different work-groups, so the only
+// portable combiner is a device-scope atomic add. That makes the result
+// **order-dependent** and therefore not bit-identical to the unfused path --
+// the equivalence test for this contract is an SNR/cosine gate, not
+// `torch.equal`. Scaling is applied before the atomic (one multiply per
+// element), so the atomic itself stays a plain `fetch_add`.
+//
+// `out == nullptr` selects the unfused path and compiles to the same code as
+// before; the branch is uniform across the work-group (it is a kernel
+// argument).
+// ---------------------------------------------------------------------------
+struct MoEFusedReduce {
+ const int* row_to_token = nullptr; // routed row -> model token (expert-local base)
+ const float* row_weight = nullptr; // routed row -> routing weight (expert-local base)
+ float* out = nullptr; // [batch, N] fp32 accumulator, zeroed by the caller
+ int batch = 0; // rows of `out`; bounds the scatter
+
+ CUTE_HOST_DEVICE bool enabled() const { return out != nullptr; }
+};
+
+CUTE_DEVICE inline void atomic_add_f32(float* addr, float value) {
+ sycl::atomic_ref<float, sycl::memory_order::relaxed, sycl::memory_scope::device,
+ sycl::access::address_space::global_space>
+ ref(*addr);
+ ref.fetch_add(value);
+}
+
+// ---------------------------------------------------------------------------
+// Single-tile int8 x int8 -> int32 mainloop with a per-block weight scale and
+// a per-row activation scale.
+//
+// Structure is `igemm_kblock_device_impl` from `sycl_tla_s8_gemm.hpp` (the
+// W4A8 weight-only GEMM), with two changes for the grouped/MoE case:
+// * the tile coordinate is passed in by the persistent scheduler instead of
+// being derived from the work-item's group id, and
+// * A/B/D base pointers are the per-expert slices.
+//
+// `blks == 1` (the AUTO_S8 `group=-1` default) collapses the outer loop to a
+// single full-K int32 accumulation -- the maximum-efficiency shape -- and gets
+// its own instantiation, because on this architecture the *register file*, not
+// the tile traffic, is what the prefill GEMM runs out of.
+//
+// Why `blks == 1` is specialized (the register-file argument)
+// -----------------------------------------------------------
+// The blocked path needs two C fragments: the int32 DPAS accumulator `tCrC`,
+// cleared once per re-scale block, and a float `tFrC` that survives across
+// blocks because the per-block weight scale has to be applied before the next
+// block overwrites `tCrC`. Both are the size of the work-group tile divided by
+// the sub-group count, and a lane holds them in GRF for the *entire* mainloop:
+//
+// tile SG C fragment int32 regs/lane + float regs/lane
+// 128x128 32 x 32 64 64
+// 128x256 32 x 64 128 128
+//
+// With `grf_size<256>` a lane has 256 registers in total, so at 128x128 the
+// float shadow alone reserves a quarter of the register file for the whole
+// mainloop, and at 128x256 the two fragments together *are* the register file
+// -- leaving nothing for the staged A/B tiles. That is the measured cliff
+// documented in the tile-policy comment above (256-wide N tiles 35-50% slower
+// than 128-wide ones, split by `TileN` and not by `TileM`), and it is pure
+// overhead when `blks == 1`: with one block there is nothing to carry across
+// blocks, so the scale can be folded on the way out and no float fragment
+// needs to exist while the mainloop runs.
+//
+// The single-block epilogue therefore keeps only `tCrC` live and applies
+// `scale_b[col] * scale_a[row]` in one pass, exactly like the `AccumBlock ==
+// false` branch of the reference `igemm_device_impl`.
+//
+// The epilogue writes through the raw `[m, n]` row-major output pointer using
+// the coordinates of `thr_mma.partition_C(...)`, exactly like the reference,
+// because the int32 accumulator has to be converted and scaled per element
+// anyway. A grouped GEMM's per-expert M is arbitrary, so tiles at the M edge
+// are partial and their *store* has to be predicated -- but the scale *loads*
+// are not: their indices are clamped into range instead. Both scale reads are
+// then unconditional loads at a compile-time offset from a uniform base, which
+// is what lets the compiler collapse the `size(tCrC)` per-element reads into
+// the handful of distinct addresses a sub-group's fragment actually covers
+// (all lanes of a row group share `scale_a[row]`, and a lane repeats the same
+// `scale_b[col]` for every row it owns). Under the previous `continue` guard
+// each read sat in its own basic block and none of that could be hoisted.
+//
+// Interior tiles skip the guard entirely (the cost that shows up at small K)
+// -------------------------------------------------------------------------
+// `m`, `n`, `m_coord` and `n_coord` are all uniform across the work-group, so
+// "does this tile touch the M or N edge" is one uniform compare, not a
+// per-element one. Off the edge the clamps and the store predicate are dead
+// weight: per fragment element they add two compares plus two selects for the
+// scale indices and another compare pair for the store, roughly doubling the
+// instruction count of an epilogue whose real work is one int32->float
+// convert, two multiplies and one store.
+//
+// That matters because the epilogue is *not* amortized over a long mainloop at
+// these shapes. A 128x128 tile runs `K / 64` k-tiles -- 12 of them for the
+// qwen3 down-projection (K = 768) -- while it always writes `TileM * TileN`
+// elements, and qwen3 down is exactly the shape the sweep reports furthest
+// from the compute target (63 TFLOPS against 87-103 for the other three). The
+// fast path emits the same expression in the same order for every element it
+// stores, so it is bit-identical to the guarded one
+// (`test_full_tile_epilogue_matches_predicated`), and
+// `ARK_MOE_W4A8_PREFILL_FULL_TILE=0` forces the guarded path for A/B
+// measurement. `test_perf_prefill_epilogue_sweep` at 384 rows/expert has it at
+// 1.04x (qwen3 down), 1.03x (qwen3 up) and 1.00-1.01x on the two minimax
+// shapes -- the shape ordering the instruction-count argument predicted, with
+// the gain concentrated where the mainloop is shortest.
+//
+// The store itself: one 2D block message instead of `size(tCrC)` scalar ones
+// -----------------------------------------------------------------------
+// Removing instructions from around the store left the store. The Xe DPAS C
+// fragment gives a lane one *column* of each 8x16 atom, so the 16 lanes of a
+// sub-group hold 16 *consecutive columns of one row*: a scalar
+// `c[row * n + col] = ...` is a 32-byte message for 16-bit `ElementD`, half a
+// cache line, and a 32x32 sub-group fragment issues **64** of them. The same
+// bytes go out in 4 messages through the hardware 2D block store, which is
+// what every sibling prefill kernel already uses for D
+// (`sycl_tla_moe_prefill_{fp8,int,s4}_dpas.hpp`) and what the dense GEMM in
+// `sycl_tla_dense_gemm.hpp` uses on this exact accumulator shape.
+//
+// D is the reason this is worth doing at prefill sizes rather than a tidy-up:
+// at 384 rows per expert the qwen3 down-projection writes `M*N` fp16 (1.5 MB
+// per expert) -- exactly as many bytes as the `N*K` int8 weights it reads,
+// because N (2048) is larger than K (768) there, and over a third of the
+// expert's traffic. It is the same shape whose mainloop is shortest, so it
+// pays the epilogue twice.
+//
+// The port follows `dense_gemm_detail::gemm_device_impl` rather than the
+// sibling MoE kernels, because those `reorder(tCrC, tCrC_out)` from the MMA
+// fragment into an explicitly chosen `XE_STORE_2D` atom's fragment, and
+// `reorder` moves *registers*: with a `float` accumulator that is free, but
+// this kernel's accumulator is `int32` (`FrgTypeC` of
+// `XE_DPAS_TT<8, int32_t, int8_t, int8_t>`) and has to be scaled and
+// numerically converted first, which `reorder` does not do. `dense_gemm`'s
+// shape is the one that fits: `make_block_2d_copy_D(mma, D)` derives its
+// layout from the MMA's own C partition, so the scaled `ElementD` fragment
+// (`make_tensor_like<ElementD>(tCrC)`, filled through the same `tCgC(i)`
+// coordinates the scalar path uses) can be handed straight to
+// `copy(copy_d, tCrD, tCgC)` with no `reorder` in between.
+//
+// It also *removes* the store predicate rather than skipping it: the 2D block
+// message clips to the surface (`m` rows x `n` columns) described by the D
+// tensor, so a partial tile at the M edge drops its out-of-range rows in
+// hardware -- exactly how the sibling grouped GEMMs handle their ragged
+// experts. Only the scale *loads* still need their index clamps, and only on
+// edge tiles. The value written is computed by the same expression in the same
+// order as the scalar path, so the two are bit-identical
+// (`test_prefill_2d_store_matches_scalar`); `ARK_MOE_W4A8_PREFILL_STORE_2D=0`
+// restores the scalar store for A/B measurement. `test_perf_prefill_store_-
+// sweep` at 384 rows/expert makes it the largest single prefill win of the
+// set: 1.14x (qwen3 up), 1.21x (qwen3 down -- the shape that pays the epilogue
+// twice), 1.09x (minimax up) and 1.16x (minimax down); the run before read
+// 1.16 / 1.35 / 1.12 / 1.20, same ordering.
+//
+// The block 2D descriptor wants a 64-byte aligned base and a row pitch that is
+// a multiple of 16 bytes. The base here is the expert's slice
+// `Outputs + pre_rows * N`, with `pre_rows` a runtime routing value, so the
+// dispatcher gates on `N * sizeof(ElementD) % 64 == 0` (which makes *every*
+// expert's base 64-byte aligned given an aligned tensor) and on the base
+// pointer itself; anything else keeps the scalar store.
+// ---------------------------------------------------------------------------
+template <class GmemTiledCopyA, class GmemTiledCopyB, class TiledMMA, typename ElementD>
+CUTE_DEVICE void xe_gemm_w4a8(const int8_t* a, const int8_t* b, ElementD* c, const float* scale_a,
+ const float* scale_b, int m, int n, int k, int blocksize, int blks, int m_coord,
+ int n_coord, bool allow_full_tile, bool allow_block_2d_store, int prefetch_dist,
+ MoEFusedReduce const& reduce, TiledMMA const& mma) {
+ auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ const int local_id = static_cast<int>(item.get_local_linear_id());
+
+ auto wg_tile = mma.tile_mnk();
+ auto wg_coord = make_coord(m_coord, n_coord, 0);
+
+ // The fused path never writes through `c` (it scatters into `reduce.out`
+ // instead) and its caller has no `[T, N]` buffer to hand over, so `c` is
+ // null there. D and its 2D copy atom are still built -- they are ordinary
+ // objects, not lazily constructed -- so give them a valid base to describe.
+ ElementD* d_base = c != nullptr ? c : reinterpret_cast<ElementD*>(reduce.out);
+
+ auto A = make_tensor(make_gmem_ptr(const_cast<int8_t*>(a)), make_shape(m, k), make_stride(k, _1{}));
+ auto B = make_tensor(make_gmem_ptr(const_cast<int8_t*>(b)), make_shape(n, k), make_stride(k, _1{}));
+ auto D = make_tensor(make_gmem_ptr(d_base), make_shape(m, n), make_stride(n, _1{}));
+
+ Tensor cA = make_identity_tensor(A.shape());
+ Tensor cB = make_identity_tensor(B.shape());
+ Tensor cC = make_identity_tensor(D.shape());
+
+ Tensor gA = local_tile(cA, select<0, 2>(wg_tile), make_coord(m_coord, _));
+ Tensor gB = local_tile(cB, select<1, 2>(wg_tile), make_coord(n_coord, _));
+ Tensor gC = local_tile(cC, wg_tile, wg_coord, Step<_1, _1, X>{});
+
+ auto copy_a = get_block_2d_copy_A<GmemTiledCopyA>(mma, A);
+ auto copy_b = get_block_2d_copy_B<GmemTiledCopyB>(mma, B);
+ auto copy_d = make_block_2d_copy_D(mma, D);
+
+ auto thr_mma = mma.get_slice(local_id);
+ auto thr_copy_a = copy_a.get_slice(local_id);
+ auto thr_copy_b = copy_b.get_slice(local_id);
+
+ auto tCrA = thr_mma.partition_sg_fragment_A(gA(_, _, 0));
+ auto tCrB = thr_mma.partition_sg_fragment_B(gB(_, _, 0));
+
+ auto tArA = thr_copy_a.partition_sg_fragment_D(gA(_, _, 0));
+ auto tBrB = thr_copy_b.partition_sg_fragment_D(gB(_, _, 0));
+
+ Tensor tAgA = thr_copy_a.partition_S(gA);
+ Tensor tBgB = thr_copy_b.partition_S(gB);
+
+ Tensor tCrC = partition_fragment_C(mma, select<0, 1>(wg_tile));
+ Tensor tCgC = thr_mma.partition_C(gC);
+
+ auto prefetch_a = make_block_2d_prefetch(copy_a);
+ auto prefetch_b = make_block_2d_prefetch(copy_b);
+
+ auto pAgA = prefetch_a.get_slice(local_id).partition_S(gA);
+ auto pBgB = prefetch_b.get_slice(local_id).partition_S(gB);
+
+ constexpr auto barrier_scope = ScopeWorkgroup;
+
+ const int k_tile_size = static_cast<int>(get<2>(wg_tile));
+ const int k_tiles_per_block = blocksize / k_tile_size;
+ const int k_tile_count = blks * k_tiles_per_block;
+ int k_tile_prefetch = 0;
+
+ // One k-tile of the DPAS pipeline. Shared by both paths so the two
+ // instantiations differ only in what they keep live around it.
+ auto run_k_tile = [&](int k_tile) {
+ barrier_arrive(barrier_scope);
+
+ copy(copy_a, tAgA(_, _, _, k_tile), tArA);
+ copy(copy_b, tBgB(_, _, _, k_tile), tBrB);
+
+ if (k_tile_prefetch < k_tile_count) {
+ prefetch(prefetch_a, pAgA(_, _, _, k_tile_prefetch));
+ prefetch(prefetch_b, pBgB(_, _, _, k_tile_prefetch));
+ }
+ ++k_tile_prefetch;
+
+ reorder(tArA, tCrA);
+ reorder(tBrB, tCrB);
+ cute::gemm(mma, tCrA, tCrB, tCrC);
+
+ barrier_wait(barrier_scope);
+ };
+
+ // Runtime bound (`ARK_MOE_W4A8_PREFILL_PREFETCH`), so no unroll pragma: the
+ // prologue runs once per tile, ahead of a mainloop of `k_tile_count`
+ // iterations, and its trip count is uniform across the work-group.
+ for (; k_tile_prefetch < prefetch_dist && k_tile_prefetch < k_tile_count; ++k_tile_prefetch) {
+ prefetch(prefetch_a, pAgA(_, _, _, k_tile_prefetch));
+ prefetch(prefetch_b, pBgB(_, _, _, k_tile_prefetch));
+ }
+
+ // Does this tile touch the M or N edge? Uniform across the work-group (`m`,
+ // `n` and both coordinates are), so the epilogues below branch once instead
+ // of testing every fragment element.
+ const bool full_tile = allow_full_tile && (m_coord + 1) * static_cast<int>(get<0>(wg_tile)) <= m &&
+ (n_coord + 1) * static_cast<int>(get<1>(wg_tile)) <= n;
+
+ // `blks` is a kernel argument, so it is uniform across the work-group and
+ // this branch never splits the split-barrier pairing below.
+ if (blks == 1) {
+ clear(tCrC);
+
+ for (int k_tile = 0; k_tile < k_tile_count; ++k_tile) {
+ run_k_tile(k_tile);
+ }
+
+ // Single expression, instantiated once guarded and once not. `FullTile`
+ // only removes work: the value stored is computed by the same operations
+ // in the same order, so the two paths are bit-identical.
+ auto store_scaled = [&](auto full) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tCrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ if constexpr (decltype(full)::value) {
+ c[static_cast<size_t>(row) * n + col] = static_cast<ElementD>(
+ static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col)] * scale_a[row]);
+ } else {
+ // Clamp rather than branch: an out-of-range element's value is
+ // dropped by the guarded store, and unconditional loads let the
+ // redundant reads across the fragment collapse. `m` and `n` are both
+ // >= 1 here (an expert with no rows contributes no tiles).
+ const int row_in = row < m ? row : m - 1;
+ const int col_in = col < n ? col : n - 1;
+ const float value = static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col_in)] * scale_a[row_in];
+ if (row < m && col < n) {
+ c[static_cast<size_t>(row) * n + col] = static_cast<ElementD>(value);
+ }
+ }
+ }
+ };
+
+ // Same values in the same order, through the hardware 2D block store. The
+ // element predicate is gone because the message clips to the `m x n`
+ // surface; only the scale loads still clamp their indices.
+ auto store_scaled_2d = [&](auto full) {
+ Tensor tCrD = make_tensor_like<ElementD>(tCrC);
+ CUTE_UNROLL
+ for (int i = 0; i < size(tCrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ if constexpr (decltype(full)::value) {
+ tCrD(i) = static_cast<ElementD>(static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col)] *
+ scale_a[row]);
+ } else {
+ const int row_in = row < m ? row : m - 1;
+ const int col_in = col < n ? col : n - 1;
+ tCrD(i) = static_cast<ElementD>(static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col_in)] *
+ scale_a[row_in]);
+ }
+ }
+ copy(copy_d, tCrD, tCgC);
+ };
+
+ // Fused top-k reduction: scale the row by its routing weight and
+ // accumulate it into the token's row of the `[batch, n]` fp32 output.
+ // Out-of-range rows are dropped rather than clamped -- a clamped scatter
+ // would corrupt a *valid* token's accumulator, which the guarded store
+ // above cannot do -- but the loads stay unconditional so they still
+ // collapse across the fragment. `row_to_token` is caller data, so its
+ // value is range-checked as well: a bad index drops the contribution
+ // instead of writing outside the accumulator.
+ auto store_fused = [&](auto full) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tCrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ const int row_in = decltype(full)::value ? row : (row < m ? row : m - 1);
+ const int col_in = decltype(full)::value ? col : (col < n ? col : n - 1);
+ const float value = static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col_in)] *
+ scale_a[row_in] * reduce.row_weight[row_in];
+ const int token = reduce.row_to_token[row_in];
+ const bool in_tile = decltype(full)::value || (row < m && col < n);
+ if (in_tile && token >= 0 && token < reduce.batch) {
+ atomic_add_f32(&reduce.out[static_cast<size_t>(token) * n + col], value);
+ }
+ }
+ };
+
+ if (reduce.enabled()) {
+ if (full_tile) {
+ store_fused(std::true_type{});
+ } else {
+ store_fused(std::false_type{});
+ }
+ } else if (allow_block_2d_store) {
+ if (full_tile) {
+ store_scaled_2d(std::true_type{});
+ } else {
+ store_scaled_2d(std::false_type{});
+ }
+ } else if (full_tile) {
+ store_scaled(std::true_type{});
+ } else {
+ store_scaled(std::false_type{});
+ }
+ return;
+ }
+
+ Tensor tFrC = make_tensor_like<float>(tCrC);
+
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ tFrC(i) = 0.0f;
+ }
+
+ for (int ib = 0; ib < blks; ++ib) {
+ clear(tCrC);
+
+ for (int bk = 0; bk < k_tiles_per_block; ++bk) {
+ run_k_tile(ib * k_tiles_per_block + bk);
+ }
+
+ if (full_tile) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tCrC); ++i) {
+ const int col = static_cast<int>(get<1>(tCgC(i)));
+ tFrC(i) += static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col) * blks + ib];
+ }
+ } else {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tCrC); ++i) {
+ const int col = static_cast<int>(get<1>(tCgC(i)));
+ const int col_in = col < n ? col : n - 1;
+ tFrC(i) += static_cast<float>(tCrC(i)) * scale_b[static_cast<size_t>(col_in) * blks + ib];
+ }
+ }
+ }
+
+ if (reduce.enabled()) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ const int row_in = full_tile ? row : (row < m ? row : m - 1);
+ const float value = tFrC(i) * scale_a[row_in] * reduce.row_weight[row_in];
+ const int token = reduce.row_to_token[row_in];
+ const bool in_tile = full_tile || (row < m && col < n);
+ if (in_tile && token >= 0 && token < reduce.batch) {
+ atomic_add_f32(&reduce.out[static_cast<size_t>(token) * n + col], value);
+ }
+ }
+ return;
+ }
+
+ if (allow_block_2d_store) {
+ Tensor tCrD = make_tensor_like<ElementD>(tFrC);
+ if (full_tile) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ const int row = static_cast<int>(get<0>(tCgC(i)));
+ tCrD(i) = static_cast<ElementD>(tFrC(i) * scale_a[row]);
+ }
+ } else {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ const int row = static_cast<int>(get<0>(tCgC(i)));
+ const int row_in = row < m ? row : m - 1;
+ tCrD(i) = static_cast<ElementD>(tFrC(i) * scale_a[row_in]);
+ }
+ }
+ copy(copy_d, tCrD, tCgC);
+ return;
+ }
+
+ if (full_tile) {
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ c[static_cast<size_t>(row) * n + col] = static_cast<ElementD>(tFrC(i) * scale_a[row]);
+ }
+ return;
+ }
+
+ CUTE_UNROLL
+ for (int i = 0; i < size(tFrC); ++i) {
+ auto coord = tCgC(i);
+ const int row = static_cast<int>(get<0>(coord));
+ const int col = static_cast<int>(get<1>(coord));
+ const int row_in = row < m ? row : m - 1;
+ const float value = tFrC(i) * scale_a[row_in];
+ if (row < m && col < n) {
+ c[static_cast<size_t>(row) * n + col] = static_cast<ElementD>(value);
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Persistent atomic scheduler over `rows_per_expert`.
+//
+// Structurally identical to `moe_dpas_int::MoEGEMM_int` (which is itself the
+// vllm-xpu-kernels grouped-GEMM scheduler); only the per-expert pointer
+// arithmetic and the mainloop call differ:
+// * A / D advance by the expert's token offset (`pre_rows`), and so does the
+// per-token activation scale.
+// * B advances by `expert * N * K` int8 elements, the block scales by
+// `expert * N * blks` floats.
+// ---------------------------------------------------------------------------
+template <class GmemTiledCopyA, class GmemTiledCopyB, class TiledMMA, typename ElementD>
+CUTE_DEVICE void MoEGEMM_w4a8(const int8_t* Activations, const int8_t* Weights, const float* ScaleA,
+ const float* ScaleB, ElementD* Outputs, TiledMMA const& mma,
+ const int* rows_per_expert, const int32_t num_experts, const int32_t gemm_n,
+ const int32_t gemm_k, const int32_t blocksize, const int32_t blks,
+ const bool allow_full_tile, const bool allow_block_2d_store,
+ const int32_t prefetch_dist, const bool claim_early, MoEFusedReduce reduce,
+ int32_t* atomic_buffer, const sycl::local_accessor<int32_t, 1>& slm_mem_const) {
+ auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
+ auto wg_tile = mma.tile_mnk();
+ auto wg_tile_m = get<0>(wg_tile);
+ auto wg_tile_n = get<1>(wg_tile);
+
+ int group_id = item.get_group_linear_id();
+ int gemm_n_pad = (gemm_n + wg_tile_n - 1) / wg_tile_n * wg_tile_n;
+ int group_m_id = (group_id * wg_tile_n) / gemm_n_pad;
+ int group_range = item.get_group_range(1);
+ int local_id = item.get_local_linear_id();
+
+ // The work-stealing counter arrives already zeroed: `MoEGEMMLauncher_w4a8`
+ // fills it on the host and makes the kernel depend on that fill. It used to
+ // be reset here by group 0 / lane 0, which is unordered against every other
+ // work-group's `atomicAdd` on the same dword -- it held only because a
+ // work-group's first claim came after a whole GEMM tile, microseconds after
+ // group 0's store. `claim_early` moves the first claim to within a few
+ // instructions of kernel entry, which would make that window real, so the
+ // reset moved to the one place where it is ordered by construction.
+
+ int pre_rows = 0;
+ int pre_tiles = 0;
+
+ // Ping-pong slot for the claimed tile index. One SLM dword would need a
+ // second barrier after every read to stop lane 0 overwriting it while a
+ // slower sub-group is still reading; alternating between two makes the
+ // write of iteration `i + 1` target a different address from the read of
+ // iteration `i`, so the single barrier below is enough.
+ int slot = 0;
+
+ int32_t* slm_mem =
+ static_cast<int32_t*>(slm_mem_const.template get_multi_ptr<sycl::access::decorated::no>().get());
+
+ for (int i = 0; i < num_experts; ++i) {
+ int gemm_m = rows_per_expert[i];
+ int cumsum_rows_for_experts = pre_rows + gemm_m;
+ int cumsum_tiles_for_experts = (gemm_m + wg_tile_m - 1) / wg_tile_m + pre_tiles;
+
+ if (group_m_id >= cumsum_tiles_for_experts) {
+ pre_rows = cumsum_rows_for_experts;
+ pre_tiles = cumsum_tiles_for_experts;
+ continue;
+ }
+
+ const int expert_id = i;
+ const int64_t B_offset =
+ static_cast<int64_t>(expert_id) * static_cast<int64_t>(gemm_n) * static_cast<int64_t>(gemm_k);
+ const int64_t SB_offset =
+ static_cast<int64_t>(expert_id) * static_cast<int64_t>(gemm_n) * static_cast<int64_t>(blks);
+
+ const int8_t* ptr_A_curr_batch = Activations + static_cast<int64_t>(pre_rows) * gemm_k;
+ const int8_t* ptr_B_curr_batch = Weights + B_offset;
+ const float* ptr_SA_curr_batch = ScaleA + pre_rows;
+ const float* ptr_SB_curr_batch = ScaleB + SB_offset;
+ ElementD* ptr_D_curr_batch = Outputs == nullptr ? nullptr : Outputs + static_cast<int64_t>(pre_rows) * gemm_n;
+
+ // The scatter targets a `[batch, N]` accumulator shared by every expert,
+ // so only the per-row side tables advance with the expert; `reduce.out`
+ // stays put.
+ MoEFusedReduce expert_reduce = reduce;
+ if (reduce.enabled()) {
+ expert_reduce.row_to_token = reduce.row_to_token + pre_rows;
+ expert_reduce.row_weight = reduce.row_weight + pre_rows;
+ }
+
+ while (group_m_id < cumsum_tiles_for_experts) {
+ const int n_coord = (group_id * wg_tile_n) % gemm_n_pad / wg_tile_n;
+ const int m_coord = (group_m_id - pre_tiles);
+
+ // Claiming the next tile is a device-scope atomic on a single dword that
+ // every resident work-group hits. Issued in the gap between two tiles it
+ // is a fully exposed L2 round trip; issued here, the message is in flight
+ // across the whole GEMM and only the *use* of its result -- the SLM store
+ // below -- waits on it. Keeping the result in a private register rather
+ // than storing it straight to SLM is what defers that wait: an SLM store
+ // right after the atomic would stall lane 0 immediately, and with it the
+ // whole work-group at the mainloop's first barrier. The atomic itself
+ // cannot sink past those barriers, so it stays where it is written.
+ //
+ // The claim is otherwise untouched -- one `atomicAdd` per tile, one tile
+ // index per claim, handed out in the same order -- so both orders compute
+ // the same tiles from the same inputs and write the same bytes; only when
+ // the request is issued changes. It is worth most where the mainloop is
+ // shortest (12 k-tiles at K = 768) and there is least work per tile to
+ // hide the stall behind.
+ int claimed = 0;
+ if (claim_early && local_id == 0) {
+ claimed = cutlass::atomicAdd(atomic_buffer, 1);
+ }
+
+ xe_gemm_w4a8<GmemTiledCopyA, GmemTiledCopyB>(ptr_A_curr_batch, ptr_B_curr_batch, ptr_D_curr_batch,
+ ptr_SA_curr_batch, ptr_SB_curr_batch, gemm_m, gemm_n, gemm_k,
+ blocksize, blks, m_coord, n_coord, allow_full_tile,
+ allow_block_2d_store, prefetch_dist, expert_reduce, mma);
+
+ if (local_id == 0) {
+ slm_mem[slot] = claim_early ? claimed : cutlass::atomicAdd(atomic_buffer, 1);
+ }
+ item.barrier(sycl::access::fence_space::local_space);
+ group_id = group_range + slm_mem[slot];
+ group_m_id = (group_id * wg_tile_n) / gemm_n_pad;
+ slot ^= 1;
+ }
+ pre_rows = cumsum_rows_for_experts;
+ pre_tiles = cumsum_tiles_for_experts;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// GRF budget -> occupancy.
+//
+// `grf_size` is a request for how many registers each lane gets, and on this
+// architecture a vector engine's register file is fixed: it holds either 4
+// threads of 256 registers or 8 threads of 128. With SIMD16 sub-groups and 8
+// vector engines per Xe-core that is 8*4*16 = 512 work-items resident at the
+// large budget and 8*8*16 = 1024 at the small one.
+//
+// The kernel is persistent -- `MoEGEMM_w4a8` walks a device-scope counter until
+// the tiles run out, and the grid is sized to fill the device exactly once --
+// so this number is not a hint, it *is* the grid. Halving the register request
+// without doubling `kMaxThreadsPerSM` would launch the same work-groups as
+// before and change nothing at all; the two constants have to move together,
+// which is why they live in one place.
+// ---------------------------------------------------------------------------
+template <int GrfSize>
+struct W4A8GrfBudget;
+
+template <>
+struct W4A8GrfBudget<256> {
+ static constexpr int kMaxThreadsPerSM = 512;
+ static auto props() {
+ return sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::sub_group_size<16>,
+ sycl::ext::intel::experimental::grf_size<256>};
+ }
+};
+
+template <>
+struct W4A8GrfBudget<128> {
+ static constexpr int kMaxThreadsPerSM = 1024;
+ static auto props() {
+ return sycl::ext::oneapi::experimental::properties{sycl::ext::oneapi::experimental::sub_group_size<16>,
+ sycl::ext::intel::experimental::grf_size<128>};
+ }
+};
+
+// Submit the persistent grid at one GRF budget. `GrfSize` fixes the kernel
+// properties, the grid, and (through `KernelName`) the kernel identity; `body`
+// is the same device code either way and receives the SLM slot pair.
+template <int GrfSize, class KernelName, class Body>
+sycl::event moe_w4a8_submit_grf(sycl::queue& stream, sycl::event fill, int sm_count, int threads_per_wg, Body body) {
+ using Budget = W4A8GrfBudget<GrfSize>;
+
+ static constexpr int MaxThreadsPerSM = Budget::kMaxThreadsPerSM;
+ if (threads_per_wg <= 0 || MaxThreadsPerSM % threads_per_wg != 0) {
+ throw std::runtime_error("moe_gemm_w4a8: MaxThreadsPerSM must be divisible by MaxThreadsPerWorkgroup");
+ }
+
+ sycl::range<3> local(1, 1, threads_per_wg);
+ sycl::range<3> global(1, sm_count * MaxThreadsPerSM / threads_per_wg, 1);
+
+ auto kernel_props = Budget::props();
+
+ return stream.submit([&](sycl::handler& cgh) {
+ cgh.depends_on(fill);
+ sycl::local_accessor<int32_t, 1> local_mem(sycl::range<1>(2), cgh);
+ cgh.parallel_for<KernelName>(sycl::nd_range<3>{global * local, local}, kernel_props,
+ [=](auto) { body(local_mem); });
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Grouped-GEMM launcher (fork of `moe_dpas_int::MoEGEMMLauncher_int`, with the
+// int8 DPAS atom of `sycl_tla_s8_gemm.hpp`).
+// ---------------------------------------------------------------------------
+template <class Policy, typename ElementD>
+void MoEGEMMLauncher_w4a8(sycl::queue& stream, const int8_t* activations, const int8_t* weights,
+ const float* scale_a, const float* scale_b, ElementD* outputs, const int gemm_n,
+ const int gemm_k, const int* rows_per_expert, const int num_experts, const int blocksize,
+ const int blks, const bool allow_full_tile, const bool allow_block_2d_store,
+ const int prefetch_dist, const bool claim_early, const bool small_grf,
+ MoEFusedReduce reduce, int32_t* atomic_buffer) {
+ using Op = XE_DPAS_TT<8, int32_t, int8_t, int8_t>;
+ using WGTile = typename Policy::WGTile;
+ using SGLayout = typename Policy::SGLayout;
+ using MMA = typename TiledMMAHelper<MMA_Atom<Op>, Layout<WGTile>, SGLayout>::TiledMMA;
+ auto mma = MMA{};
+
+ int sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0);
+ const int threads_per_wg = static_cast<int>(size(mma));
+
+ using GmemTiledCopyA = typename Policy::GmemTiledCopyA;
+ using GmemTiledCopyB = typename Policy::GmemTiledCopyB;
+
+ // Zero the work-stealing counter on the host rather than from group 0 at
+ // kernel entry. The slot is pool-cached and shared across dispatches, so it
+ // arrives holding the previous call's final count; the in-kernel reset was
+ // unordered against the other work-groups' `atomicAdd` on the same dword,
+ // and `claim_early` shrinks the window it relied on to a few instructions.
+ // `depends_on` orders the fill ahead of the kernel on in-order and
+ // out-of-order queues alike, and the fill is one dword -- it costs a command
+ // rather than a synchronization.
+ auto fill = stream.memset(atomic_buffer, 0, sizeof(int32_t));
+
+ auto body = [=](sycl::local_accessor<int32_t, 1> local_mem) {
+ MoEGEMM_w4a8<GmemTiledCopyA, GmemTiledCopyB>(activations, weights, scale_a, scale_b, outputs, mma, rows_per_expert,
+ num_experts, gemm_n, gemm_k, blocksize, blks, allow_full_tile,
+ allow_block_2d_store, prefetch_dist, claim_early, reduce,
+ atomic_buffer, local_mem);
+ };
+
+ // The halved register budget is only offered to tiles whose accumulator
+ // leaves room for the staged A/B fragments, and only for `blks == 1`: a
+ // blocked re-scale carries the float shadow `tFrC` alongside the int32
+ // accumulator for the whole mainloop (see `xe_gemm_w4a8`), which doubles the
+ // live fragment and takes even a 64-register tile to the full 128. The
+ // `if constexpr` keeps the second kernel out of the 256-wide-N translation
+ // units entirely rather than leaving it dead.
+ sycl::event event;
+ bool launched = false;
+ if constexpr (Policy::kSmallGrfOk) {
+ if (small_grf && blks == 1) {
+ event = moe_w4a8_submit_grf<128, MoEW4A8GemmName<Policy, ElementD, 128>>(stream, fill, sm_count, threads_per_wg,
+ body);
+ launched = true;
+ }
+ }
+ if (!launched) {
+ event = moe_w4a8_submit_grf<256, MoEW4A8GemmName<Policy, ElementD, 256>>(stream, fill, sm_count, threads_per_wg,
+ body);
+ }
+
+ EventManager::getInstance().addEvent(event);
+ event.wait();
+}
+
+// ---------------------------------------------------------------------------
+// Prefill launch: one instantiation per tile policy (see `moe_w4a8_prefill_select_tile`).
+//
+// The rungs match the tile ladder of `launch_igemm_kblock` in
+// `sycl_tla_s8_gemm.hpp`: a grouped GEMM's M is *per expert*, so the ladder
+// walks the average rows/expert rather than the total token count.
+//
+// The M rung is a row threshold and the N rung a divisibility test, and both
+// are about not scheduling work the shape does not have:
+//
+// * `TileM` stops at 128. The 256-row tile halves how often each expert's B
+// panel is pulled through L2/DRAM (B is read once per M tile), but an
+// expert launches `ceil(M / TileM)` *full* tiles, so it only breaks even
+// where `ceil(M/256)*256 == ceil(M/128)*128` -- false at the 384 and 341
+// rows/expert the perf suite measures, where it computes 512 rows for 384
+// rows of data and reads 1.05-1.45x slower. The 8K prompt puts Qwen3-MoE
+// at exactly 512 rows/expert, where the padding argument does not apply,
+// and `test_perf_prefill_tile_sweep_long_seq` measures it there: still not
+// ahead (a tie on qwen3 up, 5.4% behind on qwen3 down). So the rung is
+// gone rather than gated -- there is no routing at which it has been
+// measured to win, and the ladder only sees the *average* rows/expert, so
+// a skewed routing would put individual experts back on the padding cliff
+// even when the average divides. Both 256-row policies stay compiled and
+// reachable through `ARK_MOE_W4A8_PREFILL_TILE` for a re-sweep.
+//
+// * `TileN = 256` halves how often A is re-read (once per N tile) and is
+// ahead or level everywhere the sweeps can compare it, so it is taken
+// whenever N divides into it exactly. `N % 256 != 0` would pad the last
+// tile the same way a ragged M does, and no shipped shape needs it: every
+// N here (1536 / 2048 / 3072) is a multiple of 256.
+//
+// The rung used to be `A_avg_M >= 256 -> 256x128` with no padding test and a
+// 128-wide N at every rung, which is what made the 384 rows/expert batch --
+// the compute-bound batch the perf suite now runs -- land on the slowest
+// column of its own sweep; it then became a padding-gated 256-row tile, which
+// the 8K-prompt sweep has now retired.
+//
+// The tile choice itself lives in `moe_w4a8_prefill_select_tile`
+// (`sycl_tla_moe_w4a8_helpers.hpp`) and happens before this function is
+// reached, so each translation unit instantiates exactly one policy. See
+// `ARK_MOE_W4A8_PREFILL_TILE` there for the override.
+//
+// `ARK_MOE_W4A8_PREFILL_FULL_TILE=0` makes every tile take the guarded
+// epilogue (see `xe_gemm_w4a8`), which is the A/B baseline for the interior-
+// tile fast path; it is read here, once per call, rather than on the device.
+//
+// `ARK_MOE_W4A8_PREFILL_STORE_2D=0` puts the epilogue back on the scalar
+// predicated store instead of the hardware 2D block store, the A/B baseline
+// for that change. The block message needs a 64-byte aligned surface base and
+// a 16-byte multiple row pitch; D's per-expert base is `outputs + pre_rows * N`
+// for a routing-dependent `pre_rows`, so the gate is on the row stride itself
+// (`N * sizeof(ElementD) % 64 == 0`, which covers the pitch as well) plus the
+// tensor base. Every shipped N (1536 / 2048 / 3072 with 16-bit D) clears it;
+// anything that does not keeps the scalar store rather than risking a
+// misaligned descriptor.
+//
+// `ARK_MOE_W4A8_PREFILL_CLAIM_EARLY=0` puts the work-stealing claim back after
+// the GEMM instead of before it, the A/B baseline for that change. The kernel
+// is persistent -- the grid is sized to the device and tiles are handed out by
+// a device-scope `atomicAdd` on one dword -- so between two tiles a work-group
+// used to sit on a fully exposed L2 round trip. Issuing the claim ahead of the
+// tile puts that round trip in flight across the DPAS mainloop instead. Which
+// tiles get computed does not change (see `MoEGEMM_w4a8`), so the two settings
+// are bit-identical and `test_prefill_claim_early_matches` asserts it.
+// `test_perf_prefill_claim_early_sweep` times the pair, and on B70 it is a tie
+// at both shapes and both batches: the claim was never the stall. Half of the
+// short-K down projection's time is per-tile cost that does not scale with `K`,
+// and ~78% of *that* is the 64 KB of D each tile writes -- bytes, not latency,
+// which is why this and the prefetch-depth sweep both come back flat. The early
+// claim stays on because it is free and counter contention grows with the
+// number of resident work-groups. The host-side counter reset it forced is a
+// correctness fix and applies to both settings.
+// `ARK_MOE_W4A8_PREFILL_SMALL_GRF=1` lets a tile policy that can afford it ask
+// for `grf_size<128>` instead of `<256>`, which doubles both the threads an Xe
+// core holds (512 -> 1024) and, because this kernel is persistent and its grid
+// is sized to fill the device exactly once, the launched grid with it. It is
+// **off by default: measured on B70, it loses, and not narrowly.**
+//
+// tile 128x128, forced grf 256 grf 128
+// qwen3 up @ 49152 tokens 2.399 ms 3.745 ms 1.56x slower
+// qwen3 up @ 65536 tokens 2.866 ms 4.579 ms 1.60x slower
+// qwen3 down @ 49152 tokens 1.794 ms 2.147 ms 1.20x slower
+// qwen3 down @ 65536 tokens 2.352 ms 2.723 ms 1.16x slower
+//
+// The occupancy did double; it bought nothing because the tile no longer fits.
+// A 128-wide-N tile's accumulator is 64 int32 per lane, which is half of a
+// 128-register file before a single operand is staged, and the measurement says
+// the other half does not hold the mainloop's live set. The penalty scales with
+// `K` -- 1.56-1.60x at K=2048 against 1.16-1.20x at K=768, i.e. with mainloop
+// trips rather than with tile count -- which places the spill inside the
+// mainloop, on the staged A/B fragments that are live across every iteration.
+// Round-to-round drift on the spilling rows also jumped from the usual 0.5-1.7%
+// to 4.2-15.3%, as scratch traffic makes the runtime depend on memory state.
+//
+// So the reason the small tiles in the ladder were swept at the large budget is
+// not an oversight: at 128 registers they stop being fast. `kSmallGrfOk` and
+// `W4A8GrfBudget` stay so the result can be re-checked on a part with a
+// different register file, but on this one the knob is closed. Both settings
+// remain bit-identical (`test_prefill_small_grf_matches`), and
+// `test_perf_prefill_grf_sweep{,_long_seq}` reproduces the table above --
+// forcing `ARK_MOE_W4A8_PREFILL_TILE=128x128`, since the ladder sends every
+// shipped qwen3 shape to `128x256`, which is not eligible either way.
+//
+// This closes the last latency knob. Prefetch depth, tile order, claim order
+// and now occupancy have all come back flat or worse, which is what the cost
+// model predicted: the down projection's per-tile cost is ~78% the 64 KB of D
+// it writes, and bytes are not something residency can hide.
+// ---------------------------------------------------------------------------
+template <class Policy, typename ElementD>
+void moe_w4a8_prefill_launch(const moe_w4a8_detail::W4A8PrefillParams& p) {
+ if (p.num_experts == 0 || p.N == 0 || p.K == 0 || p.total_tokens == 0) return;
+
+ compat::set_default_queue(*p.q);
+
+ auto* outputs = static_cast<ElementD*>(p.outputs);
+
+ MoEFusedReduce reduce{};
+ if (p.fused_out != nullptr) {
+ reduce.row_to_token = p.row_to_token;
+ reduce.row_weight = p.row_weight;
+ reduce.out = p.fused_out;
+ reduce.batch = p.fused_batch;
+ }
+
+ const bool allow_full_tile = moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_PREFILL_FULL_TILE", true);
+ const bool store_2d_aligned = !reduce.enabled() && (static_cast<size_t>(p.N) * sizeof(ElementD)) % 64 == 0 &&
+ reinterpret_cast<uintptr_t>(outputs) % 64 == 0;
+ const bool allow_block_2d_store =
+ store_2d_aligned && moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_PREFILL_STORE_2D", true);
+ const int prefetch_dist = moe_w4a8_prefill_prefetch_dist();
+ const bool claim_early = moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_PREFILL_CLAIM_EARLY", true);
+ const bool small_grf = moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_PREFILL_SMALL_GRF", false);
+ int32_t* atomic_buffer = moe_dpas_fp8::get_atomic_scratch_buffer(p.q);
+
+ MoEGEMMLauncher_w4a8<Policy, ElementD>(*p.q, p.qact, p.weights, p.ascale, p.wscale, outputs, p.N, p.K,
+ p.num_tokens_per_expert, p.num_experts, p.blocksize, p.blks,
+ allow_full_tile, allow_block_2d_store, prefetch_dist, claim_early,
+ small_grf, reduce, atomic_buffer);
+}
+
+} // namespace moe_w4a8
+
+} // namespace ark
+
+#endif // ARK_XPU && ARK_SYCL_TLA
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_helpers.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_helpers.hpp
new file mode 100644
index 000000000..5c3c2ee39
--- /dev/null
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_helpers.hpp
@@ -0,0 +1,634 @@
+// SYCL MoE W4A8 -- cutlass-free front end (declarations + host helpers)
+//
+// Companion to `sycl_tla_moe_w4a8.hpp`. That header pulls in the whole
+// cutlass-sycl / CuTe include set and defines every W4A8 kernel template, so a
+// translation unit that includes it pays the full parse *and* instantiates
+// whichever kernels it names. Concentrating all of them in one TU is what made
+// the generated `sycl_tla_moe_w4a8.cpp` peak at ~4.2 GB of compiler RSS.
+//
+// This header carries the part the public entry points need and no kernels:
+// the host-side shape/environment helpers, POD parameter structs, and
+// declarations of the per-variant `dispatch` entry points. Everything it
+// includes is cutlass-free, so the dispatcher TU that includes *this* header
+// compiles for almost nothing. The device scratch pools are declared in
+// `sycl_tla_moe_w4a8_scratch.hpp` and defined in the matching `.cpp`.
+//
+// Each declared entry point is defined in its own generated TU (see
+// `sycl_tla_generation.cmake`), mirroring how `sycl_tla_moe_prefill_s4_-
+// helpers.hpp` fans the S4 prefill tiles out across TUs. The split axes are
+// documented next to the declarations below.
+//
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <limits>
+#include <map>
+#include <mutex>
+#include <stdexcept>
+#include <string>
+#include <utility>
+#include <vector>
+
+#ifdef ARK_XPU
+#include <sycl/sycl.hpp>
+#endif
+
+#if defined(ARK_XPU) && defined(ARK_SYCL_TLA)
+
+// `env_flag_enabled`, `fill_expert_id_per_token`, `SG_SIZE` / `N_TILE`.
+// Cutlass-free, unlike the DPAS headers.
+#include "sycl_tla_moe_decode.hpp"
+// Scratch slab acquire/release. Declarations only -- the `DeviceMemoryPool`
+// bookkeeping lives in `sycl_tla_moe_w4a8_scratch.cpp`, which keeps `utils.hpp`
+// and the bestla JIT headers behind it out of this include chain.
+#include "sycl_tla_moe_w4a8_scratch.hpp"
+
+namespace ark {
+namespace moe_w4a8 {
+
+using moe_decode_detail::N_TILE;
+using moe_decode_detail::SG_SIZE;
+
+// Symmetric int4 full range: 2^(bits-1). Matches `fullrange` in
+// `xpu_wrapper.hpp`'s `packscale` rescale kernel.
+constexpr float kInt4FullRange = 8.0f;
+constexpr float kInt8Max = 127.0f;
+constexpr int64_t kInt8AccumMax = 127;
+constexpr int64_t kMaxAccumK = std::numeric_limits<int32_t>::max() / (kInt8AccumMax * kInt8AccumMax);
+
+// K elements decoded per work-item in the prepack kernel (one 32-bit word of
+// packed nibbles). Requires `K % 8 == 0`, which the shape gate enforces.
+constexpr int kPrepackOctet = 8;
+
+
+// Host-side helpers
+// ---------------------------------------------------------------------------
+
+// Resolve the effective AUTO_S8 re-scale block size.
+//
+// `requested <= 0` (the `group=-1` spelling) or any value that is not a valid
+// block size falls back to `K`, i.e. one scale per output channel -- the
+// maximum-efficiency shape. `ARK_MOE_W4A8_AUTO_S8` overrides the argument so
+// benchmarks can sweep the block size without touching the caller.
+inline int moe_w4a8_rescale_block_size(int K, int group_size, int requested) {
+ int v = requested;
+ const char* env = std::getenv("ARK_MOE_W4A8_AUTO_S8");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long parsed = std::strtol(env, &end, 10);
+ if (end != env) v = static_cast<int>(parsed);
+ }
+ if (K <= 0) return K;
+ if (v <= 0 || v >= K) return K;
+ if (group_size > 0 && (v < group_size || v % group_size != 0)) return K;
+ if (K % v != 0) return K;
+ // The mainloop slices each block into 64-wide DPAS K tiles.
+ if (v % 64 != 0) return K;
+ return v;
+}
+
+inline bool moe_w4a8_k_ok(int K) {
+ return K > 0 && static_cast<int64_t>(K) <= kMaxAccumK;
+}
+
+// Shape preconditions shared by the prepack, prefill and decode paths.
+inline bool moe_w4a8_shape_ok(int N, int K, int group_size) {
+ if (N <= 0 || K <= 0 || group_size <= 0) return false;
+ if (N % N_TILE != 0) return false;
+ if (K % 64 != 0) return false;
+ if (!moe_w4a8_k_ok(K)) return false;
+ if (group_size % kPrepackOctet != 0) return false;
+ if (K % group_size != 0) return false;
+ return true;
+}
+
+// Token count at or below which the auto phase selection picks the decode
+// GEMV. Mirrors `ARK_MOE_AUTO_DECODE_MAX_TOKENS` used by the Python `moe()`
+// dispatcher; overridable with `ARK_MOE_W4A8_DECODE_MAX_TOKENS`.
+inline int moe_w4a8_decode_max_tokens() {
+ const char* env = std::getenv("ARK_MOE_W4A8_DECODE_MAX_TOKENS");
+ if (env == nullptr) return 128;
+ char* end = nullptr;
+ const long parsed = std::strtol(env, &end, 10);
+ if (end == env || parsed < 0) return 128;
+ return static_cast<int>(parsed);
+}
+
+// Prefill tile selection.
+//
+// The ladder used to live inside `moe_w4a8_prefill_dispatch<ElementD>`, which
+// meant the TU holding it instantiated all six policies. It is pure host
+// arithmetic, so it moves here and the caller launches only the tile it picks
+// -- that is what lets each policy live in its own translation unit.
+//
+// Rungs (measured on Arc Pro B60, see the sweep notes in
+// `sycl_tla_moe_w4a8.hpp`): tiny M takes the 8-row tile, the 64-row tile
+// covers M up to 128, and above that the choice is between the 256-wide and
+// the 128-wide N tile depending on whether N splits evenly.
+enum class W4A8PrefillTile { M8, M64, M128, M128N256, M256N128, Large };
+
+// `ARK_MOE_W4A8_PREFILL_TILE` overrides the choice with an explicit `MxN` tile
+// so it can be swept on hardware without a rebuild; anything unrecognised --
+// including the default `auto` -- keeps the ladder.
+inline W4A8PrefillTile moe_w4a8_prefill_select_tile(int A_avg_M, int N) {
+ const char* tile_env = std::getenv("ARK_MOE_W4A8_PREFILL_TILE");
+ if (tile_env != nullptr) {
+ if (std::strcmp(tile_env, "8x128") == 0) return W4A8PrefillTile::M8;
+ if (std::strcmp(tile_env, "64x128") == 0) return W4A8PrefillTile::M64;
+ if (std::strcmp(tile_env, "128x128") == 0) return W4A8PrefillTile::M128;
+ if (std::strcmp(tile_env, "128x256") == 0) return W4A8PrefillTile::M128N256;
+ if (std::strcmp(tile_env, "256x128") == 0) return W4A8PrefillTile::M256N128;
+ if (std::strcmp(tile_env, "256x256") == 0) return W4A8PrefillTile::Large;
+ }
+
+ if (A_avg_M < 16) return W4A8PrefillTile::M8;
+ if (A_avg_M < 128) return W4A8PrefillTile::M64;
+ if ((N % 256) == 0) return W4A8PrefillTile::M128N256;
+ return W4A8PrefillTile::M128;
+}
+
+} // namespace moe_w4a8
+
+// ---------------------------------------------------------------------------
+// Per-variant entry points.
+//
+// Every function below is defined in its own generated translation unit; this
+// header only declares them, so including it never instantiates a kernel. The
+// parameter structs are plain PODs of scalars and pointers -- deliberately no
+// cutlass types -- so the declarations stay usable from a TU that has not seen
+// CuTe.
+//
+// The split follows `sycl_tla_moe_prefill_s4_helpers.hpp`: one TU per
+// (dtype x tile) for the DPAS prefill, which is where the compile cost is, and
+// coarser grouping for the plain-SYCL kernels. Kernel counts per TU:
+//
+// prefill_{f16,bf16}_* : 1-2 DPAS kernels (12 TUs)
+// decode_{f16,bf16} : 7 GEMV kernels (2 TUs)
+// quant_{f16,bf16} : 11 quant kernels (2 TUs)
+// prepack_{f16,bf16} : 2 rescale kernels (2 TUs)
+//
+// versus 52 kernels -- 12 of them DPAS -- in the single TU this replaced.
+//
+// The prefill TUs whose policy sets `kSmallGrfOk` build their DPAS kernel twice,
+// once per GRF budget (see `W4A8GrfBudget` in `sycl_tla_moe_w4a8.hpp`) -- the
+// register request is a compile-time kernel property, so the runtime choice
+// needs both to exist. That is the 128-wide-N tiles only; the 256-wide-N ones,
+// which is where the shipped shapes land, still build exactly one.
+// ---------------------------------------------------------------------------
+namespace moe_w4a8_detail {
+
+// One-shot AUTO_S8 prepack: int4 + per-group scales -> int8 + block scales.
+struct W4A8PrepackParams {
+ sycl::queue* q = nullptr;
+ const void* weights_s4 = nullptr; // [E, N, K/2] packed nibbles
+ const void* scales = nullptr; // [E, N, K/group_size] act dtype
+ int8_t* weights_s8 = nullptr; // [E, N, K] out
+ float* wscales = nullptr; // [E, N, blks] out
+ int num_experts = 0;
+ int N = 0;
+ int K = 0;
+ int group_size = 0;
+ int blocksize = 0;
+ int blks = 0;
+};
+
+// Per-token activation quantization, optionally emitting the decode expert map
+// in the same pass (`expert_map != nullptr`).
+struct W4A8QuantParams {
+ sycl::queue* q = nullptr;
+ const void* activations = nullptr; // [T, K] act dtype
+ int8_t* qact = nullptr; // [T, K] out
+ float* ascale = nullptr; // [T] out
+ int total_tokens = 0;
+ int K = 0;
+ int* expert_map = nullptr;
+ const int* num_tokens_per_expert = nullptr;
+ int num_experts = 0;
+};
+
+// Decode GEMV (K-split or legacy, chosen inside the TU).
+struct W4A8DecodeParams {
+ sycl::queue* q = nullptr;
+ const int8_t* qact = nullptr;
+ const float* ascale = nullptr;
+ const int8_t* weights = nullptr;
+ const float* wscale = nullptr;
+ void* outputs = nullptr; // act dtype
+ const int* expert_id_per_token = nullptr;
+ int total_tokens = 0;
+ int N = 0;
+ int K = 0;
+ int blocksize = 0;
+ int blks = 0;
+};
+
+// Grouped prefill GEMM. The tile is chosen by `moe_w4a8_prefill_select_tile`
+// before the call, so each TU below instantiates exactly one policy.
+struct W4A8PrefillParams {
+ sycl::queue* q = nullptr;
+ const int8_t* qact = nullptr;
+ const float* ascale = nullptr;
+ const int8_t* weights = nullptr;
+ const float* wscale = nullptr;
+ void* outputs = nullptr; // act dtype
+ const int* num_tokens_per_expert = nullptr;
+ int num_experts = 0;
+ int N = 0;
+ int K = 0;
+ int blocksize = 0;
+ int blks = 0;
+ int total_tokens = 0;
+ // Optional fused top-k reduction; `fused_out != nullptr` turns it on.
+ const int* row_to_token = nullptr;
+ const float* row_weight = nullptr;
+ float* fused_out = nullptr;
+ int fused_batch = 0;
+};
+
+void prepack_f16(const W4A8PrepackParams& params);
+void prepack_bf16(const W4A8PrepackParams& params);
+
+void quant_f16(const W4A8QuantParams& params);
+void quant_bf16(const W4A8QuantParams& params);
+
+void decode_f16(const W4A8DecodeParams& params);
+void decode_bf16(const W4A8DecodeParams& params);
+
+void prefill_f16_m8(const W4A8PrefillParams& params);
+void prefill_f16_m64(const W4A8PrefillParams& params);
+void prefill_f16_m128(const W4A8PrefillParams& params);
+void prefill_f16_m128n256(const W4A8PrefillParams& params);
+void prefill_f16_m256n128(const W4A8PrefillParams& params);
+void prefill_f16_large(const W4A8PrefillParams& params);
+
+void prefill_bf16_m8(const W4A8PrefillParams& params);
+void prefill_bf16_m64(const W4A8PrefillParams& params);
+void prefill_bf16_m128(const W4A8PrefillParams& params);
+void prefill_bf16_m128n256(const W4A8PrefillParams& params);
+void prefill_bf16_m256n128(const W4A8PrefillParams& params);
+void prefill_bf16_large(const W4A8PrefillParams& params);
+
+// ---------------------------------------------------------------------------
+// Public entry point 1 -- one-shot AUTO_S8 prepack.
+//
+// Converts auto-round's packed int4-sym weights + per-group scales into the
+// int8 weights + FP32 block scales the W4A8 kernels consume. Callers are
+// expected to run this once per checkpoint and keep the results resident.
+// ---------------------------------------------------------------------------
+inline void moe_w4a8_prepack(sycl::queue* q, void* weights_s4, void* scales, void* weights_s8, void* wscales,
+ BTLA_DTYPE act_dtype, int num_experts, int N, int K, int group_size,
+ int rescale_group_size) {
+ if (q == nullptr) {
+ throw std::invalid_argument("moe_w4a8_prepack: stream must be a valid SYCL queue");
+ }
+ if (num_experts <= 0) {
+ throw std::invalid_argument("moe_w4a8_prepack: num_experts must be positive");
+ }
+ if (!moe_w4a8::moe_w4a8_shape_ok(N, K, group_size)) {
+ throw std::invalid_argument("moe_w4a8_prepack: unsupported shape (need N % 16 == 0, K % 64 == 0, K <= " +
+ std::to_string(moe_w4a8::kMaxAccumK) +
+ " to avoid int32 accumulator overflow, group_size % 8 == 0 and K % group_size == 0)");
+ }
+ if (weights_s4 == nullptr || scales == nullptr || weights_s8 == nullptr || wscales == nullptr) {
+ throw std::invalid_argument("moe_w4a8_prepack: null buffer");
+ }
+ if (act_dtype != BTLA_DTYPE::F16 && act_dtype != BTLA_DTYPE::BF16) {
+ throw std::invalid_argument("moe_w4a8_prepack: act_dtype must be F16 or BF16");
+ }
+
+ W4A8PrepackParams params;
+ params.q = q;
+ params.weights_s4 = weights_s4;
+ params.scales = scales;
+ params.weights_s8 = static_cast<int8_t*>(weights_s8);
+ params.wscales = static_cast<float*>(wscales);
+ params.num_experts = num_experts;
+ params.N = N;
+ params.K = K;
+ params.group_size = group_size;
+ params.blocksize = moe_w4a8::moe_w4a8_rescale_block_size(K, group_size, rescale_group_size);
+ params.blks = K / params.blocksize;
+
+ if (act_dtype == BTLA_DTYPE::F16) {
+ prepack_f16(params);
+ } else {
+ prepack_bf16(params);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Public entry point 2 -- W4A8 MoE GEMM (prefill + decode).
+//
+// `phase`: 0 = auto (decode when `total_tokens <=
+// ARK_MOE_W4A8_DECODE_MAX_TOKENS`), 1 = force decode GEMV, 2 = force prefill
+// grouped GEMM.
+//
+// Two optional call contracts trade interface work for DRAM traffic. Both are
+// opt-in and the defaults are unchanged.
+//
+// Pre-quantized activations (`qact_in` + `ascale_in`)
+// ---------------------------------------------------
+// By default the call quantizes `[T, K]` itself: it reads the 16-bit
+// activations, writes an int8 copy and the GEMM reads that copy back, i.e.
+// `4 * T * K` bytes on top of the GEMM's own operands. On the down-projection
+// that is 27% of everything the call moves -- and it is redundant, because the
+// producer of those activations (the SiLU/gate elementwise kernel) already
+// writes `[T, K]` once and could write int8 plus a per-row scale instead: the
+// absmax it needs is a reduction over the row it is already holding. When both
+// pointers are supplied all three streams disappear, along with a kernel
+// launch. `ascale_in` is `[T]` fp32, `scale = absmax / 127`, matching what
+// `launch_act_dynamic_quant` writes.
+//
+// Fused top-k reduction (`row_to_token` + `routing_weights` + `fused_out`)
+// -----------------------------------------------------------------------
+// See `MoEFusedReduce`. Prefill only, and the accumulator must be zeroed by
+// the caller; `outputs` is then unused and may be null.
+// ---------------------------------------------------------------------------
+inline void moe_gemm_w4a8(sycl::queue* q, void* activations, void* weights_s8, void* wscales, void* outputs,
+ BTLA_DTYPE act_dtype, int N, int K, int rescale_block_size,
+ int* num_tokens_per_expert, int num_experts, int total_tokens, int phase,
+ const void* qact_in = nullptr, const float* ascale_in = nullptr,
+ const int* row_to_token = nullptr, const float* routing_weights = nullptr,
+ float* fused_out = nullptr, int fused_batch = 0) {
+ if (q == nullptr) {
+ throw std::invalid_argument("moe_gemm_w4a8: stream must be a valid SYCL queue");
+ }
+ if (num_experts <= 0) {
+ throw std::invalid_argument("moe_gemm_w4a8: num_experts must be positive");
+ }
+ if (total_tokens < 0) {
+ throw std::invalid_argument("moe_gemm_w4a8: total_tokens must be non-negative");
+ }
+ if (N % moe_w4a8::N_TILE != 0) {
+ throw std::invalid_argument("moe_gemm_w4a8: N must be a multiple of 16");
+ }
+ if (K % 64 != 0) {
+ throw std::invalid_argument("moe_gemm_w4a8: K must be a multiple of 64");
+ }
+ if (!moe_w4a8::moe_w4a8_k_ok(K)) {
+ throw std::invalid_argument("moe_gemm_w4a8: K must be <= " + std::to_string(moe_w4a8::kMaxAccumK) +
+ " to avoid int32 accumulator overflow");
+ }
+ if (rescale_block_size <= 0 || rescale_block_size > K || K % rescale_block_size != 0 ||
+ rescale_block_size % 64 != 0) {
+ throw std::invalid_argument(
+ "moe_gemm_w4a8: rescale_block_size must be a multiple of 64 that divides K "
+ "(use moe_w4a8_rescale_block_size to resolve it)");
+ }
+ if (act_dtype != BTLA_DTYPE::F16 && act_dtype != BTLA_DTYPE::BF16) {
+ throw std::invalid_argument("moe_gemm_w4a8: act_dtype must be F16 or BF16");
+ }
+ if (weights_s8 == nullptr || wscales == nullptr || num_tokens_per_expert == nullptr) {
+ throw std::invalid_argument("moe_gemm_w4a8: weights_s8, wscales and num_tokens_per_expert must be non-null");
+ }
+
+ const bool prequantized = qact_in != nullptr || ascale_in != nullptr;
+ if (prequantized && (qact_in == nullptr || ascale_in == nullptr)) {
+ throw std::invalid_argument("moe_gemm_w4a8: pre-quantized activations need both qact and ascale");
+ }
+ if (!prequantized && activations == nullptr) {
+ throw std::invalid_argument("moe_gemm_w4a8: null activations");
+ }
+
+ const bool fused_reduce = row_to_token != nullptr || routing_weights != nullptr || fused_out != nullptr;
+ if (fused_reduce && (row_to_token == nullptr || routing_weights == nullptr || fused_out == nullptr ||
+ fused_batch <= 0)) {
+ throw std::invalid_argument(
+ "moe_gemm_w4a8: the fused top-k reduction needs row_to_token, routing_weights, a zeroed [batch, N] "
+ "fp32 output and batch > 0");
+ }
+ if (!fused_reduce && outputs == nullptr) {
+ throw std::invalid_argument("moe_gemm_w4a8: null outputs");
+ }
+ if (total_tokens == 0) return;
+
+ const bool is_f16 = act_dtype == BTLA_DTYPE::F16;
+ const int blocksize = rescale_block_size;
+ const int blks = K / blocksize;
+
+ const bool use_decode =
+ phase == 1 || (phase != 2 && total_tokens <= moe_w4a8::moe_w4a8_decode_max_tokens());
+
+ if (fused_reduce && use_decode) {
+ throw std::invalid_argument("moe_gemm_w4a8: the fused top-k reduction is prefill-only");
+ }
+
+ const int8_t* qact = static_cast<const int8_t*>(qact_in);
+ const float* ascale = ascale_in;
+ int8_t* qact_scratch = nullptr;
+ float* ascale_scratch = nullptr;
+
+ if (!prequantized) {
+ // Quantized activations + per-token scales share one slab: `[T, K]` int8
+ // followed by `[T]` fp32 (the int8 region is already 4-byte aligned because
+ // K is a multiple of 64).
+ const size_t qact_bytes = static_cast<size_t>(total_tokens) * static_cast<size_t>(K);
+ const size_t scale_offset = (qact_bytes + sizeof(float) - 1) / sizeof(float) * sizeof(float);
+ const size_t slab_bytes = scale_offset + static_cast<size_t>(total_tokens) * sizeof(float);
+ uint8_t* slab = moe_w4a8::acquire_qact_scratch(q, slab_bytes);
+ qact_scratch = reinterpret_cast<int8_t*>(slab);
+ ascale_scratch = reinterpret_cast<float*>(slab + scale_offset);
+ qact = qact_scratch;
+ ascale = ascale_scratch;
+ }
+
+ // Decode consumes `expert_id_per_token`; the activation-quant kernel already
+ // runs one sub-group per token, so it derives the map as well instead of
+ // paying for a second launch (`fill_expert_id_per_token`) on a timeline where
+ // one call is issued per generated token. Prefill passes nullptr and the scan
+ // is not compiled into the work. With pre-quantized activations that kernel
+ // does not run at all, so decode falls back to the standalone scan.
+ int* expert_map = nullptr;
+ if (use_decode) {
+ expert_map = moe_w4a8::acquire_expert_map_scratch(q, static_cast<size_t>(total_tokens) * sizeof(int));
+ }
+
+ if (prequantized) {
+ if (use_decode) {
+ moe_decode_detail::fill_expert_id_per_token(q, expert_map, num_tokens_per_expert, num_experts,
+ total_tokens);
+ }
+ } else {
+ W4A8QuantParams qp;
+ qp.q = q;
+ qp.activations = activations;
+ qp.qact = qact_scratch;
+ qp.ascale = ascale_scratch;
+ qp.total_tokens = total_tokens;
+ qp.K = K;
+ qp.expert_map = expert_map;
+ qp.num_tokens_per_expert = num_tokens_per_expert;
+ qp.num_experts = num_experts;
+ if (is_f16) {
+ quant_f16(qp);
+ } else {
+ quant_bf16(qp);
+ }
+ }
+
+ const auto* weights = static_cast<const int8_t*>(weights_s8);
+ const auto* wscale = static_cast<const float*>(wscales);
+
+ if (use_decode) {
+ W4A8DecodeParams dp;
+ dp.q = q;
+ dp.qact = qact;
+ dp.ascale = ascale;
+ dp.weights = weights;
+ dp.wscale = wscale;
+ dp.outputs = outputs;
+ dp.expert_id_per_token = expert_map;
+ dp.total_tokens = total_tokens;
+ dp.N = N;
+ dp.K = K;
+ dp.blocksize = blocksize;
+ dp.blks = blks;
+ if (is_f16) {
+ decode_f16(dp);
+ } else {
+ decode_bf16(dp);
+ }
+ return;
+ }
+
+ W4A8PrefillParams pp;
+ pp.q = q;
+ pp.qact = qact;
+ pp.ascale = ascale;
+ pp.weights = weights;
+ pp.wscale = wscale;
+ pp.outputs = outputs;
+ pp.num_tokens_per_expert = num_tokens_per_expert;
+ pp.num_experts = num_experts;
+ pp.N = N;
+ pp.K = K;
+ pp.blocksize = blocksize;
+ pp.blks = blks;
+ pp.total_tokens = total_tokens;
+ if (fused_reduce) {
+ pp.row_to_token = row_to_token;
+ pp.row_weight = routing_weights;
+ pp.fused_out = fused_out;
+ pp.fused_batch = fused_batch;
+ }
+
+ // One `dispatch` symbol per (dtype, tile); only the selected one is linked
+ // against a kernel-bearing TU, and none of them is instantiated here.
+ switch (moe_w4a8::moe_w4a8_prefill_select_tile(total_tokens / num_experts, N)) {
+ case moe_w4a8::W4A8PrefillTile::M8:
+ if (is_f16) {
+ prefill_f16_m8(pp);
+ } else {
+ prefill_bf16_m8(pp);
+ }
+ break;
+ case moe_w4a8::W4A8PrefillTile::M64:
+ if (is_f16) {
+ prefill_f16_m64(pp);
+ } else {
+ prefill_bf16_m64(pp);
+ }
+ break;
+ case moe_w4a8::W4A8PrefillTile::M128N256:
+ if (is_f16) {
+ prefill_f16_m128n256(pp);
+ } else {
+ prefill_bf16_m128n256(pp);
+ }
+ break;
+ case moe_w4a8::W4A8PrefillTile::M256N128:
+ if (is_f16) {
+ prefill_f16_m256n128(pp);
+ } else {
+ prefill_bf16_m256n128(pp);
+ }
+ break;
+ case moe_w4a8::W4A8PrefillTile::Large:
+ if (is_f16) {
+ prefill_f16_large(pp);
+ } else {
+ prefill_bf16_large(pp);
+ }
+ break;
+ case moe_w4a8::W4A8PrefillTile::M128:
+ default:
+ if (is_f16) {
+ prefill_f16_m128(pp);
+ } else {
+ prefill_bf16_m128(pp);
+ }
+ break;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Public entry point 3 -- the per-token activation quantization on its own.
+//
+// This is the same pass `moe_gemm_w4a8` runs internally when the caller does
+// not supply `qact_in`/`ascale_in`, exposed so it can be *measured*. Until now
+// the quantizer had no standalone entry point, so the harness priced it by
+// differencing a 16-bit-input call against a pre-quantized one: two GEMM
+// timings subtracted, with the whole GEMM's run-to-run noise landing on a
+// number that is a quarter of one of them. Every claim about the quantizer --
+// its share of the call, the bandwidth it achieves, the ceiling a faster one
+// could reach -- rests on that difference, so it is worth having directly.
+//
+// It is a measurement and pre-quantization entry point, not a new call
+// contract: `moe_gemm_w4a8` is unchanged, and its result is what feeds
+// `qact_in`/`ascale_in` there. `expert_map` stays null (the decode map is a
+// decode-path concern the fused pass folds in for itself).
+//
+// - activations : [total_tokens, K] act dtype
+// - qact : [total_tokens, K] int8 out
+// - ascale : [total_tokens] fp32 out, `absmax / 127`
+// ---------------------------------------------------------------------------
+inline void moe_w4a8_quant_act(sycl::queue* q, const void* activations, void* qact, void* ascale,
+ BTLA_DTYPE act_dtype, int total_tokens, int K) {
+ if (q == nullptr) {
+ throw std::invalid_argument("moe_w4a8_quant_act: stream must be a valid SYCL queue");
+ }
+ if (total_tokens < 0) {
+ throw std::invalid_argument("moe_w4a8_quant_act: total_tokens must be non-negative");
+ }
+ if (K <= 0 || K % 64 != 0) {
+ throw std::invalid_argument("moe_w4a8_quant_act: K must be a positive multiple of 64");
+ }
+ if (activations == nullptr || qact == nullptr || ascale == nullptr) {
+ throw std::invalid_argument("moe_w4a8_quant_act: null buffer");
+ }
+ if (act_dtype != BTLA_DTYPE::F16 && act_dtype != BTLA_DTYPE::BF16) {
+ throw std::invalid_argument("moe_w4a8_quant_act: act_dtype must be F16 or BF16");
+ }
+ if (total_tokens == 0) return;
+
+ W4A8QuantParams qp;
+ qp.q = q;
+ qp.activations = activations;
+ qp.qact = static_cast<int8_t*>(qact);
+ qp.ascale = static_cast<float*>(ascale);
+ qp.total_tokens = total_tokens;
+ qp.K = K;
+
+ if (act_dtype == BTLA_DTYPE::F16) {
+ quant_f16(qp);
+ } else {
+ quant_bf16(qp);
+ }
+}
+
+// Resolve the effective AUTO_S8 block size (host helper, also exported to
+// Python so callers can size the `wscales` tensor consistently).
+inline int moe_w4a8_rescale_block_size(int K, int group_size, int rescale_group_size) {
+ return moe_w4a8::moe_w4a8_rescale_block_size(K, group_size, rescale_group_size);
+}
+
+} // namespace moe_w4a8_detail
+
+} // namespace ark
+
+#endif // ARK_XPU && ARK_SYCL_TLA
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_kernels.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_kernels.hpp
new file mode 100644
index 000000000..c4b84fd9d
--- /dev/null
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_kernels.hpp
@@ -0,0 +1,1095 @@
+// SYCL MoE W4A8 -- cutlass-free kernels (activation quant, prepack, decode)
+//
+// Split out of `sycl_tla_moe_w4a8.hpp` so the translation units that only need
+// these kernels never parse the cutlass-sycl / CuTe include set. Nothing here
+// touches CuTe: the activation-quantization, AUTO_S8 prepack and decode-GEMV
+// kernels are plain SYCL, and only the grouped prefill GEMM needs DPAS.
+//
+// The narrative for each kernel -- the message-width / unroll / single-pass
+// choices for the quant pass, the AUTO_S8 re-scale, and the decode K-split
+// lane mapping -- stays inline with the code below. See
+// `sycl_tla_moe_w4a8.hpp` for the overall W4A8 design.
+//
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <stdexcept>
+#include <type_traits>
+
+#ifdef ARK_XPU
+#include <sycl/sycl.hpp>
+#endif
+
+#if defined(ARK_XPU) && defined(ARK_SYCL_TLA)
+
+// `env_flag_enabled`, `fill_expert_id_per_token`, `SG_SIZE` / `N_TILE`, and
+// the shared nibble decoders. Cutlass-free.
+#include "sycl_tla_moe_decode.hpp"
+// Scratch pools, host-side helpers and the parameter structs the launch
+// wrappers below are expressed in terms of.
+#include "sycl_tla_moe_w4a8_helpers.hpp"
+
+namespace ark {
+namespace moe_w4a8 {
+
+using moe_dequant::decode_int4_octet;
+
+// ---------------------------------------------------------------------------
+// Kernel name tags (one per specialization, required for SYCL kernel naming)
+// ---------------------------------------------------------------------------
+template <typename ScalarT>
+class MoEW4A8ActQuant;
+
+template <typename ScalarT, int VEC, int UNROLL>
+class MoEW4A8ActQuantVec;
+
+template <typename ScalarT, int VEC, int MAX_STEPS>
+class MoEW4A8ActQuantSingle;
+
+template <typename ScalarT>
+class MoEW4A8ScaleReduce;
+
+template <typename ScalarT>
+class MoEW4A8Repack;
+
+template <typename ElementD>
+class MoEW4A8DecodeGemv;
+
+template <typename ElementD, int NCOLS, int CH>
+class MoEW4A8DecodeKSplit;
+
+// ---------------------------------------------------------------------------
+// Per-token dynamic activation quantization: act dtype -> int8 + fp32 scale.
+//
+// One sub-group per token: lanes stride the K axis (coalesced), reduce the
+// absmax with `reduce_over_group`, then write back the quantized row. A row
+// that is entirely zero gets `scale = 0` and quantizes to all zeros (the
+// reciprocal is forced to 0 instead of inf).
+//
+// The decode path also needs `expert_id_per_token`, which
+// `moe_decode_detail::fill_expert_id_per_token` produces in a kernel of its
+// own. That kernel does one tiny scan per token, so at decode sizes it is pure
+// launch overhead on a timeline where the GEMV itself is only tens of
+// microseconds and one call is issued per generated token. This kernel already
+// runs one sub-group per token, so when `expert_id_per_token != nullptr` lane 0
+// folds the same scan in and the separate launch disappears -- the same "one
+// fewer kernel launch on the decode timeline" the FP8 DPAS decode dispatch
+// gets by consuming `num_tokens_per_expert` directly. The scan is the verbatim
+// body of `fill_expert_id_per_token`, including its clamp to
+// `num_experts - 1` for a routing table that sums to less than `total_tokens`.
+//
+// Message width (the prefill cost that matters)
+// ---------------------------------------------
+// This kernel is a pure streaming pass -- it reads `[T, K]` activations twice
+// (absmax, then quantize) and writes `[T, K]` int8 -- so at prefill sizes it is
+// a sizeable fraction of the whole `moe_gemm_w4a8` call, not a preamble. At
+// 32768 routed rows and K = 2048 it touches ~200 MB, next to the ~400 MB the
+// grouped GEMM streams for the qwen3 up-proj weights.
+//
+// The scalar mapping below (`k = lane; k < K; k += SG_SIZE`) moves that traffic
+// in the *narrowest* messages the sub-group can issue: 16 lanes x one 16-bit
+// element is a 32-byte load and 16 lanes x one int8 is a **16-byte** store, i.e.
+// a quarter of a cache line per store message. That is the same defect the
+// decode GEMV had before the K-split rewrite, and it was worth 1.09-1.93x there.
+//
+// `launch_act_dynamic_quant_vec` fixes it the same way: each lane owns `VEC`
+// *consecutive* elements, so one message covers `SG_SIZE * VEC` contiguous
+// elements -- 256 bytes of activations and 128 bytes of int8 at `VEC = 8`.
+// Both passes read the same `sycl::vec`, and the second pass re-reads a row the
+// first pass just touched, so it is served by the cache rather than DRAM.
+//
+// `VEC` is chosen from K: 8 when `K % 128 == 0` (every shipped MoE shape --
+// 768 / 1536 / 2048 / 3072), otherwise 4, which the `K % 64 == 0` shape gate
+// always satisfies. A misaligned base pointer (never the case for torch
+// allocations or the scratch pool) falls back to the scalar kernel, and
+// `ARK_MOE_W4A8_ACT_QUANT_VEC=0` forces it for A/B measurement.
+//
+// `test_perf_prefill_act_quant_sweep` on BMG (384 rows/expert, bf16 act) puts
+// the widened messages at 1.12x (qwen3 up), 1.10x (qwen3 down), 1.15x (minimax
+// up) and 1.07x (minimax down) of the scalar mapping on the *whole*
+// `moe_gemm_w4a8` call -- the quantization pass alone is a larger share of
+// prefill than that, since the GEMM around it is unchanged. (Earlier runs of
+// the same sweep read 1.05 / 1.13 / 1.11 / 1.04, 1.13 / 1.14 / 1.12 / 1.04 and
+// 1.14 / 1.07 / 1.10 / 1.07: the ranking is stable, the individual ratios move
+// by a few percent between runs.)
+//
+// `sycl::vec<uint16_t, VEC>` is used rather than `sycl::vec<ScalarT, VEC>`
+// because `sycl::vec` of `bfloat16` is not universally available; the elements
+// are `bit_cast` back one at a time, exactly like the decode kernels'
+// `ActVec` loads in `sycl_tla_moe_decode.hpp`.
+//
+// Requests in flight (the cost widening the messages did not address)
+// -------------------------------------------------------------------
+// Wide messages fix how many bytes each *request* moves; they do not change
+// how many requests a work-item has outstanding. This kernel walks K with a
+// runtime trip count (`steps = K / (SG_SIZE * VEC)`) and folds every vector
+// into the same `local_max` accumulator, so the loop reads as: issue one load,
+// stall until it returns, `fmax` it, repeat. Xe cores execute in order and
+// `fmax` is not reassociated without fast-math, so each thread keeps roughly
+// *one* 256-byte load in flight.
+//
+// That is a Little's-law problem, not a bandwidth one: 1280 concurrent
+// sub-groups (the B60's occupancy ceiling -- 160 XVEs x 8 thread slots) x 256
+// bytes is ~320 KB of in-flight reads, under the ~456 KB a 456 GB/s device
+// needs to stay busy across a ~1 us memory latency, and a real launch rarely
+// fills every slot. The same argument is why the decode GEMV loads two chunks
+// per iteration (`launch_w4a8_decode_ksplit`), and why the pair is spelled out
+// there rather than left to the compiler.
+//
+// `UNROLL` gives the pass the same treatment: each iteration loads `UNROLL`
+// *independent* vectors before consuming any of them, and reduces them into
+// `UNROLL` separate partial maxima so the loads do not serialize behind the
+// accumulator chain either. At the default `UNROLL = 4` a thread holds 1 KB,
+// which clears the 456 KB well before every slot is occupied. The quantize
+// pass batches its loads the same way, and its stores are already independent.
+// `steps % UNROLL` vectors are left to a tail loop -- `K = 768` (qwen3 down)
+// gives `steps = 6`, so the tail is real code, not a formality.
+//
+// Nothing that rounds changes: the per-lane partial reduction is still `fmax`
+// over the same values (exact and order-independent, so partial maxima merge
+// to the same bits), and every element goes through the same `rint`/`clamp`
+// expression. `UNROLL = 1` is the previous kernel instruction for instruction,
+// so `ARK_MOE_W4A8_ACT_QUANT_UNROLL=1` is an exact A/B baseline;
+// `test_act_quant_unroll_matches` asserts every depth is bit-identical and
+// `test_perf_prefill_act_quant_unroll_sweep` times them.
+//
+// That sweep keeps the default, though not by much: only minimax up is a real
+// A/B in it (the other three shapes take the single-pass kernel below, where
+// `UNROLL` is dead code, so their rows are three sets of identical kernels --
+// a useful noise probe, spreading 3.3-7.3% in the latest run and 0.4-3.9% in
+// the one before). On that shape the three depths read 6.982 ms at 1,
+// 6.795 ms at 2 and 6.837 ms at 4: the batched loads are worth 1.02-1.03x over
+// `UNROLL = 1`, and the 0.6% between 2 and 4 is an order of magnitude inside
+// the noise the identical-kernel rows show, so the default stays at 4 (the
+// earlier run had it 8.959 / 8.967 / 9.139 ms, i.e. 4 fastest).
+//
+// Reading the row once (the traffic the two passes duplicate)
+// -----------------------------------------------------------
+// Batching the loads did not change how many there are. The absmax has to see
+// the whole row before the first element can be quantized, so the kernel reads
+// `[T, K]`, reduces, then reads `[T, K]` again -- and at 384 rows per expert
+// the activation matrix is 1.5 MB for K = 2048, against 3.1 MB of weights for
+// the whole GEMM. The re-read is L2-resident when the row is still there, but
+// the rows a work-group quantizes second are evicted by the ones it quantized
+// first well before the pass ends: at 8 MB of L2 and 4 KB per bf16 row of
+// K = 2048, only ~2000 of 2048 tokens' rows fit *if nothing else is resident*,
+// and the GEMM's weights are competing for the same cache immediately after.
+//
+// A row is small enough to keep in registers instead: a lane owns `K / 16`
+// elements, so `K = 2048` is 256 bytes -- 64 of the 128 dwords per lane the
+// quantizer gets (it launches without `grf_size<256>`, unlike the GEMM). Load
+// the row once, reduce it, then quantize out of the registers. The second read
+// disappears, and every load is issued before any of them is consumed, which
+// subsumes what `UNROLL` was doing (`UNROLL = steps`, effectively) rather than
+// competing with it.
+//
+// `MAX_STEPS` is the compile-time cap that makes the fragment a register array
+// rather than scratch: the loop is `#pragma unroll` over `MAX_STEPS` with an
+// `if (s < steps)` guard, so every index is a constant and SROA can promote it.
+// Two rungs are instantiated -- 8 vectors (K <= 1024 at VEC = 8, 32 dwords) and
+// 16 (K <= 2048, 64 dwords) -- and anything longer keeps the two-pass kernel,
+// which is why minimax's K = 3072 up-projection still takes the old path. The
+// partial maxima stay at four accumulators, as in the two-pass kernel, so the
+// reduction chain is unchanged in both cost and value.
+//
+// This was a register-pressure gamble -- if 64 dwords of row plus addressing
+// spilled, the pass would get slower, not faster -- and the sweep settled it in
+// its favour: at 384 rows/expert the single-pass kernel is 1.06x (qwen3 down,
+// K = 768), 1.04x (qwen3 up, K = 2048, the rung filled exactly) and 1.02x
+// (minimax down, K = 1536) against the two-pass one. Nothing spills. minimax
+// up (K = 3072) is past the last rung, so both of its rows run the *same*
+// two-pass kernel and their 1.01x is this sweep's noise probe.
+// `ARK_MOE_W4A8_ACT_QUANT_SINGLE_PASS=0` still restores the two-pass
+// kernel exactly, `test_perf_prefill_act_quant_single_pass_sweep` times the
+// pair, and `test_act_quant_single_pass_matches` asserts they agree bit for bit
+// (same `fmax` set, same `inv`, same `rint`/`clamp`).
+// ---------------------------------------------------------------------------
+
+// Fold the per-token expert scan (decode only) into the quantization kernel.
+// Verbatim body of `moe_decode_detail::fill_expert_id_per_token`.
+inline void act_quant_write_scale(float* ascale, int token, float scale, int* expert_id_per_token,
+ const int* num_tokens_per_expert, int num_experts) {
+ ascale[token] = scale;
+ if (expert_id_per_token == nullptr) return;
+ int offset = 0;
+ int expert = num_experts - 1;
+ for (int e = 0; e < num_experts; ++e) {
+ const int n = num_tokens_per_expert[e];
+ if (token < offset + n) {
+ expert = e;
+ break;
+ }
+ offset += n;
+ }
+ expert_id_per_token[token] = expert;
+}
+
+// ---------------------------------------------------------------------------
+// Work-group shape: how many token rows share one work-group.
+//
+// Every kernel below maps one sub-group to one token, so the obvious launch is
+// `global{T, SG_SIZE} local{1, SG_SIZE}` -- and that is what shipped: one
+// sub-group, i.e. **one hardware thread, per work-group**. 65536 routed rows
+// are then 65536 single-thread work-groups.
+//
+// That is the one dimension of this kernel nobody has swept. `ACT_QUANT_VEC`
+// (bytes per lane), `ACT_QUANT_UNROLL` (loads in flight) and
+// `ACT_QUANT_SINGLE_PASS` (row resident in registers) all tune *what one thread
+// does*; none of them changes *how many threads are resident*. Intel's thread
+// dispatcher caps the work-groups resident on an Xe-core well below the number
+// of thread slots that Xe-core has, so at one thread per work-group the
+// work-group limit binds first and the slots go unfilled. Every other kernel in
+// this file runs 256 work-items per work-group; the quantizer is the outlier.
+//
+// Widening to `local{R, SG_SIZE}` carries no synchronization risk: there is no
+// barrier and no SLM here, and SYCL linearizes work-items with the last
+// dimension fastest, so local id `(r, lane)` is linear id `r * SG_SIZE + lane`.
+// With `reqd_sub_group_size(SG_SIZE)` each sub-group therefore still covers
+// exactly one token's SG_SIZE lanes, `reduce_over_group(sg, ...)` keeps its
+// meaning, and the `token >= total_tokens` guard is sub-group-uniform (all
+// SG_SIZE lanes of a sub-group share one `token`), which is what a sub-group
+// collective requires. The output is bit-identical, and
+// `test_act_quant_rows_per_wg_matches` asserts exactly that with `torch.equal`.
+//
+// R is a *runtime* value -- it reaches `nd_range` and nothing else, never the
+// kernel body -- so the rungs cost no extra kernel instantiations in a
+// translation unit that already builds 11.
+//
+// Default 1, today's shape, until `test_perf_act_quant_wg_sweep` rules on real
+// hardware; the per-policy GRF budget is the standing reminder of what shipping
+// an unmeasured default costs. Expect little at long prefill: at 65536 rows the
+// pass already streams ~493 GB/s, above this machine's own device-copy probe,
+// so it is sitting on the roof and there is nothing there to win. The room is
+// in the short batch -- 8192 rows read only ~370 GB/s, and 8x the rows cost
+// 6.0x the time, so it is short prompts (and decode) that are under-fed.
+inline constexpr int kActQuantRowsPerWgDefault = 1;
+
+inline int moe_w4a8_act_quant_rows_per_wg() {
+ const char* env = std::getenv("ARK_MOE_W4A8_ACT_QUANT_ROWS_PER_WG");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long long v = std::strtoll(env, &end, 10);
+ // Powers of two through 16. 16 rows is 256 work-items -- the work-group
+ // size the GEMMs in this file already launch -- so no device query is
+ // needed to know the largest rung fits.
+ if (end != env && (v == 1 || v == 2 || v == 4 || v == 8 || v == 16)) return static_cast<int>(v);
+ }
+ return kActQuantRowsPerWgDefault;
+}
+
+// Row count rounded up to whole work-groups; the padding rows exit on the
+// guard at the top of each kernel.
+inline sycl::nd_range<2> act_quant_nd_range(int total_tokens, int rows_per_wg) {
+ const size_t rows = static_cast<size_t>(rows_per_wg);
+ const size_t padded = ((static_cast<size_t>(total_tokens) + rows - 1) / rows) * rows;
+ return sycl::nd_range<2>(sycl::range<2>{padded, static_cast<size_t>(SG_SIZE)},
+ sycl::range<2>{rows, static_cast<size_t>(SG_SIZE)});
+}
+
+template <typename ScalarT, int VEC, int UNROLL>
+void launch_act_dynamic_quant_vec(sycl::queue* q, const ScalarT* activations, int8_t* qact, float* ascale,
+ int total_tokens, int K, int* expert_id_per_token,
+ const int* num_tokens_per_expert, int num_experts) {
+ static_assert(sizeof(ScalarT) == sizeof(uint16_t), "ScalarT must be a 16-bit floating type");
+ static_assert(VEC == 4 || VEC == 8, "VEC must be 4 or 8");
+ static_assert(UNROLL >= 1 && (UNROLL & (UNROLL - 1)) == 0, "UNROLL must be a power of two");
+ using ActVec = sycl::vec<uint16_t, VEC>;
+ using QVec = sycl::vec<int8_t, VEC>;
+
+ // Vectors a lane walks over. `K % (SG_SIZE * VEC) == 0` is checked by the
+ // caller, so the loop needs no tail -- but `steps` need not be a multiple of
+ // `UNROLL` (K = 768 gives 6 vectors at VEC = 8), hence the second loop.
+ const int steps = K / (SG_SIZE * VEC);
+ const int main_steps = steps - (steps % UNROLL);
+
+ q->parallel_for<MoEW4A8ActQuantVec<ScalarT, VEC, UNROLL>>(
+ act_quant_nd_range(total_tokens, moe_w4a8_act_quant_rows_per_wg()),
+ [=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(SG_SIZE)]] {
+ const int token = static_cast<int>(it.get_global_id(0));
+ if (token >= total_tokens) return;
+ const int lane = static_cast<int>(it.get_local_id(1));
+ const ActVec* row = reinterpret_cast<const ActVec*>(activations + static_cast<size_t>(token) * K);
+ QVec* out = reinterpret_cast<QVec*>(qact + static_cast<size_t>(token) * K);
+
+ // One partial maximum per unrolled slot: `fmax` is exact, so merging
+ // them below gives the same absmax as a single chain, but the loads no
+ // longer wait on it.
+ float part_max[UNROLL];
+#pragma unroll
+ for (int u = 0; u < UNROLL; ++u) part_max[u] = 0.0f;
+
+ for (int s = 0; s < main_steps; s += UNROLL) {
+ ActVec v[UNROLL];
+#pragma unroll
+ for (int u = 0; u < UNROLL; ++u) {
+ v[u] = row[static_cast<size_t>(s + u) * SG_SIZE + lane];
+ }
+#pragma unroll
+ for (int u = 0; u < UNROLL; ++u) {
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[u][e]));
+ part_max[u] = sycl::fmax(part_max[u], sycl::fabs(static_cast<float>(a)));
+ }
+ }
+ }
+ for (int s = main_steps; s < steps; ++s) {
+ const ActVec v = row[static_cast<size_t>(s) * SG_SIZE + lane];
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[e]));
+ part_max[0] = sycl::fmax(part_max[0], sycl::fabs(static_cast<float>(a)));
+ }
+ }
+
+ float local_max = part_max[0];
+#pragma unroll
+ for (int u = 1; u < UNROLL; ++u) local_max = sycl::fmax(local_max, part_max[u]);
+
+ auto sg = it.get_sub_group();
+ const float absmax = sycl::reduce_over_group(sg, local_max, sycl::maximum<float>{});
+
+ const float scale = absmax / kInt8Max;
+ const float inv = absmax > 0.0f ? kInt8Max / absmax : 0.0f;
+ if (lane == 0) {
+ act_quant_write_scale(ascale, token, scale, expert_id_per_token, num_tokens_per_expert, num_experts);
+ }
+
+ // Same batching on the way back: the re-read of a row the first pass
+ // just touched is served by the cache, but only if enough of it is
+ // requested at once.
+ for (int s = 0; s < main_steps; s += UNROLL) {
+ ActVec v[UNROLL];
+#pragma unroll
+ for (int u = 0; u < UNROLL; ++u) {
+ v[u] = row[static_cast<size_t>(s + u) * SG_SIZE + lane];
+ }
+#pragma unroll
+ for (int u = 0; u < UNROLL; ++u) {
+ QVec qv;
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[u][e]));
+ const float x = sycl::rint(static_cast<float>(a) * inv);
+ qv[e] = static_cast<int8_t>(sycl::clamp(x, -kInt8Max, kInt8Max));
+ }
+ out[static_cast<size_t>(s + u) * SG_SIZE + lane] = qv;
+ }
+ }
+ for (int s = main_steps; s < steps; ++s) {
+ const ActVec v = row[static_cast<size_t>(s) * SG_SIZE + lane];
+ QVec qv;
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[e]));
+ const float x = sycl::rint(static_cast<float>(a) * inv);
+ qv[e] = static_cast<int8_t>(sycl::clamp(x, -kInt8Max, kInt8Max));
+ }
+ out[static_cast<size_t>(s) * SG_SIZE + lane] = qv;
+ }
+ });
+}
+
+// Vectors a lane loads before it consumes any of them. `4` covers every
+// shipped shape's `steps` (6 / 12 / 16 / 24 at VEC = 8) with at most a
+// two-vector tail. `ARK_MOE_W4A8_ACT_QUANT_UNROLL` selects 1 (the previous
+// kernel), 2 or 4; anything else falls back to the default.
+constexpr int kActQuantUnrollDefault = 4;
+
+// Partial maxima the single-pass kernel reduces into, matching the two-pass
+// kernel's default `UNROLL` so the two produce the same value bit for bit.
+constexpr int kActQuantSinglePartials = 4;
+
+// Longest row a lane keeps in registers, in vectors. 16 vectors is 64 dwords
+// per lane at VEC = 8 (K = 2048), half the default 128-dword budget; longer
+// rows take the two-pass kernel rather than risk a spill.
+constexpr int kActQuantSingleMaxSteps = 16;
+
+// Single-pass variant: the row is loaded once into registers, reduced, then
+// quantized out of them. `MAX_STEPS` bounds the register array at compile time
+// (see the design note above); `steps <= MAX_STEPS` is the caller's contract.
+template <typename ScalarT, int VEC, int MAX_STEPS>
+void launch_act_dynamic_quant_vec_single(sycl::queue* q, const ScalarT* activations, int8_t* qact, float* ascale,
+ int total_tokens, int K, int* expert_id_per_token,
+ const int* num_tokens_per_expert, int num_experts) {
+ static_assert(sizeof(ScalarT) == sizeof(uint16_t), "ScalarT must be a 16-bit floating type");
+ static_assert(VEC == 4 || VEC == 8, "VEC must be 4 or 8");
+ static_assert(MAX_STEPS >= kActQuantSinglePartials, "MAX_STEPS must cover the partial accumulators");
+ using ActVec = sycl::vec<uint16_t, VEC>;
+ using QVec = sycl::vec<int8_t, VEC>;
+
+ const int steps = K / (SG_SIZE * VEC);
+
+ q->parallel_for<MoEW4A8ActQuantSingle<ScalarT, VEC, MAX_STEPS>>(
+ act_quant_nd_range(total_tokens, moe_w4a8_act_quant_rows_per_wg()),
+ [=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(SG_SIZE)]] {
+ const int token = static_cast<int>(it.get_global_id(0));
+ if (token >= total_tokens) return;
+ const int lane = static_cast<int>(it.get_local_id(1));
+ const ActVec* row = reinterpret_cast<const ActVec*>(activations + static_cast<size_t>(token) * K);
+ QVec* out = reinterpret_cast<QVec*>(qact + static_cast<size_t>(token) * K);
+
+ // The whole row, one load per slot, every one issued before the first
+ // is consumed. Constant indices under the unroll keep it in registers.
+ ActVec v[MAX_STEPS];
+#pragma unroll
+ for (int s = 0; s < MAX_STEPS; ++s) {
+ if (s < steps) {
+ v[s] = row[static_cast<size_t>(s) * SG_SIZE + lane];
+ }
+ }
+
+ float part_max[kActQuantSinglePartials];
+#pragma unroll
+ for (int u = 0; u < kActQuantSinglePartials; ++u) part_max[u] = 0.0f;
+
+#pragma unroll
+ for (int s = 0; s < MAX_STEPS; ++s) {
+ if (s < steps) {
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[s][e]));
+ part_max[s % kActQuantSinglePartials] =
+ sycl::fmax(part_max[s % kActQuantSinglePartials], sycl::fabs(static_cast<float>(a)));
+ }
+ }
+ }
+
+ float local_max = part_max[0];
+#pragma unroll
+ for (int u = 1; u < kActQuantSinglePartials; ++u) local_max = sycl::fmax(local_max, part_max[u]);
+
+ auto sg = it.get_sub_group();
+ const float absmax = sycl::reduce_over_group(sg, local_max, sycl::maximum<float>{});
+
+ const float scale = absmax / kInt8Max;
+ const float inv = absmax > 0.0f ? kInt8Max / absmax : 0.0f;
+ if (lane == 0) {
+ act_quant_write_scale(ascale, token, scale, expert_id_per_token, num_tokens_per_expert, num_experts);
+ }
+
+ // No second read of the row: it is already here.
+#pragma unroll
+ for (int s = 0; s < MAX_STEPS; ++s) {
+ if (s < steps) {
+ QVec qv;
+#pragma unroll
+ for (int e = 0; e < VEC; ++e) {
+ const ScalarT a = sycl::bit_cast<ScalarT>(static_cast<uint16_t>(v[s][e]));
+ const float x = sycl::rint(static_cast<float>(a) * inv);
+ qv[e] = static_cast<int8_t>(sycl::clamp(x, -kInt8Max, kInt8Max));
+ }
+ out[static_cast<size_t>(s) * SG_SIZE + lane] = qv;
+ }
+ }
+ });
+}
+
+inline int moe_w4a8_act_quant_unroll() {
+ const char* env = std::getenv("ARK_MOE_W4A8_ACT_QUANT_UNROLL");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long long v = std::strtoll(env, &end, 10);
+ if (end != env && (v == 1 || v == 2 || v == 4)) return static_cast<int>(v);
+ }
+ return kActQuantUnrollDefault;
+}
+
+// How many k-tiles of A and B the prefill mainloop keeps prefetched ahead of
+// the tile it is computing. The prologue issues `prefetch_dist` pairs before
+// the first DPAS and the loop then issues one pair per tile, so this is the
+// depth of the memory pipeline the mainloop runs against -- too shallow and
+// the DPAS waits on L2, too deep and the prefetched lines are evicted before
+// use (and the prologue itself becomes a serial stall on short K).
+//
+// 3 is the value the mainloop was written with and the sibling prefill kernels
+// use. The shapes here are short in K (12 k-tiles at K = 768), which is exactly
+// where the depth is worth re-measuring, so it is a runtime knob rather than a
+// constant; `test_perf_prefill_prefetch_sweep` walks it.
+inline constexpr int kPrefillPrefetchDefault = 3;
+
+inline int moe_w4a8_prefill_prefetch_dist() {
+ const char* env = std::getenv("ARK_MOE_W4A8_PREFILL_PREFETCH");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long long v = std::strtoll(env, &end, 10);
+ if (end != env && v >= 1 && v <= 8) return static_cast<int>(v);
+ }
+ return kPrefillPrefetchDefault;
+}
+
+// Runtime unroll depth -> compile-time bridge.
+template <typename ScalarT, int VEC>
+void launch_act_dynamic_quant_vec_unroll(int unroll, sycl::queue* q, const ScalarT* activations, int8_t* qact,
+ float* ascale, int total_tokens, int K, int* expert_id_per_token,
+ const int* num_tokens_per_expert, int num_experts) {
+ // Register-resident single pass when the row fits, the two-pass kernel
+ // otherwise. The smallest rung that covers `steps` is chosen so a short row
+ // does not reserve registers for slots it never loads.
+ const int steps = K / (SG_SIZE * VEC);
+ if (steps <= kActQuantSingleMaxSteps &&
+ moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_ACT_QUANT_SINGLE_PASS", true)) {
+ if (steps <= kActQuantSingleMaxSteps / 2) {
+ launch_act_dynamic_quant_vec_single<ScalarT, VEC, kActQuantSingleMaxSteps / 2>(
+ q, activations, qact, ascale, total_tokens, K, expert_id_per_token, num_tokens_per_expert, num_experts);
+ } else {
+ launch_act_dynamic_quant_vec_single<ScalarT, VEC, kActQuantSingleMaxSteps>(
+ q, activations, qact, ascale, total_tokens, K, expert_id_per_token, num_tokens_per_expert, num_experts);
+ }
+ return;
+ }
+
+ if (unroll == 1) {
+ launch_act_dynamic_quant_vec<ScalarT, VEC, 1>(q, activations, qact, ascale, total_tokens, K,
+ expert_id_per_token, num_tokens_per_expert, num_experts);
+ } else if (unroll == 2) {
+ launch_act_dynamic_quant_vec<ScalarT, VEC, 2>(q, activations, qact, ascale, total_tokens, K,
+ expert_id_per_token, num_tokens_per_expert, num_experts);
+ } else {
+ launch_act_dynamic_quant_vec<ScalarT, VEC, 4>(q, activations, qact, ascale, total_tokens, K,
+ expert_id_per_token, num_tokens_per_expert, num_experts);
+ }
+}
+
+template <typename ScalarT>
+void launch_act_dynamic_quant(sycl::queue* q, const ScalarT* activations, int8_t* qact, float* ascale,
+ int total_tokens, int K, int* expert_id_per_token = nullptr,
+ const int* num_tokens_per_expert = nullptr, int num_experts = 0) {
+ static_assert(sizeof(ScalarT) == sizeof(uint16_t), "ScalarT must be a 16-bit floating type");
+ if (total_tokens == 0) return;
+
+ // Widest lane chunk this shape and these buffers support. The alignment
+ // checks never fire for torch allocations or the scratch pool (both are at
+ // least 256-byte aligned), but a caller-supplied activation view could be
+ // offset, and an unaligned `sycl::vec` access would be undefined.
+ if (moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_ACT_QUANT_VEC", true)) {
+ const auto act_addr = reinterpret_cast<std::uintptr_t>(activations);
+ const auto q_addr = reinterpret_cast<std::uintptr_t>(qact);
+ const int unroll = moe_w4a8_act_quant_unroll();
+ if (K % (SG_SIZE * 8) == 0 && act_addr % (8 * sizeof(ScalarT)) == 0 && q_addr % 8 == 0) {
+ launch_act_dynamic_quant_vec_unroll<ScalarT, 8>(unroll, q, activations, qact, ascale, total_tokens, K,
+ expert_id_per_token, num_tokens_per_expert, num_experts);
+ return;
+ }
+ if (K % (SG_SIZE * 4) == 0 && act_addr % (4 * sizeof(ScalarT)) == 0 && q_addr % 4 == 0) {
+ launch_act_dynamic_quant_vec_unroll<ScalarT, 4>(unroll, q, activations, qact, ascale, total_tokens, K,
+ expert_id_per_token, num_tokens_per_expert, num_experts);
+ return;
+ }
+ }
+
+ q->parallel_for<MoEW4A8ActQuant<ScalarT>>(
+ act_quant_nd_range(total_tokens, moe_w4a8_act_quant_rows_per_wg()),
+ [=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(SG_SIZE)]] {
+ const int token = static_cast<int>(it.get_global_id(0));
+ if (token >= total_tokens) return;
+ const int lane = static_cast<int>(it.get_local_id(1));
+ const ScalarT* row = activations + static_cast<size_t>(token) * K;
+ int8_t* out = qact + static_cast<size_t>(token) * K;
+
+ float local_max = 0.0f;
+ for (int k = lane; k < K; k += SG_SIZE) {
+ local_max = sycl::fmax(local_max, sycl::fabs(static_cast<float>(row[k])));
+ }
+ auto sg = it.get_sub_group();
+ const float absmax = sycl::reduce_over_group(sg, local_max, sycl::maximum<float>{});
+
+ const float scale = absmax / kInt8Max;
+ const float inv = absmax > 0.0f ? kInt8Max / absmax : 0.0f;
+ if (lane == 0) {
+ act_quant_write_scale(ascale, token, scale, expert_id_per_token, num_tokens_per_expert, num_experts);
+ }
+
+ for (int k = lane; k < K; k += SG_SIZE) {
+ const float v = sycl::rint(static_cast<float>(row[k]) * inv);
+ out[k] = static_cast<int8_t>(sycl::clamp(v, -kInt8Max, kInt8Max));
+ }
+ });
+}
+
+// ---------------------------------------------------------------------------
+// AUTO_S8 stage 1: per-(expert, output channel, block) re-scale factor.
+//
+// sxt[e][n][j] = max_{g in block j} |s[e][n][g]| * (8 / 127)
+//
+// Verbatim port of the rescale branch of `packscale` in `xpu_wrapper.hpp`
+// (with `fullrange = 8` for int4). An all-zero block yields `sxt = 0`; stage 2
+// turns that into all-zero int8 weights, so the (equally zero) product is
+// still exact.
+// ---------------------------------------------------------------------------
+template <typename ScalarT>
+void launch_weight_scale_reduce(sycl::queue* q, const ScalarT* scales, float* wscale_out, int E, int N, int K,
+ int group_size, int rescale_block, int nblk) {
+ const int groups_k = K / group_size;
+ const int groups_per_block = rescale_block / group_size;
+
+ q->parallel_for<MoEW4A8ScaleReduce<ScalarT>>(
+ sycl::range<1>(static_cast<size_t>(E) * static_cast<size_t>(N) * static_cast<size_t>(nblk)),
+ [=](sycl::id<1> id) {
+ const size_t idx = id[0];
+ const int blk = static_cast<int>(idx % static_cast<size_t>(nblk));
+ const size_t row = idx / static_cast<size_t>(nblk); // e * N + n
+ const ScalarT* s_row =
+ scales + row * static_cast<size_t>(groups_k) + static_cast<size_t>(blk) * groups_per_block;
+
+ float absmax = 0.0f;
+ for (int g = 0; g < groups_per_block; ++g) {
+ absmax = sycl::fmax(absmax, sycl::fabs(static_cast<float>(s_row[g])));
+ }
+ wscale_out[idx] = absmax * (kInt4FullRange / kInt8Max);
+ });
+}
+
+// ---------------------------------------------------------------------------
+// AUTO_S8 stage 2: int4 -> int8 re-scale.
+//
+// w8[k] = round(w4[k] * s[k / group_size] / sxt[k / rescale_block])
+//
+// Verbatim port of the `CfgDequantS8Rescale` branch of `unpackq` in
+// `xpu_wrapper.hpp`. One work-item decodes one 32-bit word (8 nibbles); the
+// shape gate guarantees `group_size % 8 == 0` and `rescale_block % 8 == 0`, so
+// all 8 K indices of a word share the same group scale and the same block
+// scale and both loads hoist out of the inner loop.
+// ---------------------------------------------------------------------------
+template <typename ScalarT>
+void launch_weight_rescale_s4_to_s8(sycl::queue* q, const uint8_t* weights, const ScalarT* scales,
+ const float* wscale, int8_t* w8_out, int E, int N, int K, int group_size,
+ int rescale_block, int nblk) {
+ const int groups_k = K / group_size;
+ const int octets = K / kPrepackOctet;
+
+ q->parallel_for<MoEW4A8Repack<ScalarT>>(
+ sycl::range<2>(static_cast<size_t>(E) * static_cast<size_t>(N), static_cast<size_t>(octets)),
+ [=](sycl::id<2> id) {
+ const size_t row = id[0]; // e * N + n
+ const int oct = static_cast<int>(id[1]);
+ const int k_base = oct * kPrepackOctet;
+
+ const uint8_t* w_ptr = weights + row * static_cast<size_t>(K / 2) + static_cast<size_t>(oct) * 4;
+ const uint32_t word = *reinterpret_cast<const uint32_t*>(w_ptr);
+ int q4[kPrepackOctet];
+ decode_int4_octet<false>(word, q4);
+
+ const float s = static_cast<float>(scales[row * static_cast<size_t>(groups_k) + k_base / group_size]);
+ const float sx = wscale[row * static_cast<size_t>(nblk) + k_base / rescale_block];
+ const float f = sx > 0.0f ? s / sx : 0.0f;
+
+ int8_t* out = w8_out + row * static_cast<size_t>(K) + k_base;
+#pragma unroll
+ for (int j = 0; j < kPrepackOctet; ++j) {
+ const float v = sycl::rint(static_cast<float>(q4[j]) * f);
+ out[j] = static_cast<int8_t>(sycl::clamp(v, -kInt8Max, kInt8Max));
+ }
+ });
+}
+
+// Both prepack kernels for one dtype, behind the shared parameter struct so a
+// generated TU can define `prepack_f16` / `prepack_bf16` in three lines.
+template <typename ScalarT>
+void moe_w4a8_prepack_launch(const moe_w4a8_detail::W4A8PrepackParams& p) {
+ launch_weight_scale_reduce<ScalarT>(p.q, static_cast<const ScalarT*>(p.scales), p.wscales, p.num_experts, p.N,
+ p.K, p.group_size, p.blocksize, p.blks);
+ launch_weight_rescale_s4_to_s8<ScalarT>(p.q, static_cast<const uint8_t*>(p.weights_s4),
+ static_cast<const ScalarT*>(p.scales), p.wscales, p.weights_s8,
+ p.num_experts, p.N, p.K, p.group_size, p.blocksize, p.blks);
+}
+
+
+// ---------------------------------------------------------------------------
+// Decode GEMV: int8 x int8 -> int32, one output column per sub-group lane.
+//
+// Same work decomposition as `moe_decode_detail::launch_int8` (work-group =
+// one sub-group covering 16 consecutive N columns of one token), with the
+// per-K-group float dequantization replaced by a per-block int32 dot product.
+// Two accumulators hide the multiply-add latency; int32 cannot overflow here
+// (|a|,|w| <= 127 gives < 2^14 per product, so K would have to exceed 130k).
+// ---------------------------------------------------------------------------
+template <typename ElementD>
+void launch_w4a8_decode(sycl::queue* q, const int8_t* qact, const float* ascale, const int8_t* weights,
+ const float* wscale, ElementD* outputs, const int* expert_id_per_token, int total_tokens,
+ int N, int K, int blocksize, int blks) {
+ if (N % N_TILE != 0) {
+ throw std::invalid_argument("moe_gemm_w4a8(decode): N must be a multiple of 16");
+ }
+ if (total_tokens == 0) return;
+
+ const int n_tiles = N / N_TILE;
+ sycl::range<2> global{static_cast<size_t>(total_tokens), static_cast<size_t>(n_tiles * SG_SIZE)};
+ sycl::range<2> local{1, static_cast<size_t>(SG_SIZE)};
+
+ q->parallel_for<MoEW4A8DecodeGemv<ElementD>>(
+ sycl::nd_range<2>(global, local), [=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(SG_SIZE)]] {
+ const int token = static_cast<int>(it.get_global_id(0));
+ const int n_tile = static_cast<int>(it.get_group(1));
+ const int lane = static_cast<int>(it.get_local_id(1));
+ const int n_global = n_tile * N_TILE + lane;
+
+ const int expert = expert_id_per_token[token];
+ const int8_t* act_row = qact + static_cast<size_t>(token) * K;
+ const int8_t* w_row = weights + (static_cast<size_t>(expert) * N + static_cast<size_t>(n_global)) * K;
+ const float* s_row =
+ wscale + (static_cast<size_t>(expert) * N + static_cast<size_t>(n_global)) * blks;
+
+ constexpr int SUB = 16;
+ using QVec = sycl::vec<int8_t, SUB>;
+
+ float accf = 0.0f;
+ for (int ib = 0; ib < blks; ++ib) {
+ const int k_base = ib * blocksize;
+ int acc0 = 0;
+ int acc1 = 0;
+ int kk = 0;
+ const int end = (blocksize / SUB) * SUB;
+ for (; kk < end; kk += SUB) {
+ const QVec av = *reinterpret_cast<const QVec*>(act_row + k_base + kk);
+ const QVec wv = *reinterpret_cast<const QVec*>(w_row + k_base + kk);
+#pragma unroll
+ for (int u = 0; u < SUB; u += 2) {
+ acc0 += static_cast<int>(av[u]) * static_cast<int>(wv[u]);
+ acc1 += static_cast<int>(av[u + 1]) * static_cast<int>(wv[u + 1]);
+ }
+ }
+ for (; kk < blocksize; ++kk) {
+ acc0 += static_cast<int>(act_row[k_base + kk]) * static_cast<int>(w_row[k_base + kk]);
+ }
+ accf += static_cast<float>(acc0 + acc1) * s_row[ib];
+ }
+
+ outputs[static_cast<size_t>(token) * N + n_global] = static_cast<ElementD>(accf * ascale[token]);
+ });
+}
+
+// ---------------------------------------------------------------------------
+// Decode GEMV, K-split lane mapping (default) -- one sub-group per output
+// element, lanes splitting K, plus N-blocking over `NCOLS` columns.
+//
+// `launch_w4a8_decode` above maps one *work-item* to one output element, so a
+// lane walks a whole `[n_global, K]` int8 weight row on its own. That is the
+// same mapping the FP8 decode GEMV started from, and it costs the same two
+// things on a kernel that does exactly one multiply-add per weight byte:
+//
+// 1. Weight loads are not coalesced. Lanes `l` and `l+1` read bytes `K`
+// apart, so each 16-byte load turns into 16 scattered cache-line
+// requests. No DRAM byte is wasted (each lane consumes its lines as it
+// walks the row), but the memory controller sees 16 independent streams
+// per sub-group -- the pattern DRAM row buffers handle worst.
+// 2. The grid is small: `total_tokens * N / 16` sub-groups, i.e. 768 SIMD16
+// threads for a Qwen3-MoE batch-1 step (8 routed rows, N = 1536). That is
+// below the thread slots of a BMG-class GPU (1280 on a B60), so there are
+// never enough loads in flight to cover DRAM latency.
+//
+// This kernel transposes the mapping exactly like `launch_fp8_ksplit`: a whole
+// sub-group cooperates on one output element and lane `l` owns the `CH`
+// consecutive K elements at `l * CH` inside each `SG_SIZE * CH`-wide K tile.
+// One instruction then covers `SG_SIZE * CH` *contiguous* weight bytes (256 B =
+// four full cache lines at the default `CH = 16`, 512 B at `CH = 32`) and the
+// same span of int8 activations, every thread walks a single sequential stream,
+// and the sub-group count grows by `SG_SIZE` (12288 for that batch-1 step). The
+// price is one `reduce_over_group` per output element -- a handful of shuffles
+// against `K` multiply-adds.
+//
+// On top of that the sub-group blocks N: it owns `NCOLS` consecutive columns
+// and reuses one activation load for all of them, which cuts activation
+// messages per weight chunk to `1 / NCOLS` and multiplies the number of
+// independent weight loads in flight by `NCOLS` (see
+// `moe_w4a8_decode_ksplit_ncols`).
+//
+// Numerics are equivalent, not bit-identical: the int32 partial sums are still
+// folded to float once per AUTO_S8 block with that block's scale, but they are
+// split across the 16 lanes and summed at the end. Integer addition is exact
+// and associative, so the *integer* partition is lossless; only the float
+// accumulation is reordered (per lane, then across lanes, instead of one lane
+// folding every block in sequence), which can differ from the legacy result by
+// a rounding step. A lane's chunk is `CH` consecutive K elements starting at a
+// multiple of `CH`, and the shape gate requires the block to be a multiple of
+// `CH`, so a chunk never straddles two blocks.
+// ---------------------------------------------------------------------------
+
+// K elements a lane owns per step: `KSPLIT_CH_DEFAULT` is one 16-byte int8
+// weight load and one 16-byte int8 activation load, the same transactions the
+// legacy GEMV issues. `ARK_MOE_W4A8_DECODE_KSPLIT_CH=32` doubles them to
+// 32-byte loads, which halves the number of memory messages per byte and
+// doubles the bytes a thread keeps in flight; it costs GRF (2 x NCOLS chunks
+// live at once) and needs `blocksize >= SG_SIZE * CH`.
+//
+// Measured (`test_perf_decode_config_sweep`, BMG, 8 routed rows, bf16 act), at
+// the default NCOLS: 284.0 -> 278.9 GB/s (qwen3 up), 280.1 -> 244.4 (qwen3
+// down), 268.1 -> 259.9 (minimax up), 315.5 -> 308.7 (minimax down). The wider
+// chunk never wins at any NCOLS and costs up to 13%, so 16 stays the default
+// and 32 stays an opt-in sweep point.
+constexpr int KSPLIT_CH_DEFAULT = 16;
+constexpr int KSPLIT_CH_MAX = 32;
+// Sub-groups per work-group. Each owns `NCOLS` output columns, so a work-group
+// covers `KSPLIT_WG_SGS * NCOLS` consecutive columns.
+constexpr int KSPLIT_WG_SGS = N_TILE;
+// `NCOLS = 2` is the measured default: it is the fastest configuration on two
+// of the four swept shapes and within 2% of the best (`4` on qwen3 down, `1` on
+// minimax up) on the other two, while `1` costs 47% on qwen3 up and `4` costs
+// 14% on minimax up.
+constexpr int KSPLIT_NCOLS_DEFAULT = 2;
+constexpr int KSPLIT_NCOLS_MAX = 4;
+
+// A lane's `CH`-byte chunk, as a register type.
+//
+// `sycl::vec` only exists for 1, 2, 3, 4, 8 and 16 elements, so a `CH = 32`
+// chunk cannot be spelled `sycl::vec<int8_t, 32>`: that instantiation is a hard
+// static_assert in the SYCL headers ("Invalid number of elements for
+// sycl::vec"). A chunk is therefore an aggregate of `CH / 16` 16-byte
+// sub-vectors covering *consecutive* bytes. The lane still reads one contiguous
+// `CH`-byte span at a `CH`-aligned address (`moe_w4a8_decode_ksplit_shape_ok`
+// makes every chunk offset a multiple of `CH` off a row base that is a multiple
+// of `K`, itself a multiple of `CH`), the sub-vectors are adjacent both in
+// memory and in the GRF, and the declared alignment lets IGC fold the pair back
+// into a single wider message. At the default `CH = 16` the aggregate holds a
+// single `sycl::vec<int8_t, 16>`, i.e. exactly the load this kernel issued
+// before.
+//
+// `operator[]` is only ever called from the fully unrolled inner loops, so the
+// sub-vector selection folds away at compile time and no dynamic indexing
+// (which would push the chunk out to scratch) is generated.
+template <int CH>
+struct alignas(CH) QChunk {
+ static constexpr int kSub = KSPLIT_CH_DEFAULT;
+ static_assert(CH % kSub == 0, "chunk width must be a whole number of 16-byte sub-vectors");
+ sycl::vec<int8_t, kSub> v[CH / kSub];
+
+ int8_t operator[](int i) const { return v[i / kSub][i % kSub]; }
+};
+
+// `ARK_MOE_W4A8_DECODE_KSPLIT` (default ON). Setting it to "0" / "false" /
+// "off" / "no" forces the legacy per-lane-strided GEMV, for A/B comparison and
+// as a regression escape. Re-read on every call so benchmarks can toggle the
+// path in-process.
+inline bool moe_w4a8_decode_ksplit_enabled() {
+ return moe_decode_detail::env_flag_enabled("ARK_MOE_W4A8_DECODE_KSPLIT", true);
+}
+
+// Per-lane chunk width in K elements (= bytes). 16 or 32; anything else falls
+// back to the default.
+inline int moe_w4a8_decode_ksplit_chunk() {
+ const char* env = std::getenv("ARK_MOE_W4A8_DECODE_KSPLIT_CH");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long long v = std::strtoll(env, &end, 10);
+ if (end != env && (v == 16 || v == 32)) return static_cast<int>(v);
+ }
+ return KSPLIT_CH_DEFAULT;
+}
+
+// Shape gate. `blocksize >= SG_SIZE * ch` keeps every lane of the sub-group
+// busy: below that some lanes own no chunk in a block and only pay the
+// reduction, which is the one regime where splitting K cannot pay for itself.
+// `blocksize % ch == 0` combined with `K % blocksize == 0` also makes every
+// chunk offset a multiple of `ch` off a row base that is a multiple of `K`, so
+// the vector loads stay naturally aligned. The resolved AUTO_S8 block is always
+// a multiple of 64 that divides K, so the conditions hold for every shipped
+// configuration and only very fine re-scale blocks fall back to the legacy
+// GEMV.
+inline bool moe_w4a8_decode_ksplit_shape_ok(int N, int K, int blocksize, int ch = KSPLIT_CH_DEFAULT) {
+ if (N % N_TILE != 0) return false;
+ if (blocksize < SG_SIZE * ch) return false;
+ if (blocksize % ch != 0) return false;
+ if (K % blocksize != 0) return false;
+ return true;
+}
+
+// N-blocking factor. A work-group covers `KSPLIT_WG_SGS * ncols` columns, so
+// `ncols` shrinks until it tiles N. `ARK_MOE_W4A8_DECODE_KSPLIT_NCOLS`
+// overrides the default (1, 2 or 4); `NCOLS == 1` reproduces the plain K-split
+// mapping instruction for instruction.
+inline int moe_w4a8_decode_ksplit_ncols(int N) {
+ int ncols = KSPLIT_NCOLS_DEFAULT;
+ const char* env = std::getenv("ARK_MOE_W4A8_DECODE_KSPLIT_NCOLS");
+ if (env != nullptr) {
+ char* end = nullptr;
+ const long long v = std::strtoll(env, &end, 10);
+ if (end != env && v >= 1 && v <= KSPLIT_NCOLS_MAX && (v & (v - 1)) == 0) {
+ ncols = static_cast<int>(v);
+ }
+ }
+ while (ncols > 1 && (N % (KSPLIT_WG_SGS * ncols)) != 0) ncols /= 2;
+ return ncols;
+}
+
+template <typename ElementD, int NCOLS, int CH = KSPLIT_CH_DEFAULT>
+void launch_w4a8_decode_ksplit(sycl::queue* q, const int8_t* qact, const float* ascale, const int8_t* weights,
+ const float* wscale, ElementD* outputs, const int* expert_id_per_token,
+ int total_tokens, int N, int K, int blocksize, int blks) {
+ static_assert(NCOLS >= 1 && (NCOLS & (NCOLS - 1)) == 0, "NCOLS must be a power of two");
+ static_assert(CH == 16 || CH == KSPLIT_CH_MAX, "CH must be 16 or 32");
+ // K elements a sub-group covers per step -- the contiguous span its 16 lanes
+ // read in one instruction.
+ constexpr int STEP = SG_SIZE * CH;
+ if (!moe_w4a8_decode_ksplit_shape_ok(N, K, blocksize, CH) || (N % (KSPLIT_WG_SGS * NCOLS)) != 0) {
+ throw std::invalid_argument("moe_gemm_w4a8(decode): K-split GEMV called on an unsupported shape");
+ }
+ if (total_tokens == 0) return;
+
+ // One sub-group per (token, NCOLS columns); `KSPLIT_WG_SGS` of them per
+ // work-group.
+ sycl::range<2> global{static_cast<size_t>(total_tokens), static_cast<size_t>(N / NCOLS) * SG_SIZE};
+ sycl::range<2> local{1, static_cast<size_t>(KSPLIT_WG_SGS * SG_SIZE)};
+
+ q->parallel_for<MoEW4A8DecodeKSplit<ElementD, NCOLS, CH>>(
+ sycl::nd_range<2>(global, local), [=](sycl::nd_item<2> it) [[intel::reqd_sub_group_size(SG_SIZE)]] {
+ const auto sg = it.get_sub_group();
+ const int token = static_cast<int>(it.get_global_id(0));
+ const int local_id = static_cast<int>(it.get_local_id(1));
+ // The work-group is one row of `KSPLIT_WG_SGS * SG_SIZE` work-items, so
+ // sub-group index and lane index are the halves of the local id.
+ const int lane = local_id % SG_SIZE;
+ const int n_base = (static_cast<int>(it.get_group(1)) * KSPLIT_WG_SGS + local_id / SG_SIZE) * NCOLS;
+
+ const int expert = expert_id_per_token[token];
+ const int8_t* act_row = qact + static_cast<size_t>(token) * K;
+ const size_t row0 = static_cast<size_t>(expert) * N + static_cast<size_t>(n_base);
+ const int8_t* w_rows[NCOLS];
+ const float* s_rows[NCOLS];
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) {
+ w_rows[c] = weights + (row0 + static_cast<size_t>(c)) * K;
+ s_rows[c] = wscale + (row0 + static_cast<size_t>(c)) * blks;
+ }
+
+ using QVec = QChunk<CH>;
+
+ float acc[NCOLS];
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) acc[c] = 0.0f;
+
+ for (int ib = 0; ib < blks; ++ib) {
+ const int block_begin = ib * blocksize;
+ const int block_end = block_begin + blocksize;
+ int32_t iacc[NCOLS];
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) iacc[c] = 0;
+
+ int k0 = block_begin + lane * CH;
+ // Two chunks per iteration: their loads are independent, so the pair
+ // doubles the weight requests a thread keeps in flight. All
+ // `2 * NCOLS` weight loads are issued before the first is consumed.
+ for (; k0 + STEP + CH <= block_end; k0 += 2 * STEP) {
+ const QVec av0 = *reinterpret_cast<const QVec*>(act_row + k0);
+ const QVec av1 = *reinterpret_cast<const QVec*>(act_row + k0 + STEP);
+ QVec wv0[NCOLS], wv1[NCOLS];
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) {
+ wv0[c] = *reinterpret_cast<const QVec*>(w_rows[c] + k0);
+ wv1[c] = *reinterpret_cast<const QVec*>(w_rows[c] + k0 + STEP);
+ }
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) {
+ int p0 = 0;
+ int p1 = 0;
+#pragma unroll
+ for (int u = 0; u < CH; u += 2) {
+ p0 += static_cast<int>(av0[u]) * static_cast<int>(wv0[c][u]);
+ p1 += static_cast<int>(av0[u + 1]) * static_cast<int>(wv0[c][u + 1]);
+ p0 += static_cast<int>(av1[u]) * static_cast<int>(wv1[c][u]);
+ p1 += static_cast<int>(av1[u + 1]) * static_cast<int>(wv1[c][u + 1]);
+ }
+ iacc[c] += p0 + p1;
+ }
+ }
+ // Tail: the chunk of a lane whose partner a full step away falls
+ // outside the block. At most one chunk per lane.
+ for (; k0 < block_end; k0 += STEP) {
+ const QVec av = *reinterpret_cast<const QVec*>(act_row + k0);
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) {
+ const QVec wv = *reinterpret_cast<const QVec*>(w_rows[c] + k0);
+ int p0 = 0;
+ int p1 = 0;
+#pragma unroll
+ for (int u = 0; u < CH; u += 2) {
+ p0 += static_cast<int>(av[u]) * static_cast<int>(wv[u]);
+ p1 += static_cast<int>(av[u + 1]) * static_cast<int>(wv[u + 1]);
+ }
+ iacc[c] += p0 + p1;
+ }
+ }
+
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) acc[c] += static_cast<float>(iacc[c]) * s_rows[c][ib];
+ }
+
+ const float sa = ascale[token];
+#pragma unroll
+ for (int c = 0; c < NCOLS; ++c) {
+ const float total = sycl::reduce_over_group(sg, acc[c], sycl::plus<float>{});
+ if (lane == 0) {
+ outputs[static_cast<size_t>(token) * N + n_base + c] = static_cast<ElementD>(total * sa);
+ }
+ }
+ });
+}
+
+// Runtime (NCOLS, CH) -> compile-time bridge, plus the K-split / legacy choice.
+// `CH = 32` needs a block of at least 512 elements, so it silently falls back to
+// 16 on shapes it cannot serve rather than dropping to the legacy GEMV.
+template <typename ElementD>
+void launch_w4a8_decode_dispatch(sycl::queue* q, const int8_t* qact, const float* ascale, const int8_t* weights,
+ const float* wscale, ElementD* outputs, const int* expert_id_per_token,
+ int total_tokens, int N, int K, int blocksize, int blks) {
+ if (moe_w4a8_decode_ksplit_enabled() && moe_w4a8_decode_ksplit_shape_ok(N, K, blocksize)) {
+ const int ncols = moe_w4a8_decode_ksplit_ncols(N);
+ const int ch = moe_w4a8_decode_ksplit_chunk() == KSPLIT_CH_MAX &&
+ moe_w4a8_decode_ksplit_shape_ok(N, K, blocksize, KSPLIT_CH_MAX)
+ ? KSPLIT_CH_MAX
+ : KSPLIT_CH_DEFAULT;
+
+#define ARK_MOE_W4A8_KSPLIT(ncols_v, ch_v) \
+ launch_w4a8_decode_ksplit<ElementD, ncols_v, ch_v>(q, qact, ascale, weights, wscale, outputs, \
+ expert_id_per_token, total_tokens, N, K, blocksize, blks); \
+ return;
+
+ if (ch == KSPLIT_CH_MAX) {
+ switch (ncols) {
+ case 4:
+ ARK_MOE_W4A8_KSPLIT(4, KSPLIT_CH_MAX)
+ case 2:
+ ARK_MOE_W4A8_KSPLIT(2, KSPLIT_CH_MAX)
+ default:
+ ARK_MOE_W4A8_KSPLIT(1, KSPLIT_CH_MAX)
+ }
+ }
+ switch (ncols) {
+ case 4:
+ ARK_MOE_W4A8_KSPLIT(4, KSPLIT_CH_DEFAULT)
+ case 2:
+ ARK_MOE_W4A8_KSPLIT(2, KSPLIT_CH_DEFAULT)
+ default:
+ ARK_MOE_W4A8_KSPLIT(1, KSPLIT_CH_DEFAULT)
+ }
+#undef ARK_MOE_W4A8_KSPLIT
+ }
+ launch_w4a8_decode<ElementD>(q, qact, ascale, weights, wscale, outputs, expert_id_per_token, total_tokens, N, K,
+ blocksize, blks);
+}
+
+// Activation quantization for one dtype, behind the shared parameter struct.
+template <typename ScalarT>
+void moe_w4a8_quant_launch(const moe_w4a8_detail::W4A8QuantParams& p) {
+ launch_act_dynamic_quant<ScalarT>(p.q, static_cast<const ScalarT*>(p.activations), p.qact, p.ascale,
+ p.total_tokens, p.K, p.expert_map, p.num_tokens_per_expert, p.num_experts);
+}
+
+// Decode GEMV for one dtype, behind the shared parameter struct. The K-split
+// vs. legacy choice and the (NCOLS, CH) specialization stay inside the TU.
+template <typename ElementD>
+void moe_w4a8_decode_launch(const moe_w4a8_detail::W4A8DecodeParams& p) {
+ launch_w4a8_decode_dispatch<ElementD>(p.q, p.qact, p.ascale, p.weights, p.wscale,
+ static_cast<ElementD*>(p.outputs), p.expert_id_per_token, p.total_tokens,
+ p.N, p.K, p.blocksize, p.blks);
+}
+
+
+} // namespace moe_w4a8
+} // namespace ark
+
+#endif // ARK_XPU && ARK_SYCL_TLA
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_scratch.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_scratch.hpp
new file mode 100644
index 000000000..acad56fac
--- /dev/null
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/sycl_tla_moe_w4a8_scratch.hpp
@@ -0,0 +1,61 @@
+// Device scratch for the W4A8 MoE path.
+//
+// The activation-quantization buffers (`[total_tokens, K]` int8 +
+// `[total_tokens]` fp32) and the decode expert map (`[total_tokens]` int32) are
+// recomputed on every call, so they come from persistent slabs instead of a
+// hot-path `malloc_device`.
+//
+// The slabs are owned by the extension-wide `DeviceMemoryPool`, keyed by
+// device, context and queue identity rather than a raw `sycl::queue*`.
+// Repeated requests reuse the existing allocation; larger requests grow it
+// automatically. No W4A8-specific state or explicit create/release is needed.
+//
+// Like the other global scratch slots, allocations persist for the lifetime
+// of the process and are not freed from a static destructor, when the SYCL
+// context may already be torn down.
+//
+// Different queues use separate allocations, matching the pool's other slots.
+//
+// Only the declarations live here; the pool access is defined in
+// `sycl_tla_moe_w4a8_scratch.cpp` so that `utils.hpp` stays out of this include
+// chain. `utils.hpp` drags in bestla's AVX512/xbyak JIT headers, which
+// would grow every cutlass-free W4A8 translation unit by an order of magnitude
+// and undo much of the TU split. This mirrors
+// `sycl_tla_moe_decode_scratch.{hpp,cpp}`.
+//
+// Copyright (C) 2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+#ifdef ARK_XPU
+#include <sycl/sycl.hpp>
+#endif
+
+#if defined(ARK_XPU) && defined(ARK_SYCL_TLA)
+
+namespace ark {
+namespace moe_w4a8 {
+
+// `DeviceMemoryPool` slots owned by the W4A8 path. Slots 0-7 belong to the
+// dnnl / xpu / sycl-s8 / cpu wrappers and the SDPA kernels, slot 8 to the DPAS
+// work-group counter, slots 9-10 to the int4 decode scratch, and slot 11 to
+// the XMX Hadamard staging buffer. Slot 12 is the SYCL-TLA prefill workspace.
+inline constexpr size_t kW4A8QactScratchLoc = 13;
+inline constexpr size_t kW4A8ExpertMapScratchLoc = 14;
+
+// Acquire the quantized-activation slab (int8 activations + per-token scales).
+// Returns `nullptr` for a zero-byte request; throws `std::invalid_argument` on
+// a null queue and `std::runtime_error` if the pool cannot allocate.
+uint8_t* acquire_qact_scratch(sycl::queue* q, size_t bytes);
+
+// Acquire the decode expert map (`[total_tokens]` int32). Same contract.
+int* acquire_expert_map_scratch(sycl::queue* q, size_t bytes);
+
+} // namespace moe_w4a8
+} // namespace ark
+
+#endif // ARK_XPU && ARK_SYCL_TLA
diff --git a/auto_round_extension/ark/auto_round_kernel/wrapper/include/utils.hpp b/auto_round_extension/ark/auto_round_kernel/wrapper/include/utils.hpp
index 09f650332..cf8c74d78 100644
--- a/auto_round_extension/ark/auto_round_kernel/wrapper/include/utils.hpp
+++ b/auto_round_extension/ark/auto_round_kernel/wrapper/include/utils.hpp
@@ -218,7 +218,11 @@ class DeviceMemoryPool {
// slot 11 is the XMX Hadamard staging buffer
// (`kHadamardStagingScratchLoc` in `ark.cpp`); slot 12 is the SYCL-TLA
// prefill workspace (`kPrefillScratchLoc` in `sycl_tla_wrapper.hpp`).
- static constexpr int MaxLocNum = 13;
+ // slots 13 and 14 are the W4A8
+ // activation-quantization and expert-map buffers
+ // (`moe_w4a8::kW4A8QactScratchLoc` / `kW4A8ExpertMapScratchLoc`).
+ static constexpr int MaxLocNum = 15;
+
using SizeMap = std::unordered_map<size_t, size_t>;
using PtrMap = std::unordered_map<size_t, int8_t*>;
diff --git a/auto_round_extension/ark/test/test_moe_w4a8_perf.py b/auto_round_extension/ark/test/test_moe_w4a8_perf.py
new file mode 100755
index 000000000..ac5ee138a
--- /dev/null
+++ b/auto_round_extension/ark/test/test_moe_w4a8_perf.py
@@ -0,0 +1,4171 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2026 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Performance + accuracy benchmark for the W4A8 ARK XPU MoE kernel.
+
+W4A8 = int4 weights, **int8 compute**. The int4 weights are converted once
+into int8 with ARK's ``AUTO_S8`` re-scale (int4 ``group=32`` -> int8
+``group=-1``, i.e. one scale per output channel) and the activations are
+dynamically quantized to int8 per token inside the kernel, so the mainloop is
+a pure ``s8 x s8 -> s32`` DPAS -- the highest-throughput shape on Xe.
+
+This script covers **both phases**:
+
+* **prefill** -- grouped GEMM over expert-sorted tokens
+ (``ark.moe_w4a8(..., phase="prefill")``).
+* **decode** -- GEMV for one/few tokens per expert
+ (``ark.moe_w4a8(..., phase="decode")``).
+
+and reports, per shape:
+
+* accuracy of W4A8 against (a) an fp32 reference computed from the
+ dequantized int4 weights and (b) the existing W4A16 ARK kernel, as SNR
+ (dB), cosine similarity and max relative error;
+* latency, TFLOPS and effective weight bandwidth of W4A8 vs the W4A16 ARK
+ path and vs a PyTorch matmul baseline on dequantized weights.
+
+How to run (pytest)::
+
+ pytest -v -s auto_round_extension/ark/test/test_moe_w4a8_perf.py
+
+The ``-s`` flag is required to see the printed tables. By default only the
+smallest batch group is run; pass ``--all-shapes`` for the full sweep::
+
+ pytest -v -s auto_round_extension/ark/test/test_moe_w4a8_perf.py --all-shapes
+
+It also runs standalone, without pytest::
+
+ python auto_round_extension/ark/test/test_moe_w4a8_perf.py --all-shapes
+ python auto_round_extension/ark/test/test_moe_w4a8_perf.py --phase decode
+ python auto_round_extension/ark/test/test_moe_w4a8_perf.py --rescale-group-size 256
+ python auto_round_extension/ark/test/test_moe_w4a8_perf.py --phase prefill --long-seq
+
+The prefill throughput points are two: ``--compute-bound`` derives, per model,
+the batch that puts 384 rows on every expert (the smallest routing where the
+100 TFLOPS goal is reachable at all), and ``--long-seq`` runs a fixed 8K-token
+prompt, whose 65536 routed rows divide into 512 rows per expert for Qwen3-MoE
+and 341 for MiniMax -- a higher intensity than the compute-bound batch for one
+model and a lower one for the other.
+
+Useful environment variables (read by the kernel itself):
+
+* ``ARK_MOE_W4A8_AUTO_S8`` -- override the AUTO_S8 re-scale block size.
+ Unset / ``-1`` keeps the default (one scale per output channel).
+* ``ARK_MOE_W4A8_DECODE_MAX_TOKENS`` -- token count at or below which
+ ``phase="auto"`` picks the GEMV (default 128).
+
+The dispatch knobs the sweeps here drive -- ``ARK_MOE_W4A8_PREFILL_TILE``,
+``ARK_MOE_W4A8_ACT_QUANT_VEC``, ``ARK_MOE_W4A8_ACT_QUANT_UNROLL``,
+``ARK_MOE_W4A8_PREFILL_FULL_TILE`` and the ``ARK_MOE_W4A8_DECODE_KSPLIT*``
+family -- are documented in ``README_MOE_W4A8.md``; each sweep sets them itself
+and restores the environment afterwards.
+
+.. note::
+
+ The W4A8 kernel is a new SYCL/CuTe port; this script is the intended
+ on-hardware validation vehicle for it (the kernel header is marked
+ ``STATUS: PARTIALLY HARDWARE-VALIDATED`` and names the paths that still
+ need a device run).
+"""
+
+import argparse
+import contextlib
+import math
+import os
+import sys
+from typing import Optional
+
+import torch
+
+try: # pytest is optional when the script is run directly
+ import pytest
+except ImportError: # pragma: no cover - standalone execution without pytest
+ pytest = None
+
+import auto_round_kernel
+
+# Reuse the pack/dequant helpers validated by the correctness tests.
+from test_moe import _dequant_int4_sym, _pack_int4_sym # noqa: E402
+
+ark = auto_round_kernel
+
+
+# ---------------------------------------------------------------------------
+# Skip reasons
+# ---------------------------------------------------------------------------
+
+
+def _xpu_available() -> bool:
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+def _xpu_skip_reason() -> str:
+ if not hasattr(torch, "xpu"):
+ return "torch has no xpu submodule (need an Intel XPU build of torch)"
+ if not torch.xpu.is_available():
+ return "torch.xpu.is_available() == False (no XPU device or driver visible)"
+ return ""
+
+
+def _w4a8_skip_reason() -> str:
+ """Return a non-empty string if the W4A8 MoE kernel can't be exercised."""
+ reason = _xpu_skip_reason()
+ if reason:
+ return reason
+ if ark.xpu_lib is None:
+ return (
+ "ark.xpu_lib is None -- the XPU extension module "
+ "(auto_round_kernel_xpu) failed to import; check that auto_round_kernel "
+ "was installed for THIS Python env with XPU support enabled"
+ )
+ for symbol in ("moe_w4a8_prepack", "moe_gemm_w4a8"):
+ if not hasattr(ark.xpu_lib, symbol):
+ return (
+ f"ark.xpu_lib loaded but has no {symbol} symbol -- "
+ "rebuild with ARK_SYCL_TLA=ON to compile the W4A8 MoE kernel"
+ )
+ return ""
+
+
+_W4A8_SKIP = _w4a8_skip_reason()
+
+
+def _quant_act_skip_reason() -> str:
+ """Skip reason for the tests that need the standalone quantization entry point.
+
+ Kept apart from :data:`_W4A8_SKIP` so an extension built before
+ ``moe_w4a8_quant_act`` existed still runs the rest of the suite instead of
+ skipping all of it.
+ """
+ if _W4A8_SKIP:
+ return _W4A8_SKIP
+ if not hasattr(ark.xpu_lib, "moe_w4a8_quant_act"):
+ return (
+ "ark.xpu_lib has no moe_w4a8_quant_act symbol -- rebuild the extension "
+ "to measure the activation quantization pass on its own"
+ )
+ return ""
+
+
+_QUANT_ACT_SKIP = _quant_act_skip_reason()
+
+print(
+ f"[moe-w4a8-perf] xpu_available={_xpu_available()} "
+ f"xpu_lib={'loaded' if ark.xpu_lib is not None else 'None'} "
+ f"has_moe_gemm_w4a8={hasattr(ark.xpu_lib, 'moe_gemm_w4a8') if ark.xpu_lib is not None else False}"
+)
+if _W4A8_SKIP:
+ print(f"[moe-w4a8-perf] suite will SKIP. reason: {_W4A8_SKIP}")
+
+
+# ---------------------------------------------------------------------------
+# Timing utilities
+# ---------------------------------------------------------------------------
+
+WARMUP = 5
+ITERS = 30
+# Rounds the config sweeps round-robin over their configurations. Three is
+# enough to separate a real ranking from clock drift without making the sweep
+# slower: the per-round iteration count is ITERS // SWEEP_ROUNDS, so the total
+# number of timed iterations per configuration is unchanged.
+SWEEP_ROUNDS = 3
+
+
+def _release_xpu_memory() -> None:
+ """Free cached XPU memory and synchronize between shapes."""
+ if _xpu_available():
+ torch.xpu.synchronize()
+ if hasattr(torch.xpu, "empty_cache"):
+ torch.xpu.empty_cache()
+
+
+def _env_override(**overrides):
+ """Temporarily set environment variables, restoring the previous values.
+
+ The kernel re-reads its dispatch flags on every call (they are never
+ cached in a static), so an in-process override is enough to A/B two code
+ paths without reloading the extension. A ``None`` value unsets the variable
+ for the duration of the block, which is how a sweep expresses "kernel
+ default".
+ """
+ previous = {name: os.environ.get(name) for name in overrides}
+ try:
+ for name, value in overrides.items():
+ if value is None:
+ os.environ.pop(name, None)
+ else:
+ os.environ[name] = value
+ yield
+ finally:
+ for name, value in previous.items():
+ if value is None:
+ os.environ.pop(name, None)
+ else:
+ os.environ[name] = value
+
+
+def _xpu_time_ms(fn, warmup: int | None = None, iters: int | None = None) -> float:
+ """Time ``fn`` on XPU using device events; returns the median ms per call.
+
+ ``warmup`` / ``iters`` default to the module-level ``WARMUP`` / ``ITERS``
+ at *call* time (not at definition time) so the standalone CLI's
+ ``--warmup`` / ``--iters`` flags take effect.
+ """
+ warmup = WARMUP if warmup is None else warmup
+ iters = ITERS if iters is None else iters
+ for _ in range(warmup):
+ fn()
+ torch.xpu.synchronize()
+
+ timings = []
+ for _ in range(iters):
+ start = torch.xpu.Event(enable_timing=True)
+ end = torch.xpu.Event(enable_timing=True)
+ start.record()
+ fn()
+ end.record()
+ end.synchronize()
+ timings.append(start.elapsed_time(end))
+ timings.sort()
+ return timings[len(timings) // 2]
+
+
+# ---------------------------------------------------------------------------
+# Accuracy metrics
+# ---------------------------------------------------------------------------
+
+
+def _snr_db(reference: torch.Tensor, actual: torch.Tensor) -> float:
+ """Signal-to-noise ratio in dB: ``10 log10(||ref||^2 / ||ref - act||^2)``.
+
+ Higher is better. ``inf`` means bit-exact. As a rule of thumb an int8
+ activation path lands around 25-40 dB against an fp32 reference; below
+ ~15 dB something is structurally wrong (wrong scale block, wrong layout)
+ rather than merely lossy.
+ """
+ ref = reference.to(torch.float32).flatten()
+ act = actual.to(torch.float32).flatten()
+ noise = torch.sum((ref - act) ** 2).item()
+ signal = torch.sum(ref**2).item()
+ if noise == 0.0:
+ return float("inf")
+ if signal == 0.0:
+ return float("-inf")
+ return 10.0 * math.log10(signal / noise)
+
+
+def _cosine(reference: torch.Tensor, actual: torch.Tensor) -> float:
+ ref = reference.to(torch.float32).flatten()
+ act = actual.to(torch.float32).flatten()
+ denom = ref.norm().item() * act.norm().item()
+ if denom == 0.0:
+ return float("nan")
+ return float(torch.dot(ref, act).item() / denom)
+
+
+def _max_rel_err(reference: torch.Tensor, actual: torch.Tensor) -> float:
+ """Max relative error, normalized by the reference magnitude scale.
+
+ Elements are normalized by ``max(|ref_elem|, 0.01 * max|ref|)`` so that
+ near-zero outputs (where the relative error is meaningless and explodes)
+ do not dominate the metric.
+ """
+ ref = reference.to(torch.float32)
+ act = actual.to(torch.float32)
+ scale = ref.abs().max().item()
+ if scale == 0.0:
+ return 0.0
+ denom = torch.clamp(ref.abs(), min=0.01 * scale)
+ return float(((ref - act).abs() / denom).max().item())
+
+
+_ULP_INT_DTYPE = {
+ torch.bfloat16: torch.int16,
+ torch.float16: torch.int16,
+ torch.float32: torch.int32,
+}
+
+
+def _ulp_diff(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ """Elementwise distance between two tensors counted in representable steps.
+
+ ``1`` means the two values are neighbours in the format -- the smallest
+ disagreement that can be expressed -- and ``0`` means identical. This is
+ the right unit for comparing two computations that are algebraically the
+ same but not required to round identically: a tolerance in absolute or
+ relative terms has to be picked to fit the magnitudes at hand, while "one
+ step apart" is a property of the format and holds across the whole range.
+
+ Floats are ordered by their bit pattern within a sign, so the pattern read
+ as an integer counts steps directly; the negatives run backwards, so their
+ magnitude is negated to get one monotone key over the whole line (which
+ also makes ``-0`` and ``+0`` the same key).
+ """
+ if a.dtype != b.dtype:
+ raise TypeError(f"_ulp_diff needs one dtype, got {a.dtype} and {b.dtype}")
+ int_dtype = _ULP_INT_DTYPE.get(a.dtype)
+ if int_dtype is None:
+ raise TypeError(f"_ulp_diff does not know the bit layout of {a.dtype}")
+ magnitude = torch.iinfo(int_dtype).max # 0x7fff / 0x7fffffff: everything but the sign
+
+ def key(t: torch.Tensor) -> torch.Tensor:
+ bits = t.contiguous().view(int_dtype).to(torch.int64)
+ return torch.where(bits < 0, -(bits & magnitude), bits)
+
+ return (key(a) - key(b)).abs()
+
+
+def _ulp_report(a: torch.Tensor, b: torch.Tensor) -> str:
+ """``max ULP`` plus how much of the tensor moved, for assertion messages.
+
+ The SNR is printed alongside because the two numbers fail differently: a
+ contract that reads the wrong scale or the wrong row misses by orders of
+ magnitude and takes the SNR down with it, while a difference confined to
+ the last bits leaves the SNR high however large the worst ULP distance is
+ (an output that cancels to near zero is many steps from its neighbour at
+ no cost in energy).
+ """
+ ulp = _ulp_diff(a, b)
+ differing = int((ulp > 0).sum().item())
+ total = ulp.numel()
+ return (
+ f"max {int(ulp.max().item())} ULP, {differing}/{total} elements differ "
+ f"({differing / total:.3%}), max |diff| {(a.float() - b.float()).abs().max().item():.6g}, "
+ f"SNR {_snr_db(a, b):.2f} dB"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Shapes
+#
+# Qwen3-MoE (the shape group the int4 MoE work targets):
+# hidden_size = 2048, intermediate_size = 768, num_local_experts = 128,
+# num_experts_per_tok = 8, int4-sym weights, group_size = 32
+#
+# w13 (gate/up-proj): N = 2 * 768 = 1536, K = 2048
+# w2 (down-proj) : N = 2048, K = 768
+#
+# Routed expert-token rows = ``batch * top_k``, spread round-robin over the
+# 128 experts.
+#
+# NOTE: the W4A8 kernel requires ``K % 64 == 0``; the down-proj K of 768
+# satisfies it, and the AUTO_S8 default block (= K) keeps a single full-K
+# accumulation for both GEMMs.
+# ---------------------------------------------------------------------------
+
+_QWEN3_E = 128
+_QWEN3_HIDDEN = 2048
+_QWEN3_INTER = 768
+_QWEN3_TOPK = 8
+_QWEN3_GROUP_SIZE = 32
+
+# (label, N, K) for the two grouped GEMMs of one Qwen3-MoE layer.
+_QWEN3_NK = [
+ ("qwen3 up ", 2 * _QWEN3_INTER, _QWEN3_HIDDEN),
+ ("qwen3 down", _QWEN3_HIDDEN, _QWEN3_INTER),
+]
+
+# ---------------------------------------------------------------------------
+# MiniMax-M2 shapes, matching ``test_moe_prefill_perf.py``:
+# hidden_size = 3072, intermediate_size = 1536, num_local_experts = 192,
+# num_experts_per_tok = 8.
+#
+# A second shape group matters here because both perf targets are shape
+# dependent: with 192 experts a given batch spreads over 1.5x more experts
+# (fewer rows per expert, so a *lower* compute ceiling at the same batch), while
+# K doubles for the up-proj (3072 vs 2048), which lengthens the decode GEMV's
+# sequential stream and gives the prefill tile more K per tile-load. Routing is
+# the same round-robin spread used for Qwen3; the heavy-tailed empirical
+# distribution lives in ``test_moe_prefill_perf.py``'s ``minimax real`` rows.
+# ---------------------------------------------------------------------------
+_MINIMAX_E = 192
+_MINIMAX_HIDDEN = 3072
+_MINIMAX_INTER = 1536
+_MINIMAX_TOPK = 8
+_MINIMAX_NK = [
+ ("minimax up ", _MINIMAX_INTER, _MINIMAX_HIDDEN),
+ ("minimax down", _MINIMAX_HIDDEN, _MINIMAX_INTER),
+]
+
+# A "model" is the (experts, top-k, group size, [(label, N, K)]) tuple the
+# sweeps iterate over. Everything downstream reads the per-row ``E``/``topk``,
+# so adding a group here is enough to get it benchmarked and target-checked.
+_MODELS = {
+ "qwen3": {"E": _QWEN3_E, "topk": _QWEN3_TOPK, "group_size": _QWEN3_GROUP_SIZE, "nk": _QWEN3_NK},
+ "minimax": {"E": _MINIMAX_E, "topk": _MINIMAX_TOPK, "group_size": _QWEN3_GROUP_SIZE, "nk": _MINIMAX_NK},
+}
+_DEFAULT_MODELS = ["qwen3"]
+
+
+def _models(names) -> list:
+ """Resolve model names (or ``"all"``) to ``(name, spec)`` pairs."""
+ if names is None:
+ names = _DEFAULT_MODELS
+ if isinstance(names, str):
+ names = _MODELS.keys() if names == "all" else [names]
+ return [(n, _MODELS[n]) for n in names]
+
+
+def _models_option(request):
+ """Read the ``--models`` pytest option (absent under a foreign conftest)."""
+ value = request.config.getoption("--models", default=None) if request is not None else None
+ if not value:
+ return None
+ if value == "all":
+ return "all"
+ return [name.strip() for name in value.split(",") if name.strip()]
+
+
+# Model-token batches (routed rows = batch * top_k).
+_DECODE_BATCHES = [1]
+_DECODE_BATCHES_EXTENDED = [1, 2, 8, 16]
+_PREFILL_BATCHES = [128]
+_PREFILL_BATCHES_EXTENDED = [128, 512, 2048, 8192]
+# Rows per expert at which the prefill TFLOPS target is physically reachable.
+#
+# This was 256, chosen from the weights-only roofline (``2 * rows/E *
+# weight_bandwidth``, i.e. "256 rows/expert needs only ~195 GB/s"). Counting
+# every stream the call moves (see ``_traffic_bytes``) puts the real
+# requirement at 374-423 GB/s, and 423 GB/s -- the qwen3 down-projection, the
+# shape with the smallest K and therefore the largest non-weight share -- is
+# past what a 456 GB/s part delivers: its ceiling at 256 rows/expert is 94
+# TFLOPS, so the target was *unreachable at the batch it was being measured
+# at*, whatever the kernel did.
+#
+# 384 is the smallest round value that clears 100 TFLOPS on every shipped shape
+# with margin (ceilings 112 / 130 / 137 / 154 TFLOPS at a 400 GB/s probe;
+# qwen3 down alone needs >= 290). The batch is derived per model
+# (``rows/E * E / top_k``): 6144 model tokens for Qwen3-MoE (128 experts),
+# 9216 for MiniMax (192).
+_PREFILL_TARGET_ROWS_PER_EXPERT = 384
+
+# A second prefill point, sized like a real prompt instead of by a target
+# rows/expert: one 8K-token sequence, i.e. 65536 routed rows -- the same 8K
+# group ``test_moe_prefill_perf.py`` sweeps.
+#
+# It is not a larger copy of the compute-bound batch. That batch is *derived*
+# per model so both land on 384 rows/expert; a fixed token count is divided by
+# a different expert count in each model, so the same 8K prompt puts 512 rows
+# on each of Qwen3-MoE's 128 experts and 341 on each of MiniMax's 192. The
+# arithmetic intensity therefore moves in opposite directions, and the roofline
+# with it: at a 400 GB/s probe the ceilings go 129 -> 145 and 112 -> 123 TFLOPS
+# for qwen3 up/down, and 137 -> 129 and 154 -> 145 for minimax up/down.
+#
+# 512 rows/expert also moves the *tile ladder*, which is why this point is
+# worth a sweep of its own rather than one more perf row: it is the only
+# routing in the suite at which the 256-row tile does not pad
+# (``ceil(M/256)*256 == ceil(M/128)*128``, false at 384 and true at 512), i.e.
+# the only one that can measure `TileM = 256` on its merits rather than on its
+# padding. ``test_perf_prefill_tile_sweep_long_seq`` did, and it came out level
+# or behind, which is why the ladder no longer has a 256-row rung.
+_PREFILL_LONG_SEQ_LEN = 8192
+
+
+# Rows per expert for the epilogue equivalence tests: enough to give every
+# expert interior *and* ragged tiles against the prefill tile the ladder picks
+# for this shape (128 rows: 300 is two full tiles plus a 44-row remainder),
+# which is what makes a single launch exercise both epilogue paths. It is
+# deliberately not tied to the perf batch above -- these tests need a specific
+# tile geometry, not a compute-bound routing, and the smaller batch keeps them
+# quick.
+_RAGGED_TILE_ROWS_PER_EXPERT = 300
+
+
+def _compute_bound_batches(model: dict) -> list:
+ """Model-token batches that put ``_PREFILL_TARGET_ROWS_PER_EXPERT`` rows on every expert."""
+ return [_PREFILL_TARGET_ROWS_PER_EXPERT * model["E"] // model["topk"]]
+
+
+def _long_seq_batches() -> list:
+ """The long-prompt prefill point: one ``_PREFILL_LONG_SEQ_LEN``-token sequence.
+
+ Unlike ``_compute_bound_batches`` this is *not* derived per model -- the
+ point of it is that a fixed prompt length routes differently in each model
+ (see ``_PREFILL_LONG_SEQ_LEN``).
+ """
+ return [_PREFILL_LONG_SEQ_LEN]
+
+
+def _spread_tokens(total_tokens: int, num_experts: int) -> list:
+ """Distribute ``total_tokens`` across ``num_experts`` round-robin."""
+ tpe = [0] * num_experts
+ for i in range(total_tokens):
+ tpe[i % num_experts] += 1
+ return tpe
+
+
+def _decode_batches(all_shapes: bool) -> list:
+ return list(_DECODE_BATCHES_EXTENDED if all_shapes else _DECODE_BATCHES)
+
+
+def _prefill_batches(all_shapes: bool) -> list:
+ return list(_PREFILL_BATCHES_EXTENDED if all_shapes else _PREFILL_BATCHES)
+
+
+# ---------------------------------------------------------------------------
+# Workload construction
+# ---------------------------------------------------------------------------
+
+
+def _int8_grid_activations(total_tokens, K, dtype, generator):
+ """Activations every correct absmax quantizer maps to the *same* int8 bytes.
+
+ The pre-quantized contract is only testable if the caller's int8 and the
+ kernel's own agree, and on arbitrary data they are not required to. Both
+ compute ``inv = 127 / absmax`` and round ``a * inv``, but the harness runs
+ that division in exact fp32 while SPIR-V lets the device's carry a few ulp,
+ so any product sitting on a ``.5`` tie can land on either side. With 16-bit
+ activations that is not a rare accident -- a bf16 row carries 8 mantissa
+ bits, so exact ties are common -- and a flipped int8 is *not* a rounding
+ difference in the output: it is a different input to the dot product, which
+ moves the result by ``|w| * scales`` in absolute terms, i.e. without bound
+ in ULP wherever the accumulator happens to cancel to near zero.
+
+ So the rows are put on the quantizer's own grid instead. ``a = q * 2^-e``
+ with integer ``|q| <= 127`` is exact in every 16-bit float format, ``127``
+ is planted in each row so its absmax is exactly ``127 * 2^-e``, and both
+ ``127 / absmax = 2^e`` and ``absmax / 127 = 2^-e`` are powers of two. Every
+ product is then the integer ``q`` itself -- half a step from the nearest
+ tie, a margin no plausible division error comes close to bridging -- so the
+ two quantizers must produce identical bytes and any difference in the
+ output belongs to the contract rather than to the rounding.
+
+ ``e`` walks 4..8 down the rows so neighbouring rows have different scales:
+ a scale read from the wrong row is then a factor of two, not a coincidence.
+ """
+ q = torch.randint(-127, 128, (total_tokens, K), generator=generator, dtype=torch.int32)
+ q[:, 0] = 127
+ exponent = -(4 + torch.arange(total_tokens, dtype=torch.int32) % 5)
+ activations = torch.ldexp(q.to(torch.float32), exponent.unsqueeze(1)).to(dtype)
+
+ # The construction is only worth anything if it survives the cast to
+ # `dtype` and the reference quantizer's own two divisions, so it is checked
+ # here -- cheaply, on the host, before the rows reach the device -- rather
+ # than left for a later edit to reintroduce the ties unnoticed.
+ q_back, scale_back = _quantize_rows(activations)
+ assert torch.equal(q_back.to(torch.int32), q), f"the int8 grid does not survive {dtype}"
+ assert torch.equal(
+ scale_back, torch.ldexp(torch.ones(total_tokens), exponent)
+ ), "the row scales are not the powers of two the grid was built from"
+ return activations
+
+
+def _build_case(
+ N,
+ K,
+ E,
+ total_tokens,
+ group_size,
+ dtype,
+ device="xpu",
+ seed=0,
+ need_reference=True,
+ need_dequant=True,
+ topk=None,
+ act_int8_grid=False,
+):
+ """Build one W4A8 MoE test case.
+
+ Returns a dict with the packed int4 weights + scales, the activations,
+ the routing histogram, and the fp32 reference output computed from the
+ dequantized weights (so quantization error of the *weights* is excluded
+ from the W4A8-vs-reference comparison, isolating the extra error the int8
+ activation path introduces).
+
+ ``need_dequant`` / ``need_reference`` are opt-outs for the perf sweeps:
+ the dequantized ``[E, N, K]`` weights (805 MB at the Qwen3 up-proj shape in
+ bf16) are only needed by the torch baseline, and the fp32 reference
+ (``[total_tokens, N]`` plus a full fp32 grouped matmul) is only needed by
+ the accuracy sweep. Skipping them is what keeps the compute-bound batches
+ -- the only ones where a prefill TOPS target is physically reachable --
+ inside a sane memory and time budget.
+
+ ``topk`` adds the side tables the fused top-k reduction needs: a
+ ``row -> model token`` map and a per-row routing weight. Row ``r`` is given
+ to token ``r % batch``, which puts each token on exactly ``top_k`` rows and
+ -- because an expert's block of rows is shorter than ``batch`` at every
+ shipped ``E`` -- never twice on the same expert, i.e. the same structure a
+ real router produces after the rows are sorted by expert.
+
+ ``act_int8_grid`` swaps the normally-distributed activations for rows that
+ quantize exactly (:func:`_int8_grid_activations`). It is for the tests that
+ compare two *quantizers* against each other rather than the kernel against
+ a reference, where a tie broken differently on either side would swamp what
+ is being measured.
+ """
+ generator = torch.Generator(device="cpu").manual_seed(seed)
+ w_float = torch.randn(E, N, K, generator=generator, dtype=torch.float32) * 0.05
+ scales = torch.empty(E, N, K // group_size, dtype=dtype)
+ packed = _pack_int4_sym(w_float, scales, group_size)
+
+ if act_int8_grid:
+ activations = _int8_grid_activations(total_tokens, K, dtype, generator)
+ else:
+ activations = (torch.randn(total_tokens, K, generator=generator, dtype=torch.float32) * 0.5).to(dtype)
+ tpe = _spread_tokens(total_tokens, E)
+ ntpe = torch.tensor(tpe, dtype=torch.int32)
+
+ row_to_token = None
+ routing_weights = None
+ batch = None
+ if topk:
+ batch = total_tokens // topk
+ row_to_token = (torch.arange(total_tokens, dtype=torch.int32) % max(batch, 1)).contiguous()
+ routing_weights = (torch.rand(total_tokens, generator=generator, dtype=torch.float32) + 0.5) / topk
+
+ packed = packed.to(device)
+ scales = scales.to(device)
+ activations = activations.to(device)
+ ntpe = ntpe.to(device)
+ if topk:
+ row_to_token = row_to_token.to(device)
+ routing_weights = routing_weights.to(device)
+
+ dequant = _dequant_int4_sym(packed, scales, group_size) if (need_dequant or need_reference) else None
+
+ # fp32 per-expert reference on the dequantized weights.
+ reference = None
+ if need_reference:
+ reference = torch.empty(total_tokens, N, device=device, dtype=torch.float32)
+ offset = 0
+ for e, n_e in enumerate(tpe):
+ if n_e == 0:
+ continue
+ a = activations[offset : offset + n_e].to(torch.float32)
+ reference[offset : offset + n_e] = a @ dequant[e].to(torch.float32).t()
+ offset += n_e
+ if not need_dequant:
+ dequant = None
+
+ return {
+ "packed": packed,
+ "scales": scales,
+ "dequant": dequant,
+ "activations": activations,
+ "ntpe": ntpe,
+ "tpe": tpe,
+ "reference": reference,
+ "N": N,
+ "K": K,
+ "E": E,
+ "total_tokens": total_tokens,
+ "group_size": group_size,
+ "dtype": dtype,
+ "topk": topk,
+ "batch": batch,
+ "row_to_token": row_to_token,
+ "routing_weights": routing_weights,
+ }
+
+
+def _torch_baseline(case):
+ """Per-expert ``A @ W.T`` on pre-dequantized weights (matmul-only cost)."""
+ activations = case["activations"]
+ dequant = case["dequant"]
+ out = torch.empty(case["total_tokens"], case["N"], device=activations.device, dtype=activations.dtype)
+ offset = 0
+ for e, n_e in enumerate(case["tpe"]):
+ if n_e == 0:
+ continue
+ out[offset : offset + n_e] = activations[offset : offset + n_e] @ dequant[e].t()
+ offset += n_e
+ return out
+
+
+def _w4a16(case, phase):
+ """The existing W4A16 ARK path (int4 weights, fp16/bf16 compute)."""
+ if phase == "decode":
+ return ark.moe_gemm_decode(
+ case["activations"],
+ case["packed"],
+ case["ntpe"],
+ scales=case["scales"],
+ weight_bits=4,
+ group_size=case["group_size"],
+ asym=False,
+ )
+ return ark.moe_gemm_prefill(
+ case["activations"],
+ case["packed"],
+ case["ntpe"],
+ scales=case["scales"],
+ weight_bits=4,
+ group_size=case["group_size"],
+ asym=False,
+ )
+
+
+def _quantize_rows(activations):
+ """Per-row absmax int8 quantization -- the reference for what the kernel does.
+
+ Reproduces ``launch_act_dynamic_quant`` expression for expression: the
+ absmax is an exact reduction, ``inv = 127 / absmax`` and
+ ``scale = absmax / 127`` are the same two fp32 operations, and ``rint`` is
+ round-half-to-even, which is what ``torch.round`` does as well.
+
+ Same expressions is not the same bits, though. Those two divisions are
+ exact in IEEE fp32 here and only approximate on the device -- SPIR-V lets
+ a division carry a few ulp of error, and the kernel is not built with the
+ flags that would forbid that -- so ``inv`` can land one step off, and any
+ product that sits on a ``.5`` tie then rounds the other way. The callers
+ that need the two to agree byte for byte hand this function rows that
+ cannot tie (:func:`_int8_grid_activations`); on arbitrary rows it is a
+ faithful model of the kernel, not a bit-exact one.
+ """
+ a = activations.to(torch.float32)
+ absmax = a.abs().amax(dim=1)
+ scale = absmax / 127.0
+ inv = torch.where(absmax > 0, 127.0 / absmax, torch.zeros_like(absmax))
+ q = torch.clamp(torch.round(a * inv.unsqueeze(1)), -127.0, 127.0).to(torch.int8)
+ return q.contiguous(), scale.contiguous()
+
+
+def _prequantized(case):
+ """Cached ``(int8 activations, fp32 row scales)`` for ``case``."""
+ if case.get("qact") is None:
+ qact, ascale = _quantize_rows(case["activations"])
+ case["qact"], case["ascale"] = qact, ascale
+ return case["qact"], case["ascale"]
+
+
+def _reduces_topk(nk_label: str) -> bool:
+ """Whether this projection's output is the one the top-k combine reduces.
+
+ Only the second (down) GEMM of a MoE layer produces rows that are scaled by
+ the routing weights and summed back per token. The up/gate output stays
+ expanded -- one row per routed token, straight into SiLU -- so it owes no
+ caller-side reduction and cannot use the fused epilogue. Charging it one
+ would credit the fused contract with removing work that never existed, the
+ same overstatement :func:`_traffic_bytes` avoids by leaving ``fused_rows``
+ unset.
+ """
+ return nk_label.strip().endswith("down")
+
+
+def _reduce_topk(case, out):
+ """Reduce an unfused ``[T, N]`` output the way a caller would.
+
+ ``index_add_`` on an fp32 accumulator, i.e. exactly the reduction the fused
+ epilogue replaces -- so this is what a fused result is compared against.
+ """
+ reduced = torch.zeros((case["batch"], case["N"]), device=out.device, dtype=torch.float32)
+ reduced.index_add_(0, case["row_to_token"].to(torch.long), out.to(torch.float32) * case["routing_weights"][:, None])
+ return reduced
+
+
+def _w4a8(case, weights_s8, wscales, block, phase, prequant=False, fused=False):
+ """One ``moe_gemm_w4a8`` call under the requested call contract.
+
+ ``prequant`` hands the kernel int8 activations and their per-row scales so
+ it skips its own quantization pass; ``fused`` asks the epilogue to apply
+ the routing weights and scatter-add into a ``[batch, N]`` fp32 accumulator
+ instead of writing the unreduced ``[T, N]``.
+ """
+ kwargs = {}
+ activations = case["activations"]
+ if prequant:
+ activations, ascale = _prequantized(case)
+ kwargs["activation_scale"] = ascale
+ kwargs["out_dtype"] = case["dtype"]
+ if fused:
+ kwargs["row_to_token"] = case["row_to_token"]
+ kwargs["routing_weights"] = case["routing_weights"]
+ kwargs["output_rows"] = case["batch"]
+ return ark.moe_gemm_w4a8(
+ activations,
+ weights_s8,
+ wscales,
+ case["ntpe"],
+ rescale_block_size=block,
+ phase=phase,
+ **kwargs,
+ )
+
+
+def _flops(total_tokens, N, K) -> float:
+ """MoE grouped GEMM FLOPs: each token does one ``[K] x [K, N]`` product."""
+ return float(total_tokens) * N * K * 2.0
+
+
+def _weight_bytes(E, N, K, bits) -> float:
+ return float(E) * N * K * bits / 8.0
+
+
+def _dtype_bytes(dtype) -> int:
+ return torch.empty((), dtype=dtype).element_size()
+
+
+# ---------------------------------------------------------------------------
+# Targets and the roofline they have to be read against
+#
+# The weights are the largest single stream, but they are not the only one. A
+# W4A8 MoE call moves, per invocation:
+#
+# * ``T * K * sizeof(act)`` -- the routed activations, read by the quantizer
+# * ``T * K`` -- the int8 quantized copy, written
+# * ``T * K`` -- and read back by the GEMM
+# * ``E_active * N * K`` -- every active expert's int8 weights, once
+# * ``T * N * sizeof(out)`` -- the output
+#
+# Only the fourth line is what ``W GB/s`` reports, and it is a *minority* of
+# the total whenever K is small: at 384 rows per expert the qwen3
+# down-projection (N = 2048, K = 768) moves 201 MB of weights inside 554 MB of
+# traffic, so a roofline built on weights alone understates the bandwidth a
+# shape needs by ~2.7x. This matters for the verdict, not just the bookkeeping:
+# at the 256 rows per expert this harness used to measure at, the same shape
+# needs 423 GB/s to reach 100 TFLOPS -- past what a 456 GB/s part delivers, so
+# the target was unreachable there whatever the kernel did. See
+# ``_PREFILL_TARGET_ROWS_PER_EXPERT``.
+#
+# The old model -- ``TFLOPS <= 2 * rows_per_expert * weight_bandwidth``, i.e.
+# ``BW@100T = 50 TB/s / rows_per_expert`` -- is the weights-only special case
+# and is what the earlier tuning rounds were judged against. It is kept in mind
+# here only as the reason those rounds read as "close to target": the target
+# was measured against half the traffic.
+#
+# The intensity still rises with ``rows/E`` (the weight term is the only one
+# that does not grow with T), which is why the perf table prints ``rows/E`` and
+# why the prefill target sweep uses a compute-bound batch -- but the ceiling
+# now saturates instead of growing without bound, because the activation,
+# quantized-activation and output streams all scale with T exactly as the
+# FLOPs do.
+# ---------------------------------------------------------------------------
+
+_TARGET_PREFILL_TFLOPS = 100.0
+_TARGET_DECODE_GBPS = 300.0
+
+
+def _rows_per_expert(total_tokens, active_experts) -> float:
+ return float(total_tokens) / float(active_experts) if active_experts else 0.0
+
+
+def _traffic_bytes(total_tokens, active_experts, N, K, act_bytes=2, out_bytes=2, prequantized=False, fused_rows=None):
+ """Compulsory DRAM traffic of one ``moe_gemm_w4a8`` call, in bytes.
+
+ Counts each byte once: re-reads of A across the N tiles are L2 hits at any
+ launch this kernel produces (~20 concurrent work-groups against 8 MB of
+ L2), so they are not DRAM traffic. This is a lower bound, which keeps the
+ derived ceiling optimistic and therefore never excuses a slow kernel.
+
+ The two optional call contracts remove whole streams, so the model has to
+ know which one is in force or every derived number (``BW@100T``, the
+ ceiling, the PASS/FAIL verdict) is computed against traffic the call no
+ longer moves:
+
+ * ``prequantized``: the caller hands over int8 activations, so the 16-bit
+ read and the int8 write are gone and only the GEMM's read-back remains.
+ * ``fused_rows``: the epilogue reduces into a ``[batch, N]`` fp32
+ accumulator, so instead of writing ``T * N`` elements it reads *and*
+ writes ``batch * N`` fp32 ones.
+
+ This counts one *call*, so the caller-side reduction an unfused result
+ still owes is deliberately not in here: only the second projection's output
+ is reduced in a real layer, and the up/gate output feeds SiLU unreduced, so
+ charging every unfused shape for a reduction would overstate the traffic on
+ half of them. The contract sweep accounts for that reduction in the timing
+ instead, where it can be applied per configuration.
+ """
+ act_read = 0.0 if prequantized else float(total_tokens) * K * act_bytes
+ qact_write_read = (1.0 if prequantized else 2.0) * float(total_tokens) * K
+ weights = float(active_experts) * N * K
+ if fused_rows:
+ out_write = 2.0 * float(fused_rows) * N * 4
+ else:
+ out_write = float(total_tokens) * N * out_bytes
+ return act_read + qact_write_read + weights + out_write
+
+
+def _bw_needed_for_tflops(
+ total_tokens,
+ active_experts,
+ N,
+ K,
+ act_bytes=2,
+ out_bytes=2,
+ tflops_target=_TARGET_PREFILL_TFLOPS,
+ prequantized=False,
+ fused_rows=None,
+) -> float:
+ """GB/s of DRAM traffic a shape needs to hit ``tflops_target``."""
+ flops = _flops(total_tokens, N, K)
+ if flops <= 0.0:
+ return float("inf")
+ seconds_at_target = flops / (tflops_target * 1e12)
+ traffic = _traffic_bytes(
+ total_tokens, active_experts, N, K, act_bytes, out_bytes, prequantized=prequantized, fused_rows=fused_rows
+ )
+ return traffic / seconds_at_target / 1e9
+
+
+def _tflops_ceiling(
+ total_tokens, active_experts, N, K, gbps, act_bytes=2, out_bytes=2, prequantized=False, fused_rows=None
+) -> float:
+ """Best TFLOPS this shape can reach at ``gbps`` of DRAM bandwidth."""
+ traffic = _traffic_bytes(
+ total_tokens, active_experts, N, K, act_bytes, out_bytes, prequantized=prequantized, fused_rows=fused_rows
+ )
+ if traffic <= 0.0:
+ return float("inf")
+ return _flops(total_tokens, N, K) / (traffic / (gbps * 1e9)) / 1e12
+
+
+_DEVICE_BW_GBPS = None
+
+
+def _device_bandwidth_gbps():
+ """Measure achievable device DRAM bandwidth with a large device-to-device copy.
+
+ Used to turn ``rows/E`` into a *hard* TFLOPS ceiling for the current GPU,
+ so a prefill row can be reported as "unreachable at this routing" instead
+ of "slow". Deriving the ceiling from the kernel's own measured bandwidth
+ would be circular (it reproduces the measured TFLOPS exactly), hence the
+ independent probe.
+
+ The copy counts one read plus one write, which slightly *understates*
+ read-only weight streaming. That conservatism is not free: a ceiling that
+ is too low reads as "bandwidth bound", and :func:`_assert_targets` skips
+ enforcement on exactly those rows, so an under-measured probe silently
+ excuses a slow kernel. :func:`_apply_bandwidth_evidence` is the guard.
+
+ Taken as the *best* of several rounds rather than one burst's median. A
+ single burst samples whatever clock state the device happens to be in, and
+ on B70 that spread three consecutive runs across 439 / 373 / 299 GB/s --
+ a 47% swing in a number the ceilings treat as a hardware constant. The
+ fastest copy is the one least contaminated by throttling, which is the same
+ reason every other measurement here min-filters. Cached after the first
+ call; returns ``None`` if XPU is unavailable or the probe fails.
+ """
+ global _DEVICE_BW_GBPS
+ if _DEVICE_BW_GBPS is not None:
+ return _DEVICE_BW_GBPS
+ if not _xpu_available():
+ return None
+ nbytes = 128 * 1024 * 1024 # far past any device cache
+ try:
+ src = torch.empty(nbytes, dtype=torch.int8, device="xpu")
+ dst = torch.empty_like(src)
+ ms = min(_xpu_time_ms(lambda: dst.copy_(src), warmup=2, iters=5) for _ in range(3))
+ _DEVICE_BW_GBPS = 2.0 * nbytes / (ms * 1e-3) / 1e9
+ except Exception as exc: # pragma: no cover - depends on device/runtime
+ print(f"[moe-w4a8-perf] device bandwidth probe unavailable: {exc}")
+ return None
+ finally:
+ src = dst = None
+ _release_xpu_memory()
+ return _DEVICE_BW_GBPS
+
+
+def _apply_bandwidth_evidence(rows) -> None:
+ """Raise the ceilings when a row proved the probe under-measured.
+
+ The ceilings are derived from an independent copy probe, but the probe is
+ only ever a *lower* bound on what the part can stream: it counts a read
+ plus a write, and it samples one moment of one clock state. A kernel row
+ that moved its own traffic at a higher rate is direct evidence the device
+ sustains at least that much -- so the probe, not the row, is what was
+ wrong.
+
+ Without this a run can print "118% of the bandwidth ceiling", which is not
+ a thing a roofline can do; worse, :func:`_assert_targets` waives the target
+ for any row sitting below its ceiling, so a cold probe hands out the
+ "bandwidth bound, unreachable" excuse to rows that are merely slow.
+
+ Ceilings are linear in bandwidth, so each is rescaled by the same ratio.
+ This only ever raises them, which only ever makes the verdict stricter.
+ """
+ if not rows:
+ return
+ probe = rows[0].get("device_bw_gbps")
+ if not probe:
+ return
+ best = max((r.get("dram_gbps") or 0.0) for r in rows)
+ if best <= probe:
+ return
+ winner = max(rows, key=lambda r: r.get("dram_gbps") or 0.0)
+ scale = best / probe
+ for row in rows:
+ if row.get("tflops_ceiling") is not None:
+ row["tflops_ceiling"] *= scale
+ row["bw_evidence_gbps"] = best
+ row["bw_evidence_label"] = winner["label"]
+
+
+# ---------------------------------------------------------------------------
+# Printing
+# ---------------------------------------------------------------------------
+
+_ACC_WIDTH = 150
+_PERF_WIDTH = 179
+
+
+def _print_acc_header(title: str) -> None:
+ """Accuracy table.
+
+ * ``SNR ref`` / ``cos ref`` / ``maxrel ref``: W4A8 against the fp32
+ reference computed from the *dequantized* int4 weights. This isolates
+ the error added by the int8 activation quantization and the AUTO_S8
+ weight re-scale.
+ * ``SNR w4a16``: W4A8 against the existing W4A16 ARK kernel -- the
+ quality delta a caller sees when switching paths.
+ """
+ print()
+ print("=" * _ACC_WIDTH)
+ print(title)
+ print(
+ f"{'shape':<14}{'E':>5}{'N':>7}{'K':>7}{'tokens':>8}{'block':>8}"
+ f"{'SNR ref(dB)':>14}{'cos ref':>12}{'maxrel ref':>13}"
+ f"{'SNR w4a16(dB)':>16}{'cos w4a16':>12}{'w4a16 SNR ref':>16}"
+ )
+ print("-" * _ACC_WIDTH)
+
+
+def _print_acc_row(label, E, N, K, tokens, block, snr_ref, cos_ref, maxrel_ref, snr_w4a16, cos_w4a16, w4a16_snr_ref):
+ def _fmt(v, digits=3):
+ if v is None:
+ return "--"
+ if isinstance(v, float) and (math.isinf(v) or math.isnan(v)):
+ return "inf" if v > 0 else ("nan" if math.isnan(v) else "-inf")
+ return f"{v:.{digits}f}"
+
+ print(
+ f"{label:<14}{E:>5}{N:>7}{K:>7}{tokens:>8}{block:>8}"
+ f"{_fmt(snr_ref, 2):>14}{_fmt(cos_ref, 5):>12}{_fmt(maxrel_ref, 4):>13}"
+ f"{_fmt(snr_w4a16, 2):>16}{_fmt(cos_w4a16, 5):>12}{_fmt(w4a16_snr_ref, 2):>16}"
+ )
+
+
+def _print_perf_header(title: str) -> None:
+ """Perf table.
+
+ * ``torch(ms)``: per-expert ``A @ W.T`` on pre-dequantized weights
+ (matmul-only; the dequant is outside the timed region).
+ * ``w4a16(ms)``: the existing ARK int4 kernel for the same phase.
+ * ``w4a8(ms)`` / ``TFLOPS`` / ``W GB/s``: the new int8-compute path.
+ ``W GB/s`` counts only the expert weight traffic actually touched by
+ the routed tokens, which is what a memory-bound decode is limited by.
+ * ``DRAM GB/s``: *all* the traffic the call moves -- the activations the
+ quantizer reads, the int8 copy it writes, the GEMM's read of that copy,
+ the weights and the output. On the small-K shapes the weights are under
+ half of this, so it is the number to compare against the device probe.
+ * ``rows/E``: routed tokens per active expert. The weight stream is the
+ only one that does not grow with the token count, so this is what raises
+ the arithmetic intensity -- but the other four streams keep it bounded.
+ * ``BW@100T``: DRAM bandwidth the shape would need to reach 100 TFLOPS.
+ When it exceeds what the device can stream, ``TFLOPS`` is capped by
+ memory and no kernel change can reach the target at that shape.
+ * ``vs torch`` / ``vs w4a16``: speedups (``other / w4a8``).
+ """
+ print()
+ print("=" * _PERF_WIDTH)
+ print(title)
+ print(
+ f"{'shape':<14}{'E':>5}{'N':>7}{'K':>7}{'tokens':>8}{'rows/E':>8}"
+ f"{'torch(ms)':>12}{'w4a16(ms)':>12}{'w4a8(ms)':>12}"
+ f"{'TFLOPS':>10}{'W GB/s':>10}{'DRAM GB/s':>11}{'BW@100T':>10}"
+ f"{'vs torch':>11}{'vs w4a16':>11}{'prepack(ms)':>13}"
+ )
+ print("-" * _PERF_WIDTH)
+
+
+def _print_perf_row(
+ label,
+ E,
+ N,
+ K,
+ tokens,
+ torch_ms,
+ w4a16_ms,
+ w4a8_ms,
+ tflops,
+ gbps,
+ prepack_ms,
+ rows_per_expert=None,
+ bw_at_100t=None,
+ dram_gbps=None,
+):
+ def _fmt(v, digits=3):
+ if v is None:
+ return "--"
+ if isinstance(v, float) and math.isinf(v):
+ return "inf"
+ return f"{v:.{digits}f}"
+
+ vs_torch = None if (torch_ms is None or not w4a8_ms) else torch_ms / w4a8_ms
+ vs_w4a16 = None if (w4a16_ms is None or not w4a8_ms) else w4a16_ms / w4a8_ms
+ print(
+ f"{label:<14}{E:>5}{N:>7}{K:>7}{tokens:>8}{_fmt(rows_per_expert, 1):>8}"
+ f"{_fmt(torch_ms):>12}{_fmt(w4a16_ms):>12}{_fmt(w4a8_ms):>12}"
+ f"{_fmt(tflops, 2):>10}{_fmt(gbps, 1):>10}{_fmt(dram_gbps, 1):>11}{_fmt(bw_at_100t, 0):>10}"
+ f"{(_fmt(vs_torch, 2) + 'x') if vs_torch else '--':>11}"
+ f"{(_fmt(vs_w4a16, 2) + 'x') if vs_w4a16 else '--':>11}"
+ f"{_fmt(prepack_ms, 2):>13}"
+ )
+
+
+def _print_targets(phase: str, rows) -> None:
+ """Print the goal verdict for a perf sweep.
+
+ Prefill is judged on TFLOPS, decode on weight bandwidth. A prefill row
+ whose device-bandwidth ceiling is already below the target is reported as
+ ``N/A`` rather than ``FAIL``: at that routing the target is unreachable by
+ construction (see the roofline note above ``_TARGET_PREFILL_TFLOPS``), and
+ the row's measured bandwidth is what should be judged instead.
+
+ The ceiling counts every stream the call moves, not just the weights, so a
+ small-K shape can be ``N/A`` here while the weights-only model of earlier
+ rounds called it reachable. A reachable row also prints how much of the
+ ceiling it actually reaches, which is the number a kernel change can move.
+ """
+ if not rows:
+ return
+ is_prefill = phase == "prefill"
+ target = _TARGET_PREFILL_TFLOPS if is_prefill else _TARGET_DECODE_GBPS
+ unit = "TFLOPS" if is_prefill else "GB/s"
+ device_bw = rows[0].get("device_bw_gbps")
+ evidence = rows[0].get("bw_evidence_gbps")
+ print()
+ print(f"targets [{phase}]: {'prefill compute' if is_prefill else 'decode weight bandwidth'} > {target:g} {unit}")
+ if device_bw:
+ note = ""
+ if evidence:
+ note = (
+ f" (under-measured: {rows[0]['bw_evidence_label']} streamed {evidence:.0f} GB/s, "
+ f"so the ceilings below use that)"
+ )
+ print(f" device copy bandwidth probe: {device_bw:.0f} GB/s{note}")
+ for row in rows:
+ measured = row["tflops"] if is_prefill else row["gbps"]
+ ceiling = row.get("tflops_ceiling")
+ if is_prefill and ceiling is not None and ceiling < target:
+ verdict = (
+ f"N/A (bandwidth bound: ceiling {ceiling:.1f} {unit} at {row['rows_per_expert']:.0f} rows/expert; "
+ f"reaching {target:g} would need {row['bw_at_100t']:.0f} GB/s of DRAM traffic)"
+ )
+ else:
+ verdict = "PASS" if measured > target else "FAIL"
+ if is_prefill and ceiling:
+ verdict += f" ({measured / ceiling * 100:.0f}% of the {ceiling:.0f} {unit} bandwidth ceiling)"
+ print(
+ f" {row['label']:<12} tokens={row['tokens']:<6} rows/E={row['rows_per_expert']:<6.1f} "
+ f"{measured:8.2f} {unit} vs {target:g} -> {verdict}"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Core sweeps (shared by pytest and the standalone CLI)
+# ---------------------------------------------------------------------------
+
+
+def run_accuracy(phase, batches, dtype=torch.bfloat16, rescale_group_size=-1, verbose=True):
+ """Run the W4A8 accuracy sweep. Returns a list of per-row metric dicts."""
+ rows = []
+ if verbose:
+ _print_acc_header(
+ f"W4A8 accuracy [{phase}] (E={_QWEN3_E}, group_size={_QWEN3_GROUP_SIZE}, "
+ f"act={str(dtype).split('.')[-1]}, rescale_group_size={rescale_group_size}) "
+ f"-- ark.moe_w4a8 vs fp32(dequant int4) and vs W4A16"
+ )
+ for nk_label, N, K in _QWEN3_NK:
+ for batch in batches:
+ total_tokens = batch * _QWEN3_TOPK
+ case = _build_case(N, K, _QWEN3_E, total_tokens, _QWEN3_GROUP_SIZE, dtype)
+
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"],
+ case["scales"],
+ group_size=_QWEN3_GROUP_SIZE,
+ rescale_group_size=rescale_group_size,
+ )
+ out_w4a8 = _w4a8(case, weights_s8, wscales, block, phase)
+
+ try:
+ out_w4a16 = _w4a16(case, phase)
+ except Exception as exc: # pragma: no cover - depends on build
+ print(f"[moe-w4a8-perf] W4A16 reference unavailable for {nk_label}: {exc}")
+ out_w4a16 = None
+
+ reference = case["reference"]
+ row = {
+ "label": nk_label,
+ "phase": phase,
+ "E": _QWEN3_E,
+ "N": N,
+ "K": K,
+ "tokens": total_tokens,
+ "block": block,
+ "snr_ref": _snr_db(reference, out_w4a8),
+ "cos_ref": _cosine(reference, out_w4a8),
+ "maxrel_ref": _max_rel_err(reference, out_w4a8),
+ "snr_w4a16": None if out_w4a16 is None else _snr_db(out_w4a16, out_w4a8),
+ "cos_w4a16": None if out_w4a16 is None else _cosine(out_w4a16, out_w4a8),
+ "w4a16_snr_ref": None if out_w4a16 is None else _snr_db(reference, out_w4a16),
+ }
+ rows.append(row)
+ if verbose:
+ _print_acc_row(
+ nk_label,
+ _QWEN3_E,
+ N,
+ K,
+ total_tokens,
+ block,
+ row["snr_ref"],
+ row["cos_ref"],
+ row["maxrel_ref"],
+ row["snr_w4a16"],
+ row["cos_w4a16"],
+ row["w4a16_snr_ref"],
+ )
+
+ # Drop the (large) int8 weights before the next shape allocates.
+ case = weights_s8 = wscales = out_w4a8 = out_w4a16 = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+ return rows
+
+
+def run_perf(
+ phase,
+ batches,
+ dtype=torch.bfloat16,
+ rescale_group_size=-1,
+ verbose=True,
+ torch_baseline=True,
+ models=None,
+ compute_bound=False,
+ prequantized=False,
+ fused_reduce=False,
+):
+ """Run the W4A8 perf sweep. Returns a list of per-row metric dicts.
+
+ ``torch_baseline=False`` skips both the dequantized weights and the torch
+ matmul timing; the compute-bound batches need it to stay within memory.
+
+ ``models`` selects the shape groups (``"qwen3"``, ``"minimax"``, ``"all"``
+ or a list); ``compute_bound=True`` ignores ``batches`` and derives, per
+ model, the batch that puts ``_PREFILL_TARGET_ROWS_PER_EXPERT`` rows on every
+ expert -- the only regime where the prefill TOPS target is reachable.
+
+ ``prequantized`` / ``fused_reduce`` select the traffic-cutting call
+ contracts (see :func:`_w4a8`). They change what the call moves, so they are
+ also fed to the traffic model: the printed ``DRAM GB/s``, ``BW@100T`` and
+ the ceiling that decides the verdict all follow the contract in force.
+
+ ``fused_reduce`` applies only to the projection whose output is actually
+ top-k reduced (:func:`_reduces_topk`). Fusing the up/gate projection is not
+ a contract a layer can take -- that output stays expanded into SiLU -- so
+ enabling it there measures a configuration nobody can ship and charges the
+ contract for it. The header says which shapes it reached.
+ """
+ rows = []
+ # Probed before anything large is allocated (and cached across sweeps).
+ device_bw = _device_bandwidth_gbps()
+ resolved = _models(models)
+ contract = "".join(
+ [
+ ", A=int8-in" if prequantized else "",
+ ", fused top-k reduce (down-proj only)" if fused_reduce else "",
+ ]
+ )
+ if verbose:
+ _print_perf_header(
+ f"W4A8 perf [{phase}] (models={'+'.join(n for n, _ in resolved)}, "
+ f"group_size={_QWEN3_GROUP_SIZE}, "
+ f"act={str(dtype).split('.')[-1]}, rescale_group_size={rescale_group_size}{contract}) "
+ f"-- ark.moe_gemm_w4a8 vs W4A16 vs torch"
+ )
+ shapes = [
+ (nk_label, N, K, spec, batch)
+ for _, spec in resolved
+ for nk_label, N, K in spec["nk"]
+ for batch in (_compute_bound_batches(spec) if compute_bound else batches)
+ ]
+ for nk_label, N, K, spec, batch in shapes:
+ E, topk, group_size = spec["E"], spec["topk"], spec["group_size"]
+ total_tokens = batch * topk
+ # Only the reduced projection can take the fused contract.
+ fused_here = fused_reduce and _reduces_topk(nk_label)
+ case = _build_case(
+ N,
+ K,
+ E,
+ total_tokens,
+ group_size,
+ dtype,
+ need_reference=False,
+ need_dequant=torch_baseline,
+ topk=topk if fused_here else None,
+ )
+
+ # One-shot int4 -> int8 AUTO_S8 conversion. Timed separately: it
+ # happens once at model load, not per forward.
+ prepack_ms = _xpu_time_ms(
+ lambda: ark.moe_w4a8_prepack(
+ case["packed"],
+ case["scales"],
+ group_size=group_size,
+ rescale_group_size=rescale_group_size,
+ ),
+ warmup=1,
+ iters=3,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"],
+ case["scales"],
+ group_size=group_size,
+ rescale_group_size=rescale_group_size,
+ )
+
+ # Round-robin over the three implementations rather than timing each
+ # to completion in turn. Measuring w4a8 first and w4a16 last put the
+ # two on opposite ends of the sweep's clock droop, which biases the
+ # headline `vs w4a16` ratio *upward* -- both the numerator being
+ # measured hot and the denominator cold push it the same way. Taking
+ # each one's least-throttled round removes that from the ratio; see
+ # `_sweep_timings` for the measurement this is guarding against.
+ w4a8_samples, torch_samples, w4a16_samples = [], [], []
+ w4a16_failed = None
+ iters = max(1, ITERS // SWEEP_ROUNDS)
+ for _ in range(SWEEP_ROUNDS):
+ w4a8_samples.append(
+ _xpu_time_ms(
+ lambda: _w4a8(case, weights_s8, wscales, block, phase, prequant=prequantized, fused=fused_here),
+ iters=iters,
+ )
+ )
+ if torch_baseline:
+ torch_samples.append(_xpu_time_ms(lambda: _torch_baseline(case), iters=iters))
+ if w4a16_failed is None:
+ try:
+ w4a16_samples.append(_xpu_time_ms(lambda: _w4a16(case, phase), iters=iters))
+ except Exception as exc: # pragma: no cover - depends on build
+ w4a16_failed = exc
+ if w4a16_failed is not None:
+ print(f"[moe-w4a8-perf] W4A16 timing unavailable for {nk_label}: {w4a16_failed}")
+ w4a8_ms = min(w4a8_samples)
+ torch_ms = min(torch_samples) if torch_samples else None
+ w4a16_ms = min(w4a16_samples) if w4a16_samples else None
+
+ active_experts = sum(1 for n_e in case["tpe"] if n_e > 0)
+ tflops = _flops(total_tokens, N, K) / (w4a8_ms * 1e-3) / 1e12
+ # W4A8 streams int8 weights: 1 byte per element, only for the
+ # experts that actually received tokens.
+ gbps = _weight_bytes(active_experts, N, K, 8) / (w4a8_ms * 1e-3) / 1e9
+ # Everything the call moves, not just the weights: the quantizer's read
+ # of A, the int8 copy it writes, the GEMM's read of that copy and the
+ # output. On the small-K shapes the weights are under half of it.
+ act_bytes = _dtype_bytes(dtype)
+ fused_rows = case["batch"] if fused_here else None
+ traffic = _traffic_bytes(
+ total_tokens,
+ active_experts,
+ N,
+ K,
+ act_bytes,
+ act_bytes,
+ prequantized=prequantized,
+ fused_rows=fused_rows,
+ )
+ dram_gbps = traffic / (w4a8_ms * 1e-3) / 1e9
+ rows_per_expert = _rows_per_expert(total_tokens, active_experts)
+ bw_at_100t = _bw_needed_for_tflops(
+ total_tokens,
+ active_experts,
+ N,
+ K,
+ act_bytes,
+ act_bytes,
+ prequantized=prequantized,
+ fused_rows=fused_rows,
+ )
+
+ row = {
+ "label": nk_label,
+ "phase": phase,
+ "E": E,
+ "N": N,
+ "K": K,
+ "tokens": total_tokens,
+ "torch_ms": torch_ms,
+ "w4a16_ms": w4a16_ms,
+ "w4a8_ms": w4a8_ms,
+ "tflops": tflops,
+ "gbps": gbps,
+ "dram_gbps": dram_gbps,
+ "prepack_ms": prepack_ms,
+ "active_experts": active_experts,
+ "rows_per_expert": rows_per_expert,
+ "bw_at_100t": bw_at_100t,
+ # Hard ceiling for this routing on this device (``None`` when
+ # the bandwidth probe is unavailable).
+ "tflops_ceiling": (
+ None
+ if device_bw is None
+ else _tflops_ceiling(
+ total_tokens,
+ active_experts,
+ N,
+ K,
+ device_bw,
+ act_bytes,
+ act_bytes,
+ prequantized=prequantized,
+ fused_rows=fused_rows,
+ )
+ ),
+ "device_bw_gbps": device_bw,
+ "prequantized": prequantized,
+ "fused_reduce": fused_here,
+ }
+ rows.append(row)
+ if verbose:
+ _print_perf_row(
+ nk_label,
+ E,
+ N,
+ K,
+ total_tokens,
+ torch_ms,
+ w4a16_ms,
+ w4a8_ms,
+ tflops,
+ gbps,
+ prepack_ms,
+ rows_per_expert=rows_per_expert,
+ bw_at_100t=bw_at_100t,
+ dram_gbps=dram_gbps,
+ )
+
+ # Drop the (large) int8 weights before the next shape allocates.
+ case = weights_s8 = wscales = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+ # Before any verdict is drawn from the ceilings -- including the one
+ # `_assert_targets` draws from the returned rows, which is why this is not
+ # gated on `verbose`.
+ _apply_bandwidth_evidence(rows)
+ if verbose:
+ _print_targets(phase, rows)
+ return rows
+
+
+def run_dedup_quant(batches=None, dtype=torch.bfloat16, models=None, verbose=True):
+ """End-to-end permute + GEMM for the up/gate projection, two ways.
+
+ The kernel quantizes its activations per row, and the row absmax is a
+ property of the *token*: ``a.abs().amax(dim=1)`` does not depend on which
+ expert the row was routed to. On the up/gate projection the ``T`` rows the
+ kernel is handed are ``top_k`` copies of ``batch`` distinct tokens, so the
+ in-call pass computes every scale ``top_k`` times and writes ``top_k``
+ copies of every int8 row -- 8x redundant at the shipped ``top_k = 8``.
+
+ Hoisting the same quantization above the permute removes that redundancy
+ and lets a caller reach the pre-quantized contract *without* an int8
+ producer upstream: the dynamic quantization still happens, just on
+ ``batch`` rows instead of ``batch * top_k``, and the permute then moves
+ int8 instead of 16-bit.
+
+ Every path is timed **including the caller's permute and its
+ quantization**, which is what makes this an honest comparison rather than
+ an accounting shift. The pre-quantized contract on its own only moves the
+ quantization across the call boundary; it is the deduplication -- and the
+ halved permute that comes with moving int8 instead of bf16 -- that makes
+ the work actually smaller. A caller who quantized the *permuted* rows
+ themselves would see the contract's gain cancel almost exactly.
+
+ **Which quantizer does the deduplicated work matters more than the
+ deduplication.** :func:`_quantize_rows` is the eager-torch reference: it
+ upcasts to fp32 and walks the tensor about seven times, once per operator,
+ materializing a full-size intermediate each time. The in-call path uses the
+ fused SYCL quantizer, which reads each row once and keeps the absmax in
+ registers. Comparing them directly charges the deduplicated path a constant
+ factor roughly fifteen times worse per row, which is more than enough to
+ eat an 8x reduction in rows -- so this reports all three points and lets
+ the columns say which effect is which:
+
+ * ``in-call quant`` -- what ships today: permute 16-bit, kernel quantizes
+ ``T`` rows with the fused quantizer.
+ * ``dedup, torch quant`` -- the deduplication done with the reference
+ quantizer. Not a shipping configuration; it is here because it is the
+ obvious way to try this and it *loses*, and that is worth recording.
+ * ``dedup, fused quant`` -- the deduplication with a quantizer of the same
+ quality as the one already in the kernel.
+
+ The fused quantizer's cost is measured rather than assumed, and since
+ ``moe_w4a8_quant_act`` exists it is measured *directly* -- the pass is
+ timed on its own instead of being inferred from the gap between the same
+ GEMM run with 16-bit and with int8 input. That matters here: the two agree
+ at 65536 rows but not at small row counts, where the difference is taken
+ between two timings whose own drift is the size of the answer, and it
+ reads high. The deduplicated path is costed at ``batch`` rows, so it was
+ exactly the case the old estimate got wrong. Both numbers are still
+ reported, together with the ``top_k`` linearity check that first exposed
+ the discrepancy.
+
+ Up/gate only. The down projection's ``T`` rows are the SiLU output, one
+ distinct row per routed row, so there is nothing to deduplicate; its route
+ to the same contract is folding the quantization into the SiLU epilogue
+ that already writes that tensor, which is what
+ ``test_perf_prefill_prequant_long_seq`` measures.
+ """
+ batches = _long_seq_batches() if batches is None else batches
+ resolved = _models(models)
+ if verbose:
+ print()
+ print("=" * _PERF_WIDTH)
+ print(
+ f"W4A8 end-to-end [prefill] (models={'+'.join(n for n, _ in resolved)}, up/gate only) "
+ f"-- caller permute + moe_gemm_w4a8, in-call quant vs deduplicated quant"
+ )
+ print(
+ f"{'shape':<14}{'E':>5}{'N':>7}{'K':>7}{'tokens':>8}{'batch':>8}{'topk':>6}"
+ f"{'path':>21}{'permute(ms)':>13}{'quant(ms)':>11}{'gemm(ms)':>11}{'total(ms)':>12}"
+ f"{'vs in-call':>12}"
+ )
+ print("-" * _PERF_WIDTH)
+ rows = []
+ shapes = [
+ (nk_label, N, K, spec, batch)
+ for _, spec in resolved
+ for nk_label, N, K in spec["nk"]
+ if not _reduces_topk(nk_label)
+ for batch in batches
+ ]
+ for nk_label, N, K, spec, batch in shapes:
+ E, topk, group_size = spec["E"], spec["topk"], spec["group_size"]
+ total_tokens = batch * topk
+ case = _build_case(
+ N, K, E, total_tokens, group_size, dtype, need_reference=False, need_dequant=False, topk=topk
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=group_size, rescale_group_size=-1
+ )
+ # The unpermuted hidden states a real layer holds, and the map the
+ # router produces. `index_select` wants a 64-bit index; converting it
+ # is one-off setup a caller does once per layer, not per call, so it
+ # stays outside both timed paths.
+ n_tokens = case["batch"]
+ # `clone`, not `contiguous`: a leading slice of a contiguous tensor is
+ # already contiguous, so `contiguous()` would hand back a view and keep
+ # the whole [T, K] allocation alive through it. This function holds
+ # several large tensors live at once -- both permuted forms are
+ # materialized so each stage can be timed on its own -- so the 268 MB
+ # the full activations occupy at this shape is worth actually
+ # releasing.
+ hidden = case["activations"][:n_tokens].clone()
+ index = case["row_to_token"].long()
+ ntpe_full = case["ntpe"]
+ case["activations"] = case["packed"] = case["scales"] = None
+ _release_xpu_memory()
+
+ # Routing histogram for a `batch`-row call: same weights, same experts,
+ # one row per distinct token. Only used to isolate the fused
+ # quantizer's cost at that row count.
+ ntpe_batch = torch.tensor(_spread_tokens(n_tokens, E), dtype=torch.int32, device=hidden.device)
+
+ def _call(act, ascale=None, ntpe=None):
+ kwargs = {"rescale_block_size": block, "phase": "prefill"}
+ if ascale is not None:
+ kwargs["activation_scale"] = ascale
+ kwargs["out_dtype"] = dtype
+ return ark.moe_gemm_w4a8(act, weights_s8, wscales, ntpe_full if ntpe is None else ntpe, **kwargs)
+
+ # Materialized once, outside every timed region: each stage is timed on
+ # its own so the reported columns are attributable, and the three
+ # stages form a true dependency chain (permute -> quantize -> GEMM),
+ # which is why summing separately-timed stages is a faithful model of
+ # running them back to back.
+ qact_batch, ascale_batch = _quantize_rows(hidden)
+ permuted_bf16 = hidden.index_select(0, index)
+ permuted_int8 = qact_batch.index_select(0, index)
+ permuted_scale = ascale_batch.index_select(0, index)
+
+ # Round-robin, min-filtered: the same guard against clock droop the
+ # other sweeps use, since these points are compared to each other
+ # rather than reported in isolation.
+ stages = {
+ k: []
+ for k in (
+ "perm_bf16",
+ "perm_int8",
+ "quant_torch",
+ "gemm_bf16_t",
+ "gemm_int8_t",
+ "gemm_bf16_b",
+ "gemm_int8_b",
+ )
+ }
+ iters = max(1, ITERS // SWEEP_ROUNDS)
+ for _ in range(SWEEP_ROUNDS):
+ stages["perm_bf16"].append(_xpu_time_ms(lambda: hidden.index_select(0, index), iters=iters))
+ stages["perm_int8"].append(
+ _xpu_time_ms(
+ lambda: (qact_batch.index_select(0, index), ascale_batch.index_select(0, index)), iters=iters
+ )
+ )
+ stages["quant_torch"].append(_xpu_time_ms(lambda: _quantize_rows(hidden), iters=iters))
+ stages["gemm_bf16_t"].append(_xpu_time_ms(lambda: _call(permuted_bf16), iters=iters))
+ stages["gemm_int8_t"].append(_xpu_time_ms(lambda: _call(permuted_int8, permuted_scale), iters=iters))
+ stages["gemm_bf16_b"].append(_xpu_time_ms(lambda: _call(hidden, ntpe=ntpe_batch), iters=iters))
+ stages["gemm_int8_b"].append(
+ _xpu_time_ms(lambda: _call(qact_batch, ascale_batch, ntpe=ntpe_batch), iters=iters)
+ )
+ t = {k: min(v) for k, v in stages.items()}
+
+ # Difference the same GEMM with 16-bit and int8 input: identical shape,
+ # identical weights, identical output -- the only work that differs is
+ # the in-kernel quantization of exactly those rows. This is the older,
+ # softer estimate, kept only as a cross-check.
+ diff_fused_t = max(t["gemm_bf16_t"] - t["gemm_int8_t"], 0.0)
+ diff_fused_b = max(t["gemm_bf16_b"] - t["gemm_int8_b"], 0.0)
+
+ # Measured on B70, the difference is only trustworthy when the pass is
+ # a large share of the call. At 65536 rows differencing and the direct
+ # measurement agree to 0-7%; at 1024 rows, where the call is weight-
+ # bound and the pass is 2-4% of it, differencing reads 4-7x high --
+ # it is subtracting two ~1 ms timings whose own drift is the size of
+ # the answer. `batch` rows sits between the two, so the deduplicated
+ # path is costed with the direct measurement where it is available and
+ # only falls back to the difference on a build without the entry point.
+ if not _QUANT_ACT_SKIP:
+ # The output tensors must stay referenced for as long as the
+ # callable is used: it captures their raw `data_ptr()`, so dropping
+ # them here would leave the timed call writing into freed memory.
+ quant_t = _quant_act_caller(permuted_bf16)
+ quant_fused_t = _xpu_time_ms(quant_t[0])
+ quant_t = None
+ _release_xpu_memory()
+ quant_b = _quant_act_caller(hidden)
+ quant_fused_b = _xpu_time_ms(quant_b[0])
+ quant_b = None
+ _release_xpu_memory()
+ quant_measured = True
+ else:
+ quant_fused_t, quant_fused_b = diff_fused_t, diff_fused_b
+ quant_measured = False
+ # Should be ~top_k: the quantizer is a pure streaming pass, so its cost
+ # is linear in rows. This is the check that first caught the estimate
+ # being wrong -- differencing put it at 6.0x for an 8x row count, which
+ # was read as the short row count being under-fed when it was really
+ # the smaller difference being inflated.
+ fused_ratio = (quant_fused_t / quant_fused_b) if quant_fused_b > 0 else None
+ diff_ratio = (diff_fused_t / diff_fused_b) if diff_fused_b > 0 else None
+
+ perm_bf16_ms, perm_int8_ms = t["perm_bf16"], t["perm_int8"]
+ gemm_ms = t["gemm_int8_t"]
+ today_ms = perm_bf16_ms + t["gemm_bf16_t"]
+ dedup_torch_ms = perm_int8_ms + t["quant_torch"] + gemm_ms
+ dedup_fused_ms = perm_int8_ms + quant_fused_b + gemm_ms
+
+ # The deduplicated path must not change the result: the row absmax is
+ # expert-independent, so quantizing before the permute and permuting
+ # the int8 is the same arithmetic on the same row values.
+ snr_db = _snr_db(_call(permuted_bf16).to(torch.float32), _call(permuted_int8, permuted_scale).to(torch.float32))
+
+ rows.append(
+ {
+ "label": nk_label,
+ "E": E,
+ "N": N,
+ "K": K,
+ "tokens": total_tokens,
+ "batch": n_tokens,
+ "topk": topk,
+ "today_ms": today_ms,
+ "dedup_ms": dedup_fused_ms,
+ "dedup_torch_ms": dedup_torch_ms,
+ "permute_bf16_ms": perm_bf16_ms,
+ "permute_int8_ms": perm_int8_ms,
+ "gemm_int8_ms": gemm_ms,
+ "quant_torch_ms": t["quant_torch"],
+ "quant_fused_batch_ms": quant_fused_b,
+ "quant_fused_tokens_ms": quant_fused_t,
+ "quant_measured": quant_measured,
+ "diff_fused_batch_ms": diff_fused_b,
+ "diff_fused_tokens_ms": diff_fused_t,
+ "fused_ratio": fused_ratio,
+ "diff_ratio": diff_ratio,
+ "speedup": (today_ms / dedup_fused_ms) if dedup_fused_ms else None,
+ "speedup_torch": (today_ms / dedup_torch_ms) if dedup_torch_ms else None,
+ "snr_db": snr_db,
+ }
+ )
+ if verbose:
+ for path, perm_ms, quant_ms, total_ms in (
+ ("in-call quant", perm_bf16_ms, quant_fused_t, today_ms),
+ ("dedup, torch quant", perm_int8_ms, t["quant_torch"], dedup_torch_ms),
+ ("dedup, fused quant", perm_int8_ms, quant_fused_b, dedup_fused_ms),
+ ):
+ speedup = None if total_ms == today_ms else (today_ms / total_ms if total_ms else None)
+ print(
+ f"{nk_label:<14}{E:>5}{N:>7}{K:>7}{total_tokens:>8}{n_tokens:>8}{topk:>6}"
+ f"{path:>21}{perm_ms:>13.3f}{quant_ms:>11.3f}{gemm_ms:>11.3f}{total_ms:>12.3f}"
+ f"{(f'{speedup:.2f}x' if speedup else '--'):>12}"
+ )
+
+ case = weights_s8 = wscales = hidden = None
+ qact_batch = ascale_batch = permuted_bf16 = permuted_int8 = permuted_scale = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ if verbose and rows:
+ print()
+ print("deduplicated dynamic quantization [prefill] (up/gate only; the down projection has no duplicate rows):")
+ for row in rows:
+ ratio = row["fused_ratio"]
+ print(
+ f" {row['label']:<12} {row['today_ms']:.3f} ms -> {row['dedup_ms']:.3f} ms "
+ f"{row['speedup']:.2f}x end-to-end (quantizes {row['batch']} rows instead of "
+ f"{row['tokens']}, permutes int8 instead of {str(dtype).split('.')[-1]}) "
+ f"SNR {row['snr_db']:.1f} dB"
+ )
+ print(
+ f" {'':<12} with the eager-torch quantizer instead: {row['dedup_torch_ms']:.3f} ms "
+ f"({row['speedup_torch']:.2f}x) -- {row['quant_torch_ms']:.3f} ms to quantize "
+ f"{row['batch']} rows, vs {row['quant_fused_batch_ms']:.3f} ms fused"
+ )
+ print(
+ f" {'':<12} fused quant {'measured directly' if row['quant_measured'] else 'by differencing'}: "
+ f"{row['quant_fused_tokens_ms']:.3f} ms at {row['tokens']} rows / "
+ f"{row['quant_fused_batch_ms']:.3f} ms at {row['batch']} rows = "
+ f"{(f'{ratio:.1f}x' if ratio else 'n/a')} for {row['topk']}x the rows"
+ f"{'' if ratio and 0.5 * row['topk'] <= ratio <= 2.0 * row['topk'] else ' <- NOT linear, treat as noise'}"
+ )
+ if row["quant_measured"]:
+ diff_ratio = row["diff_ratio"]
+ print(
+ f" {'':<12} the old differenced estimate, for comparison: "
+ f"{row['diff_fused_tokens_ms']:.3f} ms / {row['diff_fused_batch_ms']:.3f} ms = "
+ f"{(f'{diff_ratio:.1f}x' if diff_ratio else 'n/a')}"
+ )
+ else:
+ # Say why, rather than quietly reporting the softer number: the
+ # fallback previously fired on every run because the guard
+ # tested the skip reason against `None` when it is `""`, and a
+ # plausible-looking differenced figure is exactly the kind of
+ # thing that hides such a bug.
+ print(
+ f" {'':<12} (differenced because the direct measurement is unavailable: "
+ f"{_QUANT_ACT_SKIP or 'unknown'})"
+ )
+ return rows
+
+
+# ---------------------------------------------------------------------------
+# The activation quantization pass, measured on its own
+#
+# Until `moe_w4a8_quant_act` existed the pass had no standalone entry point, so
+# its cost was only ever *inferred*: time the same GEMM with 16-bit input and
+# with int8 input and subtract. That is two whole-call timings differenced into
+# a number a quarter their size, carrying the run-to-run noise of both -- and
+# every claim about the quantizer rests on it (its share of the call, the
+# bandwidth it achieves, the ceiling a faster one could reach). This sweep
+# measures the pass directly and prints the differenced estimate next to it, so
+# the soft number can finally be checked against a hard one.
+# ---------------------------------------------------------------------------
+
+# Token rows per work-group. 1 is the shape that shipped -- `local{1, SG_SIZE}`,
+# one sub-group and therefore one *hardware thread* per work-group, which is
+# the worst dispatch shape on an Intel GPU: the thread dispatcher's per-Xe-core
+# work-group limit binds long before its thread slots fill. 16 rows is 256
+# work-items, the work-group size every GEMM in the same header already uses.
+_ACT_QUANT_WG_ROWS = (1, 2, 4, 8, 16)
+
+# A row count deliberately *not* a multiple of the largest rung, so the
+# quantizer's `token >= total_tokens` guard is live in the identity test
+# instead of being dead code. Every shipped routing gives a round number of
+# rows, so nothing else in this file would ever reach the padding path.
+_ACT_QUANT_RAGGED_TOKENS = _PREFILL_BATCHES[0] * _QWEN3_TOPK + 5
+
+
+def _quant_act_caller(activations):
+ """A zero-allocation callable that runs one activation-quantization pass.
+
+ Goes through the extension entry point rather than
+ :func:`ark.moe_w4a8_quant_act` on purpose: the Python wrapper allocates its
+ two output tensors per call, and this measurement exists to put a hard
+ number on the *kernel*, not on the caching allocator. Hoisting the
+ allocation is the only difference; the arguments are the ones the wrapper
+ would have passed.
+
+ Returns ``(call, qact, ascale)`` -- the outputs are handed back so the
+ caller can compare them across configurations.
+ """
+ total_tokens, K = activations.shape
+ qact = torch.empty((total_tokens, K), device=activations.device, dtype=torch.int8)
+ ascale = torch.empty((total_tokens,), device=activations.device, dtype=torch.float32)
+ args = (
+ ark.get_stream(activations),
+ activations.data_ptr(),
+ qact.data_ptr(),
+ ascale.data_ptr(),
+ ark.cvt_dtype(activations.dtype),
+ total_tokens,
+ K,
+ )
+ lib = ark.get_lib(activations)
+ return (lambda: lib.moe_w4a8_quant_act(*args)), qact, ascale
+
+
+def _act_quant_bytes(total_tokens, K, act_bytes) -> float:
+ """Bytes the quantization pass has to move, at best.
+
+ Read ``[T, K]`` activations, write ``[T, K]`` int8, write ``[T]`` fp32
+ scales. The second pass re-reads a row the first pass just touched and is
+ served by cache, so it is not counted -- which makes this a *lower* bound
+ on traffic and therefore an *upper* bound on the achieved bandwidth.
+ """
+ return float(total_tokens) * K * act_bytes + float(total_tokens) * K + float(total_tokens) * 4.0
+
+
+def run_act_quant(batches=None, dtype=torch.bfloat16, models=None, verbose=True, wg_rows=None):
+ """Time the activation quantization pass alone, one row per work-group shape.
+
+ Three things come out of this that the whole-call sweeps cannot give:
+
+ * **The pass's real cost.** Directly measured, not differenced.
+ * **The bandwidth it achieves**, against the harness's own device-copy
+ probe. At 65536 rows and K = 2048 the pass moves 402.9 MB; if that lands
+ near the probe there is no room in the kernel and the only way to make
+ the pass cheaper is to give it fewer bytes (deduplicate the rows, or take
+ int8 from the caller), both of which are call-contract changes.
+ * **Whether the work-group shape matters.** ``ACT_QUANT_VEC`` (bytes per
+ lane), ``ACT_QUANT_UNROLL`` (loads in flight) and ``ACT_QUANT_SINGLE_PASS``
+ (row resident in registers) all tune what one thread does; none of them
+ changes how many threads are resident, and one thread per work-group is
+ the one shape nobody has swept.
+
+ Every row is required to be bit-identical to the first: the shape only
+ changes which thread handles which row, so a difference would be a bug, not
+ a trade-off.
+ """
+ batches = _PREFILL_BATCHES if batches is None else batches
+ rungs = _ACT_QUANT_WG_ROWS if wg_rows is None else tuple(wg_rows)
+ resolved = _models(models)
+ probe_gbps = _device_bandwidth_gbps()
+ if verbose:
+ print()
+ print("=" * _PERF_WIDTH)
+ print(
+ f"W4A8 activation quantization [prefill] (models={'+'.join(n for n, _ in resolved)}, "
+ f"act={str(dtype).split('.')[-1]}) -- the pass timed on its own, one row per work-group shape"
+ )
+ print(
+ f"{'shape':<14}{'E':>5}{'N':>7}{'K':>7}{'tokens':>8}{'rows/WG':>9}{'items/WG':>10}"
+ f"{'quant(ms)':>11}{'GB/s':>9}{'% of probe':>12}{'% of call':>11}{'vs 1 row':>10}{'bits':>10}"
+ )
+ print("-" * _PERF_WIDTH)
+ rows = []
+ shapes = [
+ (nk_label, N, K, spec, batch) for _, spec in resolved for nk_label, N, K in spec["nk"] for batch in batches
+ ]
+ for nk_label, N, K, spec, batch in shapes:
+ E, topk, group_size = spec["E"], spec["topk"], spec["group_size"]
+ total_tokens = batch * topk
+ case = _build_case(
+ N, K, E, total_tokens, group_size, dtype, need_reference=False, need_dequant=False, topk=topk
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=group_size, rescale_group_size=-1
+ )
+
+ # The call this pass is a part of, and the same call with the pass
+ # removed -- the pair the old estimate came from.
+ call_ms = _xpu_time_ms(lambda: _w4a8(case, weights_s8, wscales, block, "prefill"))
+ prequant_ms = _xpu_time_ms(lambda: _w4a8(case, weights_s8, wscales, block, "prefill", prequant=True))
+ differenced_ms = max(call_ms - prequant_ms, 0.0)
+
+ quant_bytes = _act_quant_bytes(total_tokens, K, _dtype_bytes(dtype))
+ call, qact, ascale = _quant_act_caller(case["activations"])
+ reference = None
+ first_row = len(rows)
+ for wg in rungs:
+ with _env_override(ARK_MOE_W4A8_ACT_QUANT_ROWS_PER_WG=str(wg)):
+ quant_ms = _xpu_time_ms(call)
+ call() # leave `qact`/`ascale` holding this configuration's output
+ torch.xpu.synchronize()
+ if reference is None:
+ reference = (qact.clone(), ascale.clone())
+ identical = True
+ else:
+ identical = torch.equal(qact, reference[0]) and torch.equal(ascale, reference[1])
+ gbps = quant_bytes / (quant_ms * 1e-3) / 1e9 if quant_ms > 0 else 0.0
+ rows.append(
+ {
+ "label": nk_label,
+ "E": E,
+ "N": N,
+ "K": K,
+ "tokens": total_tokens,
+ "batch": batch,
+ "rows_per_wg": wg,
+ "quant_ms": quant_ms,
+ "quant_bytes": quant_bytes,
+ "gbps": gbps,
+ "device_bw_gbps": probe_gbps,
+ "call_ms": call_ms,
+ "prequant_ms": prequant_ms,
+ "differenced_ms": differenced_ms,
+ "share_of_call": (quant_ms / call_ms) if call_ms > 0 else None,
+ "identical": identical,
+ }
+ )
+ # `vs 1 row` is relative to this shape's first rung, so it can only be
+ # filled in once that rung has been timed.
+ shape_rows = rows[first_row:]
+ baseline_ms = shape_rows[0]["quant_ms"]
+ for row in shape_rows:
+ row["vs_first"] = (baseline_ms / row["quant_ms"]) if row["quant_ms"] > 0 else None
+ if verbose:
+ share = row["share_of_call"]
+ probe_pct = (100.0 * row["gbps"] / probe_gbps) if probe_gbps else None
+ probe_txt = f"{probe_pct:.0f}%" if probe_pct else "--"
+ share_txt = f"{100.0 * share:.1f}%" if share else "--"
+ vs_txt = f"{row['vs_first']:.2f}x" if row["vs_first"] else "--"
+ bits_txt = "same" if row["identical"] else "DIFFER"
+ print(
+ f"{row['label']:<14}{E:>5}{N:>7}{K:>7}{total_tokens:>8}{row['rows_per_wg']:>9}"
+ f"{row['rows_per_wg'] * 16:>10}{row['quant_ms']:>11.3f}{row['gbps']:>9.0f}"
+ f"{probe_txt:>12}{share_txt:>11}{vs_txt:>10}{bits_txt:>10}"
+ )
+
+ call = qact = ascale = reference = None
+ case = weights_s8 = wscales = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ if verbose and rows:
+ print()
+ print("the pass, measured against the estimate every earlier conclusion used:")
+ for row in rows:
+ # One line per shape: the first rung is the shipped launch shape.
+ if row["rows_per_wg"] != rungs[0]:
+ continue
+ direct, differenced = row["quant_ms"], row["differenced_ms"]
+ gap = (abs(direct - differenced) / direct * 100.0) if direct > 0 else None
+ share = row["share_of_call"]
+ share_txt = f", {100.0 * share:.1f}% of the {row['call_ms']:.3f} ms call" if share else ""
+ gap_txt = f" -- {gap:.0f}% apart" if gap is not None else ""
+ verdict = " <- the estimate was off" if gap is not None and gap > 25.0 else ""
+ print(
+ f" {row['label'].strip():<12} {row['tokens']:>6} rows: measured {direct:.3f} ms "
+ f"({row['quant_bytes'] / 1e6:.1f} MB at {row['gbps']:.0f} GB/s{share_txt})"
+ )
+ print(
+ f" {'':<12} {'':>6} differencing the same call against int8-in says "
+ f"{differenced:.3f} ms{gap_txt}{verdict}"
+ )
+ return rows
+
+
+# ---------------------------------------------------------------------------
+# Kernel-configuration sweeps
+#
+# Both perf targets depend on a dispatch choice that can only be settled on
+# hardware (how many bytes a decode lane keeps in flight; how wide a prefill
+# tile should be). Every choice is reachable through an environment variable
+# and re-read per call, so one run can time them all against the same
+# workload -- built and prepacked once -- and name the winner.
+#
+# Each configuration is also checked against the first one for numerical
+# equivalence, so a configuration that is fast because it computes the wrong
+# thing cannot win.
+# ---------------------------------------------------------------------------
+
+# Decode: (label, env overrides). ``None`` unsets a variable.
+_DECODE_CONFIGS = [
+ ("legacy gemv", {"ARK_MOE_W4A8_DECODE_KSPLIT": "0"}),
+] + [
+ (
+ f"ksplit ch{ch} ncols{ncols}",
+ {
+ "ARK_MOE_W4A8_DECODE_KSPLIT": "1",
+ "ARK_MOE_W4A8_DECODE_KSPLIT_CH": str(ch),
+ "ARK_MOE_W4A8_DECODE_KSPLIT_NCOLS": str(ncols),
+ },
+ )
+ for ch in (16, 32)
+ for ncols in (1, 2, 4)
+]
+
+# Prefill: work-group tile shapes. ``auto`` is the built-in ladder.
+_PREFILL_TILES = ["auto", "128x128", "128x256", "256x128", "256x256"]
+_PREFILL_TILE_CONFIGS = [
+ (f"tile {tile}", {"ARK_MOE_W4A8_PREFILL_TILE": None if tile == "auto" else tile}) for tile in _PREFILL_TILES
+]
+
+# Prefill: activation-quantization message width. The vectorized kernel hands
+# each lane ``VEC`` *consecutive* elements, turning the scalar mapping's 32-byte
+# loads / 16-byte stores into 256-byte / 128-byte ones. At prefill sizes this
+# pass streams ~200 MB next to the GEMM's ~400 MB, so it is a real share of the
+# call, not a preamble.
+_ACT_QUANT_CONFIGS = [
+ ("act-quant scalar", {"ARK_MOE_W4A8_ACT_QUANT_VEC": "0"}),
+ ("act-quant vec", {"ARK_MOE_W4A8_ACT_QUANT_VEC": "1"}),
+]
+
+# Prefill: activation-quantization loads in flight. Widening the messages set
+# how many bytes each *request* moves; this sets how many requests a work-item
+# has outstanding. ``UNROLL`` vectors are loaded before any is consumed, and
+# reduced into ``UNROLL`` partial maxima so they do not serialize behind the
+# accumulator either. ``1`` is the kernel as it was before the batching, so the
+# first row is an exact A/B baseline.
+_ACT_QUANT_UNROLL_CONFIGS = [
+ (
+ f"act-quant unroll {u}",
+ {"ARK_MOE_W4A8_ACT_QUANT_VEC": "1", "ARK_MOE_W4A8_ACT_QUANT_UNROLL": str(u)},
+ )
+ for u in (1, 2, 4)
+]
+
+# Prefill: activation-quantization passes over the row. The two-pass kernel
+# reads ``[T, K]`` twice -- once for the absmax, once to quantize -- because the
+# scale is not known until the row has been seen. The single-pass kernel keeps
+# the row in registers between the two, which removes the second read at the
+# cost of ``K / 16`` elements of register pressure per lane. Whether that trade
+# pays depends on whether it spills, which only hardware can say; rows longer
+# than the register budget take the two-pass kernel either way.
+_ACT_QUANT_SINGLE_PASS_CONFIGS = [
+ (
+ "act-quant two-pass",
+ {"ARK_MOE_W4A8_ACT_QUANT_VEC": "1", "ARK_MOE_W4A8_ACT_QUANT_SINGLE_PASS": "0"},
+ ),
+ (
+ "act-quant single-pass",
+ {"ARK_MOE_W4A8_ACT_QUANT_VEC": "1", "ARK_MOE_W4A8_ACT_QUANT_SINGLE_PASS": "1"},
+ ),
+]
+
+# Prefill: epilogue guard. A tile that touches neither the M nor the N edge
+# needs no store predicate and no scale-index clamp, and whether it does is
+# uniform across the work-group. The guarded path is what every tile used to
+# run; it stays reachable so the saving can be measured (it is largest where
+# the mainloop is shortest, i.e. small K).
+_EPILOGUE_CONFIGS = [
+ ("epilogue guarded", {"ARK_MOE_W4A8_PREFILL_FULL_TILE": "0"}),
+ ("epilogue interior", {"ARK_MOE_W4A8_PREFILL_FULL_TILE": "1"}),
+]
+
+# Prefill: how D leaves the registers. The DPAS C fragment gives a lane one
+# column of each 8x16 atom, so a scalar store is a 32-byte message for 16-bit D
+# and a 32x32 sub-group fragment issues 64 of them; the hardware 2D block store
+# moves the same bytes in a handful of messages and needs no predicate, because
+# it clips to the output surface. D is a third of the tile traffic on the
+# down-projection shapes, so this is where the store width should show.
+_PREFILL_STORE_CONFIGS = [
+ ("store scalar", {"ARK_MOE_W4A8_PREFILL_STORE_2D": "0"}),
+ ("store block2d", {"ARK_MOE_W4A8_PREFILL_STORE_2D": "1"}),
+]
+
+# Prefill: how many k-tiles the mainloop keeps prefetched ahead of the tile it
+# is computing. The prologue issues this many A/B prefetch pairs before the
+# first DPAS and the loop then issues one pair per tile, so it is the depth of
+# the memory pipeline the DPAS chain runs against. 3 is what the kernel was
+# written with; the shipped shapes are short in K (12 k-tiles at K = 768, where
+# a prologue of 3 is a quarter of the whole mainloop), which is exactly the
+# regime where the depth is worth re-measuring in both directions.
+#
+# The sweep spans the whole range the kernel accepts (1-8) rather than a window
+# around the default. The narrower `2 / 3 / 4 / 6` it used to probe cannot
+# distinguish "3 is the optimum" from "3 is the best of the four points that
+# were tried": both endpoints are legal values the clamp in
+# `moe_w4a8_prefill_prefetch_dist` admits, and on a 12-k-tile mainloop they are
+# the two hypotheses that matter -- 1 is the shortest prologue the kernel can
+# have, 8 is deep enough to cover two thirds of that mainloop before the first
+# DPAS. A K-aware default can only be justified by a sweep that includes them.
+_PREFILL_PREFETCH_CONFIGS = [
+ (f"prefetch {dist}", {"ARK_MOE_W4A8_PREFILL_PREFETCH": str(dist)}) for dist in (1, 2, 3, 4, 6, 8)
+]
+
+# Prefill: when the persistent kernel asks for its next tile.
+#
+# The grid is sized to the device, not to the problem -- `sm_count` times the
+# work-groups that fit on an Xe core -- and the tiles are handed out by a
+# device-scope `atomicAdd` on a single dword that every resident work-group
+# hits. Claiming *after* the GEMM puts that L2 round trip in the gap between
+# two tiles, where the work-group has nothing to overlap it with; claiming
+# before puts the message in flight across the DPAS mainloop and only the use
+# of its result waits.
+#
+# The size of that stall is bounded by how much work a tile has to hide it
+# behind, so this should show on the down projections and not much on the up
+# ones: at K = 768 a tile is 12 k-tiles against 32 at K = 2048, and the down
+# projection is where the measured TFLOPS sits furthest below the up
+# projection's on the same tile shape and the same kernel. If the two rows tie
+# on every shape, the claim was never the stall and this sweep says so.
+_PREFILL_CLAIM_CONFIGS = [
+ ("claim after gemm", {"ARK_MOE_W4A8_PREFILL_CLAIM_EARLY": "0"}),
+ ("claim before gemm", {"ARK_MOE_W4A8_PREFILL_CLAIM_EARLY": "1"}),
+]
+
+# Prefill: the register budget, and therefore how many work-groups are resident.
+#
+# `grf_size` used to be hardwired at 256 in the launcher, which pinned every
+# tile in the ladder at 4 hardware threads per vector engine -- 512 work-items
+# per Xe-core, which is exactly the `MaxThreadsPerSM` the persistent grid is
+# sized from. Asking for 128 registers instead doubles both. The small tiles are
+# in the ladder *because* they ask for fewer registers, so every one of them has
+# been swept so far paying that cost without ever collecting the occupancy that
+# is their reason to exist.
+#
+# The flag alone would sweep nothing: the ladder sends every shipped qwen3 shape
+# to `128x256`, whose 32x64 sub-group accumulator is 128 int32 registers -- the
+# entire small-GRF file, nothing left for the staged A/B tiles -- so that policy
+# declines the halved budget and both settings launch the identical kernel. The
+# tile therefore has to be forced for the knob to be observable at all, and the
+# first two rows do exactly that: same 128x128 tile, same everything else, one
+# register budget each. That pair is the measurement.
+#
+# The third row is the shipped default, for reference.
+#
+# Measured on B70, and the answer is unambiguous: the halved budget loses.
+#
+# tile 128x128, forced grf 256 grf 128
+# qwen3 up @ 49152 tokens 2.399 ms 3.745 ms 1.56x slower
+# qwen3 up @ 65536 tokens 2.866 ms 4.579 ms 1.60x slower
+# qwen3 down @ 49152 tokens 1.794 ms 2.147 ms 1.20x slower
+# qwen3 down @ 65536 tokens 2.352 ms 2.723 ms 1.16x slower
+#
+# The occupancy did double. The tile stopped fitting: a 128-wide-N accumulator
+# is 64 int32 per lane, half a 128-register file before anything is staged, and
+# the other half does not hold the mainloop's live set. The penalty scales with
+# K -- 1.56-1.60x at K=2048 against 1.16-1.20x at K=768 -- so it is per mainloop
+# trip, not per tile, which puts the spill on the staged A/B fragments that are
+# live across every iteration. Drift on the spilling rows rose from the usual
+# 0.5-1.7% to 4.2-15.3%, as scratch traffic makes the runtime depend on memory
+# state.
+#
+# So the small tiles were never being short-changed: at 128 registers they stop
+# being fast, which is why the ladder was swept at the large budget to begin
+# with. The flag defaults to off and this sweep stays as the regression guard.
+# It also closes the last latency knob -- prefetch depth, tile order, claim
+# order and now occupancy have all come back flat or worse, exactly as the cost
+# model predicted, because ~78% of qwen3 down's per-tile cost is the 64 KB of D
+# it writes and bytes are not something residency can hide.
+_PREFILL_GRF_CONFIGS = [
+ ("128x128, grf 256", {"ARK_MOE_W4A8_PREFILL_TILE": "128x128", "ARK_MOE_W4A8_PREFILL_SMALL_GRF": "0"}),
+ ("128x128, grf 128", {"ARK_MOE_W4A8_PREFILL_TILE": "128x128", "ARK_MOE_W4A8_PREFILL_SMALL_GRF": "1"}),
+ ("128x256 (default)", {"ARK_MOE_W4A8_PREFILL_TILE": "128x256"}),
+]
+
+# Prefill: the two call contracts that cut traffic instead of cycles.
+#
+# Neither changes the GEMM. They change what crosses the call boundary, which
+# is where the remaining traffic is: on the qwen3 down-projection at 384
+# rows/expert the call moves 528 MB, of which only 36% is weights -- 27% is the
+# activation quantization round-trip (read fp16, write int8, read the int8
+# back) and 36% is a `[T, N]` output that the caller immediately reduces to
+# `[batch, N]`. Both are redundancies of the *interface*: the producer of the
+# activations already writes `[T, K]` once and could write int8, and the
+# reduction the caller performs can be done in the epilogue while the values
+# are still in registers.
+#
+# The fused row is not bit-identical to the others -- fp32 atomics do not
+# commit in a fixed order, and the unfused baseline additionally rounds each
+# row to the activation dtype before the caller's reduction sees it -- so this
+# is the one sweep whose SNR column is a quality gate rather than an identity
+# check.
+_PREFILL_CONTRACT_CONFIGS = [
+ ("A quant in-call", {}, {}),
+ ("A int8 in", {}, {"prequant": True}),
+ ("fused reduce", {}, {"fused": True}),
+ ("A int8 + fused", {}, {"prequant": True, "fused": True}),
+]
+
+_SWEEP_MIN_SNR_DB = 40.0
+
+
+def _sweep_timings(configs, call, extra=None):
+ """Time every configuration, round-robin, and return the per-round samples.
+
+ Timing each configuration to completion in turn -- warmup and all its
+ iterations, then on to the next -- silently ranks by position as much as
+ by configuration. These shapes draw enough power to droop the clock over
+ a sweep, so every configuration measured later is handicapped by the
+ heat the earlier ones produced. On the qwen3 up-proj shape that artefact
+ is worth 6-7% run to run, which is *larger* than the spread the sweep is
+ being used to rank: two runs of the prefill prefetch sweep an hour apart
+ put the optimum at depth 3-4 and then at depth 1-2, with the ordering
+ essentially reversed and the last-measured configuration slowest in both.
+
+ Round-robin instead, so the drift is spread evenly across configurations
+ rather than accumulating against the later ones. The caller takes the
+ minimum across rounds (each configuration at its least-throttled) and
+ keeps the spread as the noise floor a ranking has to clear.
+
+ ``call`` is invoked as ``call(call_kwargs)`` with the configuration's env
+ overrides in force. ``extra`` is an optional zero-argument callable timed
+ once per round alongside them, for work that is charged to some
+ configurations but is not itself one. Returns
+ ``(per_config_samples, extra_samples)``, the former positionally aligned
+ with ``configs``.
+ """
+ samples = [[] for _ in configs]
+ extra_samples = []
+ iters = max(1, ITERS // SWEEP_ROUNDS)
+ for _ in range(SWEEP_ROUNDS):
+ for idx, (_, overrides, call_kwargs) in enumerate(configs):
+ with _env_override(**overrides):
+ samples[idx].append(_xpu_time_ms(lambda: call(call_kwargs), iters=iters))
+ if extra is not None:
+ # Timed inside the round-robin, not after it: a measurement taken
+ # once at the end of the sweep lands at the sweep's hottest point
+ # and would be biased high against the configurations it is added
+ # to, which is the artefact the round-robin exists to remove.
+ extra_samples.append(_xpu_time_ms(extra, iters=iters))
+ return samples, extra_samples
+
+
+def _print_sweep_header(title: str, metric: str, with_reduce: bool = False) -> None:
+ print()
+ print("=" * _PERF_WIDTH)
+ print(title)
+ extra = f"{'+reduce':>10}" if with_reduce else ""
+ print(
+ f"{'shape':<14}{'E':>5}{'N':>7}{'K':>7}{'tokens':>8}{'rows/E':>8} "
+ f"{'config':<22}{'ms':>10}{extra}{metric:>10}{'vs default':>12}{'SNR(dB)':>10}{'drift':>9}"
+ )
+ print("-" * _PERF_WIDTH)
+
+
+def run_config_sweep(phase, configs, dtype=torch.bfloat16, models=None, verbose=True, compute_bound=None, batches=None):
+ """Time every kernel configuration in ``configs`` on the same workload.
+
+ ``phase`` picks the sweep's shapes and its metric: ``decode`` reports
+ weight bandwidth (the decode target), ``prefill`` reports TFLOPS (the
+ prefill target) at the compute-bound batch. ``batches`` runs the sweep at
+ an explicit list of model-token batches instead -- what the long-prompt
+ sweeps use, since a fixed prompt length is exactly what the compute-bound
+ derivation replaces. Returns one dict per (shape, batch, configuration).
+
+ A configuration is ``(label, env_overrides)`` or, for the sweeps that
+ compare *call contracts* rather than dispatch knobs,
+ ``(label, env_overrides, call_kwargs)`` -- the extra dict is forwarded to
+ :func:`_w4a8`. A contract that reduces inside the kernel returns a
+ ``[batch, N]`` tensor where the others return ``[T, N]``, so outputs are
+ put in the same frame (:func:`_reduce_topk`) before they are compared.
+
+ When some configuration fuses the top-k reduction, timing the others as a
+ bare GEMM would rank them against a baseline that skips work: the fused row
+ pays for the reduction inside its epilogue while the unfused rows leave a
+ ``[T, N]`` tensor their caller still has to reduce. Every row therefore also
+ carries the caller-side reduction it would owe (``+reduce``, zero for the
+ fused rows), and ``vs default`` ranks on the sum -- the cost of *producing
+ the routed output*, which is the thing the contract actually changes.
+
+ That sum brackets the win rather than pinning it. The reduction is timed as
+ :func:`_reduce_topk`, a torch ``index_add_`` that materializes fp32
+ temporaries, so it is an upper bound on a hand-written one; the GEMM-only
+ ``ms`` column is the lower bound. The truth is between the two columns,
+ which is why both are printed.
+ """
+ is_prefill = phase == "prefill"
+ # An explicit batch list opts out of the compute-bound derivation, which
+ # ignores ``batches`` and sizes the batch from the target rows/expert.
+ if compute_bound is None:
+ compute_bound = is_prefill and batches is None
+ metric_name = "TFLOPS" if is_prefill else "W GB/s"
+ device_bw = _device_bandwidth_gbps()
+ resolved = _models(models)
+ configs = [(cfg[0], cfg[1], cfg[2] if len(cfg) > 2 else {}) for cfg in configs]
+ # Only build the routing side tables when some configuration asks for them.
+ need_routing = any(kwargs.get("fused") for _, _, kwargs in configs)
+ if verbose:
+ _print_sweep_header(
+ f"W4A8 config sweep [{phase}] (models={'+'.join(n for n, _ in resolved)}, "
+ f"act={str(dtype).split('.')[-1]}) -- same workload, one row per kernel configuration",
+ metric_name,
+ with_reduce=need_routing,
+ )
+ if batches is None:
+ batches = _DECODE_BATCHES
+ rows = []
+ for _, spec in resolved:
+ E, topk, group_size = spec["E"], spec["topk"], spec["group_size"]
+ for nk_label, N, K in spec["nk"]:
+ for batch in _compute_bound_batches(spec) if compute_bound else batches:
+ total_tokens = batch * topk
+ case = _build_case(
+ N,
+ K,
+ E,
+ total_tokens,
+ group_size,
+ dtype,
+ need_reference=False,
+ need_dequant=False,
+ topk=topk if need_routing else None,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=group_size, rescale_group_size=-1
+ )
+ active_experts = sum(1 for n_e in case["tpe"] if n_e > 0)
+ rows_per_expert = _rows_per_expert(total_tokens, active_experts)
+
+ # Correctness first, one configuration at a time, so that only
+ # the baseline output and the one being compared to it are
+ # alive: a six-configuration sweep that held every output at
+ # once would need six [T, N] tensors (1.2 GB on the qwen3
+ # up-proj shape).
+ baseline_out = None
+ snrs = []
+ for label, overrides, call_kwargs in configs:
+ with _env_override(**overrides):
+ out = _w4a8(case, weights_s8, wscales, block, phase, **call_kwargs)
+ if need_routing and not call_kwargs.get("fused"):
+ out = _reduce_topk(case, out)
+ if baseline_out is None:
+ # Cloned: the kernel may hand back a reused scratch
+ # buffer, which would make every later comparison
+ # compare a tensor with itself.
+ baseline_out = out.clone()
+ snrs.append(float("inf"))
+ else:
+ snrs.append(_snr_db(baseline_out.to(torch.float32), out.to(torch.float32)))
+ out = None
+ baseline_out = None
+
+ # What an unfused caller still owes after the GEMM returns --
+ # but only on the projection whose output is actually reduced.
+ # Timed inside the round-robin so it is min-filtered on the
+ # same basis as the configurations it is charged to.
+ charge_reduce = need_routing and _reduces_topk(nk_label)
+ unreduced = _w4a8(case, weights_s8, wscales, block, phase) if charge_reduce else None
+ samples, reduce_samples = _sweep_timings(
+ configs,
+ lambda kw: _w4a8(case, weights_s8, wscales, block, phase, **kw),
+ extra=(lambda: _reduce_topk(case, unreduced)) if charge_reduce else None,
+ )
+ reduce_ms = min(reduce_samples) if reduce_samples else 0.0
+ unreduced = None
+ _release_xpu_memory()
+
+ baseline_ms = None
+ for idx, (label, overrides, call_kwargs) in enumerate(configs):
+ # The least-throttled round, and the spread across rounds
+ # as the noise floor this shape's ranking has to clear.
+ ms = min(samples[idx])
+ noise = (max(samples[idx]) - ms) / ms if ms else 0.0
+ snr = snrs[idx]
+ # The fused epilogue has already done the reduction; every
+ # other configuration leaves it for the caller.
+ row_reduce_ms = 0.0 if call_kwargs.get("fused") else reduce_ms
+ total_ms = ms + row_reduce_ms
+ if baseline_ms is None:
+ baseline_ms = total_ms
+ tflops = _flops(total_tokens, N, K) / (ms * 1e-3) / 1e12
+ gbps = _weight_bytes(active_experts, N, K, 8) / (ms * 1e-3) / 1e9
+ row = {
+ "label": nk_label,
+ "phase": phase,
+ "config": label,
+ "overrides": overrides,
+ "call_kwargs": call_kwargs,
+ "E": E,
+ "N": N,
+ "K": K,
+ "tokens": total_tokens,
+ "rows_per_expert": rows_per_expert,
+ "w4a8_ms": ms,
+ "reduce_ms": row_reduce_ms,
+ "total_ms": total_ms,
+ "noise": noise,
+ "tflops": tflops,
+ "gbps": gbps,
+ "snr_db": snr,
+ "speedup": baseline_ms / total_ms if total_ms else None,
+ "device_bw_gbps": device_bw,
+ }
+ rows.append(row)
+ if verbose:
+ metric = tflops if is_prefill else gbps
+ snr_txt = "--" if math.isinf(snr) else f"{snr:.1f}"
+ speedup_txt = "--" if row["speedup"] is None else f"{row['speedup']:.2f}x"
+ reduce_txt = f"{row_reduce_ms:>10.3f}" if need_routing else ""
+ print(
+ f"{nk_label:<14}{E:>5}{N:>7}{K:>7}{total_tokens:>8}{rows_per_expert:>8.1f} "
+ f"{label:<22}{ms:>10.3f}{reduce_txt}{metric:>10.2f}{speedup_txt:>12}{snr_txt:>10}"
+ f"{noise * 100:>8.1f}%"
+ )
+ out = None
+ case = weights_s8 = wscales = baseline_out = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+ if verbose:
+ _print_sweep_best(phase, rows)
+ return rows
+
+
+def _ranked_ms(row):
+ """The time a configuration is ranked on: GEMM plus any reduction it left.
+
+ Equal to ``w4a8_ms`` for every sweep that has no fused-reduce
+ configuration, so the dispatch-knob sweeps rank exactly as before.
+ """
+ return row.get("total_ms", row["w4a8_ms"])
+
+
+def _ranked_noise(row):
+ """``row``'s round-to-round drift as a fraction of the time it is ranked on.
+
+ The drift is measured on the GEMM call, so charging a configuration an
+ unmeasured constant on top of it dilutes the same absolute jitter.
+ """
+ ranked = _ranked_ms(row)
+ if not ranked:
+ return row.get("noise", 0.0)
+ return row.get("noise", 0.0) * row["w4a8_ms"] / ranked
+
+
+def _print_sweep_best(phase, rows) -> None:
+ """Report, per shape, the fastest numerically-equivalent configuration.
+
+ A shape swept at more than one batch gets one line per batch: the winner
+ is a property of the routing as much as of the shape (the tile ladder
+ changes rung with ``rows/expert``), so the two must not be pooled.
+ """
+ if not rows:
+ return
+ is_prefill = phase == "prefill"
+ print()
+ print(f"best configuration [{phase}] (equivalent within {_SWEEP_MIN_SNR_DB:g} dB SNR of the first configuration):")
+ shapes = []
+ for row in rows:
+ if row["label"] not in shapes:
+ shapes.append(row["label"])
+ for shape in shapes:
+ shape_rows = [r for r in rows if r["label"] == shape]
+ batches = []
+ for row in shape_rows:
+ if row["tokens"] not in batches:
+ batches.append(row["tokens"])
+ for tokens in batches:
+ group = [r for r in shape_rows if r["tokens"] == tokens]
+ name = shape if len(batches) == 1 else f"{shape.strip()} T={tokens}"
+ candidates = [r for r in group if r["snr_db"] >= _SWEEP_MIN_SNR_DB]
+ if not candidates:
+ print(f" {name:<14} no numerically-equivalent configuration")
+ continue
+ best = min(candidates, key=_ranked_ms)
+ # A winner is only a winner if its lead over the sweep's own
+ # first (= default) configuration is larger than the drift the
+ # sweep measured on itself. Below that the ranking is reporting
+ # which configuration happened to be timed on the coolest
+ # device, and recommending it bakes an artefact into a default.
+ # ``noise`` is a spread relative to the GEMM time, but the lead is
+ # a ratio of GEMM+reduce times. Adding the same reduction to both
+ # sides of that ratio shrinks it, so the gate has to be put on the
+ # same basis or a real win between two unfused configurations gets
+ # discarded as drift.
+ noise = max(_ranked_noise(r) for r in group)
+ lead = _ranked_ms(group[0]) / _ranked_ms(best) - 1.0 if _ranked_ms(best) else 0.0
+ if lead <= noise:
+ print(
+ f" {name:<14} inconclusive: best is {lead * 100:.1f}% ahead of the default, "
+ f"within the {noise * 100:.1f}% round-to-round drift -- keep the default"
+ )
+ continue
+ metric = f"{best['tflops']:.2f} TFLOPS" if is_prefill else f"{best['gbps']:.1f} GB/s"
+ parts = [f"{k}={v}" for k, v in sorted(best["overrides"].items()) if v is not None]
+ parts += [f"{k}={v}" for k, v in sorted(best.get("call_kwargs", {}).items()) if v]
+ env = " ".join(parts) or "(defaults)"
+ # The metric is derived from the GEMM time, so the GEMM time is what
+ # is printed beside it; the reduction is shown as a separate term so
+ # the ranked total stays recoverable without implying the metric was
+ # computed from it.
+ ms_txt = f"{best['w4a8_ms']:.3f} ms"
+ if best.get("reduce_ms"):
+ ms_txt += f" + {best['reduce_ms']:.3f} reduce"
+ print(f" {name:<14} {best['config']:<22} {ms_txt:<26} {metric:<16} {env}")
+
+
+# ---------------------------------------------------------------------------
+# pytest entry points
+# ---------------------------------------------------------------------------
+
+if pytest is not None:
+
+ @pytest.fixture(autouse=True)
+ def _xpu_cleanup_between_tests():
+ """Release cached weights and the XPU allocator cache around every test.
+
+ The prepacked int8 weights are ``E * N * K`` bytes (200+ MB for the
+ Qwen3 up-proj shape), so a test that aborts mid-sweep would otherwise
+ leave the allocator holding them and starve the next parametrization.
+ Global scratch remains allocated and grows on demand across tests.
+ """
+ _release_xpu_memory()
+ try:
+ yield
+ finally:
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ @pytest.mark.skipif(bool(_W4A8_SKIP), reason=_W4A8_SKIP or "W4A8 MoE kernel unavailable")
+ class TestMoEW4A8:
+ """W4A8 MoE: accuracy + performance for prefill and decode."""
+
+ @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
+ def test_scratch_reuse_across_shapes(self, dtype):
+ """Global scratch survives shape changes and weight-cache clears.
+
+ Alternate decode and prefill, grow both token count and K, then
+ return to smaller shapes without creating or releasing scratch.
+ Pre-quantized calls independently exercise the decode expert map.
+ """
+ shapes = (
+ ("decode", 3, 768),
+ ("prefill", 257, 768),
+ ("decode", 31, 2048),
+ ("prefill", 513, 2048),
+ ("decode", 3, 768),
+ )
+ for phase, tokens, K in shapes:
+ case = _build_case(
+ 128,
+ K,
+ 4,
+ tokens,
+ 32,
+ dtype,
+ need_dequant=False,
+ act_int8_grid=True,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(case["packed"], case["scales"], group_size=32)
+ internal = _w4a8(case, weights_s8, wscales, block, phase).clone()
+ external = _w4a8(case, weights_s8, wscales, block, phase, prequant=True).clone()
+ assert int(_ulp_diff(internal, external).max().item()) <= 1, (
+ f"{phase} T={tokens} K={K}: scratch reuse changed quantization: "
+ f"{_ulp_report(internal, external)}"
+ )
+ assert _snr_db(case["reference"], internal) >= _MIN_SNR_DB
+ assert _cosine(case["reference"], internal) >= _MIN_COSINE
+ case = weights_s8 = wscales = internal = external = None
+ ark.clear_moe_w4a8_prepack_cache()
+
+ @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
+ def test_accuracy_decode(self, request, dtype):
+ all_shapes = request.config.getoption("--all-shapes", default=False)
+ rows = run_accuracy("decode", _decode_batches(all_shapes), dtype=dtype)
+ _assert_accuracy(rows)
+
+ @pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float16])
+ def test_accuracy_prefill(self, request, dtype):
+ all_shapes = request.config.getoption("--all-shapes", default=False)
+ rows = run_accuracy("prefill", _prefill_batches(all_shapes), dtype=dtype)
+ _assert_accuracy(rows)
+
+ def test_accuracy_rescale_group_size(self, request):
+ """AUTO_S8 with an explicit sub-K block must stay at least as accurate.
+
+ A smaller re-scale block tracks the per-group int4 scales more
+ closely, so it can only reduce the weight re-quantization error --
+ at the cost of an accumulator fold per block in the mainloop.
+ """
+ all_shapes = request.config.getoption("--all-shapes", default=False)
+ batches = _prefill_batches(all_shapes)[:1]
+ coarse = run_accuracy("prefill", batches, rescale_group_size=-1)
+ fine = run_accuracy("prefill", batches, rescale_group_size=256)
+ _assert_accuracy(coarse)
+ _assert_accuracy(fine)
+ for c, f in zip(coarse, fine):
+ assert f["block"] <= c["block"]
+
+ def test_cache_rekeys_on_resolved_block_override(self):
+ """Changing ``ARK_MOE_W4A8_AUTO_S8`` must not reuse a stale prepack.
+
+ The convenience wrapper caches the int8 conversion, but the effective
+ block comes from the environment as well as the argument. Reusing a
+ cache entry across two override values would silently ignore the
+ second setting and feed GEMM scales laid out for the first one.
+ """
+ case = _build_case(16, 256, 1, 1, 128, torch.bfloat16, need_reference=False, need_dequant=False)
+ with _env_override(ARK_MOE_W4A8_AUTO_S8="128"):
+ ark.moe_w4a8(case["activations"], case["packed"], case["ntpe"], scales=case["scales"])
+ with _env_override(ARK_MOE_W4A8_AUTO_S8="256"):
+ ark.moe_w4a8(case["activations"], case["packed"], case["ntpe"], scales=case["scales"])
+ blocks = sorted(entry[2] for entry in ark._MOE_W4A8_PREPACK_CACHE.values())
+ assert blocks == [128, 256], f"expected separate cache entries per resolved block, got {blocks}"
+
+ def test_clear_prepack_cache_waits_for_inflight_work(self):
+ """Clearing the cache must not release weights still in use by queued work."""
+ case = _build_case(16, 256, 1, 8, 128, torch.bfloat16, need_reference=False, need_dequant=False)
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(case["packed"], case["scales"], group_size=128)
+ expected = ark.moe_gemm_w4a8(
+ case["activations"],
+ weights_s8,
+ wscales,
+ case["ntpe"],
+ rescale_block_size=block,
+ phase="prefill",
+ ).clone()
+ actual = ark.moe_w4a8(
+ case["activations"], case["packed"], case["ntpe"], scales=case["scales"], phase="prefill"
+ )
+ ark.clear_moe_w4a8_prepack_cache()
+ assert torch.equal(actual, expected), "clearing the prepack cache changed an in-flight W4A8 result"
+
+ def test_gemm_rejects_aux_tensor_device_mismatch(self):
+ """Every auxiliary tensor passed to the XPU kernel must share the XPU device."""
+ case = _build_case(16, 256, 1, 2, 128, torch.bfloat16, need_reference=False, need_dequant=False, topk=1)
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(case["packed"], case["scales"], group_size=128)
+ with pytest.raises(ValueError, match="num_tokens_per_expert"):
+ ark.moe_gemm_w4a8(
+ case["activations"],
+ weights_s8,
+ wscales,
+ case["ntpe"].cpu(),
+ rescale_block_size=block,
+ phase="prefill",
+ )
+ with pytest.raises(ValueError, match="routing_weights"):
+ ark.moe_gemm_w4a8(
+ case["activations"],
+ weights_s8,
+ wscales,
+ case["ntpe"],
+ rescale_block_size=block,
+ phase="prefill",
+ row_to_token=case["row_to_token"],
+ routing_weights=case["routing_weights"].cpu(),
+ output_rows=case["batch"],
+ )
+
+ def test_rejects_oversized_k(self):
+ """Reject shapes whose int32 accumulator would overflow before dispatch."""
+ K = ((ark._MOE_W4A8_MAX_ACCUM_K // 64) + 1) * 64
+ group_size = 128
+ packed = torch.empty((1, 16, K // 2), device="xpu", dtype=torch.uint8)
+ scales = torch.empty((1, 16, K // group_size), device="xpu", dtype=torch.bfloat16)
+ activations = torch.empty((1, K), device="xpu", dtype=torch.bfloat16)
+ weights_s8 = torch.empty((1, 16, K), device="xpu", dtype=torch.int8)
+ wscales = torch.empty((1, 16, 1), device="xpu", dtype=torch.float32)
+ ntpe = torch.ones(1, device="xpu", dtype=torch.int32)
+ with pytest.raises(ValueError, match="accumulator overflow"):
+ ark.moe_w4a8_prepack(packed, scales, group_size=group_size)
+ with pytest.raises(ValueError, match="accumulator overflow"):
+ ark.moe_gemm_w4a8(activations, weights_s8, wscales, ntpe, rescale_block_size=K, phase="prefill")
+
+ def test_perf_decode(self, request):
+ all_shapes = request.config.getoption("--all-shapes", default=False)
+ rows = run_perf("decode", _decode_batches(all_shapes), models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "decode", rows)
+
+ def test_perf_prefill(self, request):
+ all_shapes = request.config.getoption("--all-shapes", default=False)
+ rows = run_perf("prefill", _prefill_batches(all_shapes), models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "prefill", rows)
+
+ def test_perf_prefill_compute_bound(self, request):
+ """Prefill throughput at a batch where the TFLOPS target is reachable.
+
+ ``test_perf_prefill`` runs 128 model tokens, i.e. 8 rows per
+ expert: at that routing the grouped GEMM only does 16 FLOPs per
+ weight byte, so it is pinned to the DRAM roofline and no amount of
+ kernel work can push it to 100 TFLOPS. This case routes enough
+ tokens to put ``_PREFILL_TARGET_ROWS_PER_EXPERT`` rows on every
+ expert, which is the smallest routing where 100 TFLOPS is under the
+ device's bandwidth ceiling for *all* the shipped shapes -- counting
+ the activation, quantized-activation and output streams, not just
+ the weights.
+ """
+ rows = run_perf("prefill", None, torch_baseline=False, compute_bound=True, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "prefill", rows)
+
+ def test_perf_prefill_long_seq(self, request):
+ """Prefill throughput for one 8K-token prompt.
+
+ ``test_perf_prefill_compute_bound`` derives its batch per model so
+ that both land on the same 384 rows per expert. A prompt does not
+ work that way: a fixed 8192 model tokens (65536 routed rows) is
+ divided by whatever expert count the model has, which puts 512 rows
+ on each of Qwen3-MoE's 128 experts and 341 on each of MiniMax's
+ 192.
+
+ Both directions are worth measuring. More rows per expert raise the
+ arithmetic intensity -- the weights are the only stream that does
+ not grow with the token count -- so the qwen3 ceilings rise from
+ 129 / 112 to 145 / 123 TFLOPS at a 400 GB/s probe, which is the
+ regime where the 100 TFLOPS target has the most margin. Fewer rows
+ lower it, so minimax comes down from 137 / 154 to 129 / 145 and the
+ same kernel should read *slower* there: the point of running both
+ is that the prompt length alone does not decide the throughput, the
+ routing it produces does.
+ """
+ rows = run_perf(
+ "prefill",
+ _long_seq_batches(),
+ torch_baseline=False,
+ models=_models_option(request),
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "prefill", rows)
+
+ def test_perf_decode_config_sweep(self, request):
+ """Time every decode lane mapping on one workload and name the best.
+
+ The decode target is weight bandwidth, and how close the GEMV gets
+ to the device's streaming rate is decided by how many bytes a lane
+ keeps in flight (``CH``) and how many output columns a sub-group
+ blocks over (``NCOLS``). Both are dispatch-time environment knobs,
+ so a single run can measure the whole grid -- including the legacy
+ mapping -- against the same prepacked weights.
+ """
+ rows = run_config_sweep("decode", _DECODE_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"decode config {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_tile_sweep(self, request):
+ """Time every prefill work-group tile at the compute-bound batch.
+
+ A ``TileM x TileN`` tile re-reads A once per N tile and B once per M
+ tile, so the tile shape sets the GEMM's tile-load traffic
+ (``~ M*N*K * (1/TileM + 1/TileN)``) and therefore whether a
+ compute-bound shape is actually limited by compute. This sweep
+ measures the ladder's choice against every explicit tile.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_TILE_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"prefill tile {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_tile_sweep_long_seq(self, request):
+ """Time every prefill work-group tile at the 8K-prompt routing.
+
+ The tile sweep above runs at the derived compute-bound batch, where
+ every model sits at 384 rows per expert -- a routing at which the
+ 256-row tile can only lose, because it would schedule 512 rows for
+ 384 rows of data. A fixed 8K prompt is the routing that changes
+ that: Qwen3-MoE's 128 experts get 512 rows each, an exact multiple
+ of 256, so both candidate ``TileM`` values schedule the same rows
+ and the sweep measures the tile rather than its padding. It is the
+ only case in the suite that can, which is what makes it the
+ evidence for (or, as it turned out, against) a 256-row rung.
+ """
+ rows = run_config_sweep(
+ "prefill",
+ _PREFILL_TILE_CONFIGS,
+ models=_models_option(request),
+ batches=_long_seq_batches(),
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"prefill tile {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_act_quant_sweep(self, request):
+ """Time both activation-quantization mappings at the compute-bound batch.
+
+ Quantizing the routed activations is a pure streaming pass -- read
+ ``[T, K]`` twice, write ``[T, K]`` int8 -- so its cost is set by how
+ wide a message the sub-group issues, not by arithmetic. The scalar
+ mapping (``k = lane; k += SG_SIZE``) stores 16 bytes per message, a
+ quarter of a cache line; the vectorized one gives each lane
+ ``VEC`` consecutive elements instead. Both are dispatch-time
+ choices, so one run measures the pair against the same workload.
+ """
+ rows = run_config_sweep("prefill", _ACT_QUANT_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"act-quant config {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_act_quant_unroll_sweep(self, request):
+ """Time the activation quantizer's loads-in-flight depth.
+
+ Widening the messages (the sweep above) set how many bytes each
+ request moves; it did not change how many requests a work-item has
+ outstanding. The pass walks K with a runtime trip count and folds
+ every vector into one ``local_max``, so an in-order thread keeps
+ about one 256-byte load in flight -- ~320 KB even at a B60's
+ 1280-thread occupancy ceiling, under what a 456 GB/s part needs to
+ stay busy over a memory latency. ``UNROLL`` loads that many
+ independent vectors
+ before consuming any of them. The first row is the kernel as it was
+ before the batching, so this is an exact A/B measurement; the
+ arithmetic is unchanged, which
+ ``test_act_quant_unroll_matches`` asserts bit-for-bit.
+ """
+ rows = run_config_sweep("prefill", _ACT_QUANT_UNROLL_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"act-quant unroll {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_act_quant_single_pass_sweep(self, request):
+ """Time the quantizer against its own second read of the row.
+
+ The absmax has to see the whole row before the first element can
+ be quantized, so the two-pass kernel reads ``[T, K]``, reduces,
+ then reads ``[T, K]`` again. The single-pass kernel keeps the row
+ in registers across the reduction and deletes the second read --
+ ~0.8 MB per expert at 384 rows and K = 2048, against 3.1 MB of
+ weights for the whole GEMM. It costs ``K / 16`` elements of
+ register pressure per lane (64 dwords of the default 128-dword
+ budget at K = 2048), which is exactly the risk this sweep exists to
+ settle: if it spills, the single-pass row is *slower*, and the
+ default should be flipped. Rows too long for the budget take the
+ two-pass kernel in both rows of the sweep, so those shapes should
+ read as noise.
+ """
+ rows = run_config_sweep("prefill", _ACT_QUANT_SINGLE_PASS_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert row["snr_db"] >= _SWEEP_MIN_SNR_DB, (
+ f"act-quant pass count {row['config']} disagrees with {rows[0]['config']}: "
+ f"SNR {row['snr_db']:.2f} dB"
+ )
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_perf_act_quant_wg_sweep(self, request):
+ """Measure the quantization pass directly, and sweep its work-group shape.
+
+ Two things at once, because they need the same setup.
+
+ **The measurement.** Every earlier conclusion about this pass came
+ from differencing a 16-bit-input call against a pre-quantized one:
+ two whole-call timings subtracted into a number a quarter their
+ size. ``moe_w4a8_quant_act`` makes the pass callable on its own, so
+ the table prints the measured cost, the bandwidth it implies
+ against the harness's own copy probe, and the differenced estimate
+ beside it. If the two disagree, the estimate was the problem.
+
+ **The sweep.** The pass ships as ``local{1, SG_SIZE}`` -- one
+ sub-group, i.e. one hardware thread, per work-group. That is the
+ worst dispatch shape on an Intel GPU: the thread dispatcher caps
+ resident work-groups per Xe-core well below the thread slots that
+ Xe-core has, so the work-group limit binds first and the slots go
+ unfilled. Every other kernel in the same header launches 256
+ work-items. ``VEC``, ``UNROLL`` and ``SINGLE_PASS`` all tune what
+ one thread does; this is the only knob that changes how many
+ threads are resident.
+
+ Expect little at long prefill -- the pass already streams close to
+ the probe there, and a kernel on the roof has nothing to give. The
+ room, if any, is at the short batch, which reads well under it.
+
+ The shape only decides which thread handles which row, so every
+ rung must be bit-identical, not merely close.
+ """
+ rows = run_act_quant(models=_models_option(request))
+ assert rows and all(r["quant_ms"] > 0 for r in rows)
+ for row in rows:
+ assert row["identical"], (
+ f"{row['label'].strip()}: {row['rows_per_wg']} rows/work-group changed the quantized "
+ f"activations -- the work-group shape must only move work between threads"
+ )
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_perf_act_quant_wg_sweep_long_seq(self, request):
+ """Sweep the quantizer's work-group shape at the 8K-prompt routing.
+
+ The point where the pass is most expensive in absolute terms and
+ least likely to be helped: at 65536 routed rows it is already
+ streaming enough to sit against the device copy probe, so its cost
+ is the byte count, not the dispatch. That makes this the row that
+ decides whether the whole line of attack is dead -- and it is the
+ batch whose 28% quantization share every ceiling calculation for
+ the up projection was built on.
+ """
+ rows = run_act_quant(batches=_long_seq_batches(), models=_models_option(request))
+ assert rows and all(r["quant_ms"] > 0 for r in rows)
+ for row in rows:
+ assert row["identical"], (
+ f"{row['label'].strip()}: {row['rows_per_wg']} rows/work-group changed the quantized "
+ f"activations at the long-sequence routing"
+ )
+
+ def test_perf_prefill_store_sweep(self, request):
+ """Time the D store width at the compute-bound batch.
+
+ The mainloop is identical in both rows. The DPAS C fragment hands a
+ lane one column of each 8x16 atom, so the 16 lanes of a sub-group
+ hold 16 consecutive columns of one row: a scalar store is a
+ 32-byte message for 16-bit D, and a 32x32 sub-group fragment issues
+ 64 of them. The 2D block store moves the same bytes in a handful of
+ messages and needs no predicate, because it clips to the output
+ surface in hardware.
+
+ Expect the largest gain where D is the largest share of tile
+ traffic and the mainloop the shortest -- the small-K
+ down-projections, which are also the shapes furthest from the
+ compute target.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_STORE_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"store config {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_epilogue_sweep(self, request):
+ """Time the epilogue guard at the compute-bound batch.
+
+ The mainloop is identical in both rows; only the store differs. A
+ tile that lies entirely inside the expert's rows and inside N can
+ skip the per-element store predicate and the two scale-index
+ clamps, and the answer is uniform across the work-group, so the
+ branch costs one comparison per tile rather than per element. The
+ saving is a fixed number of instructions per output element, so it
+ shows up as a larger fraction where the mainloop is shortest --
+ the small-K down-projections -- and should never be negative.
+ """
+ rows = run_config_sweep("prefill", _EPILOGUE_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"epilogue config {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_prefetch_sweep(self, request):
+ """Time the mainloop's prefetch depth at the compute-bound batch.
+
+ The mainloop is otherwise identical in every row: only how far
+ ahead of the computing tile the A/B block prefetches run changes.
+ The shipped shapes are short in K -- the qwen3 down-projection has
+ 12 k-tiles at a 64-element k-tile -- so the default depth of 3 is a
+ quarter of the whole mainloop, which is the regime where both
+ directions are plausible: deeper hides more latency but spends more
+ of the tile in a prologue that computes nothing, and the prefetched
+ lines have to survive in L2 until the tile that wants them runs.
+
+ Nothing about the arithmetic changes, so every row must be
+ bit-identical to the first; only the timing is a measurement.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_PREFETCH_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"prefetch depth {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_prefetch_sweep_long_seq(self, request):
+ """Time the mainloop's prefetch depth at the 8K-prompt routing.
+
+ Same sweep as above at the other prefill point, and the one that
+ has to decide whether the depth should depend on K. The compute-
+ bound batch derives its token count per model so every shape lands
+ on 384 rows per expert; a fixed 8K prompt does not, so the qwen3
+ shapes get 512 rows per expert and the minimax ones 341. That is
+ the routing the shipped-contract numbers were taken at, and the one
+ where the qwen3 down-projection reads 74% of its DRAM ceiling while
+ the other three sit at 91-100% -- i.e. the only shape in the suite
+ with headroom a scheduling change could still take.
+
+ K is what separates it: at a 64-element k-tile its mainloop is 12
+ iterations against 32 for qwen3 up and 48 for minimax up, so a
+ prologue of 3 is a quarter of the loop there and a sixteenth here.
+ Whether that costs anything is not decidable from the shape alone
+ -- a shorter prologue starts computing sooner but runs against a
+ shallower memory pipeline -- so `moe_w4a8_prefill_prefetch_dist`
+ deliberately stays a single constant until this sweep separates the
+ two shapes. Making it K-aware on the strength of the k-tile count
+ alone would be picking one of those two effects by assertion.
+
+ Nothing about the arithmetic changes, so every row must be
+ bit-identical to the first; only the timing is a measurement.
+ """
+ rows = run_config_sweep(
+ "prefill",
+ _PREFILL_PREFETCH_CONFIGS,
+ models=_models_option(request),
+ batches=_long_seq_batches(),
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"prefetch depth {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_claim_early_sweep(self, request):
+ """Time when the persistent kernel claims its next tile.
+
+ The grid is sized to the device, so a work-group does not own one
+ tile -- it loops, taking the next index from a device-scope
+ ``atomicAdd`` on a single dword that every resident work-group
+ hits. Claimed after the GEMM, that L2 round trip lands in the gap
+ between two tiles with nothing to overlap it; claimed before, the
+ message is in flight across the whole DPAS mainloop and only the
+ store of its result waits on it.
+
+ Which tiles are computed does not change -- one claim per tile,
+ same indices, same order -- so every row must be bit-identical to
+ the first and only the timing is a measurement.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_CLAIM_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"claim order {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_claim_early_sweep_long_seq(self, request):
+ """Time the tile-claim order at the 8K-prompt routing.
+
+ Same sweep at the other prefill point, and the one that should
+ decide it. How much a claim stall costs depends on how much work
+ the tile it precedes has to hide it behind, so the effect is
+ bounded by the mainloop length: 12 k-tiles on the qwen3 down
+ projection against 32 on qwen3 up, at the same tile shape and the
+ same kernel. That is also the shape the shipped-contract numbers
+ leave furthest below its own bandwidth ceiling, so it is where a
+ per-tile fixed cost should be visible at all.
+
+ A tie on every shape is a real result: it says the claim was not
+ the stall, and the down projection's gap is the prologue, the
+ epilogue or the D write instead.
+ """
+ rows = run_config_sweep(
+ "prefill",
+ _PREFILL_CLAIM_CONFIGS,
+ models=_models_option(request),
+ batches=_long_seq_batches(),
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"claim order {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_grf_sweep(self, request):
+ """Time the register budget, which is really a test of occupancy.
+
+ The kernel is persistent and its grid is sized to fill the device
+ exactly once, so the number of work-groups launched *is* the
+ residency. That number comes from a threads-per-Xe-core constant
+ that only holds at ``grf_size<256>``; halving the register request
+ doubles it, and the two have to move together or nothing changes.
+
+ The first two rows are the measurement -- one tile, two budgets --
+ and the third is the shipped default for reference. Measured on
+ B70 the halved budget loses by 1.56x here and 1.20x on the down
+ projection: the occupancy doubles and the tile stops fitting, since
+ a 128-wide-N accumulator is already half of a 128-register file.
+ The row to watch is therefore not a hoped-for win but the size of
+ the spill, which is why this stays as a regression guard.
+
+ Every row computes the same tiles from the same inputs, so all
+ three must be bit-identical and only the timing is a measurement.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_GRF_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"GRF budget {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_grf_sweep_long_seq(self, request):
+ """Time the register budget at the 8K-prompt routing.
+
+ The other prefill point, and the one where the occupancy argument
+ is weakest for the small tile: 512 rows/expert divides evenly by
+ both 128 and 256, so the padding penalty that decides the ladder
+ elsewhere is absent here and the tiles compete on their merits.
+
+ Measured on B70 the halved budget loses by 1.60x on the up
+ projection and 1.16x on the down. Both ratios are larger at
+ K=2048 than at K=768, so the cost scales with mainloop trips
+ rather than with tile count -- the spill is inside the mainloop,
+ on the staged A/B fragments. That closes the last of the latency
+ knobs, after prefetch depth, tile order and claim order all came
+ back flat, and leaves the D write as the only remaining prefill
+ lever.
+ """
+ rows = run_config_sweep(
+ "prefill",
+ _PREFILL_GRF_CONFIGS,
+ models=_models_option(request),
+ batches=_long_seq_batches(),
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"GRF budget {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_contract_sweep(self, request):
+ """Time the two traffic-cutting call contracts at the compute-bound batch.
+
+ This is the sweep that decides whether the qwen3 shapes can reach
+ the 100 TFLOPS target at all. Every kernel configuration above
+ moves the same bytes and competes for the same ~60-75% of the
+ device's bandwidth; the target on the down-projection needs 358
+ GB/s of a ~390 GB/s part, which no scheduling change reaches. The
+ contracts are the only levers that change the numerator: handing
+ the kernel int8 activations removes 27% of the call's traffic and
+ reducing in the epilogue removes another 27%.
+
+ Both rows are also a correctness check on the harness's own model:
+ the ``TFLOPS`` column here is directly comparable to
+ ``test_perf_prefill_compute_bound`` because the workload, the
+ weights and the routing are the same objects.
+ """
+ rows = run_config_sweep("prefill", _PREFILL_CONTRACT_CONFIGS, models=_models_option(request))
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ for row in rows:
+ assert (
+ row["snr_db"] >= _SWEEP_MIN_SNR_DB
+ ), f"call contract {row['config']} disagrees with {rows[0]['config']}: SNR {row['snr_db']:.2f} dB"
+
+ def test_perf_prefill_dedup_quant_long_seq(self, request):
+ """End-to-end win from deduplicating the dynamic quantization.
+
+ The answer for a caller whose upstream operator has no int8 to
+ hand over. The quantization still has to happen -- it just does not
+ have to happen ``top_k`` times per token. See :func:`run_dedup_quant`
+ for why the row absmax makes that safe, and why both paths are
+ timed with the caller's permute included.
+
+ Asserts the two paths agree: the deduplicated path is the same
+ arithmetic on the same row values, so the only permitted difference
+ is the few-ulp fp32 division noise :func:`_quantize_rows` documents.
+ """
+ rows = run_dedup_quant(models=_models_option(request))
+ assert rows and all(r["today_ms"] > 0 and r["dedup_ms"] > 0 for r in rows)
+ for row in rows:
+ assert row["snr_db"] >= _SWEEP_MIN_SNR_DB, (
+ f"deduplicated quantization changed {row['label']}: "
+ f"SNR {row['snr_db']:.2f} dB below {_SWEEP_MIN_SNR_DB}"
+ )
+ # The fused quantizer's cost is obtained by differencing two
+ # GEMM timings, so it is only meaningful if the difference is
+ # signal. A pure streaming pass must scale with rows: if
+ # quantizing top_k times as many rows does not cost roughly
+ # top_k times as much, the differences are measurement noise
+ # and every number derived from them is meaningless.
+ ratio, topk = row["fused_ratio"], row["topk"]
+ assert ratio is not None and 0.5 * topk <= ratio <= 2.0 * topk, (
+ f"fused activation quantization does not scale with rows on {row['label']}: "
+ f"{row['quant_fused_tokens_ms']:.3f} ms at {row['tokens']} rows vs "
+ f"{row['quant_fused_batch_ms']:.3f} ms at {row['batch']} rows "
+ f"({'n/a' if ratio is None else f'{ratio:.2f}x'} for {topk}x the rows) -- "
+ f"the GEMM difference is noise, not the quantizer"
+ )
+
+ def test_perf_prefill_prequant_long_seq(self, request):
+ """Prefill throughput for one 8K prompt with the int8-in contract alone.
+
+ The two contracts were only ever measured together, and together
+ they regress on B70 (see the README): the fused epilogue's cost
+ swamps whatever the activation round-trip saves, so that run says
+ nothing about the round-trip itself. This isolates it.
+
+ It is also the contract a serving stack can actually adopt without
+ touching its layer code -- the previous op already produced int8 in
+ most quantized pipelines -- whereas the fused reduction requires the
+ caller to hand over the routing map and give up a bit-identical
+ result. Removing the round-trip drops ``3 * T * K`` bytes, a third
+ of the up projection's traffic, and the traffic model here is told
+ about it so the printed ceiling matches what the call moves.
+ """
+ rows = run_perf(
+ "prefill",
+ _long_seq_batches(),
+ torch_baseline=False,
+ models=_models_option(request),
+ prequantized=True,
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "prefill", rows)
+
+ def test_perf_prefill_contracts_long_seq(self, request):
+ """Prefill throughput for one 8K prompt with both contracts enabled.
+
+ ``test_perf_prefill_long_seq`` measures the shipped contract, where
+ the qwen3 shapes are bandwidth-bound below the target. This runs
+ the same prompt with the activation round-trip removed, and the
+ output reduction folded into the epilogue on the one projection
+ that is actually reduced; the ceiling printed next to it is
+ computed from the same reduced traffic model, so the verdict is
+ against the right roof.
+
+ On B70 this is *slower* than the shipped contract even though it
+ moves fewer bytes -- the fused epilogue trades a coalesced 2D block
+ store for one device-scope atomic per output element. Compare
+ against ``test_perf_prefill_prequant_long_seq`` to separate the two
+ contracts' contributions.
+ """
+ rows = run_perf(
+ "prefill",
+ _long_seq_batches(),
+ torch_baseline=False,
+ models=_models_option(request),
+ prequantized=True,
+ fused_reduce=True,
+ )
+ assert rows and all(r["w4a8_ms"] > 0 for r in rows)
+ _assert_targets(request, "prefill", rows)
+
+ def test_prequantized_activations_match_internal(self):
+ """Handing the kernel int8 activations must reproduce the in-call quantization.
+
+ The pre-quantized entry point does not change any arithmetic: it
+ removes the pass that computes the int8 copy and takes the caller's
+ instead. Everything downstream -- the policy, the tiling, the
+ accumulation order, the epilogue -- is selected from the same
+ arguments on both contracts, so the only thing that can differ is
+ the int8 bytes and the row scales.
+
+ :func:`_quantize_rows` is that pass expression for expression, but
+ it runs its two divisions in exact fp32 while the device is allowed
+ a few ulp on them, so on ordinary activations a product that sits
+ on a rounding tie can round the other way. That is not a rounding
+ difference in the *output*: a flipped int8 is a different input to
+ every dot product it takes part in, and one that lands next to a
+ cancelling accumulator moves the result by any number of steps. No
+ useful bound survives it, so the case is built on the quantizer's
+ own grid instead (:func:`_int8_grid_activations`), where every
+ product is an integer half a step from the nearest tie and both
+ quantizers must emit the same bytes.
+
+ What is left is the row scale. ``absmax / 127`` is a power of two
+ on this grid, so the exact result is representable and the device's
+ division can miss it by at most an ulp -- and it enters the
+ epilogue as a *factor*, so it perturbs every output by the same
+ relative amount rather than by an absolute one, which is at most
+ one step of the output format wherever the output lies. Hence the
+ bound below, which is not a fitted tolerance but the smallest
+ difference the format can express.
+
+ It still fails loudly for the bugs this is here to catch -- a
+ transposed scale, an off-by-one row, the scale read as its
+ reciprocal -- because none of those are worth one step, and the
+ per-row exponent makes a scale taken from the wrong row a factor of
+ two rather than a coincidence.
+
+ Both K are covered because the internal quantizer picks its lane
+ mapping from K, and only one of the two rungs would be exercised by
+ a single shape.
+ """
+ for nk_label, N, K in _QWEN3_NK:
+ case = _build_case(
+ N,
+ K,
+ _QWEN3_E,
+ _PREFILL_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ act_int8_grid=True,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ internal = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ external = _w4a8(case, weights_s8, wscales, block, "prefill", prequant=True).clone()
+ assert int(_ulp_diff(internal, external).max().item()) <= 1, (
+ f"{nk_label.strip()} (K={K}): pre-quantized activations disagree with the in-call "
+ f"quantizer by more than a rounding step: {_ulp_report(internal, external)}"
+ )
+ case = weights_s8 = wscales = internal = external = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ def test_prequantized_activations_match_internal_decode(self):
+ """The same, on the decode GEMV, where the expert map comes from elsewhere.
+
+ Decode needs a ``token -> expert`` map, and the shipped path gets
+ it for free: the activation-quant kernel already runs one sub-group
+ per token, so it fills the map on the way past. Pre-quantized
+ activations delete that kernel, so the map has to come from the
+ standalone scan instead -- a different code path producing a value
+ the GEMV indexes its weights with. If it were wrong every token
+ would read another expert's weights, which this test sees as a
+ gross mismatch rather than the one-step scale difference the two
+ paths are entitled to.
+ """
+ case = _build_case(
+ _QWEN3_NK[0][1],
+ _QWEN3_NK[0][2],
+ _QWEN3_E,
+ _DECODE_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ act_int8_grid=True,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ internal = _w4a8(case, weights_s8, wscales, block, "decode").clone()
+ external = _w4a8(case, weights_s8, wscales, block, "decode", prequant=True).clone()
+ assert int(_ulp_diff(internal, external).max().item()) <= 1, (
+ "pre-quantized activations disagree with the in-call quantizer on decode by more than a "
+ f"rounding step: {_ulp_report(internal, external)}"
+ )
+
+ def test_fused_reduce_matches_unfused(self):
+ """The fused epilogue must agree with reducing the unfused output.
+
+ Unlike every other prefill A/B in this file, this one is *not* a
+ bit-identity check and cannot be. The fused epilogue combines a
+ token's ``top_k`` contributions with device-scope fp32 atomics,
+ which commit in whatever order the work-groups finish, and fp32
+ addition is not associative; the unfused path additionally rounds
+ each row to the activation dtype before the caller's reduction ever
+ sees it. So the two differ by rounding on both sides, and the gate
+ is the accuracy gate the rest of the suite uses against the fp32
+ reference (20 dB / 0.99 cosine) -- generous enough to survive
+ reassociation, far too tight to survive a wrong token index, a
+ missing routing weight or an expert-offset slip, all of which
+ misplace whole rows.
+
+ The batch is the ragged one: 300 rows per expert against the
+ ladder's 128-row tile gives every expert two interior tiles and one
+ partial tile, so both the fast and the guarded scatter run, and the
+ partial tile is where a scatter can do damage a predicated store
+ cannot -- an out-of-range row would land on a *valid* token.
+ """
+ rows_per_expert = _RAGGED_TILE_ROWS_PER_EXPERT
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ rows_per_expert * _QWEN3_E,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ topk=_QWEN3_TOPK,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ unfused = _reduce_topk(case, _w4a8(case, weights_s8, wscales, block, "prefill"))
+ fused = _w4a8(case, weights_s8, wscales, block, "prefill", fused=True)
+ assert fused.shape == unfused.shape, f"fused output shape {tuple(fused.shape)} != {tuple(unfused.shape)}"
+ snr = _snr_db(unfused, fused)
+ cos = _cosine(unfused, fused)
+ assert snr >= _MIN_SNR_DB, f"the fused top-k reduction disagrees with the unfused one: SNR {snr:.2f} dB"
+ assert cos >= _MIN_COSINE, f"the fused top-k reduction disagrees with the unfused one: cosine {cos:.6f}"
+
+ def test_fused_reduce_rejects_decode(self):
+ """The fused reduction must refuse the decode phase rather than mis-reduce.
+
+ The scatter lives in the grouped GEMM's epilogue; the decode GEMV
+ has no such epilogue, so a decode call with routing tables would
+ silently return the unreduced output under a shape that claims to
+ be reduced. Both the Python guard and the kernel's own check exist
+ for this; the Python one is what a caller hits.
+ """
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ _DECODE_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ topk=_QWEN3_TOPK,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ with pytest.raises(ValueError):
+ _w4a8(case, weights_s8, wscales, block, "decode", fused=True)
+
+ def test_act_quant_vec_matches_scalar(self):
+ """The vectorized activation quantizer must be bit-identical to the scalar one.
+
+ Unlike the K-split decode rewrite, this one reorders nothing that
+ rounds: the per-lane partial reduction is ``fmax``, which is exact
+ and order-independent, so both mappings feed the sub-group reduce
+ the same absmax and therefore the same reciprocal. Every element is
+ then put through the same ``rint``/``clamp`` expression, and the
+ GEMM that consumes the int8 is deterministic. Only the lane -> K
+ assignment differs, so any difference at all is a bug (a wrong
+ vector index, a row-stride slip, or a missed tail).
+ """
+ case = _build_case(
+ _QWEN3_NK[0][1],
+ _QWEN3_NK[0][2],
+ _QWEN3_E,
+ _PREFILL_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_ACT_QUANT_VEC=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ "vectorized activation quantization disagrees with the scalar mapping: "
+ f"max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}"
+ )
+
+ def test_act_quant_unroll_matches(self):
+ """Batching the quantizer's loads must be bit-identical at every depth.
+
+ ``UNROLL`` only changes how many vectors are in flight before any
+ is consumed: the per-lane reduction is still ``fmax`` over the same
+ values (exact and order-independent, so the partial maxima merge to
+ the same bits as one chain), and every element goes through the
+ same ``rint``/``clamp``. ``UNROLL = 1`` is the kernel as it was
+ before the batching, so it is the reference here.
+
+ Both K are checked because the tail loop is what a wrong bound
+ would break: at ``VEC = 8`` a lane walks ``K / 128`` vectors, so
+ K = 2048 divides by the default depth of 4 and K = 768 leaves a
+ two-vector tail. A missed or double-counted tail changes the
+ absmax, and hence every element of the row.
+ """
+ for nk_label, N, K in _QWEN3_NK:
+ case = _build_case(
+ N,
+ K,
+ _QWEN3_E,
+ _PREFILL_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for unroll in ("1", "2", "4"):
+ with _env_override(ARK_MOE_W4A8_ACT_QUANT_VEC="1", ARK_MOE_W4A8_ACT_QUANT_UNROLL=unroll):
+ outs[unroll] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ for unroll in ("2", "4"):
+ assert torch.equal(outs["1"], outs[unroll]), (
+ f"{nk_label.strip()} (K={K}): activation quantization at unroll {unroll} disagrees with "
+ f"unroll 1: max |diff| "
+ f"{(outs['1'].float() - outs[unroll].float()).abs().max().item():.6g}"
+ )
+ case = weights_s8 = wscales = outs = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ def test_full_tile_epilogue_matches_predicated(self):
+ """Skipping the epilogue guard on interior tiles must change nothing.
+
+ The fast path drops only the store predicate and the two
+ scale-index clamps, all three of which are no-ops on a tile that
+ lies inside the expert's rows and inside N; the convert, the two
+ multiplies and their order are untouched, so the results must be
+ bit-identical, not merely close.
+
+ The shape matters: the batch puts 300 rows on every expert, which
+ the tile ladder resolves to a 128-row tile, so each expert has two
+ interior tiles *and* one ragged 44-row tile and a single launch
+ exercises both paths. A small-batch case would leave every tile
+ ragged and the test would pass without the fast path ever running.
+ """
+ rows_per_expert = _RAGGED_TILE_ROWS_PER_EXPERT
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ rows_per_expert * _QWEN3_E,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_PREFILL_FULL_TILE=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ "the interior-tile epilogue disagrees with the guarded one: "
+ f"max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}"
+ )
+
+ def test_act_quant_single_pass_matches(self):
+ """Holding the row in registers must be bit-identical to re-reading it.
+
+ The single-pass kernel changes *when* the row is read, not what is
+ computed from it: the per-lane reduction is still ``fmax`` over the
+ same values into the same four partial maxima (exact and
+ order-independent, so any grouping merges to the same bits), the
+ sub-group reduce and the reciprocal are untouched, and every
+ element goes through the same ``rint``/``clamp``. So the two-pass
+ kernel is an exact reference, not an approximate one.
+
+ Both K are checked because the register array is bounded at compile
+ time and the rung is chosen from ``K``: at ``VEC = 8`` a lane walks
+ ``K / 128`` vectors, so K = 768 (6 vectors) takes the 8-slot rung
+ and K = 2048 (16) fills the 16-slot one exactly. An off-by-one in
+ the ``s < steps`` guard would either drop a vector from the absmax
+ or quantize past the end of the row, and both show up here.
+ """
+ for nk_label, N, K in _QWEN3_NK:
+ case = _build_case(
+ N,
+ K,
+ _QWEN3_E,
+ _PREFILL_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_ACT_QUANT_VEC="1", ARK_MOE_W4A8_ACT_QUANT_SINGLE_PASS=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ f"{nk_label.strip()} (K={K}): the single-pass activation quantizer disagrees with the "
+ f"two-pass one: max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}"
+ )
+ case = weights_s8 = wscales = outs = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_act_quant_rows_per_wg_matches(self):
+ """Packing more token rows into a work-group must change nothing.
+
+ ``ARK_MOE_W4A8_ACT_QUANT_ROWS_PER_WG`` only widens the launch:
+ ``local{R, SG_SIZE}`` instead of ``local{1, SG_SIZE}``. SYCL
+ linearizes work-items with the last dimension fastest, so local id
+ ``(r, lane)`` is linear id ``r * SG_SIZE + lane`` and, under
+ ``reqd_sub_group_size(SG_SIZE)``, each sub-group still covers
+ exactly one token's lanes. The reduction is the same sub-group
+ reduce over the same values, and there is no barrier or SLM for a
+ wider group to interact through -- so the outputs must be equal bit
+ for bit.
+
+ The row count is deliberately *not* a multiple of the largest rung:
+ the launch rounds the global range up to whole work-groups, so the
+ trailing rows exercise the ``token >= total_tokens`` guard. Without
+ it those threads would read and write past the end of the buffers.
+ """
+ for nk_label, N, K in _QWEN3_NK:
+ case = _build_case(
+ N,
+ K,
+ _QWEN3_E,
+ _ACT_QUANT_RAGGED_TOKENS,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ total_tokens = case["total_tokens"]
+ assert total_tokens % max(_ACT_QUANT_WG_ROWS) != 0, (
+ f"{nk_label.strip()}: {total_tokens} rows divides by {max(_ACT_QUANT_WG_ROWS)}, so the "
+ f"padding guard is never exercised -- pick a row count that does not"
+ )
+ outs = {}
+ for wg in _ACT_QUANT_WG_ROWS:
+ with _env_override(ARK_MOE_W4A8_ACT_QUANT_ROWS_PER_WG=str(wg)):
+ qact, ascale = ark.moe_w4a8_quant_act(case["activations"])
+ outs[wg] = (qact, ascale)
+ base_q, base_s = outs[_ACT_QUANT_WG_ROWS[0]]
+ for wg in _ACT_QUANT_WG_ROWS[1:]:
+ q, s = outs[wg]
+ assert torch.equal(base_q, q), (
+ f"{nk_label.strip()} (K={K}): {wg} rows/work-group quantizes differently from 1: "
+ f"max |diff| {(base_q.float() - q.float()).abs().max().item():.6g}"
+ )
+ assert torch.equal(base_s, s), (
+ f"{nk_label.strip()} (K={K}): {wg} rows/work-group writes different row scales than 1: "
+ f"max |diff| {(base_s - s).abs().max().item():.6g}"
+ )
+ case = outs = base_q = base_s = q = s = qact = ascale = None
+ _release_xpu_memory()
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_quant_act_zero_tokens_returns_empty_outputs(self):
+ """The Python wrapper should preserve the valid zero-token no-op."""
+ activations = torch.empty((0, 64), device="xpu", dtype=torch.bfloat16)
+ qact, ascale = ark.moe_w4a8_quant_act(activations)
+ assert qact.shape == (0, 64)
+ assert qact.dtype == torch.int8
+ assert ascale.shape == (0,)
+ assert ascale.dtype == torch.float32
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_quant_act_zero_tokens_still_validates_entry_point_args(self):
+ """The standalone entry point must validate queue/buffer arguments even for zero tokens."""
+ activations = torch.empty((0, 64), device="xpu", dtype=torch.bfloat16)
+ qact = torch.empty((0, 64), device="xpu", dtype=torch.int8)
+ ascale = torch.empty((0,), device="xpu", dtype=torch.float32)
+ lib = ark.get_lib(activations)
+ args = (
+ activations.data_ptr(),
+ qact.data_ptr(),
+ ascale.data_ptr(),
+ ark.cvt_dtype(activations.dtype),
+ 0,
+ 64,
+ )
+ with pytest.raises(Exception, match="stream must be a valid SYCL queue"):
+ lib.moe_w4a8_quant_act(0, *args)
+ with pytest.raises(Exception, match="null buffer"):
+ lib.moe_w4a8_quant_act(ark.get_stream(activations), 0, qact.data_ptr(), ascale.data_ptr(), *args[3:])
+
+ @pytest.mark.skipif(bool(_QUANT_ACT_SKIP), reason=_QUANT_ACT_SKIP or "standalone quantizer unavailable")
+ def test_quant_act_matches_in_call_quant(self):
+ """The standalone quantizer must be the pass the call runs internally.
+
+ Timing ``moe_w4a8_quant_act`` only says something about
+ ``moe_gemm_w4a8`` if it is the same work. It is the same launcher
+ behind the same parameter struct, and this pins that down from the
+ outside: feed its output back as the pre-quantized contract and the
+ GEMM has to produce bit-identical results to letting the call
+ quantize for itself. Any difference -- a different rounding, a
+ different scale convention, a missed row -- moves at least one
+ output element.
+ """
+ for nk_label, N, K in _QWEN3_NK:
+ case = _build_case(
+ N,
+ K,
+ _QWEN3_E,
+ _PREFILL_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ in_call = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ qact, ascale = ark.moe_w4a8_quant_act(case["activations"])
+ standalone = ark.moe_gemm_w4a8(
+ qact,
+ weights_s8,
+ wscales,
+ case["ntpe"],
+ rescale_block_size=block,
+ phase="prefill",
+ activation_scale=ascale,
+ out_dtype=case["dtype"],
+ )
+ assert torch.equal(in_call, standalone), (
+ f"{nk_label.strip()} (K={K}): pre-quantizing with moe_w4a8_quant_act disagrees with the "
+ f"call's own quantization: max |diff| "
+ f"{(in_call.float() - standalone.float()).abs().max().item():.6g}"
+ )
+ case = weights_s8 = wscales = in_call = standalone = qact = ascale = None
+ ark.clear_moe_w4a8_prepack_cache()
+ _release_xpu_memory()
+
+ def test_prefill_2d_store_matches_scalar(self):
+ """The 2D block store must write exactly what the scalar store wrote.
+
+ Only the store mechanism changes: the scaled value is computed by
+ the same convert and the same two multiplies in the same order, and
+ the fragment is handed to ``copy`` through the same coordinates the
+ scalar path indexes with. The store predicate is gone because the
+ block message clips to the ``m x n`` output surface in hardware, so
+ the interesting failure is a *ragged* tile writing rows that belong
+ to the next expert -- which is silent corruption, not a crash.
+
+ The batch is therefore the one from the interior-tile test: 300
+ rows on every expert against the ladder's 128-row tile gives each
+ expert two interior tiles and one ragged one, and the experts are
+ adjacent in the output, so anything spilling past an expert's last
+ row lands in the comparison.
+ """
+ rows_per_expert = _RAGGED_TILE_ROWS_PER_EXPERT
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ rows_per_expert * _QWEN3_E,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_PREFILL_STORE_2D=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ "the 2D block store disagrees with the scalar store: "
+ f"max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}"
+ )
+
+ def test_prefill_claim_early_matches(self):
+ """Claiming the next tile early must not change which tiles run.
+
+ The persistent kernel hands tiles out with a device-scope
+ ``atomicAdd`` on one dword. Moving that claim from after the GEMM
+ to before it changes only when the message is issued: the loop
+ still performs exactly one claim per tile and still consumes the
+ indices in the order the counter produces them, so the two orders
+ must agree bit for bit, not merely to an SNR.
+
+ The failure this guards against is a work-stealing bug, and those
+ are silent: a tile computed twice or skipped leaves a band of the
+ output stale or doubled rather than raising. Two things could
+ cause it here -- the claimed index being consumed a tile late, and
+ the counter's reset racing the first claims now that they are
+ issued within a few instructions of kernel entry (which is why the
+ reset moved to the host). Both show up as a mismatch against the
+ claim-after-GEMM baseline.
+
+ The batch is the ragged one: 300 rows on every expert against the
+ ladder's 128-row tile gives each expert two interior tiles and one
+ partial, so the expert boundaries the tile walk has to respect are
+ in the comparison, and every expert contributes more tiles than a
+ single work-group processes in one pass.
+ """
+ rows_per_expert = _RAGGED_TILE_ROWS_PER_EXPERT
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ rows_per_expert * _QWEN3_E,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_PREFILL_CLAIM_EARLY=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ "claiming the next tile before the GEMM changed the result: "
+ f"max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}, "
+ f"{(outs['0'] != outs['1']).sum().item()} of {outs['0'].numel()} elements differ"
+ )
+
+ def test_prefill_small_grf_matches(self):
+ """The halved register budget must not change the result.
+
+ ``grf_size`` asks the compiler for a register allocation; it does
+ not change what the kernel computes. But it is not only a compiler
+ hint here: the request also sets how many work-groups are resident,
+ and the persistent grid is sized from that number, so the two
+ budgets launch *different grids* over the same tiles. That is the
+ part worth testing. Tiles are handed out by a device-scope counter
+ rather than owned by a work-group, so a grid of a different size
+ must still consume every index exactly once.
+
+ The failure mode is silent in the same way the claim-order one is:
+ too few work-groups leave the last tiles uncomputed, too many leave
+ a band recomputed, and neither raises. Both show up as a mismatch
+ against the large-GRF baseline.
+
+ The tile is forced to 128x128 because that is the only rung the
+ halved budget applies to -- the ladder's own choice for these
+ shapes is 128x256, which declines it and would make this test
+ compare a kernel against itself. The batch is the ragged one, so
+ every expert contributes two interior tiles and one partial and the
+ expert boundaries the tile walk has to respect are in the
+ comparison.
+ """
+ rows_per_expert = _RAGGED_TILE_ROWS_PER_EXPERT
+ case = _build_case(
+ _QWEN3_NK[1][1],
+ _QWEN3_NK[1][2],
+ _QWEN3_E,
+ rows_per_expert * _QWEN3_E,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(
+ ARK_MOE_W4A8_PREFILL_TILE="128x128",
+ ARK_MOE_W4A8_PREFILL_SMALL_GRF=flag,
+ ):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "prefill").clone()
+ assert torch.equal(outs["0"], outs["1"]), (
+ "halving the register budget changed the result: "
+ f"max |diff| {(outs['0'].float() - outs['1'].float()).abs().max().item():.6g}, "
+ f"{(outs['0'] != outs['1']).sum().item()} of {outs['0'].numel()} elements differ"
+ )
+
+ def test_decode_ksplit_matches_legacy(self):
+ """The K-split decode mapping must agree with the legacy one.
+
+ Both paths accumulate the same int32 partial sums per re-scale
+ block and apply the same scales; only the assignment of K elements
+ to lanes differs. That does reorder the *float* accumulation (the
+ legacy kernel folds every block in one lane, the K-split kernel
+ folds per lane and then reduces across the sub-group), so the two
+ are not required to be bit-identical -- but they must agree far
+ more closely than either agrees with the fp32 reference. A wrong
+ lane mapping, expert offset or block scale would miss by orders of
+ magnitude, not by a rounding step.
+ """
+ case = _build_case(
+ _QWEN3_NK[0][1],
+ _QWEN3_NK[0][2],
+ _QWEN3_E,
+ _DECODE_BATCHES[0] * _QWEN3_TOPK,
+ _QWEN3_GROUP_SIZE,
+ torch.bfloat16,
+ need_reference=False,
+ need_dequant=False,
+ )
+ weights_s8, wscales, block = ark.moe_w4a8_prepack(
+ case["packed"], case["scales"], group_size=_QWEN3_GROUP_SIZE
+ )
+ outs = {}
+ for flag in ("0", "1"):
+ with _env_override(ARK_MOE_W4A8_DECODE_KSPLIT=flag):
+ outs[flag] = _w4a8(case, weights_s8, wscales, block, "decode").clone()
+ snr = _snr_db(outs["0"], outs["1"])
+ cos = _cosine(outs["0"], outs["1"])
+ assert snr >= 40.0, f"K-split decode disagrees with the legacy GEMV: SNR {snr:.2f} dB"
+ assert cos >= 0.9999, f"K-split decode disagrees with the legacy GEMV: cosine {cos:.6f}"
+
+
+# Minimum quality gate for the int8 activation path against an fp32 reference
+# built from the same dequantized int4 weights. Per-token absmax int8
+# activations lose ~7 bits of mantissa, which empirically lands well above
+# 20 dB / 0.999 cosine; anything below indicates a structural bug (wrong
+# scale block, transposed layout, wrong expert offset) rather than lossiness.
+_MIN_SNR_DB = 20.0
+_MIN_COSINE = 0.99
+
+
+def _assert_accuracy(rows) -> None:
+ assert rows, "no accuracy rows were produced"
+ for row in rows:
+ label = f"{row['label']} phase={row['phase']} N={row['N']} K={row['K']} tokens={row['tokens']}"
+ assert row["snr_ref"] >= _MIN_SNR_DB, f"{label}: SNR vs fp32 reference {row['snr_ref']:.2f} dB is too low"
+ assert row["cos_ref"] >= _MIN_COSINE, f"{label}: cosine vs fp32 reference {row['cos_ref']:.5f} is too low"
+
+
+def _assert_targets(request, phase, rows) -> None:
+ """Enforce the perf goals only when ``--enforce-targets`` was passed.
+
+ The goals are device-dependent (they assume a discrete Arc-class GPU), so
+ by default the verdict printed by ``_print_targets`` is informational and
+ the perf tests stay green anywhere the kernel merely runs. Rows whose
+ bandwidth-bound ceiling is below the target are never enforced: no kernel
+ change can satisfy the target at that routing.
+ """
+ if not request.config.getoption("--enforce-targets", default=False):
+ return
+ is_prefill = phase == "prefill"
+ target = _TARGET_PREFILL_TFLOPS if is_prefill else _TARGET_DECODE_GBPS
+ for row in rows:
+ ceiling = row.get("tflops_ceiling")
+ if is_prefill and ceiling is not None and ceiling < target:
+ continue
+ measured = row["tflops"] if is_prefill else row["gbps"]
+ unit = "TFLOPS" if is_prefill else "GB/s"
+ label = f"{row['label']} phase={phase} N={row['N']} K={row['K']} tokens={row['tokens']}"
+ assert measured > target, f"{label}: {measured:.2f} {unit} is below the {target:g} {unit} target"
+
+
+# ---------------------------------------------------------------------------
+# Standalone CLI
+# ---------------------------------------------------------------------------
+
+
+def _parse_args(argv):
+ parser = argparse.ArgumentParser(description="W4A8 ARK XPU MoE performance / accuracy benchmark")
+ parser.add_argument(
+ "--phase",
+ choices=("decode", "prefill", "both"),
+ default="both",
+ help="Which phase(s) to benchmark (default: both).",
+ )
+ parser.add_argument(
+ "--all-shapes",
+ action="store_true",
+ help="Sweep the full batch matrix instead of the single smallest batch.",
+ )
+ parser.add_argument(
+ "--dtype",
+ choices=("bf16", "fp16"),
+ default="bf16",
+ help="Activation dtype (default: bf16).",
+ )
+ parser.add_argument(
+ "--models",
+ default=",".join(_DEFAULT_MODELS),
+ help=(
+ "Comma-separated shape groups to benchmark, or 'all' "
+ f"(available: {', '.join(_MODELS)}; default: {','.join(_DEFAULT_MODELS)})."
+ ),
+ )
+ parser.add_argument(
+ "--sweep-configs",
+ action="store_true",
+ help=(
+ "Also sweep the kernel dispatch configurations (decode lane mapping, prefill tile) "
+ "and report the fastest numerically-equivalent one per shape."
+ ),
+ )
+ parser.add_argument(
+ "--rescale-group-size",
+ type=int,
+ default=-1,
+ help="AUTO_S8 re-scale block size; -1 (default) = one scale per output channel.",
+ )
+ parser.add_argument("--skip-accuracy", action="store_true", help="Only run the perf sweep.")
+ parser.add_argument("--skip-perf", action="store_true", help="Only run the accuracy sweep.")
+ parser.add_argument(
+ "--compute-bound",
+ action="store_true",
+ help=(
+ f"Also run the compute-bound prefill batch ({_PREFILL_TARGET_ROWS_PER_EXPERT} rows per expert), "
+ "the smallest sweep point where the 100 TFLOPS goal is not capped by weight bandwidth."
+ ),
+ )
+ parser.add_argument(
+ "--long-seq",
+ action="store_true",
+ help=(
+ f"Also run the long-prompt prefill point ({_PREFILL_LONG_SEQ_LEN} model tokens, one 8K sequence), "
+ "where Qwen3-MoE routes 512 rows per expert -- a higher intensity than the compute-bound batch, "
+ "and the only routing at which a 256-row tile does not pad. With --sweep-configs the "
+ "prefill tile sweep is repeated there."
+ ),
+ )
+ parser.add_argument(
+ "--dedup-quant",
+ action="store_true",
+ help=(
+ "Also run the end-to-end up/gate comparison that deduplicates the dynamic quantization: "
+ "quantize the batch distinct tokens once and permute int8, instead of permuting 16-bit and "
+ "letting the kernel quantize every routed row. Both paths are timed with the permute included."
+ ),
+ )
+ parser.add_argument(
+ "--contracts",
+ action="store_true",
+ help=(
+ "Also run the prefill points with the traffic-cutting call contracts (caller-supplied int8 "
+ "activations + the fused top-k reduction), and with --sweep-configs the contract A/B sweep. "
+ "These change what the call moves, so the printed ceiling and BW@100T follow the contract."
+ ),
+ )
+ parser.add_argument(
+ "--prefetch",
+ action="store_true",
+ help=(
+ "Also sweep the prefill mainloop's prefetch depth (1-8) at whichever prefill points are "
+ "selected. This is the measurement a K-dependent default would have to rest on: the "
+ "qwen3 down-projection has 12 k-tiles where minimax up has 48, so a fixed depth is a very "
+ "different fraction of the mainloop on each. Pair with --long-seq for the 8K-prompt routing."
+ ),
+ )
+ parser.add_argument(
+ "--claim-early",
+ action="store_true",
+ help=(
+ "Also sweep when the persistent prefill kernel claims its next tile: after the GEMM (the "
+ "old order, a device-scope atomic round trip fully exposed between two tiles) or before it, "
+ "in flight across the mainloop. Bounded by how much work a tile has to hide it behind, so "
+ "pair with --long-seq for the 12-k-tile down projections where it should show first."
+ ),
+ )
+ parser.add_argument(
+ "--grf",
+ action="store_true",
+ help=(
+ "Also sweep the prefill register budget: the same 128x128 tile at grf_size 256 and 128, "
+ "plus the shipped 128x256 tile for reference. Halving the request doubles how many "
+ "work-groups are resident, which the persistent grid is sized from, so this is the "
+ "occupancy sweep the small tiles in the ladder have never had -- they were all measured "
+ "at the large budget their smaller accumulator was supposed to avoid."
+ ),
+ )
+ parser.add_argument(
+ "--act-quant-wg",
+ action="store_true",
+ help=(
+ "Also time the activation quantization pass on its own, one row per work-group shape "
+ "(1-16 token rows per group). Two answers in one table: what the pass actually costs -- "
+ "until now it was only ever differenced out of two whole-call timings -- and whether the "
+ "shipped one-thread-per-work-group launch is leaving the thread dispatcher idle. Pair "
+ "with --long-seq for the routing whose 28% quantization share the up-projection ceilings "
+ "were computed from."
+ ),
+ )
+ parser.add_argument("--iters", type=int, default=ITERS, help=f"Timed iterations per measurement (default {ITERS}).")
+ parser.add_argument("--warmup", type=int, default=WARMUP, help=f"Warmup iterations (default {WARMUP}).")
+ parser.add_argument(
+ "--rounds",
+ type=int,
+ default=SWEEP_ROUNDS,
+ help=f"Rounds the sweeps round-robin over their configurations (default {SWEEP_ROUNDS}). "
+ "Each round times ITERS // ROUNDS iterations, so the total is unchanged; raise it when the "
+ "reported drift is comparable to the spread being ranked.",
+ )
+ return parser.parse_args(argv)
+
+
+def main(argv=None) -> int:
+ global WARMUP, ITERS, SWEEP_ROUNDS
+ args = _parse_args(sys.argv[1:] if argv is None else argv)
+ if _W4A8_SKIP:
+ print(f"[moe-w4a8-perf] cannot run: {_W4A8_SKIP}")
+ return 1
+
+ WARMUP = args.warmup
+ ITERS = args.iters
+ SWEEP_ROUNDS = max(1, args.rounds)
+ dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
+ phases = ("decode", "prefill") if args.phase == "both" else (args.phase,)
+
+ env_block = os.environ.get("ARK_MOE_W4A8_AUTO_S8")
+ if env_block is not None:
+ print(f"[moe-w4a8-perf] ARK_MOE_W4A8_AUTO_S8={env_block} overrides --rescale-group-size")
+
+ models = "all" if args.models == "all" else [m.strip() for m in args.models.split(",") if m.strip()]
+
+ failures = []
+ for phase in phases:
+ batches = _decode_batches(args.all_shapes) if phase == "decode" else _prefill_batches(args.all_shapes)
+ if not args.skip_accuracy:
+ rows = run_accuracy(phase, batches, dtype=dtype, rescale_group_size=args.rescale_group_size)
+ try:
+ _assert_accuracy(rows)
+ except AssertionError as exc:
+ failures.append(str(exc))
+ if not args.skip_perf:
+ run_perf(phase, batches, dtype=dtype, rescale_group_size=args.rescale_group_size, models=models)
+ if phase == "prefill" and args.compute_bound:
+ run_perf(
+ phase,
+ None,
+ dtype=dtype,
+ rescale_group_size=args.rescale_group_size,
+ torch_baseline=False,
+ compute_bound=True,
+ models=models,
+ )
+ if phase == "prefill" and args.long_seq:
+ run_perf(
+ phase,
+ _long_seq_batches(),
+ dtype=dtype,
+ rescale_group_size=args.rescale_group_size,
+ torch_baseline=False,
+ models=models,
+ )
+ if phase == "prefill" and args.contracts:
+ run_perf(
+ phase,
+ _long_seq_batches() if args.long_seq else None,
+ dtype=dtype,
+ rescale_group_size=args.rescale_group_size,
+ torch_baseline=False,
+ compute_bound=not args.long_seq,
+ models=models,
+ prequantized=True,
+ fused_reduce=True,
+ )
+ if phase == "prefill" and args.dedup_quant:
+ run_dedup_quant(
+ _long_seq_batches() if args.long_seq else None,
+ dtype=dtype,
+ models=models,
+ )
+ if args.sweep_configs:
+ configs = _PREFILL_TILE_CONFIGS if phase == "prefill" else _DECODE_CONFIGS
+ run_config_sweep(phase, configs, dtype=dtype, models=models)
+ if phase == "prefill" and args.long_seq:
+ run_config_sweep(phase, configs, dtype=dtype, models=models, batches=_long_seq_batches())
+ if phase == "prefill" and args.contracts:
+ run_config_sweep(phase, _PREFILL_CONTRACT_CONFIGS, dtype=dtype, models=models)
+ if phase == "prefill" and args.prefetch:
+ if not args.long_seq or args.compute_bound:
+ run_config_sweep(phase, _PREFILL_PREFETCH_CONFIGS, dtype=dtype, models=models)
+ if args.long_seq:
+ run_config_sweep(
+ phase,
+ _PREFILL_PREFETCH_CONFIGS,
+ dtype=dtype,
+ models=models,
+ batches=_long_seq_batches(),
+ )
+ if phase == "prefill" and args.claim_early:
+ if not args.long_seq or args.compute_bound:
+ run_config_sweep(phase, _PREFILL_CLAIM_CONFIGS, dtype=dtype, models=models)
+ if args.long_seq:
+ run_config_sweep(
+ phase,
+ _PREFILL_CLAIM_CONFIGS,
+ dtype=dtype,
+ models=models,
+ batches=_long_seq_batches(),
+ )
+ if phase == "prefill" and args.grf:
+ if not args.long_seq or args.compute_bound:
+ run_config_sweep(phase, _PREFILL_GRF_CONFIGS, dtype=dtype, models=models)
+ if args.long_seq:
+ run_config_sweep(
+ phase,
+ _PREFILL_GRF_CONFIGS,
+ dtype=dtype,
+ models=models,
+ batches=_long_seq_batches(),
+ )
+
+ if phase == "prefill" and args.act_quant_wg:
+ if _QUANT_ACT_SKIP:
+ print(f"[moe-w4a8-perf] --act-quant-wg unavailable: {_QUANT_ACT_SKIP}")
+ else:
+ if not args.long_seq or args.compute_bound:
+ run_act_quant(dtype=dtype, models=models)
+ if args.long_seq:
+ run_act_quant(dtype=dtype, models=models, batches=_long_seq_batches())
+
+ if failures:
+ print()
+ print("ACCURACY FAILURES:")
+ for message in failures:
+ print(f" - {message}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())