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(server): replay ModernBERT flash forwards as CUDA graphs (#423)

svonava4c4c3a21eb07
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index 6f359036e..02eeceb89 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -389,6 +389,121 @@ space is read only in its last 4,096 characters, and reading stops there. An ite
not fit whole with `options={"overflow_policy": "error"}`, returns a per-item
`INPUT_TOO_LONG` error while the other items succeed.
+### ModernBERT CUDA graphs
+
+The ModernBERT flash-attention adapters, for dense embeddings
+(`modernbert_flash`), late interaction (`colbert_modernbert_flash`) and
+reranking (`modernbert_flash_cross_encoder`), run a packed, unpadded token
+stream through hundreds of small kernels per forward (about 500 for a
+22-layer encoder). At the sizes of a query
+or a few short documents, the host that launches those kernels is the
+bottleneck: on an L4, a one-query forward of `GTE-ModernColBERT-v1` keeps the
+GPU busy for about 2 ms of its 12. A CUDA graph records the launches of one
+shape once and replays them in one call. Graphs are an operator setting,
+fixed when the model loads:
+
+```yaml
+profiles:
+ default:
+ adapter_options:
+ loadtime:
+ cuda_graphs: bucketed
+```
+
+`off` (the default) runs every forward eagerly. With `bucketed`, a graph
+records the encoder (token embeddings, layers and final norm) for one packed
+shape: the token count padded up to 64, 128, 192, 256, 384, 512, 768, 1,024
+tokens and so on, a fixed number of sequence slots, and `max_seqlen` 512 (or
+the bucket, when a row is longer). Padding tokens belong to no sequence, so
+real rows attend only to their own tokens, as eagerly. The adapter's head
+(pooling, the late-interaction projection or the reranking head) runs
+eagerly on the real rows. Forwards past a token bound run eagerly: 2,048
+tokens for encoders up to 384 wide, 1,024 up to 768, 512 wider. Past that,
+the GPU rather than kernel launches bounds a forward, and padding to the
+bucket costs more than a graph saves. A model with LoRA adapters loaded runs
+eagerly, because its forward depends on which adapter is active.
+
+Speed on an NVIDIA L4 with 8 vCPUs, eager and graphs in one process with
+their requests interleaved (median latency, and items per second over the
+run). SciFact queries and abstracts; documents are cut at the profile's
+length (300 tokens for `GTE-ModernColBERT-v1`, 512 for
+`mxbai-edge-colbert-v0-32m`):
+
+| Model | 1 query | 8 queries | 1 document | Larger requests |
+|--|--|--|--|--|
+| `GTE-ModernColBERT-v1` | 18.1 → 2.6 ms | 360 → 1,857/s | 22.3 → 5.1 ms | within 2% |
+| `gte-modernbert-base` | 17.5 → 2.4 ms | 378 → 2,414/s | 21.4 → 4.3 ms | within 1% |
+| `mxbai-edge-colbert-v0-32m` | 9.2 → 1.1 ms | 658 → 3,345/s | 12.1 → 2.8 ms | within 2% |
+| `granite-embedding-small-english-r2` | 10.4 → 1.2 ms | 581 → 4,551/s | 14.0 → 2.4 ms | within 2% |
+| `gte-reranker-modernbert-base` | 1 pair: 17.3 → 4.3 ms | 8 short pairs: 351 → 1,307/s | | within 2% |
+
+"Larger requests" are 8 and 64 abstracts, 32 items of mixed lengths, and 8
+or 32 (query, abstract) pairs: about 2,000 to 16,000 packed tokens, mostly
+past the token bound. The eager side depends on the host's CPU: on another L4
+host with faster cores, a one-query `GTE-ModernColBERT-v1` forward took
+12.2 ms eagerly and 2.5 ms from a graph.
+
+Padding changes how many rows a matrix multiply sees, so outputs can move by
+floating-point rounding, as batching requests together does. We compared
+graphs with eager forwards on SciFact: the 300 test queries, 500 abstracts
+(every one relevant to those queries, and random others) and, for the
+reranker, 20 abstracts per query. Items were encoded one per request, on
+both paths, and the eager path was also run with 8 queries or 4 abstracts
+(3 pairs) per request, which is its own batching noise. Scores are query–
+document dot products for dense models and MaxSim for late interaction:
+
+| Model | Graphs: largest score change | Graphs: pairs reordered in a top 10 (largest eager margin of any reordered pair) | Eager batching: largest score change (largest margin of a reordered pair) |
+|--|--|--|--|
+| `GTE-ModernColBERT-v1` | none (bit-identical) | none | 0.013 (0.018) |
+| `mxbai-edge-colbert-v0-32m` | none (bit-identical) | none | 0.13 (0.23) |
+| `gte-modernbert-base` | 0.006 | 12 (0.008) | 0.008 (0.012) |
+| `granite-embedding-small-english-r2` | 0.004 | 16 (0.005) | 0.015 (0.014) |
+| `gte-reranker-modernbert-base` | 0.015 | 21 (0.006) | 0.025 (0.019) |
+| `modernbert-embed-base` | 0.004 | 10 (0.004) | 0.005 (0.006) |
+| `granite-embedding-97m-multilingual-r2` | 0.006 | 57 (0.008) | 0.015 (0.015) |
+| `Reason-ModernColBERT` | 0.007 | 1 (0.007) | 0.022 (0.021) |
+| `mLateOn` | 0.020 | 17 (0.029) | 0.037 (0.046) |
+| `Iso-ModernColBERT` | 0.047 | 19 (0.058) | 0.082 (0.100) |
+
+Graphs meet the rule a GLiClass speed-up ships under (see "When a speed-up
+ships enabled" above), read for scores instead of label probabilities: no
+score moves by more than 0.02 (for MaxSim, which sums over a query's tokens,
+0.02 per query token), and every pair that graphs reorder had an eager margin
+smaller than the eager path's own batching noise, the largest score change
+eager execution makes when the same items share a request with others. For
+embeddings, the rule reads on the retrieval order the vectors give, and the
+vectors stay as close to eager as eager batching keeps them (cosine at least
+0.9997 for the dense models). Retrieval quality on the
+full SciFact corpus (5,183 abstracts, nDCG@10, the same requests on both
+paths) did not change beyond that noise: `gte-modernbert-base` 0.7632 eager
+and 0.7644 with graphs, `GTE-ModernColBERT-v1` 0.7573 and 0.7558, and
+`gte-reranker-modernbert-base` reranking the top 20 of `gte-modernbert-base`
+0.7760 and 0.7767.
+
+The shipped profiles of every model on these adapters load with `bucketed`
+graphs: `GTE-ModernColBERT-v1`, `Reason-ModernColBERT`, `mLateOn`,
+`Iso-ModernColBERT`, `mxbai-edge-colbert-v0-32m`, `gte-modernbert-base`,
+`modernbert-embed-base`, `granite-embedding-small-english-r2`,
+`granite-embedding-97m-multilingual-r2` and `gte-reranker-modernbert-base`.
+To run one of them eagerly, set `cuda_graphs: off` in its profile. A Candle
+profile of these models sets its own load-time options, so it does not
+inherit the setting.
+
+A graph is recorded the first time a request needs its shape (the dense
+adapter's warm-up records the smallest at load), and that request is answered
+by its first replay. Recording follows the rules of the GLiClass graphs above,
+and shares their process-wide limits: one recording at a time in the process,
+none while less than a tenth of the device's memory is free, at most 16
+recordings at once and then one per 2 seconds, and a model's graphs within
+4% of the device's memory (900 MB on an L4). A model's graphs, which share
+one memory pool and one output buffer, held 40 to 105 MB on an L4 once every
+shape its traffic needed was recorded. A recording that runs out of memory
+drops the model's graphs and pauses recording for a minute; a shape that
+fails to record for another reason runs eagerly from then on, and after
+three such shapes the model runs eagerly for the rest of the process. Each
+model counts the forwards it replays, records and runs eagerly (by reason),
+and logs the counts every ten minutes while it serves requests.
+
## Configuration
`sie-server` reads its config from `SIE_*` environment variables (Pydantic
diff --git a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml
index 8b4651c39..3ede8f010 100644
--- a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml
+++ b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml
@@ -21,7 +21,8 @@ profiles:
compute_precision: bfloat16
adapter_path: sie_server.adapters.modernbert_flash:ModernBERTFlashAdapter
adapter_options:
- loadtime: {}
+ loadtime:
+ cuda_graphs: bucketed
runtime:
pooling: cls
normalize: true
@@ -29,6 +30,10 @@ profiles:
extends: default
adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter
adapter_options:
+ # Its own load-time options, so the default profile's cuda_graphs (a
+ # PyTorch setting) does not reach the Candle worker, which refuses it.
+ loadtime:
+ max_seq_length: 8192
runtime:
pooling: cls
normalize: true
diff --git a/packages/sie_server/models/Alibaba-NLP__gte-reranker-modernbert-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-reranker-modernbert-base.yaml
index 07c041805..7d4abc348 100644
--- a/packages/sie_server/models/Alibaba-NLP__gte-reranker-modernbert-base.yaml
+++ b/packages/sie_server/models/Alibaba-NLP__gte-reranker-modernbert-base.yaml
@@ -19,4 +19,5 @@ profiles:
adapter_options:
loadtime:
trust_remote_code: true
+ cuda_graphs: bucketed
runtime: {}
diff --git a/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml
index 28f130f12..b9399ada5 100644
--- a/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml
+++ b/packages/sie_server/models/ibm-granite__granite-embedding-97m-multilingual-r2.yaml
@@ -24,7 +24,8 @@ profiles:
# Standard HF ModernBERT safetensors checkpoint, not an open_clip-format
# one: config.json claims architectures ["ModernBertModel"] / model_type
# "modernbert", so no open_clip backend loadtime options apply.
- loadtime: {}
+ loadtime:
+ cuda_graphs: bucketed
runtime:
# 1_Pooling/config.json claim: {"pooling_mode_cls_token": true}
pooling: cls
diff --git a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml
index 49f246dd3..dbb113e06 100644
--- a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml
+++ b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml
@@ -21,7 +21,8 @@ profiles:
compute_precision: bfloat16
adapter_path: sie_server.adapters.modernbert_flash:ModernBERTFlashAdapter
adapter_options:
- loadtime: {}
+ loadtime:
+ cuda_graphs: bucketed
runtime:
pooling: cls
normalize: true
@@ -29,6 +30,10 @@ profiles:
extends: default
adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter
adapter_options:
+ # Its own load-time options, so the default profile's cuda_graphs (a
+ # PyTorch setting) does not reach the Candle worker, which refuses it.
+ loadtime:
+ max_seq_length: 8192
runtime:
pooling: cls
normalize: true
diff --git a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
index bc9d29ffc..1534f1f7c 100644
--- a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
+++ b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml
@@ -35,6 +35,7 @@ profiles:
query_prefix: '[Q] '
doc_prefix: '[D] '
doc_punctuation_skiplist: true
+ cuda_graphs: bucketed
runtime:
# Published MTEB recipe at the revision used by the governed targets.
query_max_length: 48
diff --git a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml
index 5a29a2dd7..2a2095a6e 100644
--- a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml
+++ b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml
@@ -32,6 +32,7 @@ profiles:
query_max_length: 32
skip_special_tokens: false
doc_punctuation_skiplist: false
+ cuda_graphs: bucketed
runtime: {}
muvera:
extends: default
diff --git a/packages/sie_server/models/lightonai__mLateOn.yaml b/packages/sie_server/models/lightonai__mLateOn.yaml
index 92d3fccc0..3135bfd49 100644
--- a/packages/sie_server/models/lightonai__mLateOn.yaml
+++ b/packages/sie_server/models/lightonai__mLateOn.yaml
@@ -44,6 +44,7 @@ profiles:
skip_special_tokens: false
# The pinned recipe declares skiplist_words: [].
doc_punctuation_skiplist: false
+ cuda_graphs: bucketed
# No serving-time truncation override: preserve the pinned 8192-token
# query/document recipe.
runtime: {}
diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
index 6d9c13a0e..fd9138323 100644
--- a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
+++ b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml
@@ -35,6 +35,7 @@ profiles:
query_prefix: '[Q] '
doc_prefix: '[D] '
doc_punctuation_skiplist: true
+ cuda_graphs: bucketed
runtime:
muvera: null
query_max_length: 48
diff --git a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml
index 735573874..8399d1492 100644
--- a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml
+++ b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml
@@ -21,7 +21,8 @@ profiles:
compute_precision: bfloat16
adapter_path: sie_server.adapters.modernbert_flash:ModernBERTFlashAdapter
adapter_options:
- loadtime: {}
+ loadtime:
+ cuda_graphs: bucketed
runtime:
pooling: mean
normalize: true
@@ -31,6 +32,10 @@ profiles:
extends: default
adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter
adapter_options:
+ # Its own load-time options, so the default profile's cuda_graphs (a
+ # PyTorch setting) does not reach the Candle worker, which refuses it.
+ loadtime:
+ max_seq_length: 8192
runtime:
pooling: mean
normalize: true
diff --git a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
index 3ea428ca3..c81a0006b 100644
--- a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
+++ b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml
@@ -27,6 +27,7 @@ profiles:
query_max_length: 32
skip_special_tokens: false
doc_punctuation_skiplist: false
+ cuda_graphs: bucketed
runtime: {}
candle:
extends: default
diff --git a/packages/sie_server/src/sie_server/adapters/_cuda_graphs.py b/packages/sie_server/src/sie_server/adapters/_cuda_graphs.py
new file mode 100644
index 000000000..3479dcd68
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/_cuda_graphs.py
@@ -0,0 +1,69 @@
+"""Process-wide pieces shared by the CUDA graph runners.
+
+A runner records the kernel launches of a forward once per input shape and
+replays them with one call. Two runners exist: the GLiClass DeBERTa encoder
+(``gliclass/cuda_graphs.py``) and the ModernBERT flash-attention varlen
+encoders (``_modernbert_flash_graphs.py``). They record different forwards,
+but they share one device and one caching allocator, so these rules hold
+across every runner in the process:
+
+- at most one recording at a time (``RECORDING_LOCK``): while a graph is
+ being recorded, PyTorch's caching allocator will not free cached blocks to
+ satisfy another allocation, so another model on the same GPU could run out
+ of memory;
+- no recording while less than a tenth of the device's memory is free;
+- a runner's graphs hold at most 4% of the device's memory.
+"""
+
+from __future__ import annotations
+
+import threading
+from dataclasses import dataclass, field
+
+import torch
+
+# One recording at a time in the process, across every model's runner.
+RECORDING_LOCK = threading.Lock()
+# Recording waits until at least this share of the device's memory is free.
+RECORDING_HEADROOM = 0.1
+# Device memory a runner's graphs may hold, as a share of the device's memory.
+MEMORY_BUDGET_SHARE = 0.04
+
+
+@dataclass
+class CudaGraphStats:
+ """Counters of the forwards a runner was offered since the model loaded.
+
+ Each forward counts once: ``replayed`` (a recorded graph served it),
+ ``recorded`` (it recorded a graph and was answered by the first replay)
+ or under ``eager`` by why it ran eagerly. Requests that opt out of graphs
+ are not offered to the runner. ``recording_failures`` counts shapes that
+ failed to record for reasons other than memory; ``drops`` counts the times
+ every graph was dropped (out of memory, or over the memory budget).
+ """
+
+ replayed: int = 0
+ recorded: int = 0
+ eager: dict[str, int] = field(default_factory=dict)
+ recording_failures: int = 0
+ drops: int = 0
+
+ @property
+ def forwards(self) -> int:
+ return self.replayed + self.recorded + sum(self.eager.values())
+
+
+def free_memory(device: torch.device) -> int:
+ """Free device memory in bytes."""
+ return torch.cuda.mem_get_info(device)[0]
+
+
+def has_headroom(device: torch.device) -> bool:
+ """Whether enough device memory is free to record without starving other models."""
+ free, total = torch.cuda.mem_get_info(device)
+ return free >= RECORDING_HEADROOM * total
+
+
+def memory_budget(device: torch.device) -> int:
+ """Device memory one runner's graphs may hold."""
+ return int(MEMORY_BUDGET_SHARE * torch.cuda.mem_get_info(device)[1])
diff --git a/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py
new file mode 100644
index 000000000..5d73ead03
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py
@@ -0,0 +1,717 @@
+"""CUDA graphs for the ModernBERT flash-attention varlen encoders.
+
+The ModernBERT flash adapters (dense embeddings, late interaction and
+cross-encoder reranking) pack a batch into one unpadded token stream and run
+it through ``flash_attn_varlen_func``. A forward launches about 500 kernels
+(some 23 per layer), and PyTorch spends roughly 20 microseconds of host time
+on each. So below a few thousand packed tokens the GPU waits on the host that
+launches them: on an L4, a one-query forward of a 22-layer, 768-wide encoder
+keeps the GPU busy for 2 ms of its 12. A CUDA graph records those launches
+once for one shape and replays them with one call.
+
+Graphs are an operator setting, fixed when the model loads
+(``adapter_options.loadtime.cuda_graphs: bucketed``).
+
+What a graph holds. A graph records the encoder: the token embeddings and
+their norm, the layers and the final norm, for one packed shape. The
+adapter's own head (pooling, the late-interaction projection or the reranking
+head) runs eagerly on the real rows of the graph's output, as it does after
+an eager forward.
+
+Shapes. A varlen forward has three shapes that vary: the packed token count,
+the number of sequences and ``max_seqlen``. A graph fixes all three:
+
+- the token count is padded up to a bucket: 64, 128 and the powers of two
+ above it, with a midpoint (1.5 times) between each, up to a token bound;
+- the sequences get a fixed number of slots, one per 16 tokens of the bucket
+ (at least 8, at most 128). The real rows fill the first slots; the others
+ are empty sequences. A forward with more rows than its bucket's slots uses
+ a larger bucket;
+- ``max_seqlen`` is 512 when every row fits in it, and the bucket otherwise.
+ flash-attn launches a block per 128 query positions per slot per head
+ whether or not a sequence fills it, so a graph for short rows launches
+ fewer.
+
+Padding tokens belong to no sequence: ``cu_seqlens`` ends at the real token
+count. flash-attn never reads or writes their rows, and every other step of
+the encoder (embedding lookup, norms, projections, the rotary embedding, the
+MLP) works on each token alone, so no padding row reaches a real one, and
+real rows attend exactly to their own tokens as eagerly. What changes is the
+number of rows a matrix multiply sees, and with it the kernel cuBLAS picks
+and the order it sums in: the same kind of change that batching requests
+together makes. Outputs move by floating-point rounding (see the README).
+
+The token bound depends on the encoder's width. Past about that many tokens
+the GPU, not kernel launches, bounds a forward: a graph saves little, and
+padding to the bucket can cost more than it saves. The bound is 2,048 tokens
+up to 384 wide, 1,024 up to 768 and 512 wider (GPU time per token grows with
+the square of the width, kernel launches do not). On an L4, a graph of a
+768-wide, 22-layer encoder is 3.8-5.7x as fast as an eager forward up to 256
+tokens, 1.4-1.6x at 1,024, and at 1,200 tokens padded to 1,536 it is slower
+(0.9x); a 384-wide one still gains 1.25x at 2,048. Larger forwards run
+eagerly.
+
+Recording follows the GLiClass DeBERTa graphs (``gliclass/cuda_graphs.py``)
+and shares their process-wide rules (``_cuda_graphs.py``): one recording at a
+time in the process, none while less than a tenth of the device's memory is
+free, at most 16 recordings at once and then one per 2 seconds, and the
+graphs of one model within 4% of the device's memory. The set of shapes is
+fixed, so when a model's graphs reach that budget the runner stops recording
+and keeps replaying the graphs it has. A shape is recorded the first time a
+forward needs it (the dense adapter's warm-up forward, at load, records the
+smallest), and the new graph's first replay answers that forward. A
+recording that runs out of memory drops every graph and pauses recording for
+a minute. A shape whose recording or first replay fails for any other reason
+is not recorded again, and after three such shapes the runner turns graphs
+off for the process. The adapter's head is not part of that count: its
+errors fail the forward alone, as they would eagerly.
+
+Replays never overlap: a lock serializes them, and each replay's output is
+read by the adapter's head before the next replay. The runner counts every
+forward it is offered (``CudaGraphStats``) and logs the counts every ten
+minutes while it serves forwards.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import threading
+import time
+from collections import OrderedDict
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+from typing import Any, Literal, TypeVar, cast
+
+import numpy as np
+import torch
+
+from sie_server.adapters._cuda_graphs import (
+ RECORDING_LOCK,
+ CudaGraphStats,
+ free_memory,
+ has_headroom,
+ memory_budget,
+)
+from sie_server.adapters._modernbert_flash import (
+ modernbert_rope_cos_sin,
+ modernbert_rope_theta,
+ run_modernbert_flash_layers,
+)
+from sie_server.core.oom import is_oom_error
+
+logger = logging.getLogger(__name__)
+
+GraphMode = Literal["off", "bucketed"]
+GRAPH_MODES: tuple[GraphMode, ...] = ("off", "bucketed")
+
+# The smallest bucket, and the first to get a midpoint above it.
+_MIN_TOKENS = 64
+_FIRST_MIDPOINT = 128
+# Sequence slots: one per this many tokens of the bucket, within these bounds.
+_TOKENS_PER_SLOT = 16
+_MIN_SLOTS = 8
+_MAX_SLOTS = 128
+# ``max_seqlen`` of a graph for rows that all fit in it.
+_SHORT_ROWS = 512
+# A runner may record this many graphs at once, then one per this many seconds.
+_RECORDING_BURST = 16
+_SECONDS_PER_RECORDING = 2.0
+# After a recording runs out of memory, the runner records nothing for this long.
+_OOM_COOL_DOWN_SECONDS = 60.0
+# Shapes that may fail to record, for reasons other than memory, before the
+# runner turns graphs off for the process.
+_MAX_RECORDING_FAILURES = 3
+# A runner serving forwards logs its counters this often.
+_SUMMARY_SECONDS = 600.0
+
+# (padded token count, max_seqlen)
+Key = tuple[int, int]
+# Why a forward the runner was offered ran eagerly.
+EagerReason = Literal[
+ "empty", # no tokens
+ "too_long", # a row longer than the model window
+ "too_large", # past the token bound, or more rows than any bucket has slots
+ "disabled", # graphs turned off for the process after recording failures
+ "failed_shape", # the shape failed to record before
+ "budget_full", # the memory budget holds no more graphs
+ "recording_paused", # out of recording credit, or cooling down after an out-of-memory error
+ "no_headroom", # too little free device memory to record
+ "busy", # another model's runner is recording
+ "recording_failed", # this forward's recording failed
+]
+
+# The encoder a graph records: (token ids, positions, cu_seqlens, max_seqlen,
+# total tokens) -> hidden states ``[total tokens, hidden]``. Ids, positions
+# and cu_seqlens are int32 device tensors.
+EncodeFn = Callable[[torch.Tensor, torch.Tensor, torch.Tensor, int, int], torch.Tensor]
+T = TypeVar("T")
+
+
+def token_bound(hidden_size: int) -> int:
+ """Packed tokens a graph of an encoder with this hidden size may hold."""
+ if hidden_size <= 384:
+ return 2048
+ if hidden_size <= 768:
+ return 1024
+ return 512
+
+
+def token_buckets(max_tokens: int) -> tuple[int, ...]:
+ """Packed-token sizes graphs hold: 64, 128, 192, 256, 384, 512, 768, ... up to ``max_tokens``."""
+ sizes: list[int] = []
+ size = _MIN_TOKENS
+ while size <= max_tokens:
+ sizes.append(size)
+ midpoint = size * 3 // 2
+ if size >= _FIRST_MIDPOINT and midpoint <= max_tokens:
+ sizes.append(midpoint)
+ size *= 2
+ return tuple(sizes)
+
+
+def row_slots(tokens: int) -> int:
+ """Sequence slots of a graph holding this many tokens."""
+ return min(_MAX_SLOTS, max(_MIN_SLOTS, tokens // _TOKENS_PER_SLOT))
+
+
+def seqlen_buckets(tokens: int, window: int) -> tuple[int, ...]:
+ """The ``max_seqlen`` values graphs of this token bucket are recorded with."""
+ longest = min(tokens, window)
+ short = min(_SHORT_ROWS, longest)
+ return (short,) if short == longest else (short, longest)
+
+
+def bucketed_shapes(max_tokens: int, window: int) -> frozenset[Key]:
+ """Every shape a runner can record."""
+ return frozenset(
+ (tokens, seqlen) for tokens in token_buckets(max_tokens) for seqlen in seqlen_buckets(tokens, window)
+ )
+
+
+def unsupported_reason(device: str | torch.device) -> str | None:
+ """Why graphs cannot run on ``device``; None when they can."""
+ if not str(device).startswith("cuda"):
+ return "CUDA graphs need a CUDA device"
+ if not torch.cuda.is_available():
+ return "CUDA is not available"
+ return None
+
+
+def parse_graph_mode(value: object, *, adapter: str) -> GraphMode:
+ """The load-time ``cuda_graphs`` option; YAML reads an unquoted ``off`` as False."""
+ if value is False:
+ return "off"
+ if isinstance(value, str) and value in GRAPH_MODES:
+ return cast("GraphMode", value)
+ msg = f"{adapter} cuda_graphs must be 'off' or 'bucketed', got {value!r}"
+ raise ValueError(msg)
+
+
+def graph_runner(
+ build: Callable[[], tuple[EncodeFn, Sequence[torch.Tensor]]],
+ *,
+ mode: GraphMode,
+ device: str,
+ hidden_size: int,
+ dtype: torch.dtype,
+ window: int,
+ pad_token_id: int | None,
+ name: str,
+) -> VarlenGraphRunner | None:
+ """A runner for a loaded model; None when graphs are off or the device cannot run them.
+
+ ``build`` returns the encoder a graph records and the tensors it reads
+ (RoPE tables), counted against the runner's memory budget.
+ """
+ if mode == "off":
+ return None
+ reason = unsupported_reason(device)
+ if reason is not None:
+ logger.warning("ModernBERT cuda_graphs=%s does not apply to %s, which runs eagerly: %s", mode, name, reason)
+ return None
+ encode, static_tensors = build()
+ return VarlenGraphRunner(
+ encode,
+ hidden_size=hidden_size,
+ dtype=dtype,
+ device=device,
+ window=window,
+ pad_token_id=pad_token_id or 0,
+ static_tensors=static_tensors,
+ name=name,
+ )
+
+
+def modernbert_encoder(model: Any, *, window: int, dtype: torch.dtype) -> 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 the
+ final norm: what the dense and late-interaction adapters run eagerly.
+ Eagerly they compute each forward's RoPE ``cos``/``sin`` rows from its
+ positions; here the rows are gathered from tables over the model window,
+ computed the same way, so they hold the same values.
+
+ Returns:
+ The encoder, and the RoPE tables it reads (for the runner's memory budget).
+ """
+ config = model.config
+ weight = model.embeddings.tok_embeddings.weight
+ positions = torch.arange(window, device=weight.device)
+ head_dim = config.hidden_size // config.num_attention_heads
+ tables = {
+ kind: modernbert_rope_cos_sin(
+ positions,
+ head_dim=head_dim,
+ theta=modernbert_rope_theta(config, use_global=kind == "global"),
+ dtype=dtype,
+ )
+ for kind in ("global", "local")
+ }
+ global_cos, global_sin = tables["global"]
+ local_cos, local_sin = tables["local"]
+ embeddings = model.embeddings
+
+ def encode(
+ input_ids: torch.Tensor, positions: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int, total: int
+ ) -> torch.Tensor:
+ hidden = embeddings.tok_embeddings(input_ids)
+ if hasattr(embeddings, "norm"):
+ hidden = embeddings.norm(hidden)
+ if hasattr(embeddings, "drop"):
+ hidden = embeddings.drop(hidden)
+ hidden = run_modernbert_flash_layers(
+ model,
+ hidden,
+ cu_seqlens,
+ max_seqlen,
+ total,
+ global_cos[positions],
+ global_sin[positions],
+ local_cos[positions],
+ local_sin[positions],
+ )
+ if hasattr(model, "final_norm"):
+ hidden = model.final_norm(hidden)
+ return hidden
+
+ return encode, [global_cos, global_sin, local_cos, local_sin]
+
+
+@dataclass
+class PackedForward:
+ """The real rows of a replayed forward, as device tensors the adapter's head reads.
+
+ The tensors are views of the runner's buffers: read them before the
+ runner is used again (the head runs while the runner holds its lock).
+ """
+
+ hidden: torch.Tensor # [total tokens, hidden], after the final norm
+ cu_seqlens: torch.Tensor # [rows + 1], int32
+ input_ids: torch.Tensor # [total tokens], int32
+ lengths: list[int]
+
+
+class _RecordingOutOfMemoryError(Exception):
+ """Recording a graph ran out of device memory."""
+
+
+@dataclass
+class _Graph:
+ graph: Any
+ # int32 [2 * tokens + slots + 1]: token ids, positions, cu_seqlens.
+ inputs: torch.Tensor
+ # Device memory the recording took: pool growth and the recorded graph.
+ device_bytes: int = 0
+
+
+class VarlenGraphRunner:
+ """Records and replays the packed encoder of one model, per bucketed shape.
+
+ Args:
+ encode: The encoder a graph records (``EncodeFn``).
+ hidden_size: Width of the encoder's output.
+ dtype: dtype of the encoder's output.
+ device: The model's CUDA device.
+ window: The longest row the model serves (its RoPE tables' length).
+ pad_token_id: Token id at padding positions (any id in the vocabulary).
+ max_tokens: Token bound; defaults to ``token_bound(hidden_size)``.
+ static_tensors: Device tensors the graphs read that the runner should
+ count against its memory budget (RoPE tables).
+ name: Model name for logs.
+ clock: Monotonic clock (tests move it).
+ """
+
+ def __init__(
+ self,
+ encode: EncodeFn,
+ *,
+ hidden_size: int,
+ dtype: torch.dtype,
+ device: str | torch.device,
+ window: int,
+ pad_token_id: int = 0,
+ max_tokens: int | None = None,
+ static_tensors: Sequence[torch.Tensor] = (),
+ name: str = "",
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._encode = encode
+ self._hidden_size = hidden_size
+ self._dtype = dtype
+ self._device = torch.device(device)
+ self._window = window
+ self._pad_token_id = pad_token_id
+ self._max_tokens = max_tokens if max_tokens is not None else token_bound(hidden_size)
+ self._tokens = token_buckets(self._max_tokens)
+ self._shapes = bucketed_shapes(self._max_tokens, window)
+ self._static_bytes = sum(tensor.nbytes for tensor in static_tensors)
+ self._name = name
+ self._clock = clock
+ self._graphs: OrderedDict[Key, _Graph] = OrderedDict()
+ self._failed: set[Key] = set()
+ self._lock = threading.RLock()
+ self._stream: torch.cuda.Stream | None = None
+ self._disabled = False
+ # Set when the memory budget holds no more graphs.
+ self._full = False
+ # Device memory recordings have taken since the graphs were last dropped.
+ self._device_bytes = 0
+ self._recording_credit = float(_RECORDING_BURST)
+ self._credited_at = clock()
+ # The hidden states every graph writes, sized for the token bound.
+ self._hidden: torch.Tensor | None = None
+ self.stats = CudaGraphStats()
+ self._summary_at = clock()
+ self._summary_forwards = 0
+ self._summary_replayed = 0
+
+ # -- policy ------------------------------------------------------------
+
+ def key(self, total: int, rows: int, longest: int) -> Key | None:
+ """The graph a forward of this shape replays; None when it runs eagerly."""
+ for tokens in self._tokens:
+ if tokens >= total and row_slots(tokens) >= rows:
+ seqlens = seqlen_buckets(tokens, self._window)
+ return (tokens, seqlens[0] if longest <= seqlens[0] else seqlens[-1])
+ return None
+
+ def _why_not_record(self, key: Key) -> EagerReason | None:
+ if key in self._failed:
+ return "failed_shape"
+ if self._full:
+ return "budget_full"
+ if self._recording_credit < 1:
+ return "recording_paused"
+ if not self._has_headroom(self._device):
+ return "no_headroom"
+ return None
+
+ # -- entry point -------------------------------------------------------
+
+ def run(
+ self, token_ids: Sequence[int] | np.ndarray, lengths: Sequence[int], head: Callable[[PackedForward], T]
+ ) -> T | None:
+ """``head`` applied to the replayed encoder output, or None to run the forward eagerly.
+
+ Args:
+ token_ids: The packed token ids of the real rows, row after row.
+ lengths: Tokens per row.
+ head: The adapter's head. It must not return None, and must not
+ keep the ``PackedForward`` tensors past its return.
+ """
+ with self._lock:
+ try:
+ result, reason = self._run(token_ids, lengths, head)
+ except Exception as exc:
+ # Graph memory is held until its graphs go: drop them so the
+ # caller's out-of-memory recovery has that memory to work with.
+ if is_oom_error(exc):
+ self.clear()
+ self.stats.drops += 1
+ raise
+ if reason is not None:
+ self.stats.eager[reason] = self.stats.eager.get(reason, 0) + 1
+ self._log_summary()
+ return result
+
+ def _run(
+ self, token_ids: Sequence[int] | np.ndarray, lengths: Sequence[int], head: Callable[[PackedForward], T]
+ ) -> tuple[T | None, EagerReason | None]:
+ if self._disabled:
+ return None, "disabled"
+ total = int(sum(lengths))
+ if not total:
+ return None, "empty"
+ longest = max(lengths)
+ if longest > self._window:
+ return None, "too_long"
+ key = self.key(total, len(lengths), longest)
+ if key is None:
+ return None, "too_large"
+ now = self._clock()
+ elapsed, self._credited_at = now - self._credited_at, now
+ self._recording_credit = min(float(_RECORDING_BURST), self._recording_credit + elapsed / _SECONDS_PER_RECORDING)
+ entry = self._graphs.get(key)
+ if entry is not None:
+ self.stats.replayed += 1
+ return head(self._replay(key, entry, token_ids, lengths)), None
+ reason = self._why_not_record(key)
+ if reason is not None:
+ return None, reason
+ if not RECORDING_LOCK.acquire(blocking=False):
+ return None, "busy" # another model is recording
+ try:
+ self._recording_credit -= 1
+ try:
+ entry = self._record(key)
+ except Exception as exc: # noqa: BLE001 -- any failure to record runs the forward eagerly
+ self._recording_failed(key, exc)
+ return None, "recording_failed"
+ # The graph answers the forward that recorded it. Its first replay
+ # is part of recording it: a failure other than memory runs the
+ # forward eagerly and the graph is not kept.
+ try:
+ packed = self._replay(key, entry, token_ids, lengths)
+ except Exception as exc:
+ if is_oom_error(exc):
+ # Part of recording: pause as an out-of-memory recording does.
+ self._recording_credit = 1 - _OOM_COOL_DOWN_SECONDS / _SECONDS_PER_RECORDING
+ raise
+ self._recording_failed(key, exc)
+ return None, "recording_failed"
+ self._keep(key, entry)
+ self.stats.recorded += 1
+ finally:
+ RECORDING_LOCK.release()
+ # The head reads the forward's own rows, so its errors are the
+ # forward's, as eagerly: they fail this forward and count nothing
+ # against the shape.
+ return head(packed), None
+
+ def _keep(self, key: Key, entry: _Graph) -> None:
+ """Cache a new graph and hold the runner's graphs to their memory budget."""
+ self._graphs[key] = entry
+ self._device_bytes += entry.device_bytes
+ held = self.held_bytes
+ if held <= self._memory_budget(self._device):
+ return
+ # A fixed set of shapes: dropping graphs to record others would only
+ # record the same shapes again, so keep these.
+ self._full = True
+ logger.warning(
+ "ModernBERT CUDA graphs for %s took %d MB, their memory budget, with %d of %d shapes recorded; "
+ "the other shapes run eagerly",
+ self._name,
+ held // 2**20,
+ len(self._graphs),
+ len(self._shapes),
+ )
+
+ def _recording_failed(self, key: Key, exc: BaseException) -> None:
+ if isinstance(exc, _RecordingOutOfMemoryError) or is_oom_error(exc):
+ # Release the graphs; the forward runs eagerly, and recording pauses.
+ self.clear()
+ self.stats.drops += 1
+ self._recording_credit = 1 - _OOM_COOL_DOWN_SECONDS / _SECONDS_PER_RECORDING
+ logger.info(
+ "ModernBERT CUDA graph recording for %s ran out of memory; graphs dropped, recording paused for %d s",
+ self._name,
+ _OOM_COOL_DOWN_SECONDS,
+ )
+ return
+ self._failed.add(key)
+ self.stats.recording_failures += 1
+ logger.warning(
+ "ModernBERT CUDA graph recording for %s failed for %d tokens, max_seqlen %d; that shape runs eagerly",
+ self._name,
+ key[0],
+ key[1],
+ exc_info=exc,
+ )
+ if len(self._failed) >= _MAX_RECORDING_FAILURES:
+ self._disabled = True
+ self.clear()
+ logger.error(
+ "ModernBERT CUDA graphs for %s are off for this process after %d shapes failed to record; "
+ "its forwards run eagerly",
+ self._name,
+ len(self._failed),
+ )
+
+ def clear(self) -> None:
+ """Drop every graph and its memory."""
+ with self._lock:
+ self._graphs.clear()
+ self._hidden = None
+ self._device_bytes = 0
+ self._full = False
+
+ @property
+ def graph_count(self) -> int:
+ return len(self._graphs)
+
+ @property
+ def disabled(self) -> bool:
+ return self._disabled
+
+ @property
+ def shape_count(self) -> int:
+ """How many shapes the runner can record."""
+ return len(self._shapes)
+
+ @property
+ def held_bytes(self) -> int:
+ """Device memory the runner counts against its budget."""
+ inputs = sum(entry.inputs.nbytes for entry in self._graphs.values())
+ hidden = self._hidden.nbytes if self._hidden is not None else 0
+ return self._device_bytes + inputs + hidden + self._static_bytes
+
+ def _log_summary(self) -> None:
+ now = self._clock()
+ if now - self._summary_at < _SUMMARY_SECONDS:
+ return
+ stats = self.stats
+ forwards = stats.forwards - self._summary_forwards
+ replayed = stats.replayed - self._summary_replayed
+ interval = now - self._summary_at
+ self._summary_at, self._summary_forwards, self._summary_replayed = now, stats.forwards, stats.replayed
+ if not forwards:
+ return
+ logger.info(
+ "ModernBERT CUDA graphs for %s: %d forwards in the last %d s, %.1f%% replayed; "
+ "since load: %d replayed, %d recorded, eager %s, %d recording failures, %d drops; "
+ "%d of %d graphs, %d MB%s",
+ self._name,
+ forwards,
+ round(interval),
+ 100.0 * replayed / forwards,
+ stats.replayed,
+ stats.recorded,
+ dict(sorted(stats.eager.items())),
+ stats.recording_failures,
+ stats.drops,
+ len(self._graphs),
+ len(self._shapes),
+ self.held_bytes // 2**20,
+ ", off for this process" if self._disabled else "",
+ )
+
+ # -- recording and replay ---------------------------------------------
+
+ @staticmethod
+ def _has_headroom(device: torch.device) -> bool:
+ return has_headroom(device)
+
+ @staticmethod
+ def _memory_budget(device: torch.device) -> int:
+ return memory_budget(device)
+
+ @staticmethod
+ def _free_memory(device: torch.device) -> int:
+ return free_memory(device)
+
+ def _hidden_states(self, tokens: int) -> torch.Tensor:
+ """The shared output buffer, viewed as ``[tokens, hidden]``."""
+ if self._hidden is None:
+ # Recorded graphs write here, so it lives as long as they do: only clear() drops it.
+ self._hidden = torch.empty(self._max_tokens * self._hidden_size, dtype=self._dtype, device=self._device)
+ return self._hidden[: tokens * self._hidden_size].view(tokens, self._hidden_size)
+
+ def _record(self, key: Key) -> _Graph:
+ """Record the graph for ``key``.
+
+ Recording runs on a stream of the runner's own, whose first use
+ creates per-stream state (the cuBLAS handle and workspace, compiled
+ Triton kernels) that cannot be created while recording: the first
+ recording warms that stream up with a forward of the smallest shape,
+ the only memory left cached on it. Recording launches no kernels; the
+ caller replays the graph to answer the forward.
+
+ Raises:
+ _RecordingOutOfMemoryError: When the warm-up or the recording runs out
+ of device memory.
+ """
+ try:
+ return self._capture(key)
+ except Exception as exc:
+ if is_oom_error(exc):
+ raise _RecordingOutOfMemoryError(str(exc)) from exc
+ raise
+
+ def _capture(self, key: Key) -> _Graph:
+ tokens, seqlen = key
+ slots = row_slots(tokens)
+ # Every slot empty and every id and position 0: valid to warm up on.
+ inputs = torch.zeros(2 * tokens + slots + 1, dtype=torch.int32, device=self._device)
+ hidden = self._hidden_states(tokens)
+ current = torch.cuda.current_stream(self._device)
+ warm_up = self._stream is None
+ stream = self._stream or torch.cuda.Stream(device=self._device)
+ pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else None
+ graph = torch.cuda.CUDAGraph()
+ stream.wait_stream(current)
+ try:
+ with torch.inference_mode(), torch.cuda.stream(stream):
+ if warm_up:
+ small = torch.zeros(
+ 2 * _MIN_TOKENS + row_slots(_MIN_TOKENS) + 1, dtype=torch.int32, device=self._device
+ )
+ self._forward(small, _MIN_TOKENS, _MIN_TOKENS)
+ # Kept only once warmed up, so a failed warm-up is tried again.
+ self._stream = stream
+ free_before = self._free_memory(self._device)
+ graph.capture_begin(pool=pool, capture_error_mode="thread_local")
+ try:
+ encoded = self._forward(inputs, tokens, seqlen)
+ if encoded.shape != hidden.shape or encoded.dtype != hidden.dtype:
+ msg = f"expected hidden states of {tuple(hidden.shape)}, got {tuple(encoded.shape)}"
+ raise RuntimeError(msg)
+ hidden.copy_(encoded)
+ del encoded
+ except BaseException:
+ # End the recording without hiding why it failed.
+ with contextlib.suppress(Exception):
+ graph.capture_end()
+ raise
+ graph.capture_end()
+ device_bytes = max(0, free_before - self._free_memory(self._device))
+ finally:
+ current.wait_stream(stream)
+ return _Graph(graph=graph, inputs=inputs, device_bytes=device_bytes)
+
+ def _forward(self, inputs: torch.Tensor, tokens: int, seqlen: int) -> torch.Tensor:
+ ids, positions, cu_seqlens = inputs[:tokens], inputs[tokens : 2 * tokens], inputs[2 * tokens :]
+ return self._encode(ids, positions, cu_seqlens, seqlen, tokens)
+
+ def _replay(
+ self, key: Key, entry: _Graph, token_ids: Sequence[int] | np.ndarray, lengths: Sequence[int]
+ ) -> PackedForward:
+ """Replay ``entry`` on the real rows; their hidden states and layout."""
+ if self._hidden is None: # dropped only with every graph
+ raise RuntimeError("ModernBERT CUDA graph replayed without its output buffer")
+ tokens, _ = key
+ slots = row_slots(tokens)
+ rows = len(lengths)
+ lengths_np = np.asarray(lengths, dtype=np.int32)
+ ends = np.cumsum(lengths_np, dtype=np.int32)
+ total = int(ends[-1])
+ host = np.zeros(2 * tokens + slots + 1, dtype=np.int32)
+ host[:total] = np.asarray(token_ids, dtype=np.int32)
+ host[total:tokens] = self._pad_token_id
+ # Positions restart at every row; padding positions stay 0.
+ starts = ends - lengths_np
+ host[tokens : tokens + total] = np.arange(total, dtype=np.int32) - np.repeat(starts, lengths_np)
+ # cu_seqlens: the real rows, then empty slots at the real token count.
+ cu_seqlens = host[2 * tokens :]
+ cu_seqlens[1 : rows + 1] = ends
+ cu_seqlens[rows + 1 :] = total
+ # From pageable memory: the copy has read ``host`` when it returns.
+ entry.inputs.copy_(torch.from_numpy(host), non_blocking=True)
+ entry.graph.replay()
+ return PackedForward(
+ hidden=self._hidden_states(tokens)[:total],
+ cu_seqlens=entry.inputs[2 * tokens : 2 * tokens + rows + 1],
+ input_ids=entry.inputs[:total],
+ lengths=list(lengths),
+ )
diff --git a/packages/sie_server/src/sie_server/adapters/_packed_rope.py b/packages/sie_server/src/sie_server/adapters/_packed_rope.py
new file mode 100644
index 000000000..944982c29
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/_packed_rope.py
@@ -0,0 +1,133 @@
+# Triton reads a kernel's parameter annotations, and accepts only its own types
+# there: the kernel's tensor and integer arguments stay unannotated.
+# ruff: noqa: ANN001
+"""Rotary position embedding for a packed token stream, one position per token.
+
+Flash-attention encoders pack a batch into one unpadded token stream. The
+rotary kernel flash-attn ships (``flash_attn.ops.triton.rotary``) finds each
+token's position from ``cu_seqlens``: it launches one program per block of
+``max_seqlen`` positions per sequence per head. That is the right launch for
+a batch of real rows, but not for a CUDA graph, whose ``cu_seqlens`` has a
+fixed number of sequence slots and whose ``max_seqlen`` is a bucket: most of
+its programs would find no token to rotate.
+
+:func:`rotate_packed_qkv_` takes each token's position from a tensor instead,
+so its launch grows with the number of tokens only. Its arithmetic is
+flash-attn's for the non-interleaved (GPT-NeoX) layout: the halves ``x0`` and
+``x1`` of a head are read in float32 and written back rounded once, as
+``x0 * cos - x1 * sin`` and ``x0 * sin + x1 * cos``, with the float32 cosine
+and sine of the model's dtype tables.
+"""
+
+from __future__ import annotations
+
+import torch
+
+try: # Triton ships with CUDA builds of PyTorch; CPU-only installs lack it.
+ import triton
+ import triton.language as tl
+except ImportError: # pragma: no cover - exercised only on installs without Triton
+ _TRITON = False
+else:
+ _TRITON = True
+
+# Tokens per program.
+_BLOCK_TOKENS = 32
+
+
+def packed_rope_available(device: str | torch.device) -> bool:
+ """Whether :func:`rotate_packed_qkv_` can run on ``device``."""
+ return _TRITON and str(device).startswith("cuda")
+
+
+if _TRITON:
+
+ @triton.jit(do_not_specialize=["n_tokens", "n_rows"])
+ def _rotate_packed_kernel(
+ qk_ptr,
+ positions_ptr,
+ cos_ptr,
+ sin_ptr,
+ n_tokens,
+ n_rows,
+ stride_position,
+ stride_token,
+ stride_head,
+ stride_table,
+ half: tl.constexpr,
+ block_half: tl.constexpr,
+ block_tokens: tl.constexpr,
+ ) -> None:
+ pid_tokens = tl.program_id(axis=0)
+ pid_head = tl.program_id(axis=1)
+ tokens = pid_tokens * block_tokens + tl.arange(0, block_tokens)
+ cols = tl.arange(0, block_half)
+ mask = (tokens[:, None] < n_tokens) & (cols[None, :] < half)
+ positions = tl.load(positions_ptr + tokens * stride_position, mask=tokens < n_tokens, other=0)
+ # A position outside the tables reads and writes nothing: its token is
+ # left exactly as it was.
+ mask = mask & ((positions >= 0) & (positions < n_rows))[:, None]
+ table = positions[:, None] * stride_table + cols[None, :]
+ cos = tl.load(cos_ptr + table, mask=mask, other=1.0).to(tl.float32)
+ sin = tl.load(sin_ptr + table, mask=mask, other=0.0).to(tl.float32)
+ x = qk_ptr + tokens[:, None] * stride_token + pid_head * stride_head + cols[None, :]
+ x0 = tl.load(x, mask=mask, other=0.0).to(tl.float32)
+ x1 = tl.load(x + half, mask=mask, other=0.0).to(tl.float32)
+ o0 = x0 * cos - x1 * sin
+ o1 = x0 * sin + x1 * cos
+ tl.store(x, o0, mask=mask)
+ tl.store(x + half, o1, mask=mask)
+
+
+def rotate_packed_qkv_(qkv: torch.Tensor, positions: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> None:
+ """Rotate the queries and keys of a packed QKV tensor in place.
+
+ Args:
+ qkv: ``[tokens, 3, heads, head_dim]``, contiguous, on CUDA. The
+ queries (``qkv[:, 0]``) and keys (``qkv[:, 1]``) are rotated; the
+ values are untouched.
+ positions: ``[tokens]`` integer position of each token, any stride.
+ A position outside ``[0, max_positions)`` leaves its token
+ exactly as it was (flash-attn's rotary kernel, too, does not
+ rotate past its tables): checking positions on the host would
+ wait for the device, which a CUDA graph being recorded cannot do.
+ cos, sin: ``[max_positions, head_dim / 2]`` tables in ``qkv``'s dtype,
+ with rows laid out ``stride(0)`` apart (a ``[max_positions,
+ head_dim]`` table's first half is accepted as a view).
+
+ Raises:
+ RuntimeError: If Triton is unavailable.
+ ValueError: On a layout the kernel does not handle.
+ """
+ if not _TRITON:
+ raise RuntimeError("rotate_packed_qkv_ needs Triton")
+ tokens, three, heads, head_dim = qkv.shape
+ half = head_dim // 2
+ if three != 3 or head_dim % 2 or not qkv.is_contiguous():
+ raise ValueError(f"expected a contiguous [tokens, 3, heads, head_dim] tensor, got {tuple(qkv.shape)}")
+ if cos.shape[-1] != half or sin.shape != cos.shape or cos.stride(-1) != 1 or sin.stride() != cos.stride():
+ raise ValueError(f"expected [positions, {half}] cos and sin tables with unit column stride")
+ if cos.dtype != qkv.dtype or sin.dtype != qkv.dtype:
+ raise ValueError(f"cos and sin must be {qkv.dtype}, like qkv")
+ if positions.shape != (tokens,):
+ raise ValueError(f"expected {tokens} positions, got {tuple(positions.shape)}")
+ if not tokens:
+ return
+ # Queries and keys are the first two thirds of every token: heads 0..2H-1.
+ grid = (triton.cdiv(tokens, _BLOCK_TOKENS), 2 * heads)
+ with torch.cuda.device(qkv.device):
+ _rotate_packed_kernel[grid](
+ qkv,
+ positions,
+ cos,
+ sin,
+ tokens,
+ cos.shape[0],
+ positions.stride(0),
+ qkv.stride(0),
+ qkv.stride(2),
+ cos.stride(0),
+ half=half, # ty: ignore[invalid-argument-type] -- Triton makes constexpr arguments of plain values
+ block_half=triton.next_power_of_2(half),
+ block_tokens=_BLOCK_TOKENS, # ty: ignore[invalid-argument-type]
+ )
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.py
index fd3520f9d..f5440d063 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
@@ -16,6 +16,13 @@ from sie_server.adapters._modernbert_flash import (
modernbert_rope_theta,
run_modernbert_flash_layers,
)
+from sie_server.adapters._modernbert_flash_graphs import (
+ PackedForward,
+ VarlenGraphRunner,
+ graph_runner,
+ modernbert_encoder,
+ parse_graph_mode,
+)
from sie_server.adapters._multivector import maxsim_scores_batched
from sie_server.adapters._pylate_dense import apply_dense_chain, load_pylate_dense_chain
from sie_server.adapters._spec import AdapterSpec
@@ -64,7 +71,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
spec = AdapterSpec(
inputs=("text",),
outputs=("multivector", "score"),
- unload_fields=("_model", "_tokenizer", "_dense_chain"),
+ unload_fields=("_model", "_tokenizer", "_dense_chain", "_graphs"),
)
def __init__(
@@ -82,6 +89,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
doc_prefix: str = "",
muvera_config: dict[str, Any] | None = None,
revision: str | None = None,
+ cuda_graphs: str | bool = "off",
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -103,9 +111,17 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading the tokenizer, model, and Dense-chain artifacts.
Forwarded to ``from_pretrained(..., revision=...)``.
+ cuda_graphs: "off" (the default) or "bucketed": whether forwards
+ replay the encoder as CUDA graphs (see
+ ``sie_server.adapters._modernbert_flash_graphs``). An operator
+ setting, fixed at load.
**kwargs: Additional arguments (ignored).
+
+ Raises:
+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed".
"""
_ = kwargs
+ self._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="ColBERTModernBERTFlashAdapter")
self._model_name_or_path = str(model_name_or_path)
self._revision = revision
self._token_dim = token_dim
@@ -125,6 +141,8 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._device: str | None = None
self._dense_chain: list[torch.Tensor] | None = None
self._doc_skiplist_ids: set[int] = set()
+ # Replays the encoder as CUDA graphs, when the operator enabled them.
+ self._graphs: VarlenGraphRunner | None = None
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -187,6 +205,27 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._token_dim,
None if self._dense_chain is None else [tuple(w.shape) for w in self._dense_chain],
)
+ self._graphs = self._graph_runner(dtype)
+
+ def _graph_runner(self, dtype: torch.dtype) -> VarlenGraphRunner | None:
+ """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 = self._model
+ window = self._max_seq_length
+ positions = getattr(model.config, "max_position_embeddings", None)
+ if isinstance(positions, int) and positions > 0:
+ window = min(window, positions)
+ return graph_runner(
+ lambda: modernbert_encoder(model, window=window, dtype=dtype),
+ mode=self._cuda_graphs,
+ device=self._device,
+ hidden_size=model.config.hidden_size,
+ dtype=dtype,
+ window=window,
+ pad_token_id=self._tokenizer.pad_token_id,
+ name=self._model_name_or_path,
+ )
def _load_tokenizer(self) -> PreTrainedTokenizerFast:
"""Load the tokenizer, tolerating checkpoints saved by newer transformers.
@@ -286,23 +325,58 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
)
encodings = self._tokenize_inputs(texts, max_length)
+ seq_lengths = [enc["input_ids"].shape[1] for enc in encodings]
+
+ multivectors = self._encode_graphed(encodings, seq_lengths, is_query=is_query)
+ if multivectors is None:
+ multivectors = self._encode_eager(encodings, seq_lengths, is_query=is_query)
+
+ return EncodeOutput(
+ multivector=multivectors,
+ batch_size=len(items),
+ is_query=is_query,
+ multivector_token_dim=self._token_dim,
+ extra={"input_token_counts": [int(length) for length in seq_lengths]},
+ )
+
+ def _encode_graphed(
+ self, encodings: list[Any], seq_lengths: list[int], *, is_query: bool
+ ) -> list[np.ndarray] | None:
+ """Token vectors from a replayed CUDA graph; None when the forward runs eagerly.
+
+ A model with LoRA adapters loaded always runs eagerly: its forward
+ depends on which adapter is active.
+ """
+ if self._graphs is None or self._peft_model is not None:
+ return None
+ flat_ids = torch.cat([enc["input_ids"].squeeze(0) for enc in encodings]).numpy()
+
+ def head(packed: PackedForward) -> list[np.ndarray]:
+ return self._token_vectors(
+ packed.hidden, packed.cu_seqlens, seq_lengths, packed.input_ids.long(), is_query=is_query
+ )
+
+ with torch.inference_mode():
+ return self._graphs.run(flat_ids, seq_lengths, head)
+ def _encode_eager(self, encodings: list[Any], seq_lengths: list[int], *, is_query: bool) -> list[np.ndarray]:
+ """Token vectors from an eager forward over the packed rows."""
# Build packed representation
- seq_lengths = [enc["input_ids"].shape[1] for enc in encodings]
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
+ num_seqs = len(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 (cumulative sequence lengths)
- cu_seqlens = torch.zeros(len(texts) + 1, dtype=torch.int32, device=self._device)
+ cu_seqlens = torch.zeros(num_seqs + 1, dtype=torch.int32, device=self._device)
for i, length in enumerate(seq_lengths):
cu_seqlens[i + 1] = cu_seqlens[i] + length
with torch.inference_mode():
# Build position IDs for RoPE
- position_ids_packed = self._build_position_ids(cu_seqlens, len(texts))
+ position_ids_packed = self._build_position_ids(cu_seqlens, num_seqs)
# Run embeddings
hidden = self._run_embeddings(input_ids_packed)
@@ -328,29 +402,33 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
if hasattr(self._model, "final_norm"):
hidden = self._model.final_norm(hidden)
- # Apply the trained pylate Dense chain (if the checkpoint ships one)
- # then Matryoshka-truncate to token_dim; see #1680.
- hidden = self._project(hidden)
+ return self._token_vectors(hidden, cu_seqlens, seq_lengths, input_ids_packed, is_query=is_query)
- # L2 normalize
- if self._normalize:
- hidden = functional.normalize(hidden, p=2, dim=-1)
+ def _token_vectors(
+ self,
+ hidden: torch.Tensor,
+ cu_seqlens: torch.Tensor,
+ seq_lengths: list[int],
+ input_ids: torch.Tensor,
+ *,
+ is_query: bool,
+ ) -> list[np.ndarray]:
+ """Project, normalize and split final-normed packed hidden states into per-item token vectors."""
+ # Apply the trained pylate Dense chain (if the checkpoint ships one)
+ # then Matryoshka-truncate to token_dim; see #1680.
+ hidden = self._project(hidden)
- # Split back into per-item results
- multivectors = self._split_embeddings(
- hidden,
- cu_seqlens,
- seq_lengths,
- input_ids_packed,
- is_query=is_query,
- )
+ # L2 normalize
+ if self._normalize:
+ hidden = functional.normalize(hidden, p=2, dim=-1)
- return EncodeOutput(
- multivector=multivectors,
- batch_size=len(items),
+ # Split back into per-item results
+ return self._split_embeddings(
+ hidden,
+ cu_seqlens,
+ seq_lengths,
+ input_ids,
is_query=is_query,
- multivector_token_dim=self._token_dim,
- extra={"input_token_counts": [int(length) for length in seq_lengths]},
)
def _tokenize_inputs(self, texts: list[str], max_length: int) -> list[Any]:
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
index 65372e488..779095a0d 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
@@ -106,6 +106,13 @@ from typing import Any, Literal
import torch
+from sie_server.adapters._cuda_graphs import (
+ RECORDING_LOCK,
+ CudaGraphStats,
+ free_memory,
+ has_headroom,
+ memory_budget,
+)
from sie_server.core.oom import is_oom_error
logger = logging.getLogger(__name__)
@@ -130,15 +137,11 @@ _WIDE_ENCODER_HIDDEN_SIZE = 768
# and while it runs the allocator cannot free cached memory for other models.
_RECORDING_BURST = 16
_SECONDS_PER_RECORDING = 2.0
-# Recording waits until at least this share of the device's memory is free.
-_RECORDING_HEADROOM = 0.1
# After a recording runs out of memory, the runner records nothing for this long.
_OOM_COOL_DOWN_SECONDS = 60.0
-# One recording at a time in the process, across every model's runner.
-_RECORDING_LOCK = threading.Lock()
-# Device memory a runner's graphs may hold (their recordings, relative-position
-# tables and buffers), as a share of the device's memory.
-_MEMORY_BUDGET_SHARE = 0.04
+# One recording at a time in the process, across every model's runner and
+# the ModernBERT varlen runner too (see ``sie_server.adapters._cuda_graphs``).
+_RECORDING_LOCK = RECORDING_LOCK
# Shapes that may fail to record, for reasons other than memory, before the
# runner turns graphs off for the process.
_MAX_RECORDING_FAILURES = 3
@@ -217,29 +220,6 @@ def bucketed_shapes(max_length: int, max_tokens: int) -> frozenset[Key]:
return frozenset((batch, length) for length in lengths for batch in batch_buckets(length, max_tokens))
-@dataclass
-class CudaGraphStats:
- """Counters of the forwards a runner was offered since the model loaded.
-
- Each forward counts once: ``replayed`` (a recorded graph served it),
- ``recorded`` (it recorded a graph and was answered by the first replay)
- or under ``eager`` by why it ran eagerly. Requests that opt out of graphs
- are not offered to the runner. ``recording_failures`` counts shapes that
- failed to record for reasons other than memory; ``drops`` counts the times
- every graph was dropped (out of memory, or ``exact`` mode over its budget).
- """
-
- replayed: int = 0
- recorded: int = 0
- eager: dict[str, int] = field(default_factory=dict)
- recording_failures: int = 0
- drops: int = 0
-
- @property
- def forwards(self) -> int:
- return self.replayed + self.recorded + sum(self.eager.values())
-
-
class _RecordingOutOfMemoryError(Exception):
"""Recording a graph ran out of device memory."""
@@ -603,17 +583,16 @@ class CudaGraphRunner:
@staticmethod
def _has_headroom(device: torch.device) -> bool:
"""Whether enough device memory is free to record without starving other models."""
- free, total = torch.cuda.mem_get_info(device)
- return free >= _RECORDING_HEADROOM * total
+ return has_headroom(device)
@staticmethod
def _memory_budget(device: torch.device) -> int:
"""Device memory this runner's graphs may hold."""
- return int(_MEMORY_BUDGET_SHARE * torch.cuda.mem_get_info(device)[1])
+ return memory_budget(device)
@staticmethod
def _free_memory(device: torch.device) -> int:
- return torch.cuda.mem_get_info(device)[0]
+ return free_memory(device)
def _tensor_bytes(self) -> int:
"""Device memory of the tensors the graphs keep: tables, static inputs and the hidden states."""
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__.py
index 0b8a5f192..9e03ab4f5 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
@@ -13,6 +13,12 @@ from sie_server.adapters._modernbert_flash import (
modernbert_rope_theta,
run_modernbert_flash_layers,
)
+from sie_server.adapters._modernbert_flash_graphs import (
+ VarlenGraphRunner,
+ graph_runner,
+ modernbert_encoder,
+ parse_graph_mode,
+)
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategy
from sie_server.adapters._utils import (
@@ -50,7 +56,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
spec = AdapterSpec(
inputs=("text",),
outputs=("dense",),
- unload_fields=("_model", "_tokenizer", "_dense_dim"),
+ unload_fields=("_model", "_tokenizer", "_dense_dim", "_graphs"),
)
def __init__(
@@ -65,6 +71,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
doc_template: str | None = None,
trust_remote_code: bool = True,
revision: str | None = None,
+ cuda_graphs: str | bool = "off",
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -80,9 +87,17 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
trust_remote_code: Whether to trust remote code for model/tokenizer.
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
+ cuda_graphs: "off" (the default) or "bucketed": whether forwards
+ replay the encoder as CUDA graphs (see
+ ``sie_server.adapters._modernbert_flash_graphs``). An operator
+ setting, fixed at load.
**kwargs: Additional arguments (ignored, for compatibility).
+
+ Raises:
+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed".
"""
_ = kwargs
+ self._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="ModernBERTFlashAdapter")
self._model_name_or_path = str(model_name_or_path)
self._normalize = normalize
self._max_seq_length = max_seq_length
@@ -97,6 +112,8 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._tokenizer: PreTrainedTokenizerFast | None = None
self._device: str | None = None
self._dense_dim: int | None = None
+ # Replays the encoder as CUDA graphs, when the operator enabled them.
+ self._graphs: VarlenGraphRunner | None = None
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -153,6 +170,23 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
self._model,
self._max_seq_length,
)
+ self._graphs = self._graph_runner(dtype)
+
+ def _graph_runner(self, dtype: torch.dtype) -> VarlenGraphRunner | None:
+ """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
+ return graph_runner(
+ lambda: modernbert_encoder(model, window=window, dtype=dtype),
+ mode=self._cuda_graphs,
+ device=self._device,
+ hidden_size=model.config.hidden_size,
+ dtype=dtype,
+ window=window,
+ pad_token_id=self._tokenizer.pad_token_id,
+ name=self._model_name_or_path,
+ )
def warmup(self) -> None:
# Warmup flash attention kernels
@@ -220,6 +254,64 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Extract input_ids as lists and compute seq_lengths
input_ids_lists = batch_encoding["input_ids"]
seq_lengths = [len(ids) for ids in input_ids_lists]
+
+ dense_np = self._encode_graphed(input_ids_lists, seq_lengths, normalize=normalize, pooling=pooling)
+ if dense_np is None:
+ dense_np = self._encode_eager(input_ids_lists, seq_lengths, normalize=normalize, pooling=pooling)
+ output = EncodeOutput(
+ dense=dense_np,
+ batch_size=len(items),
+ is_query=is_query,
+ dense_dim=self._dense_dim,
+ )
+ # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
+ # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
+ # the model's query/doc template before tokenizing (e.g. modernbert-embed's
+ # ``search_query:``/``search_document:``), so the real post-template,
+ # post-truncation per-item token counts exist only here. ``seq_lengths``
+ # is the exact ``len(input_ids)`` the model processed; expose it through
+ # ``EncodeOutput.extra`` (the designated adapter-extension point) aligned
+ # 1:1 with ``items``. The encode pipeline forwards these for metering, in
+ # preference to the base ``count_input_tokens`` fallback which re-tokenizes
+ # raw ``item.text`` and would undercount by the template's tokens (a no-op
+ # for templateless models like gte-modernbert/granite). Mirrors ``bert_flash``.
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
+
+ def _encode_graphed(
+ self,
+ input_ids_lists: list[list[int]],
+ seq_lengths: list[int],
+ *,
+ normalize: bool,
+ pooling: str,
+ ) -> np.ndarray | None:
+ """Dense vectors from a replayed CUDA graph; None when the forward runs eagerly.
+
+ A model with LoRA adapters loaded always runs eagerly: its forward
+ depends on which adapter is active.
+ """
+ if self._graphs is None or self._peft_model is not None:
+ return None
+ flat_ids = [token for ids in input_ids_lists for token in ids]
+ with torch.inference_mode():
+ return self._graphs.run(
+ flat_ids,
+ seq_lengths,
+ lambda packed: self._pool_to_numpy(
+ packed.hidden, packed.cu_seqlens, seq_lengths, None, normalize=normalize, pooling=pooling
+ ),
+ )
+
+ def _encode_eager(
+ self,
+ input_ids_lists: list[list[int]],
+ seq_lengths: list[int],
+ *,
+ normalize: bool,
+ pooling: str,
+ ) -> np.ndarray:
+ """Dense vectors from an eager forward over the packed rows."""
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
@@ -231,7 +323,7 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Build cu_seqlens with vectorized cumsum
seq_lengths_tensor = torch.tensor(seq_lengths, dtype=torch.int32, device=self._device)
- cu_seqlens = torch.zeros(len(texts) + 1, dtype=torch.int32, device=self._device)
+ cu_seqlens = torch.zeros(len(seq_lengths) + 1, dtype=torch.int32, device=self._device)
cu_seqlens[1:] = torch.cumsum(seq_lengths_tensor, dim=0)
with torch.inference_mode():
@@ -262,36 +354,31 @@ class ModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
hidden = self._model.final_norm(hidden)
# Pool to get dense embeddings
- dense_vecs = self._pool_embeddings(
- hidden,
- cu_seqlens,
- seq_lengths,
- seq_lengths_tensor=seq_lengths_tensor,
- normalize=normalize,
- pooling=pooling,
+ return self._pool_to_numpy(
+ hidden, cu_seqlens, seq_lengths, seq_lengths_tensor, normalize=normalize, pooling=pooling
)
- # Transfer 16-bit to CPU first, then upcast to float32 — halves GPU->CPU bandwidth
- dense_np = dense_vecs.cpu().float().numpy()
- output = EncodeOutput(
- dense=dense_np,
- batch_size=len(items),
- is_query=is_query,
- dense_dim=self._dense_dim,
+ def _pool_to_numpy(
+ self,
+ hidden: torch.Tensor,
+ cu_seqlens: torch.Tensor,
+ seq_lengths: list[int],
+ seq_lengths_tensor: torch.Tensor | None,
+ *,
+ normalize: bool,
+ pooling: str,
+ ) -> np.ndarray:
+ """Pool packed hidden states and bring the vectors to the host as float32."""
+ dense_vecs = self._pool_embeddings(
+ hidden,
+ cu_seqlens,
+ seq_lengths,
+ seq_lengths_tensor=seq_lengths_tensor,
+ normalize=normalize,
+ pooling=pooling,
)
- # Unit-meter seam (§7.3): this adapter owns tokenization (the registry
- # preprocessor for flash adapters is a char-count ESTIMATOR) AND applies
- # the model's query/doc template before tokenizing (e.g. modernbert-embed's
- # ``search_query:``/``search_document:``), so the real post-template,
- # post-truncation per-item token counts exist only here. ``seq_lengths``
- # is the exact ``len(input_ids)`` the model processed; expose it through
- # ``EncodeOutput.extra`` (the designated adapter-extension point) aligned
- # 1:1 with ``items``. The encode pipeline forwards these for metering, in
- # preference to the base ``count_input_tokens`` fallback which re-tokenizes
- # raw ``item.text`` and would undercount by the template's tokens (a no-op
- # for templateless models like gte-modernbert/granite). Mirrors ``bert_flash``.
- output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
- return output
+ # Transfer 16-bit to CPU first, then upcast to float32 — halves GPU->CPU bandwidth
+ return dense_vecs.cpu().float().numpy()
def _build_position_ids(self, seq_lengths_tensor: torch.Tensor, total_tokens: int) -> torch.Tensor:
"""Build position IDs for packed sequences (vectorized).
diff --git a/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
index ac9e0aaf1..be8b54753 100644
--- a/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/modernbert_flash_cross_encoder/__init__.py
@@ -3,9 +3,18 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, ClassVar
+import numpy as np
import torch
from sie_server.adapters._flash_base import FlashBaseAdapter
+from sie_server.adapters._modernbert_flash_graphs import (
+ EncodeFn,
+ PackedForward,
+ VarlenGraphRunner,
+ graph_runner,
+ parse_graph_mode,
+)
+from sie_server.adapters._packed_rope import packed_rope_available, rotate_packed_qkv_
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecision
from sie_server.adapters._utils import extract_text
@@ -35,7 +44,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
spec = AdapterSpec(
inputs=("text",),
outputs=("score",),
- unload_fields=("_model", "_tokenizer", "_dtype", "_num_heads", "_head_dim", "_hidden_size"),
+ unload_fields=("_model", "_tokenizer", "_dtype", "_num_heads", "_head_dim", "_hidden_size", "_graphs"),
)
def __init__(
@@ -46,6 +55,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
max_seq_length: int = 8192,
compute_precision: ComputePrecision = "bfloat16",
revision: str | None = None,
+ cuda_graphs: str | bool = "off",
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -57,9 +67,17 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
compute_precision: Compute precision (bfloat16 recommended for ModernBERT).
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading model artifacts. Forwarded to ``from_pretrained(..., revision=...)``.
+ cuda_graphs: "off" (the default) or "bucketed": whether forwards
+ replay the encoder as CUDA graphs (see
+ ``sie_server.adapters._modernbert_flash_graphs``). An operator
+ setting, fixed at load.
**kwargs: Additional arguments (ignored).
+
+ Raises:
+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed".
"""
_ = kwargs
+ self._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="ModernBertFlashCrossEncoder")
self._model_name_or_path = str(model_name_or_path)
self._trust_remote_code = trust_remote_code
self._max_seq_length = max_seq_length
@@ -78,6 +96,8 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._hidden_size: int = 0
self._use_sigmoid: bool = True
self._use_mean_pooling: bool = False
+ # Replays the encoder as CUDA graphs, when the operator enabled them.
+ self._graphs: VarlenGraphRunner | None = None
def load(self, device: str) -> None:
"""Load model weights onto the specified device."""
@@ -144,6 +164,100 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
self._model,
self._max_seq_length,
)
+ self._graphs = self._graph_runner()
+
+ def _graph_runner(self) -> VarlenGraphRunner | None:
+ """The CUDA graph runner for the loaded model; None when graphs are off or do not apply."""
+ if self._cuda_graphs == "off" or self._device is None or self._tokenizer is None:
+ return None
+ reason = self._graph_unsupported_reason()
+ if reason is not None:
+ logger.warning(
+ "ModernBERT cuda_graphs=%s does not apply to %s, which runs eagerly: %s",
+ self._cuda_graphs,
+ self._model_name_or_path,
+ reason,
+ )
+ return None
+ window = self._max_seq_length
+ return graph_runner(
+ lambda: self._graph_encoder(window),
+ mode=self._cuda_graphs,
+ device=self._device,
+ hidden_size=self._hidden_size,
+ dtype=self._dtype or self._resolve_dtype(),
+ window=window,
+ pad_token_id=self._tokenizer.pad_token_id,
+ name=self._model_name_or_path,
+ )
+
+ def _graph_unsupported_reason(self) -> str | None:
+ """Why this model's forward cannot be recorded; None when it can."""
+ if not packed_rope_available(self._device or "cpu"):
+ return "the graph's rotary kernel needs Triton on CUDA"
+ for layer in self._model.model.layers:
+ rotary = getattr(layer.attn, "rotary_emb", None)
+ if not callable(getattr(rotary, "_update_cos_sin_cache", None)):
+ return "its attention layers have no flash-attn rotary embedding"
+ return None
+
+ def _graph_encoder(self, window: int) -> tuple[EncodeFn, list[torch.Tensor]]:
+ """The encoder a graph records: ``_forward_flash`` up to the final norm.
+
+ The eager forward rotates queries and keys with each layer's
+ flash-attn rotary embedding, whose kernel finds positions from
+ ``cu_seqlens``. A graph's ``cu_seqlens`` has fixed slots, so the graph
+ rotates by token position instead (``rotate_packed_qkv_``), with the
+ same arithmetic and the same cosine and sine tables: each rotary
+ module's own cache, grown to the model window once here.
+
+ Returns:
+ The encoder and the tables it reads.
+ """
+ backbone = self._model.model
+ embeddings = backbone.embeddings
+ layers = list(backbone.layers)
+ final_norm = backbone.final_norm
+ tables: dict[Any, tuple[torch.Tensor, torch.Tensor]] = {}
+ layer_tables: list[tuple[torch.Tensor, torch.Tensor]] = []
+ for layer in layers:
+ rotary = layer.attn.rotary_emb
+ base = getattr(rotary, "base", None)
+ key = float(base) if isinstance(base, (int, float)) else id(rotary)
+ if key not in tables:
+ rotary._update_cos_sin_cache(window, device=self._device, dtype=self._dtype)
+ # Held here: the module replaces its cache when it grows, and a graph keeps reading these.
+ tables[key] = (rotary._cos_cached, rotary._sin_cached)
+ layer_tables.append(tables[key])
+ num_heads, head_dim, hidden_size = self._num_heads, self._head_dim, self._hidden_size
+ softmax_scale = 1.0 / (head_dim**0.5)
+
+ def encode(
+ input_ids: torch.Tensor, positions: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int, total: int
+ ) -> torch.Tensor:
+ from flash_attn.flash_attn_interface import flash_attn_varlen_qkvpacked_func
+
+ hidden = embeddings.tok_embeddings(input_ids)
+ if hasattr(embeddings, "norm"):
+ hidden = embeddings.norm(hidden)
+ if hasattr(embeddings, "drop"):
+ hidden = embeddings.drop(hidden)
+ for layer, (cos, sin) in zip(layers, layer_tables, strict=True):
+ qkv = layer.attn.Wqkv(layer.attn_norm(hidden)).view(total, 3, num_heads, head_dim)
+ rotate_packed_qkv_(qkv, positions, cos, sin)
+ attn_out = flash_attn_varlen_qkvpacked_func(
+ qkv,
+ cu_seqlens,
+ max_seqlen=max_seqlen,
+ softmax_scale=softmax_scale,
+ causal=False,
+ window_size=layer.attn.local_attention,
+ )
+ hidden = hidden + layer.attn.Wo(attn_out.reshape(total, hidden_size))
+ hidden = hidden + layer.mlp(layer.mlp_norm(hidden))
+ return final_norm(hidden)
+
+ return encode, [table for pair in tables.values() for table in pair]
def _resolve_dtype(self) -> torch.dtype:
"""Resolve compute dtype."""
@@ -198,38 +312,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
)
for q, d in pairs
]
-
- # Build packed representation
- seq_lengths = [enc["input_ids"].shape[1] for enc in encodings]
- total_tokens = sum(seq_lengths)
- max_seqlen = max(seq_lengths)
-
- # Pack tensors
- input_ids = torch.cat([enc["input_ids"].squeeze(0) for enc in encodings]).to(self._device)
-
- # Build cu_seqlens
- cu_seqlens = torch.zeros(len(pairs) + 1, dtype=torch.int32, device=self._device)
- for i, length in enumerate(seq_lengths):
- cu_seqlens[i + 1] = cu_seqlens[i] + length
-
- with torch.inference_mode():
- # Run forward pass with flash attention
- logits = self._forward_flash(
- input_ids,
- cu_seqlens,
- max_seqlen,
- total_tokens,
- len(pairs),
- seq_lengths,
- )
-
- # Apply activation function
- scores_tensor = logits.squeeze(-1).float()
- if self._use_sigmoid:
- scores_tensor = torch.sigmoid(scores_tensor)
- scores = scores_tensor.cpu().tolist()
-
- return scores
+ return self._scores(encodings).tolist()
def score_pairs(
self,
@@ -284,9 +367,24 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
)
for q, d in pairs
]
+ return ScoreOutput(scores=self._scores(encodings))
- # Build packed representation
+ def _scores(self, encodings: list[Any]) -> np.ndarray:
+ """float32 relevance scores for tokenized (query, doc) pairs: a replayed CUDA graph, or eagerly."""
seq_lengths = [enc["input_ids"].shape[1] for enc in encodings]
+ if self._graphs is not None:
+ flat_ids = torch.cat([enc["input_ids"].squeeze(0) for enc in encodings]).numpy()
+
+ def head(packed: PackedForward) -> np.ndarray:
+ logits = self._head_logits(packed.hidden, packed.cu_seqlens, len(seq_lengths))
+ return self._activate(logits)
+
+ with torch.inference_mode():
+ scores = self._graphs.run(flat_ids, seq_lengths, head)
+ if scores is not None:
+ return scores
+
+ # Build packed representation
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
@@ -294,7 +392,7 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
input_ids = torch.cat([enc["input_ids"].squeeze(0) for enc in encodings]).to(self._device)
# Build cu_seqlens
- cu_seqlens = torch.zeros(len(pairs) + 1, dtype=torch.int32, device=self._device)
+ cu_seqlens = torch.zeros(len(encodings) + 1, dtype=torch.int32, device=self._device)
for i, length in enumerate(seq_lengths):
cu_seqlens[i + 1] = cu_seqlens[i] + length
@@ -304,20 +402,17 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
cu_seqlens,
max_seqlen,
total_tokens,
- len(pairs),
+ len(encodings),
seq_lengths,
)
+ return self._activate(logits)
- scores_tensor = logits.squeeze(-1).float()
- if self._use_sigmoid:
- scores_tensor = torch.sigmoid(scores_tensor)
-
- # Convert to float32 numpy array and wrap in ScoreOutput
- import numpy as np
-
- scores_array = scores_tensor.cpu().numpy().astype(np.float32)
-
- return ScoreOutput(scores=scores_array)
+ def _activate(self, logits: torch.Tensor) -> np.ndarray:
+ """Scores from logits: sigmoid for single-label models, as float32 on the host."""
+ scores_tensor = logits.squeeze(-1).float()
+ if self._use_sigmoid:
+ scores_tensor = torch.sigmoid(scores_tensor)
+ return scores_tensor.cpu().numpy().astype(np.float32)
def _forward_flash(
self,
@@ -348,9 +443,6 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
embeddings = backbone.embeddings
layers = backbone.layers
final_norm = backbone.final_norm
- head = self._model.head
- drop = self._model.drop
- classifier = self._model.classifier
# Compute embeddings (ModernBERT: tok_embeddings -> norm -> drop)
hidden = embeddings.tok_embeddings(input_ids)
@@ -400,6 +492,13 @@ class ModernBertFlashCrossEncoderAdapter(FlashBaseAdapter):
# Apply final layer norm
hidden = final_norm(hidden)
+ return self._head_logits(hidden, cu_seqlens, batch_size)
+
+ def _head_logits(self, hidden: torch.Tensor, cu_seqlens: torch.Tensor, batch_size: int) -> torch.Tensor:
+ """Classification logits ``[batch_size, 1]`` from final-normed packed hidden states."""
+ head = self._model.head
+ drop = self._model.drop
+ classifier = self._model.classifier
# Pool hidden states based on config
if self._use_mean_pooling:
diff --git a/packages/sie_server/tests/adapters/test_modernbert_flash_graphs.py b/packages/sie_server/tests/adapters/test_modernbert_flash_graphs.py
new file mode 100644
index 000000000..11dd90025
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_modernbert_flash_graphs.py
@@ -0,0 +1,867 @@
+"""ModernBERT flash adapters replaying their encoder as CUDA graphs.
+
+The CPU tests replace a recorded graph with a stand-in whose replay runs the
+recorded encoder again on the graph's static inputs, and small references
+stand in for flash-attn's kernels. So they check what a graph is fed and what
+the adapters make of its output: the bucketed shapes, the packed layout
+(padding tokens outside every sequence, empty slots, positions), the
+recording policy, and the dense, late-interaction and reranking heads against
+their eager forwards. The reference attention writes NaN to every row outside
+a sequence, as the real kernel leaves them unwritten, so a padding row that
+reached a real one would fail every comparison. The ``gpu_hw`` tests record
+and replay real graphs.
+"""
+
+from __future__ import annotations
+
+import logging
+import sys
+import types
+from itertools import pairwise
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import numpy as np
+import pytest
+import torch
+from sie_server.adapters import _modernbert_flash_graphs as graphs_module
+from sie_server.adapters._cuda_graphs import RECORDING_LOCK
+from sie_server.adapters._modernbert_flash_graphs import (
+ PackedForward,
+ VarlenGraphRunner,
+ _Graph,
+ bucketed_shapes,
+ modernbert_encoder,
+ parse_graph_mode,
+ row_slots,
+ seqlen_buckets,
+ token_bound,
+ token_buckets,
+)
+from sie_server.adapters.colbert_modernbert_flash.adapter import ColBERTModernBERTFlashAdapter
+from sie_server.adapters.gliclass import cuda_graphs as gliclass_graphs
+from sie_server.adapters.modernbert_flash import ModernBERTFlashAdapter
+from sie_server.adapters.modernbert_flash_cross_encoder import ModernBertFlashCrossEncoderAdapter
+from sie_server.core.loader import load_model_configs, reject_unknown_loadtime_options
+from sie_server.types.inputs import Item
+from tokenizers import Tokenizer, models, pre_tokenizers, processors
+from torch.nn import functional
+from transformers import ModernBertConfig, ModernBertForSequenceClassification, ModernBertModel, PreTrainedTokenizerFast
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+_ADAPTER_PATHS = frozenset(
+ {
+ "sie_server.adapters.modernbert_flash:ModernBERTFlashAdapter",
+ "sie_server.adapters.colbert_modernbert_flash.adapter:ColBERTModernBERTFlashAdapter",
+ "sie_server.adapters.modernbert_flash_cross_encoder:ModernBertFlashCrossEncoderAdapter",
+ }
+)
+# The shipped models that load with graphs: every one on these adapters, each
+# of which passed the margin rule against eager forwards (see the server README).
+_GRAPHS_BY_DEFAULT = {
+ "Alibaba-NLP/gte-modernbert-base",
+ "Alibaba-NLP/gte-reranker-modernbert-base",
+ "ibm-granite/granite-embedding-97m-multilingual-r2",
+ "ibm-granite/granite-embedding-small-english-r2",
+ "lightonai/GTE-ModernColBERT-v1",
+ "lightonai/Reason-ModernColBERT",
+ "lightonai/mLateOn",
+ "mixedbread-ai/mxbai-edge-colbert-v0-32m",
+ "nomic-ai/modernbert-embed-base",
+ "topk-io/Iso-ModernColBERT",
+}
+_WINDOW = 64
+_HIDDEN = 32
+_WORDS = [
+ "the",
+ "a",
+ "patient",
+ "drug",
+ "trial",
+ "dose",
+ "protein",
+ "cell",
+ "gene",
+ "effect",
+ "risk",
+ "study",
+ "model",
+ "data",
+ "result",
+ "group",
+]
+# From one word to past the window, so rows pack against each other, span
+# several sliding windows and get truncated.
+_TEXTS = [" ".join(_WORDS[: 1 + i % len(_WORDS)] * (1 + i // 4)) for i in range(24)]
+
+
+# -- reference kernels ------------------------------------------------------
+
+
+def _reference_varlen(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ cu_seqlens_q: torch.Tensor,
+ cu_seqlens_k: torch.Tensor,
+ max_seqlen_q: int,
+ max_seqlen_k: int,
+ *,
+ causal: bool = False,
+ softmax_scale: float | None = None,
+ window_size: tuple[int, int] = (-1, -1),
+) -> torch.Tensor:
+ """``flash_attn_varlen_func``: attention within each sequence; rows outside every sequence left unwritten (NaN)."""
+ assert not causal
+ assert torch.equal(cu_seqlens_q, cu_seqlens_k)
+ bounds = cu_seqlens_q.tolist()
+ lengths = [end - start for start, end in pairwise(bounds)]
+ assert bounds[0] == 0
+ assert all(length >= 0 for length in lengths)
+ assert max(lengths) <= max_seqlen_q == max_seqlen_k
+ out = torch.full_like(query, float("nan"))
+ for start, end in pairwise(bounds):
+ if start == end:
+ continue
+ rows = [t[start:end].transpose(0, 1) for t in (query, key, value)]
+ mask = None
+ if window_size != (-1, -1):
+ positions = torch.arange(end - start, device=query.device)
+ mask = (positions[:, None] - positions[None, :]).abs() <= window_size[0]
+ attended = functional.scaled_dot_product_attention(*rows, attn_mask=mask, scale=softmax_scale)
+ out[start:end] = attended.transpose(0, 1)
+ return out
+
+
+def _reference_qkvpacked(
+ qkv: torch.Tensor,
+ cu_seqlens: torch.Tensor,
+ max_seqlen: int,
+ *,
+ softmax_scale: float | None = None,
+ causal: bool = False,
+ window_size: tuple[int, int] = (-1, -1),
+) -> torch.Tensor:
+ """``flash_attn_varlen_qkvpacked_func`` on ``[tokens, 3, heads, dim]``."""
+ return _reference_varlen(
+ qkv[:, 0],
+ qkv[:, 1],
+ qkv[:, 2],
+ cu_seqlens,
+ cu_seqlens,
+ max_seqlen,
+ max_seqlen,
+ causal=causal,
+ softmax_scale=softmax_scale,
+ window_size=window_size,
+ )
+
+
+def _rotate(qk: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
+ """flash-attn's non-interleaved rotation of ``[tokens, heads, dim]`` by per-token ``[tokens, dim / 2]`` tables."""
+ half = qk.shape[-1] // 2
+ x0, x1 = qk[..., :half].float(), qk[..., half:].float()
+ cos, sin = cos[:, None, :].float(), sin[:, None, :].float()
+ return torch.cat([x0 * cos - x1 * sin, x0 * sin + x1 * cos], dim=-1).to(qk.dtype)
+
+
+def _reference_rotate_packed(qkv: torch.Tensor, positions: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> None:
+ """``rotate_packed_qkv_`` in PyTorch."""
+ positions = positions.long()
+ qkv[:, :2] = torch.stack([_rotate(qkv[:, i], cos[positions], sin[positions]) for i in range(2)], dim=1)
+
+
+class _FlashRotary(torch.nn.Module):
+ """flash-attn's ``RotaryEmbedding`` as Hugging Face ModernBERT's flash-attention layers use it."""
+
+ def __init__(self, dim: int, base: float) -> None:
+ super().__init__()
+ self.base = base
+ self.inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.float32) / dim))
+ self._seq_len_cached = 0
+ self._cos_cached: torch.Tensor | None = None
+ self._sin_cached: torch.Tensor | None = None
+
+ def _update_cos_sin_cache(self, seqlen: int, device: Any = None, dtype: Any = None) -> None:
+ if seqlen > self._seq_len_cached or self._cos_cached is None:
+ self._seq_len_cached = seqlen
+ freqs = torch.outer(torch.arange(seqlen, dtype=torch.float32), self.inv_freq)
+ self._cos_cached, self._sin_cached = freqs.cos().to(dtype), freqs.sin().to(dtype)
+
+ def forward(self, qkv: torch.Tensor, cu_seqlens: torch.Tensor, max_seqlen: int) -> torch.Tensor:
+ self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype)
+ positions = torch.cat([torch.arange(end - start) for start, end in pairwise(cu_seqlens.tolist())])
+ _reference_rotate_packed(qkv, positions, self._cos_cached, self._sin_cached)
+ return qkv
+
+
+def reference_flash(monkeypatch: pytest.MonkeyPatch) -> None:
+ module = types.ModuleType("flash_attn")
+ module.flash_attn_varlen_func = _reference_varlen # ty: ignore[unresolved-attribute]
+ interface = types.ModuleType("flash_attn.flash_attn_interface")
+ interface.flash_attn_varlen_qkvpacked_func = _reference_qkvpacked # ty: ignore[unresolved-attribute]
+ monkeypatch.setitem(sys.modules, "flash_attn", module)
+ monkeypatch.setitem(sys.modules, "flash_attn.flash_attn_interface", interface)
+
+
+# -- a runner whose graphs replay on the CPU ----------------------------------
+
+
+class _Replay:
+ """A recorded graph's stand-in: replaying runs the recorded encoder on the static inputs."""
+
+ def __init__(self, runner: VarlenGraphRunner, inputs: torch.Tensor, key: tuple[int, int]) -> None:
+ self._runner, self._inputs, self.key = runner, inputs, key
+ self.replays = 0
+
+ def replay(self) -> None:
+ tokens, seqlen = self.key
+ self._runner._hidden_states(tokens).copy_(self._runner._forward(self._inputs, tokens, seqlen))
+ self.replays += 1
+
+ def pool(self) -> None:
+ return None
+
+
+class _Runner(VarlenGraphRunner):
+ """Records graphs as ``_Replay`` stand-ins. Time stands still unless a test moves ``now``.
+
+ ``capture_error`` fails the next recording (every one with ``keep_failing``);
+ the device has memory to spare unless a test clears ``headroom`` or sets a
+ ``budget``.
+ """
+
+ def __init__(self, encode: Any, **kwargs: Any) -> None:
+ self.now = 0.0
+ kwargs.setdefault("hidden_size", _HIDDEN)
+ kwargs.setdefault("dtype", torch.float32)
+ kwargs.setdefault("device", "cpu")
+ kwargs.setdefault("window", 8192)
+ super().__init__(encode, clock=lambda: self.now, **kwargs)
+ self.recorded: list[tuple[int, int]] = []
+ self.capture_error: Exception | None = None
+ self.keep_failing = False
+ self.headroom = True
+ self.budget = 2**40
+ self.bytes_per_graph = 0
+
+ def _has_headroom(self, device: torch.device) -> bool:
+ return self.headroom
+
+ def _memory_budget(self, device: torch.device) -> int:
+ return self.budget
+
+ def _capture(self, key: tuple[int, int]) -> _Graph:
+ if self.capture_error is not None:
+ error, self.capture_error = self.capture_error, (self.capture_error if self.keep_failing else None)
+ raise error
+ self.recorded.append(key)
+ tokens, _ = key
+ inputs = torch.zeros(2 * tokens + row_slots(tokens) + 1, dtype=torch.int32)
+ self._hidden_states(tokens)
+ return _Graph(graph=_Replay(self, inputs, key), inputs=inputs, device_bytes=self.bytes_per_graph)
+
+
+def _echo_encode(
+ ids: torch.Tensor, positions: torch.Tensor, cu: torch.Tensor, max_seqlen: int, total: int
+) -> torch.Tensor:
+ """An encoder whose output rows carry (token id, position) so layouts can be read back."""
+ out = torch.zeros(total, _HIDDEN)
+ out[:, 0] = ids.float()
+ out[:, 1] = positions.float()
+ return out
+
+
+def _ids(lengths: list[int]) -> list[int]:
+ return [100 + i for i in range(sum(lengths))]
+
+
+def _layout(packed: PackedForward) -> tuple[list[int], list[int], list[int]]:
+ return packed.hidden[:, 0].int().tolist(), packed.hidden[:, 1].int().tolist(), packed.cu_seqlens.tolist()
+
+
+# -- shapes --------------------------------------------------------------------
+
+
+class TestShapes:
+ def test_token_buckets_are_powers_of_two_and_their_midpoints(self) -> None:
+ assert token_buckets(1024) == (64, 128, 192, 256, 384, 512, 768, 1024)
+ assert token_buckets(2048)[-3:] == (1024, 1536, 2048)
+ assert token_buckets(512) == (64, 128, 192, 256, 384, 512)
+
+ @pytest.mark.parametrize(("hidden_size", "tokens"), [(384, 2048), (768, 1024), (1024, 512)])
+ def test_wider_encoders_hold_fewer_tokens(self, hidden_size: int, tokens: int) -> None:
+ assert token_bound(hidden_size) == tokens
+
+ @pytest.mark.parametrize(("tokens", "slots"), [(64, 8), (128, 8), (256, 16), (1024, 64), (2048, 128), (4096, 128)])
+ def test_slots_grow_with_the_bucket(self, tokens: int, slots: int) -> None:
+ assert row_slots(tokens) == slots
+
+ @pytest.mark.parametrize(
+ ("tokens", "window", "seqlens"),
+ [
+ (64, 8192, (64,)),
+ (512, 8192, (512,)),
+ (1024, 8192, (512, 1024)),
+ (1024, 300, (300,)),
+ (1024, 768, (512, 768)),
+ ],
+ )
+ def test_short_and_long_row_graphs(self, tokens: int, window: int, seqlens: tuple[int, ...]) -> None:
+ assert seqlen_buckets(tokens, window) == seqlens
+
+ def test_the_shape_set_is_fixed_and_small(self) -> None:
+ assert len(bucketed_shapes(1024, 8192)) == 10
+ assert len(bucketed_shapes(2048, 8192)) == 14
+ assert len(bucketed_shapes(512, 8192)) == 6
+
+ @pytest.mark.parametrize(
+ ("total", "rows", "longest", "key"),
+ [
+ (1, 1, 1, (64, 64)),
+ (64, 4, 16, (64, 64)),
+ (65, 1, 65, (128, 128)),
+ (300, 1, 300, (384, 384)),
+ (600, 2, 300, (768, 512)),
+ (600, 1, 600, (768, 768)),
+ (1024, 8, 128, (1024, 512)),
+ # more rows than a bucket's slots move up a bucket
+ (64, 9, 7, (192, 192)),
+ (80, 20, 4, (384, 384)),
+ ],
+ )
+ def test_a_forward_replays_the_smallest_graph_that_holds_it(
+ self, total: int, rows: int, longest: int, key: tuple[int, int]
+ ) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024, window=8192)
+ assert runner.key(total, rows, longest) == key
+
+ def test_past_the_bound_or_the_slots_runs_eagerly(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ assert runner.key(1025, 1, 64) is None
+ assert runner.key(200, 65, 4) is None
+
+ def test_graph_modes(self) -> None:
+ assert parse_graph_mode("bucketed", adapter="A") == "bucketed"
+ assert parse_graph_mode("off", adapter="A") == "off"
+ assert parse_graph_mode(False, adapter="A") == "off" # an unquoted YAML off
+ for value in ("exact", "on", True, None, 1):
+ with pytest.raises(ValueError, match="cuda_graphs must be 'off' or 'bucketed'"):
+ parse_graph_mode(value, adapter="A")
+
+
+# -- the packed layout ---------------------------------------------------------
+
+
+class TestLayout:
+ def test_padding_is_outside_every_sequence_and_positions_restart_per_row(self) -> None:
+ seen: list[tuple[list[int], list[int], list[int], int]] = []
+
+ def encode(
+ ids: torch.Tensor, positions: torch.Tensor, cu: torch.Tensor, max_seqlen: int, total: int
+ ) -> torch.Tensor:
+ seen.append((ids.tolist(), positions.tolist(), cu.tolist(), max_seqlen))
+ return _echo_encode(ids, positions, cu, max_seqlen, total)
+
+ runner = _Runner(encode, max_tokens=1024, pad_token_id=7)
+ lengths = [3, 1, 5]
+ packed = runner.run(_ids(lengths), lengths, lambda packed: packed)
+ assert packed is not None
+ ids, positions, cu = seen[-1][:3]
+ assert len(ids) == 64
+ assert ids[:9] == _ids(lengths)
+ assert ids[9:] == [7] * 55 # padding ids
+ assert positions[:9] == [0, 1, 2, 0, 0, 1, 2, 3, 4]
+ assert positions[9:] == [0] * 55
+ # the real rows, then every other slot empty at the real token count
+ assert cu == [0, 3, 4, 9] + [9] * (row_slots(64) - 3)
+ assert seen[-1][3] == 64
+ # the head sees the real rows only
+ assert _layout(packed) == (_ids(lengths), [0, 1, 2, 0, 0, 1, 2, 3, 4], [0, 3, 4, 9])
+ assert packed.input_ids.tolist() == _ids(lengths)
+ assert packed.lengths == lengths
+
+ def test_a_replay_rewrites_the_whole_layout(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ runner.run(_ids([40]), [40], lambda packed: None or 0)
+ packed = runner.run([5, 6], [1, 1], lambda packed: packed)
+ assert packed is not None
+ assert _layout(packed) == ([5, 6], [0, 0], [0, 1, 2])
+ assert runner.recorded == [(64, 64)]
+ assert runner.stats.replayed == 1
+
+
+# -- the recording policy -------------------------------------------------------
+
+
+def _run(runner: _Runner, lengths: list[int]) -> Any:
+ return runner.run(_ids(lengths), lengths, lambda packed: "graph")
+
+
+def _lengths_for(key: tuple[int, int]) -> list[int]:
+ """Rows that fill a graph of ``key`` exactly: one row of its ``max_seqlen``, then shorter ones."""
+ tokens, seqlen = key
+ lengths, left = [seqlen], tokens - seqlen
+ while left:
+ lengths.append(min(left, 512))
+ left -= lengths[-1]
+ return lengths
+
+
+class TestPolicy:
+ def test_a_shape_records_once_then_replays(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ assert _run(runner, [10]) == "graph"
+ assert _run(runner, [20, 30]) == "graph"
+ assert runner.recorded == [(64, 64)]
+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 1)
+
+ @pytest.mark.parametrize(
+ ("lengths", "reason"),
+ [([], "empty"), ([0], "empty"), ([_WINDOW + 1], "too_long"), ([60] * 20, "too_large")],
+ )
+ def test_forwards_a_graph_cannot_hold_run_eagerly(self, lengths: list[int], reason: str) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024, window=_WINDOW)
+ assert _run(runner, lengths) is None
+ assert runner.stats.eager == {reason: 1}
+ assert runner.recorded == []
+
+ def test_a_failed_shape_is_not_recorded_again_and_three_turn_graphs_off(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ runner.capture_error = RuntimeError("capture failed")
+ assert _run(runner, [10]) is None
+ assert _run(runner, [10]) is None
+ assert runner.stats.eager == {"recording_failed": 1, "failed_shape": 1}
+ assert _run(runner, [100]) == "graph" # other shapes still record
+ runner.capture_error, runner.keep_failing = RuntimeError("capture failed"), True
+ with caplog.at_level(logging.ERROR):
+ assert _run(runner, [200]) is None
+ assert _run(runner, [300]) is None
+ assert runner.disabled
+ assert runner.graph_count == 0
+ assert "off for this process" in caplog.text
+ assert _run(runner, [100]) is None
+ assert runner.stats.eager["disabled"] == 1
+ assert runner.stats.recording_failures == 3
+
+ def test_a_failed_first_replay_counts_as_a_failed_recording(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ original = runner._replay
+
+ def failing(*args: Any) -> Any:
+ raise RuntimeError("replay failed")
+
+ runner._replay = failing # ty: ignore[invalid-assignment]
+ assert _run(runner, [10]) is None
+ assert runner.graph_count == 0
+ runner._replay = original # ty: ignore[invalid-assignment]
+ assert _run(runner, [10]) is None
+ assert runner.stats.eager == {"recording_failed": 1, "failed_shape": 1}
+
+ def test_head_errors_fail_the_forward_but_not_the_shape(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+
+ def head(packed: PackedForward) -> Any:
+ raise ValueError("head failed")
+
+ for _ in range(4):
+ with pytest.raises(ValueError, match="head failed"):
+ runner.run(_ids([10]), [10], head)
+ assert runner.stats.recording_failures == 0
+ assert not runner.disabled
+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 3)
+
+ def test_running_out_of_memory_while_recording_drops_graphs_and_pauses(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ _run(runner, [10])
+ runner.capture_error = torch.OutOfMemoryError("CUDA out of memory")
+ assert _run(runner, [100]) is None
+ assert runner.graph_count == 0
+ assert runner.stats.drops == 1
+ assert _run(runner, [10]) is None
+ assert runner.stats.eager["recording_paused"] == 1
+ runner.now += 62.0
+ assert _run(runner, [10]) == "graph"
+ assert 100 not in {key[0] for key in runner._failed}
+
+ def test_out_of_memory_in_a_first_replay_drops_the_graphs_and_pauses(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ _run(runner, [10])
+ original = runner._replay
+
+ def out_of_memory(*args: Any) -> Any:
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ runner._replay = out_of_memory # ty: ignore[invalid-assignment]
+ with pytest.raises(torch.OutOfMemoryError):
+ _run(runner, [100])
+ runner._replay = original # ty: ignore[invalid-assignment]
+ assert runner.graph_count == 0
+ assert runner.stats.drops == 1
+ assert runner.stats.recording_failures == 0
+ assert _run(runner, [100]) is None
+ assert runner.stats.eager == {"recording_paused": 1}
+ runner.now += 62.0
+ assert _run(runner, [100]) == "graph"
+
+ def test_out_of_memory_in_a_forward_drops_the_graphs(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ _run(runner, [10])
+
+ def head(packed: PackedForward) -> Any:
+ raise torch.OutOfMemoryError("CUDA out of memory")
+
+ with pytest.raises(torch.OutOfMemoryError):
+ runner.run(_ids([10]), [10], head)
+ assert runner.graph_count == 0
+ assert runner.stats.drops == 1
+ assert _run(runner, [10]) == "graph"
+
+ def test_recording_is_rationed(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=8192)
+ shapes = sorted(bucketed_shapes(8192, 8192))
+ for key in shapes[:16]:
+ assert _run(runner, _lengths_for(key)) == "graph"
+ assert _run(runner, _lengths_for(shapes[16])) is None
+ assert runner.stats.eager == {"recording_paused": 1}
+ runner.now += 2.0
+ assert _run(runner, _lengths_for(shapes[16])) == "graph"
+ assert runner.recorded == shapes[:17]
+
+ def test_no_recording_without_headroom_or_while_another_model_records(self) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ runner.headroom = False
+ assert _run(runner, [10]) is None
+ runner.headroom = True
+ assert RECORDING_LOCK.acquire(blocking=False)
+ try:
+ assert _run(runner, [10]) is None
+ finally:
+ RECORDING_LOCK.release()
+ assert runner.stats.eager == {"no_headroom": 1, "busy": 1}
+ assert _run(runner, [10]) == "graph"
+ assert not RECORDING_LOCK.locked()
+
+ def test_the_recording_lock_is_shared_with_the_gliclass_graphs(self) -> None:
+ assert gliclass_graphs._RECORDING_LOCK is RECORDING_LOCK
+ assert graphs_module.RECORDING_LOCK is RECORDING_LOCK
+
+ def test_a_full_budget_stops_recording_and_keeps_the_graphs(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024)
+ runner.bytes_per_graph = 10 * 2**20
+ runner.budget = 15 * 2**20
+ _run(runner, [10])
+ with caplog.at_level(logging.WARNING):
+ _run(runner, [100]) # over budget once kept
+ assert "their memory budget" in caplog.text
+ assert _run(runner, [300]) is None
+ assert runner.stats.eager == {"budget_full": 1}
+ assert _run(runner, [10]) == "graph"
+ assert _run(runner, [100]) == "graph"
+ assert runner.graph_count == 2
+
+ def test_held_memory_counts_recordings_buffers_and_tables(self) -> None:
+ table = torch.zeros(1024)
+ runner = _Runner(_echo_encode, max_tokens=1024, static_tensors=[table])
+ runner.bytes_per_graph = 1000
+ _run(runner, [10])
+ inputs = (2 * 64 + row_slots(64) + 1) * 4
+ hidden = 1024 * _HIDDEN * 4
+ assert runner.held_bytes == 1000 + inputs + hidden + table.nbytes
+ runner.clear()
+ assert runner.held_bytes == table.nbytes
+
+ def test_counters_are_logged_every_ten_minutes(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner(_echo_encode, max_tokens=1024, name="m")
+ _run(runner, [10])
+ runner.now += 601.0
+ with caplog.at_level(logging.INFO):
+ _run(runner, [10])
+ assert "ModernBERT CUDA graphs for m: 2 forwards" in caplog.text
+
+
+# -- adapters ----------------------------------------------------------------
+
+
+def _tokenizer() -> PreTrainedTokenizerFast:
+ specials = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[Q]", "[D]"]
+ vocab = {token: index for index, token in enumerate([*specials, *_WORDS, ".", ","])}
+ backend = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]")) # noqa: S106 -- a vocabulary entry, not a secret
+ backend.pre_tokenizer = pre_tokenizers.Whitespace()
+ backend.post_processor = processors.TemplateProcessing(
+ single="[CLS] $A [SEP]",
+ pair="[CLS] $A [SEP] $B [SEP]",
+ special_tokens=[("[CLS]", vocab["[CLS]"]), ("[SEP]", vocab["[SEP]"])],
+ )
+ return PreTrainedTokenizerFast(
+ tokenizer_object=backend,
+ pad_token="[PAD]", # noqa: S106
+ unk_token="[UNK]", # noqa: S106
+ cls_token="[CLS]", # noqa: S106
+ sep_token="[SEP]", # noqa: S106
+ model_max_length=_WINDOW,
+ )
+
+
+def _config(**extra: Any) -> ModernBertConfig:
+ torch.manual_seed(0)
+ return ModernBertConfig(
+ vocab_size=32,
+ hidden_size=_HIDDEN,
+ intermediate_size=48,
+ num_hidden_layers=4,
+ num_attention_heads=2,
+ global_attn_every_n_layers=3,
+ local_attention=8,
+ global_rope_theta=160000.0,
+ local_rope_theta=10000.0,
+ max_position_embeddings=_WINDOW,
+ pad_token_id=0,
+ attn_implementation="eager",
+ **extra,
+ )
+
+
+def _sharpen(model: torch.nn.Module) -> None:
+ """Larger attention weights, so a wrong position, window or RoPE base changes the outputs visibly."""
+ with torch.no_grad():
+ for name, parameter in model.named_parameters():
+ if "Wqkv" in name:
+ parameter.mul_(8.0)
+
+
+def _texts(count: int, offset: int = 0) -> list[Item]:
+ return [Item(text=_TEXTS[(offset + i) % len(_TEXTS)]) for i in range(count)]
+
+
+def _attach_cpu_graphs(adapter: Any, encode: Any, tables: list[torch.Tensor], window: int) -> _Runner:
+ runner = _Runner(encode, max_tokens=1024, window=window, static_tensors=tables)
+ adapter._graphs = runner
+ return runner
+
+
+def _dense_pair() -> tuple[ModernBERTFlashAdapter, ModernBERTFlashAdapter, _Runner]:
+ model = ModernBertModel(_config()).eval()
+ _sharpen(model)
+ adapters = []
+ for graphs in ("bucketed", "off"):
+ adapter = ModernBERTFlashAdapter(
+ "tiny", compute_precision="float32", max_seq_length=_WINDOW, cuda_graphs=graphs
+ )
+ adapter._model, adapter._tokenizer, adapter._device, adapter._dense_dim = model, _tokenizer(), "cpu", _HIDDEN
+ adapters.append(adapter)
+ encode, tables = modernbert_encoder(model, window=_WINDOW, dtype=torch.float32)
+ runner = _attach_cpu_graphs(adapters[0], encode, tables, _WINDOW)
+ return adapters[0], adapters[1], runner
+
+
+def _colbert_pair() -> tuple[ColBERTModernBERTFlashAdapter, ColBERTModernBERTFlashAdapter, _Runner]:
+ model = ModernBertModel(_config()).eval()
+ _sharpen(model)
+ chain = [torch.randn(16, _HIDDEN), torch.randn(8, 16)]
+ adapters = []
+ for graphs in ("bucketed", "off"):
+ adapter = ColBERTModernBERTFlashAdapter(
+ "tiny",
+ token_dim=8,
+ compute_precision="float32",
+ max_seq_length=_WINDOW,
+ query_max_length=12,
+ doc_punctuation_skiplist=True,
+ cuda_graphs=graphs,
+ )
+ adapter._model, adapter._tokenizer, adapter._device, adapter._dense_chain = model, _tokenizer(), "cpu", chain
+ adapter._doc_skiplist_ids = {adapter._tokenizer.convert_tokens_to_ids(",")}
+ adapters.append(adapter)
+ encode, tables = modernbert_encoder(model, window=_WINDOW, dtype=torch.float32)
+ runner = _attach_cpu_graphs(adapters[0], encode, tables, _WINDOW)
+ return adapters[0], adapters[1], runner
+
+
+def _reranker_pair(
+ monkeypatch: pytest.MonkeyPatch, pooling: str
+) -> tuple[ModernBertFlashCrossEncoderAdapter, ModernBertFlashCrossEncoderAdapter, _Runner]:
+ from sie_server.adapters import modernbert_flash_cross_encoder as module
+
+ monkeypatch.setattr(module, "rotate_packed_qkv_", _reference_rotate_packed)
+ model = ModernBertForSequenceClassification(_config(num_labels=1, classifier_pooling=pooling)).eval()
+ _sharpen(model)
+ for layer in model.model.layers:
+ base = 160000.0 if layer.attn.local_attention == (-1, -1) else 10000.0
+ layer.attn.rotary_emb = _FlashRotary(_HIDDEN // 2, base)
+ adapters = []
+ for graphs in ("bucketed", "off"):
+ adapter = ModernBertFlashCrossEncoderAdapter(
+ "tiny", compute_precision="float32", max_seq_length=_WINDOW, cuda_graphs=graphs
+ )
+ adapter._model, adapter._tokenizer, adapter._device, adapter._dtype = model, _tokenizer(), "cpu", torch.float32
+ adapter._num_heads, adapter._hidden_size, adapter._head_dim = 2, _HIDDEN, _HIDDEN // 2
+ adapter._use_sigmoid, adapter._use_mean_pooling = True, pooling == "mean"
+ adapters.append(adapter)
+ encoded = adapters[0]._graph_encoder(_WINDOW)
+ assert encoded is not None
+ runner = _attach_cpu_graphs(adapters[0], *encoded, _WINDOW)
+ return adapters[0], adapters[1], runner
+
+
[email protected]("reference_flash")
+class TestAdapters:
+ @pytest.mark.parametrize("pooling", ["cls", "mean"])
+ @pytest.mark.parametrize(("count", "offset"), [(1, 0), (1, 23), (5, 3), (12, 0)])
+ def test_dense_vectors_match_eager(self, pooling: str, count: int, offset: int) -> None:
+ graphed, eager, runner = _dense_pair()
+ items = _texts(count, offset)
+ options = {"pooling": pooling}
+ for _ in range(2): # recorded, then replayed
+ got = graphed.encode(items, ["dense"], options=options)
+ want = eager.encode(items, ["dense"], options=options)
+ np.testing.assert_allclose(got.dense, want.dense, atol=1e-5)
+ assert got.extra["input_token_counts"] == want.extra["input_token_counts"]
+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 1)
+
+ @pytest.mark.parametrize("is_query", [True, False])
+ @pytest.mark.parametrize(("count", "offset"), [(1, 5), (4, 0), (9, 11)])
+ def test_token_vectors_match_eager(self, is_query: bool, count: int, offset: int) -> None:
+ graphed, eager, runner = _colbert_pair()
+ items = _texts(count, offset)
+ for _ in range(2):
+ got = graphed.encode(items, ["multivector"], is_query=is_query)
+ want = eager.encode(items, ["multivector"], is_query=is_query)
+ assert [g.shape for g in got.multivector] == [w.shape for w in want.multivector]
+ for g, w in zip(got.multivector, want.multivector, strict=True):
+ np.testing.assert_allclose(g, w, atol=1e-5)
+ assert got.extra == want.extra
+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 1)
+
+ def test_maxsim_scores_match_eager(self) -> None:
+ graphed, eager, _ = _colbert_pair()
+ query, docs = Item(text=_TEXTS[3]), _texts(6, 7)
+ np.testing.assert_allclose(graphed.score(query, docs), eager.score(query, docs), atol=1e-4)
+
+ @pytest.mark.parametrize("pooling", ["cls", "mean"])
+ @pytest.mark.parametrize(("count", "offset"), [(1, 0), (3, 9), (8, 2)])
+ def test_rerank_scores_match_eager(
+ self, monkeypatch: pytest.MonkeyPatch, pooling: str, count: int, offset: int
+ ) -> None:
+ graphed, eager, runner = _reranker_pair(monkeypatch, pooling)
+ queries, docs = _texts(count, offset), _texts(count, offset + 5)
+ for _ in range(2):
+ got = graphed.score_pairs(queries, docs)
+ want = eager.score_pairs(queries, docs)
+ np.testing.assert_allclose(got.scores, want.scores, atol=1e-5)
+ np.testing.assert_allclose(graphed.score(queries[0], docs), eager.score(queries[0], docs), atol=1e-5)
+ assert runner.stats.forwards == runner.stats.recorded + runner.stats.replayed == 3
+
+ def test_rows_past_the_bound_run_eagerly(self) -> None:
+ graphed, eager, runner = _dense_pair()
+ runner._max_tokens, runner._tokens = 64, token_buckets(64)
+ items = _texts(12)
+ np.testing.assert_allclose(
+ graphed.encode(items, ["dense"]).dense, eager.encode(items, ["dense"]).dense, atol=1e-5
+ )
+ assert runner.stats.eager == {"too_large": 1}
+
+ def test_a_model_with_lora_adapters_loaded_runs_eagerly(self) -> None:
+ graphed, _, runner = _dense_pair()
+ graphed._peft_model = SimpleNamespace() # ty: ignore[invalid-assignment]
+ graphed.encode(_texts(2), ["dense"])
+ assert runner.stats.forwards == 0
+
+ def test_unload_drops_the_graphs(self) -> None:
+ graphed, _, _ = _dense_pair()
+ graphed.unload()
+ assert graphed._graphs is None
+
+
+class TestOptions:
+ @pytest.mark.parametrize(
+ "adapter", [ModernBERTFlashAdapter, ColBERTModernBERTFlashAdapter, ModernBertFlashCrossEncoderAdapter]
+ )
+ def test_cuda_graphs_is_a_load_time_option(self, adapter: Any) -> None:
+ reject_unknown_loadtime_options(adapter, {"cuda_graphs": "bucketed"}, model_name="m")
+ assert adapter("m", cuda_graphs="bucketed")._cuda_graphs == "bucketed"
+ assert adapter("m", cuda_graphs=False)._cuda_graphs == "off"
+ assert adapter("m")._cuda_graphs == "off"
+ with pytest.raises(ValueError, match="cuda_graphs must be 'off' or 'bucketed'"):
+ adapter("m", cuda_graphs="exact")
+
+ def test_off_cuda_the_adapters_build_no_runner(self, caplog: pytest.LogCaptureFixture) -> None:
+ adapter = ModernBERTFlashAdapter("m", cuda_graphs="bucketed")
+ adapter._model = ModernBertModel(_config()).eval()
+ adapter._tokenizer, adapter._device = _tokenizer(), "cpu"
+ with caplog.at_level(logging.WARNING):
+ assert adapter._graph_runner(torch.float32) is None
+ assert "CUDA graphs need a CUDA device" in caplog.text
+
+ def test_profiles_on_other_workers_do_not_inherit_graphs(self) -> None:
+ """A profile that extends a graphed default onto the Candle worker must set its own load-time options.
+
+ The Candle worker refuses load-time options it does not know, and a
+ profile without its own load-time options inherits the default's.
+ """
+ for config in load_model_configs(_MODELS_DIR).values():
+ for name in config.profiles:
+ profile = config.resolve_profile(name)
+ if not profile.adapter_path.startswith("sie_server."):
+ assert "cuda_graphs" not in profile.loadtime, f"{config.sie_id} profile {name}"
+
+ def test_shipped_profiles_load_with_graphs(self) -> None:
+ """Every model on these adapters ships with graphs: each passed the margin rule (see the server README)."""
+ graphed = set()
+ for config in load_model_configs(_MODELS_DIR).values():
+ for name in config.profiles:
+ profile = config.resolve_profile(name)
+ if profile.adapter_path in _ADAPTER_PATHS:
+ assert parse_graph_mode(profile.loadtime.get("cuda_graphs"), adapter=profile.adapter_path) == (
+ "bucketed"
+ ), f"{config.sie_id} profile {name}"
+ graphed.add(config.sie_id.split(":")[0])
+ assert graphed == _GRAPHS_BY_DEFAULT
+
+
+# -- real graphs -------------------------------------------------------------
+
+
+def _cuda_ready() -> bool:
+ if not torch.cuda.is_available():
+ return False
+ from sie_server.core.inference import is_flash_attention_available
+
+ return is_flash_attention_available("cuda:0")
+
+
+class TestOnGpu:
+ def test_recorded_graphs_match_eager(self) -> None:
+ if not _cuda_ready():
+ pytest.skip("requires CUDA and flash-attn")
+ model = ModernBertModel(_config()).eval().to("cuda", torch.bfloat16)
+ adapters = []
+ for graphs in ("bucketed", "off"):
+ adapter = ModernBERTFlashAdapter("tiny", max_seq_length=_WINDOW, cuda_graphs=graphs)
+ adapter._model, adapter._tokenizer, adapter._device, adapter._dense_dim = (
+ model,
+ _tokenizer(),
+ "cuda:0",
+ _HIDDEN,
+ )
+ adapter._graphs = adapter._graph_runner(torch.bfloat16)
+ adapters.append(adapter)
+ graphed, eager = adapters
+ assert graphed._graphs is not None
+ for count, offset in ((1, 0), (5, 3), (12, 0), (1, 23)):
+ items = _texts(count, offset)
+ for _ in range(2):
+ got = graphed.encode(items, ["dense"]).dense
+ want = eager.encode(items, ["dense"]).dense
+ cosine = (got * want).sum(1) / (np.linalg.norm(got, axis=1) * np.linalg.norm(want, axis=1))
+ assert cosine.min() > 0.999
+ stats = graphed._graphs.stats
+ assert stats.recorded >= 1
+ assert stats.replayed >= 4
+ assert stats.recording_failures == 0
+ assert graphed._graphs.held_bytes > 0
diff --git a/packages/sie_server/tests/adapters/test_packed_rope.py b/packages/sie_server/tests/adapters/test_packed_rope.py
new file mode 100644
index 000000000..4ae81b300
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_packed_rope.py
@@ -0,0 +1,108 @@
+"""The packed rotary kernel: when it applies, what it accepts, and its arithmetic against flash-attn's."""
+
+from __future__ import annotations
+
+import pytest
+import torch
+from sie_server.adapters import _packed_rope
+from sie_server.adapters._packed_rope import packed_rope_available, rotate_packed_qkv_
+
+
+def _inputs(
+ tokens: int = 5, heads: int = 2, head_dim: int = 8, dtype: torch.dtype = torch.float16
+) -> tuple[torch.Tensor, ...]:
+ qkv = torch.zeros(tokens, 3, heads, head_dim, dtype=dtype)
+ positions = torch.arange(tokens, dtype=torch.int32)
+ cos = torch.ones(16, head_dim // 2, dtype=dtype)
+ return qkv, positions, cos, torch.zeros_like(cos)
+
+
+def test_it_applies_on_cuda_with_triton(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(_packed_rope, "_TRITON", True)
+ assert packed_rope_available("cuda:0")
+ assert packed_rope_available(torch.device("cuda", 1))
+ assert not packed_rope_available("cpu")
+ assert not packed_rope_available("mps")
+ monkeypatch.setattr(_packed_rope, "_TRITON", False)
+ assert not packed_rope_available("cuda:0")
+ with pytest.raises(RuntimeError, match="needs Triton"):
+ rotate_packed_qkv_(*_inputs())
+
+
[email protected](not _packed_rope._TRITON, reason="requires Triton")
+ ("change", "message"),
+ [
+ (lambda q, p, c, s: (q[:, :2], p, c, s), "contiguous"),
+ (lambda q, p, c, s: (torch.zeros(5, 3, 2, 7, dtype=q.dtype), p, c, s), "contiguous"), # odd head_dim
+ (lambda q, p, c, s: (q, p, c[:, :3], s[:, :3]), "cos and sin tables"),
+ (lambda q, p, c, s: (q, p, c, s[:8]), "cos and sin tables"),
+ (lambda q, p, c, s: (q, p, c.float(), s.float()), "must be torch.float16"),
+ (lambda q, p, c, s: (q, p[:4], c, s), "expected 5 positions"),
+ ],
+)
+def test_layouts_it_does_not_handle_are_refused(change, message: str) -> None:
+ with pytest.raises(ValueError, match=message):
+ rotate_packed_qkv_(*change(*_inputs()))
+
+
[email protected](not _packed_rope._TRITON, reason="requires Triton")
+def test_no_tokens_launch_nothing() -> None:
+ rotate_packed_qkv_(*_inputs(tokens=0)) # CPU tensors: a launch would fail
+
+
+def test_rotation_matches_flash_attn_bit_for_bit() -> None:
+ if not torch.cuda.is_available():
+ pytest.skip("requires CUDA")
+ rotary = pytest.importorskip("flash_attn.ops.triton.rotary")
+ torch.manual_seed(0)
+ lengths = [7, 300, 1, 64, 129]
+ 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]).int()
+ for dtype in (torch.float16, torch.bfloat16):
+ for heads, base in ((12, 160000.0), (6, 10000.0)):
+ qkv = torch.randn(total, 3, heads, 64, device="cuda", dtype=dtype) * 3
+ inv_freq = 1.0 / (base ** (torch.arange(0, 64, 2, device="cuda", dtype=torch.float32) / 64))
+ freqs = torch.outer(torch.arange(512, device="cuda", dtype=torch.float32), inv_freq)
+ cos, sin = freqs.cos().to(dtype), freqs.sin().to(dtype)
+ want = qkv.clone()
+ rotary.apply_rotary(
+ want[:, :2].view(total, -1, 64), cos, sin, cu_seqlens=cu, max_seqlen=max(lengths), inplace=True
+ )
+ got = qkv.clone()
+ rotate_packed_qkv_(got, positions, cos, sin)
+ assert torch.equal(got, want)
+ # a [positions, head_dim] table's first half, as the shared layer stack holds them
+ wide = qkv.clone()
+ rotate_packed_qkv_(
+ wide, positions.long(), torch.cat([cos, cos], -1)[:, :32], torch.cat([sin, sin], -1)[:, :32]
+ )
+ assert torch.equal(wide, want)
+
+
+def test_strided_positions_and_rows_outside_the_tables() -> None:
+ """Positions are read at their stride; a position outside the tables leaves its token unrotated."""
+ if not torch.cuda.is_available():
+ pytest.skip("requires CUDA")
+ torch.manual_seed(0)
+ qkv = torch.randn(4, 3, 2, 8, device="cuda", dtype=torch.float16)
+ cos = torch.rand(16, 4, device="cuda", dtype=torch.float16)
+ sin = torch.rand(16, 4, device="cuda", dtype=torch.float16)
+ strided = torch.tensor([3, 99, 0, 99, 7, 99, 15, 99], device="cuda", dtype=torch.int32)[::2]
+ got, want = qkv.clone(), qkv.clone()
+ rotate_packed_qkv_(got, strided, cos, sin)
+ rotate_packed_qkv_(want, strided.contiguous(), cos, sin)
+ assert torch.equal(got, want)
+ assert not torch.equal(got, qkv)
+
+ outside = torch.tensor([2, -1, 16, 5], device="cuda", dtype=torch.int32)
+ qkv[2, 0, 0, 5] = float("inf") # left as is, not multiplied by a zero sine
+ rotated = qkv.clone()
+ rotate_packed_qkv_(rotated, outside, cos, sin)
+ assert torch.equal(rotated[1:3], qkv[1:3])
+ reference = qkv.clone()
+ rotate_packed_qkv_(reference, torch.tensor([2, 0, 0, 5], device="cuda", dtype=torch.int32), cos, sin)
+ assert torch.equal(rotated[[0, 3]], reference[[0, 3]])