Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(server): fuse the ModernBERT flash RoPE for models as accurate against float32 (#424)
svonavaf18d6d5e1abf
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 0ae38a9fb..add2193d1 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -132,17 +132,26 @@ between the top two labels, and eager execution flips some near ties too,depending on which inputs share its batch.**When a speed-up ships enabled.** A shipped GLiClass profile enables a-speed-up that changes scores, such as `bucketed` graphs, only when both hold-against eager execution on the evaluation sets below:+speed-up that changes scores, such as `bucketed` graphs, only when, on the+evaluation sets below, both of the first two conditions hold against eager+execution, or the third holds against float32:1. no probability moves by more than 0.02;2. every answer whose top label changes had an eager top-two margin smallerthan eager's own regrouping noise, δ_eager: the largest probability changeeager execution makes on the same inputs when they share a batch with other- inputs.+ inputs;+3. against a float32 reference of the same checkpoint, the speed-up is at+ least as accurate as the current path: its largest change against float32+ is no larger than the current path's, and it changes no more top labels (or,+ for scores, reorders no more pairs) against float32 than the current path+ does.A top label that changes under the second condition was a near tie that eager-fp16 execution already flips under batching.+fp16 execution already flips under batching. The third condition admits a+speed-up that rounds differently from the current path, by more than eager's+own batching noise, but lands no farther from float32. The ModernBERT+adapters below apply the same rule to their scores.**Evaluation sets.** The main set is the 384 CVE descriptions from`examples/typed-decisions`, three questions each, asked one at a time, as@@ -528,6 +537,20 @@ three such shapes the model runs eagerly for the rest of the process. Eachmodel counts the forwards it replays, records and runs eagerly (by reason),and logs the counts every ten minutes while it serves requests.+**Fused rotary embedding.** The dense and late-interaction adapters rotate+queries and keys with about ten small PyTorch kernels per layer. With+`adapter_options.loadtime.fused_rope: true`, one Triton kernel per layer does+it instead, with flash-attn's rotary arithmetic (float32, rounded once, as+the Hugging Face flash-attention forward rotates): on an L4, 26.5 µs instead+of 178 µs per layer at 2,048 tokens. For the models below that is 1.13-1.18x+the speed of one-query requests (with CUDA graphs on both sides) and+1.17-1.22x the throughput of 64-abstract requests. Outputs change by rounding, more than the eager path's own batching+noise, so the option ships under the third condition of the rule above.+Against a float32 reference of each checkpoint, on the SciFact sets of the+graphs comparison, it is at least as accurate as the unfused rotation for+`modernbert-embed-base`, `Reason-ModernColBERT` and `mLateOn`, and their+profiles enable it. The other models load without it.+## Configuration`sie-server` reads its config from `SIE_*` environment variables (Pydanticdiff --git a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yamlindex 2a2095a6e..fbabce6ad 100644--- a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml+++ b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml@@ -33,6 +33,8 @@ profiles:skip_special_tokens: falsedoc_punctuation_skiplist: falsecuda_graphs: bucketed+ # At least as accurate as the unfused rotation against float32 (see the server README).+ fused_rope: trueruntime: {}muvera:extends: defaultdiff --git a/packages/sie_server/models/lightonai__mLateOn.yaml b/packages/sie_server/models/lightonai__mLateOn.yamlindex 3135bfd49..1542964da 100644--- a/packages/sie_server/models/lightonai__mLateOn.yaml+++ b/packages/sie_server/models/lightonai__mLateOn.yaml@@ -45,6 +45,8 @@ profiles:# The pinned recipe declares skiplist_words: [].doc_punctuation_skiplist: falsecuda_graphs: bucketed+ # At least as accurate as the unfused rotation against float32 (see the server README).+ fused_rope: true# No serving-time truncation override: preserve the pinned 8192-token# query/document recipe.runtime: {}diff --git a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yamlindex 8399d1492..e72b61c8e 100644--- a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml+++ b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml@@ -23,6 +23,8 @@ profiles:adapter_options:loadtime:cuda_graphs: bucketed+ # At least as accurate as the unfused rotation against float32 (see the server README).+ fused_rope: trueruntime:pooling: meannormalize: truediff --git a/packages/sie_server/src/sie_server/adapters/_modernbert_flash.py b/packages/sie_server/src/sie_server/adapters/_modernbert_flash.pyindex bd2661883..7a234933f 100644--- a/packages/sie_server/src/sie_server/adapters/_modernbert_flash.py+++ b/packages/sie_server/src/sie_server/adapters/_modernbert_flash.py@@ -15,6 +15,7 @@ from typing import Anyimport torch+from sie_server.adapters._packed_rope import packed_rope_available, rotate_packed_qkv_from sie_server.adapters._utils import apply_rotary_pos_emb# ModernBertConfig class defaults in transformers 4.x.@@ -74,6 +75,14 @@ def modernbert_rope_theta(config: Any, *, use_global: bool) -> float:return theta+def parse_fused_rope(value: object, *, adapter: str) -> bool:+ """The load-time ``fused_rope`` option: a boolean."""+ if isinstance(value, bool):+ return value+ msg = f"{adapter} fused_rope must be true or false, got {value!r}"+ raise ValueError(msg)++def modernbert_rope_cos_sin(position_ids: torch.Tensor,*,@@ -105,6 +114,7 @@ def run_modernbert_flash_layers(local_sin: torch.Tensor,*,compute_dtype: torch.dtype | None = None,+ fused_rope: bool = False,) -> torch.Tensor:"""Run a ModernBERT layer stack over a packed batch with flash attention.@@ -113,6 +123,14 @@ def run_modernbert_flash_layers(with the global RoPE base; the rest use a sliding window of``local_attention`` tokens with the local RoPE base.+ Queries and keys are rotated with PyTorch elementwise operations in the+ projection dtype. With ``fused_rope``, on CUDA with Triton, one kernel per+ layer (``rotate_packed_qkv_``) rotates them in place instead: in float32+ and rounded once, which is flash-attn's rotary arithmetic, the one the+ Hugging Face ModernBERT flash-attention forward runs. It is faster, and+ its outputs differ by rounding; a model's profile opts in (see the server+ README), and elsewhere ``fused_rope`` changes nothing.+``compute_dtype`` lets a caller keep the residual stream (``hidden``) andthe layer norms in a wider type than the projections, the way mixedprecision autocast runs the reference forward: norm outputs are cast to@@ -129,6 +147,7 @@ def run_modernbert_flash_layers(total_tokens: ``cu_seqlens[-1]``.global_cos, global_sin, local_cos, local_sin: Per-token RoPE tables.compute_dtype: Dtype of the attention/MLP projections, or ``None``.+ fused_rope: Rotate queries and keys with the fused kernel where it runs.Returns:Hidden states ``[total_tokens, hidden_size]`` before ``final_norm``.@@ -147,6 +166,13 @@ def run_modernbert_flash_layers(local_window = getattr(cfg, "local_attention", -1)# flash_attn_varlen_func expects window_size as (left, right) tuplewindow = (local_window // 2, local_window // 2) if local_window > 0 else (-1, -1)+ # The fused rotation reads row i of the per-token cos/sin tables for token i.+ token_rows = (+ torch.arange(total_tokens, dtype=torch.int32, device=hidden.device)+ if fused_rope and packed_rope_available(hidden.device)+ else None+ )+ half = head_dim // 2for layer_idx, layer in enumerate(model.layers):is_global = (layer_idx % global_every_n == 0) if global_every_n > 1 else True@@ -159,12 +185,16 @@ def run_modernbert_flash_layers(# Fused QKV projectionqkv = layer.attn.Wqkv(normed_hidden)qkv = qkv.view(total_tokens, 3, num_heads, head_dim)- query = qkv[:, 0] # [total_tokens, num_heads, head_dim]- key = qkv[:, 1]- value = qkv[:, 2]- # Apply RoPE to Q and K (using layer-appropriate theta)- query, key = apply_rotary_pos_emb(query, key, cos, sin)+ # Apply RoPE to Q and K (using layer-appropriate theta). The tables'+ # two halves are equal (cos/sin of [freqs, freqs]); the fused kernel+ # reads the first.+ if token_rows is not None:+ rotate_packed_qkv_(qkv, token_rows, cos[:, :half].to(qkv.dtype), sin[:, :half].to(qkv.dtype))+ query, key = qkv[:, 0], qkv[:, 1] # [total_tokens, num_heads, head_dim]+ else:+ query, key = apply_rotary_pos_emb(qkv[:, 0], qkv[:, 1], cos, sin)+ value = qkv[:, 2]# Flash attention — global layers use full attention,# local layers use sliding windowdiff --git a/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.pyindex 998a38275..32e164029 100644--- a/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py+++ b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py@@ -245,14 +245,17 @@ def graph_runner()-def modernbert_encoder(model: Any, *, window: int, dtype: torch.dtype) -> tuple[EncodeFn, list[torch.Tensor]]:+def modernbert_encoder(+ model: Any, *, window: int, dtype: torch.dtype, fused_rope: bool = False+) -> tuple[EncodeFn, list[torch.Tensor]]:"""The encoder a graph records for a Hugging Face ``ModernBertModel`` on the shared layer stack.Token embeddings (and their norm), ``run_modernbert_flash_layers`` and thefinal norm: what the dense and late-interaction adapters run eagerly.Eagerly they compute each forward's RoPE ``cos``/``sin`` rows from itspositions; here the rows are gathered from tables over the model window,- computed the same way, so they hold the same values.+ computed the same way, so they hold the same values. ``fused_rope`` goes to+ the layer stack, so a graph records the rotation its model runs eagerly.Returns:The encoder, and the RoPE tables it reads (for the runner's memory budget).@@ -292,6 +295,7 @@ def modernbert_encoder(model: Any, *, window: int, dtype: torch.dtype) -> tuple[global_sin[positions],local_cos[positions],local_sin[positions],+ fused_rope=fused_rope,)if hasattr(model, "final_norm"):hidden = model.final_norm(hidden)diff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.pyindex f5440d063..d8e10350e 100644--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/adapter.py@@ -14,6 +14,7 @@ from sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._modernbert_flash import (modernbert_rope_cos_sin,modernbert_rope_theta,+ parse_fused_rope,run_modernbert_flash_layers,)from sie_server.adapters._modernbert_flash_graphs import (@@ -90,6 +91,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):muvera_config: dict[str, Any] | None = None,revision: str | None = None,cuda_graphs: str | bool = "off",+ fused_rope: bool = False,**kwargs: Any,) -> None:"""Initialize the adapter.@@ -115,13 +117,20 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):replay the encoder as CUDA graphs (see``sie_server.adapters._modernbert_flash_graphs``). An operatorsetting, fixed at load.+ fused_rope: Whether queries and keys are rotated by one fused kernel+ on CUDA (see ``run_modernbert_flash_layers``) instead of+ PyTorch elementwise operations. An operator setting, fixed at+ load; a model's profile enables it only where it is at least as+ accurate against float32 (see the server README).**kwargs: Additional arguments (ignored).Raises:- ValueError: If ``cuda_graphs`` is not "off" or "bucketed".+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed", or+ ``fused_rope`` is not a boolean."""_ = kwargsself._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="ColBERTModernBERTFlashAdapter")+ self._fused_rope = parse_fused_rope(fused_rope, adapter="ColBERTModernBERTFlashAdapter")self._model_name_or_path = str(model_name_or_path)self._revision = revisionself._token_dim = token_dim@@ -216,8 +225,9 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):positions = getattr(model.config, "max_position_embeddings", None)if isinstance(positions, int) and positions > 0:window = min(window, positions)+ fused_rope = self._fused_ropereturn graph_runner(- lambda: modernbert_encoder(model, window=window, dtype=dtype),+ lambda: modernbert_encoder(model, window=window, dtype=dtype, fused_rope=fused_rope),mode=self._cuda_graphs,device=self._device,hidden_size=model.config.hidden_size,@@ -651,6 +661,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):global_sin,local_cos,local_sin,+ fused_rope=self._fused_rope,)def _split_embeddings(diff --git a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.pyindex 9e03ab4f5..9debb25af 100644--- a/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/modernbert_flash/__init__.py@@ -11,6 +11,7 @@ from sie_server.adapters._flash_base import FlashBaseAdapterfrom sie_server.adapters._modernbert_flash import (modernbert_rope_cos_sin,modernbert_rope_theta,+ parse_fused_rope,run_modernbert_flash_layers,)from sie_server.adapters._modernbert_flash_graphs import (@@ -72,6 +73,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):trust_remote_code: bool = True,revision: str | None = None,cuda_graphs: str | bool = "off",+ fused_rope: bool = False,**kwargs: Any,) -> None:"""Initialize the adapter.@@ -91,13 +93,20 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):replay the encoder as CUDA graphs (see``sie_server.adapters._modernbert_flash_graphs``). An operatorsetting, fixed at load.+ fused_rope: Whether queries and keys are rotated by one fused kernel+ on CUDA (see ``run_modernbert_flash_layers``) instead of+ PyTorch elementwise operations. An operator setting, fixed at+ load; a model's profile enables it only where it is at least as+ accurate against float32 (see the server README).**kwargs: Additional arguments (ignored, for compatibility).Raises:- ValueError: If ``cuda_graphs`` is not "off" or "bucketed".+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed", or+ ``fused_rope`` is not a boolean."""_ = kwargsself._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="ModernBERTFlashAdapter")+ self._fused_rope = parse_fused_rope(fused_rope, adapter="ModernBERTFlashAdapter")self._model_name_or_path = str(model_name_or_path)self._normalize = normalizeself._max_seq_length = max_seq_length@@ -176,9 +185,9 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):"""The CUDA graph runner for the loaded model; None when graphs are off."""if self._device is None or self._tokenizer is None:return None- model, window = self._model, self._max_seq_length+ model, window, fused_rope = self._model, self._max_seq_length, self._fused_ropereturn graph_runner(- lambda: modernbert_encoder(model, window=window, dtype=dtype),+ lambda: modernbert_encoder(model, window=window, dtype=dtype, fused_rope=fused_rope),mode=self._cuda_graphs,device=self._device,hidden_size=model.config.hidden_size,@@ -460,6 +469,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):global_sin,local_cos,local_sin,+ fused_rope=self._fused_rope,)def _pool_embeddings(diff --git a/packages/sie_server/tests/adapters/test_modernbert_flash_rope.py b/packages/sie_server/tests/adapters/test_modernbert_flash_rope.pynew file mode 100644index 000000000..e952931e2--- /dev/null+++ b/packages/sie_server/tests/adapters/test_modernbert_flash_rope.py@@ -0,0 +1,225 @@+"""The shared ModernBERT layer stack rotates queries and keys with one fused kernel where a model opts in.++On CPU the tests stand a PyTorch reference in for the kernel and for+flash-attn's varlen attention, so they check what the stack hands the+kernel: the per-token cos/sin rows, the first half of each table, and the+queries and keys it then attends with. The ``gpu_hw`` test checks the fused+stack against the same loop rotated by flash-attn's own rotary kernel, bit for+bit.+"""++from __future__ import annotations++import sys+import types+from itertools import pairwise+from pathlib import Path+from typing import Any++import pytest+import torch+from sie_server.adapters import _modernbert_flash as stack+from sie_server.adapters import _modernbert_flash_graphs as graphs_module+from sie_server.adapters._modernbert_flash import parse_fused_rope+from sie_server.adapters.colbert_modernbert_flash.adapter import ColBERTModernBERTFlashAdapter+from sie_server.adapters.modernbert_flash import ModernBERTFlashAdapter+from sie_server.core.loader import load_model_configs, reject_unknown_loadtime_options+from torch.nn import functional+from transformers import ModernBertConfig, ModernBertModel+++def _reference_varlen(query, key, value, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, **kwargs):+ out = torch.empty_like(query)+ window = kwargs.get("window_size", (-1, -1))+ for start, end in pairwise(cu_seqlens_q.tolist()):+ rows = [t[start:end].transpose(0, 1) for t in (query, key, value)]+ mask = None+ if window != (-1, -1):+ positions = torch.arange(end - start)+ mask = (positions[:, None] - positions[None, :]).abs() <= window[0]+ out[start:end] = functional.scaled_dot_product_attention(+ *rows, attn_mask=mask, scale=kwargs.get("softmax_scale")+ ).transpose(0, 1)+ return out+++def _model() -> ModernBertModel:+ torch.manual_seed(0)+ config = ModernBertConfig(+ vocab_size=64,+ hidden_size=64,+ intermediate_size=96,+ num_hidden_layers=3,+ num_attention_heads=2,+ global_attn_every_n_layers=3,+ local_attention=8,+ max_position_embeddings=128,+ pad_token_id=0,+ attn_implementation="eager",+ )+ return ModernBertModel(config).eval()+++def _inputs(lengths: list[int]) -> tuple[torch.Tensor, ...]:+ total = sum(lengths)+ cu = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()], dtype=torch.int32)+ positions = torch.cat([torch.arange(n) for n in lengths])+ tables = [+ t+ for theta in (160000.0, 10000.0)+ for t in stack.modernbert_rope_cos_sin(positions, head_dim=32, theta=theta, dtype=torch.float32)+ ]+ return (torch.randn(total, 64), cu, max(lengths), total, *tables)++[email protected](("available", "fused_rope"), [(False, True), (True, False)], ids=["off-cuda", "not-opted-in"])+def test_the_stack_rotates_with_pytorch_operations_unless_fused_where_it_runs(+ monkeypatch: pytest.MonkeyPatch, available: bool, fused_rope: bool+) -> None:+ monkeypatch.setitem(sys.modules, "flash_attn", types.SimpleNamespace(flash_attn_varlen_func=_reference_varlen))+ monkeypatch.setattr(stack, "packed_rope_available", lambda device: available)++ def unexpected(*args: object) -> None:+ raise AssertionError("the fused kernel runs only when opted in, on CUDA")++ monkeypatch.setattr(stack, "rotate_packed_qkv_", unexpected)+ model, args = _model(), _inputs([3, 9, 1])+ with torch.inference_mode():+ stack.run_modernbert_flash_layers(model, *args, fused_rope=fused_rope)+++def test_the_kernel_gets_each_tokens_row_and_the_tables_first_half(monkeypatch: pytest.MonkeyPatch) -> None:+ """With a PyTorch stand-in for the kernel, the fused stack matches the unfused one (float32)."""+ monkeypatch.setitem(sys.modules, "flash_attn", types.SimpleNamespace(flash_attn_varlen_func=_reference_varlen))+ calls: list[tuple[int, int]] = []++ def rotate(qkv: torch.Tensor, rows: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> None:+ calls.append((rows.shape[0], cos.shape[-1]))+ assert torch.equal(rows, torch.arange(qkv.shape[0], dtype=torch.int32))+ half = cos.shape[-1]+ x0, x1 = qkv[:, :2, :, :half], qkv[:, :2, :, half:]+ c, s = cos[rows.long()][:, None, None, :], sin[rows.long()][:, None, None, :]+ qkv[:, :2] = torch.cat([x0 * c - x1 * s, x0 * s + x1 * c], dim=-1)++ model, args = _model(), _inputs([3, 9, 1, 20])+ with torch.inference_mode():+ unfused = stack.run_modernbert_flash_layers(model, *args)+ monkeypatch.setattr(stack, "packed_rope_available", lambda device: True)+ monkeypatch.setattr(stack, "rotate_packed_qkv_", rotate)+ fused = stack.run_modernbert_flash_layers(model, *args, fused_rope=True)+ assert calls == [(33, 16)] * 3+ torch.testing.assert_close(fused, unfused, atol=1e-5, rtol=1e-5)+++def test_the_shared_layer_stack_rotates_with_flash_attn_arithmetic(monkeypatch: pytest.MonkeyPatch) -> None:+ """``run_modernbert_flash_layers`` on CUDA: flash-attn's rotation of every token, bit for bit."""+ if not torch.cuda.is_available():+ pytest.skip("requires CUDA")+ rotary = pytest.importorskip("flash_attn.ops.triton.rotary")++ torch.manual_seed(0)+ config = ModernBertConfig(+ vocab_size=64,+ hidden_size=128,+ intermediate_size=192,+ num_hidden_layers=3,+ num_attention_heads=2,+ global_attn_every_n_layers=3,+ local_attention=16,+ max_position_embeddings=512,+ pad_token_id=0,+ attn_implementation="eager",+ )+ model = ModernBertModel(config).eval().to("cuda", torch.bfloat16)+ lengths = [5, 200, 1, 64]+ total = sum(lengths)+ cu = torch.tensor([0, *torch.tensor(lengths).cumsum(0).tolist()], dtype=torch.int32, device="cuda")+ positions = torch.cat([torch.arange(n, device="cuda") for n in lengths])+ tables = [+ stack.modernbert_rope_cos_sin(positions, head_dim=64, theta=theta, dtype=torch.bfloat16)+ for theta in (160000.0, 10000.0)+ ]+ hidden = torch.randn(total, 128, device="cuda", dtype=torch.bfloat16)++ def run(*, fused_rope: bool) -> torch.Tensor:+ with torch.inference_mode():+ return stack.run_modernbert_flash_layers(+ model, hidden, cu, max(lengths), total, *tables[0], *tables[1], fused_rope=fused_rope+ )++ fused = run(fused_rope=True)+ unfused = run(fused_rope=False)++ def flash_rotation(query, key, cos, sin):+ qk = torch.stack([query, key], dim=1).contiguous().view(1, total, -1, 64)+ half = cos.shape[-1] // 2+ rotary.apply_rotary(qk, cos[:, :half].contiguous(), sin[:, :half].contiguous(), inplace=True)+ qk = qk.view(total, 2, -1, 64)+ return qk[:, 0], qk[:, 1]++ monkeypatch.setattr(stack, "apply_rotary_pos_emb", flash_rotation)+ assert torch.equal(fused, run(fused_rope=False))+ # the unfused rotation rounds three times, so it differs from the fused one, but only by rounding+ assert not torch.equal(fused, unfused)+ cosine = torch.nn.functional.cosine_similarity(fused.float(), unfused.float(), dim=-1)+ assert cosine.min() > 0.99+++# -- the per-model option ----------------------------------------------------------++_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+_ADAPTERS = (ModernBERTFlashAdapter, ColBERTModernBERTFlashAdapter)+# The shipped models whose profiles enable the fused rotation: those at least as+# accurate as the unfused one against float32 (see the server README).+_FUSED_BY_DEFAULT = {+ "nomic-ai/modernbert-embed-base",+ "lightonai/Reason-ModernColBERT",+ "lightonai/mLateOn",+}++[email protected]("adapter", _ADAPTERS)+def test_fused_rope_is_a_boolean_load_time_option(adapter: Any) -> None:+ reject_unknown_loadtime_options(adapter, {"fused_rope": True}, model_name="m")+ assert adapter("m")._fused_rope is False+ assert adapter("m", fused_rope=True)._fused_rope is True+ for value in ("true", 1, None):+ with pytest.raises(ValueError, match="fused_rope must be true or false"):+ adapter("m", fused_rope=value)++[email protected]("adapter", _ADAPTERS)[email protected]("fused_rope", [False, True])+def test_the_adapters_pass_their_option_to_the_stack(+ monkeypatch: pytest.MonkeyPatch, adapter: Any, fused_rope: bool+) -> None:+ seen: list[bool] = []++ def layers(model: Any, hidden: torch.Tensor, *args: Any, fused_rope: bool = False, **kwargs: Any) -> torch.Tensor:+ seen.append(fused_rope)+ return hidden++ monkeypatch.setattr(sys.modules[adapter.__module__], "run_modernbert_flash_layers", layers)+ monkeypatch.setattr(graphs_module, "run_modernbert_flash_layers", layers)+ instance = adapter("m", fused_rope=fused_rope)+ instance._model = _model()+ hidden = torch.zeros(4, 64)+ instance._run_transformer_flash(hidden, torch.tensor([0, 4], dtype=torch.int32), 4, 4, *_inputs([4])[4:])+ encode, _ = graphs_module.modernbert_encoder(+ instance._model, window=8, dtype=torch.float32, fused_rope=instance._fused_rope+ )+ ids = torch.zeros(4, dtype=torch.int32)+ encode(ids, ids, torch.tensor([0, 4], dtype=torch.int32), 4, 4)+ assert seen == [fused_rope, fused_rope]+++def test_only_models_at_least_as_accurate_against_float32_ship_fused() -> None:+ fused = set()+ for config in load_model_configs(_MODELS_DIR).values():+ for name in config.profiles:+ profile = config.resolve_profile(name)+ if "fused_rope" in profile.loadtime:+ assert parse_fused_rope(profile.loadtime["fused_rope"], adapter=profile.adapter_path)+ fused.add(config.sie_id.split(":")[0])+ assert fused == _FUSED_BY_DEFAULT