Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(server): replay GLiClass forwards as CUDA graphs (#367)

svonava7afc1691422c
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index c9f221559..8b11c182c 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -149,6 +149,15 @@ An item whose document pushes the labels out of the window, in any of its rows,
comes back with an `INPUT_TOO_LONG` error in its `error` field and is not
billed. The other items still succeed.
+On a CUDA server, the operator can load the DeBERTa-based GLiClass models with
+CUDA graphs, which cut the CPU time spent launching kernels. With `bucketed`
+graphs, sequence lengths are padded to buckets, which moves probabilities
+slightly, as batching requests together does: by up to 0.006 on
+`gliclass-large-v1.0` and 0.023 on `gliclass-multilang-mini` in our tests.
+Send `options={"cuda_graphs": "off"}` to run a request eagerly; a request
+cannot turn graphs on. See the server README for the supported models and
+memory use.
+
## Generation prompts and guard verdicts
`generate` and `stream_generate` treat text-only prompts as raw continuation
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index 68f0ac54d..61d4e1a3c 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -67,6 +67,101 @@ Label names are refused when their total length exceeds 16 characters per
token of the window (8,192 characters for a 512-token model), more than any
label prompt can fit.
+### GLiClass CUDA graphs
+
+A GLiClass forward on a DeBERTa encoder launches about a thousand small GPU
+kernels, so at small batch sizes the CPU that launches them is the bottleneck.
+A CUDA graph records the kernel launches of one input shape once; a replay
+launches them all in one call. Graphs are an operator setting, fixed when the
+model loads, in the model profile:
+
+```yaml
+profiles:
+ default:
+ adapter_options:
+ loadtime:
+ cuda_graphs: bucketed
+```
+
+| Value | Shapes recorded | Scores |
+|--|--|--|
+| `off` (default) | none | eager |
+| `exact` | each (batch, sequence length, label slots) seen twice | bit-identical to eager |
+| `bucketed` | sequence lengths padded up to a multiple of 32 tokens (64 on 1,024-token models) | padding moves fp16 probabilities (see below) |
+
+A request can send `options={"cuda_graphs": "off"}` to run eagerly on a model
+loaded with graphs. It cannot turn graphs on: any other value is refused.
+
+Padding is masked, but a longer sequence rounds fp16 sums differently, the same
+kind of change batching requests together makes. We compared `bucketed` with
+eager execution on the 384 CVE descriptions from `examples/typed-decisions`,
+three questions each, asked one at a time, as separate groups and as joint
+groups, plus 65 long documents. Each input was sent three times (long
+documents twice), so that graphs were recorded and then replayed: 11,538
+answers per model. A small change can still flip a near tie between the top
+two labels:
+
+| Model | Largest probability change | Top label changed |
+|--|--|--|
+| `gliclass-small-v1.0` | 0.004 | 3 answers |
+| `gliclass-base-v1.0` | 0.005 | none |
+| `gliclass-large-v1.0` | 0.006 | none |
+| `gliclass-base-v3.0` | 0.005 | 3 |
+| `gliclass-large-v3.0` | 0.009 | 3 |
+| `gliclass-instruct-base-v1.0` | 0.008 | 12 |
+| `gliclass-instruct-large-v1.0` | 0.010 | 18 |
+| `opir-multitask-large-v1.0` | 0.014 | none |
+| `gliclass-multilang-mini` (100 descriptions, no joint groups: 2,016 answers) | 0.023 | 3 |
+
+`exact` changed nothing.
+
+Graphs apply on CUDA to the DeBERTa-based GLiClass models: the v1.0 models,
+`gliclass-base-v3.0` and `gliclass-large-v3.0`, the base and large instruct
+models, the Opir multitask models and `gliclass-multilang-mini`. The
+ModernBERT-based models (the edge models, `gliclass-multilang-edge` and the
+Opir edge models), CPU and MPS run eagerly with any value, and the load logs a
+warning.
+
+Nothing is recorded at load. A shape is recorded the first time a request
+needs it (the second time in `exact` mode), and that request takes a little
+over two eager forwards (76 ms against 33 ms on `gliclass-large-v1.0` on an
+L4). A model keeps at most 64 graphs, least recently used first
+out. A graph holds at most 2,048 tokens (batch times padded length); larger
+forwards are bound by the GPU rather than by kernel launches and run eagerly.
+
+**Memory, and other models on the same GPU.** Graph memory counts as device
+memory in use, but it is not attributed to the model: under memory pressure
+the server evicts whole models, least recently used first, which may be
+another model. A model's graphs share one memory pool, and the driver keeps a
+copy of each graph: about 8 MB for a `gliclass-large-v1.0` forward. On
+`gliclass-large-v1.0` in `bucketed` mode, the 31 graphs recorded for the CVE
+descriptions above took 555 MB of device memory: 490 MB for the pool and
+the graphs, 60 MB cached on the recording stream (its cuBLAS workspace and one
+warm-up row) and 5 MB of relative-position tables. The pool keeps what evicted
+graphs used, so traffic with many shapes keeps growing it. The runner therefore
+adds up the device memory its graphs hold (what each recording took, plus the
+tables and buffers they read), and past 4% of the device's memory (900 MB on
+an L4) it drops every graph, returns their memory to the device and records
+again. Graphs are also released when the model unloads, and
+when one of its forwards runs out of memory.
+
+While a graph records, PyTorch's caching allocator does not free cached blocks
+to satisfy other allocations, so another model on the same GPU that needs
+memory in that window (about one forward) can run out of memory where it
+otherwise would not. Recording is kept rare to limit this: one recording at a
+time in the process, none while less than a tenth of the device's memory is
+free, and per model at most 16 recordings at once, then one per 2 seconds. If a
+recording itself runs out of memory, the request still gets its eager answer;
+the model drops its graphs and records nothing for a minute.
+
+Both limits are approximate. The free-memory check reads the device once,
+before recording, so a model loading at the same moment can still meet one
+recording. The memory budget is checked after each recording, so a model's
+graphs can exceed it by one recording: up to about 330 MB, one graph of the
+largest shape on `gliclass-large-v1.0`. On a GPU shared with other models,
+leave memory headroom, or enable graphs only where the model has the GPU to
+itself. Usage and billing do not change.
+
## Configuration
`sie-server` reads its config from `SIE_*` environment variables (Pydantic
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
index 744d5bf5f..7f99de89e 100644
--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py
@@ -25,6 +25,10 @@ like the pipeline call used before these fields existed):
this request, overriding the load-time default.
- ``options.label_groups``: named label groups, ``{"urgency": ["low", "high"],
...}``, used instead of ``labels``. ``data`` holds one answer per group.
+- ``options.cuda_graphs``: only ``"off"``, which runs this request eagerly
+ when the model was loaded with CUDA graphs. Graphs are enabled by the
+ operator, at load, with ``adapter_options.loadtime.cuda_graphs``: ``"off"``
+ (the default), ``"exact"`` or ``"bucketed"`` (see ``cuda_graphs.py``).
- ``options.group_encoding``: how label groups are encoded. ``"separate"`` (the
default) encodes the document once per group, with only that group's labels.
Each group scores like a request whose ``labels`` are that group's labels.
@@ -52,6 +56,7 @@ document needing more fails alone with ``INPUT_TOO_LONG``.
from __future__ import annotations
+import logging
import math
import re
from collections.abc import Iterator
@@ -69,8 +74,10 @@ 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.gliclass.cuda_graphs import GRAPH_MODES, CudaGraphRunner, GraphMode, unsupported_reason
from sie_server.core.extract_cost import MAX_EXTRACT_LABELS
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
from sie_server.types.overflow_policy import DEFAULT_OVERFLOW_POLICY, OverflowPolicy
from sie_server.types.responses import Classification, ErrorCode
@@ -80,6 +87,8 @@ if TYPE_CHECKING:
from sie_server.types.inputs import Item
+logger = logging.getLogger(__name__)
+
_ERR_REQUIRES_LABELS = "Zero-shot classification requires labels parameter."
_ERR_INPUT_TOO_LONG = (
"Input overflowed the gliclass model's max sequence length (the label/text "
@@ -450,7 +459,7 @@ class GLiClassAdapter(BaseAdapter):
spec: ClassVar[AdapterSpec] = AdapterSpec(
inputs=("text",),
outputs=("json",),
- unload_fields=("_pipe", "_tokenizer"),
+ unload_fields=("_pipe", "_tokenizer", "_graphs"),
)
def __init__(
@@ -462,6 +471,7 @@ class GLiClassAdapter(BaseAdapter):
max_seq_length: int | None = None,
compute_precision: ComputePrecision = "float16",
revision: str | None = None,
+ cuda_graphs: str | bool = "off",
**kwargs: Any,
) -> None:
"""Initialize GLiClass adapter.
@@ -481,7 +491,15 @@ class GLiClassAdapter(BaseAdapter):
compute_precision: Precision for inference (float16, float32, bfloat16).
revision: Optional HuggingFace revision/branch/commit SHA to pin when
loading model artifacts.
+ cuda_graphs: "off" (the default), "exact" or "bucketed": whether a
+ DeBERTa-based model on CUDA replays its forwards as CUDA graphs
+ (see ``cuda_graphs.py``). An operator setting: a request can
+ only opt out, with ``options={"cuda_graphs": "off"}``. YAML
+ reads an unquoted ``off`` as ``False``, which also means off.
**kwargs: Additional arguments (ignored for compatibility).
+
+ Raises:
+ ValueError: If ``cuda_graphs`` is not one of the three modes.
"""
self._model_name_or_path = str(model_name_or_path)
self._classification_type = self._validate_classification_type(classification_type)
@@ -489,10 +507,19 @@ class GLiClassAdapter(BaseAdapter):
self._max_seq_length = max_seq_length
self._compute_precision = compute_precision
self._revision = revision
+ 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:
+ msg = f"GLiClass cuda_graphs must be 'off', 'exact' or 'bucketed', got {cuda_graphs!r}"
+ raise ValueError(msg)
+ self._cuda_graphs = cast("GraphMode", cuda_graphs)
# The gliclass pipe for the model's architecture: it assembles and
# tokenizes model inputs and holds the model.
self._pipe: Any | None = None
+ # Records and replays forwards as CUDA graphs, when the operator
+ # enabled them and the model and device support them.
+ self._graphs: CudaGraphRunner | None = None
self._tokenizer: PreTrainedTokenizerBase | None = None
self._special_count: int = 0
self._max_token_chars: int = _DEFAULT_MAX_TOKEN_CHARS
@@ -563,6 +590,7 @@ class GLiClassAdapter(BaseAdapter):
self._tokenizer = tokenizer
self._special_count = int(tokenizer.num_special_tokens_to_add(pair=False))
self._max_token_chars = _longest_token_chars(tokenizer)
+ self._graphs = self._graph_runner(pipe, tokenizer)
def _load_tokenizer(self, shared_kwargs: dict[str, Any]) -> PreTrainedTokenizerBase:
try:
@@ -704,8 +732,8 @@ class GLiClassAdapter(BaseAdapter):
("single-label" or "multi-label"), ``examples`` (few-shot
``[{"text": str, "labels": [str, ...]}]``), ``label_groups``
(``{group: [label, ...]}``, used instead of ``labels``),
- ``group_encoding`` ("separate" or "joint") and
- ``overflow_policy``.
+ ``group_encoding`` ("separate" or "joint"), ``cuda_graphs``
+ (only "off", to run eagerly) and ``overflow_policy``.
Returns:
ExtractOutput where ``classifications[i]`` is the list of
@@ -755,6 +783,7 @@ class GLiClassAdapter(BaseAdapter):
effective_threshold = self._validate_threshold(opts.get("threshold", self._threshold))
overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)
+ graphs = self._request_cuda_graphs(opts)
tokens = _RequestTokens(self._tokenizer, self._visible_tokens())
if label_groups is not None and group_encoding == "separate":
@@ -768,6 +797,7 @@ class GLiClassAdapter(BaseAdapter):
threshold=effective_threshold,
overflow_policy=overflow_policy,
tokens=tokens,
+ graphs=graphs,
)
texts = [tokens.visible(text) or text for text in texts]
@@ -783,7 +813,9 @@ class GLiClassAdapter(BaseAdapter):
if label_groups is not None:
rows = (
- self._joint_scores(kept_texts, label_groups, normalized_labels, classification_type, prompt, examples)
+ self._joint_scores(
+ kept_texts, label_groups, normalized_labels, classification_type, prompt, examples, graphs=graphs
+ )
if kept_texts
else []
)
@@ -813,6 +845,7 @@ class GLiClassAdapter(BaseAdapter):
classification_type=classification_type,
prompt=prompt,
examples=examples,
+ graphs=graphs,
)
all_classifications: list[list[Classification]] = [[] for _ in items]
@@ -888,6 +921,7 @@ class GLiClassAdapter(BaseAdapter):
prompt: str | None,
examples: list[dict[str, Any]] | list[list[dict[str, Any]]] | None,
batch_size: int = _PIPELINE_BATCH_SIZE,
+ graphs: GraphMode = "off",
) -> list[list[float]]:
"""Each row's label scores, computed as the gliclass pipeline computes them.
@@ -897,6 +931,7 @@ class GLiClassAdapter(BaseAdapter):
sub-batches. A single-label row gets a softmax over the label slots a
call with only its labels would have; a multi-label row a sigmoid per
label. Each forward's scores come back in one device-to-host copy.
+ ``graphs`` chooses how forwards run on CUDA (see ``cuda_graphs``).
"""
pipe = self._require_pipe()
shared = isinstance(labels[0], str)
@@ -910,7 +945,7 @@ class GLiClassAdapter(BaseAdapter):
inputs = pipe.prepare_inputs(
batch_texts, batch_labels, same_labels=shared, examples=batch_examples, prompt=prompt
)
- logits = self._forward(pipe, inputs, batch_labels, same_labels=shared)
+ logits = self._forward(pipe, inputs, batch_labels, same_labels=shared, graphs=graphs)
row_labels = cast("list[list[str]]", [batch_labels] * len(batch_texts) if shared else batch_labels)
probs = torch.sigmoid(logits) if classification_type == "multi-label" else None
rows: list[torch.Tensor] = []
@@ -932,14 +967,58 @@ class GLiClassAdapter(BaseAdapter):
position += len(row_label_list)
return scores
- @staticmethod
- def _forward(pipe: Any, inputs: Any, labels: list[str] | list[list[str]], *, same_labels: bool) -> torch.Tensor:
- """Run the model on tokenized rows, passing the class-slot count the pipeline passes."""
+ def _forward(
+ self,
+ pipe: Any,
+ inputs: Any,
+ labels: list[str] | list[list[str]],
+ *,
+ same_labels: bool,
+ graphs: GraphMode = "off",
+ ) -> torch.Tensor:
+ """Run the model on tokenized rows, passing the class-slot count the pipeline passes.
+
+ With ``graphs`` other than "off", a CUDA graph replays the forward
+ when the model and shape allow it; otherwise it runs eagerly.
+ """
forward_kwargs: dict[str, Any] = {}
resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)
if resolve_max_num_classes is not None:
forward_kwargs["max_num_classes"] = resolve_max_num_classes(labels, same_labels)
- return pipe.model(**inputs, **forward_kwargs).logits
+ classes = forward_kwargs.get("max_num_classes")
+ try:
+ if self._graphs is not None and isinstance(classes, int):
+ logits = self._graphs.run(dict(inputs), classes, graphs)
+ if logits is not None:
+ return logits
+ return pipe.model(**inputs, **forward_kwargs).logits
+ except Exception as exc:
+ # Graph memory is held until its graphs go; drop them so the
+ # worker's OOM recovery can reuse it.
+ if self._graphs is not None and is_oom_error(exc):
+ self._graphs.clear()
+ raise
+
+ def _graph_runner(self, pipe: Any, tokenizer: PreTrainedTokenizerBase) -> CudaGraphRunner | None:
+ """The CUDA graph runner for a loaded model; None when graphs are off or unsupported."""
+ model = getattr(pipe, "model", None)
+ if self._cuda_graphs == "off" or model is None:
+ return None
+ reason = unsupported_reason(model, getattr(pipe, "device", "cpu"))
+ if reason is not None:
+ logger.warning(
+ "GLiClass cuda_graphs=%s does not apply to %s, which runs eagerly: %s",
+ self._cuda_graphs,
+ self._model_name_or_path,
+ reason,
+ )
+ return None
+ return CudaGraphRunner(
+ model,
+ pad_token_id=int(tokenizer.pad_token_id),
+ pad_token_type_id=int(getattr(tokenizer, "pad_token_type_id", 0) or 0),
+ max_length=int(pipe.max_length),
+ )
@staticmethod
def _row_width(pipe: Any, labels: list[str], batch_width: int) -> int:
@@ -961,6 +1040,8 @@ class GLiClassAdapter(BaseAdapter):
classification_type: ClassificationType,
prompt: str | None,
examples: list[dict[str, Any]] | None,
+ *,
+ graphs: GraphMode = "off",
) -> list[list[float]]:
"""Score all groups' labels in one row per text and normalize per group.
@@ -984,7 +1065,7 @@ class GLiClassAdapter(BaseAdapter):
examples=examples,
prompt=prompt,
)
- logits = self._forward(pipe, inputs, flat_labels, same_labels=True)
+ logits = self._forward(pipe, inputs, flat_labels, same_labels=True, graphs=graphs)
if logits.shape[-1] < num_labels:
raise InputTooLongError(_ERR_INPUT_TOO_LONG)
chunks.append(logits[:, :num_labels].float())
@@ -1012,6 +1093,7 @@ class GLiClassAdapter(BaseAdapter):
threshold: float,
overflow_policy: OverflowPolicy,
tokens: _RequestTokens,
+ graphs: GraphMode = "off",
) -> ExtractOutput:
"""Encode the document once per group, with only that group's labels.
@@ -1094,6 +1176,7 @@ class GLiClassAdapter(BaseAdapter):
prompt=prompt,
group_examples=group_examples,
row_lengths=None if item_lengths is None else [item_lengths[index] for index in kept],
+ graphs=graphs,
)
return self._grouped_output(
rows,
@@ -1115,6 +1198,7 @@ class GLiClassAdapter(BaseAdapter):
prompt: str | None,
group_examples: list[list[dict[str, Any]]] | None,
row_lengths: list[list[int]] | None = None,
+ graphs: GraphMode = "off",
) -> list[list[float]]:
"""Scores of every (item, group) row, flattened per item in group order.
@@ -1149,6 +1233,7 @@ class GLiClassAdapter(BaseAdapter):
prompt=prompt,
examples=None if row_examples is None else [row_examples[row] for row in chunk],
batch_size=len(chunk),
+ graphs=graphs,
)
for row, row_scores in zip(chunk, scored, strict=True):
per_row[row] = row_scores
@@ -1160,6 +1245,7 @@ class GLiClassAdapter(BaseAdapter):
classification_type=classification_type,
prompt=prompt,
examples=group_examples[group] if group_examples is not None else None,
+ graphs=graphs,
)
for group, (_, group_labels) in enumerate(label_groups)
]
@@ -1323,6 +1409,19 @@ class GLiClassAdapter(BaseAdapter):
raise InvalidInputError("GLiClass group_encoding applies only with options.label_groups")
return encoding
+ def _request_cuda_graphs(self, opts: dict[str, Any]) -> GraphMode:
+ """The graph mode for a request: the load-time mode, unless the request opts out."""
+ if "cuda_graphs" not in opts:
+ return self._cuda_graphs
+ value = opts["cuda_graphs"]
+ # ``False`` is how YAML reads an unquoted ``off`` in a profile's runtime options.
+ if value is False or (isinstance(value, str) and value == "off"):
+ return "off"
+ raise InvalidInputError(
+ "GLiClass options.cuda_graphs accepts only 'off', to run a request eagerly. "
+ "CUDA graphs are enabled when the model loads, with adapter_options.loadtime.cuda_graphs."
+ )
+
def _check_group_count(self, label_groups: list[tuple[str, list[str]]]) -> None:
"""Bound the rows a separate-group request adds per item: one full row per group."""
window = self._max_seq_length or getattr(self._pipe, "max_length", None)
diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
new file mode 100644
index 000000000..b54814fa7
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py
@@ -0,0 +1,463 @@
+"""CUDA graphs for the GLiClass forward pass.
+
+A GLiClass forward on a DeBERTa encoder launches about a thousand small
+kernels, so at small batch sizes the GPU waits on the CPU that launches them.
+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``); a request can only opt out. A
+graph is recorded per (batch size, sequence length, class slots) and kept in
+a bounded least-recently-used cache. Forwards over 2,048 tokens run eagerly:
+the GPU, not kernel launches, bounds them. Two modes choose the sequence
+length:
+
+- ``exact`` records the request's own length. Replay launches the kernels
+ eager execution launches, so scores are bit-identical to eager. A shape is
+ recorded the second time it is seen, so lengths seen once cost nothing.
+- ``bucketed`` pads the length up to a bucket (a multiple of 32 tokens at a
+ 512-token window, 64 at 1,024), so a few graphs cover every length. Padding
+ is masked, but a longer sequence rounds fp16 sums differently, as when
+ requests are batched together: up to 0.006 in probability on
+ gliclass-large-v1.0 and 0.023 on gliclass-multilang-mini in our tests.
+
+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 is
+therefore kept rare and short:
+
+- 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 records at most 16 graphs at once, then one per 2 seconds.
+
+A runner's graphs hold device memory the server does not attribute to the
+model: their shared pool, which also keeps what evicted graphs used, the
+driver's copy of each recorded graph (about 8 MB for a DeBERTa-large
+forward), and the relative-position tables and static buffers they read. The
+runner adds up the device memory each recording takes, plus those tensors.
+Past 4% of the device's memory it drops every graph, returns the memory to the
+device and starts again.
+
+Recording needs a forward that never waits on the host. Two parts of the
+gliclass DeBERTa forward do: the relative-position table copies a CPU scalar
+to the GPU, and segment ids (instruct and Opir multitask models) read each
+row's positions with ``.item()``. While recording, the runner hands the
+encoder a table precomputed for the length, shared by the graphs of that
+length, and computes segment ids with tensor operations; both give the same
+integers.
+
+Replays never overlap (a lock serializes them) and every result is copied out
+before the next replay.
+Anything unsupported, larger than the token bound, or failing to record runs
+eagerly; a recording failure turns the runner off.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import logging
+import math
+import threading
+import time
+from collections import OrderedDict
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any, Literal
+
+import torch
+
+from sie_server.core.oom import is_oom_error
+
+logger = logging.getLogger(__name__)
+
+GraphMode = Literal["off", "exact", "bucketed"]
+GRAPH_MODES: tuple[GraphMode, ...] = ("off", "exact", "bucketed")
+# Recorded graphs per runner. Their activations share one pool; each also
+# holds its static inputs and output (up to 48 KB at 2,048 tokens).
+_MAX_GRAPHS = 64
+# Shapes whose sightings ``exact`` mode counts.
+_MAX_SIGHTINGS = 4096
+# ``exact`` mode records a shape the time it is seen this many times.
+_EXACT_RECORD_AT = 2
+# Tokens (batch x padded length) a graph may hold. Past about that many tokens
+# the GPU, not kernel launches, bounds a forward, so a graph saves little and
+# would pin a larger memory pool.
+_MAX_GRAPH_TOKENS = 2048
+# A runner may record this many graphs at once, then one per this many
+# seconds, however its forwards repeat: recording costs a forward, and while
+# it runs the allocator cannot free cached memory for other models.
+_RECORDING_BURST = 16
+_SECONDS_PER_RECORDING = 2.0
+# Recording waits until at least this share of the device's memory is free.
+_RECORDING_HEADROOM = 0.1
+# After a recording runs out of memory, the runner records nothing for this long.
+_OOM_COOL_DOWN_SECONDS = 60.0
+# One recording at a time in the process, across every model's runner.
+_RECORDING_LOCK = threading.Lock()
+# Device memory a runner's graphs may hold (their recordings, relative-position
+# tables and static buffers), as a share of the device's memory, before it
+# drops them and starts again.
+_MEMORY_BUDGET_SHARE = 0.04
+# Encoders whose forward records cleanly once the two host reads are replaced.
+_ENCODERS = frozenset({"deberta-v2"})
+# Poolings whose pooled vector ignores padded positions, so ``bucketed`` mode
+# pads only the length.
+_PADDING_SAFE_POOLINGS = frozenset({"first", "pass"})
+
+Key = tuple[int, int, int]
+
+
+def unsupported_reason(model: Any, device: str | torch.device) -> str | None:
+ """Why ``model`` cannot use CUDA graphs on ``device``; None when it can."""
+ if not str(device).startswith("cuda"):
+ return "CUDA graphs need a CUDA device"
+ config = getattr(model, "config", None)
+ if getattr(config, "architecture_type", None) != "uni-encoder":
+ return "only uni-encoder GLiClass models are supported"
+ encoder_type = getattr(getattr(config, "encoder_config", None), "model_type", None)
+ if encoder_type not in _ENCODERS:
+ return f"the {encoder_type} encoder is not supported"
+ encoder = getattr(getattr(getattr(model, "model", None), "encoder_model", None), "encoder", None)
+ if encoder is None or not hasattr(encoder, "get_rel_pos"):
+ return "the encoder has no relative-position hook"
+ return None
+
+
+def bucket_width(max_length: int) -> int:
+ """Sequence-length bucket for ``bucketed`` mode: 32 tokens at a 512 window, 64 at 1,024."""
+ return max(16, max_length // 16)
+
+
+class _RecordingError(Exception):
+ """Recording a graph failed after the eager forward had answered the call."""
+
+ def __init__(self, cause: BaseException, logits: torch.Tensor) -> None:
+ super().__init__(str(cause))
+ self.cause = cause
+ self.logits = logits
+
+
+@dataclass
+class _Graph:
+ graph: Any
+ inputs: dict[str, torch.Tensor]
+ output: torch.Tensor
+ # Device memory the recording took: pool growth and the recorded graph.
+ device_bytes: int = 0
+
+
+class CudaGraphRunner:
+ """Records and replays the forward pass of one GLiClass model, per input shape."""
+
+ def __init__(
+ self,
+ model: Any,
+ *,
+ pad_token_id: int,
+ max_length: int,
+ pad_token_type_id: int = 0,
+ max_graphs: int = _MAX_GRAPHS,
+ clock: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self._model = model
+ self._pad_values = {"input_ids": pad_token_id, "attention_mask": 0, "token_type_ids": pad_token_type_id}
+ self._max_length = max_length
+ self._bucket = bucket_width(max_length)
+ self._max_tokens = _MAX_GRAPH_TOKENS
+ self._max_graphs = max_graphs
+ self._graphs: OrderedDict[Key, _Graph] = OrderedDict()
+ self._sightings: OrderedDict[Key, int] = OrderedDict()
+ self._lock = threading.RLock()
+ self._stream: torch.cuda.Stream | None = None
+ self._disabled = False
+ self._clock = clock
+ # Device memory recordings have taken since the graphs were last
+ # dropped; evicting a graph does not give its share of the pool back.
+ 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] = {}
+ # Set only while recording: the relative-position table the encoder uses.
+ self._recording_relative_pos: torch.Tensor | None = None
+ self._recording = False
+ config = model.config
+ self._padding_safe = config.pooling_strategy in _PADDING_SAFE_POOLINGS and not getattr(
+ config, "use_lstm", False
+ )
+ self._install_hooks()
+
+ # -- hooks -------------------------------------------------------------
+
+ def _install_hooks(self) -> None:
+ inner = self._model.model
+ encoder = inner.encoder_model.encoder
+ get_rel_pos = encoder.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 self._recording and relative_pos is None:
+ return self._recording_relative_pos
+ return get_rel_pos(hidden_states, query_states, relative_pos)
+
+ encoder.get_rel_pos = recording_get_rel_pos
+ if getattr(self._model.config, "use_segment_embeddings", False):
+ create_segment_ids = inner._create_segment_ids
+ config = self._model.config
+
+ def recording_segment_ids(input_ids: torch.Tensor) -> torch.Tensor:
+ if not self._recording:
+ return create_segment_ids(input_ids)
+ return segment_ids(input_ids, config)
+
+ inner._create_segment_ids = recording_segment_ids
+
+ # -- policy ------------------------------------------------------------
+
+ def key(self, batch: int, length: int, classes: int, mode: GraphMode) -> Key | None:
+ """The graph a forward of this shape would replay; None when it runs eagerly."""
+ if mode == "bucketed" and self._padding_safe:
+ length = min(self._max_length, math.ceil(length / self._bucket) * self._bucket)
+ if batch * length > self._max_tokens or length > self._max_length:
+ return None
+ return (batch, length, classes)
+
+ def _should_record(self, key: Key, mode: GraphMode) -> bool:
+ if mode != "exact":
+ return True
+ seen = self._sightings.pop(key, 0) + 1
+ self._sightings[key] = seen
+ while len(self._sightings) > _MAX_SIGHTINGS:
+ self._sightings.popitem(last=False)
+ return seen >= _EXACT_RECORD_AT
+
+ # -- entry point -------------------------------------------------------
+
+ def run(self, inputs: dict[str, torch.Tensor], max_num_classes: int, mode: GraphMode) -> torch.Tensor | None:
+ """Logits for ``inputs`` from a graph, or None to run the forward eagerly."""
+ if mode == "off" or self._disabled:
+ return None
+ input_ids = inputs.get("input_ids")
+ if input_ids is None or input_ids.dim() != 2 or set(inputs) - set(self._pad_values):
+ return None
+ batch, length = input_ids.shape
+ key = self.key(batch, length, max_num_classes, mode)
+ if key is None:
+ return None
+ with self._lock:
+ 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._graphs.move_to_end(key)
+ return self._replay(entry, inputs, length)
+ if not self._should_record(key, mode) or self._recording_credit < 1:
+ return None
+ if not self._has_headroom(input_ids.device):
+ return None
+ if not _RECORDING_LOCK.acquire(blocking=False):
+ return None # another model is recording
+ try:
+ self._recording_credit -= 1
+ try:
+ entry, logits = self._record(key, inputs)
+ except _RecordingError as failure:
+ # The eager forward has answered this call; only the graph
+ # failed, so the answer stands and no OOM recovery is needed.
+ self.clear()
+ if is_oom_error(failure.cause):
+ logger.info(
+ "GLiClass CUDA graph recording ran out of memory; recording paused for %d s",
+ _OOM_COOL_DOWN_SECONDS,
+ )
+ self._recording_credit = 1 - _OOM_COOL_DOWN_SECONDS / _SECONDS_PER_RECORDING
+ else:
+ logger.warning(
+ "GLiClass CUDA graph recording failed; running eagerly from now on", exc_info=failure.cause
+ )
+ self._disabled = True
+ return failure.logits
+ except Exception as exc: # the eager forward that answers this call failed
+ if is_oom_error(exc):
+ # Release the graphs and let the worker's OOM recovery
+ # see the error.
+ self.clear()
+ raise
+ logger.warning("GLiClass CUDA graph recording failed; running eagerly from now on", exc_info=True)
+ self.clear()
+ self._disabled = True
+ return None
+ self._graphs[key] = entry
+ self._device_bytes += entry.device_bytes
+ del entry # the cache holds the only reference, so dropping it frees the graph
+ while len(self._graphs) > self._max_graphs:
+ self._graphs.popitem(last=False)
+ self._drop_unused_tables()
+ held = self._device_bytes + self._tensor_bytes()
+ if held > self._memory_budget(input_ids.device):
+ logger.info(
+ "GLiClass CUDA graphs took %d MB, over their budget; dropping them to record again",
+ held // 2**20,
+ )
+ self.clear()
+ # With every graph gone, their pool can go back to the device.
+ torch.cuda.empty_cache()
+ return logits
+ finally:
+ _RECORDING_LOCK.release()
+
+ def clear(self) -> None:
+ """Drop every graph and its memory."""
+ with self._lock:
+ self._graphs.clear()
+ self._sightings.clear()
+ self._relative_pos.clear()
+ self._device_bytes = 0
+
+ @property
+ def graph_count(self) -> int:
+ return len(self._graphs)
+
+ @property
+ def disabled(self) -> bool:
+ return self._disabled
+
+ # -- recording and replay ---------------------------------------------
+
+ @staticmethod
+ def _has_headroom(device: torch.device) -> bool:
+ """Whether enough device memory is free to record without starving other models."""
+ free, total = torch.cuda.mem_get_info(device)
+ return free >= _RECORDING_HEADROOM * total
+
+ @staticmethod
+ def _memory_budget(device: torch.device) -> int:
+ """Device memory this runner's recordings may take before its graphs are dropped."""
+ return int(_MEMORY_BUDGET_SHARE * torch.cuda.mem_get_info(device)[1])
+
+ @staticmethod
+ def _free_memory(device: torch.device) -> int:
+ return torch.cuda.mem_get_info(device)[0]
+
+ def _tensor_bytes(self) -> int:
+ """Device memory of the tensors the graphs keep: tables, static inputs and outputs."""
+ tables = sum(table.nbytes for table in self._relative_pos.values())
+ buffers = sum(
+ sum(tensor.nbytes for tensor in entry.inputs.values()) + entry.output.nbytes
+ for entry in self._graphs.values()
+ )
+ return tables + buffers
+
+ def _drop_unused_tables(self) -> None:
+ lengths = {length for _, length, _ in self._graphs}
+ for length in [length for length in self._relative_pos if length not in lengths]:
+ del self._relative_pos[length]
+
+ def _static_inputs(self, key: Key, inputs: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
+ batch, length, _ = key
+ static: dict[str, torch.Tensor] = {}
+ for name, value in inputs.items():
+ buffer = torch.full((batch, length), self._pad_values[name], dtype=value.dtype, device=value.device)
+ buffer[:, : value.shape[1]].copy_(value)
+ static[name] = buffer
+ return static
+
+ def _record(self, key: Key, inputs: dict[str, torch.Tensor]) -> tuple[_Graph, torch.Tensor]:
+ """Record the graph for ``key``; return it and this forward's logits.
+
+ This call is answered by an eager forward on the current stream, as
+ eager execution answers it; a replay of the new graph returns the same
+ values. Its activations go back to the cache that eager forwards
+ reuse. Recording runs on a stream of the runner's own, whose first use
+ creates per-stream state (the cuBLAS handle and workspace) that cannot
+ be created while recording: the first recording warms that stream up
+ with one row of its inputs, the only memory left cached on it.
+
+ Raises:
+ _RecordingError: With the eager logits, when anything after the
+ eager forward fails: the table, the warm-up or the recording.
+ """
+ classes = key[2]
+ static = self._static_inputs(key, inputs)
+ device = static["input_ids"].device
+ current = torch.cuda.current_stream(device)
+ with torch.inference_mode():
+ logits = self._model(**static, max_num_classes=classes).logits.clone()
+ try:
+ return self._capture(key, static, current), logits
+ except Exception as exc:
+ raise _RecordingError(exc, logits) from exc
+
+ def _capture(self, key: Key, static: dict[str, torch.Tensor], current: torch.cuda.Stream) -> _Graph:
+ _, padded_length, classes = key
+ device = static["input_ids"].device
+ relative_pos = self._relative_pos.get(padded_length)
+ if relative_pos is None:
+ with torch.inference_mode():
+ # Built eagerly, outside the recording: its CPU-to-GPU copy cannot be recorded.
+ relative_pos = self._build_relative_pos(torch.empty((1, padded_length, 1), device=device))
+ if relative_pos is not None:
+ self._relative_pos[padded_length] = relative_pos
+ warm_up = self._stream is None
+ stream = self._stream or torch.cuda.Stream(device=device)
+ pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else None
+ graph = torch.cuda.CUDAGraph()
+ stream.wait_stream(current)
+ self._recording_relative_pos = relative_pos
+ self._recording = True
+ try:
+ with torch.inference_mode(), torch.cuda.stream(stream):
+ if warm_up:
+ self._model(**{name: value[:1] for name, value in static.items()}, max_num_classes=classes)
+ # Kept only once warmed up, so a failed warm-up is tried again.
+ self._stream = stream
+ free_before = self._free_memory(device)
+ graph.capture_begin(pool=pool, capture_error_mode="thread_local")
+ try:
+ output = self._model(**static, max_num_classes=classes).logits
+ 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:
+ self._recording = False
+ self._recording_relative_pos = None
+ current.wait_stream(stream)
+ return _Graph(graph=graph, inputs=static, output=output, device_bytes=device_bytes)
+
+ def _replay(self, entry: _Graph, inputs: dict[str, torch.Tensor], length: int) -> torch.Tensor:
+ for name, value in inputs.items():
+ buffer = entry.inputs[name]
+ buffer[:, :length].copy_(value)
+ if length < buffer.shape[1]:
+ buffer[:, length:].fill_(self._pad_values[name])
+ entry.graph.replay()
+ return entry.output.clone()
+
+
+def segment_ids(input_ids: torch.Tensor, config: Any) -> torch.Tensor:
+ """The segment ids of gliclass ``_create_segment_ids``, without host reads.
+
+ gliclass marks the text from its first text token with 1 and, when a row
+ has an example token, everything from ``argmin`` of the example mask with
+ 2 (``argmin`` finds the first position that is not an example token,
+ usually 0). This reproduces that exactly with tensor operations.
+ """
+ example_mask = input_ids == config.example_token_index
+ example_start = example_mask.int().argmin(dim=-1)
+ has_example = example_mask.any(dim=-1)
+ text_start = (input_ids == config.text_token_index).int().argmax(dim=-1)
+ positions = torch.arange(input_ids.shape[1], device=input_ids.device).unsqueeze(0)
+ text = (positions >= text_start[:, None]).to(input_ids.dtype)
+ with_examples = torch.where(positions >= example_start[:, None], torch.full_like(text, 2), text)
+ return torch.where(has_example[:, None], with_examples, text)
diff --git a/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py
new file mode 100644
index 000000000..43018d303
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py
@@ -0,0 +1,544 @@
+"""GLiClass CUDA graph policy: which forwards 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 are checked against eager scores in test_gliclass_parity.py
+(``gpu_hw``).
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+import torch
+import yaml
+from gliclass.model import GLiClassUniEncoder
+from sie_server.adapters.gliclass import GLiClassAdapter
+from sie_server.adapters.gliclass import cuda_graphs as cuda_graphs_module
+from sie_server.adapters.gliclass.cuda_graphs import (
+ CudaGraphRunner,
+ bucket_width,
+ segment_ids,
+ unsupported_reason,
+)
+from sie_server.core.loader import reject_unknown_loadtime_options
+from sie_server.types.inputs import InvalidInputError
+
+
+class _Encoder:
+ 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 _model(
+ *,
+ encoder_type: str = "deberta-v2",
+ architecture: str = "uni-encoder",
+ pooling: str = "first",
+ segment_embeddings: bool = False,
+) -> Any:
+ config = SimpleNamespace(
+ architecture_type=architecture,
+ encoder_config=SimpleNamespace(model_type=encoder_type),
+ pooling_strategy=pooling,
+ use_lstm=False,
+ use_segment_embeddings=segment_embeddings,
+ example_token_index=9,
+ text_token_index=8,
+ )
+ inner = SimpleNamespace(encoder_model=SimpleNamespace(encoder=_Encoder()), _create_segment_ids=lambda ids: "eager")
+ return SimpleNamespace(config=config, model=inner)
+
+
+class _Runner(CudaGraphRunner):
+ """Records and replays with fakes: logits say which path produced them.
+
+ Recording answers with zeros, a replay with ones, and a recording whose
+ capture fails (``capture_error``) with the eager answer, twos. ``fail``
+ makes the eager forward of a recording fail instead.
+
+ Time stands still unless a test moves ``now``; the device always has
+ memory to spare unless a test clears ``headroom`` or sets a ``budget``.
+ """
+
+ def __init__(self, model: Any = None, *, fail: bool | Exception = False, **kwargs: Any) -> None:
+ self.now = 0.0
+ super().__init__(model or _model(), pad_token_id=0, max_length=512, clock=lambda: self.now, **kwargs)
+ self.recorded: list[tuple[int, int, int]] = []
+ self.replayed: list[tuple[int, int, int]] = []
+ self.fail = fail
+ self.capture_error: Exception | None = None
+ self.headroom = True
+ self.budget = 2**40
+ self.bytes_per_graph = 0
+ self.replay_error: Exception | None = None
+
+ 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, inputs: dict[str, torch.Tensor]) -> Any:
+ if isinstance(self.fail, Exception):
+ raise self.fail
+ if self.fail:
+ raise RuntimeError("the eager forward failed")
+ if self.capture_error is not None:
+ raise cuda_graphs_module._RecordingError(self.capture_error, torch.full((key[0], key[2]), 2.0))
+ self.recorded.append(key)
+ self._relative_pos.setdefault(key[1], torch.zeros(1))
+ entry = SimpleNamespace(key=key, device_bytes=self.bytes_per_graph, inputs={}, output=torch.zeros(0))
+ return entry, torch.zeros(key[0], key[2])
+
+ def _replay(self, entry: Any, inputs: dict[str, torch.Tensor], length: int) -> torch.Tensor:
+ if self.replay_error is not None:
+ raise self.replay_error
+ self.replayed.append(entry.key)
+ return torch.ones(entry.key[0], entry.key[2])
+
+
+def _inputs(batch: int, length: int) -> dict[str, torch.Tensor]:
+ return {
+ "input_ids": torch.ones(batch, length, dtype=torch.long),
+ "attention_mask": torch.ones(batch, length, dtype=torch.long),
+ }
+
+
+class TestSupport:
+ def test_deberta_uni_encoders_on_cuda_are_supported(self) -> None:
+ assert unsupported_reason(_model(), "cuda:0") is None
+
+ @pytest.mark.parametrize(
+ ("model", "device", "reason"),
+ [
+ (_model(), "cpu", "CUDA device"),
+ (_model(), "mps", "CUDA device"),
+ (_model(encoder_type="modernbert"), "cuda:0", "modernbert encoder"),
+ (_model(architecture="bi-encoder"), "cuda:0", "uni-encoder"),
+ ],
+ )
+ def test_other_models_and_devices_run_eagerly(self, model: Any, device: str, reason: str) -> None:
+ message = unsupported_reason(model, device)
+ assert message is not None
+ assert reason in message
+
+
+class TestShapes:
+ @pytest.mark.parametrize(("max_length", "width"), [(512, 32), (1024, 64), (128, 16)])
+ def test_bucket_width_follows_the_window(self, max_length: int, width: int) -> None:
+ assert bucket_width(max_length) == width
+
+ @pytest.mark.parametrize(("length", "bucketed"), [(1, 32), (32, 32), (33, 64), (500, 512), (512, 512)])
+ def test_bucketed_lengths_round_up_to_the_bucket(self, length: int, bucketed: int) -> None:
+ runner = _Runner()
+
+ assert runner.key(1, length, 8, "bucketed") == (1, bucketed, 8)
+ assert runner.key(1, length, 8, "exact") == (1, length, 8)
+
+ def test_shapes_past_2048_tokens_run_eagerly(self) -> None:
+ runner = _Runner()
+
+ assert runner.key(4, 512, 4, "exact") == (4, 512, 4)
+ assert runner.key(5, 512, 4, "exact") is None
+ assert runner.key(64, 32, 4, "bucketed") == (64, 32, 4)
+ assert runner.key(65, 32, 4, "bucketed") is None
+ assert runner.key(5, 380, 8, "bucketed") == (5, 384, 8)
+ assert runner.key(5, 400, 8, "bucketed") is None # 5 x 416 tokens
+
+ def test_the_token_bound_does_not_grow_with_the_window(self) -> None:
+ runner = CudaGraphRunner(_model(), pad_token_id=0, max_length=1024)
+
+ assert runner.key(2, 1024, 4, "exact") == (2, 1024, 4)
+ assert runner.key(3, 1024, 4, "exact") is None
+ assert runner.key(3, 600, 4, "bucketed") == (3, 640, 4) # 64-token buckets
+
+ @pytest.mark.parametrize("pooling", ["avg", "last", "max"])
+ def test_poolings_that_read_padding_keep_exact_lengths(self, pooling: str) -> None:
+ runner = _Runner(_model(pooling=pooling))
+
+ assert runner.key(1, 100, 4, "bucketed") == (1, 100, 4)
+
+
+class TestRecordingPolicy:
+ def test_off_never_records(self) -> None:
+ runner = _Runner()
+
+ assert runner.run(_inputs(1, 100), 4, "off") is None
+ assert runner.recorded == []
+
+ def test_exact_mode_records_a_shape_the_second_time_it_is_seen(self) -> None:
+ runner = _Runner()
+
+ first = runner.run(_inputs(1, 100), 4, "exact")
+ second = runner.run(_inputs(1, 100), 4, "exact")
+ third = runner.run(_inputs(1, 100), 4, "exact")
+
+ assert first is None # eager
+ assert second is not None
+ assert torch.equal(second, torch.zeros(1, 4)) # the recording forward answers
+ assert third is not None
+ assert torch.equal(third, torch.ones(1, 4)) # a replay
+ assert runner.recorded == [(1, 100, 4)]
+ assert runner.replayed == [(1, 100, 4)]
+
+ def test_bucketed_mode_records_once_per_bucket(self) -> None:
+ runner = _Runner()
+
+ runner.run(_inputs(1, 100), 4, "bucketed")
+ runner.run(_inputs(1, 110), 4, "bucketed")
+ runner.run(_inputs(1, 128), 4, "bucketed")
+ runner.run(_inputs(1, 129), 4, "bucketed")
+
+ assert runner.recorded == [(1, 128, 4), (1, 160, 4)]
+ assert runner.replayed == [(1, 128, 4), (1, 128, 4)]
+
+ def test_batch_size_and_class_slots_are_part_of_the_shape(self) -> None:
+ runner = _Runner()
+
+ for batch, classes in ((1, 4), (2, 4), (1, 8)):
+ runner.run(_inputs(batch, 100), classes, "bucketed")
+
+ assert runner.recorded == [(1, 128, 4), (2, 128, 4), (1, 128, 8)]
+
+ def test_the_least_recently_used_graph_is_dropped_past_the_bound(self) -> None:
+ runner = _Runner(max_graphs=2)
+
+ runner.run(_inputs(1, 32), 4, "bucketed")
+ runner.run(_inputs(1, 64), 4, "bucketed")
+ runner.run(_inputs(1, 32), 4, "bucketed") # 32 is now the most recent
+ runner.run(_inputs(1, 96), 4, "bucketed") # drops 64
+ runner.run(_inputs(1, 64), 4, "bucketed") # recorded again
+
+ assert runner.graph_count == 2
+ assert runner.recorded == [(1, 32, 4), (1, 64, 4), (1, 96, 4), (1, 64, 4)]
+ # A length's relative-position table lives as long as a graph of that length.
+ assert set(runner._relative_pos) == {64, 96}
+
+ def test_recording_is_rationed_in_time(self) -> None:
+ runner = _Runner(max_graphs=1000)
+ shapes = iter(range(2, 10_000))
+
+ # Every call is a new shape: sixteen record at once, then none while time stands still.
+ answers = [runner.run(_inputs(1, 100), next(shapes), "bucketed") for _ in range(80)]
+ assert len(runner.recorded) == 16
+ assert answers.count(None) == 64 # the rest ran eagerly
+
+ runner.now += 2.0 # one more recording every 2 seconds
+ for _ in range(10):
+ runner.run(_inputs(1, 100), next(shapes), "bucketed")
+ assert len(runner.recorded) == 17
+
+ runner.now += 3600.0 # an idle hour refills only the burst
+ for _ in range(40):
+ runner.run(_inputs(1, 100), next(shapes), "bucketed")
+ assert len(runner.recorded) == 33
+
+ def test_repeating_each_shape_does_not_buy_recordings(self) -> None:
+ runner = _Runner()
+
+ # Each new shape sent twice, one forward per 10 ms for 80 seconds.
+ for classes in range(2, 4002):
+ for _ in range(2):
+ runner.run(_inputs(1, 100), classes, "bucketed")
+ runner.now += 0.01
+
+ # The burst, then one per 2 seconds of the 80.
+ assert 16 + 80 / 2 - 1 <= len(runner.recorded) <= 16 + 80 / 2
+
+ def test_one_recording_at_a_time_in_the_process(self) -> None:
+ runner = _Runner()
+
+ assert cuda_graphs_module._RECORDING_LOCK.acquire(blocking=False) # another model is recording
+ try:
+ assert runner.run(_inputs(1, 100), 4, "bucketed") is None
+ finally:
+ cuda_graphs_module._RECORDING_LOCK.release()
+ assert runner.recorded == []
+ assert runner.run(_inputs(1, 100), 4, "bucketed") is not None
+ assert runner.recorded == [(1, 128, 4)]
+ assert not cuda_graphs_module._RECORDING_LOCK.locked()
+
+ def test_graphs_are_dropped_when_their_memory_passes_the_budget(self) -> None:
+ runner = _Runner()
+ runner.budget, runner.bytes_per_graph = 250, 100
+
+ runner.run(_inputs(1, 32), 4, "bucketed")
+ runner.run(_inputs(1, 64), 4, "bucketed")
+ assert runner.graph_count == 2
+ runner.run(_inputs(1, 96), 4, "bucketed") # 300 bytes: over the budget
+
+ assert runner.graph_count == 0
+ assert runner._relative_pos == {}
+ assert not runner.disabled
+ runner.run(_inputs(1, 32), 4, "bucketed") # records again from nothing
+ assert runner.recorded[-1] == (1, 32, 4)
+ assert runner.graph_count == 1
+
+ def test_the_budget_counts_the_tensors_graphs_keep(self) -> None:
+ runner = _Runner()
+ runner.budget = 999
+ runner._relative_pos[32] = torch.zeros(1000, dtype=torch.uint8) # a 1,000-byte table
+
+ runner.run(_inputs(1, 32), 4, "bucketed") # nothing recorded counts, but the table does
+
+ assert runner.graph_count == 0
+
+ def test_evicting_graphs_does_not_give_their_memory_back(self) -> None:
+ # Evicted graphs leave their share of the shared pool behind, so their
+ # memory still counts until the graphs are dropped.
+ runner = _Runner(max_graphs=1)
+ runner.budget, runner.bytes_per_graph = 250, 100
+
+ runner.run(_inputs(1, 32), 4, "bucketed")
+ runner.run(_inputs(1, 64), 4, "bucketed")
+ assert runner.graph_count == 1
+ runner.run(_inputs(1, 96), 4, "bucketed")
+
+ assert runner.graph_count == 0
+
+ def test_no_recording_while_device_memory_is_short(self) -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 4, "bucketed")
+ runner.headroom = False
+
+ assert runner.run(_inputs(1, 200), 4, "bucketed") is None # would record: runs eagerly
+ assert runner.run(_inputs(1, 100), 4, "bucketed") is not None # replays still run
+ assert runner.recorded == [(1, 128, 4)]
+ assert runner.replayed == [(1, 128, 4)]
+
+ def test_a_recording_failure_turns_graphs_off_and_keeps_the_eager_answer(self) -> None:
+ runner = _Runner()
+ runner.capture_error = RuntimeError("operation not permitted when stream is capturing")
+
+ answer = runner.run(_inputs(1, 100), 4, "bucketed")
+
+ assert answer is not None
+ assert torch.equal(answer, torch.full((1, 4), 2.0)) # the eager answer
+ assert runner.disabled
+ assert not cuda_graphs_module._RECORDING_LOCK.locked()
+ runner.capture_error = None
+ assert runner.run(_inputs(1, 100), 4, "bucketed") is None
+ assert runner.recorded == []
+
+ def test_an_eager_forward_that_fails_while_recording_turns_graphs_off(self) -> None:
+ runner = _Runner(fail=True)
+
+ assert runner.run(_inputs(1, 100), 4, "bucketed") is None # the adapter runs it eagerly
+ assert runner.disabled
+ assert not cuda_graphs_module._RECORDING_LOCK.locked()
+
+ def test_running_out_of_memory_while_capturing_keeps_the_eager_answer_and_pauses(self) -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 4, "bucketed")
+ runner.capture_error = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ answer = runner.run(_inputs(1, 200), 4, "bucketed")
+
+ assert answer is not None
+ assert torch.equal(answer, torch.full((1, 4), 2.0)) # the eager answer, not an error
+ assert runner.graph_count == 0
+ assert not runner.disabled
+ assert not cuda_graphs_module._RECORDING_LOCK.locked()
+ # Recording pauses for a minute, then resumes.
+ runner.capture_error = None
+ runner.now += 59.0
+ assert runner.run(_inputs(1, 300), 4, "bucketed") is None
+ runner.now += 2.0
+ assert runner.run(_inputs(1, 300), 4, "bucketed") is not None
+ assert runner.recorded[-1] == (1, 320, 4)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ torch.cuda.OutOfMemoryError("CUDA out of memory"),
+ RuntimeError("CUDA error: out of memory"),
+ RuntimeError("CUBLAS_STATUS_ALLOC_FAILED: failed to allocate workspace"),
+ ],
+ )
+ def test_an_eager_forward_out_of_memory_while_recording_drops_the_graphs_and_raises(self, error: Exception) -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 4, "bucketed")
+ runner.fail = error
+
+ with pytest.raises(type(error)):
+ runner.run(_inputs(1, 200), 4, "bucketed")
+
+ assert runner.graph_count == 0
+ assert not runner.disabled # memory pressure is not a reason to stop recording
+ assert not cuda_graphs_module._RECORDING_LOCK.locked()
+
+ def test_unexpected_inputs_run_eagerly(self) -> None:
+ runner = _Runner()
+ inputs = {**_inputs(1, 100), "class_input_ids": torch.ones(1, 4, dtype=torch.long)}
+
+ assert runner.run(inputs, 4, "bucketed") is None
+ assert runner.recorded == []
+
+
+class TestRecordingHooks:
+ def test_hooks_leave_eager_forwards_alone(self) -> None:
+ model = _model(segment_embeddings=True)
+ _Runner(model)
+ encoder = model.model.encoder_model.encoder
+ hidden = torch.zeros(1, 7, 4)
+
+ assert encoder.get_rel_pos(hidden) == ("built", 7)
+ assert model.model._create_segment_ids(torch.ones(1, 3, dtype=torch.long)) == "eager"
+
+ def test_while_recording_the_encoder_gets_the_precomputed_table(self) -> None:
+ model = _model(segment_embeddings=True)
+ runner = _Runner(model)
+ encoder = model.model.encoder_model.encoder
+ table = torch.arange(4)
+ runner._recording, runner._recording_relative_pos = True, table
+
+ assert encoder.get_rel_pos(torch.zeros(1, 7, 4)) is table
+ assert encoder.get_rel_pos(torch.zeros(1, 7, 4), None, "given") == ("built", 7)
+ ids = torch.tensor([[0, 8, 5, 5, 2]])
+ assert torch.equal(model.model._create_segment_ids(ids), torch.tensor([[0, 1, 1, 1, 1]]))
+
+
+ "rows",
+ [
+ [[0, 5, 8, 5, 5, 2]], # text token, no examples
+ [[0, 5, 8, 5, 9, 5, 2]], # text then an example
+ [[0, 9, 9, 8, 5, 2]], # examples first
+ [[0, 5, 5, 5, 5, 2]], # neither
+ [[0, 8, 5, 9, 5, 2], [0, 5, 5, 8, 5, 2]], # rows differ
+ ],
+)
+def test_segment_ids_are_the_libraries_own(rows: list[list[int]]) -> None:
+ config = SimpleNamespace(example_token_index=9, text_token_index=8)
+ input_ids = torch.tensor(rows)
+
+ expected = GLiClassUniEncoder._create_segment_ids(SimpleNamespace(config=config), input_ids) # ty:ignore[invalid-argument-type]
+
+ assert torch.equal(segment_ids(input_ids, config), expected)
+
+
+class _Pipe:
+ def __init__(self, error: Exception | None = None) -> None:
+ self.error = error or torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ def _resolve_max_num_classes(self, labels: list[str], same_labels: bool) -> int:
+ return len(labels)
+
+ def model(self, **_: Any) -> Any:
+ raise self.error
+
+
+def _adapter_with(runner: _Runner) -> GLiClassAdapter:
+ adapter = GLiClassAdapter("tiny", max_seq_length=512, cuda_graphs="bucketed")
+ adapter._graphs = runner
+ return adapter
+
+
+def test_an_eager_out_of_memory_drops_the_graphs() -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 2, "bucketed")
+ assert runner.graph_count == 1
+ runner._recording_credit = 0.0 # the next shape is not recorded and runs eagerly
+
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ _adapter_with(runner)._forward(_Pipe(), _inputs(1, 300), ["a", "b"], same_labels=True, graphs="bucketed")
+
+ assert runner.graph_count == 0
+ assert runner.recorded == [(1, 128, 2)]
+ assert not runner.disabled
+
+
+def test_an_eager_error_worded_as_out_of_memory_drops_the_graphs() -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 2, "bucketed")
+ pipe = _Pipe(RuntimeError("CUDA error: out of memory"))
+
+ with pytest.raises(RuntimeError):
+ _adapter_with(runner)._forward(pipe, _inputs(1, 100), ["a", "b"], same_labels=True, graphs="off")
+
+ assert runner.graph_count == 0
+
+
+def test_other_eager_errors_keep_the_graphs() -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 2, "bucketed")
+ pipe = _Pipe(ValueError("bad input"))
+
+ with pytest.raises(ValueError, match="bad input"):
+ _adapter_with(runner)._forward(pipe, _inputs(1, 100), ["a", "b"], same_labels=True, graphs="off")
+
+ assert runner.graph_count == 1
+
+
+def test_a_capture_out_of_memory_answers_eagerly_without_oom_recovery() -> None:
+ runner = _Runner()
+ runner.capture_error = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ # The fake pipe's own forward would raise: the answer must come from the recording.
+ logits = _adapter_with(runner)._forward(_Pipe(), _inputs(1, 100), ["a", "b"], same_labels=True, graphs="bucketed")
+
+ assert torch.equal(logits, torch.full((1, 2), 2.0))
+ assert runner.graph_count == 0
+ assert not runner.disabled
+
+
+def test_an_out_of_memory_error_in_a_replay_drops_the_graphs() -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 2, "bucketed")
+ runner.replay_error = torch.cuda.OutOfMemoryError("CUDA out of memory")
+
+ with pytest.raises(torch.cuda.OutOfMemoryError):
+ _adapter_with(runner)._forward(_Pipe(), _inputs(1, 100), ["a", "b"], same_labels=True, graphs="bucketed")
+
+ assert runner.graph_count == 0
+
+
+class TestOperatorSetting:
+ """Graphs are chosen when the model loads; a request can only opt out."""
+
+ @pytest.mark.parametrize("mode", ["off", "exact", "bucketed"])
+ def test_requests_use_the_load_time_mode(self, mode: str) -> None:
+ adapter = GLiClassAdapter("tiny", cuda_graphs=mode)
+
+ assert adapter._request_cuda_graphs({}) == mode
+ assert adapter._request_cuda_graphs({"cuda_graphs": "off"}) == "off"
+
+ def test_a_request_may_send_false_for_off(self) -> None:
+ # A profile's runtime options read an unquoted YAML ``off`` as False.
+ assert GLiClassAdapter("tiny", cuda_graphs="bucketed")._request_cuda_graphs({"cuda_graphs": False}) == "off"
+
+ @pytest.mark.parametrize("value", ["exact", "bucketed", "on", "Off", True, None, 0, 1])
+ def test_a_request_can_only_turn_graphs_off(self, value: object) -> None:
+ adapter = GLiClassAdapter("tiny", cuda_graphs="bucketed")
+
+ with pytest.raises(InvalidInputError, match="accepts only 'off'"):
+ adapter._request_cuda_graphs({"cuda_graphs": value})
+
+ @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 GLiClassAdapter("tiny", **loadtime)._cuda_graphs == mode
+
+ @pytest.mark.parametrize("value", ["on", "Exact", "", None, True, 0])
+ def test_unknown_load_time_modes_fail_the_load(self, value: Any) -> None:
+ with pytest.raises(ValueError, match="cuda_graphs must be 'off', 'exact' or 'bucketed'"):
+ GLiClassAdapter("tiny", cuda_graphs=value)
+
+ def test_profiles_may_set_it_at_load(self) -> None:
+ reject_unknown_loadtime_options(GLiClassAdapter, {"cuda_graphs": "bucketed"}, model_name="tiny")
+
+ def test_a_request_that_opts_out_runs_eagerly(self) -> None:
+ runner = _Runner()
+ runner.run(_inputs(1, 100), 2, "bucketed")
+
+ with pytest.raises(torch.cuda.OutOfMemoryError): # the fake pipe's eager forward
+ _adapter_with(runner)._forward(_Pipe(), _inputs(1, 100), ["a", "b"], same_labels=True, graphs="off")
+
+ assert runner.replayed == []
diff --git a/packages/sie_server/tests/adapters/test_gliclass_parity.py b/packages/sie_server/tests/adapters/test_gliclass_parity.py
index 66c8d4464..46664b53b 100644
--- a/packages/sie_server/tests/adapters/test_gliclass_parity.py
+++ b/packages/sie_server/tests/adapters/test_gliclass_parity.py
@@ -16,7 +16,7 @@ import pytest
import torch
from gliclass import GLiClassModel, GLiClassModelConfig, ZeroShotClassificationPipeline
from sie_server.adapters.gliclass import GLiClassAdapter
-from sie_server.types.inputs import Item
+from sie_server.types.inputs import InvalidInputError, Item
from tokenizers import Tokenizer, models, pre_tokenizers, processors
from transformers import DebertaV2Config, PreTrainedTokenizerFast
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
@@ -97,21 +97,29 @@ def _model(tokenizer: PreTrainedTokenizerFast, *, prompt_first: bool, scorer: st
class _Rig:
"""A tiny GLiClass model behind both the gliclass pipelines and the adapter."""
- def __init__(self, *, prompt_first: bool, scorer: str) -> None:
+ def __init__(
+ self,
+ *,
+ prompt_first: bool,
+ scorer: str,
+ device: str = "cpu",
+ dtype: torch.dtype = torch.float32,
+ cuda_graphs: str = "off",
+ ) -> None:
tokenizer = _tokenizer()
- model = _model(tokenizer, prompt_first=prompt_first, scorer=scorer)
+ model = _model(tokenizer, prompt_first=prompt_first, scorer=scorer).to(device, dtype=dtype)
self.pipelines = {
classification_type: ZeroShotClassificationPipeline(
model,
tokenizer,
max_length=_MAX_LENGTH,
classification_type=classification_type,
- device="cpu",
+ device=device,
progress_bar=False,
)
for classification_type in ("single-label", "multi-label")
}
- self.adapter = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH)
+ self.adapter = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH, cuda_graphs=cuda_graphs)
self.adapter._attach(self.pipelines["single-label"].pipe, tokenizer)
def pipeline_scores(
@@ -352,3 +360,231 @@ def test_a_document_that_cannot_be_cut_costs_what_reading_it_whole_does(
# document is then tokenized once for every check and for metering.
search_bound = 2 * 64 * (_MAX_LENGTH - 2 + 8)
assert with_search <= sum(seen) + search_bound
+
+
+_GRAPH_REQUESTS = [
+ {"labels": _LABELS},
+ {"labels": _LABELS, "instruction": _INSTRUCTION, "options": {"classification_type": "multi-label"}},
+ {"options": {"label_groups": _GROUPS, "group_encoding": "joint"}},
+ {"options": {"label_groups": _GROUPS}},
+]
+_GRAPH_REQUEST_IDS = ["labels", "labels-context", "joint", "separate"]
+
+
+_LAYOUTS = {"params": [(False, "simple"), (True, "mlp")], "ids": ["text-first", "labels-first"]}
+
+
+def _cuda_rig(request: pytest.FixtureRequest, mode: str) -> _Rig:
+ if not torch.cuda.is_available():
+ pytest.skip("requires CUDA")
+ prompt_first, scorer = request.param
+ return _Rig(prompt_first=prompt_first, scorer=scorer, device="cuda:0", dtype=torch.float16, cuda_graphs=mode)
+
+
[email protected](scope="module", **_LAYOUTS)
+def exact_rig(request: pytest.FixtureRequest) -> _Rig:
+ return _cuda_rig(request, "exact")
+
+
[email protected](scope="module", **_LAYOUTS)
+def bucketed_rig(request: pytest.FixtureRequest) -> _Rig:
+ return _cuda_rig(request, "bucketed")
+
+
+def _fresh_runner(rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> Any:
+ """The rig's graph runner, emptied, with a full recording burst, counting replays."""
+ runner = rig.adapter._graphs
+ assert runner is not None
+ runner.clear()
+ runner._recording_credit = 16.0
+ runner.replayed = []
+ replay = runner._replay
+
+ def counted(entry: Any, inputs: dict[str, torch.Tensor], length: int) -> torch.Tensor:
+ runner.replayed.append(length)
+ return replay(entry, inputs, length)
+
+ monkeypatch.setattr(runner, "_replay", counted)
+ return runner
+
+
+_EAGER = {"cuda_graphs": "off"}
+
+
+def _eager_request(request_kwargs: dict[str, Any]) -> dict[str, Any]:
+ return {**request_kwargs, "options": {**request_kwargs.get("options", {}), **_EAGER}}
+
+
[email protected]("request_kwargs", _GRAPH_REQUESTS, ids=_GRAPH_REQUEST_IDS)
+def test_exact_cuda_graphs_score_bit_for_bit_like_eager(
+ exact_rig: _Rig, request_kwargs: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # Eleven texts of different lengths, sent three times: a shape is recorded
+ # the second time it is seen and replayed the third.
+ items = [Item(text=text) for text in _TEXTS]
+ runner = _fresh_runner(exact_rig, monkeypatch)
+
+ eager = _outputs(exact_rig.adapter.extract(items, **_eager_request(request_kwargs)))
+ for _ in range(3):
+ assert _outputs(exact_rig.adapter.extract(items, **request_kwargs)) == eager
+
+ assert runner.graph_count > 0
+ assert runner.replayed # the third pass replayed
+ assert not runner.disabled
+ # Graphs of one length share its relative-position table.
+ assert set(runner._relative_pos) == {length for _, length, _ in runner._graphs}
+
+
[email protected]("request_kwargs", _GRAPH_REQUESTS, ids=_GRAPH_REQUEST_IDS)
+def test_bucketed_cuda_graphs_stay_close_to_eager(
+ bucketed_rig: _Rig, request_kwargs: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [Item(text=text) for text in _TEXTS]
+ runner = _fresh_runner(bucketed_rig, monkeypatch)
+
+ eager = bucketed_rig.adapter.extract(items, **_eager_request(request_kwargs))
+ for _ in range(2):
+ graphed = bucketed_rig.adapter.extract(items, **request_kwargs)
+ if eager.data:
+ pairs = [
+ (a["probabilities"], b["probabilities"])
+ for row_a, row_b in zip(eager.data, graphed.data or [], strict=True)
+ for a, b in zip(row_a.values(), row_b.values(), strict=True)
+ ]
+ else:
+ pairs = list(zip(_scores(eager), _scores(graphed), strict=True))
+ for expected, got in pairs:
+ assert got == pytest.approx(expected, abs=2e-2)
+ assert graphed.input_token_counts == eager.input_token_counts
+ assert runner.graph_count > 0
+ assert runner.replayed # the second pass replayed
+ assert not runner.disabled
+
+
+def test_graphs_over_their_memory_budget_are_dropped(exact_rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> None:
+ items = [Item(text=text) for text in _TEXTS]
+ runner = _fresh_runner(exact_rig, monkeypatch)
+ monkeypatch.setattr(runner, "_memory_budget", lambda device: 0) # every recording goes over
+
+ eager = _outputs(exact_rig.adapter.extract(items, labels=_LABELS, options=_EAGER))
+ torch.cuda.synchronize()
+ reserved = torch.cuda.memory_reserved()
+ for _ in range(3):
+ assert _outputs(exact_rig.adapter.extract(items, labels=_LABELS)) == eager
+
+ assert runner.graph_count == 0
+ assert not runner.disabled
+ assert runner._device_bytes == 0
+ # The dropped graphs' pool went back to the device.
+ assert torch.cuda.memory_reserved() <= reserved
+
+
+class _OutOfMemoryGraph:
+ """A CUDA graph whose recording runs out of memory."""
+
+ def capture_begin(self, **_: Any) -> None:
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory while recording")
+
+ def capture_end(self) -> None:
+ pass
+
+
+def test_running_out_of_memory_while_recording_answers_eagerly(
+ exact_rig: _Rig, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [Item(text=text) for text in _TEXTS]
+ runner = _fresh_runner(exact_rig, monkeypatch)
+ eager = _outputs(exact_rig.adapter.extract(items, labels=_LABELS, options=_EAGER))
+ monkeypatch.setattr(torch.cuda, "CUDAGraph", _OutOfMemoryGraph)
+
+ # The second sighting records; the recording fails, and the call still gets its answer.
+ for _ in range(2):
+ assert _outputs(exact_rig.adapter.extract(items, labels=_LABELS)) == eager
+
+ assert runner.graph_count == 0
+ assert not runner.disabled
+ assert runner._recording_credit < 1 # paused
+
+
+def test_a_warm_up_that_runs_out_of_memory_is_tried_again(exact_rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> None:
+ items = [Item(text=text) for text in _TEXTS[:3]]
+ runner = _fresh_runner(exact_rig, monkeypatch)
+ runner._stream = None # the next recording creates and warms up its stream
+ model = runner._model
+ failures = []
+
+ def warm_up_fails_once(**inputs: Any) -> Any:
+ # The warm-up is the only one-row forward of a three-item request.
+ if inputs["input_ids"].shape[0] == 1 and not failures:
+ failures.append(True)
+ raise torch.cuda.OutOfMemoryError("CUDA out of memory during warm-up")
+ return model(**inputs)
+
+ monkeypatch.setattr(runner, "_model", warm_up_fails_once)
+ eager = _outputs(exact_rig.adapter.extract(items, labels=_LABELS, options=_EAGER))
+ for _ in range(2): # the second sighting records; its warm-up fails
+ assert _outputs(exact_rig.adapter.extract(items, labels=_LABELS)) == eager
+ assert failures
+ assert runner._stream is None
+ assert not runner.disabled
+
+ runner._recording_credit = 16.0 # skip the pause
+ # Dropping the graphs reset the sightings: seen, then warmed up and recorded, then replayed.
+ for _ in range(3):
+ assert _outputs(exact_rig.adapter.extract(items, labels=_LABELS)) == eager
+ assert runner._stream is not None
+ assert runner.graph_count > 0
+ assert runner.replayed
+ assert not runner.disabled
+
+
+def test_a_forward_that_cannot_be_recorded_falls_back_to_eager(monkeypatch: pytest.MonkeyPatch) -> None:
+ if not torch.cuda.is_available():
+ pytest.skip("requires CUDA")
+ rig = _Rig(prompt_first=True, scorer="mlp", device="cuda:0", dtype=torch.float16, cuda_graphs="bucketed")
+ items = [Item(text=text) for text in _TEXTS[:3]]
+ eager = _outputs(rig.adapter.extract(items, labels=_LABELS, options=_EAGER))
+ runner = rig.adapter._graphs
+ assert runner is not None
+ # Without the precomputed table, DeBERTa copies a CPU scalar to the GPU
+ # while recording, which CUDA refuses: the runner turns itself off.
+ monkeypatch.setattr(runner, "_build_relative_pos", lambda hidden: None)
+
+ graphed = rig.adapter.extract(items, labels=_LABELS)
+
+ assert runner.disabled
+ assert _outputs(graphed) == eager
+ assert _outputs(rig.adapter.extract(items, labels=_LABELS)) == eager
+
+
[email protected]("mode", ["exact", "bucketed"])
+def test_cuda_graphs_run_eagerly_on_cpu(mode: str) -> None:
+ items = [Item(text=text) for text in _TEXTS]
+ graphs_rig = _Rig(prompt_first=True, scorer="mlp", cuda_graphs=mode)
+ plain_rig = _Rig(prompt_first=True, scorer="mlp")
+
+ eager = plain_rig.adapter.extract(items, labels=_LABELS)
+ for _ in range(2):
+ graphed = graphs_rig.adapter.extract(items, labels=_LABELS)
+ assert _outputs(graphed) == _outputs(eager)
+ assert graphs_rig.adapter._graphs is None
+
+
[email protected]("value", ["exact", "bucketed", "on", True, None, 1])
+def test_requests_cannot_turn_cuda_graphs_on(rig: _Rig, value: object) -> None:
+ with pytest.raises(InvalidInputError, match="accepts only 'off'"):
+ rig.adapter.extract([Item(text=_TEXTS[0])], labels=_LABELS, options={"cuda_graphs": value})
+
+
+def test_requests_may_turn_cuda_graphs_off(rig: _Rig) -> None:
+ items = [Item(text=text) for text in _TEXTS]
+
+ assert _outputs(rig.adapter.extract(items, labels=_LABELS, options=_EAGER)) == _outputs(
+ rig.adapter.extract(items, labels=_LABELS)
+ )