Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(server): bound GLiClass CUDA graph keys so mixed traffic keeps replaying (#389)
svonava5c50c33089cf
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.mdindex 62590e066..15e5d81a3 100644--- a/packages/sie_sdk/README.md+++ b/packages/sie_sdk/README.md@@ -151,11 +151,11 @@ billed. The other items still succeed.On a CUDA server, the operator can load the DeBERTa-based GLiClass models withCUDA 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. `gliclass-base-v1.0`,+graphs, sequence lengths and batch sizes are padded to buckets, which moves+probabilities slightly, as batching requests together does. `gliclass-base-v1.0`,`gliclass-large-v1.0` and `opir-multitask-large-v1.0` load with `bucketed`graphs by default: their probabilities differed from eager execution by up to-0.0144 in our tests, with no top label changed. Send+0.019 in our tests, with no top label changed. Send`options={"cuda_graphs": "off"}` to run a request eagerly; a request cannotturn graphs on. See the server README for each model's measurements and thememory graphs use.diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 07f6807a0..bbb9abc11 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -88,37 +88,45 @@ profiles:cuda_graphs: bucketed```+A graph records the encoder. The scoring head (label features, pooling and+scorer) runs eagerly on the graph's output with each forward's own number of+labels, so one graph serves every label count.+| 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) |+| `exact` | each (batch size, sequence length) seen twice; the 64 most recently used are kept | bit-identical to eager |+| `bucketed` | sequence lengths padded up to a multiple of 32 tokens (64 on 1,024-token models), batch sizes up to a power of two: a fixed set of shapes, all kept | padding moves fp16 probabilities (see below) |A request can send `options={"cuda_graphs": "off"}` to run eagerly on a modelloaded 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:+Padding is masked, and padded rows are dropped before scoring, but a longer+sequence or a larger batch 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. The three models that ship with graphs were measured again with padded+batches, adding the same questions over 3- and 5-item requests (18,450+answers). A small change can still flip a near tie between the top two+labels:| Model | Largest probability change | Top label changed | Shipped profile ||--|--|--|--|| `gliclass-small-v1.0` | 0.0039 | 3 answers | `off` |-| `gliclass-base-v1.0` | 0.0049 | none | `bucketed` |-| `gliclass-large-v1.0` | 0.0056 | none | `bucketed` |+| `gliclass-base-v1.0` | 0.0068 | none | `bucketed` |+| `gliclass-large-v1.0` | 0.0063 | none | `bucketed` || `gliclass-base-v3.0` | 0.0054 | 3 | `off` || `gliclass-large-v3.0` | 0.0093 | 3 | `off` || `gliclass-instruct-base-v1.0` | 0.0076 | 12 | `off` || `gliclass-instruct-large-v1.0` | 0.0098 | 18 | `off` |-| `opir-multitask-large-v1.0` | 0.0144 | none | `bucketed` |+| `opir-multitask-large-v1.0` | 0.0190 | none | `bucketed` || `gliclass-multilang-mini` (100 descriptions, no joint groups: 2,016 answers) | 0.0227 | 3 | `off` |-`exact` changed nothing.+`exact` changed nothing. A forward whose batch size is already a bucket (one+item, for example) scores exactly as it did before batches were padded.The shipped profiles load with `bucketed` graphs only where no top labelchanged: `gliclass-base-v1.0`, `gliclass-large-v1.0` and@@ -134,28 +142,42 @@ ModernBERT-based models (the edge models, `gliclass-multilang-edge` and theOpir edge models), CPU and MPS run eagerly with any value, and the load logs awarning.+**Shapes.** A graph holds at most 2,048 tokens (batch size times padded+length), or 1,024 for encoders wider than 768 such as DeBERTa-v3-large.+Larger forwards are bound by the GPU rather than by kernel launches and run+eagerly: on an L4, a `gliclass-large-v1.0` forward stops gaining from a graph+at about 1,000 tokens, a `gliclass-base-v1.0` forward at about 2,000. In+`bucketed` mode that leaves a fixed set of shapes, 52 for+`gliclass-large-v1.0`, 71 for `gliclass-base-v1.0` and 33 for+`opir-multitask-large-v1.0`, and the model keeps a graph for every one. Once+they are recorded, every forward under the token bound replays a graph,+whatever mix of label counts, batch sizes and lengths the traffic has, and no+request's shapes push out another's.+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.+needs it (the second time in `exact` mode), and the new graph's first replay+answers that request, which takes 52 to 66 ms against 43 ms for an eager+forward on `gliclass-large-v1.0` on an L4. Recording is rationed (see below),+so traffic that needs every shape has them all recorded within about two+minutes.**Memory, and other models on the same GPU.** Graph memory counts as devicememory in use, but it is not attributed to the model: under memory pressurethe 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.+another model. A model's graphs share one memory pool and write their output+into one shared buffer, and the driver keeps a copy of each graph: about 7 MB+for the `gliclass-large-v1.0` encoder. The runner adds up the device memory+its graphs hold (what each recording took, plus the tables and buffers they+read) against 4% of the device's memory (900 MB on an L4). On an L4, all of a+model's `bucketed` shapes took 720 MB for `gliclass-large-v1.0`, 630 MB for+`gliclass-base-v1.0` and 677 MB for `opir-multitask-large-v1.0`, plus about+150 MB cached on the recording stream (its cuBLAS workspace and one warm-up+row). On a smaller GPU, where the shapes do not all fit, recording stops at the+budget and the graphs already recorded keep replaying; the other shapes run+eagerly. In `exact` mode, whose shapes are unbounded, a model past its budget+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 blocksto satisfy other allocations, so another model on the same GPU that needs@@ -169,11 +191,20 @@ 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 onerecording. 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,+graphs can exceed it by one recording. On a GPU shared with other models,leave memory headroom, or enable graphs only where the model has the GPU toitself. Usage and billing do not change.+**Failures and counters.** A shape that fails to record for a reason other+than memory runs eagerly from then on, and the failure is logged as a warning+with its traceback. After three such shapes, the model runs eagerly for the+rest of the process, logged as an error. The scoring head is not part of that+count: it reads the request's own inputs, so an error there fails that request+as it would in an eager forward. Each model counts the forwards it+replays, records, and runs eagerly (by reason: past the token bound, recording+paused, budget full, and so on), and logs the counts every ten minutes while it+serves requests.+### GLiNER2.5-Decide usage and limitsThe GLiNER2.5-Decide models (`fastino/GLiNER2.5-Decide`, `GLiNER2.5-multi-Decide`,diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.pyindex 7f99de89e..c60cb5558 100644--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py@@ -978,8 +978,9 @@ class GLiClassAdapter(BaseAdapter):) -> 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.+ With ``graphs`` other than "off", a CUDA graph replays the encoder+ when the model and shape allow it, and the scoring head runs on its+ output with this forward's class slots; otherwise it runs eagerly."""forward_kwargs: dict[str, Any] = {}resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)@@ -987,7 +988,7 @@ class GLiClassAdapter(BaseAdapter):forward_kwargs["max_num_classes"] = resolve_max_num_classes(labels, same_labels)classes = forward_kwargs.get("max_num_classes")try:- if self._graphs is not None and isinstance(classes, int):+ if self._graphs is not None:logits = self._graphs.run(dict(inputs), classes, graphs)if logits is not None:return logits@@ -1018,6 +1019,8 @@ class GLiClassAdapter(BaseAdapter):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),+ mode=self._cuda_graphs,+ name=self._model_name_or_path,)@staticmethoddiff --git a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.pyindex b54814fa7..65372e488 100644--- a/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py+++ b/packages/sie_server/src/sie_server/adapters/gliclass/cuda_graphs.py@@ -1,4 +1,4 @@-"""CUDA graphs for the GLiClass forward pass.+"""CUDA graphs for the GLiClass encoder.A GLiClass forward on a DeBERTa encoder launches about a thousand smallkernels, so at small batch sizes the GPU waits on the CPU that launches them.@@ -6,20 +6,43 @@ A CUDA graph records the launches of one input shape once and replays themwith 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.+(``adapter_options.loadtime.cuda_graphs``); a request can only opt out.++What a graph holds. A graph records the encoder: the embeddings, the DeBERTa+layers and, where a model has them, segment embeddings and layer-wise+attention, up to the hidden states gliclass scores from. The scoring head+(label and text features, pooling, projections and scorer) runs eagerly on+the replayed hidden states, with the forward's own number of label slots. It+is a few dozen small kernels, launched while the GPU still runs the graph. So+one graph serves every label count: graphs are recorded per (batch size,+sequence length) only.++A graph holds at most 2,048 tokens (batch times padded length), or 1,024 for+encoders wider than 768 (DeBERTa-v3-large); larger forwards run eagerly. Past+about that many tokens the GPU, not kernel launches, bounds a forward: per+layer, a forward's GPU time grows with the square of the hidden size while its+kernel launches do not. On an L4, a gliclass-large-v1.0 forward stops gaining from+its graph at about 1,000 tokens, a gliclass-base-v1.0 forward at about 2,000.++Two modes choose the shape:++- ``exact`` records the forward's own batch size and 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 shapes seen once cost+ nothing. The shapes are unbounded; a runner keeps the 64 most recently used+ graphs.- ``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.+ 512-token window, 64 at 1,024) and the batch up to a power of two, or to the+ largest batch the token bound allows at that length. Padded positions are+ masked, and padded rows are dropped before scoring. That makes the set of+ shapes small and fixed (52 for gliclass-large-v1.0, 71 for+ gliclass-base-v1.0, 33 for opir-multitask-large-v1.0), and the runner keeps+ a graph for every one, so after warm-up forwards replay whatever mix of+ batch sizes, lengths and label counts the traffic has. A longer sequence, or+ a larger batch, 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. A forward whose batch is already a+ bucket scores exactly as it did when graphs also covered the head.While a graph is being recorded, PyTorch's caching allocator will not freecached blocks to satisfy another allocation, so another model on the same GPU@@ -31,13 +54,21 @@ therefore kept rare and short:- 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.+The forward that records a graph is answered by its first replay.+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.+model: their shared pool, the driver's copy of each recorded graph (about+7 MB for a DeBERTa-large encoder), and the relative-position tables and+buffers they read. The graphs of a runner write their hidden states into one+shared buffer, so the pool holds only what a forward needs while it runs. The+runner adds up the device memory each recording takes, plus those tensors,+against 4% of the device's memory. On an L4, all the ``bucketed`` shapes of+each model that ships with graphs take 630 to 720 MB of that 900 MB. Where+they do not fit (a smaller GPU), recording stops at the budget and the graphs+already recorded keep replaying: dropping graphs to record others would only+record the same fixed shapes again. In ``exact`` mode, whose shapes are+unbounded, the runner past the budget 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 thegliclass DeBERTa forward do: the relative-position table copies a CPU scalar@@ -47,10 +78,18 @@ encoder a table precomputed for the length, shared by the graphs of thatlength, and computes segment ids with tensor operations; both give the sameintegers.-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.+Replays never overlap (a lock serializes them), and each replay's hidden+states are scored before the next replay. Only the recording thread's forward+is diverted while a graph records; the diversion is per thread, so an eager+forward of the same model on another thread runs unchanged. Anything+unsupported, larger than the token bound, or whose shape failed to record runs+eagerly. A shape whose recording or first replay fails for any reason but+memory is not recorded again, and after three such shapes the runner turns+graphs off for the process. The scoring head is not part of that count: it+reads the forward's own inputs, so its errors fail that forward alone, as they+would eagerly. The runner+counts every forward it is offered (``CudaGraphStats``) and logs the counts+every ten minutes while it serves forwards."""from __future__ import annotations@@ -61,8 +100,8 @@ import mathimport threadingimport timefrom collections import OrderedDict-from collections.abc import Callable-from dataclasses import dataclass+from collections.abc import Callable, Iterator+from dataclasses import dataclass, fieldfrom typing import Any, Literalimport torch@@ -73,8 +112,8 @@ 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).+# Recorded graphs an ``exact`` runner keeps, least recently used out. A+# ``bucketed`` runner keeps one for every shape it can record._MAX_GRAPHS = 64# Shapes whose sightings ``exact`` mode counts._MAX_SIGHTINGS = 4096@@ -82,11 +121,13 @@ _MAX_SIGHTINGS = 4096_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.+# would pin a larger memory pool. Encoders wider than this hidden size spend+# about twice the GPU time per token, so their graphs hold half as many._MAX_GRAPH_TOKENS = 2048+_WIDE_ENCODER_HIDDEN_SIZE = 768# 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.+# seconds, however its forwards repeat: recording costs a forward's launches,+# 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.@@ -96,16 +137,34 @@ _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.+# tables and buffers), as a share of the device's memory._MEMORY_BUDGET_SHARE = 0.04+# Shapes that may fail to record, for reasons other than memory, before the+# runner turns graphs off for the process.+_MAX_RECORDING_FAILURES = 3+# A runner serving forwards logs its counters this often.+_SUMMARY_SECONDS = 600.0# 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]+# (batch size, sequence length)+Key = tuple[int, int]+# Why a forward the runner was offered ran eagerly.+EagerReason = Literal[+ "too_large", # past the token bound or the model window+ "unsupported_inputs", # inputs other than token ids, mask and token types+ "disabled", # graphs turned off for the process after recording failures+ "unseen", # ``exact`` mode: the shape's first sighting+ "failed_shape", # the shape failed to record before+ "budget_full", # ``bucketed`` mode: 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 unsupported_reason(model: Any, device: str | torch.device) -> str | None:@@ -118,9 +177,12 @@ def unsupported_reason(model: Any, device: str | torch.device) -> str | None: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)+ inner = getattr(model, "model", None)+ encoder = getattr(getattr(inner, "encoder_model", None), "encoder", None)if encoder is None or not hasattr(encoder, "get_rel_pos"):return "the encoder has no relative-position hook"+ if not callable(getattr(inner, "process_encoder_output", None)):+ return "the model has no scoring head to run apart from its encoder"return None@@ -129,26 +191,69 @@ def bucket_width(max_length: int) -> int:return max(16, max_length // 16)-class _RecordingError(Exception):- """Recording a graph failed after the eager forward had answered the call."""+def token_bound(hidden_size: int) -> int:+ """Tokens a graph of an encoder with this hidden size may hold."""+ return _MAX_GRAPH_TOKENS if hidden_size <= _WIDE_ENCODER_HIDDEN_SIZE else _MAX_GRAPH_TOKENS // 2+++def batch_buckets(length: int, max_tokens: int) -> tuple[int, ...]:+ """Batch sizes ``bucketed`` graphs of this padded length hold: powers of two, and the largest that fits.++ A batch pads up to the next of these, so a batch past a power of two+ costs at most twice its rows, and one near the token bound pads only to+ the bound.+ """+ largest = max_tokens // length+ sizes = [1 << power for power in range(largest.bit_length())]+ if largest and sizes[-1] != largest:+ sizes.append(largest)+ return tuple(sizes)- def __init__(self, cause: BaseException, logits: torch.Tensor) -> None:- super().__init__(str(cause))- self.cause = cause- self.logits = logits++def bucketed_shapes(max_length: int, max_tokens: int) -> frozenset[Key]:+ """Every shape a ``bucketed`` runner can record at this window."""+ width = bucket_width(max_length)+ lengths = {min(max_length, width * step) for step in range(1, math.ceil(max_length / width) + 1)}+ return frozenset((batch, length) for length in lengths for batch in batch_buckets(length, max_tokens))+++@dataclass+class CudaGraphStats:+ """Counters of the forwards a runner was offered since the model loaded.++ Each forward counts once: ``replayed`` (a recorded graph served it),+ ``recorded`` (it recorded a graph and was answered by the first replay)+ or under ``eager`` by why it ran eagerly. Requests that opt out of graphs+ are not offered to the runner. ``recording_failures`` counts shapes that+ failed to record for reasons other than memory; ``drops`` counts the times+ every graph was dropped (out of memory, or ``exact`` mode over its budget).+ """++ replayed: int = 0+ recorded: int = 0+ eager: dict[str, int] = field(default_factory=dict)+ recording_failures: int = 0+ drops: int = 0++ @property+ def forwards(self) -> int:+ return self.replayed + self.recorded + sum(self.eager.values())+++class _RecordingOutOfMemoryError(Exception):+ """Recording a graph ran out of device memory."""@dataclassclass _Graph:graph: Anyinputs: dict[str, torch.Tensor]- output: torch.Tensor# Device memory the recording took: pool growth and the recorded graph.device_bytes: int = 0class CudaGraphRunner:- """Records and replays the forward pass of one GLiClass model, per input shape."""+ """Records and replays the encoder of one GLiClass model, per input shape."""def __init__(self,@@ -157,20 +262,40 @@ class CudaGraphRunner:pad_token_id: int,max_length: int,pad_token_type_id: int = 0,- max_graphs: int = _MAX_GRAPHS,+ mode: GraphMode = "bucketed",+ name: str = "",+ max_graphs: int | None = None,clock: Callable[[], float] = time.monotonic,) -> None:self._model = model+ self._name = nameself._pad_values = {"input_ids": pad_token_id, "attention_mask": 0, "token_type_ids": pad_token_type_id}self._max_length = max_lengthself._bucket = bucket_width(max_length)- self._max_tokens = _MAX_GRAPH_TOKENS+ config = model.config+ self._hidden_size = int(config.encoder_config.hidden_size)+ embeddings = getattr(model.model.encoder_model, "get_input_embeddings", None)+ self._dtype = embeddings().weight.dtype if callable(embeddings) else torch.float16+ self._max_tokens = token_bound(self._hidden_size)+ self._padding_safe = config.pooling_strategy in _PADDING_SAFE_POOLINGS and not getattr(+ config, "use_lstm", False+ )+ # A bucketed runner whose lengths are bucketed records a fixed set of+ # shapes and keeps a graph for each; any other keeps the most recent.+ self._shapes = (+ bucketed_shapes(max_length, self._max_tokens) if mode == "bucketed" and self._padding_safe else None+ )+ if max_graphs is None:+ max_graphs = len(self._shapes) if self._shapes is not None else _MAX_GRAPHSself._max_graphs = max_graphsself._graphs: OrderedDict[Key, _Graph] = OrderedDict()self._sightings: OrderedDict[Key, int] = OrderedDict()+ self._failed: set[Key] = set()self._lock = threading.RLock()self._stream: torch.cuda.Stream | None = Noneself._disabled = False+ # Set when the memory budget holds no more of a bucketed runner's graphs.+ self._full = Falseself._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.@@ -180,13 +305,16 @@ class CudaGraphRunner:# 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- )+ # The hidden states every graph writes, sized for the token bound.+ self._hidden: torch.Tensor | None = None+ # Set only on the thread that is recording, while it records: the+ # hooks divert that thread's forward and leave every other thread's+ # alone.+ self._local = threading.local()+ self.stats = CudaGraphStats()+ self._summary_at = clock()+ self._summary_forwards = 0+ self._summary_replayed = 0self._install_hooks()# -- hooks -------------------------------------------------------------@@ -200,8 +328,8 @@ class CudaGraphRunner: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+ if relative_pos is None and self._recording_here():+ return self._local.relative_posreturn get_rel_pos(hidden_states, query_states, relative_pos)encoder.get_rel_pos = recording_get_rel_pos@@ -210,108 +338,208 @@ class CudaGraphRunner:config = self._model.configdef recording_segment_ids(input_ids: torch.Tensor) -> torch.Tensor:- if not self._recording:+ if not self._recording_here():return create_segment_ids(input_ids)return segment_ids(input_ids, config)inner._create_segment_ids = recording_segment_ids+ # The head: everything the uni-encoder forward does after its encoder.+ # While recording, the forward stops there and returns the hidden states.+ head = inner.process_encoder_output+ self._head = head++ def recording_head(+ input_ids: torch.Tensor,+ attention_mask: torch.Tensor,+ encoder_layer: torch.Tensor,+ labels: Any = None,+ max_num_classes: int | None = None,+ ) -> Any:+ if self._recording_here():+ return encoder_layer, None, None, None+ return head(input_ids, attention_mask, encoder_layer, labels, max_num_classes)++ inner.process_encoder_output = recording_head++ def _recording_here(self) -> bool:+ """Whether this thread is recording a graph of this runner's model."""+ return getattr(self._local, "recording", False)++ @contextlib.contextmanager+ def _recording_on_this_thread(self, relative_pos: torch.Tensor | None) -> Iterator[None]:+ """Divert this thread's forward to a recordable one 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, batch: int, length: int, classes: int, mode: GraphMode) -> Key | None:+ def key(self, batch: int, length: 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)+ batch = next((size for size in batch_buckets(length, self._max_tokens) if size >= batch), 0)+ if not batch:+ return Noneif 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+ return (batch, length)++ def _why_not_record(self, key: Key, mode: GraphMode, device: torch.device) -> EagerReason | None:+ if key in self._failed:+ return "failed_shape"+ if mode == "exact":+ seen = self._sightings.pop(key, 0) + 1+ self._sightings[key] = seen+ while len(self._sightings) > _MAX_SIGHTINGS:+ self._sightings.popitem(last=False)+ if seen < _EXACT_RECORD_AT:+ return "unseen"+ 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, inputs: dict[str, torch.Tensor], max_num_classes: int, mode: GraphMode) -> torch.Tensor | None:+ def run(self, inputs: dict[str, torch.Tensor], max_num_classes: int | None, mode: GraphMode) -> torch.Tensor | None:"""Logits for ``inputs`` from a graph, or None to run the forward eagerly."""- if mode == "off" or self._disabled:+ if mode == "off":return None+ with self._lock:+ logits, reason = self._run(inputs, max_num_classes, mode)+ if reason is not None:+ self.stats.eager[reason] = self.stats.eager.get(reason, 0) + 1+ self._log_summary()+ return logits++ def _run(+ self, inputs: dict[str, torch.Tensor], max_num_classes: int | None, mode: GraphMode+ ) -> tuple[torch.Tensor | None, EagerReason | None]:+ if self._disabled:+ return None, "disabled"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+ if (+ input_ids is None+ or input_ids.dim() != 2+ or "attention_mask" not in inputs # the head reads it+ or set(inputs) - set(self._pad_values)+ ):+ return None, "unsupported_inputs"batch, length = input_ids.shape- key = self.key(batch, length, max_num_classes, mode)+ key = self.key(batch, length, 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+ return None, "too_large"+ now = self._clock()+ elapsed, self._credited_at = now - self._credited_at, now+ self._recording_credit = min(float(_RECORDING_BURST), self._recording_credit + elapsed / _SECONDS_PER_RECORDING)+ entry = self._graphs.get(key)+ if entry is not None:+ self._graphs.move_to_end(key)+ self.stats.replayed += 1+ return self._replay(key, entry, inputs, max_num_classes), None+ reason = self._why_not_record(key, mode, 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 -= 1try:- 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()+ entry = self._record(key, inputs)+ except Exception as exc: # noqa: BLE001 -- any failure to record runs the forward eagerly+ self._recording_failed(key, exc)+ return None, "recording_failed"+ # The graph answers the forward that recorded it, replayed before+ # the budget check below can drop it. Its first replay is part of+ # recording it: a failure other than memory runs the forward+ # eagerly and the graph is not kept.+ try:+ hidden = self._replay_graph(key, entry, inputs)+ except Exception as exc:+ if is_oom_error(exc):+ raise+ self._recording_failed(key, exc)+ return None, "recording_failed"+ self._keep(key, entry, input_ids.device)+ self.stats.recorded += 1+ finally:+ _RECORDING_LOCK.release()+ # The scoring head reads the forward's own inputs, so its errors are+ # the forward's, as in an eager forward: they fail this forward and+ # count nothing against the shape.+ return self._score(entry, hidden, max_num_classes), None++ def _keep(self, key: Key, entry: _Graph, device: torch.device) -> None:+ """Cache a new graph and hold the runner's graphs to their memory budget."""+ self._graphs[key] = entry+ self._device_bytes += entry.device_bytes+ 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(device):+ return+ if self._shapes is not None:+ # 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(+ "GLiClass 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),+ )+ return+ logger.info(+ "GLiClass CUDA graphs for %s took %d MB, over their budget; dropping them to record again",+ self._name,+ held // 2**20,+ )+ self.clear()+ self.stats.drops += 1+ # With every graph gone, their pool can go back to the device.+ torch.cuda.empty_cache()++ 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(+ "GLiClass 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(+ "GLiClass 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(+ "GLiClass 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."""@@ -319,7 +547,9 @@ class CudaGraphRunner:self._graphs.clear()self._sightings.clear()self._relative_pos.clear()+ self._hidden = Noneself._device_bytes = 0+ self._full = False@propertydef graph_count(self) -> int:@@ -329,6 +559,45 @@ class CudaGraphRunner:def disabled(self) -> bool:return self._disabled+ @property+ def shape_count(self) -> int | None:+ """How many shapes the runner can record; None when they are unbounded (``exact`` mode)."""+ return None if self._shapes is None else len(self._shapes)++ @property+ def held_bytes(self) -> int:+ """Device memory the runner counts against its budget."""+ return self._device_bytes + self._tensor_bytes()++ def _log_summary(self) -> None:+ now = self._clock()+ if now - self._summary_at < _SUMMARY_SECONDS:+ return+ stats = self.stats+ forwards = stats.forwards - self._summary_forwards+ replayed = stats.replayed - self._summary_replayed+ interval = now - self._summary_at+ self._summary_at, self._summary_forwards, self._summary_replayed = now, stats.forwards, stats.replayed+ if not forwards:+ return+ logger.info(+ "GLiClass 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%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,+ ", off for this process" if self._disabled else "",+ )+# -- recording and replay ---------------------------------------------@staticmethod@@ -339,7 +608,7 @@ class CudaGraphRunner:@staticmethoddef _memory_budget(device: torch.device) -> int:- """Device memory this runner's recordings may take before its graphs are dropped."""+ """Device memory this runner's graphs may hold."""return int(_MEMORY_BUDGET_SHARE * torch.cuda.mem_get_info(device)[1])@staticmethod@@ -347,57 +616,61 @@ class CudaGraphRunner: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."""+ """Device memory of the tensors the graphs keep: tables, static inputs and the hidden states."""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+ buffers = sum(sum(tensor.nbytes for tensor in entry.inputs.values()) for entry in self._graphs.values())+ hidden = self._hidden.nbytes if self._hidden is not None else 0+ return tables + buffers + hiddendef _drop_unused_tables(self) -> None:- lengths = {length for _, length, _ in self._graphs}+ 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 _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.+ self._hidden = torch.empty(self._max_tokens * self._hidden_size, dtype=dtype, device=device)+ elif self._hidden.dtype != dtype or self._hidden.device != device:+ msg = f"hidden states are {self._hidden.dtype} on {self._hidden.device}, not {dtype} on {device}"+ raise RuntimeError(msg)+ return self._hidden[: batch * length * self._hidden_size].view(batch, length, self._hidden_size)+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+ batch, length = key+ return {+ name: torch.full((batch, length), self._pad_values[name], dtype=value.dtype, device=value.device)+ for name, value in inputs.items()+ }++ def _record(self, key: Key, inputs: dict[str, torch.Tensor]) -> _Graph:+ """Record the graph for ``key``.++ Recording runs on a stream of the runner's own, whose first usecreates per-stream state (the cuBLAS handle and workspace) that cannotbe created while recording: the first recording warms that stream upwith one row of its inputs, the only memory left cached on it.+ Recording launches no kernels; the caller replays the graph to answer+ the forward.Raises:- _RecordingError: With the eager logits, when anything after the- eager forward fails: the table, the warm-up or the recording.+ _RecordingOutOfMemoryError: When the warm-up or the recording runs out+ of device memory."""- 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+ return self._capture(key, static)except Exception as exc:- raise _RecordingError(exc, logits) from exc+ if is_oom_error(exc):+ raise _RecordingOutOfMemoryError(str(exc)) from exc+ raise- def _capture(self, key: Key, static: dict[str, torch.Tensor], current: torch.cuda.Stream) -> _Graph:- _, padded_length, classes = key+ def _capture(self, key: Key, static: dict[str, torch.Tensor]) -> _Graph:+ _, padded_length = keydevice = static["input_ids"].device+ current = torch.cuda.current_stream(device)relative_pos = self._relative_pos.get(padded_length)if relative_pos is None:with torch.inference_mode():@@ -405,23 +678,27 @@ class CudaGraphRunner: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+ hidden = self._hidden_states(key, self._dtype, device)warm_up = self._stream is Nonestream = self._stream or torch.cuda.Stream(device=device)pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else Nonegraph = torch.cuda.CUDAGraph()stream.wait_stream(current)- self._recording_relative_pos = relative_pos- self._recording = Truetry:- with torch.inference_mode(), torch.cuda.stream(stream):+ with self._recording_on_this_thread(relative_pos), 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)+ self._model(**{name: value[:1] for name, value in static.items()})# Kept only once warmed up, so a failed warm-up is tried again.self._stream = streamfree_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+ encoded = self._model(**static).logits # the head hook returns the hidden states+ 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 encodedexcept BaseException:# End the recording without hiding why it failed.with contextlib.suppress(Exception):@@ -430,19 +707,39 @@ class CudaGraphRunner:graph.capture_end()device_bytes = max(0, free_before - self._free_memory(device))finally:- self._recording = False- self._recording_relative_pos = Nonecurrent.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:+ return _Graph(graph=graph, inputs=static, device_bytes=device_bytes)++ def _replay(+ self, key: Key, entry: _Graph, inputs: dict[str, torch.Tensor], max_num_classes: int | None+ ) -> torch.Tensor:+ """Replay ``entry`` on ``inputs`` and score the replayed hidden states of the real rows."""+ return self._score(entry, self._replay_graph(key, entry, inputs), max_num_classes)++ def _replay_graph(self, key: Key, entry: _Graph, inputs: dict[str, torch.Tensor]) -> torch.Tensor:+ """Replay ``entry`` on ``inputs``; the hidden states of the real rows."""+ shared = self._hidden+ if shared is None: # dropped only with every graph+ raise RuntimeError("GLiClass CUDA graph replayed without its hidden-state buffer")+ batch, length = next(iter(inputs.values())).shapefor name, value in inputs.items():buffer = entry.inputs[name]- buffer[:, :length].copy_(value)+ pad = self._pad_values[name]+ buffer[:batch, :length].copy_(value)if length < buffer.shape[1]:- buffer[:, length:].fill_(self._pad_values[name])+ buffer[:batch, length:].fill_(pad)+ if batch < buffer.shape[0]:+ buffer[batch:].fill_(pad)entry.graph.replay()- return entry.output.clone()+ return self._hidden_states(key, shared.dtype, shared.device)[:batch]++ def _score(self, entry: _Graph, hidden: torch.Tensor, max_num_classes: int | None) -> torch.Tensor:+ """The logits the scoring head gives the replayed hidden states of the real rows."""+ batch = hidden.shape[0]+ with torch.inference_mode():+ return self._head(+ entry.inputs["input_ids"][:batch], entry.inputs["attention_mask"][:batch], hidden, None, max_num_classes+ )[0]def segment_ids(input_ids: torch.Tensor, config: Any) -> torch.Tensor:diff --git a/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.pyindex 21b1b1fa1..990398d3e 100644--- a/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py+++ b/packages/sie_server/tests/adapters/test_gliclass_cuda_graphs.py@@ -7,6 +7,9 @@ from real graphs are checked against eager scores in test_gliclass_parity.pyfrom __future__ import annotations+import logging+import random+import threadingfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -19,8 +22,11 @@ from sie_server.adapters.gliclass import GLiClassAdapterfrom sie_server.adapters.gliclass import cuda_graphs as cuda_graphs_modulefrom sie_server.adapters.gliclass.cuda_graphs import (CudaGraphRunner,+ batch_buckets,bucket_width,+ bucketed_shapes,segment_ids,+ token_bound,unsupported_reason,)from sie_server.core.loader import _build_adapter_kwargs, load_model_configs, reject_unknown_loadtime_options@@ -51,10 +57,12 @@ def _model(architecture: str = "uni-encoder",pooling: str = "first",segment_embeddings: bool = False,+ hidden_size: int = 1024,+ head: bool = True,) -> Any:config = SimpleNamespace(architecture_type=architecture,- encoder_config=SimpleNamespace(model_type=encoder_type),+ encoder_config=SimpleNamespace(model_type=encoder_type, hidden_size=hidden_size),pooling_strategy=pooling,use_lstm=False,use_segment_embeddings=segment_embeddings,@@ -62,31 +70,38 @@ def _model(text_token_index=8,)inner = SimpleNamespace(encoder_model=SimpleNamespace(encoder=_Encoder()), _create_segment_ids=lambda ids: "eager")+ if head:+ inner.process_encoder_output = lambda ids, mask, layer, labels=None, max_num_classes=None: ("head", layer)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``.+ """Records and replays graphs with fakes; the runner's own code scores them.++ A graph replay (``_replay_graph``) returns hidden states for the forward's+ real rows, or raises ``replay_error``. The scoring head answers with ones,+ ``(batch, classes)``: the forward's real rows and label slots, or raises+ ``head_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``."""- def __init__(self, model: Any = None, *, fail: bool | Exception = False, **kwargs: Any) -> None:+ def __init__(self, model: Any = None, **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+ kwargs.setdefault("max_length", 512)+ super().__init__(model or _model(), pad_token_id=0, clock=lambda: self.now, **kwargs)+ self.recorded: list[tuple[int, int]] = []+ self.replayed: list[tuple[int, int]] = []+ self.head_classes: list[int | None] = []self.capture_error: Exception | None = Noneself.headroom = Trueself.budget = 2**40self.bytes_per_graph = 0self.replay_error: Exception | None = None+ self.head_error: Exception | None = None+ self.buffers_alive = False+ self._head = self._fake_headdef _has_headroom(self, device: torch.device) -> bool:return self.headroom@@ -94,23 +109,39 @@ class _Runner(CudaGraphRunner):def _memory_budget(self, device: torch.device) -> int:return self.budget+ # Whether ``capture_error`` fails every recording, not just the next one.+ keep_failing = False+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))+ error, self.capture_error = self.capture_error, (self.capture_error if self.keep_failing else None)+ raise errorself.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])+ self.buffers_alive = True # like the hidden-state buffer a real recording writes+ # Static inputs with a row per padded row and no memory to count.+ static = {name: torch.zeros(key[0], 0, dtype=torch.long) for name in ("input_ids", "attention_mask")}+ return SimpleNamespace(key=key, device_bytes=self.bytes_per_graph, inputs=static, graph=None)++ def clear(self) -> None:+ super().clear()+ self.buffers_alive = False- def _replay(self, entry: Any, inputs: dict[str, torch.Tensor], length: int) -> torch.Tensor:+ def _replay_graph(self, key: Any, entry: Any, inputs: dict[str, torch.Tensor]) -> torch.Tensor:+ assert self.buffers_alive, "replayed a graph after its buffers were dropped"if self.replay_error is not None:raise self.replay_errorself.replayed.append(entry.key)- return torch.ones(entry.key[0], entry.key[2])+ return torch.zeros(inputs["input_ids"].shape[0], key[1], 1)++ def _fake_head(+ self, input_ids: Any, attention_mask: Any, hidden: torch.Tensor, labels: Any, max_num_classes: int | None+ ) -> tuple[torch.Tensor]:+ assert input_ids.shape[0] == attention_mask.shape[0] == hidden.shape[0]+ if self.head_error is not None:+ raise self.head_error+ self.head_classes.append(max_num_classes)+ return (torch.ones(hidden.shape[0], max_num_classes or 1),)def _inputs(batch: int, length: int) -> dict[str, torch.Tensor]:@@ -131,6 +162,7 @@ class TestSupport:(_model(), "mps", "CUDA device"),(_model(encoder_type="modernbert"), "cuda:0", "modernbert encoder"),(_model(architecture="bi-encoder"), "cuda:0", "uni-encoder"),+ (_model(head=False), "cuda:0", "scoring head"),],)def test_other_models_and_devices_run_eagerly(self, model: Any, device: str, reason: str) -> None:@@ -144,35 +176,92 @@ class TestShapes:def test_bucket_width_follows_the_window(self, max_length: int, width: int) -> None:assert bucket_width(max_length) == width+ @pytest.mark.parametrize(("hidden_size", "tokens"), [(384, 2048), (768, 2048), (1024, 1024), (1536, 1024)])+ def test_wider_encoders_hold_fewer_tokens(self, hidden_size: int, tokens: int) -> None:+ assert token_bound(hidden_size) == tokens+@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)+ assert runner.key(1, length, "bucketed") == (1, bucketed)+ assert runner.key(1, length, "exact") == (1, length)- def test_shapes_past_2048_tokens_run_eagerly(self) -> None:+ @pytest.mark.parametrize(+ ("length", "tokens", "sizes"),+ [+ (32, 2048, (1, 2, 4, 8, 16, 32, 64)),+ (96, 2048, (1, 2, 4, 8, 16, 21)),+ (512, 2048, (1, 2, 4)),+ (96, 1024, (1, 2, 4, 8, 10)),+ (192, 1024, (1, 2, 4, 5)),+ (512, 1024, (1, 2)),+ (1024, 1024, (1,)),+ ],+ )+ def test_batch_buckets_are_powers_of_two_and_the_largest_that_fits(+ self, length: int, tokens: int, sizes: tuple[int, ...]+ ) -> None:+ assert batch_buckets(length, tokens) == sizes++ def test_bucketed_batches_pad_up_to_their_bucket(self) -> None:+ runner = _Runner() # a DeBERTa-large-wide encoder: 1,024 tokens++ assert [runner.key(batch, 100, "bucketed") for batch in (1, 2, 3, 4, 5, 8)] == [+ (1, 128),+ (2, 128),+ (4, 128),+ (4, 128),+ (8, 128),+ (8, 128),+ ]+ assert runner.key(9, 100, "bucketed") is None # 9 x 128 tokens: over the bound+ assert runner.key(5, 190, "bucketed") == (5, 192) # the largest batch at 192 tokens+ assert runner.key(3, 100, "exact") == (3, 100) # exact mode never pads++ def test_shapes_past_the_token_bound_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+ assert runner.key(2, 512, "exact") == (2, 512)+ assert runner.key(3, 512, "exact") is None+ assert runner.key(32, 32, "bucketed") == (32, 32)+ assert runner.key(33, 32, "bucketed") is None+ assert runner.key(5, 200, "bucketed") is None # 5 x 224 tokens++ narrow = _Runner(_model(hidden_size=768))+ assert narrow.key(4, 512, "exact") == (4, 512)+ assert narrow.key(9, 100, "bucketed") == (16, 128)+ assert narrow.key(65, 32, "bucketed") is Nonedef 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+ assert runner.key(1, 1024, "exact") == (1, 1024)+ assert runner.key(2, 1024, "exact") is None+ assert runner.key(1, 600, "bucketed") == (1, 640) # 64-token buckets++ @pytest.mark.parametrize(+ ("max_length", "hidden_size", "count"),+ [(512, 1024, 52), (512, 768, 71), (1024, 1024, 33)],+ ids=["gliclass-large", "gliclass-base", "opir-multitask-large"],+ )+ def test_every_bucketed_forward_maps_into_a_small_fixed_set(+ self, max_length: int, hidden_size: int, count: int+ ) -> None:+ runner = _Runner(_model(hidden_size=hidden_size), max_length=max_length)+ shapes = bucketed_shapes(max_length, token_bound(hidden_size))++ assert len(shapes) == count+ assert runner.shape_count == count+ keys = {runner.key(batch, length, "bucketed") for batch in range(1, 129) for length in range(1, max_length + 1)}+ assert keys - {None} == shapes@pytest.mark.parametrize("pooling", ["avg", "last", "max"])- def test_poolings_that_read_padding_keep_exact_lengths(self, pooling: str) -> None:+ def test_poolings_that_read_padding_keep_exact_shapes(self, pooling: str) -> None:runner = _Runner(_model(pooling=pooling))- assert runner.key(1, 100, 4, "bucketed") == (1, 100, 4)+ assert runner.key(3, 100, "bucketed") == (3, 100)+ assert runner.shape_count is None # unbounded: a most-recently-used cacheclass TestRecordingPolicy:@@ -181,85 +270,107 @@ class TestRecordingPolicy:assert runner.run(_inputs(1, 100), 4, "off") is Noneassert runner.recorded == []+ assert runner.stats.forwards == 0 # opted-out forwards are not offered to the runnerdef test_exact_mode_records_a_shape_the_second_time_it_is_seen(self) -> None:- runner = _Runner()+ runner = _Runner(mode="exact")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 second is not None # the recording forward is answered by the new graphassert 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)]+ assert runner.recorded == [(1, 100)]+ assert runner.replayed == [(1, 100), (1, 100)]+ assert runner.stats.eager == {"unseen": 1}+ assert (runner.stats.recorded, runner.stats.replayed) == (1, 1)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")+ for length in (100, 110, 128, 129):+ runner.run(_inputs(1, length), 4, "bucketed")- assert runner.recorded == [(1, 128, 4), (1, 160, 4)]- assert runner.replayed == [(1, 128, 4), (1, 128, 4)]+ assert runner.recorded == [(1, 128), (1, 160)]+ assert (runner.stats.recorded, runner.stats.replayed) == (2, 2)- def test_batch_size_and_class_slots_are_part_of_the_shape(self) -> None:+ def test_label_counts_share_one_graph(self) -> None:runner = _Runner()- for batch, classes in ((1, 4), (2, 4), (1, 8)):- runner.run(_inputs(batch, 100), classes, "bucketed")+ answers = [runner.run(_inputs(3, 100), classes, "bucketed") for classes in range(1, 101)]- assert runner.recorded == [(1, 128, 4), (2, 128, 4), (1, 128, 8)]+ assert runner.recorded == [(4, 128)]+ assert runner.head_classes == list(range(1, 101)) # the head scores each forward's own label slots+ assert all(answer is not None and answer.shape == (3, classes) for classes, answer in enumerate(answers, 1))- def test_the_least_recently_used_graph_is_dropped_past_the_bound(self) -> None:- runner = _Runner(max_graphs=2)+ def test_a_fixed_label_allocation_also_replays(self) -> None:+ runner = _Runner()- 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+ runner.run(_inputs(1, 100), None, "bucketed") # 'fixed' allocation: the model's own label count++ assert runner.head_classes == [None]++ def test_batch_sizes_share_their_bucket(self) -> None:+ runner = _Runner()++ for batch in (3, 4, 5, 6, 7, 8):+ runner.run(_inputs(batch, 100), 4, "bucketed")++ assert runner.recorded == [(4, 128), (8, 128)]++ def test_after_warm_up_every_bucketed_forward_replays_whatever_the_mix(self) -> None:+ # Shape cycling: random batch sizes, lengths and label counts for ten+ # simulated minutes, one forward per 50 ms.+ runner = _Runner()+ shapes = runner.shape_count+ rng = random.Random(0) # noqa: S311 -- a reproducible traffic mix, not a secret+ for step in range(12_000):+ runner.now = step * 0.05+ runner.run(_inputs(rng.randint(1, 32), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")++ assert len(runner.recorded) == len(set(runner.recorded)) == shapes # each shape once: nothing evicted+ assert runner.graph_count == shapes+ replayed, eager = runner.stats.replayed, dict(runner.stats.eager)+ for _ in range(1000):+ runner.run(_inputs(rng.randint(1, 32), rng.randint(1, 512)), rng.randint(1, 100), "bucketed")+ new_eager = {reason: count - eager.get(reason, 0) for reason, count in runner.stats.eager.items()}+ # Only forwards past the token bound run eagerly; every other forward replays.+ assert {reason for reason, count in new_eager.items() if count} <= {"too_large"}+ assert runner.stats.replayed - replayed == 1000 - new_eager.get("too_large", 0) > 0++ def test_the_least_recently_used_graph_is_dropped_past_the_bound_in_exact_mode(self) -> None:+ runner = _Runner(mode="exact", max_graphs=2)++ for length in (32, 32, 64, 64, 32, 96, 96, 64, 64):+ runner.run(_inputs(1, length), 4, "exact")assert runner.graph_count == 2- assert runner.recorded == [(1, 32, 4), (1, 64, 4), (1, 96, 4), (1, 64, 4)]+ # 32 and 64 recorded; 32 used again; 96 drops 64, which is then seen and recorded again.+ assert runner.recorded == [(1, 32), (1, 64), (1, 96), (1, 64)]# 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))+ runner = _Runner(_model(hidden_size=768)) # 71 shapes+ shapes = sorted(bucketed_shapes(512, 2048))# 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)]+ answers = [runner.run(_inputs(batch, length), 4, "bucketed") for batch, length in shapes[:40]]assert len(runner.recorded) == 16- assert answers.count(None) == 64 # the rest ran eagerly+ assert answers.count(None) == 24 # the rest ran eagerly+ assert runner.stats.eager == {"recording_paused": 24}runner.now += 2.0 # one more recording every 2 seconds- for _ in range(10):- runner.run(_inputs(1, 100), next(shapes), "bucketed")+ for batch, length in shapes[40:50]:+ runner.run(_inputs(batch, length), 4, "bucketed")assert len(runner.recorded) == 17runner.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+ for batch, length in shapes[50:]:+ runner.run(_inputs(batch, length), 4, "bucketed")+ assert len(runner.recorded) == 17 + min(16, len(shapes) - 50)def test_one_recording_at_a_time_in_the_process(self) -> None:runner = _Runner()@@ -270,45 +381,68 @@ class TestRecordingPolicy:finally:cuda_graphs_module._RECORDING_LOCK.release()assert runner.recorded == []+ assert runner.stats.eager == {"busy": 1}assert runner.run(_inputs(1, 100), 4, "bucketed") is not None- assert runner.recorded == [(1, 128, 4)]+ assert runner.recorded == [(1, 128)]assert not cuda_graphs_module._RECORDING_LOCK.locked()- def test_graphs_are_dropped_when_their_memory_passes_the_budget(self) -> None:+ def test_a_bucketed_runner_over_its_budget_stops_recording_and_keeps_its_graphs(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:runner = _Runner()runner.budget, runner.bytes_per_graph = 250, 100+ with caplog.at_level(logging.WARNING, logger=cuda_graphs_module.__name__):+ for length in (32, 64, 96, 128):+ runner.run(_inputs(1, length), 4, "bucketed")++ assert runner.recorded == [(1, 32), (1, 64), (1, 96)] # the third went over; no more+ assert runner.graph_count == 3+ assert runner.stats.eager == {"budget_full": 1}+ assert "3 of 52 shapes recorded" in caplog.textrunner.run(_inputs(1, 32), 4, "bucketed")- runner.run(_inputs(1, 64), 4, "bucketed")+ assert runner.replayed[-1] == (1, 32) # graphs it holds keep replaying+ runner.clear() # an out-of-memory error or unload starts over+ runner.run(_inputs(1, 128), 4, "bucketed")+ assert runner.recorded[-1] == (1, 128)++ def test_an_exact_runner_over_its_budget_drops_its_graphs(self) -> None:+ runner = _Runner(mode="exact")+ runner.budget, runner.bytes_per_graph = 250, 100++ for length in (32, 32, 64, 64):+ runner.run(_inputs(1, length), 4, "exact")assert runner.graph_count == 2- runner.run(_inputs(1, 96), 4, "bucketed") # 300 bytes: over the budget+ runner.run(_inputs(1, 96), 4, "exact")+ answer = runner.run(_inputs(1, 96), 4, "exact") # 300 bytes: over the budget+ assert answer is not None # the recording answered before its graphs were droppedassert runner.graph_count == 0assert runner._relative_pos == {}+ assert runner.stats.drops == 1assert 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 == 1def test_the_budget_counts_the_tensors_graphs_keep(self) -> None:runner = _Runner()runner.budget = 999runner._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+ runner.run(_inputs(1, 32), 4, "bucketed")+ runner.run(_inputs(1, 64), 4, "bucketed")- assert runner.graph_count == 0+ assert runner.recorded == [(1, 32)] # the table put the first recording overdef 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 = _Runner(mode="exact", 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")+ for length in (32, 32, 64, 64):+ runner.run(_inputs(1, length), 4, "exact")assert runner.graph_count == 1- runner.run(_inputs(1, 96), 4, "bucketed")+ runner.run(_inputs(1, 96), 4, "exact")+ runner.run(_inputs(1, 96), 4, "exact")assert runner.graph_count == 0@@ -319,76 +453,157 @@ class TestRecordingPolicy:assert runner.run(_inputs(1, 200), 4, "bucketed") is None # would record: runs eagerlyassert 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)]+ assert runner.recorded == [(1, 128)]+ assert runner.stats.eager == {"no_headroom": 1}- def test_a_recording_failure_turns_graphs_off_and_keeps_the_eager_answer(self) -> None:+ def test_a_shape_that_fails_to_record_runs_eagerly_and_the_others_keep_replaying(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:runner = _Runner()+ runner.run(_inputs(1, 100), 4, "bucketed")runner.capture_error = RuntimeError("operation not permitted when stream is capturing")- answer = runner.run(_inputs(1, 100), 4, "bucketed")+ with caplog.at_level(logging.WARNING, logger=cuda_graphs_module.__name__):+ assert runner.run(_inputs(1, 200), 4, "bucketed") is None # the adapter answers eagerly- assert answer is not None- assert torch.equal(answer, torch.full((1, 4), 2.0)) # the eager answer- assert runner.disabledassert not cuda_graphs_module._RECORDING_LOCK.locked()- runner.capture_error = None- assert runner.run(_inputs(1, 100), 4, "bucketed") is None- assert runner.recorded == []+ assert "failed for batch 1, length 224" in caplog.text+ assert runner.run(_inputs(1, 200), 4, "bucketed") is None # not tried again+ assert runner.run(_inputs(1, 100), 4, "bucketed") is not None # other graphs still replay+ assert runner.recorded == [(1, 128)]+ assert not runner.disabled+ assert runner.stats.recording_failures == 1+ assert runner.stats.eager == {"recording_failed": 1, "failed_shape": 1}++ def test_three_shapes_that_fail_to_record_turn_graphs_off(self, caplog: pytest.LogCaptureFixture) -> None:+ runner = _Runner()+ runner.run(_inputs(1, 32), 4, "bucketed")+ runner.keep_failing = True+ runner.capture_error = RuntimeError("operation not permitted when stream is capturing")- def test_an_eager_forward_that_fails_while_recording_turns_graphs_off(self) -> None:- runner = _Runner(fail=True)+ with caplog.at_level(logging.ERROR, logger=cuda_graphs_module.__name__):+ for length in (64, 96, 128):+ assert runner.run(_inputs(1, length), 4, "bucketed") is None- assert runner.run(_inputs(1, 100), 4, "bucketed") is None # the adapter runs it eagerlyassert runner.disabled+ assert runner.graph_count == 0+ assert "off for this process after 3 shapes failed to record" in caplog.text+ assert runner.run(_inputs(1, 32), 4, "bucketed") is None+ assert runner.stats.eager["disabled"] == 1++ def test_a_first_replay_that_fails_counts_as_a_failed_recording(self) -> None:+ runner = _Runner()+ runner.run(_inputs(1, 100), 4, "bucketed")+ runner.replay_error = RuntimeError("CUDA error: an illegal memory access was encountered")++ assert runner.run(_inputs(1, 200), 4, "bucketed") is None # the adapter answers eagerly++ assert set(runner._graphs) == {(1, 128)} # the new graph is not kept+ assert runner.stats.recording_failures == 1+ assert runner.stats.eager == {"recording_failed": 1}+ runner.replay_error = None+ assert runner.run(_inputs(1, 200), 4, "bucketed") is None # not recorded again+ assert runner.stats.eager["failed_shape"] == 1assert not cuda_graphs_module._RECORDING_LOCK.locked()- def test_running_out_of_memory_while_capturing_keeps_the_eager_answer_and_pauses(self) -> None:+ @pytest.mark.parametrize("first_use", [True, False], ids=["recording-forward", "later-forward"])+ def test_a_scoring_head_error_fails_only_its_forward(self, first_use: bool) -> None:+ # The head reads the caller's inputs, so its errors are the caller's:+ # the forward fails as it would eagerly, and no shape loses its graph.+ runner = _Runner()+ runner.run(_inputs(1, 32), 4, "bucketed")+ shapes = [(1, 64), (1, 96), (1, 128), (1, 160)]+ if not first_use:+ for _, length in shapes:+ runner.run(_inputs(1, length), 4, "bucketed")+ runner.head_error = IndexError("index 4 is out of bounds for dimension 1 with size 4")++ for _, length in shapes: # more than the three strikes that would turn graphs off+ with pytest.raises(IndexError):+ runner.run(_inputs(1, length), 4, "bucketed")++ assert runner.stats.recording_failures == 0+ assert runner._failed == set()+ assert not runner.disabled+ assert set(runner._graphs) == {(1, 32), *shapes} # the graphs are kept+ assert not cuda_graphs_module._RECORDING_LOCK.locked()+ runner.head_error = None+ replayed = runner.stats.replayed+ for _, length in shapes:+ assert runner.run(_inputs(1, length), 4, "bucketed") is not None+ assert runner.stats.replayed == replayed + len(shapes)++ def test_a_first_replay_that_runs_out_of_memory_reaches_oom_recovery(self) -> None:+ runner = _Runner()+ runner.run(_inputs(1, 100), 4, "bucketed")+ runner.replay_error = torch.cuda.OutOfMemoryError("CUDA out of memory")++ with pytest.raises(torch.cuda.OutOfMemoryError):+ runner.run(_inputs(1, 200), 4, "bucketed")++ assert (1, 224) not in runner._graphs+ assert runner.stats.recording_failures == 0+ assert not cuda_graphs_module._RECORDING_LOCK.locked()++ def test_running_out_of_memory_while_recording_pauses_recording(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 runner.run(_inputs(1, 200), 4, "bucketed") is None # answered eagerly, not an error- assert answer is not None- assert torch.equal(answer, torch.full((1, 4), 2.0)) # the eager answer, not an errorassert runner.graph_count == 0assert not runner.disabled+ assert runner.stats.drops == 1+ assert runner.stats.recording_failures == 0 # memory is not the shape's faultassert not cuda_graphs_module._RECORDING_LOCK.locked()# Recording pauses for a minute, then resumes.- runner.capture_error = Nonerunner.now += 59.0assert runner.run(_inputs(1, 300), 4, "bucketed") is Nonerunner.now += 2.0assert runner.run(_inputs(1, 300), 4, "bucketed") is not None- assert runner.recorded[-1] == (1, 320, 4)+ assert runner.recorded[-1] == (1, 320)@pytest.mark.parametrize(- "error",+ "inputs",[- torch.cuda.OutOfMemoryError("CUDA out of memory"),- RuntimeError("CUDA error: out of memory"),- RuntimeError("CUBLAS_STATUS_ALLOC_FAILED: failed to allocate workspace"),+ {**_inputs(1, 100), "class_input_ids": torch.ones(1, 4, dtype=torch.long)},+ {"input_ids": torch.ones(1, 100, dtype=torch.long)}, # the head needs the mask],+ ids=["extra-input", "no-mask"],)- def test_an_eager_forward_out_of_memory_while_recording_drops_the_graphs_and_raises(self, error: Exception) -> None:+ def test_unexpected_inputs_run_eagerly(self, inputs: dict[str, torch.Tensor]) -> 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()+ assert runner.run(inputs, 4, "bucketed") is None+ assert runner.recorded == []+ assert runner.stats.eager == {"unsupported_inputs": 1}- def test_unexpected_inputs_run_eagerly(self) -> None:+ def test_every_forward_counts_once(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 == []+ runner.run(_inputs(1, 100), 4, "bucketed") # recorded+ runner.run(_inputs(1, 100), 8, "bucketed") # replayed+ runner.run(_inputs(4, 512), 8, "bucketed") # too large+ runner.run(_inputs(4, 512), 8, "off") # opted out: not counted++ assert (runner.stats.recorded, runner.stats.replayed, runner.stats.eager) == (1, 1, {"too_large": 1})+ assert runner.stats.forwards == 3++ def test_the_runner_logs_its_counts_every_ten_minutes(self, caplog: pytest.LogCaptureFixture) -> None:+ runner = _Runner(name="knowledgator/gliclass-large-v1.0")++ with caplog.at_level(logging.INFO, logger=cuda_graphs_module.__name__):+ for _ in range(4):+ runner.run(_inputs(1, 100), 4, "bucketed")+ assert "forwards in the last" not in caplog.text+ runner.now += 600.0+ runner.run(_inputs(4, 512), 4, "bucketed")++ assert (+ "GLiClass CUDA graphs for knowledgator/gliclass-large-v1.0: 5 forwards in the last 600 s, 60.0% replayed"+ in (caplog.text)+ )class TestRecordingHooks:@@ -400,18 +615,61 @@ class TestRecordingHooks:assert encoder.get_rel_pos(hidden) == ("built", 7)assert model.model._create_segment_ids(torch.ones(1, 3, dtype=torch.long)) == "eager"+ assert model.model.process_encoder_output("ids", "mask", hidden, None, 3) == ("head", hidden)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.encodertable = 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]]))+ with runner._recording_on_this_thread(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]]))+ assert encoder.get_rel_pos(torch.zeros(1, 7, 4)) == ("built", 7)++ def test_while_recording_the_forward_stops_at_the_hidden_states(self) -> None:+ model = _model()+ runner = _Runner(model)+ hidden = torch.zeros(2, 7, 4)++ with runner._recording_on_this_thread(None):+ logits, *rest = model.model.process_encoder_output("ids", "mask", hidden, None, 3)++ assert logits is hidden+ assert rest == [None, None, None]++ def test_recording_diverts_only_the_recording_thread(self) -> None:+ # Another thread's eager forward of the same model, while a graph+ # records, must get logits, not the recording's hidden states.+ model = _model(segment_embeddings=True)+ runner = _Runner(model)+ encoder = model.model.encoder_model.encoder+ hidden = torch.zeros(2, 7, 4)+ seen: dict[str, Any] = {}++ def eager_forward() -> None:+ seen["head"] = model.model.process_encoder_output("ids", "mask", hidden, None, 3)+ seen["table"] = encoder.get_rel_pos(hidden)+ seen["segments"] = model.model._create_segment_ids(torch.ones(1, 3, dtype=torch.long))++ with runner._recording_on_this_thread(torch.arange(4)):+ other = threading.Thread(target=eager_forward)+ other.start()+ other.join()+ assert model.model.process_encoder_output("ids", "mask", hidden, None, 3)[0] is hidden++ assert seen == {"head": ("head", hidden), "table": ("built", 7), "segments": "eager"}++ def test_the_recording_state_is_cleared_when_recording_fails(self) -> None:+ runner = _Runner()++ with pytest.raises(RuntimeError), runner._recording_on_this_thread(torch.arange(4)):+ raise RuntimeError("capture failed")++ assert not runner._recording_here()@pytest.mark.parametrize(@@ -434,14 +692,18 @@ def test_segment_ids_are_the_libraries_own(rows: list[list[int]]) -> None:class _Pipe:+ """A gliclass pipe whose eager forward fails with ``error``, or answers with zeros."""+def __init__(self, error: Exception | None = None) -> None:- self.error = error or torch.cuda.OutOfMemoryError("CUDA out of memory")+ self.error = errordef _resolve_max_num_classes(self, labels: list[str], same_labels: bool) -> int:return len(labels)- def model(self, **_: Any) -> Any:- raise self.error+ def model(self, **inputs: Any) -> Any:+ if self.error is not None:+ raise self.error+ return SimpleNamespace(logits=torch.zeros(inputs["input_ids"].shape[0], inputs["max_num_classes"]))def _adapter_with(runner: _Runner) -> GLiClassAdapter:@@ -450,6 +712,9 @@ def _adapter_with(runner: _Runner) -> GLiClassAdapter:return adapter+_OOM = torch.cuda.OutOfMemoryError("CUDA out of memory")++def test_an_eager_out_of_memory_drops_the_graphs() -> None:runner = _Runner()runner.run(_inputs(1, 100), 2, "bucketed")@@ -457,10 +722,10 @@ def test_an_eager_out_of_memory_drops_the_graphs() -> None:runner._recording_credit = 0.0 # the next shape is not recorded and runs eagerlywith pytest.raises(torch.cuda.OutOfMemoryError):- _adapter_with(runner)._forward(_Pipe(), _inputs(1, 300), ["a", "b"], same_labels=True, graphs="bucketed")+ _adapter_with(runner)._forward(_Pipe(_OOM), _inputs(1, 300), ["a", "b"], same_labels=True, graphs="bucketed")assert runner.graph_count == 0- assert runner.recorded == [(1, 128, 2)]+ assert runner.recorded == [(1, 128)]assert not runner.disabled@@ -486,14 +751,25 @@ def test_other_eager_errors_keep_the_graphs() -> None:assert runner.graph_count == 1-def test_a_capture_out_of_memory_answers_eagerly_without_oom_recovery() -> None:+def test_a_recording_out_of_memory_answers_eagerly() -> None:runner = _Runner()- runner.capture_error = torch.cuda.OutOfMemoryError("CUDA out of memory")+ runner.capture_error = _OOM- # 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 torch.equal(logits, torch.zeros(1, 2)) # the eager forward's answer+ assert runner.graph_count == 0+ assert not runner.disabled+++def test_a_recording_out_of_memory_that_persists_reaches_oom_recovery() -> None:+ runner = _Runner()+ runner.run(_inputs(1, 100), 2, "bucketed")+ runner.capture_error = _OOM++ with pytest.raises(torch.cuda.OutOfMemoryError): # the eager forward also runs out+ _adapter_with(runner)._forward(_Pipe(_OOM), _inputs(1, 300), ["a", "b"], same_labels=True, graphs="bucketed")+assert runner.graph_count == 0assert not runner.disabled@@ -501,7 +777,7 @@ def test_a_capture_out_of_memory_answers_eagerly_without_oom_recovery() -> None: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")+ runner.replay_error = _OOMwith pytest.raises(torch.cuda.OutOfMemoryError):_adapter_with(runner)._forward(_Pipe(), _inputs(1, 100), ["a", "b"], same_labels=True, graphs="bucketed")@@ -509,6 +785,18 @@ def test_an_out_of_memory_error_in_a_replay_drops_the_graphs() -> None:assert runner.graph_count == 0+def test_the_adapter_passes_its_label_slots_to_the_head() -> None:+ runner = _Runner()++ logits = _adapter_with(runner)._forward(+ _Pipe(), _inputs(3, 100), ["a", "b", "c"], same_labels=True, graphs="bucketed"+ )++ assert logits.shape == (3, 3)+ assert runner.head_classes == [3]+ assert runner.recorded == [(4, 128)]++class TestOperatorSetting:"""Graphs are chosen when the model loads; a request can only opt out."""@@ -547,11 +835,12 @@ class TestOperatorSetting:def test_a_request_that_opts_out_runs_eagerly(self) -> None:runner = _Runner()runner.run(_inputs(1, 100), 2, "bucketed")+ replays = len(runner.replayed)- 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")+ logits = _adapter_with(runner)._forward(_Pipe(), _inputs(1, 100), ["a", "b"], same_labels=True, graphs="off")- assert runner.replayed == []+ assert torch.equal(logits, torch.zeros(1, 2))+ assert len(runner.replayed) == replaysdef test_shipped_profiles_enable_bucketed_graphs_only_where_measured() -> None:diff --git a/packages/sie_server/tests/adapters/test_gliclass_parity.py b/packages/sie_server/tests/adapters/test_gliclass_parity.pyindex 46664b53b..0cbe6a5ea 100644--- a/packages/sie_server/tests/adapters/test_gliclass_parity.py+++ b/packages/sie_server/tests/adapters/test_gliclass_parity.py@@ -400,9 +400,9 @@ def _fresh_runner(rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> Any: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)+ def counted(key: Any, entry: Any, inputs: dict[str, torch.Tensor], max_num_classes: int | None) -> torch.Tensor:+ runner.replayed.append(key)+ return replay(key, entry, inputs, max_num_classes)monkeypatch.setattr(runner, "_replay", counted)return runner@@ -433,7 +433,7 @@ def test_exact_cuda_graphs_score_bit_for_bit_like_eager(assert runner.replayed # the third pass replayedassert not runner.disabled# Graphs of one length share its relative-position table.- assert set(runner._relative_pos) == {length for _, length, _ in runner._graphs}+ assert set(runner._relative_pos) == {length for _, length in runner._graphs}@pytest.mark.gpu_hw@@ -463,6 +463,66 @@ def test_bucketed_cuda_graphs_stay_close_to_eager(assert not runner.disabled+def test_bucketed_graphs_serve_every_label_count(bucketed_rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> None:+ # Label counts do not enter a graph's shape: the scoring head runs eagerly+ # with each forward's own label slots. More labels only lengthen the+ # prompt, which can move a forward to a longer length bucket.+ texts = _TEXTS[:4]+ items = [Item(text=text) for text in texts]+ labels = [*_LABELS, "low", "high", "yes", "no"]+ runner = _fresh_runner(bucketed_rig, monkeypatch)+ pipe = bucketed_rig.adapter._pipe+ recorded = runner.stats.recorded+ shapes = set()+ for count in range(1, len(labels) + 1):+ batch, length = pipe.prepare_inputs(texts, labels[:count], same_labels=True)["input_ids"].shape+ shapes.add(runner.key(batch, length, "bucketed"))+ eager = bucketed_rig.adapter.extract(items, labels=labels[:count], options=_EAGER)+ for _ in range(2):+ graphed = bucketed_rig.adapter.extract(items, labels=labels[:count])+ for expected, got in zip(_scores(eager), _scores(graphed), strict=True):+ assert got == pytest.approx(expected, abs=2e-2)++ assert None not in shapes+ assert len(shapes) < len(labels)+ assert set(runner._graphs) == shapes+ assert runner.stats.recorded - recorded == len(shapes)+ assert not runner.disabled+++def test_a_bucketed_replay_scores_like_an_eager_forward_of_its_padded_shape(+ bucketed_rig: _Rig, monkeypatch: pytest.MonkeyPatch+) -> None:+ # The graph replays the encoder's kernels for the padded shape, and the+ # head runs eagerly on its output: bit-identical to an eager forward of+ # that shape when the batch is already a bucket.+ runner = _fresh_runner(bucketed_rig, monkeypatch)+ pipe = bucketed_rig.adapter._pipe+ with torch.inference_mode():+ inputs = dict(pipe.prepare_inputs(_TEXTS[:4], _LABELS, same_labels=True))+ batch, length = inputs["input_ids"].shape+ key = runner.key(batch, length, "bucketed")+ assert key is not None+ assert key[0] == batch+ assert key[1] > length # padded+ padded = {+ name: torch.nn.functional.pad(value, (0, key[1] - length), value=runner._pad_values[name])+ for name, value in inputs.items()+ }+ eager = pipe.model(**padded, max_num_classes=len(_LABELS)).logits+ before = (runner.stats.recorded, runner.stats.replayed)+ recorded = runner.run(dict(inputs), len(_LABELS), "bucketed")+ replayed = runner.run(dict(inputs), len(_LABELS), "bucketed")++ assert (runner.stats.recorded, runner.stats.replayed) == (before[0] + 1, before[1] + 1)+ assert recorded is not None+ assert replayed is not None+ assert torch.equal(recorded, eager)+ assert torch.equal(replayed, eager)++@pytest.mark.gpu_hwdef test_graphs_over_their_memory_budget_are_dropped(exact_rig: _Rig, monkeypatch: pytest.MonkeyPatch) -> None:items = [Item(text=text) for text in _TEXTS]@@ -549,17 +609,20 @@ def test_a_forward_that_cannot_be_recorded_falls_back_to_eager(monkeypatch: pytepytest.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._graphsassert 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.+ # while recording, which CUDA refuses: each shape then runs eagerly, and+ # after three such shapes the runner turns itself off.monkeypatch.setattr(runner, "_build_relative_pos", lambda hidden: None)- graphed = rig.adapter.extract(items, labels=_LABELS)+ for count in (1, 2, 3): # three batch sizes: three shapes+ eager = _outputs(rig.adapter.extract(items[:count], labels=_LABELS, options=_EAGER))+ assert _outputs(rig.adapter.extract(items[:count], labels=_LABELS)) == eager+ assert runner.disabled == (count == 3)- assert runner.disabled- assert _outputs(graphed) == eager+ assert runner.stats.recording_failures == 3+ assert runner.graph_count == 0assert _outputs(rig.adapter.extract(items, labels=_LABELS)) == eager