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(gliner2): CUDA graphs and one pass per batch for GLiNER2.5-Decide (#721)

svonavadfd25cf2bbea
diff --git a/packages/sie_server/models/fastino__GLiNER2.5-Decide.yaml b/packages/sie_server/models/fastino__GLiNER2.5-Decide.yaml
index c5f69b696..5644cb75c 100644
--- a/packages/sie_server/models/fastino__GLiNER2.5-Decide.yaml
+++ b/packages/sie_server/models/fastino__GLiNER2.5-Decide.yaml
@@ -24,5 +24,11 @@ profiles:
compute_precision: float16
adapter_path: sie_server.adapters.gliner2.decide:GLiNER2DecideAdapter
adapter_options:
- loadtime: {}
+ loadtime:
+ # Replays the encoder's forward as a CUDA graph for calls of up to 32
+ # rows and 2,048 padded tokens (adapters/gliner2/decide_graphs.py): one
+ # short message takes the GPU 6 ms instead of the 28 ms the host needs
+ # to launch its kernels on an L4. Scores move as they do when requests
+ # are batched together; "off" runs every forward eagerly.
+ cuda_graphs: bucketed
runtime: {}
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/decide.py b/packages/sie_server/src/sie_server/adapters/gliner2/decide.py
index 5a38f92c6..aa2b442bf 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner2/decide.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/decide.py
@@ -29,6 +29,20 @@ the model reads. An item none of whose words fits returns a per-item
``INPUT_TOO_LONG`` error, as does any item that does not fit whole when
``options.overflow_policy`` is ``"error"``.
+CUDA graphs: with ``adapter_options.loadtime.cuda_graphs: bucketed`` a DeBERTa
+encoder on CUDA replays its forwards as CUDA graphs (see ``decide_graphs.py``).
+It is an operator setting; ``"off"`` (the default) runs every forward eagerly.
+A call of up to 32 rows and 2,048 padded tokens then pads to the length bucket
+and batch size of its graph, which rounds float16 sums as batching rows
+together already does; a larger call runs eagerly as before.
+
+One pass per batch: a batch the worker formed may hold requests with different
+labels, questions or options. The worker hands them all to
+``prime_extract_groups`` first, which scores every row in one pass, each row at
+its own label markers; the ``extract`` call of each request shape then reads its
+rows' logits from that pass instead of running a forward of its own. Rows of
+different shapes are padded and batched together, as rows of one shape are.
+
Usage: an item's input tokens are its document tokens the model reads plus the
tokens of the caller's free text encoded with it (question instructions and
label descriptions), as the Laya and GLiClass adapters count instructions and
@@ -42,12 +56,13 @@ import json
import logging
import re
import tempfile
-from collections.abc import Iterator, Mapping
-from contextlib import contextmanager
+from collections import OrderedDict
+from collections.abc import Iterator, Mapping, Sequence
+from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
-from typing import Any, ClassVar
+from typing import Any, ClassVar, cast
import numpy as np
import torch
@@ -58,6 +73,14 @@ from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters.errors import InputTooLongError
+from sie_server.adapters.gliner2.decide_graphs import (
+ GRAPH_MODES,
+ MAX_GRAPH_TOKENS,
+ DecideGraphRunner,
+ GraphMode,
+ Key,
+ unsupported_reason,
+)
from sie_server.adapters.gliner2.decisions import (
DecisionRequest,
answer,
@@ -71,6 +94,7 @@ from sie_server.adapters.gliner2.decisions import (
from sie_server.adapters.gliner2.words import linear_equivalent
from sie_server.adapters.laya.questions import STATE_BYTES_PER_TOKEN, serialize_state
from sie_server.core.inference_output import ExtractItemError, ExtractOutput
+from sie_server.core.oom import is_oom_error
from sie_server.types.inputs import InvalidInputError, Item
from sie_server.types.overflow_policy import DEFAULT_OVERFLOW_POLICY, VALID_OVERFLOW_POLICIES
from sie_server.types.responses import Classification, ErrorCode
@@ -103,6 +127,13 @@ _COST_CHARS_PER_TOKEN = 4
# most; a longer word (a hash, an id, a base64 run) is tokenized each time.
_WORD_CACHE_SIZE = 16384
_CACHED_WORD_CHARS = 32
+# Task prompts of recent request shapes, kept across requests: the same labels
+# or questions usually come with every request of an application. Only shapes
+# whose schema takes at most _CACHED_PROMPT_CHARS characters are kept (eight
+# short labels take about 400), so the cache holds about 1 MB at most; a larger
+# schema (long descriptions) builds its prompt each time.
+_PROMPT_CACHE_SIZE = 256
+_CACHED_PROMPT_CHARS = 4096
_SENTENCE_END = (".", "!", "?")
_ERR_ITEM = (
@@ -337,7 +368,17 @@ class GLiNER2DecideAdapter(BaseAdapter):
spec: ClassVar[AdapterSpec] = AdapterSpec(
inputs=("text",),
outputs=("json",),
- unload_fields=("_model", "_processor", "_tokenizer", "_word_splitter", "_word_ids", "_word_cache"),
+ unload_fields=(
+ "_model",
+ "_processor",
+ "_tokenizer",
+ "_word_splitter",
+ "_word_ids",
+ "_word_cache",
+ "_graphs",
+ "_prompts",
+ "_primed",
+ ),
)
def __init__(
@@ -349,6 +390,7 @@ class GLiNER2DecideAdapter(BaseAdapter):
inference_batch_tokens: int = _DEFAULT_INFERENCE_BATCH_TOKENS,
compute_precision: ComputePrecision = "float16",
revision: str | None = None,
+ cuda_graphs: str | bool = "off",
**kwargs: Any,
) -> None:
"""Initialize the adapter.
@@ -363,9 +405,21 @@ class GLiNER2DecideAdapter(BaseAdapter):
compute_precision: Accelerator precision (``float16`` is the package's
``quantize=True``). CPU always runs float32.
revision: Hugging Face revision (commit SHA) to pin.
+ cuda_graphs: "off" (the default) or "bucketed": whether a DeBERTa
+ encoder on CUDA replays its forwards as CUDA graphs (see
+ ``decide_graphs.py``). An operator setting. YAML reads an
+ unquoted ``off`` as False, which means "off" too.
**kwargs: Additional loader arguments (ignored).
+
+ Raises:
+ ValueError: If the window, the prompt bound, the batch bound or
+ ``cuda_graphs`` is not a value this adapter takes.
"""
_ = kwargs
+ if cuda_graphs is False: # an unquoted YAML ``off``
+ cuda_graphs = "off"
+ if not isinstance(cuda_graphs, str) or cuda_graphs not in GRAPH_MODES:
+ raise ValueError(f"GLiNER2.5-Decide cuda_graphs must be 'off' or 'bucketed', got {cuda_graphs!r}")
window = _DEFAULT_WINDOW if max_seq_length is None else int(max_seq_length)
prompt = min(window // 2, _DEFAULT_MAX_PROMPT_TOKENS) if max_prompt_tokens is None else int(max_prompt_tokens)
if window < 2 or not 0 < prompt < window:
@@ -378,6 +432,7 @@ class GLiNER2DecideAdapter(BaseAdapter):
self._inference_batch_tokens = int(inference_batch_tokens)
self._compute_precision = compute_precision
self._revision = revision
+ self._cuda_graphs = cast("GraphMode", cuda_graphs)
self._model: Any = None
self._processor: Any = None
@@ -386,6 +441,14 @@ class GLiNER2DecideAdapter(BaseAdapter):
self._word_ids: Any = None
self._word_cache: Any = None
self._device: str | None = None
+ # Records and replays the encoder's forwards as CUDA graphs, when the
+ # operator turned them on and the loaded encoder supports them.
+ self._graphs: DecideGraphRunner | None = None
+ # Task prompts of recent request shapes, by schema (see _PROMPT_CACHE_SIZE).
+ self._prompts: OrderedDict[str, _Prefix] | None = None
+ # Logits ``prime_extract_groups`` scored for the batch in progress, by
+ # (row token ids, label markers); ``extract`` takes its rows' from here.
+ self._primed: dict[tuple[tuple[int, ...], tuple[int, ...]], np.ndarray] | None = None
# ------------------------------------------------------------------ loading
@@ -426,8 +489,9 @@ class GLiNER2DecideAdapter(BaseAdapter):
model.to(dtype=torch.bfloat16)
self._attach(model, processor, device)
+ self._graphs = self._graph_runner(model, device)
logger.info(
- "Loaded GLiNER2.5-Decide %s (%s) on %s: %s, window %d tokens, prompt at most %d, RoPE %s",
+ "Loaded GLiNER2.5-Decide %s (%s) on %s: %s, window %d tokens, prompt at most %d, RoPE %s, CUDA graphs %s",
self._model_name_or_path,
type(model).__name__,
device,
@@ -435,6 +499,31 @@ class GLiNER2DecideAdapter(BaseAdapter):
self._window,
self._max_prompt_tokens,
rope,
+ "off" if self._graphs is None else f"{self._cuda_graphs} ({self._graphs.shape_count} shapes)",
+ )
+
+ def _graph_runner(self, model: Any, device: str) -> DecideGraphRunner | None:
+ """The CUDA graph runner for a loaded model; None when graphs are off or unsupported."""
+ if self._cuda_graphs == "off":
+ return None
+ # A graph's padded shape is a forward pass, so it keeps to the operator's bound on one.
+ max_tokens = min(MAX_GRAPH_TOKENS, self._inference_batch_tokens)
+ reason = unsupported_reason(model.encoder, device, self._window, max_tokens)
+ if reason is not None:
+ logger.warning(
+ "GLiNER2.5-Decide cuda_graphs=%s does not apply to %s, which runs eagerly: %s",
+ self._cuda_graphs,
+ self._model_name_or_path,
+ reason,
+ )
+ return None
+ pad = getattr(self._tokenizer, "pad_token_id", None)
+ return DecideGraphRunner(
+ model.encoder,
+ window=self._window,
+ pad_token_id=0 if pad is None else int(pad),
+ name=self._model_name_or_path,
+ max_tokens=max_tokens,
)
def _attach(self, model: Any, processor: Any, device: str) -> None:
@@ -467,6 +556,8 @@ class GLiNER2DecideAdapter(BaseAdapter):
self._word_splitter = splitter
self._word_ids = word_ids
self._word_cache = cached
+ self._prompts = OrderedDict()
+ self._primed = {}
self._device = device
def warmup(self) -> None:
@@ -489,27 +580,12 @@ class GLiNER2DecideAdapter(BaseAdapter):
_ = prepared_items
if self._model is None:
raise RuntimeError(ERR_NOT_LOADED)
- opts = options or {}
- request = parse_request(labels=labels, output_schema=output_schema, instruction=instruction, options=opts)
- overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
- if not isinstance(overflow_policy, str) or overflow_policy not in VALID_OVERFLOW_POLICIES:
- raise InvalidInputError(
- f"GLiNER2.5-Decide overflow_policy must be one of {sorted(VALID_OVERFLOW_POLICIES)}"
- )
-
- with self._tokenizer_guard():
- prefix = self._prefix(request)
- room = self._window - len(prefix.ids)
- documents: list[_Document | None] = []
- errors: list[ExtractItemError | None] = []
- for item in items:
- document, error = self._document(item, room, overflow_policy)
- documents.append(document)
- errors.append(error)
-
+ request, prefix, documents, errors = self._read_request(
+ items, labels=labels, output_schema=output_schema, instruction=instruction, options=options
+ )
kept = [(index, document) for index, document in enumerate(documents) if document is not None]
rows = [prefix.ids + document.ids for _, document in kept]
- logits = self._score(rows, prefix.label_positions) if rows else np.empty((0, 0), dtype=np.float32)
+ logits = self._logits(rows, prefix.label_positions) if rows else np.empty((0, 0), dtype=np.float32)
data: list[dict[str, Any]] = [{} for _ in items]
item_classifications: list[list[Classification]] = [[] for _ in items]
@@ -539,8 +615,116 @@ class GLiNER2DecideAdapter(BaseAdapter):
input_token_counts=token_counts,
)
+ def _read_request(
+ self,
+ items: list[Item],
+ *,
+ labels: list[str] | None,
+ output_schema: dict[str, Any] | None,
+ instruction: str | None,
+ options: dict[str, Any] | None,
+ ) -> tuple[DecisionRequest, _Prefix, list[_Document | None], list[ExtractItemError | None]]:
+ """A request's tasks and task prompt, and each item's document or error.
+
+ Raises:
+ InvalidInputError: The request is malformed.
+ InputTooLongError: The task prompt takes more than ``max_prompt_tokens``.
+ """
+ opts = options or {}
+ request = parse_request(labels=labels, output_schema=output_schema, instruction=instruction, options=opts)
+ overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
+ if not isinstance(overflow_policy, str) or overflow_policy not in VALID_OVERFLOW_POLICIES:
+ raise InvalidInputError(
+ f"GLiNER2.5-Decide overflow_policy must be one of {sorted(VALID_OVERFLOW_POLICIES)}"
+ )
+ documents: list[_Document | None] = []
+ errors: list[ExtractItemError | None] = []
+ with self._tokenizer_guard():
+ prefix = self._prefix(request)
+ room = self._window - len(prefix.ids)
+ for item in items:
+ document, error = self._document(item, room, overflow_policy)
+ documents.append(document)
+ errors.append(error)
+ return request, prefix, documents, errors
+
+ def prime_extract_groups(self, groups: Sequence[Mapping[str, Any]]) -> None:
+ """Score the rows of several ``extract`` calls in one pass, before those calls run.
+
+ The worker calls this with every request shape of a batch it is about
+ to run: each group holds the ``items`` and the ``labels``,
+ ``output_schema``, ``instruction`` and ``options`` of one ``extract``
+ call. Every group's rows are scored together, each row at its own label
+ markers, and kept by (row token ids, label markers) until the group's
+ ``extract`` call takes them. A group that cannot be read (a malformed
+ request, a task prompt too long) is left to its own ``extract`` call,
+ which reports it. Each call drops what the one before it left.
+ """
+ if self._model is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ self._primed = primed = {}
+ if len(groups) < 2:
+ return
+ rows: list[list[int]] = []
+ positions: list[list[int]] = []
+ for group in groups:
+ try:
+ _, prefix, documents, _ = self._read_request(
+ group["items"],
+ labels=group.get("labels"),
+ output_schema=group.get("output_schema"),
+ instruction=group.get("instruction"),
+ options=group.get("options"),
+ )
+ except (InvalidInputError, InputTooLongError):
+ continue
+ for document in documents:
+ if document is not None:
+ rows.append(prefix.ids + document.ids)
+ positions.append(prefix.label_positions)
+ if len(rows) < 2:
+ return
+ for row, markers, logits in zip(rows, positions, self._score_rows(rows, positions), strict=True):
+ primed[tuple(row), tuple(markers)] = logits
+
+ def _logits(self, rows: list[list[int]], label_positions: list[int]) -> np.ndarray:
+ """Every row's label logits, ``[rows, labels]``: from the batch's one pass when it scored them all."""
+ primed = self._primed
+ if primed:
+ markers = tuple(label_positions)
+ keys = [(tuple(row), markers) for row in rows]
+ found = [primed.get(key) for key in keys]
+ if all(logits is not None for logits in found):
+ for key in keys:
+ primed.pop(key, None)
+ return np.stack(cast("list[np.ndarray]", found))
+ return self._score(rows, label_positions)
+
def _prefix(self, request: DecisionRequest) -> _Prefix:
- """The task prompt as the processor builds it, once per request.
+ """The task prompt of a request, built once per request shape and kept (see ``_PROMPT_CACHE_SIZE``).
+
+ Raises:
+ InputTooLongError: The task prompt takes more than ``max_prompt_tokens``.
+ """
+ prompts = self._prompts
+ if prompts is None:
+ return self._build_prefix(request)
+ # The prompt and its billed tokens depend on nothing but these entries.
+ shape = json.dumps([task.model_entry() for task in request.tasks], ensure_ascii=False, separators=(",", ":"))
+ if len(shape) > _CACHED_PROMPT_CHARS:
+ return self._build_prefix(request)
+ prefix = prompts.get(shape)
+ if prefix is not None:
+ prompts.move_to_end(shape)
+ return prefix
+ prefix = self._build_prefix(request)
+ prompts[shape] = prefix
+ while len(prompts) > _PROMPT_CACHE_SIZE:
+ prompts.popitem(last=False)
+ return prefix
+
+ def _build_prefix(self, request: DecisionRequest) -> _Prefix:
+ """The task prompt as the processor builds it.
Raises:
InputTooLongError: The task prompt takes more than ``max_prompt_tokens``.
@@ -683,6 +867,8 @@ class GLiNER2DecideAdapter(BaseAdapter):
model, device = self._model, self._device
if model is None or device is None:
raise RuntimeError(ERR_NOT_LOADED)
+ if self._graphs is not None and self._graphs.key(len(rows), max(map(len, rows))) is not None:
+ return np.stack(self._score_rows(rows, [label_positions] * len(rows)))
order = sorted(range(len(rows)), key=lambda row: len(rows[row]), reverse=True)
out = np.empty((len(rows), len(label_positions)), dtype=np.float32)
markers = torch.tensor(label_positions, dtype=torch.long, device=device)
@@ -705,6 +891,80 @@ class GLiNER2DecideAdapter(BaseAdapter):
start += count
return out
+ def _score_rows(self, rows: list[list[int]], positions: Sequence[Sequence[int]]) -> list[np.ndarray]:
+ """Each row's label logits, read at that row's own label markers.
+
+ Rows that fit one CUDA graph together are one forward, replayed from
+ it (or run eagerly at their own length while the graph is not recorded
+ yet, or cannot be). Otherwise the rows run eagerly, sorted longest
+ first, in the padded chunks ``_score`` forms. Every forward is queued on
+ the GPU before the host waits for any of them.
+ """
+ model, device, runner = self._model, self._device, self._graphs
+ if model is None or device is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+ order = sorted(range(len(rows)), key=lambda row: len(rows[row]), reverse=True)
+ lengths = [len(rows[row]) for row in order]
+ key = runner.key(len(rows), lengths[0]) if runner is not None else None
+ pieces: list[tuple[int, Key | None]] = [(len(rows), key)] if key is not None else self._eager_pieces(lengths)
+ input_ids = np.zeros((len(rows), lengths[0]), dtype=np.int64)
+ attention_mask = np.zeros((len(rows), lengths[0]), dtype=np.int64)
+ offsets = [0]
+ for j, row in enumerate(order):
+ input_ids[j, : lengths[j]] = rows[row]
+ attention_mask[j, : lengths[j]] = 1
+ offsets.append(offsets[-1] + len(positions[row]))
+ marker_positions = np.fromiter(
+ (position for row in order for position in positions[row]), dtype=np.int64, count=offsets[-1]
+ )
+ # Each marker's row, counted from the start of the row's own forward.
+ marker_rows = np.empty(offsets[-1], dtype=np.int64)
+ start = 0
+ for count, _ in pieces:
+ for j in range(start, start + count):
+ marker_rows[offsets[j] : offsets[j + 1]] = j - start
+ start += count
+
+ parts: list[torch.Tensor] = []
+ try:
+ with torch.inference_mode(), runner.lock if runner is not None else nullcontext():
+ ids = torch.from_numpy(input_ids).to(device)
+ mask = torch.from_numpy(attention_mask).to(device)
+ marker_row = torch.from_numpy(marker_rows).to(device)
+ marker_position = torch.from_numpy(marker_positions).to(device)
+ start = 0
+ for count, key in pieces:
+ stop = start + count
+ piece_ids, piece_mask = ids[start:stop, : lengths[start]], mask[start:stop, : lengths[start]]
+ hidden = runner.run(piece_ids, piece_mask, key) if runner is not None and key is not None else None
+ if hidden is None:
+ hidden = model.encoder(input_ids=piece_ids, attention_mask=piece_mask).last_hidden_state
+ first, last = offsets[start], offsets[stop]
+ markers = hidden[marker_row[first:last], marker_position[first:last]]
+ parts.append(model.classifier(markers).squeeze(-1))
+ start = stop
+ flat = torch.cat(parts).float().cpu().numpy()
+ except Exception as exc:
+ # Graph memory is held until the graphs go; drop them so the
+ # worker's out-of-memory recovery gets it back.
+ if runner is not None and is_oom_error(exc):
+ runner.clear()
+ raise
+ out: list[np.ndarray] = [flat[:0]] * len(rows)
+ for j, row in enumerate(order):
+ out[row] = flat[offsets[j] : offsets[j + 1]]
+ return out
+
+ def _eager_pieces(self, lengths: list[int]) -> list[tuple[int, Key | None]]:
+ """Rows sorted longest first, cut into padded chunks of at most ``inference_batch_tokens``."""
+ pieces: list[tuple[int, Key | None]] = []
+ start = 0
+ while start < len(lengths):
+ count = max(1, min(len(lengths) - start, self._inference_batch_tokens // lengths[start]))
+ pieces.append((count, None))
+ start += count
+ return pieces
+
# ------------------------------------------------------------------ cost
def extract_item_costs(
diff --git a/packages/sie_server/src/sie_server/adapters/gliner2/decide_graphs.py b/packages/sie_server/src/sie_server/adapters/gliner2/decide_graphs.py
new file mode 100644
index 000000000..c57aff5de
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliner2/decide_graphs.py
@@ -0,0 +1,650 @@
+"""CUDA graphs for the GLiNER2.5-Decide encoder.
+
+A Decide forward on its DeBERTa-v3-large encoder launches about a thousand
+small GPU kernels from Python. Launching them takes the host 10 to 50 ms a
+forward, whatever the batch size, and for a short message that is most of the
+request: the GPU waits on the CPU. A CUDA graph records the launches of one
+input shape once and replays them with a single call.
+
+Graphs are an operator setting, fixed when the model loads
+(``adapter_options.loadtime.cuda_graphs``: ``"off"`` or ``"bucketed"``).
+
+What a graph holds. A graph records the encoder, from token ids to the last
+hidden states, for one (batch size, padded length). The classification head
+runs eagerly on the replayed hidden states: it reads each row's own label
+markers, so one graph serves every label set and any number of labels.
+
+Shapes. A call's rows pad to the length bucket of its longest row (a multiple
+of 16 tokens up to 128, of 32 beyond) and to a batch size of 1, 2, 3, 4, 6, 8,
+12, 16, 24 or 32 rows. A graph holds at most 2,048 tokens (batch times padded
+length): 132 shapes at a 512-token window. Padded positions are masked, and a
+padded row is a row of padding the caller never reads. A call that fits no
+graph (more rows, or more tokens) runs eagerly, as it does without graphs.
+
+Where graphs pay. A replay costs what the GPU needs for the padded shape and
+nothing else. An eager forward costs at least what the host needs to launch its
+kernels, whatever its size. So a graph is kept only if its replay takes no
+longer than the host takes to launch one forward eagerly: such a graph cannot
+lose to the eager forward it replaces, however few of its rows and tokens a
+call fills. The runner times both when it records. It times the launch once
+(the least of three one-row forwards) and each new graph's replay (the least of
+two); a graph that takes longer is dropped and its shape runs eagerly from then
+on, as does every shape with at least its rows and its length, which the GPU
+cannot run faster. The rule follows the machine: on a faster GPU, or a slower
+CPU, more shapes keep their graph.
+
+Measured on Modal in October 2026 (float16, rows of 64 tokens): one row takes
+6.4 ms from a graph and 27.7 ms eagerly on an L4, 4.8 ms and 15.7 ms on an RTX
+PRO 6000; eight rows take 15.6 ms and 27.2 ms on the L4, 5.2 ms and 15.2 ms on
+the RTX PRO 6000. From about 1,000 tokens on that L4 and 3,000 on that RTX PRO
+6000 the GPU bounds the forward and a graph saves nothing. A graph also keeps
+the memory its recording used, which grows with its rows, so no graph holds
+more than 2,048 tokens or 32 rows.
+
+Scores. Replaying a graph launches the kernels an eager forward of the padded
+shape launches, so a graph changes a score only as padding does: a row padded
+to a longer length, or batched with other rows, rounds float16 sums differently.
+That is the difference requests batched together already see without graphs.
+On the 400 messages of the classify study no probability moved by more than
+0.0014 between a graph and an eager forward of the same request (0.0019 between
+an eager batch of eight and its requests one at a time), and no top label
+changed.
+
+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
+can hit an out-of-memory error it would otherwise have avoided. Recording
+follows the rules every runner in the process shares (``_cuda_graphs.py``):
+
+- at most one recording at a time in the process, across all models; a forward
+ that finds another recording in progress runs eagerly;
+- no recording while less than a tenth of the device's memory is free;
+- a runner has a budget of 16 recordings that refills at one every 2 seconds;
+- a runner's graphs hold at most 4% of the device's memory: the pool the
+ graphs share, the driver's copy of each graph (about 7 MB), their inputs,
+ their relative-position tables and the hidden states they write. Past that,
+ recording stops and the graphs already recorded keep replaying.
+
+The forward that records a graph is answered by its first replay.
+
+Recording needs a forward that never waits on the host. One part of the
+DeBERTa forward does: building the relative-position table copies a CPU scalar
+to the GPU. While recording, the runner hands the encoder a table built for the
+length beforehand, shared by the graphs of that length; it holds the same
+integers.
+
+Replays never overlap: the caller holds ``lock`` from ``run`` until it has
+queued the head that reads the hidden states, because every graph writes its
+hidden states into one shared buffer. Only the recording thread's forward
+is diverted while a graph records. A shape that fails to record, for any reason
+but memory, runs eagerly from then on, and after three such shapes the runner
+turns graphs off for the process. A recording or first replay that runs out of
+memory drops every graph and pauses recording for a minute. 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.abc import Callable, Iterator
+from dataclasses import dataclass
+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__)
+
+GraphMode = Literal["off", "bucketed"]
+GRAPH_MODES: tuple[GraphMode, ...] = ("off", "bucketed")
+# Tokens (batch x padded length) a graph may hold. Past about that many the GPU,
+# not kernel launches, bounds a forward (see the module docstring).
+MAX_GRAPH_TOKENS = 2048
+# Batch sizes graphs are recorded for. A call pads up to the next of them, so
+# under a third of a padded batch is padding (17 rows in a batch of 24).
+_BATCH_SIZES = (1, 2, 3, 4, 6, 8, 12, 16, 24, 32)
+# Length buckets: this wide up to ``_NARROW_UNTIL`` tokens, ``_WIDE_BUCKET`` beyond.
+_NARROW_BUCKET = 16
+_NARROW_UNTIL = 128
+_WIDE_BUCKET = 32
+# A runner's recording budget: this many recordings, refilled at 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.
+_MAX_RECORDING_FAILURES = 3
+# A runner serving forwards logs its counters this often.
+_SUMMARY_SECONDS = 600.0
+_ENCODERS = frozenset({"deberta-v2"})
+
+# (batch size, padded length)
+Key = tuple[int, int]
+# Why a forward the runner was offered ran eagerly.
+EagerReason = Literal[
+ "disabled", # graphs turned off for the process after recording failures
+ "failed_shape", # the shape failed to record before
+ "not_faster", # the shape's replay takes longer than the host takes to launch a forward
+ "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
+]
+
+
+def bucket_length(length: int, window: int) -> int:
+ """The padded length of a row of ``length`` tokens."""
+ width = _NARROW_BUCKET if length <= _NARROW_UNTIL else _WIDE_BUCKET
+ return min(window, -(-length // width) * width)
+
+
+def batch_sizes(length: int, max_tokens: int = MAX_GRAPH_TOKENS) -> tuple[int, ...]:
+ """The batch sizes graphs of this padded length are recorded for."""
+ return tuple(size for size in _BATCH_SIZES if size * length <= max_tokens)
+
+
+def shapes(window: int, max_tokens: int = MAX_GRAPH_TOKENS) -> frozenset[Key]:
+ """Every shape a runner can record at this window."""
+ lengths = {bucket_length(length, window) for length in range(1, window + 1)}
+ return frozenset((batch, length) for length in lengths for batch in batch_sizes(length, max_tokens))
+
+
+def graph_shape(rows: int, longest: int, window: int, max_tokens: int = MAX_GRAPH_TOKENS) -> Key | None:
+ """The graph a call of ``rows`` rows replays, the longest of ``longest`` tokens; None when it runs eagerly."""
+ if rows < 1 or not 0 < longest <= window:
+ return None
+ length = bucket_length(longest, window)
+ batch = next((size for size in batch_sizes(length, max_tokens) if size >= rows), None)
+ return None if batch is None else (batch, length)
+
+
+def unsupported_reason(
+ encoder: Any, device: str | torch.device, window: int, max_tokens: int = MAX_GRAPH_TOKENS
+) -> str | None:
+ """Why ``encoder`` cannot use CUDA graphs of at most ``max_tokens`` on ``device``; None when it can."""
+ if not str(device).startswith("cuda"):
+ return "CUDA graphs need a CUDA device"
+ encoder_type = getattr(getattr(encoder, "config", None), "model_type", None)
+ if encoder_type not in _ENCODERS:
+ return f"the {encoder_type} encoder is not supported"
+ if not hasattr(getattr(encoder, "encoder", None), "get_rel_pos"):
+ return "the encoder has no relative-position hook"
+ if not batch_sizes(bucket_length(window, window), max_tokens):
+ return f"a {window}-token row does not fit a graph"
+ return None
+
+
+class _RecordingOutOfMemoryError(Exception):
+ """Recording a graph ran out of device memory."""
+
+
+@dataclass
+class _Graph:
+ graph: Any
+ input_ids: torch.Tensor
+ attention_mask: torch.Tensor
+ # Device memory the recording took: pool growth and the recorded graph.
+ device_bytes: int = 0
+
+
+class DecideGraphRunner:
+ """Records and replays the encoder of one GLiNER2.5-Decide model, per input shape."""
+
+ def __init__(
+ self,
+ encoder: Any,
+ *,
+ window: int,
+ pad_token_id: int = 0,
+ name: str = "",
+ max_tokens: int = MAX_GRAPH_TOKENS,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._encoder = encoder
+ self._name = name
+ self._window = window
+ self._pad_token_id = pad_token_id
+ self._max_tokens = max_tokens
+ self._hidden_size = int(encoder.config.hidden_size)
+ self._shapes = shapes(window, max_tokens)
+ self._graphs: dict[Key, _Graph] = {}
+ self._failed: set[Key] = set()
+ # Milliseconds this host takes to launch one eager forward, timed at the first recording.
+ self._launch_ms: float | None = None
+ # Shapes whose replay takes longer than that: they run eagerly.
+ self._slow: set[Key] = set()
+ # Held by the caller from ``run`` until it has queued the head (see the module docstring).
+ 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
+ self._clock = clock
+ self._device_bytes = 0
+ self._recording_credit = float(_RECORDING_BURST)
+ self._credited_at = clock()
+ # Relative-position tables of the recorded lengths; a graph reads its length's table on every replay.
+ self._relative_pos: dict[int, torch.Tensor] = {}
+ # The hidden states every graph writes, sized for the largest graph.
+ self._hidden: torch.Tensor | None = None
+ # Set only on the thread that is recording, while it records.
+ self._local = threading.local()
+ self.stats = CudaGraphStats()
+ self._summary_at = clock()
+ self._summary_forwards = 0
+ self._summary_replayed = 0
+ self._install_hook()
+
+ # -- hook --------------------------------------------------------------
+
+ def _install_hook(self) -> None:
+ layers = self._encoder.encoder
+ get_rel_pos = layers.get_rel_pos
+ self._build_relative_pos = get_rel_pos
+
+ def recording_get_rel_pos(
+ hidden_states: torch.Tensor, query_states: Any = None, relative_pos: Any = None
+ ) -> Any:
+ if relative_pos is None and getattr(self._local, "recording", False):
+ return self._local.relative_pos
+ return get_rel_pos(hidden_states, query_states, relative_pos)
+
+ layers.get_rel_pos = recording_get_rel_pos
+
+ @contextlib.contextmanager
+ def _recording_on_this_thread(self, relative_pos: torch.Tensor | None) -> Iterator[None]:
+ """Hand this thread's forward the precomputed table while the block runs."""
+ self._local.recording, self._local.relative_pos = True, relative_pos
+ try:
+ yield
+ finally:
+ self._local.recording, self._local.relative_pos = False, None
+
+ # -- policy ------------------------------------------------------------
+
+ def key(self, rows: int, longest: int) -> Key | None:
+ """The graph a call of ``rows`` rows replays; None when it runs eagerly (see ``graph_shape``)."""
+ return graph_shape(rows, longest, self._window, self._max_tokens)
+
+ def _why_not_record(self, key: Key, device: torch.device) -> EagerReason | None:
+ if key in self._failed:
+ return "failed_shape"
+ if any(batch <= key[0] and length <= key[1] for batch, length in self._slow):
+ return "not_faster" # no faster than a shape already found slower than a launch
+ if self._full:
+ return "budget_full"
+ if self._recording_credit < 1:
+ return "recording_paused"
+ if not self._has_headroom(device):
+ return "no_headroom"
+ return None
+
+ # -- entry point -------------------------------------------------------
+
+ def run(self, input_ids: torch.Tensor, attention_mask: torch.Tensor, key: Key) -> torch.Tensor | None:
+ """Hidden states of the rows of ``input_ids`` from the graph ``key``, or None to run them eagerly.
+
+ ``input_ids`` holds at most ``key``'s rows and length. The result is a
+ view of the buffer every graph writes: read it before the next ``run``.
+ """
+ with self.lock:
+ hidden, reason = self._run(input_ids, attention_mask, key)
+ if reason is not None:
+ self.stats.eager[reason] = self.stats.eager.get(reason, 0) + 1
+ self._log_summary()
+ return hidden
+
+ def _run(
+ self, input_ids: torch.Tensor, attention_mask: torch.Tensor, key: Key
+ ) -> tuple[torch.Tensor | None, EagerReason | None]:
+ if self._disabled:
+ return None, "disabled"
+ 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 self._replay(key, entry, input_ids, attention_mask), None
+ reason = self._why_not_record(key, input_ids.device)
+ 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
+ device = input_ids.device
+ free_before = self._free_memory(device)
+ try:
+ entry = self._record(key, device)
+ pays = self._pays(key, entry)
+ except Exception as exc: # noqa: BLE001 -- any failure to record runs the forward eagerly
+ self._recording_failed(key, exc)
+ return None, "recording_failed"
+ if not pays:
+ # The graph goes; what its recording added to the pool the graphs share stays.
+ del entry
+ self._device_bytes += max(0, free_before - self._free_memory(device))
+ return None, "not_faster"
+ # The graph answers the forward that recorded it. Its first replay
+ # is part of recording it: the graph is not kept if it fails.
+ # Running out of memory reaches the forward's out-of-memory
+ # recovery; any other failure runs the forward eagerly.
+ try:
+ hidden = self._replay(key, entry, input_ids, attention_mask)
+ except Exception as exc:
+ self._recording_failed(key, exc)
+ if is_oom_error(exc):
+ raise
+ return None, "recording_failed"
+ self._keep(key, entry, input_ids.device)
+ self.stats.recorded += 1
+ finally:
+ RECORDING_LOCK.release()
+ return hidden, None
+
+ def _pays(self, key: Key, entry: _Graph) -> bool:
+ """Whether a new graph's replay takes no longer than the host takes to launch a forward eagerly.
+
+ An eager forward takes at least its launches, so such a graph cannot
+ lose to the eager forward it replaces. A graph that takes longer is not
+ kept, and its shape runs eagerly from then on.
+ """
+ if self._launch_ms is None:
+ self._launch_ms = self._time_launch(key, entry)
+ logger.info(
+ "GLiNER2.5-Decide CUDA graphs for %s: this host launches a forward in %.1f ms; a shape keeps its "
+ "graph while the replay takes no longer",
+ self._name,
+ self._launch_ms,
+ )
+ replay_ms = self._time_replay(entry)
+ if replay_ms <= self._launch_ms:
+ return True
+ self._slow.add(key)
+ logger.debug(
+ "GLiNER2.5-Decide CUDA graph for %s, batch %d, length %d, replays in %.1f ms, longer than a launch "
+ "(%.1f ms); that shape runs eagerly",
+ self._name,
+ key[0],
+ key[1],
+ replay_ms,
+ self._launch_ms,
+ )
+ return False
+
+ def _keep(self, key: Key, entry: _Graph, device: torch.device) -> None:
+ """Cache a new graph and stop recording once the graphs take their memory budget."""
+ self._graphs[key] = entry
+ self._device_bytes += entry.device_bytes
+ held = self.held_bytes
+ if held <= self._memory_budget(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(
+ "GLiNER2.5-Decide 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(
+ "GLiNER2.5-Decide 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(
+ "GLiNER2.5-Decide CUDA graph recording for %s failed for batch %d, length %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(
+ "GLiNER2.5-Decide 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._relative_pos.clear()
+ self._hidden = None
+ self._device_bytes = 0
+ self._full = False
+
+ @property
+ def graph_count(self) -> int:
+ return len(self._graphs)
+
+ @property
+ def shape_count(self) -> int:
+ """How many shapes the runner can record."""
+ return len(self._shapes)
+
+ @property
+ def disabled(self) -> bool:
+ return self._disabled
+
+ @property
+ def launch_ms(self) -> float | None:
+ """Milliseconds this host takes to launch one eager forward; None before the first recording."""
+ return self._launch_ms
+
+ @property
+ def held_bytes(self) -> int:
+ """Device memory the runner counts against its budget."""
+ tables = sum(table.nbytes for table in self._relative_pos.values())
+ buffers = sum(entry.input_ids.nbytes + entry.attention_mask.nbytes for entry in self._graphs.values())
+ hidden = self._hidden.nbytes if self._hidden is not None else 0
+ return self._device_bytes + tables + buffers + hidden
+
+ 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(
+ "GLiNER2.5-Decide 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 graphs, %d MB, "
+ "%d shapes not faster than a launch%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),
+ self.held_bytes // 2**20,
+ len(self._slow),
+ ", off for this process" if self._disabled else "",
+ )
+
+ # -- recording and replay ---------------------------------------------
+
+ @staticmethod
+ def _has_headroom(device: torch.device) -> bool:
+ """Whether enough device memory is free to record without starving other models."""
+ return has_headroom(device)
+
+ @staticmethod
+ def _memory_budget(device: torch.device) -> int:
+ """Device memory this runner's graphs may hold."""
+ return memory_budget(device)
+
+ @staticmethod
+ def _free_memory(device: torch.device) -> int:
+ return free_memory(device)
+
+ def _hidden_states(self, key: Key, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
+ """The shared hidden-state buffer, viewed as this shape's (batch, length, hidden) tensor."""
+ batch, length = key
+ if self._hidden is None:
+ # Recorded graphs write here, so it lives as long as they do: only clear() drops it.
+ largest = max(batch * length for batch, length in self._shapes)
+ self._hidden = torch.empty(largest * self._hidden_size, dtype=dtype, device=device)
+ return self._hidden[: batch * length * self._hidden_size].view(batch, length, self._hidden_size)
+
+ def _record(self, key: Key, device: torch.device) -> _Graph:
+ """Record the graph for ``key``.
+
+ Recording runs on a stream of the runner's own. A thread's first use
+ of that stream creates state (the thread's cuBLAS handle and its
+ workspace for the stream) that cannot be created while recording, so
+ each thread's first recording warms the stream up with one row. The
+ engine loads and warms a model up on one thread and serves it on
+ another, so one warm-up for the runner would not do. 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, device)
+ except Exception as exc:
+ if is_oom_error(exc):
+ raise _RecordingOutOfMemoryError(str(exc)) from exc
+ raise
+
+ def _capture(self, key: Key, device: torch.device) -> _Graph:
+ batch, length = key
+ current = torch.cuda.current_stream(device)
+ with torch.inference_mode():
+ input_ids = torch.full((batch, length), self._pad_token_id, dtype=torch.long, device=device)
+ attention_mask = torch.ones((batch, length), dtype=torch.long, device=device)
+ relative_pos = self._relative_pos.get(length)
+ if relative_pos is None:
+ # Built eagerly, outside the recording: its CPU-to-GPU copy cannot be recorded.
+ relative_pos = self._build_relative_pos(torch.empty((1, length, 1), device=device))
+ if relative_pos is not None:
+ self._relative_pos[length] = relative_pos
+ dtype = self._encoder.get_input_embeddings().weight.dtype
+ hidden = self._hidden_states(key, dtype, device)
+ if self._stream is None:
+ self._stream = torch.cuda.Stream(device=device)
+ stream = self._stream
+ warm_up = not getattr(self._local, "warmed", False)
+ pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else None
+ graph = torch.cuda.CUDAGraph()
+ stream.wait_stream(current)
+ try:
+ with self._recording_on_this_thread(relative_pos), torch.inference_mode(), torch.cuda.stream(stream):
+ if warm_up:
+ self._encoder(input_ids=input_ids[:1], attention_mask=attention_mask[:1])
+ # Set only once warmed up, so a failed warm-up is tried again.
+ self._local.warmed = True
+ free_before = self._free_memory(device)
+ graph.capture_begin(pool=pool, capture_error_mode="thread_local")
+ try:
+ encoded = self._encoder(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
+ 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(device))
+ finally:
+ current.wait_stream(stream)
+ return _Graph(graph=graph, input_ids=input_ids, attention_mask=attention_mask, device_bytes=device_bytes)
+
+ def _time_launch(self, key: Key, entry: _Graph) -> float:
+ """Milliseconds the host takes to launch one eager forward: the least of three one-row forwards.
+
+ An eager forward returns once its kernels are launched, without
+ waiting for the GPU, and launches the same kernels whatever its size.
+ The forward gets the precomputed table, as a recording does, so it
+ does not wait on the host either.
+ """
+ device = entry.input_ids.device
+ input_ids, attention_mask = entry.input_ids[:1], entry.attention_mask[:1]
+ best = float("inf")
+ with self._recording_on_this_thread(self._relative_pos.get(key[1])), torch.inference_mode():
+ for _ in range(3):
+ torch.cuda.synchronize(device)
+ start = time.perf_counter()
+ self._encoder(input_ids=input_ids, attention_mask=attention_mask)
+ best = min(best, time.perf_counter() - start)
+ torch.cuda.synchronize(device)
+ return 1000.0 * best
+
+ @staticmethod
+ def _time_replay(entry: _Graph) -> float:
+ """Milliseconds the GPU takes to run a graph: the least of two replays of its recorded inputs."""
+ device = entry.input_ids.device
+ best = float("inf")
+ with torch.inference_mode():
+ for _ in range(2):
+ torch.cuda.synchronize(device)
+ start = time.perf_counter()
+ entry.graph.replay()
+ torch.cuda.synchronize(device)
+ best = min(best, time.perf_counter() - start)
+ return 1000.0 * best
+
+ def _replay(self, key: Key, entry: _Graph, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ """Replay ``entry`` on the rows of ``input_ids``; their hidden states."""
+ shared = self._hidden
+ if shared is None: # dropped only with every graph
+ raise RuntimeError("GLiNER2.5-Decide CUDA graph replayed without its hidden-state buffer")
+ rows, length = input_ids.shape
+ with torch.inference_mode():
+ entry.input_ids[:rows, :length].copy_(input_ids)
+ entry.attention_mask[:rows, :length].copy_(attention_mask)
+ if length < key[1]:
+ entry.input_ids[:rows, length:].fill_(self._pad_token_id)
+ entry.attention_mask[:rows, length:].zero_()
+ if rows < key[0]:
+ # A padded row reads one padding token, so its forward is an ordinary one.
+ entry.input_ids[rows:].fill_(self._pad_token_id)
+ entry.attention_mask[rows:].zero_()
+ entry.attention_mask[rows:, :1].fill_(1)
+ entry.graph.replay()
+ return self._hidden_states(key, shared.dtype, shared.device)[:rows]
diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py b/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
index 21437c0d2..7a9008178 100644
--- a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
+++ b/packages/sie_server/src/sie_server/core/worker/handlers/extract.py
@@ -87,21 +87,49 @@ class ExtractHandler(OperationHandler[ExtractOutput]):
Returns:
ExtractOutput with entities.
"""
+ return adapter.extract(items, **self._arguments(config_key, metadata_list), prepared_items=prepared_items)
+
+ @staticmethod
+ def _arguments(config_key: tuple[Any, ...], metadata_list: list[RequestMetadata]) -> dict[str, Any]:
+ """The ``extract`` arguments of one configuration."""
labels_tuple, _schema_key, instruction, _options_key = config_key
- labels = list(labels_tuple) if labels_tuple else None
# Read original options from metadata like encode and score do: the
# config key turns nested lists and objects into tuples, which would
# hand adapters a lossy copy of structured options.
- options = metadata_list[0].options or None
- output_schema = metadata_list[0].output_schema
-
- return adapter.extract(
- items,
- labels=labels,
- output_schema=output_schema,
- instruction=instruction,
- options=options,
- prepared_items=prepared_items,
+ return {
+ "labels": list(labels_tuple) if labels_tuple else None,
+ "output_schema": metadata_list[0].output_schema,
+ "instruction": instruction,
+ "options": metadata_list[0].options or None,
+ }
+
+ def prime(
+ self,
+ adapter: ModelAdapter,
+ groups: list[tuple[list[Item], tuple[Any, ...], list[RequestMetadata]]],
+ ) -> None:
+ """Hand an adapter every extract configuration of a batch before the per-configuration calls.
+
+ A batch can hold requests with different labels, schemas or options;
+ each configuration gets its own ``extract`` call. An adapter that can
+ work on all of them at once (one forward pass for every row, say)
+ declares ``prime_extract_groups``; it receives the ``items`` and the
+ ``extract`` arguments of each configuration, in the order the calls
+ will follow. Adapters without the method are left alone.
+
+ Args:
+ adapter: The model adapter.
+ groups: For each configuration: its items, its config key and its
+ requests' metadata.
+ """
+ hook = getattr(adapter, "prime_extract_groups", None)
+ if not callable(hook) or len(groups) < 2:
+ return
+ hook(
+ [
+ {"items": items, **self._arguments(config_key, metadata_list)}
+ for items, config_key, metadata_list in groups
+ ]
)
def slice_output(self, output: ExtractOutput, index: int) -> ExtractOutput:
diff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.py
index 66ff0bbbc..a14401103 100644
--- a/packages/sie_server/src/sie_server/core/worker/model_worker.py
+++ b/packages/sie_server/src/sie_server/core/worker/model_worker.py
@@ -1471,6 +1471,8 @@ class ModelWorker:
duration_s=metadata.timing.queue_ms / 1_000.0,
)
+ await self._prime_extract_groups(config_groups)
+
# Run ONE inference call per unique configuration using handlers.
# The BatchExecutor wraps dispatch with reactive OOM recovery —
# cache_clear → evict_lru → split_batch → terminal failure. On
@@ -1593,6 +1595,40 @@ class ModelWorker:
self._stats.batches_processed += 1
self._stats.total_tokens_processed += batch.total_tokens
+ async def _prime_extract_groups(
+ self,
+ config_groups: dict[
+ tuple[Any, ...],
+ tuple[list[Item], list[RequestMetadata], list[int], list[HasCost]],
+ ],
+ ) -> None:
+ """Let the adapter see every extract configuration of a batch before the per-configuration calls.
+
+ Only for a batch that holds more than one extract configuration, and
+ only when the worker runs one batch at a time, so what the adapter
+ keeps belongs to this batch. It is an optimisation: whatever goes wrong
+ here, each configuration's own call still runs and reports.
+ """
+ if self._dispatch_width != 1 or len(config_groups) < 2:
+ return
+ prime = getattr(self._handlers.get("extract"), "prime", None)
+ if not callable(prime) or not callable(getattr(self._adapter, "prime_extract_groups", None)):
+ return
+ groups = [
+ (items_list, config_key[1:], metadata_list)
+ for config_key, (items_list, metadata_list, _indices, _prepared) in config_groups.items()
+ if config_key[0] == "extract"
+ ]
+ if len(groups) < 2:
+ return
+ loop = asyncio.get_running_loop()
+ try:
+ await loop.run_in_executor(self._inference_executor, functools.partial(prime, self._adapter, groups))
+ except Exception: # noqa: BLE001 -- best effort; every configuration still gets its own call
+ logger.warning(
+ "Priming %d extract configurations failed; running them one by one", len(groups), exc_info=True
+ )
+
def _config_key_or_fail(self, metadata: RequestMetadata) -> tuple[Any, ...] | None:
"""Batching key for one request, or None after failing that request alone.
diff --git a/packages/sie_server/tests/adapters/test_gliner2_decide.py b/packages/sie_server/tests/adapters/test_gliner2_decide.py
index bcd73b30d..2e18a19ae 100644
--- a/packages/sie_server/tests/adapters/test_gliner2_decide.py
+++ b/packages/sie_server/tests/adapters/test_gliner2_decide.py
@@ -479,7 +479,7 @@ def test_long_documents_are_cut_to_whole_words_in_the_window(monkeypatch: pytest
assert processor.tokenizer.tokenized_chars < 20 * 96
-def test_caches_keep_neither_long_words_nor_task_prompts() -> None:
+def test_caches_keep_neither_long_words_nor_the_processors_strings() -> None:
adapter, processor = make_adapter(window=256)
long_words = [f"{i:04d}" + "x" * 60 for i in range(20)]
@@ -492,6 +492,277 @@ def test_caches_keep_neither_long_words_nor_task_prompts() -> None:
assert processor._tokenize_cached.cache_info().currsize == 0
+# ---------------------------------------------------------------------------
+# Task prompts of recent request shapes
+# ---------------------------------------------------------------------------
+
+
+def count_prompts(processor: FakeProcessor, monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
+ """Record the schemas the processor builds a task prompt for."""
+ built: list[dict[str, Any]] = []
+ original = processor.transform_and_format
+
+ def transform_and_format(text: str, schema: dict[str, Any]) -> SimpleNamespace:
+ built.append(schema)
+ return original(text, schema)
+
+ monkeypatch.setattr(processor, "transform_and_format", transform_and_format)
+ return built
+
+
+def test_a_request_shapes_task_prompt_is_built_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, processor = make_adapter()
+ built = count_prompts(processor, monkeypatch)
+
+ first = adapter.extract([Item(text="refund please")], output_schema=QUESTIONS)
+ second = adapter.extract([Item(text="refund please")], output_schema=QUESTIONS)
+ assert len(built) == 1
+ assert second.data == first.data
+ assert second.input_token_counts == first.input_token_counts # the free text is billed from the kept prompt
+
+ adapter.extract([Item(text="refund please")], labels=["yes", "no"])
+ adapter.extract([Item(text="another text")], labels=["yes", "no"])
+ adapter.extract([Item(text="refund please")], labels=["no", "yes"]) # label order is part of the prompt
+ adapter.extract([Item(text="refund please")], labels=["yes", "no"], instruction="Is it urgent?")
+ adapter.extract([Item(text="refund please")], labels=["yes", "no"], options={"classification_type": "multi-label"})
+ assert len(built) == 5
+
+
+def test_a_kept_prompt_gives_the_rows_a_fresh_one_gives(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, _ = make_adapter()
+ items = [Item(text="refund please"), Item(text="cancel it")]
+ adapter.extract(items, output_schema=QUESTIONS)
+ rows = spy_rows(adapter, monkeypatch)
+
+ kept = adapter.extract(items, output_schema=QUESTIONS)
+ kept_rows = list(rows)
+ assert adapter._prompts is not None
+ adapter._prompts.clear()
+ rows.clear()
+ fresh = adapter.extract(items, output_schema=QUESTIONS)
+
+ assert kept_rows == rows
+ assert kept.data == fresh.data
+ assert kept.input_token_counts == fresh.input_token_counts
+
+
+def test_a_large_schema_builds_its_prompt_every_time(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, processor = make_adapter(window=4096, max_prompt_tokens=2048)
+ built = count_prompts(processor, monkeypatch)
+ criteria = {"billing": "money " * 300, "bug": "broken " * 250, "other": "else " * 300}
+ wordy = {"topic": {"type": "choice", "instructions": "What is it about?", "criteria": criteria}}
+ assert len(json.dumps(wordy)) > decide_module._CACHED_PROMPT_CHARS
+
+ for _ in range(2):
+ adapter.extract([Item(text="refund please")], output_schema=wordy)
+
+ assert len(built) == 2
+ assert not adapter._prompts
+
+
+def test_the_prompt_cache_keeps_the_most_recent_shapes(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(decide_module, "_PROMPT_CACHE_SIZE", 2)
+ adapter, processor = make_adapter()
+ built = count_prompts(processor, monkeypatch)
+
+ for labels in (["a", "b"], ["c", "d"], ["a", "b"], ["e", "f"], ["a", "b"], ["c", "d"]):
+ adapter.extract([Item(text="refund please")], labels=labels)
+
+ # ["c", "d"] was the least recently used when ["e", "f"] came, so only it is built again.
+ assert [schema["classifications"][0]["labels"] for schema in built] == [
+ ["a", "b"],
+ ["c", "d"],
+ ["e", "f"],
+ ["c", "d"],
+ ]
+ assert adapter._prompts is not None
+ assert len(adapter._prompts) == 2
+
+
+def test_a_prompt_over_budget_is_refused_every_time_and_not_kept() -> None:
+ adapter, _ = make_adapter(window=64, max_prompt_tokens=32)
+ labels = [f"label number {i}" for i in range(10)]
+
+ for _ in range(2):
+ with pytest.raises(InputTooLongError, match="takes at most 32"):
+ adapter.extract([Item(text="x")], labels=labels)
+
+ assert not adapter._prompts
+
+
+# ---------------------------------------------------------------------------
+# One pass for a batch of several request shapes
+# ---------------------------------------------------------------------------
+
+GROUPS: list[dict[str, Any]] = [
+ {"items": [Item(text="refund please"), Item(text="cancel my plan today")], "labels": ["refund", "cancel", "other"]},
+ {"items": [Item(text="the payroll file is late")], "output_schema": QUESTIONS},
+ {
+ "items": [Item(text="it crashes on start"), Item(text=" "), Item(text="thanks")],
+ "instruction": "Triage the ticket.",
+ "options": {"label_groups": {"topic": ["billing", "bug"], "urgency": ["low", "high"]}},
+ },
+]
+
+
+def call(adapter: GLiNER2DecideAdapter, group: dict[str, Any]) -> Any:
+ return adapter.extract(
+ group["items"],
+ labels=group.get("labels"),
+ output_schema=group.get("output_schema"),
+ instruction=group.get("instruction"),
+ options=group.get("options"),
+ )
+
+
+def count_forwards(adapter: GLiNER2DecideAdapter) -> list[int]:
+ """Record the rows of every encoder forward."""
+ forwards: list[int] = []
+ encoder = adapter._model.encoder
+
+ def forward(input_ids: torch.Tensor, attention_mask: torch.Tensor) -> SimpleNamespace:
+ forwards.append(input_ids.shape[0])
+ return encoder(input_ids=input_ids, attention_mask=attention_mask)
+
+ adapter._model.encoder = forward
+ return forwards
+
+
+def assert_same_answers(actual: Any, expected: Any) -> None:
+ assert actual.input_token_counts == expected.input_token_counts
+ assert [None if e is None else e.code for e in actual.errors or []] == [
+ None if e is None else e.code for e in expected.errors or []
+ ]
+ assert (actual.data is None) == (expected.data is None)
+ assert (actual.classifications is None) == (expected.classifications is None)
+ assert json.dumps(actual.data, sort_keys=True) == json.dumps(expected.data, sort_keys=True)
+ assert actual.classifications == expected.classifications
+
+
+def test_a_primed_batch_runs_one_forward_and_answers_as_its_calls_do_alone() -> None:
+ alone, _ = make_adapter()
+ expected = [call(alone, group) for group in GROUPS]
+ adapter, _ = make_adapter()
+ forwards = count_forwards(adapter)
+
+ adapter.prime_extract_groups(GROUPS)
+ assert forwards == [5] # every readable row of the three request shapes, once
+
+ for group, answers in zip(GROUPS, expected, strict=True):
+ assert_same_answers(call(adapter, group), answers)
+ assert forwards == [5] # the calls ran no forward of their own
+ assert not adapter._primed # and took what was scored for them
+
+
+def test_primed_rows_read_their_own_shapes_label_markers(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, _ = make_adapter()
+ scored: list[tuple[list[int], list[int]]] = []
+ original = adapter._score_rows
+
+ def score_rows(rows: list[list[int]], positions: list[list[int]]) -> list[np.ndarray]:
+ scored.extend(zip(rows, positions, strict=True))
+ return original(rows, positions)
+
+ monkeypatch.setattr(adapter, "_score_rows", score_rows)
+
+ adapter.prime_extract_groups(GROUPS)
+
+ assert len({tuple(positions) for _, positions in scored}) == 3 # one set of markers per request shape
+ for row, positions in scored:
+ assert all(row[position] == adapter._tokenizer.convert_tokens_to_ids(["[L]"])[0] for position in positions)
+ np.testing.assert_allclose(
+ adapter._primed[tuple(row), tuple(positions)], expected_logits(row, positions), rtol=1e-5, atol=1e-9
+ )
+
+
+def test_a_single_request_shape_is_not_primed() -> None:
+ adapter, _ = make_adapter()
+ forwards = count_forwards(adapter)
+
+ adapter.prime_extract_groups(GROUPS[:1])
+ assert forwards == []
+
+ call(adapter, GROUPS[0])
+ assert forwards == [2]
+
+
+def test_a_group_that_cannot_be_read_is_left_to_its_own_call() -> None:
+ adapter, _ = make_adapter(window=64, max_prompt_tokens=32)
+ forwards = count_forwards(adapter)
+ malformed = {"items": [Item(text="a")], "labels": ["x"], "output_schema": {"q": {"type": "noul"}}}
+ too_long = {"items": [Item(text="b")], "labels": [f"label number {i}" for i in range(10)]}
+ readable = [{"items": [Item(text="c")], "labels": ["x", "y"]}, {"items": [Item(text="d")], "labels": ["y", "x"]}]
+
+ adapter.prime_extract_groups([malformed, readable[0], too_long, readable[1]])
+
+ assert forwards == [2]
+ with pytest.raises(InvalidInputError):
+ call(adapter, malformed)
+ with pytest.raises(InputTooLongError):
+ call(adapter, too_long)
+ for group in readable:
+ assert call(adapter, group).classifications
+ assert forwards == [2]
+
+
+def test_primed_logits_are_taken_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ adapter, _ = make_adapter()
+ forwards = count_forwards(adapter)
+ adapter.prime_extract_groups(GROUPS)
+
+ first = call(adapter, GROUPS[0])
+ again = call(adapter, GROUPS[0]) # the same request later scores itself
+
+ assert forwards == [5, 2]
+ assert_same_answers(again, first)
+
+
+def test_the_next_batch_drops_what_the_last_one_left() -> None:
+ adapter, _ = make_adapter()
+ forwards = count_forwards(adapter)
+ adapter.prime_extract_groups(GROUPS)
+ assert adapter._primed
+
+ adapter.prime_extract_groups(GROUPS[:1]) # a batch of one shape primes nothing and keeps nothing
+
+ assert not adapter._primed
+ call(adapter, GROUPS[1])
+ assert forwards == [5, 1]
+
+
+def test_a_call_with_a_row_that_was_not_primed_scores_all_its_rows() -> None:
+ adapter, _ = make_adapter()
+ alone, _ = make_adapter()
+ forwards = count_forwards(adapter)
+ adapter.prime_extract_groups(GROUPS)
+ grown = {**GROUPS[0], "items": [*GROUPS[0]["items"], Item(text="one more message")]}
+
+ answers = call(adapter, grown)
+
+ assert forwards == [5, 3]
+ assert_same_answers(answers, call(alone, grown))
+
+
+def test_rows_that_repeat_in_a_batch_are_each_answered() -> None:
+ adapter, _ = make_adapter()
+ alone, _ = make_adapter()
+ forwards = count_forwards(adapter)
+ repeated = {"items": [Item(text="same text"), Item(text="same text")], "labels": ["yes", "no"]}
+ adapter.prime_extract_groups([repeated, GROUPS[1]])
+
+ answers = call(adapter, repeated)
+
+ assert forwards == [3]
+ assert_same_answers(answers, call(alone, repeated))
+
+
+def test_priming_needs_a_loaded_model() -> None:
+ adapter = GLiNER2DecideAdapter("fake/decide")
+
+ with pytest.raises(RuntimeError, match="not loaded"):
+ adapter.prime_extract_groups(GROUPS)
+
+
def test_overflow_policy_error_and_unreadable_items_fail_alone() -> None:
adapter, _ = make_adapter(window=64)
items = [
diff --git a/packages/sie_server/tests/adapters/test_gliner2_decide_graphs.py b/packages/sie_server/tests/adapters/test_gliner2_decide_graphs.py
new file mode 100644
index 000000000..08af1e9d0
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliner2_decide_graphs.py
@@ -0,0 +1,759 @@
+"""GLiNER2.5-Decide CUDA graph policy: which calls replay a graph, which record one, which run eagerly.
+
+These run without a GPU: recording and replay are replaced by fakes. Scores
+from real graphs were checked against eager scores on an L4 and an RTX PRO 6000
+(see ``decide_graphs.py``).
+"""
+
+from __future__ import annotations
+
+import logging
+import random
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import numpy as np
+import pytest
+import torch
+import yaml
+from sie_server.adapters._cuda_graphs import RECORDING_LOCK
+from sie_server.adapters.gliner2 import decide_graphs as graphs_module
+from sie_server.adapters.gliner2.decide import GLiNER2DecideAdapter
+from sie_server.adapters.gliner2.decide_graphs import (
+ DecideGraphRunner,
+ batch_sizes,
+ bucket_length,
+ graph_shape,
+ shapes,
+ unsupported_reason,
+)
+from sie_server.core.loader import _build_adapter_kwargs, load_model_configs, reject_unknown_loadtime_options
+
+from .test_gliner2_decide import FakeEncoder, expected_logits, make_adapter
+
+_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+# The shipped profile that loads with graphs: on the 400 messages of the
+# classify study its graphs moved no probability by more than 0.0014 against
+# eager execution and changed no top label, on an L4 and on an RTX PRO 6000.
+_BUCKETED_BY_DEFAULT = {"fastino/GLiNER2.5-Decide"}
+_DEVICE = torch.device("cpu")
+
+
+class _Layers:
+ def __init__(self) -> None:
+ self.built: list[int] = []
+
+ def get_rel_pos(self, hidden_states: torch.Tensor, query_states: Any = None, relative_pos: Any = None) -> Any:
+ self.built.append(hidden_states.shape[-2])
+ return ("built", hidden_states.shape[-2])
+
+
+def _encoder(encoder_type: str = "deberta-v2", hidden_size: int = 1024, hook: bool = True) -> Any:
+ layers = _Layers() if hook else SimpleNamespace()
+ return SimpleNamespace(config=SimpleNamespace(model_type=encoder_type, hidden_size=hidden_size), encoder=layers)
+
+
+class _Runner(DecideGraphRunner):
+ """Records and replays graphs with fakes; the runner's own code decides what happens when.
+
+ A replay returns zeros for the call's rows at the graph's length, or raises
+ ``replay_error``. A recording whose capture fails (``capture_error``)
+ raises that error. Time stands still unless a test moves ``now``; the
+ device always has memory to spare unless a test clears ``headroom`` or sets
+ a ``budget``. The host launches a forward in ``host_launch_ms`` and the GPU
+ runs a graph in ``replay_ms_per_token`` for each of its padded tokens.
+ """
+
+ # Whether ``capture_error`` fails every recording, not just the next one.
+ keep_failing = False
+ # Device memory a recording adds to the pool the graphs share.
+ pool_growth = 0
+
+ def __init__(self, encoder: Any = None, **kwargs: Any) -> None:
+ self.now = 0.0
+ kwargs.setdefault("window", 512)
+ super().__init__(encoder or _encoder(), clock=lambda: self.now, **kwargs)
+ self.recorded: list[tuple[int, int]] = []
+ self.replayed: list[tuple[int, int]] = []
+ self.capture_error: Exception | None = None
+ self.replay_error: Exception | None = None
+ self.headroom = True
+ self.budget = 2**40
+ self.bytes_per_graph = 0
+ self.host_launch_ms = 30.0
+ self.replay_ms_per_token = 0.0
+ self.launches_timed = 0
+ self.free = 2**40
+
+ def _free_memory(self, device: torch.device) -> int:
+ return self.free
+
+ def _time_launch(self, key: Any, entry: Any) -> float:
+ self.launches_timed += 1
+ return self.host_launch_ms
+
+ def _time_replay(self, entry: Any) -> float:
+ return self.replay_ms_per_token * entry.input_ids.shape[0] * entry.length
+
+ def _has_headroom(self, device: torch.device) -> bool:
+ return self.headroom
+
+ def _memory_budget(self, device: torch.device) -> int:
+ return self.budget
+
+ def _record(self, key: Any, device: torch.device) -> Any:
+ 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)
+ self._relative_pos.setdefault(key[1], torch.zeros(1))
+ # Static inputs with a row per padded row and no memory to count.
+ empty = torch.zeros(key[0], 0, dtype=torch.long)
+ self.free -= self.pool_growth
+ return SimpleNamespace(
+ graph=None, input_ids=empty, attention_mask=empty, device_bytes=self.bytes_per_graph, length=key[1]
+ )
+
+ def _replay(self, key: Any, entry: Any, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ if self.replay_error is not None:
+ raise self.replay_error
+ self.replayed.append(key)
+ return torch.zeros(input_ids.shape[0], key[1], 2)
+
+ def offer(self, rows: int, length: int) -> torch.Tensor | None:
+ """Offer the runner a call of ``rows`` rows of ``length`` tokens, as the adapter does."""
+ key = self.key(rows, length)
+ if key is None:
+ return None
+ ids = torch.ones(rows, length, dtype=torch.long)
+ return self.run(ids, ids, key)
+
+
+class TestSupport:
+ def test_a_deberta_encoder_on_cuda_is_supported(self) -> None:
+ assert unsupported_reason(_encoder(), "cuda:0", 512) is None
+
+ @pytest.mark.parametrize(
+ ("encoder", "device", "window", "reason"),
+ [
+ (_encoder(), "cpu", 512, "need a CUDA device"),
+ (_encoder(), "mps", 512, "need a CUDA device"),
+ (_encoder(encoder_type="modernbert"), "cuda", 512, "modernbert encoder is not supported"),
+ (_encoder(hook=False), "cuda", 512, "no relative-position hook"),
+ (_encoder(), "cuda", 4096, "does not fit a graph"),
+ ],
+ )
+ def test_other_encoders_devices_and_windows_run_eagerly(
+ self, encoder: Any, device: str, window: int, reason: str
+ ) -> None:
+ message = unsupported_reason(encoder, device, window)
+
+ assert message is not None
+ assert reason in message
+
+
+class TestShapes:
+ @pytest.mark.parametrize(
+ ("length", "padded"),
+ [(1, 16), (16, 16), (17, 32), (47, 48), (62, 64), (65, 80), (128, 128), (129, 160), (500, 512), (512, 512)],
+ )
+ def test_lengths_round_up_to_their_bucket(self, length: int, padded: int) -> None:
+ assert bucket_length(length, 512) == padded
+
+ def test_a_bucket_never_passes_the_window(self) -> None:
+ assert bucket_length(300, 300) == 300
+ assert bucket_length(290, 300) == 300
+
+ @pytest.mark.parametrize(
+ ("length", "largest"), [(16, 32), (64, 32), (80, 24), (128, 16), (160, 12), (256, 8), (320, 6), (512, 4)]
+ )
+ def test_a_graph_holds_at_most_2048_tokens_and_32_rows(self, length: int, largest: int) -> None:
+ sizes = batch_sizes(length)
+
+ assert sizes[-1] == largest
+ assert all(size * length <= 2048 for size in sizes)
+
+ @pytest.mark.parametrize(
+ ("rows", "batch"),
+ [(1, 1), (2, 2), (3, 3), (4, 4), (5, 6), (7, 8), (8, 8), (9, 12), (13, 16), (17, 24), (25, 32), (32, 32)],
+ )
+ def test_a_batch_pads_up_to_the_next_batch_size(self, rows: int, batch: int) -> None:
+ assert graph_shape(rows, 60, 512) == (batch, 64)
+
+ def test_a_call_that_fits_no_graph_runs_eagerly(self) -> None:
+ assert graph_shape(33, 60, 512) is None # more rows than a graph holds
+ assert graph_shape(17, 100, 512) is None # 24 rows of 112 tokens pass the token bound
+ assert graph_shape(5, 500, 512) is None
+ assert graph_shape(4, 500, 512) == (4, 512)
+ assert graph_shape(1, 513, 512) is None # past the window
+ assert graph_shape(0, 60, 512) is None
+
+ def test_every_call_that_replays_maps_into_a_small_fixed_set(self) -> None:
+ fixed = shapes(512)
+
+ assert len(fixed) == 132
+ rng = random.Random(7) # noqa: S311 -- reproducible shapes, not security
+ for _ in range(5000):
+ rows, longest = rng.randint(1, 80), rng.randint(1, 512)
+ key = graph_shape(rows, longest, 512)
+ if key is None:
+ # Not even the batch that just holds the rows fits the token bound.
+ assert rows > batch_sizes(bucket_length(longest, 512))[-1]
+ else:
+ assert key in fixed
+ assert key[0] >= rows
+ assert key[1] >= longest
+ assert key[0] * key[1] <= 2048
+
+ def test_under_a_third_of_a_padded_batch_is_padding(self) -> None:
+ for rows in range(1, 33):
+ key = graph_shape(rows, 16, 512)
+ assert key is not None
+ assert 3 * (key[0] - rows) < key[0]
+
+
+class TestRecordingPolicy:
+ def test_a_shape_is_recorded_once_and_replayed_from_then_on(self) -> None:
+ runner = _Runner()
+
+ for _ in range(3):
+ assert runner.offer(1, 50) is not None
+
+ assert runner.recorded == [(1, 64)]
+ assert runner.replayed == [(1, 64)] * 3 # the recording forward is answered by the first replay
+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 2)
+
+ def test_lengths_and_batches_share_their_bucket(self) -> None:
+ runner = _Runner()
+
+ for rows, length in [(1, 49), (1, 64), (5, 60), (6, 51)]:
+ runner.offer(rows, length)
+
+ assert runner.recorded == [(1, 64), (6, 64)]
+
+ def test_the_hidden_states_are_those_of_the_calls_rows(self) -> None:
+ hidden = _Runner().offer(5, 50)
+
+ assert hidden is not None
+ assert hidden.shape == (5, 64, 2)
+
+ def test_a_call_that_fits_no_graph_is_not_offered(self) -> None:
+ runner = _Runner()
+
+ assert runner.offer(33, 50) is None
+ assert runner.stats.forwards == 0
+
+ def test_after_warm_up_every_call_replays_whatever_the_mix(self) -> None:
+ runner = _Runner()
+ rng = random.Random(3) # noqa: S311 -- reproducible shapes, not security
+ calls = [(rng.randint(1, 8), rng.randint(40, 80)) for _ in range(400)]
+ for rows, length in calls: # warm-up: the clock moves, so the recording budget refills
+ runner.now += 2.0
+ runner.offer(rows, length)
+ recorded = len(runner.recorded)
+
+ for rows, length in calls:
+ assert runner.offer(rows, length) is not None
+
+ assert len(runner.recorded) == recorded <= 6 * 3 # six batch sizes, three length buckets
+ assert runner.stats.eager == {}
+
+ def test_recording_is_rationed_in_time(self) -> None:
+ runner = _Runner()
+
+ results = [runner.offer(1, 16 * (step + 1)) for step in range(8)] + [
+ runner.offer(2, 16 * (step + 1)) for step in range(8)
+ ]
+ assert all(result is not None for result in results) # a burst of 16 recordings
+ assert runner.offer(3, 16) is None # the 17th waits
+ assert runner.stats.eager == {"recording_paused": 1}
+
+ runner.now += 2.0 # one more recording every 2 seconds
+ assert runner.offer(3, 16) is not None
+ assert runner.offer(4, 16) is None
+
+ def test_one_recording_at_a_time_in_the_process(self) -> None:
+ runner = _Runner()
+
+ with RECORDING_LOCK: # another model's runner is recording
+ assert runner.offer(1, 50) is None
+ assert runner.stats.eager == {"busy": 1}
+
+ assert runner.offer(1, 50) is not None
+
+ def test_a_runner_over_its_budget_stops_recording_and_keeps_its_graphs(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ runner = _Runner()
+ runner.bytes_per_graph, runner.budget = 100, 250
+
+ with caplog.at_level(logging.WARNING):
+ for rows in (1, 2, 3, 4):
+ runner.offer(rows, 50)
+
+ assert runner.recorded == [(1, 64), (2, 64), (3, 64)]
+ assert runner.graph_count == 3
+ assert runner.offer(1, 50) is not None # the recorded shapes keep replaying
+ assert runner.stats.eager == {"budget_full": 1}
+ assert "their memory budget, with 3 of 132 shapes recorded" in caplog.text
+
+ def test_the_budget_counts_the_tensors_graphs_keep(self) -> None:
+ runner = _Runner()
+ runner.offer(1, 50)
+ assert runner.held_bytes == torch.zeros(1).nbytes # the fake relative-position table
+
+ runner._hidden = torch.zeros(1000, dtype=torch.float16)
+ assert runner.held_bytes == torch.zeros(1).nbytes + 2000
+
+ def test_no_recording_while_device_memory_is_short(self) -> None:
+ runner = _Runner()
+ runner.headroom = False
+
+ assert runner.offer(1, 50) is None
+ assert runner.stats.eager == {"no_headroom": 1}
+
+ runner.headroom = True
+ assert runner.offer(1, 50) is not None
+
+ def test_a_shape_that_fails_to_record_runs_eagerly_and_the_others_keep_replaying(
+ self, caplog: pytest.LogCaptureFixture
+ ) -> None:
+ runner = _Runner()
+ runner.offer(1, 50)
+ runner.capture_error = RuntimeError("cannot capture")
+
+ with caplog.at_level(logging.WARNING):
+ assert runner.offer(2, 50) is None
+ assert runner.offer(2, 50) is None # not tried again
+ assert runner.offer(1, 50) is not None
+
+ assert runner.stats.eager == {"recording_failed": 1, "failed_shape": 1}
+ assert runner.stats.recording_failures == 1
+ assert "failed for batch 2, length 64" in caplog.text
+ assert not runner.disabled
+ assert not RECORDING_LOCK.locked()
+
+ def test_three_shapes_that_fail_to_record_turn_graphs_off(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner()
+ runner.offer(1, 50)
+ runner.capture_error, runner.keep_failing = RuntimeError("cannot capture"), True
+
+ with caplog.at_level(logging.ERROR):
+ for rows in (2, 3, 4):
+ assert runner.offer(rows, 50) is None
+
+ assert runner.disabled
+ assert runner.graph_count == 0
+ assert runner.offer(1, 50) is None
+ assert runner.stats.eager == {"recording_failed": 3, "disabled": 1}
+ assert "are off for this process after 3 shapes failed to record" in caplog.text
+
+ def test_a_first_replay_that_fails_counts_as_a_failed_recording(self) -> None:
+ runner = _Runner()
+ runner.replay_error = RuntimeError("replay failed")
+
+ assert runner.offer(1, 50) is None
+
+ assert runner.graph_count == 0
+ assert runner.stats.recorded == 0
+ assert runner.stats.recording_failures == 1
+ runner.replay_error = None
+ assert runner.offer(1, 50) is None # that shape is not recorded again
+ assert runner.stats.eager == {"recording_failed": 1, "failed_shape": 1}
+
+ def test_a_first_replay_that_runs_out_of_memory_reaches_oom_recovery_and_pauses_recording(self) -> None:
+ runner = _Runner()
+ runner.offer(1, 50)
+ runner.replay_error = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ runner.offer(2, 50)
+
+ assert runner.graph_count == 0 # every graph dropped
+ assert runner.stats.drops == 1
+ assert runner.stats.recording_failures == 0 # memory is not the shape's fault
+ assert not RECORDING_LOCK.locked()
+ runner.replay_error = None
+ assert runner.offer(2, 50) is None
+ assert runner.stats.eager == {"recording_paused": 1}
+ runner.now += 60.0
+ assert runner.offer(2, 50) is not None
+
+ def test_running_out_of_memory_while_recording_pauses_recording(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner()
+ runner.offer(1, 50)
+ runner.capture_error = graphs_module._RecordingOutOfMemoryError("CUDA out of memory")
+
+ with caplog.at_level(logging.INFO):
+ assert runner.offer(2, 50) is None
+
+ assert runner.graph_count == 0
+ assert "ran out of memory; graphs dropped, recording paused for 60 s" in caplog.text
+ runner.now += 59.0
+ assert runner.offer(2, 50) is None
+ runner.now += 1.0
+ assert runner.offer(2, 50) is not None
+
+ def test_every_call_counts_once(self) -> None:
+ runner = _Runner()
+ runner.capture_error = RuntimeError("cannot capture")
+
+ for rows in (1, 1, 2, 2, 2):
+ runner.offer(rows, 50)
+
+ stats = runner.stats
+ assert stats.forwards == 5
+ assert (stats.recorded, stats.replayed, stats.eager) == (1, 2, {"recording_failed": 1, "failed_shape": 1})
+
+ def test_the_runner_logs_its_counts_every_ten_minutes(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner(name="fastino/GLiNER2.5-Decide")
+
+ with caplog.at_level(logging.INFO):
+ runner.offer(1, 50)
+ assert "forwards in the last" not in caplog.text
+ runner.now += 600.0
+ runner.offer(1, 50)
+ runner.offer(1, 50)
+
+ assert caplog.text.count("forwards in the last") == 1
+ assert "fastino/GLiNER2.5-Decide: 2 forwards in the last 600 s, 50.0% replayed" in caplog.text
+ assert "1 graphs" in caplog.text
+
+ def test_clear_drops_every_graph_and_what_it_kept(self) -> None:
+ runner = _Runner()
+ runner.bytes_per_graph, runner.budget = 100, 150
+ runner.offer(1, 50)
+ runner.offer(2, 50) # over the budget: recording stops
+
+ runner.clear()
+
+ assert (runner.graph_count, runner.held_bytes) == (0, 0)
+ assert runner.offer(3, 50) is not None # and may start again
+
+
+class TestGraphsThatDoNotPay:
+ """A graph is kept only if the GPU replays it no slower than the host launches a forward."""
+
+ def test_a_graph_slower_than_a_launch_is_not_kept_and_its_shape_runs_eagerly(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 30.0, 0.03 # an L4: about 1,000 tokens in a launch
+
+ assert runner.offer(8, 60) is not None # 512 tokens: 15 ms
+ assert runner.offer(16, 60) is None # 1,024 tokens: 31 ms
+ assert runner.offer(16, 60) is None # not recorded again
+
+ assert runner.recorded == [(8, 64), (16, 64)]
+ assert runner.graph_count == 1
+ assert runner.stats.eager == {"not_faster": 2}
+ assert runner.stats.recording_failures == 0
+ assert not runner.disabled
+ assert not RECORDING_LOCK.locked()
+
+ def test_a_faster_gpu_keeps_more_shapes(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 15.0, 0.006 # an RTX PRO 6000
+
+ assert runner.offer(16, 60) is not None
+ assert runner.offer(32, 60) is not None # 2,048 tokens: 12 ms
+ assert runner.stats.eager == {}
+
+ def test_a_replay_as_long_as_a_launch_keeps_its_graph(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 32.0, 0.5
+
+ assert runner.offer(1, 60) is not None # 64 tokens: 32 ms
+
+ def test_the_launch_is_timed_once(self) -> None:
+ runner = _Runner()
+ assert runner.launch_ms is None
+
+ for rows in (1, 2, 3):
+ runner.offer(rows, 60)
+
+ assert runner.launches_timed == 1
+ assert runner.launch_ms == 30.0
+
+ def test_shapes_no_smaller_than_a_slow_one_are_not_recorded(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 30.0, 0.03
+ runner.offer(16, 60) # slower than a launch
+ recorded = list(runner.recorded)
+
+ assert runner.offer(16, 70) is None # as many rows, longer
+ assert runner.offer(24, 60) is None # more rows, as long
+ assert runner.offer(32, 10) is not None # more rows but shorter (512 tokens): timed for itself
+ assert runner.offer(12, 70) is not None # fewer rows (960 tokens): timed for itself
+
+ assert runner.recorded == [*recorded, (32, 16), (12, 80)]
+ assert runner.stats.eager == {"not_faster": 3}
+
+ def test_what_the_runner_learned_about_the_host_survives_dropping_the_graphs(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 30.0, 0.03
+ runner.offer(8, 60)
+ runner.offer(16, 60)
+
+ runner.clear()
+
+ assert runner.offer(16, 60) is None
+ assert runner.offer(8, 60) is not None
+ assert runner.launches_timed == 1
+
+ def test_memory_a_dropped_recording_left_in_the_pool_counts_against_the_budget(self) -> None:
+ runner = _Runner()
+ runner.host_launch_ms, runner.replay_ms_per_token = 30.0, 0.03
+ runner.pool_growth = 100
+
+ runner.offer(16, 60)
+
+ assert runner.graph_count == 0
+ assert runner.held_bytes == 100 + torch.zeros(1).nbytes # and the length's relative-position table
+
+ def test_the_summary_counts_the_shapes_that_do_not_pay(self, caplog: pytest.LogCaptureFixture) -> None:
+ runner = _Runner(name="fastino/GLiNER2.5-Decide")
+ runner.host_launch_ms, runner.replay_ms_per_token = 30.0, 0.03
+
+ with caplog.at_level(logging.INFO):
+ runner.offer(16, 60)
+ runner.now += 600.0
+ runner.offer(1, 60)
+
+ assert "this host launches a forward in 30.0 ms" in caplog.text
+ assert "1 shapes not faster than a launch" in caplog.text
+
+
+class TestRecordingHook:
+ def test_the_hook_leaves_eager_forwards_alone(self) -> None:
+ encoder = _encoder()
+ DecideGraphRunner(encoder, window=512)
+
+ assert encoder.encoder.get_rel_pos(torch.zeros(1, 7, 1)) == ("built", 7)
+
+ def test_while_recording_the_encoder_gets_the_precomputed_table(self) -> None:
+ encoder = _encoder()
+ runner = DecideGraphRunner(encoder, window=512)
+
+ with runner._recording_on_this_thread("precomputed"):
+ assert encoder.encoder.get_rel_pos(torch.zeros(1, 7, 1)) == "precomputed"
+ # A caller that brings its own table keeps it.
+ assert encoder.encoder.get_rel_pos(torch.zeros(1, 7, 1), None, "own") == ("built", 7)
+ assert encoder.encoder.get_rel_pos(torch.zeros(1, 7, 1)) == ("built", 7)
+
+ def test_recording_diverts_only_the_recording_thread(self) -> None:
+ encoder = _encoder()
+ runner = DecideGraphRunner(encoder, window=512)
+ seen: list[Any] = []
+
+ with runner._recording_on_this_thread("precomputed"):
+ thread = threading.Thread(target=lambda: seen.append(encoder.encoder.get_rel_pos(torch.zeros(1, 9, 1))))
+ thread.start()
+ thread.join()
+
+ assert seen == [("built", 9)]
+
+ def test_each_thread_warms_the_recording_stream_up_for_itself(self) -> None:
+ # The engine loads and warms a model up on one thread and serves it on another; a thread that
+ # records without having used the runner's stream fails in cublasCreate.
+ runner = DecideGraphRunner(_encoder(), window=512)
+ runner._local.warmed = True # what a recording on this thread leaves
+ seen: list[bool] = []
+
+ thread = threading.Thread(target=lambda: seen.append(getattr(runner._local, "warmed", False)))
+ thread.start()
+ thread.join()
+
+ assert seen == [False]
+
+ def test_the_recording_state_is_cleared_when_recording_fails(self) -> None:
+ encoder = _encoder()
+ runner = DecideGraphRunner(encoder, window=512)
+
+ with pytest.raises(RuntimeError, match="boom"), runner._recording_on_this_thread("precomputed"):
+ raise RuntimeError("boom")
+
+ assert encoder.encoder.get_rel_pos(torch.zeros(1, 7, 1)) == ("built", 7)
+
+
+class _PaddingRunner(_Runner):
+ """Replays by running the adapter's fake encoder on the call padded to its graph's shape."""
+
+ def _replay(self, key: Any, entry: Any, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
+ if self.replay_error is not None:
+ raise self.replay_error
+ self.replayed.append(key)
+ rows, length = input_ids.shape
+ ids = torch.zeros(key, dtype=torch.long)
+ mask = torch.zeros(key, dtype=torch.long)
+ ids[:rows, :length], mask[:rows, :length] = input_ids, attention_mask
+ return FakeEncoder()(ids, mask).last_hidden_state[:rows]
+
+
+def _adapter_with(runner: _Runner | None, **kwargs: Any) -> GLiNER2DecideAdapter:
+ adapter, _ = make_adapter(**kwargs)
+ adapter._graphs = runner
+ return adapter
+
+
+class TestAdapter:
+ def test_a_call_that_fits_a_graph_scores_as_it_does_eagerly(self) -> None:
+ runner = _PaddingRunner(window=256)
+ adapter = _adapter_with(runner)
+ rows = [[5] * n for n in (3, 40, 7, 61, 1)]
+ positions = [0, 1, 2]
+
+ out = adapter._score(rows, positions)
+
+ np.testing.assert_allclose(
+ out, np.array([expected_logits(row, positions) for row in rows]), rtol=1e-5, atol=1e-9
+ )
+ assert runner.replayed == [(6, 64)] # one forward: five rows, padded to six of 64 tokens
+
+ def test_a_call_that_fits_no_graph_runs_as_it_does_without_graphs(self) -> None:
+ runner = _PaddingRunner(window=256)
+ adapter = _adapter_with(runner, inference_batch_tokens=256)
+ rows = [[5] * n for n in (3, 40, 7, 250, 1, 9, 9, 9, 9)] # nine rows of 256 tokens pass the token bound
+ positions = [0, 1, 2]
+
+ out = adapter._score(rows, positions)
+
+ np.testing.assert_allclose(
+ out, np.array([expected_logits(row, positions) for row in rows]), rtol=1e-5, atol=1e-9
+ )
+ assert runner.stats.forwards == 0
+
+ def test_a_graph_that_cannot_be_recorded_yet_runs_its_call_eagerly(self) -> None:
+ runner = _PaddingRunner(window=256)
+ runner.headroom = False
+ adapter = _adapter_with(runner)
+ rows = [[5] * n for n in (3, 40)]
+
+ out = adapter._score(rows, [0, 1])
+
+ np.testing.assert_allclose(out, np.array([expected_logits(row, [0, 1]) for row in rows]), rtol=1e-5, atol=1e-9)
+ assert runner.stats.eager == {"no_headroom": 1}
+
+ def test_rows_read_their_own_label_markers(self) -> None:
+ runner = _PaddingRunner(window=256)
+ adapter = _adapter_with(runner)
+ rows = [[5] * 12, [7] * 30, [9] * 20]
+ positions = [[0, 3], [1, 2, 4, 8], [5]]
+
+ out = adapter._score_rows(rows, positions)
+
+ assert [len(logits) for logits in out] == [2, 4, 1]
+ for logits, row, markers in zip(out, rows, positions, strict=True):
+ np.testing.assert_allclose(logits, expected_logits(row, markers), rtol=1e-5, atol=1e-9)
+ assert runner.replayed == [(3, 32)]
+
+ def test_rows_read_their_own_label_markers_without_graphs_too(self) -> None:
+ adapter = _adapter_with(None, window=64, inference_batch_tokens=64)
+ rows = [[5] * 12, [7] * 64, [9] * 20, [3] * 40] # 64 tokens a forward: three forwards
+ positions = [[0, 3], [1, 2, 4, 8], [5], [6, 7]]
+
+ out = adapter._score_rows(rows, positions)
+
+ for logits, row, markers in zip(out, rows, positions, strict=True):
+ np.testing.assert_allclose(logits, expected_logits(row, markers), rtol=1e-5, atol=1e-9)
+
+ def test_an_out_of_memory_error_drops_the_graphs(self) -> None:
+ runner = _PaddingRunner(window=256)
+ adapter = _adapter_with(runner)
+ adapter._score([[5] * 10], [0])
+ assert runner.graph_count == 1
+ runner.replay_error = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ adapter._score([[5] * 10], [0])
+
+ assert runner.graph_count == 0
+
+ def test_other_errors_keep_the_graphs(self) -> None:
+ runner = _PaddingRunner(window=256)
+ adapter = _adapter_with(runner)
+ adapter._score([[5] * 10], [0])
+ runner.replay_error = RuntimeError("device-side assert")
+
+ with pytest.raises(RuntimeError, match="device-side assert"):
+ adapter._score([[5] * 10], [0])
+
+ assert runner.graph_count == 1
+
+ def test_unloading_drops_the_runner(self) -> None:
+ assert "_graphs" in GLiNER2DecideAdapter.spec.unload_fields
+
+
+class TestOperatorSetting:
+ """Graphs are chosen when the model loads."""
+
+ @pytest.mark.parametrize(("text", "mode"), [("off", "off"), ('"off"', "off"), ("bucketed", "bucketed")])
+ def test_profiles_may_write_off_unquoted(self, text: str, mode: str) -> None:
+ loadtime = yaml.safe_load(f"cuda_graphs: {text}") # YAML reads unquoted off as False
+
+ assert GLiNER2DecideAdapter("tiny", **loadtime)._cuda_graphs == mode
+
+ def test_graphs_are_off_unless_the_operator_turns_them_on(self) -> None:
+ assert GLiNER2DecideAdapter("tiny")._cuda_graphs == "off"
+
+ @pytest.mark.parametrize("value", ["on", "exact", "Bucketed", "", None, True, 0])
+ def test_unknown_modes_fail_the_load(self, value: Any) -> None:
+ with pytest.raises(ValueError, match="cuda_graphs must be 'off' or 'bucketed'"):
+ GLiNER2DecideAdapter("tiny", cuda_graphs=value)
+
+ def test_profiles_may_set_it_at_load(self) -> None:
+ reject_unknown_loadtime_options(GLiNER2DecideAdapter, {"cuda_graphs": "bucketed"}, model_name="tiny")
+
+ def test_off_builds_no_runner(self) -> None:
+ adapter = GLiNER2DecideAdapter("tiny")
+
+ assert adapter._graph_runner(SimpleNamespace(encoder=_encoder()), "cuda") is None
+
+ def test_an_encoder_graphs_do_not_apply_to_runs_eagerly_and_says_so(self, caplog: pytest.LogCaptureFixture) -> None:
+ adapter = GLiNER2DecideAdapter("fastino/GLiNER2.5-Decide-1B", cuda_graphs="bucketed")
+
+ with caplog.at_level(logging.WARNING):
+ runner = adapter._graph_runner(SimpleNamespace(encoder=_encoder(encoder_type="modernbert")), "cuda")
+
+ assert runner is None
+ assert "cuda_graphs=bucketed does not apply to fastino/GLiNER2.5-Decide-1B" in caplog.text
+ assert "the modernbert encoder is not supported" in caplog.text
+
+ def test_a_supported_encoder_gets_a_runner_for_the_models_window(self) -> None:
+ adapter = GLiNER2DecideAdapter("tiny", cuda_graphs="bucketed", max_seq_length=512)
+ adapter._tokenizer = SimpleNamespace(pad_token_id=3)
+
+ runner = adapter._graph_runner(SimpleNamespace(encoder=_encoder()), "cuda:0")
+
+ assert runner is not None
+ assert runner.shape_count == 132
+ assert runner._pad_token_id == 3
+
+
+def test_a_graph_keeps_to_the_operators_bound_on_a_forward_pass() -> None:
+ adapter = GLiNER2DecideAdapter("tiny", cuda_graphs="bucketed", max_seq_length=512, inference_batch_tokens=640)
+ adapter._tokenizer = SimpleNamespace(pad_token_id=0)
+
+ runner = adapter._graph_runner(SimpleNamespace(encoder=_encoder()), "cuda")
+
+ assert runner is not None
+ assert runner.key(8, 60) == (8, 64) # 512 padded tokens
+ assert runner.key(12, 60) is None # 768 would pass the 640 the operator allows a forward
+ assert runner.key(1, 512) == (1, 512)
+ assert all(batch * length <= 640 for batch, length in runner._shapes)
+
+
+def test_shipped_profiles_enable_graphs_only_where_measured() -> None:
+ configs = load_model_configs(_MODELS_DIR)
+ modes = {
+ name.split(":")[0]: config.resolve_profile("default").loadtime.get("cuda_graphs", "off")
+ for name, config in configs.items()
+ if config.resolve_profile("default").adapter_path.endswith(":GLiNER2DecideAdapter")
+ }
+
+ assert len(modes) == 3
+ assert {name for name, mode in modes.items() if mode != "off"} == _BUCKETED_BY_DEFAULT
+ for name in _BUCKETED_BY_DEFAULT:
+ assert modes[name] == "bucketed"
+ adapter = GLiNER2DecideAdapter(**_build_adapter_kwargs(configs[name], "float16"))
+ assert adapter._cuda_graphs == "bucketed"
diff --git a/packages/sie_server/tests/core/test_worker_extract_groups.py b/packages/sie_server/tests/core/test_worker_extract_groups.py
new file mode 100644
index 000000000..17ae469eb
--- /dev/null
+++ b/packages/sie_server/tests/core/test_worker_extract_groups.py
@@ -0,0 +1,130 @@
+"""A batch with several extract configurations is shown to the adapter whole before its per-configuration calls."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from sie_server.core.inference_output import ExtractOutput
+from sie_server.core.prepared import ExtractPreparedItem
+from sie_server.core.worker import ModelWorker, WorkerConfig
+from sie_server.core.worker.handlers.extract import ExtractHandler
+from sie_server.types.inputs import Item
+
+
+def _adapter(*, primes: bool = True, error: Exception | None = None, width: int | None = None) -> MagicMock:
+ """An adapter that records, in order, the calls the worker makes (``adapter.calls``)."""
+ adapter = MagicMock()
+ adapter.calls = []
+ adapter.groups = []
+ adapter.supports_lora.return_value = False
+ if width is None:
+ del adapter.max_concurrent_dispatch
+ else:
+ adapter.max_concurrent_dispatch.return_value = width
+
+ def extract(items: list[Item], **kwargs: Any) -> ExtractOutput:
+ adapter.calls.append(("extract", (tuple(kwargs["labels"]), [item.text for item in items])))
+ return ExtractOutput(entities=[[] for _ in items])
+
+ def prime(groups: list[dict[str, Any]]) -> None:
+ adapter.calls.append(
+ ("prime", [(tuple(group["labels"]), [item.text for item in group["items"]]) for group in groups])
+ )
+ adapter.groups = groups
+ if error is not None:
+ raise error
+
+ adapter.extract.side_effect = extract
+ if primes:
+ adapter.prime_extract_groups.side_effect = prime
+ else:
+ del adapter.prime_extract_groups
+ return adapter
+
+
+async def _run(adapter: Any, requests: list[tuple[str, list[str], dict[str, Any] | None]]) -> list[Any]:
+ """Submit one-item extract requests that land in one batch; their results."""
+ worker = ModelWorker(adapter, WorkerConfig(max_batch_tokens=1000, max_batch_requests=16, max_batch_wait_ms=50))
+ await worker.start()
+ try:
+ futures = [
+ await worker.submit_extract(
+ [ExtractPreparedItem(cost=len(text), original_index=0)],
+ [Item(text=text)],
+ labels=labels,
+ options=options,
+ )
+ for text, labels, options in requests
+ ]
+ return await asyncio.wait_for(asyncio.gather(*futures, return_exceptions=True), timeout=5.0)
+ finally:
+ await worker.stop()
+
+
+async def test_a_batch_of_several_configurations_is_primed_once_before_its_calls() -> None:
+ adapter = _adapter()
+
+ results = await _run(
+ adapter,
+ [("a", ["x", "y"], None), ("b", ["y", "x"], None), ("c", ["x", "y"], None), ("d", ["z"], {"threshold": 0.5})],
+ )
+
+ assert all(result.output.batch_size == 1 for result in results)
+ groups = [(("x", "y"), ["a", "c"]), (("y", "x"), ["b"]), (("z",), ["d"])]
+ assert adapter.calls == [("prime", groups), *(("extract", group) for group in groups)]
+ # Each group carries the arguments its extract call gets.
+ assert [group["options"] for group in adapter.groups] == [None, None, {"threshold": 0.5}]
+ assert all(group["output_schema"] is None and group["instruction"] is None for group in adapter.groups)
+
+
+async def test_a_batch_of_one_configuration_is_not_primed() -> None:
+ adapter = _adapter()
+
+ await _run(adapter, [("a", ["x", "y"], None), ("b", ["x", "y"], None)])
+
+ assert adapter.calls == [("extract", (("x", "y"), ["a", "b"]))]
+
+
+async def test_an_adapter_without_the_method_is_left_alone() -> None:
+ adapter = _adapter(primes=False)
+
+ results = await _run(adapter, [("a", ["x"], None), ("b", ["y"], None)])
+
+ assert all(result.output.batch_size == 1 for result in results)
+ assert [name for name, _ in adapter.calls] == ["extract", "extract"]
+
+
+async def test_a_priming_error_leaves_every_configuration_to_its_own_call(caplog: pytest.LogCaptureFixture) -> None:
+ adapter = _adapter(error=RuntimeError("no memory for one pass"))
+
+ with caplog.at_level("WARNING"):
+ results = await _run(adapter, [("a", ["x"], None), ("b", ["y"], None)])
+
+ assert all(result.output.batch_size == 1 for result in results)
+ assert [name for name, _ in adapter.calls] == ["prime", "extract", "extract"]
+ assert "Priming 2 extract configurations failed" in caplog.text
+
+
+async def test_a_worker_that_runs_batches_side_by_side_does_not_prime() -> None:
+ # What an adapter keeps from priming belongs to one batch; two batches at once would share it.
+ adapter = _adapter(width=2)
+
+ await _run(adapter, [("a", ["x"], None), ("b", ["y"], None)])
+
+ assert "prime" not in [name for name, _ in adapter.calls]
+
+
+def test_the_handler_primes_nothing_for_a_single_group() -> None:
+ adapter = _adapter()
+
+ ExtractHandler().prime(adapter, [([Item(text="a")], (("x",), None, None, None), [])])
+
+ assert adapter.calls == []