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): run GLiClass ModernBERT encoders through the flash-attention varlen stack (#414)
svonava77577f969ed6
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex ffedd7487..7bda0b778 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -167,9 +167,11 @@ profile, or send `options={"cuda_graphs": "off"}` with a request.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 instructmodels, 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.+ModernBERT-based models (the edge models, `gliclass-multilang-edge`, the Opir+edge models and `gliclass-modern-{base,large}-v3.0`), CPU and MPS run without+graphs with any value, and the load logs a warning. On CUDA, the+ModernBERT-based models can run their encoder on the flash-attention path+below instead.**Shapes.** A graph holds at most 2,048 tokens (batch size times paddedlength), or 1,024 for encoders wider than 768 such as DeBERTa-v3-large.@@ -234,6 +236,116 @@ replays, records, and runs eagerly (by reason: past the token bound, recordingpaused, budget full, and so on), and logs the counts every ten minutes while itserves requests.+### GLiClass ModernBERT flash attention++The GLiClass models built on ModernBERT or mmBERT (`gliclass-edge-v3.0`,+`gliclass-instruct-edge-v1.0`, `gliclass-multilang-edge`, `opir-edge-v1.0`,+`opir-edge-multilang-v1.0`, `gliclass-modern-base-v3.0` and+`gliclass-modern-large-v3.0`) can run their encoder through the+flash-attention layer stack that SIE's ModernBERT embedding, late-interaction,+cross-encoder and Laya adapters share. The rows of a forward are packed into+one token stream without padding, each row attends only to itself through+`flash_attn_varlen_func`, and the RoPE tables are built once, at load. The+gliclass scoring head (label-token features, pooling, projections and scorer)+runs unchanged on the encoder output. Label groups, instructions, examples,+overflow policies, usage and per-item errors behave as before. It is an+operator setting:++```yaml+profiles:+ default:+ adapter_options:+ loadtime:+ modernbert_flash: true+```++`modernbert_flash: single-label` limits it to single-label requests; a+request with `"classification_type": "multi-label"` then runs the gliclass+forward. It applies to float16 and bfloat16 weights on CUDA GPUs with flash-attn+(Ampere or newer). On CPU, MPS, older GPUs or without flash-attn, the model+runs the gliclass forward as before, and the load logs why. DeBERTa-based+models ignore the setting. If the flash path fails with an error other than+running out of memory, the gliclass forward answers that request, and the+model logs the error and stays on the gliclass forward until it is reloaded.+The shipped profiles enable it where the scores+met the margin rule below: for every request on `gliclass-modern-base-v3.0`,+and for single-label requests on `gliclass-multilang-edge` and+`gliclass-modern-large-v3.0`. The other four models keep the gliclass forward.++On a GPU with flash-attn, the gliclass forward already runs the Hugging Face+ModernBERT flash-attention path. That path unpads and repads every batch,+rotates queries and keys with one fused kernel per layer, and runs its MLPs+through `torch.compile`. Classification forwards are small, so the host+launching kernels, not the GPU, bounds most of them, and the flash path needs+less host time per forward. On an L4, a one-item `gliclass-edge-v3.0` forward+keeps the GPU busy for 2.4 ms of its 12.7 ms on the gliclass forward, and for+0.85 ms of 8.8 ms on the flash path. The flash path runs the rotation and the+MLP activation as several separate kernels, though, so larger forwards, which+the GPU bounds, are faster on the gliclass forward. A forward with more packed+tokens than a bound therefore runs the gliclass forward: 4,096 tokens for+encoders up to 384 wide, 2,048 up to 768, and 1,024 wider. On an L4,+`gliclass-modern-large-v3.0` is 1.13x faster on the flash path at 1,024+packed tokens and 0.90x at 1,289; `gliclass-modern-base-v3.0` is 1.27x at+2,048 and 0.96x at 2,560.++Latency is the median of 400 one-item requests on the CVE descriptions from+`examples/typed-decisions`: one question with eight labels, or three questions+as separate label groups. Each throughput request holds 64 items, one in eight+of them a long document, and one question. Both paths ran in one process on an+L4, from the gliclass forward to the flash path:++| Model | One item, one question | One item, three separate groups | 64 items per request |+|--|--|--|--|+| `gliclass-edge-v3.0` | 13.6 -> 11.1 ms | 15.1 -> 12.6 ms | 351 -> 397 items/s |+| `gliclass-instruct-edge-v1.0` | 14.2 -> 11.9 ms | 15.4 -> 13.1 ms | 334 -> 376 items/s |+| `gliclass-multilang-edge` | 25.8 -> 20.6 ms | 26.8 -> 21.6 ms | 235 -> 279 items/s |+| `opir-edge-v1.0` | 13.8 -> 11.3 ms | 14.9 -> 12.4 ms | 287 -> 313 items/s |+| `opir-edge-multilang-v1.0` | 28.4 -> 22.6 ms | 29.7 -> 24.0 ms | 207 -> 241 items/s |+| `gliclass-modern-base-v3.0` | 25.3 -> 19.9 ms | 26.7 -> 21.3 ms | 229 -> 253 items/s |+| `gliclass-modern-large-v3.0` | 32.3 -> 25.1 ms | 34.2 -> 27.1 ms | 173 -> 173 items/s |++**Scores.** The two paths round float16 sums differently. We compared them on+the 384 CVE descriptions from `examples/typed-decisions`, three questions+each: asked one at a time, with an instruction, with a few-shot example, as+separate and as joint groups, and in requests of eight, plus 65 long documents+under `truncate_text`. That is 7,497 answers per model. A shipped profile+enables the flash path only when the model meets the margin rule against the+gliclass forward: (i) no probability moves by more than 0.02, and (ii) every+answer whose top label changes had a top-two margin, on the gliclass forward,+smaller than the gliclass forward's own batching noise. The batching noise is+the largest probability change the gliclass forward shows between an item sent+alone and the same item in a request of eight with the same options, over the+same kinds of requests.++| Model | Largest probability change | Top label changed | Largest margin of a changed answer | Batching noise | Shipped profile |+|--|--|--|--|--|--|+| `gliclass-multilang-edge` | 0.015 | 18 | 0.0046 | 0.016 | on (single-label) |+| `gliclass-modern-base-v3.0` | 0.010 | 22 | 0.0029 | 0.0061 | on |+| `gliclass-modern-large-v3.0` | 0.015 | 4 | 0.0039 | 0.014 | on (single-label) |+| `gliclass-edge-v3.0` | 0.016 | 24 | 0.0098 | 0.0066 | off (2 answers over the noise) |+| `gliclass-instruct-edge-v1.0` | 0.012 | 5 | 0.0077 | 0.0062 | off (1 answer over the noise) |+| `opir-edge-v1.0` | 0.018 | 12 | 0.019 | 0.011 | off |+| `opir-edge-multilang-v1.0` | 0.037 | 30 | 0.028 | 0.032 | off |++Multi-label scores (independent sigmoids) were checked the same way, with the+rule read for the 0.5 threshold at which a multi-label group selects its+labels: (i) no score moves by more than 0.02, and (ii) every score that+crosses 0.5 was closer to 0.5 than the gliclass forward's own batching noise.+Each request kind was sent one item at a time and eight at a time, 59,220+scores per model:++| Model | Largest score change | Scores crossing 0.5 (largest distance from 0.5) | Batching noise | Multi-label |+|--|--|--|--|--|+| `gliclass-modern-base-v3.0` | 0.0088 | 18 (0.0020) | 0.0059 | flash |+| `gliclass-modern-large-v3.0` | 0.024 (joint groups) | 23 (0.0044) | 0.039 | gliclass forward |+| `gliclass-multilang-edge` | 0.039 (few-shot examples) | 18 (0.0073) | 0.032 | gliclass forward |++Usage and per-item errors were identical in every answer. Against the same+checkpoints in float32, the flash path is as accurate as the gliclass forward:+over the seven models, the gliclass forward's top label differs from float32+in 128 answers, the flash path's in 126. To run a model on the other path, set+`modernbert_flash` in its profile.+### GLiNER2.5-Decide usage and limitsThe GLiNER2.5-Decide models (`fastino/GLiNER2.5-Decide`, `GLiNER2.5-multi-Decide`,diff --git a/packages/sie_server/models/knowledgator__gliclass-modern-base-v3.0.yaml b/packages/sie_server/models/knowledgator__gliclass-modern-base-v3.0.yamlnew file mode 100644index 000000000..7520980de--- /dev/null+++ b/packages/sie_server/models/knowledgator__gliclass-modern-base-v3.0.yaml@@ -0,0 +1,30 @@+sie_id: knowledgator/gliclass-modern-base-v3.0+hf_id: knowledgator/gliclass-modern-base-v3.0+hf_revision: ac369222ca4375ca66ebaf7fb5220f223514c035+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server.adapters.gliclass:GLiClassAdapter+ adapter_options:+ loadtime:+ classification_type: single-label+ modernbert_flash: true+ runtime:+ threshold: 0.0+ multi-label:+ extends: default+ adapter_options:+ runtime:+ classification_type: multi-label+ threshold: 0.0diff --git a/packages/sie_server/models/knowledgator__gliclass-modern-large-v3.0.yaml b/packages/sie_server/models/knowledgator__gliclass-modern-large-v3.0.yamlnew file mode 100644index 000000000..89e97bf4b--- /dev/null+++ b/packages/sie_server/models/knowledgator__gliclass-modern-large-v3.0.yaml@@ -0,0 +1,30 @@+sie_id: knowledgator/gliclass-modern-large-v3.0+hf_id: knowledgator/gliclass-modern-large-v3.0+hf_revision: 668dd0d2a2c0d3a2cdc9231d539b42fde10e90ad+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server.adapters.gliclass:GLiClassAdapter+ adapter_options:+ loadtime:+ classification_type: single-label+ modernbert_flash: single-label+ runtime:+ threshold: 0.0+ multi-label:+ extends: default+ adapter_options:+ runtime:+ classification_type: multi-label+ threshold: 0.0diff --git a/packages/sie_server/models/knowledgator__gliclass-multilang-edge.yaml b/packages/sie_server/models/knowledgator__gliclass-multilang-edge.yamlindex 921138df3..3c0448bda 100644--- a/packages/sie_server/models/knowledgator__gliclass-multilang-edge.yaml+++ b/packages/sie_server/models/knowledgator__gliclass-multilang-edge.yaml@@ -19,6 +19,7 @@ profiles:adapter_options:loadtime:classification_type: single-label+ modernbert_flash: single-labelruntime:threshold: 0.0multi-label:diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.pyindex c60cb5558..64eb52e5e 100644--- a/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliclass/__init__.py@@ -75,6 +75,8 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters.errors import InputTooLongErrorfrom sie_server.adapters.gliclass.cuda_graphs import GRAPH_MODES, CudaGraphRunner, GraphMode, unsupported_reason+from sie_server.adapters.gliclass.modernbert_flash import ModernBertFlashEncoder+from sie_server.adapters.gliclass.modernbert_flash import unsupported_reason as flash_unsupported_reasonfrom sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.inference_output import ExtractItemError, ExtractOutputfrom sie_server.core.oom import is_oom_error@@ -459,7 +461,7 @@ class GLiClassAdapter(BaseAdapter):spec: ClassVar[AdapterSpec] = AdapterSpec(inputs=("text",),outputs=("json",),- unload_fields=("_pipe", "_tokenizer", "_graphs"),+ unload_fields=("_pipe", "_tokenizer", "_graphs", "_flash"),)def __init__(@@ -472,6 +474,7 @@ class GLiClassAdapter(BaseAdapter):compute_precision: ComputePrecision = "float16",revision: str | None = None,cuda_graphs: str | bool = "off",+ modernbert_flash: bool | str = False,**kwargs: Any,) -> None:"""Initialize GLiClass adapter.@@ -496,10 +499,18 @@ class GLiClassAdapter(BaseAdapter):(see ``cuda_graphs.py``). An operator setting: a request canonly opt out, with ``options={"cuda_graphs": "off"}``. YAMLreads an unquoted ``off`` as ``False``, which also means off.+ modernbert_flash: Whether a model with a ModernBERT or mmBERT+ encoder runs it through the packed flash-attention layer+ stack on CUDA (see ``modernbert_flash.py``): ``true`` for+ every request, ``"single-label"`` for single-label requests+ only (multi-label requests run the gliclass forward), or+ ``false``. Other models and devices run as before. An+ operator setting.**kwargs: Additional arguments (ignored for compatibility).Raises:- ValueError: If ``cuda_graphs`` is not one of the three modes.+ ValueError: If ``cuda_graphs`` is not one of the three modes, or+ ``modernbert_flash`` is not true, false or "single-label"."""self._model_name_or_path = str(model_name_or_path)self._classification_type = self._validate_classification_type(classification_type)@@ -513,6 +524,18 @@ class GLiClassAdapter(BaseAdapter):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)+ if not isinstance(modernbert_flash, bool) and modernbert_flash != "single-label":+ msg = f"GLiClass modernbert_flash must be true, false or 'single-label', got {modernbert_flash!r}"+ raise ValueError(msg)+ self._modernbert_flash = modernbert_flash+ # The classification types whose requests may use the flash encoder.+ self._flash_types: frozenset[ClassificationType] = (+ frozenset({"single-label", "multi-label"})+ if modernbert_flash is True+ else frozenset({"single-label"})+ if modernbert_flash == "single-label"+ else frozenset()+ )# The gliclass pipe for the model's architecture: it assembles and# tokenizes model inputs and holds the model.@@ -520,6 +543,9 @@ class GLiClassAdapter(BaseAdapter):# Records and replays forwards as CUDA graphs, when the operator# enabled them and the model and device support them.self._graphs: CudaGraphRunner | None = None+ # Runs a ModernBERT encoder on packed rows with flash attention, when+ # the operator enabled it and the model and device support it.+ self._flash: ModernBertFlashEncoder | None = Noneself._tokenizer: PreTrainedTokenizerBase | None = Noneself._special_count: int = 0self._max_token_chars: int = _DEFAULT_MAX_TOKEN_CHARS@@ -591,6 +617,7 @@ class GLiClassAdapter(BaseAdapter):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)+ self._flash = self._flash_encoder(pipe)def _load_tokenizer(self, shared_kwargs: dict[str, Any]) -> PreTrainedTokenizerBase:try:@@ -784,6 +811,7 @@ class GLiClassAdapter(BaseAdapter):overflow_policy = opts.get("overflow_policy", DEFAULT_OVERFLOW_POLICY)graphs = self._request_cuda_graphs(opts)+ flash = classification_type in self._flash_typestokens = _RequestTokens(self._tokenizer, self._visible_tokens())if label_groups is not None and group_encoding == "separate":@@ -798,6 +826,7 @@ class GLiClassAdapter(BaseAdapter):overflow_policy=overflow_policy,tokens=tokens,graphs=graphs,+ flash=flash,)texts = [tokens.visible(text) or text for text in texts]@@ -814,7 +843,14 @@ class GLiClassAdapter(BaseAdapter):if label_groups is not None:rows = (self._joint_scores(- kept_texts, label_groups, normalized_labels, classification_type, prompt, examples, graphs=graphs+ kept_texts,+ label_groups,+ normalized_labels,+ classification_type,+ prompt,+ examples,+ graphs=graphs,+ flash=flash,)if kept_textselse []@@ -846,6 +882,7 @@ class GLiClassAdapter(BaseAdapter):prompt=prompt,examples=examples,graphs=graphs,+ flash=flash,)all_classifications: list[list[Classification]] = [[] for _ in items]@@ -922,6 +959,7 @@ class GLiClassAdapter(BaseAdapter):examples: list[dict[str, Any]] | list[list[dict[str, Any]]] | None,batch_size: int = _PIPELINE_BATCH_SIZE,graphs: GraphMode = "off",+ flash: bool = True,) -> list[list[float]]:"""Each row's label scores, computed as the gliclass pipeline computes them.@@ -945,7 +983,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, graphs=graphs)+ logits = self._forward(pipe, inputs, batch_labels, same_labels=shared, graphs=graphs, flash=flash)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 Nonerows: list[torch.Tensor] = []@@ -975,12 +1013,15 @@ class GLiClassAdapter(BaseAdapter):*,same_labels: bool,graphs: GraphMode = "off",+ flash: bool = True,) -> 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 encoderwhen the model and shape allow it, and the scoring head runs on itsoutput with this forward's class slots; otherwise it runs eagerly.+ A model loaded with ``modernbert_flash`` runs its encoder on packed+ rows instead, and the scoring head the same way."""forward_kwargs: dict[str, Any] = {}resolve_max_num_classes = getattr(pipe, "_resolve_max_num_classes", None)@@ -988,6 +1029,16 @@ class GLiClassAdapter(BaseAdapter):forward_kwargs["max_num_classes"] = resolve_max_num_classes(labels, same_labels)classes = forward_kwargs.get("max_num_classes")try:+ runner = self._flash if flash else None+ if runner is not None:+ try:+ logits = runner.run(inputs, classes)+ except Exception as exc:+ if is_oom_error(exc):+ raise+ logits = self._answer_flash_failure(pipe, inputs, forward_kwargs, exc)+ if logits is not None:+ return logitsif self._graphs is not None:logits = self._graphs.run(dict(inputs), classes, graphs)if logits is not None:@@ -1023,6 +1074,44 @@ class GLiClassAdapter(BaseAdapter):name=self._model_name_or_path,)+ def _answer_flash_failure(+ self, pipe: Any, inputs: Any, forward_kwargs: dict[str, Any], error: Exception+ ) -> torch.Tensor:+ """Answer a forward the flash encoder failed with the gliclass forward.++ When the gliclass forward succeeds, the failure was the flash path's:+ it is logged and the model runs the gliclass forward from then on. When+ the gliclass forward fails too, the input is at fault; its error+ propagates as it always has, and the flash encoder stays on.+ """+ logits = pipe.model(**inputs, **forward_kwargs).logits+ self._flash = None+ logger.error(+ "GLiClass flash encoder failed for %s on a forward the gliclass forward answers; "+ "the model runs the gliclass forward from now on",+ self._model_name_or_path,+ exc_info=error,+ )+ return logits++ def _flash_encoder(self, pipe: Any) -> ModernBertFlashEncoder | None:+ """The packed flash-attention encoder for a loaded model; None when it is off or does not apply."""+ model = getattr(pipe, "model", None)+ if not self._modernbert_flash or model is None:+ return None+ device = getattr(pipe, "device", "cpu")+ reason = flash_unsupported_reason(model, device)+ if reason is not None:+ # Off CUDA this is the expected fallback; on CUDA it is worth a look.+ log = logger.info if not str(device).startswith("cuda") else logger.warning+ log(+ "GLiClass modernbert_flash does not apply to %s, which runs the gliclass forward: %s",+ self._model_name_or_path,+ reason,+ )+ return None+ return ModernBertFlashEncoder(model, max_length=int(pipe.max_length))+@staticmethoddef _row_width(pipe: Any, labels: list[str], batch_width: int) -> int:"""Class slots a forward over only this row's labels would score.@@ -1045,6 +1134,7 @@ class GLiClassAdapter(BaseAdapter):examples: list[dict[str, Any]] | None,*,graphs: GraphMode = "off",+ flash: bool = True,) -> list[list[float]]:"""Score all groups' labels in one row per text and normalize per group.@@ -1068,7 +1158,7 @@ class GLiClassAdapter(BaseAdapter):examples=examples,prompt=prompt,)- logits = self._forward(pipe, inputs, flat_labels, same_labels=True, graphs=graphs)+ logits = self._forward(pipe, inputs, flat_labels, same_labels=True, graphs=graphs, flash=flash)if logits.shape[-1] < num_labels:raise InputTooLongError(_ERR_INPUT_TOO_LONG)chunks.append(logits[:, :num_labels].float())@@ -1097,6 +1187,7 @@ class GLiClassAdapter(BaseAdapter):overflow_policy: OverflowPolicy,tokens: _RequestTokens,graphs: GraphMode = "off",+ flash: bool = True,) -> ExtractOutput:"""Encode the document once per group, with only that group's labels.@@ -1180,6 +1271,7 @@ class GLiClassAdapter(BaseAdapter):group_examples=group_examples,row_lengths=None if item_lengths is None else [item_lengths[index] for index in kept],graphs=graphs,+ flash=flash,)return self._grouped_output(rows,@@ -1202,6 +1294,7 @@ class GLiClassAdapter(BaseAdapter):group_examples: list[list[dict[str, Any]]] | None,row_lengths: list[list[int]] | None = None,graphs: GraphMode = "off",+ flash: bool = True,) -> list[list[float]]:"""Scores of every (item, group) row, flattened per item in group order.@@ -1237,6 +1330,7 @@ class GLiClassAdapter(BaseAdapter):examples=None if row_examples is None else [row_examples[row] for row in chunk],batch_size=len(chunk),graphs=graphs,+ flash=flash,)for row, row_scores in zip(chunk, scored, strict=True):per_row[row] = row_scores@@ -1249,6 +1343,7 @@ class GLiClassAdapter(BaseAdapter):prompt=prompt,examples=group_examples[group] if group_examples is not None else None,graphs=graphs,+ flash=flash,)for group, (_, group_labels) in enumerate(label_groups)]diff --git a/packages/sie_server/src/sie_server/adapters/gliclass/modernbert_flash.py b/packages/sie_server/src/sie_server/adapters/gliclass/modernbert_flash.pynew file mode 100644index 000000000..a5947e520--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/gliclass/modernbert_flash.py@@ -0,0 +1,231 @@+"""Flash-attention varlen encoder for GLiClass models with a ModernBERT backbone.++GLiClass models built on ModernBERT or mmBERT (the edge models,+``gliclass-multilang-edge``, the Opir edge models, ``gliclass-modern-base-v3.0``+and ``gliclass-modern-large-v3.0``) run their encoder through the Hugging Face+``ModernBertModel`` forward. With flash-attn on CUDA, that forward unpads and+repads the batch around every call and runs its MLPs through ``torch.compile``+guards. At the batch sizes classification traffic has, the host launching+kernels bounds a forward, and the GPU mostly waits.++This runner feeds the same weights through SIE's shared ModernBERT layer loop+(``sie_server.adapters._modernbert_flash``, also used by the dense, late+interaction, cross-encoder and Laya adapters): one packed, unpadded token+stream through ``flash_attn_varlen_func``, with RoPE tables built once at load.+The encoder output is repadded, with zeros at padded positions as the Hugging+Face flash-attention forward leaves them, and the gliclass scoring head runs+unchanged on it: label-token features, pooling, projections and scorer are the+library's own code with the forward's own inputs and label slots.++What the encoder computes is the Hugging Face forward's math: token embeddings+(plus segment embeddings on instruct models) and the embedding norm, the+pre-norm layers with global attention every ``global_attn_every_n_layers``+layers and a sliding window of ``local_attention`` tokens elsewhere, each with+its RoPE base, then the final norm. Scores differ from the Hugging Face path+only by floating-point rounding.++Past a number of packed tokens that depends on the encoder's width, the GPU,+not kernel launches, bounds a forward (``token_bound``). There the Hugging+Face path is faster: it rotates queries and keys with one fused kernel per+layer and compiles its MLPs, where the shared layer loop runs each step as its+own kernel. Such forwards run the gliclass forward. On an L4, the flash path+runs a ``gliclass-modern-large-v3.0`` forward (1,024 wide) 1.13x as fast at+1,024 packed tokens and 0.90x at 1,289, a ``gliclass-modern-base-v3.0``+forward (768 wide) 1.27x at 2,048 and 0.96x at 2,560, and the 384-wide edge+models 1.3x at about 3,650 tokens and 0.81x at 5,700 on 22 layers.++Operators enable it per model, at load, with+``adapter_options.loadtime.modernbert_flash: true``, or ``single-label`` to+keep multi-label requests on the gliclass forward. It applies to uni-encoder+models whose encoder is a ModernBERT (mmBERT included) with float16 or bfloat16+weights, on a CUDA device with flash-attn; anything else runs the gliclass+forward as before, and the load logs why. So does a model that scores+intermediate encoder layers (``squeeze_layers`` or ``encoder_layer_id``),+which no published checkpoint does. A forward whose inputs the runner does not+recognise (other input tensors, rows that are not right-padded) runs the+gliclass forward too. When the flash path raises anything but an out-of-memory+error, the adapter answers that forward with the gliclass forward and, if that+succeeds, logs the failure and turns the flash path off for the model.+"""++from __future__ import annotations++import logging+from collections.abc import Mapping+from dataclasses import dataclass, field+from typing import Any, Literal++import torch++from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._modernbert_flash import (+ modernbert_rope_cos_sin,+ modernbert_rope_theta,+ run_modernbert_flash_layers,+)+from sie_server.adapters.gliclass.cuda_graphs import segment_ids++logger = logging.getLogger(__name__)++# ``encoder_config.model_type`` of the encoders this runner drives. mmBERT+# checkpoints are ModernBERT models with another vocabulary and RoPE bases.+_ENCODERS = frozenset({"modernbert"})+_DTYPES = frozenset({torch.float16, torch.bfloat16})+_INPUTS = frozenset({"input_ids", "attention_mask"})++# Why a forward ran the gliclass forward instead.+EagerReason = Literal[+ "unsupported_inputs", # inputs other than token ids and mask, or not a 2-D batch+ "not_right_padded", # a row's mask is not a run of ones followed by zeros+ "too_long", # a row longer than the RoPE tables, which cover the model window+ "too_large", # more packed tokens than the token bound+]+++def token_bound(hidden_size: int) -> int:+ """Packed tokens a flash forward of an encoder this wide may hold (see the module docstring)."""+ if hidden_size <= 384:+ return 4096+ if hidden_size <= 768:+ return 2048+ return 1024+++def unsupported_reason(model: Any, device: str | torch.device) -> str | None:+ """Why ``model`` cannot run its encoder through this runner on ``device``; None when it can."""+ if not str(device).startswith("cuda"):+ return "flash attention needs a CUDA device"+ # Imported here: sie_server.core.inference imports the model loader, which imports adapters.+ from sie_server.core.inference import is_flash_attention_available++ if not is_flash_attention_available(str(device)):+ return "flash-attn is not installed, or the GPU predates Ampere"+ 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 a ModernBERT"+ if getattr(config, "squeeze_layers", False) or getattr(config, "encoder_layer_id", -1) not in (-1, None):+ return "the model scores intermediate encoder layers"+ inner = getattr(model, "model", None)+ encoder = getattr(inner, "encoder_model", None)+ embeddings = getattr(encoder, "embeddings", None)+ if not all(hasattr(encoder, name) for name in ("layers", "final_norm")) or not hasattr(embeddings, "norm"):+ return "the encoder is not a Hugging Face ModernBertModel"+ if not callable(getattr(inner, "process_encoder_output", None)):+ return "the model has no scoring head to run apart from its encoder"+ dtype = embeddings.tok_embeddings.weight.dtype+ if dtype not in _DTYPES:+ return f"flash attention needs float16 or bfloat16 weights, not {dtype}"+ return None+++@dataclass+class FlashStats:+ """Forwards the runner was offered since the model loaded: run here, or eagerly by reason."""++ flash: int = 0+ eager: dict[str, int] = field(default_factory=dict)+++class ModernBertFlashEncoder:+ """Runs a GLiClass uni-encoder forward with its ModernBERT encoder on packed, unpadded rows.++ ``max_length`` is the model window: the longest row the RoPE tables cover.+ The runner holds no per-forward state, so threads may share it.+ """++ def __init__(self, model: Any, *, max_length: int) -> None:+ self._inner = model.model+ self._config = model.config+ self._encoder = self._inner.encoder_model+ self._segments = bool(getattr(self._config, "use_segment_embeddings", False))+ self._max_length = max_length+ encoder_config = self._encoder.config+ weight = self._encoder.embeddings.tok_embeddings.weight+ positions = torch.arange(max_length, device=weight.device)+ head_dim = encoder_config.hidden_size // encoder_config.num_attention_heads+ self._max_tokens = token_bound(encoder_config.hidden_size)+ # Per-position cos/sin tables for the global and the sliding-window+ # layers, each with its own RoPE base, in the weights' dtype.+ self._rope = {+ kind: modernbert_rope_cos_sin(+ positions,+ head_dim=head_dim,+ theta=modernbert_rope_theta(encoder_config, use_global=kind == "global"),+ dtype=weight.dtype,+ )+ for kind in ("global", "local")+ }+ self.stats = FlashStats()++ def run(self, inputs: Mapping[str, torch.Tensor], max_num_classes: int | None) -> torch.Tensor | None:+ """Logits for a padded batch of token ids, or None to run the gliclass forward.++ ``max_num_classes`` is the forward's label-slot count, passed to the+ scoring head as the gliclass forward passes it.+ """+ logits, reason = self._run(inputs, max_num_classes)+ if reason is not None:+ self.stats.eager[reason] = self.stats.eager.get(reason, 0) + 1+ else:+ self.stats.flash += 1+ return logits++ def _run(+ self, inputs: Mapping[str, torch.Tensor], max_num_classes: int | None+ ) -> tuple[torch.Tensor | None, EagerReason | None]:+ input_ids = inputs.get("input_ids")+ attention_mask = inputs.get("attention_mask")+ if input_ids is None or attention_mask is None or set(inputs) - _INPUTS or input_ids.dim() != 2:+ return None, "unsupported_inputs"+ batch, length = input_ids.shape+ # The row lengths, read once from the device: the packed layout's+ # shape. Nothing is queued ahead of this forward but its input copies.+ mask = attention_mask.cpu()+ lengths = mask.sum(dim=1)+ if not torch.equal(mask.bool(), torch.arange(length)[None, :] < lengths[:, None]):+ return None, "not_right_padded"+ max_seqlen = int(lengths.max()) if batch else 0+ if max_seqlen > self._max_length:+ return None, "too_long"+ total_tokens = int(lengths.sum())+ if not total_tokens:+ return None, "unsupported_inputs"+ if total_tokens > self._max_tokens:+ return None, "too_large"+ device = input_ids.device+ cu_seqlens = torch.zeros(batch + 1, dtype=torch.int32)+ cu_seqlens[1:] = torch.cumsum(lengths, dim=0)+ cu_seqlens = cu_seqlens.to(device)+ positions = build_position_ids(cu_seqlens, total_tokens=total_tokens)+ rows = torch.repeat_interleave(+ torch.arange(batch, device=device), cu_seqlens[1:] - cu_seqlens[:-1], output_size=total_tokens+ )++ encoder = self._encoder+ hidden = encoder.embeddings.tok_embeddings(input_ids[rows, positions])+ if self._segments:+ # As the uni-encoder forward adds them before the encoder's own+ # embedding norm. Segment ids depend on a whole padded row.+ hidden = hidden + self._inner.segment_embeddings(segment_ids(input_ids, self._config)[rows, positions])+ hidden = encoder.embeddings.norm(hidden)+ global_cos, global_sin = self._rope["global"]+ local_cos, local_sin = self._rope["local"]+ hidden = run_modernbert_flash_layers(+ encoder,+ hidden,+ cu_seqlens,+ max_seqlen,+ total_tokens,+ global_cos[positions],+ global_sin[positions],+ local_cos[positions],+ local_sin[positions],+ )+ hidden = encoder.final_norm(hidden)+ padded = hidden.new_zeros(batch, length, hidden.shape[-1])+ padded[rows, positions] = hidden+ logits = self._inner.process_encoder_output(input_ids, attention_mask, padded, None, max_num_classes)[0]+ return logits, Nonediff --git a/packages/sie_server/tests/adapters/test_gliclass_modernbert_flash.py b/packages/sie_server/tests/adapters/test_gliclass_modernbert_flash.pynew file mode 100644index 000000000..d7b668e46--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliclass_modernbert_flash.py@@ -0,0 +1,573 @@+"""GLiClass models with a ModernBERT encoder on the packed flash-attention path, against the gliclass forward.++The CPU tests stand a small reference for ``flash_attn_varlen_func`` in for the+kernel, so they check what the runner feeds the shared ModernBERT layer loop+and what it does with the result: packing, positions and RoPE bases, sliding+windows, segment embeddings, repadding, and the scoring head's inputs. The+tiny models have the head layouts of the published ModernBERT checkpoints.+The ``gpu_hw`` test runs the real kernel in float16.+"""++from __future__ import annotations++import logging+import sys+import types+from itertools import pairwise+from pathlib import Path+from typing import Any++import pytest+import torch+from gliclass import GLiClassModel, GLiClassModelConfig, ZeroShotClassificationPipeline+from sie_server.adapters.gliclass import GLiClassAdapter+from sie_server.adapters.gliclass.modernbert_flash import ModernBertFlashEncoder, token_bound, unsupported_reason+from sie_server.core import inference+from sie_server.core.loader import _build_adapter_kwargs, load_model_configs, reject_unknown_loadtime_options+from sie_server.types.inputs import Item+from tokenizers import Tokenizer, models, pre_tokenizers, processors+from torch.nn import functional+from transformers import DebertaV2Config, ModernBertConfig, ModernBertModel, PreTrainedTokenizerFast++_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+# The shipped profiles that load with the flash encoder, and for which requests:+# the ModernBERT and mmBERT GLiClass models whose flash scores met the margin+# rule against the gliclass forward, single-label only where multi-label+# scores did not (see the server README).+_FLASH_BY_DEFAULT: dict[str, bool | str] = {+ "knowledgator/gliclass-modern-base-v3.0": True,+ "knowledgator/gliclass-modern-large-v3.0": "single-label",+ "knowledgator/gliclass-multilang-edge": "single-label",+}++_MAX_LENGTH = 64+# Lengths from a few tokens to past the window, so rows pad against each other+# and span several sliding windows of the local layers.+_TEXTS: list[str] = [f"the app crashes on startup {'when config file is missing ' * i}".strip() for i in range(11)]+_LONG_TEXT: str = " ".join(["when config file is missing"] * 40)+_LABELS = ["billing", "bug report", "feature request"]+_GROUPS = {"topic": _LABELS, "urgency": ["low", "high"], "remote": ["yes", "no", "can exploit it over network"]}+_EXAMPLES = [{"text": "charged twice for one order", "labels": ["billing"]}]+_INSTRUCTION = "classify the ticket"+_WORDS = sorted(+ {+ word+ for text in [*_TEXTS, _LONG_TEXT, _EXAMPLES[0]["text"], _INSTRUCTION, *(x for v in _GROUPS.values() for x in v)]+ for word in text.split()+ }+)+# Head layouts of the published ModernBERT GLiClass checkpoints.+_LAYOUTS: dict[str, dict[str, Any]] = {+ # gliclass-edge-v3.0, opir-edge-v1.0+ "edge": {"prompt_first": True, "scorer_type": "mlp", "pooling_strategy": "first"},+ # gliclass-instruct-edge-v1.0: segment embeddings, averaged label tokens+ "instruct": {+ "prompt_first": True,+ "scorer_type": "mlp",+ "pooling_strategy": "first",+ "class_token_pooling": "average",+ "use_segment_embeddings": True,+ },+ # gliclass-multilang-edge, opir-edge-multilang-v1.0: text tokens through a cross-attention scorer+ "multilang": {+ "prompt_first": True,+ "scorer_type": "cross-attn",+ "pooling_strategy": "pass",+ "class_token_pooling": "average",+ "extract_text_features": True,+ },+ # gliclass-modern-{base,large}-v3.0 score with a dot product; text first exercises the other order+ "text-first": {"prompt_first": False, "scorer_type": "simple", "pooling_strategy": "first"},+}+_REQUESTS: dict[str, dict[str, Any]] = {+ "labels": {"labels": _LABELS},+ "multi-label": {"labels": _LABELS, "options": {"classification_type": "multi-label"}},+ "instruction": {"labels": _LABELS, "instruction": _INSTRUCTION},+ "examples": {"labels": _LABELS, "options": {"examples": _EXAMPLES}},+ "separate": {"options": {"label_groups": _GROUPS}},+ "joint": {"options": {"label_groups": _GROUPS, "group_encoding": "joint"}},+ "joint-examples": {+ "options": {+ "label_groups": _GROUPS,+ "group_encoding": "joint",+ "examples": [{"text": "charged twice for one order", "labels": {"topic": "billing"}}],+ }+ },+}+++def _reference_varlen(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ *,+ cu_seqlens_q: torch.Tensor,+ cu_seqlens_k: torch.Tensor,+ max_seqlen_q: int,+ max_seqlen_k: int,+ causal: bool,+ softmax_scale: float,+ window_size: tuple[int, int] = (-1, -1),+) -> torch.Tensor:+ """``flash_attn_varlen_func`` for packed ``[tokens, heads, dim]`` rows, one sequence at a time."""+ assert not causal+ assert torch.equal(cu_seqlens_q, cu_seqlens_k)+ bounds = cu_seqlens_q.tolist()+ lengths = [end - start for start, end in pairwise(bounds)]+ assert max(lengths) == max_seqlen_q == max_seqlen_k+ out = torch.empty_like(query)+ for start, end in pairwise(bounds):+ rows = [t[start:end].transpose(0, 1) for t in (query, key, value)]+ mask = None+ if window_size != (-1, -1):+ positions = torch.arange(end - start, device=query.device)+ mask = (positions[:, None] - positions[None, :]).abs() <= window_size[0]+ attended = functional.scaled_dot_product_attention(*rows, attn_mask=mask, scale=softmax_scale)+ out[start:end] = attended.transpose(0, 1)+ return out+++def reference_flash(monkeypatch: pytest.MonkeyPatch) -> None:+ # Hugging Face's ModernBERT module probes for flash-attn when it is first+ # imported; the module-scope ``ModernBertModel`` import has already done+ # that, so the stand-in below is never probed.+ module = types.ModuleType("flash_attn")+ module.flash_attn_varlen_func = _reference_varlen # ty: ignore[unresolved-attribute]+ monkeypatch.setitem(sys.modules, "flash_attn", module)+++def _tokenizer() -> PreTrainedTokenizerFast:+ specials = ["[PAD]", "[UNK]", "[CLS]", "[SEP]"]+ vocab = {token: index for index, token in enumerate([*specials, *_WORDS, ".", ",", ":"])}+ backend = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]")) # noqa: S106 -- a vocabulary entry, not a secret+ backend.pre_tokenizer = pre_tokenizers.Whitespace()+ backend.post_processor = processors.TemplateProcessing(+ single="[CLS] $A [SEP]",+ pair="[CLS] $A [SEP] $B [SEP]",+ special_tokens=[("[CLS]", vocab["[CLS]"]), ("[SEP]", vocab["[SEP]"])],+ )+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object=backend,+ pad_token="[PAD]", # noqa: S106 -- vocabulary entries, not secrets+ unk_token="[UNK]", # noqa: S106+ cls_token="[CLS]", # noqa: S106+ sep_token="[SEP]", # noqa: S106+ # As ModernBERT tokenizers: no token type ids.+ model_input_names=["input_ids", "attention_mask"],+ )+ tokenizer.add_tokens(["<<LABEL>>", "<<SEP>>", "<<EXAMPLE>>"], special_tokens=True)+ tokenizer.model_max_length = _MAX_LENGTH+ return tokenizer+++def _encoder_config(tokenizer: PreTrainedTokenizerFast) -> ModernBertConfig:+ config = ModernBertConfig(+ vocab_size=len(tokenizer),+ hidden_size=32,+ intermediate_size=48,+ num_hidden_layers=3,+ num_attention_heads=2,+ max_position_embeddings=128,+ # Layers 0 and 2 attend globally, layer 1 through a window of 4 tokens+ # each side; the two RoPE bases differ, as in ModernBERT.+ global_attn_every_n_layers=2,+ local_attention=8,+ global_rope_theta=160000.0,+ local_rope_theta=10000.0,+ pad_token_id=tokenizer.pad_token_id,+ bos_token_id=tokenizer.cls_token_id,+ cls_token_id=tokenizer.cls_token_id,+ eos_token_id=tokenizer.sep_token_id,+ sep_token_id=tokenizer.sep_token_id,+ reference_compile=False,+ )+ config._attn_implementation = "sdpa"+ return config+++def _model(tokenizer: PreTrainedTokenizerFast, **layout: Any) -> GLiClassModel:+ torch.manual_seed(0)+ config = GLiClassModelConfig(+ encoder_config=_encoder_config(tokenizer),+ encoder_model="tiny-modernbert-not-on-disk",+ class_token_index=tokenizer.convert_tokens_to_ids("<<LABEL>>"),+ text_token_index=tokenizer.convert_tokens_to_ids("<<SEP>>"),+ example_token_index=tokenizer.convert_tokens_to_ids("<<EXAMPLE>>"),+ vocab_size=len(tokenizer),+ scorer_mlp_hidden_size=32,+ scorer_num_heads=2,+ dropout=0.0,+ **layout,+ )+ model = GLiClassModel(config).eval()+ with torch.no_grad():+ # At initialization scale, attention is nearly uniform and segment+ # embeddings are small, so positions, RoPE bases, windows and segment+ # ids barely move scores. Larger weights make each of them visible.+ for layer in model.model.encoder_model.layers:+ layer.attn.Wqkv.weight.normal_(std=0.3)+ segments = getattr(model.model, "segment_embeddings", None)+ if segments is not None:+ segments.weight.normal_(std=1.0)+ return model+++class _Rig:+ """A tiny ModernBERT GLiClass model behind two adapters: the gliclass forward and the flash encoder."""++ def __init__(self, layout: str, *, device: str = "cpu", dtype: torch.dtype = torch.float32) -> None:+ tokenizer = _tokenizer()+ self.model = _model(tokenizer, **_LAYOUTS[layout]).to(device, dtype=dtype)+ assert isinstance(self.model.model.encoder_model, ModernBertModel)+ pipe = ZeroShotClassificationPipeline(+ self.model,+ tokenizer,+ max_length=_MAX_LENGTH,+ classification_type="single-label",+ device=device,+ progress_bar=False,+ ).pipe+ self.eager = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH)+ self.eager._attach(pipe, tokenizer)+ self.flash = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH, modernbert_flash=True)+ self.flash._attach(pipe, tokenizer)+ if device == "cpu":+ # Off CUDA the adapter keeps the gliclass forward; drive the runner directly.+ assert self.flash._flash is None+ self.flash._flash = ModernBertFlashEncoder(self.model, max_length=_MAX_LENGTH)+ assert self.flash._flash is not None+ self.runner: ModernBertFlashEncoder = self.flash._flash+++def _answers(output: Any) -> list[dict[str, float]]:+ if output.data:+ return [+ {f"{group}.{label}": p for group, answer in row.items() for label, p in answer["probabilities"].items()}+ for row in output.data+ ]+ return [{c["label"]: c["score"] for c in row} for row in output.classifications]+++def _assert_close(eager: Any, flash: Any, *, abs_tol: float) -> None:+ assert flash.input_token_counts == eager.input_token_counts+ assert flash.errors == eager.errors+ for expected, got in zip(_answers(eager), _answers(flash), strict=True):+ assert got.keys() == expected.keys()+ for label, probability in expected.items():+ assert got[label] == pytest.approx(probability, abs=abs_tol), label++[email protected](scope="module", params=list(_LAYOUTS))+def rig(request: pytest.FixtureRequest) -> _Rig:+ return _Rig(request.param)++[email protected]("request_kwargs", list(_REQUESTS.values()), ids=list(_REQUESTS))+def test_flash_encoder_scores_like_the_gliclass_forward(+ rig: _Rig, reference_flash: None, request_kwargs: dict[str, Any]+) -> None:+ # Eleven texts of different lengths: padded forwards of eight and three rows.+ items = [Item(text=text) for text in _TEXTS]+ before = rig.runner.stats.flash++ flash = rig.flash.extract(items, **request_kwargs)++ assert rig.runner.stats.flash > before+ assert not rig.runner.stats.eager+ _assert_close(rig.eager.extract(items, **request_kwargs), flash, abs_tol=1e-5)+++def test_truncated_long_documents_score_like_the_gliclass_forward(rig: _Rig, reference_flash: None) -> None:+ items = [Item(text=_LONG_TEXT), Item(text=_TEXTS[0]), Item(text=_LONG_TEXT + " the app crashes")]+ for kwargs in (_REQUESTS["labels"], _REQUESTS["separate"], _REQUESTS["joint"]):+ request: dict[str, Any] = {+ **kwargs,+ "options": {**kwargs.get("options", {}), "overflow_policy": "truncate_text"},+ }+ _assert_close(rig.eager.extract(items, **request), rig.flash.extract(items, **request), abs_tol=1e-5)+ assert not rig.runner.stats.eager+++def test_the_scoring_head_reads_zeros_at_padded_positions(reference_flash: None) -> None:+ rig = _Rig("edge")+ head = rig.model.model.process_encoder_output+ seen: list[torch.Tensor] = []++ def spy(input_ids: Any, attention_mask: torch.Tensor, encoder_layer: torch.Tensor, *args: Any) -> Any:+ seen.append(encoder_layer[attention_mask == 0])+ return head(input_ids, attention_mask, encoder_layer, *args)++ rig.model.model.process_encoder_output = spy+ try:+ rig.flash.extract([Item(text=_TEXTS[0]), Item(text=_TEXTS[6])], labels=_LABELS)+ finally:+ rig.model.model.process_encoder_output = head+ assert seen[0].numel() > 0+ assert torch.count_nonzero(seen[0]) == 0+++def _padded(rig: _Rig, texts: list[str]) -> dict[str, torch.Tensor]:+ pipe = rig.flash._pipe+ assert pipe is not None+ return dict(pipe.prepare_inputs(texts, _LABELS, same_labels=True))+++def test_rows_that_are_not_right_padded_run_the_gliclass_forward(reference_flash: None) -> None:+ rig = _Rig("edge")+ inputs = _padded(rig, [_TEXTS[0], _TEXTS[5]])+ inputs = {name: tensor.flip(-1) for name, tensor in inputs.items()} # padding first++ assert rig.runner.run(inputs, len(_LABELS)) is None+ assert rig.runner.stats.eager == {"not_right_padded": 1}+++def test_inputs_other_than_ids_and_mask_run_the_gliclass_forward(reference_flash: None) -> None:+ rig = _Rig("edge")+ inputs = _padded(rig, [_TEXTS[0]])+ inputs["token_type_ids"] = torch.zeros_like(inputs["input_ids"])++ assert rig.runner.run(inputs, len(_LABELS)) is None+ assert rig.runner.stats.eager == {"unsupported_inputs": 1}+++def test_rows_past_the_rope_tables_run_the_gliclass_forward(reference_flash: None) -> None:+ rig = _Rig("edge")+ short = ModernBertFlashEncoder(rig.model, max_length=8)++ assert short.run(_padded(rig, [_TEXTS[5]]), len(_LABELS)) is None+ assert short.stats.eager == {"too_long": 1}+++def test_forwards_past_the_token_bound_run_the_gliclass_forward(reference_flash: None) -> None:+ rig = _Rig("edge")+ items = [Item(text=text) for text in _TEXTS[:4]]+ inputs = _padded(rig, _TEXTS[:4])+ rig.runner._max_tokens = int(inputs["attention_mask"].sum()) - 1++ assert rig.runner.run(inputs, len(_LABELS)) is None+ assert rig.runner.stats.eager == {"too_large": 1}+ # The gliclass forward answers such a request, so it scores exactly as that path does.+ assert _answers(rig.flash.extract(items, labels=_LABELS)) == _answers(rig.eager.extract(items, labels=_LABELS))+ assert rig.runner.stats.flash == 0++[email protected](("hidden_size", "tokens"), [(256, 4096), (384, 4096), (768, 2048), (1024, 1024)])+def test_wider_encoders_hand_smaller_forwards_to_the_gliclass_forward(hidden_size: int, tokens: int) -> None:+ assert token_bound(hidden_size) == tokens+++def _fail_flash(rig: _Rig, monkeypatch: pytest.MonkeyPatch, error: Exception) -> list[int]:+ """Make the rig's flash encoder raise ``error``; returns a list counting its calls."""+ calls: list[int] = []++ def failing(inputs: Any, max_num_classes: int | None) -> torch.Tensor:+ calls.append(1)+ raise error++ monkeypatch.setattr(rig.runner, "run", failing)+ return calls+++def test_a_failing_flash_encoder_is_answered_by_the_gliclass_forward_and_turned_off(+ reference_flash: None, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+) -> None:+ rig = _Rig("edge")+ calls = _fail_flash(rig, monkeypatch, RuntimeError("an unexpected flash-attn error"))+ items = [Item(text=text) for text in _TEXTS[:4]]++ with caplog.at_level(logging.ERROR, logger="sie_server.adapters.gliclass"):+ output = rig.flash.extract(items, labels=_LABELS)++ assert _answers(output) == _answers(rig.eager.extract(items, labels=_LABELS))+ assert rig.flash._flash is None+ assert "an unexpected flash-attn error" in caplog.text+ assert "gliclass forward from now on" in caplog.text+ # Later requests run the gliclass forward without trying the flash encoder again.+ rig.flash.extract(items, labels=_LABELS)+ assert calls == [1]+++def test_a_flash_encoder_out_of_memory_error_propagates_and_keeps_the_encoder(+ reference_flash: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ rig = _Rig("edge")+ _fail_flash(rig, monkeypatch, RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB"))++ with pytest.raises(RuntimeError, match="out of memory"):+ rig.flash.extract([Item(text=_TEXTS[0])], labels=_LABELS)+ assert rig.flash._flash is rig.runner+++def test_an_error_the_gliclass_forward_also_raises_propagates_and_keeps_the_encoder(+ reference_flash: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ rig = _Rig("edge")+ _fail_flash(rig, monkeypatch, RuntimeError("flash-attn rejected the input"))++ def failing_forward(*args: Any, **kwargs: Any) -> Any:+ raise ValueError("the input is at fault")++ monkeypatch.setattr(rig.model, "forward", failing_forward)+ with pytest.raises(ValueError, match="the input is at fault"):+ rig.flash.extract([Item(text=_TEXTS[0])], labels=_LABELS)+ assert rig.flash._flash is rig.runner+++def _supported_model() -> GLiClassModel:+ return _model(_tokenizer(), **_LAYOUTS["edge"]).half()+++def flash_available(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(inference, "is_flash_attention_available", lambda device=None: True)+++def test_a_float16_modernbert_model_on_cuda_is_supported(flash_available: None) -> None:+ assert unsupported_reason(_supported_model(), "cuda:0") is None+++def test_off_cuda_the_model_runs_the_gliclass_forward(flash_available: None) -> None:+ assert unsupported_reason(_supported_model(), "cpu") == "flash attention needs a CUDA device"+ assert unsupported_reason(_supported_model(), "mps") == "flash attention needs a CUDA device"+++def test_without_flash_attn_the_model_runs_the_gliclass_forward(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(inference, "is_flash_attention_available", lambda device=None: False)+ reason = unsupported_reason(_supported_model(), "cuda:0")+ assert reason is not None+ assert "flash-attn" in reason+++def test_a_deberta_encoder_runs_the_gliclass_forward(flash_available: None) -> None:+ tokenizer = _tokenizer()+ config = GLiClassModelConfig(+ encoder_config=DebertaV2Config(+ vocab_size=len(tokenizer), hidden_size=32, num_hidden_layers=1, num_attention_heads=2, intermediate_size=64+ ),+ encoder_model="tiny-deberta-not-on-disk",+ vocab_size=len(tokenizer),+ )+ reason = unsupported_reason(GLiClassModel(config).half(), "cuda:0")+ assert reason == "the deberta-v2 encoder is not a ModernBERT"+++ ("change", "reason"),+ [+ ({"squeeze_layers": True}, "the model scores intermediate encoder layers"),+ ({"encoder_layer_id": 2}, "the model scores intermediate encoder layers"),+ ({"architecture_type": "bi-encoder"}, "only uni-encoder GLiClass models are supported"),+ ],+)+def test_models_the_runner_does_not_cover_run_the_gliclass_forward(+ flash_available: None, change: dict[str, Any], reason: str+) -> None:+ model = _supported_model()+ for name, value in change.items():+ setattr(model.config, name, value)+ assert unsupported_reason(model, "cuda:0") == reason+++def test_float32_weights_run_the_gliclass_forward(flash_available: None) -> None:+ reason = unsupported_reason(_supported_model().float(), "cuda:0")+ assert reason == "flash attention needs float16 or bfloat16 weights, not torch.float32"+++def test_the_option_is_off_by_default() -> None:+ rig_model = _model(_tokenizer(), **_LAYOUTS["edge"])+ adapter = GLiClassAdapter("tiny", max_seq_length=_MAX_LENGTH)+ pipe = ZeroShotClassificationPipeline(+ rig_model, _tokenizer(), max_length=_MAX_LENGTH, device="cpu", progress_bar=False+ ).pipe+ adapter._attach(pipe, _tokenizer())+ assert adapter._flash is None+++def test_off_cuda_the_option_logs_why_it_does_not_apply(caplog: pytest.LogCaptureFixture) -> None:+ tokenizer = _tokenizer()+ pipe = ZeroShotClassificationPipeline(+ _model(tokenizer, **_LAYOUTS["edge"]), tokenizer, max_length=_MAX_LENGTH, device="cpu", progress_bar=False+ ).pipe+ adapter = GLiClassAdapter("tiny-edge", max_seq_length=_MAX_LENGTH, modernbert_flash=True)+ with caplog.at_level(logging.INFO, logger="sie_server.adapters.gliclass"):+ adapter._attach(pipe, tokenizer)+ assert adapter._flash is None+ assert "tiny-edge" in caplog.text+ assert "CUDA" in caplog.text++[email protected]("value", ["true", "multi-label", 1, 0, None])+def test_modernbert_flash_must_be_a_boolean_or_single_label(value: object) -> None:+ with pytest.raises(ValueError, match="modernbert_flash"):+ GLiClassAdapter("tiny", modernbert_flash=value) # ty: ignore[invalid-argument-type]+++ "request_kwargs",+ [+ {"labels": _LABELS, "options": {"classification_type": "multi-label"}},+ {"options": {"classification_type": "multi-label", "label_groups": _GROUPS}},+ {"options": {"classification_type": "multi-label", "label_groups": _GROUPS, "group_encoding": "joint"}},+ ],+ ids=["labels", "separate", "joint"],+)+def test_single_label_mode_runs_multi_label_requests_on_the_gliclass_forward(+ reference_flash: None, request_kwargs: dict[str, Any]+) -> None:+ rig = _Rig("edge")+ rig.flash._flash_types = GLiClassAdapter("tiny", modernbert_flash="single-label")._flash_types+ items = [Item(text=text) for text in _TEXTS[:4]]++ multi = rig.flash.extract(items, **request_kwargs)+ assert rig.runner.stats.flash == 0+ assert _answers(multi) == _answers(rig.eager.extract(items, **request_kwargs))++ rig.flash.extract(items, labels=_LABELS)+ assert rig.runner.stats.flash > 0+++def test_unloading_drops_the_runner(reference_flash: None) -> None:+ rig = _Rig("edge")+ rig.flash.unload()+ assert rig.flash._flash is None+++def test_the_modernbert_gliclass_models_ship_with_the_flash_encoder() -> None:+ configs = load_model_configs(_MODELS_DIR)+ # Named profiles (``model:profile``) inherit the default profile's load-time options.+ modes = {+ name.split(":")[0]: config.resolve_profile("default").loadtime.get("modernbert_flash", False)+ for name, config in configs.items()+ if config.resolve_profile("default").adapter_path.endswith(":GLiClassAdapter")+ }++ assert {name: mode for name, mode in modes.items() if mode is not False} == _FLASH_BY_DEFAULT+ for name, mode in _FLASH_BY_DEFAULT.items():+ loadtime = configs[name].resolve_profile("default").loadtime+ reject_unknown_loadtime_options(GLiClassAdapter, loadtime, model_name=name)+ adapter = GLiClassAdapter(**_build_adapter_kwargs(configs[name], "float16"))+ assert adapter._modernbert_flash == mode+++def _has_flash_attn() -> bool:+ try:+ import flash_attn # ty: ignore[unresolved-import]+ except ImportError:+ return False+ return True++[email protected]("layout", list(_LAYOUTS))+def test_the_flash_kernel_scores_like_the_gliclass_forward_in_float16(layout: str) -> None:+ if not torch.cuda.is_available() or not _has_flash_attn():+ pytest.skip("requires CUDA and flash-attn")+ rig = _Rig(layout, device="cuda:0", dtype=torch.float16)+ items = [Item(text=text) for text in _TEXTS]+ for request_kwargs in _REQUESTS.values():+ _assert_close(+ rig.eager.extract(items, **request_kwargs), rig.flash.extract(items, **request_kwargs), abs_tol=2e-2+ )+ assert rig.runner.stats.flash > 0+ assert not rig.runner.stats.eager