Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

perf(qwen3-embedding): fuse the 8B's elementwise layer work into exact Triton kernels (#645)

svonava6949a8b935c1
diff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml
index 4bb2201ed..cd0a6e982 100644
--- a/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-8B.yaml
@@ -23,6 +23,10 @@ profiles:
adapter_options:
loadtime:
causal: true
+ # Fused Triton kernels for each layer's RMSNorm, rotary and SiLU-gated MLP
+ # elementwise work: about 1.28x the documents per second on an H100, with
+ # bit-identical embeddings (the kernels round where the eager ops round).
+ fused_kernels: true
runtime:
pooling: last
normalize: true
diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
index 8fe1f0dac..c4c7bbf35 100644
--- a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import itertools
import json
import logging
from pathlib import Path
from typing import TYPE_CHECKING, Any, ClassVar
+import numpy as np
import torch
from torch.nn import functional
@@ -19,6 +21,7 @@ from sie_server.adapters._utils import (
validate_output_types,
)
from sie_server.adapters.peft_lora_mixin import PEFTLoRAMixin
+from sie_server.adapters.qwen2_flash import _fused_layers
from sie_server.core.inference_output import EncodeOutput
from sie_server.types.inputs import Item
@@ -61,6 +64,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
uses_legacy_transformers_cache: bool = False,
dense_projection_path: str | None = None,
causal: bool = False,
+ fused_kernels: bool = False,
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -84,6 +88,11 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
causal: If True, use causal (autoregressive) attention instead of
bidirectional. Required for decoder-based embedding models like
Qwen3-Embedding that use last-token pooling with causal masking.
+ fused_kernels: If True, run each layer's residual add + RMSNorm,
+ q/k RMSNorm, rotary embedding and SiLU-gated MLP product as
+ single Triton kernels (``_fused_ops``) instead of chains of
+ elementwise PyTorch ops. The kernels round where the eager ops
+ round, so embeddings match the eager path.
"""
_ = kwargs
self._model_name_or_path = str(model_name_or_path)
@@ -95,6 +104,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._query_template = query_template
self._doc_template = doc_template
self._causal = causal
+ self._fused_kernels = fused_kernels
self._uses_legacy_transformers_cache = uses_legacy_transformers_cache
self._dense_projection_path = dense_projection_path
@@ -168,6 +178,14 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._model.to(device)
self._model.eval()
+ if self._fused_kernels and not _fused_layers.supported(self._model):
+ logger.warning(
+ "fused_kernels needs Triton and Qwen2/Qwen3 layers with a SiLU-gated MLP; "
+ "%s runs the eager layers instead",
+ self._model_name_or_path,
+ )
+ self._fused_kernels = False
+
self._dense_dim = self._model.config.hidden_size
if self._dense_projection_path:
@@ -285,32 +303,29 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
err_msg="Qwen2FlashAdapter requires text input",
)
- # Tokenize each sequence individually (no padding)
- encodings = [
- self._tokenizer(
- text,
- max_length=self._max_seq_length,
- truncation=True,
- return_tensors="pt",
- )
- for text in texts
- ]
+ # Tokenize every sequence (no padding) in one batched call: the fast
+ # tokenizer encodes the texts in parallel and returns, per text, exactly
+ # the ids a call on that text alone returns.
+ token_ids = self._tokenizer(
+ texts,
+ max_length=self._max_seq_length,
+ truncation=True,
+ return_attention_mask=False,
+ )["input_ids"]
# Build packed representation
- seq_lengths = [enc["input_ids"].shape[1] for enc in encodings]
+ seq_lengths = [len(ids) for ids in token_ids]
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
- # Pack input_ids
- input_ids_packed = torch.cat([enc["input_ids"].squeeze(0) for enc in encodings]).to(self._device)
-
- # Build cu_seqlens using cumsum (no Python loop, no GPU sync points)
- cu_seqlens = torch.zeros(len(texts) + 1, dtype=torch.int32, device=self._device)
- cu_seqlens[1:] = torch.cumsum(torch.tensor(seq_lengths, dtype=torch.int32, device=self._device), dim=0)
+ # Pack input_ids and cu_seqlens on the host: one copy each, no GPU sync points
+ flat_ids = np.fromiter(itertools.chain.from_iterable(token_ids), dtype=np.int64, count=total_tokens)
+ input_ids_packed = torch.from_numpy(flat_ids).to(self._device)
+ cu_seqlens = torch.from_numpy(np.concatenate(([0], np.cumsum(seq_lengths))).astype(np.int32)).to(self._device)
with torch.inference_mode():
- # Build position IDs for RoPE
- position_ids_packed = self._build_position_ids(cu_seqlens, len(texts))
+ # Build position IDs for RoPE (the host-known total avoids a device sync)
+ position_ids_packed = self._build_position_ids(cu_seqlens, len(texts), total_tokens=total_tokens)
# Get word embeddings (Qwen2 has no position embeddings - uses RoPE)
hidden = self._model.embed_tokens(input_ids_packed)
@@ -349,9 +364,11 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
return output
- def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:
+ def _build_position_ids(
+ self, cu_seqlens: torch.Tensor, num_seqs: int, *, total_tokens: int | None = None
+ ) -> torch.Tensor:
"""Build position IDs for packed sequences (each restarts at 0)."""
- return build_position_ids(cu_seqlens)
+ return build_position_ids(cu_seqlens, total_tokens=total_tokens)
def _compute_rope(
self,
@@ -415,6 +432,9 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
- GQA (grouped query attention with fewer KV heads)
- Separate Q/K/V projections
"""
+ if self._fused_kernels:
+ return self._run_transformer_fused(hidden, cu_seqlens, max_seqlen, total_tokens, position_ids)
+
from flash_attn import flash_attn_varlen_func
num_heads = self._model.config.num_attention_heads
@@ -486,6 +506,23 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
return hidden
+ def _run_transformer_fused(
+ self,
+ hidden: torch.Tensor,
+ cu_seqlens: torch.Tensor,
+ max_seqlen: int,
+ total_tokens: int,
+ position_ids: torch.Tensor,
+ ) -> torch.Tensor:
+ """The layers of ``_run_transformer_flash`` with the elementwise work in fused kernels (``_fused_layers``)."""
+ rotary_emb = (
+ self._model.rotary_emb if hasattr(self._model, "rotary_emb") else self._model.layers[0].self_attn.rotary_emb
+ )
+ cos, sin = self._compute_rope(rotary_emb, position_ids, max_seqlen)
+ return _fused_layers.run_layers(
+ self._model, hidden, cu_seqlens, max_seqlen, total_tokens, cos, sin, causal=self._causal
+ )
+
def _pool_embeddings(
self,
hidden: torch.Tensor,
diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_layers.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_layers.py
new file mode 100644
index 000000000..212080ae4
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_layers.py
@@ -0,0 +1,100 @@
+"""Qwen2/Qwen3 decoder layers with their elementwise work in fused Triton kernels.
+
+``run_layers`` is the layer loop of ``Qwen2FlashAdapter._run_transformer_flash``
+with each residual add folded into the next RMSNorm, q/k-norm as one kernel per
+tensor, the rotary embedding as one in-place kernel per tensor and the MLP's
+``silu(gate) * up`` as one kernel (see ``_fused_ops``). The kernels round where
+the eager ops round, so the result matches the eager layers bit for bit; the
+projections and attention are the same calls.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import torch
+
+
+def supported(model: Any) -> bool:
+ """Whether ``run_layers`` can run ``model``.
+
+ Needs Triton, a SiLU-gated MLP, and decoder layers with the modules the
+ loop reads (checked on the first layer): separate gate/up/down projections
+ and RMSNorms exposing ``weight`` and ``variance_epsilon``. A remote-code
+ variant with a fused ``gate_up_proj`` or a norm with ``eps`` keeps the
+ eager layers.
+ """
+ if getattr(model.config, "hidden_act", None) != "silu":
+ return False
+ try:
+ import triton # ty: ignore[unresolved-import]
+ except ImportError:
+ return False
+ return _layer_layout(model.layers)
+
+
+def _layer_layout(layers: Any) -> bool:
+ if not len(layers):
+ return False
+ layer = layers[0]
+ norms = [layer.input_layernorm, layer.post_attention_layernorm]
+ attn = layer.self_attn
+ norms += [getattr(attn, name) for name in ("q_norm", "k_norm") if hasattr(attn, name)]
+ return all(hasattr(layer.mlp, name) for name in ("gate_proj", "up_proj", "down_proj")) and all(
+ hasattr(norm, "weight") and hasattr(norm, "variance_epsilon") for norm in norms
+ )
+
+
+def run_layers(
+ model: Any,
+ hidden: torch.Tensor,
+ cu_seqlens: torch.Tensor,
+ max_seqlen: int,
+ total_tokens: int,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+ *,
+ causal: bool,
+) -> torch.Tensor:
+ """Run ``model``'s decoder layers over the packed ``hidden``; returns the residual stream before the final norm."""
+ from flash_attn import flash_attn_varlen_func
+
+ from sie_server.adapters.qwen2_flash._fused_ops import rms_norm, rotary_, silu_mul
+
+ config = model.config
+ num_heads = config.num_attention_heads
+ num_kv_heads = config.num_key_value_heads
+ head_dim = getattr(config, "head_dim", config.hidden_size // num_heads)
+ softmax_scale = 1.0 / (head_dim**0.5)
+ cos, sin = cos.contiguous(), sin.contiguous()
+
+ residual: torch.Tensor | None = None
+ for layer in model.layers:
+ attn = layer.self_attn
+ norm = layer.input_layernorm
+ normed, residual = rms_norm(hidden, norm.weight, norm.variance_epsilon, residual)
+ query = attn.q_proj(normed).view(total_tokens, num_heads, head_dim)
+ key = attn.k_proj(normed).view(total_tokens, num_kv_heads, head_dim)
+ value = attn.v_proj(normed).view(total_tokens, num_kv_heads, head_dim)
+ if hasattr(attn, "q_norm"):
+ query, _ = rms_norm(query, attn.q_norm.weight, attn.q_norm.variance_epsilon)
+ if hasattr(attn, "k_norm"):
+ key, _ = rms_norm(key, attn.k_norm.weight, attn.k_norm.variance_epsilon)
+ query = rotary_(query.contiguous(), cos, sin)
+ key = rotary_(key.contiguous(), cos, sin)
+ attn_out = flash_attn_varlen_func(
+ query,
+ key,
+ value,
+ cu_seqlens_q=cu_seqlens,
+ cu_seqlens_k=cu_seqlens,
+ max_seqlen_q=max_seqlen,
+ max_seqlen_k=max_seqlen,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ ).reshape(total_tokens, num_heads * head_dim)
+ norm = layer.post_attention_layernorm
+ normed, residual = rms_norm(attn.o_proj(attn_out), norm.weight, norm.variance_epsilon, residual)
+ mlp = layer.mlp
+ hidden = mlp.down_proj(silu_mul(mlp.gate_proj(normed), mlp.up_proj(normed)))
+ return hidden if residual is None else residual + hidden
diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_ops.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_ops.py
new file mode 100644
index 000000000..8dc42e6ee
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/_fused_ops.py
@@ -0,0 +1,208 @@
+# Triton reads a kernel's parameter annotations itself, so the kernels' pointer and stride
+# arguments stay unannotated.
+# ruff: noqa: ANN001, ANN202
+"""Fused Triton kernels for the elementwise work of a Qwen2/Qwen3 decoder layer.
+
+Each kernel does in one pass what the eager layer does in a chain of PyTorch
+ops, and rounds to the activation dtype at the same points the eager ops do, so
+it reproduces their results bit for bit:
+
+* ``rms_norm``: optional residual add, then HF's RMSNorm
+ ``weight * (x * rsqrt(mean(x**2) + eps)).to(dtype)``. The add is rounded
+ to the activation dtype first, as ``residual + hidden`` is, and the mean is
+ PyTorch's own reduction of the same float32 squares.
+* ``rotary_``: HF's ``q * cos + rotate_half(q) * sin`` in place, each product
+ and the sum rounded as the eager bfloat16 ops round them.
+* ``silu_mul``: ``silu(gate) * up``, the SiLU rounded before the product.
+
+The eager layer launches about 48 elementwise kernels per layer and these about
+14, which matters because each of those kernels reads and writes the whole
+activation.
+"""
+
+from __future__ import annotations
+
+import torch
+import triton # ty: ignore[unresolved-import]
+import triton.language as tl # ty: ignore[unresolved-import]
+from triton.language.extra.cuda import libdevice # ty: ignore[unresolved-import]
+
+# Elements per program of the elementwise SiLU-product kernel.
+_SILU_BLOCK = 1024
+
+
+def _round(x, dtype: tl.constexpr):
+ """``x`` rounded to ``dtype`` to nearest-even, as PyTorch rounds each op's float result.
+
+ The products, sums and casts are explicit intrinsics so the compiler can
+ neither contract a product into the next add nor drop a round trip.
+ """
+ return tl.cast(x, dtype, fp_downcast_rounding="rtne")
+
+
+def _add_square_kernel(
+ x_ptr,
+ residual_ptr,
+ summed_ptr,
+ squares_ptr,
+ stride_x,
+ stride_residual,
+ stride_summed,
+ n_cols,
+ has_residual: tl.constexpr,
+ block: tl.constexpr,
+):
+ """``summed = x + residual`` rounded (or ``x``), and ``float(summed) ** 2`` for the variance."""
+ row = tl.program_id(0).to(tl.int64)
+ cols = tl.arange(0, block)
+ mask = cols < n_cols
+ x = tl.load(x_ptr + row * stride_x + cols, mask=mask, other=0.0).to(tl.float32)
+ if has_residual:
+ residual = tl.load(residual_ptr + row * stride_residual + cols, mask=mask, other=0.0).to(tl.float32)
+ summed = _round(libdevice.add_rn(x, residual), summed_ptr.dtype.element_ty)
+ tl.store(summed_ptr + row * stride_summed + cols, summed, mask=mask)
+ x = summed.to(tl.float32)
+ tl.store(squares_ptr + row * n_cols + cols, libdevice.mul_rn(x, x), mask=mask)
+
+
+def _normalize_kernel(
+ x_ptr,
+ variance_ptr,
+ weight_ptr,
+ out_ptr,
+ stride_x,
+ stride_out,
+ n_cols,
+ eps,
+ block: tl.constexpr,
+):
+ """``weight * (x * rsqrt(variance + eps)).to(dtype)``, rounded where HF's RMSNorm rounds."""
+ row = tl.program_id(0).to(tl.int64)
+ cols = tl.arange(0, block)
+ mask = cols < n_cols
+ x = tl.load(x_ptr + row * stride_x + cols, mask=mask, other=0.0).to(tl.float32)
+ rstd = libdevice.rsqrt(libdevice.add_rn(tl.load(variance_ptr + row), eps))
+ normed = _round(libdevice.mul_rn(x, rstd), out_ptr.dtype.element_ty).to(tl.float32)
+ weight = tl.load(weight_ptr + cols, mask=mask, other=0.0).to(tl.float32)
+ tl.store(
+ out_ptr + row * stride_out + cols, _round(libdevice.mul_rn(normed, weight), out_ptr.dtype.element_ty), mask=mask
+ )
+
+
+def rms_norm(
+ x: torch.Tensor, weight: torch.Tensor, eps: float, residual: torch.Tensor | None = None
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """``(rms_norm(x + residual), x + residual)`` over the last dimension (``x`` alone without a residual).
+
+ The variance is ``squares.mean(-1)`` in PyTorch over the same float32
+ squares HF's ``x.float().pow(2)`` makes, so it is reduced in PyTorch's own
+ order and matches HF's RMSNorm bit for bit; the add, the squares and the
+ scaling run as two Triton kernels.
+ """
+ shape = x.shape
+ x2 = x.reshape(-1, shape[-1])
+ n_rows, n_cols = x2.shape
+ if residual is None:
+ summed2 = x2
+ residual2 = x2
+ else:
+ summed2 = torch.empty_like(x2)
+ residual2 = residual.reshape(-1, shape[-1])
+ squares = torch.empty(shape, dtype=torch.float32, device=x.device)
+ out = torch.empty_like(x2)
+ if n_rows:
+ block = triton.next_power_of_2(n_cols)
+ _add_square_kernel[(n_rows,)](
+ x2,
+ residual2,
+ summed2,
+ squares,
+ x2.stride(0),
+ residual2.stride(0),
+ summed2.stride(0),
+ n_cols,
+ has_residual=residual is not None,
+ block=block,
+ )
+ variance = squares.mean(-1)
+ _normalize_kernel[(n_rows,)](
+ summed2, variance, weight, out, summed2.stride(0), out.stride(0), n_cols, eps, block=block
+ )
+ return out.view(shape), (x if residual is None else summed2.view(shape))
+
+
+def _rotary_kernel(x_ptr, cos_ptr, sin_ptr, stride_token, stride_head, stride_table, half: tl.constexpr):
+ token = tl.program_id(0).to(tl.int64)
+ head = tl.program_id(1).to(tl.int64)
+ offs = tl.arange(0, half)
+ base = x_ptr + token * stride_token + head * stride_head
+ table = token * stride_table
+ x1 = tl.load(base + offs)
+ x2 = tl.load(base + half + offs)
+ dtype = x1.dtype
+ x1 = x1.to(tl.float32)
+ x2 = x2.to(tl.float32)
+ cos1 = tl.load(cos_ptr + table + offs).to(tl.float32)
+ cos2 = tl.load(cos_ptr + table + half + offs).to(tl.float32)
+ sin1 = tl.load(sin_ptr + table + offs).to(tl.float32)
+ sin2 = tl.load(sin_ptr + table + half + offs).to(tl.float32)
+ # q * cos + rotate_half(q) * sin, rotate_half(q) = cat(-x2, x1): round each product, then the sum.
+ out1 = _round(
+ libdevice.add_rn(
+ _round(libdevice.mul_rn(x1, cos1), dtype).to(tl.float32),
+ _round(libdevice.mul_rn(-x2, sin1), dtype).to(tl.float32),
+ ),
+ dtype,
+ )
+ out2 = _round(
+ libdevice.add_rn(
+ _round(libdevice.mul_rn(x2, cos2), dtype).to(tl.float32),
+ _round(libdevice.mul_rn(x1, sin2), dtype).to(tl.float32),
+ ),
+ dtype,
+ )
+ tl.store(base + offs, out1)
+ tl.store(base + half + offs, out2)
+
+
+def rotary_(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
+ """Rotate ``x`` (``[tokens, heads, head_dim]``) in place by per-token ``cos``/``sin`` (``[tokens, head_dim]``)."""
+ tokens, heads, head_dim = x.shape
+ half = head_dim // 2
+ if cos.shape != (tokens, head_dim) or sin.shape != cos.shape or head_dim % 2 or half & (half - 1):
+ msg = "rotary_ needs cos/sin of shape [tokens, head_dim] and a head_dim that is twice a power of two"
+ raise ValueError(msg)
+ if x.stride(-1) != 1 or cos.stride(-1) != 1 or sin.stride(-1) != 1 or cos.stride(0) != sin.stride(0):
+ msg = "rotary_ needs a contiguous last dimension and matching cos/sin layouts"
+ raise ValueError(msg)
+ if tokens:
+ _rotary_kernel[(tokens, heads)](x, cos, sin, x.stride(0), x.stride(1), cos.stride(0), half=half)
+ return x
+
+
+def _silu_mul_kernel(gate_ptr, up_ptr, out_ptr, n_elements, block: tl.constexpr):
+ offs = tl.program_id(0).to(tl.int64) * block + tl.arange(0, block)
+ mask = offs < n_elements
+ gate = tl.load(gate_ptr + offs, mask=mask, other=0.0).to(tl.float32)
+ up = tl.load(up_ptr + offs, mask=mask, other=0.0).to(tl.float32)
+ # PyTorch's SiLU: x / (1 + exp(-x)) in float, rounded; then the product, rounded.
+ dtype = out_ptr.dtype.element_ty
+ silu = _round(libdevice.div_rn(gate, libdevice.add_rn(1.0, libdevice.exp(-gate))), dtype).to(tl.float32)
+ tl.store(out_ptr + offs, _round(libdevice.mul_rn(silu, up), dtype), mask=mask)
+
+
+def silu_mul(gate: torch.Tensor, up: torch.Tensor) -> torch.Tensor:
+ """``silu(gate) * up`` for contiguous tensors of one shape."""
+ if not (gate.is_contiguous() and up.is_contiguous()) or gate.shape != up.shape:
+ msg = "silu_mul needs contiguous gate and up tensors of one shape"
+ raise ValueError(msg)
+ out = torch.empty_like(gate)
+ n = gate.numel()
+ if n:
+ _silu_mul_kernel[(triton.cdiv(n, _SILU_BLOCK),)](gate, up, out, n, block=_SILU_BLOCK)
+ return out
diff --git a/packages/sie_server/tests/adapters/test_qwen2_flash.py b/packages/sie_server/tests/adapters/test_qwen2_flash.py
index abe867ab3..cfa47a2e0 100644
--- a/packages/sie_server/tests/adapters/test_qwen2_flash.py
+++ b/packages/sie_server/tests/adapters/test_qwen2_flash.py
@@ -36,9 +36,9 @@ class _RecordingTokenizer:
def __init__(self) -> None:
self.texts: list[str] = []
- def __call__(self, text: str, **_: Any) -> dict[str, torch.Tensor]:
- self.texts.append(text)
- return {"input_ids": torch.zeros((1, len(text)), dtype=torch.long)}
+ def __call__(self, texts: list[str], **_: Any) -> dict[str, list[list[int]]]:
+ self.texts.extend(texts)
+ return {"input_ids": [[0] * len(text) for text in texts]}
def _config(model_file: str) -> ModelConfig:
diff --git a/packages/sie_server/tests/adapters/test_qwen2_flash_fused.py b/packages/sie_server/tests/adapters/test_qwen2_flash_fused.py
new file mode 100644
index 000000000..a714352bc
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_qwen2_flash_fused.py
@@ -0,0 +1,153 @@
+"""Qwen2FlashAdapter's fused-kernel layers: opt-in per profile, bit-identical to the eager layers on CUDA."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+import torch
+from sie_server.adapters.qwen2_flash import Qwen2FlashAdapter, _fused_layers
+from sie_server.core.loader import load_model_config
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+
+try:
+ import triton # ty: ignore[unresolved-import]
+
+ _HAS_TRITON = True
+except ImportError:
+ _HAS_TRITON = False
+
+needs_cuda_triton = pytest.mark.skipif(not (torch.cuda.is_available() and _HAS_TRITON), reason="needs CUDA and Triton")
+
+
+def test_qwen3_embedding_8b_turns_fused_kernels_on() -> None:
+ profile = load_model_config(_MODELS_DIR / "Qwen__Qwen3-Embedding-8B.yaml").resolve_profile("default")
+ assert profile.loadtime["fused_kernels"] is True
+
+
+def test_fused_kernels_are_off_unless_a_profile_asks() -> None:
+ assert Qwen2FlashAdapter("unused")._fused_kernels is False
+
+
+def _small_qwen3(layers: int = 1) -> Any:
+ from transformers import Qwen3Config, Qwen3Model
+
+ config = Qwen3Config(
+ vocab_size=16,
+ hidden_size=32,
+ intermediate_size=64,
+ num_hidden_layers=layers,
+ num_attention_heads=2,
+ num_key_value_heads=1,
+ head_dim=16,
+ )
+ return Qwen3Model(config)
+
+
+def test_fused_kernels_need_a_silu_mlp() -> None:
+ model = _small_qwen3()
+ assert _fused_layers.supported(model) is _HAS_TRITON
+ model.config.hidden_act = "gelu"
+ assert not _fused_layers.supported(model)
+
+
+def test_fused_kernels_need_the_qwen_layer_layout() -> None:
+ layers = _small_qwen3().layers
+ assert _fused_layers._layer_layout(layers)
+ assert not _fused_layers._layer_layout(torch.nn.ModuleList())
+ del layers[0].mlp.gate_proj # e.g. a remote-code layer with a fused gate_up_proj
+ assert not _fused_layers._layer_layout(layers)
+
+
+@needs_cuda_triton
+def test_rotary_rejects_tables_that_do_not_match_the_input() -> None:
+ from sie_server.adapters.qwen2_flash._fused_ops import rotary_
+
+ x = torch.zeros(4, 2, 8, device="cuda", dtype=torch.bfloat16)
+ table = torch.zeros(3, 8, device="cuda", dtype=torch.bfloat16)
+ with pytest.raises(ValueError, match="rotary_ needs"):
+ rotary_(x, table, table)
+
+
+def test_the_option_routes_the_layers_to_the_fused_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter = Qwen2FlashAdapter("unused", fused_kernels=True)
+ calls: list[tuple[Any, ...]] = []
+ monkeypatch.setattr(adapter, "_run_transformer_fused", lambda *args: calls.append(args) or args[0])
+ hidden = torch.zeros(3, 4)
+ assert adapter._run_transformer_flash(hidden, torch.tensor([0, 3]), 3, 3, torch.arange(3)) is hidden
+ assert len(calls) == 1
+
+
+@needs_cuda_triton
+def test_each_fused_op_is_bit_identical_to_the_eager_ops() -> None:
+ from sie_server.adapters._utils import apply_rotary_pos_emb
+ from sie_server.adapters.qwen2_flash._fused_ops import rms_norm, rotary_, silu_mul
+ from transformers.models.qwen3.modeling_qwen3 import Qwen3RMSNorm
+
+ torch.manual_seed(0)
+ dev, dt = "cuda", torch.bfloat16
+ tokens, hidden_size, head_dim, heads, kv_heads, inter = 777, 512, 128, 8, 2, 1536
+ norm = Qwen3RMSNorm(hidden_size, eps=1e-6).to(dev, dt)
+ head_norm = Qwen3RMSNorm(head_dim, eps=1e-6).to(dev, dt)
+ with torch.no_grad():
+ norm.weight.copy_(torch.randn(hidden_size, device=dev, dtype=dt) * 0.1 + 1)
+ head_norm.weight.copy_(torch.randn(head_dim, device=dev, dtype=dt) * 0.1 + 1)
+ x = torch.randn(tokens, hidden_size, device=dev, dtype=dt) * 3
+ residual = torch.randn(tokens, hidden_size, device=dev, dtype=dt) * 10
+ query = torch.randn(tokens, heads, head_dim, device=dev, dtype=dt)
+ key = torch.randn(tokens, kv_heads, head_dim, device=dev, dtype=dt)
+ positions = torch.cat([torch.arange(n, device=dev) for n in (300, 400, 77)]).float()
+ inv_freq = 1.0 / (1_000_000 ** (torch.arange(0, head_dim, 2, device=dev).float() / head_dim))
+ angles = torch.cat([positions[:, None] * inv_freq] * 2, dim=-1)
+ cos, sin = angles.cos().to(dt), angles.sin().to(dt)
+ gate = torch.randn(tokens, inter, device=dev, dtype=dt) * 4
+ up = torch.randn(tokens, inter, device=dev, dtype=dt)
+
+ with torch.no_grad():
+ out, summed = rms_norm(x, norm.weight, norm.variance_epsilon, residual)
+ assert torch.equal(summed, residual + x)
+ assert torch.equal(out, norm(residual + x))
+ out, same = rms_norm(x, norm.weight, norm.variance_epsilon)
+ assert same is x
+ assert torch.equal(out, norm(x))
+ assert torch.equal(rms_norm(query, head_norm.weight, head_norm.variance_epsilon)[0], head_norm(query))
+ eager_q, eager_k = apply_rotary_pos_emb(query, key, cos, sin)
+ assert torch.equal(rotary_(query.clone(), cos, sin), eager_q)
+ assert torch.equal(rotary_(key.clone(), cos, sin), eager_k)
+ assert torch.equal(silu_mul(gate, up), torch.nn.functional.silu(gate) * up)
+
+
+@needs_cuda_triton
+def test_fused_layers_match_the_eager_layers_on_a_small_qwen3() -> None:
+ pytest.importorskip("flash_attn")
+ from transformers import Qwen3Config, Qwen3Model
+
+ torch.manual_seed(0)
+ config = Qwen3Config(
+ vocab_size=128,
+ hidden_size=256,
+ intermediate_size=768,
+ num_hidden_layers=3,
+ num_attention_heads=4,
+ num_key_value_heads=2,
+ head_dim=64,
+ max_position_embeddings=1024,
+ )
+ model = Qwen3Model(config).to("cuda", torch.bfloat16).eval()
+ lengths = [5, 300, 1, 64]
+ cu_seqlens = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()], dtype=torch.int32, device="cuda")
+ total = sum(lengths)
+ position_ids = torch.cat([torch.arange(n) for n in lengths]).to("cuda")
+ hidden = model.embed_tokens(torch.randint(0, 128, (total,), device="cuda"))
+
+ def run(fused: bool) -> torch.Tensor:
+ adapter = Qwen2FlashAdapter("unused", causal=True, fused_kernels=fused)
+ adapter._model = model
+ adapter._device = "cuda"
+ with torch.inference_mode():
+ return adapter._run_transformer_flash(hidden, cu_seqlens, max(lengths), total, position_ids)
+
+ assert torch.equal(run(fused=True), run(fused=False))