Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(gliformer): bound span decoding and keep padding out of it (#375)

svonava0ee26b0337c8
diff --git a/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py b/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py
index cdd3f8e84..0ccb929f9 100644
--- a/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py
@@ -4,8 +4,12 @@ from __future__ import annotations
import copy
import hashlib
+import importlib
+import inspect
import logging
import math
+import operator
+import sys
import threading
import warnings
import weakref
@@ -14,7 +18,7 @@ from collections.abc import Callable, Mapping
from dataclasses import dataclass
from numbers import Real
from pathlib import Path
-from types import ModuleType
+from types import ModuleType, SimpleNamespace
from typing import Any, ClassVar
import torch
@@ -34,6 +38,17 @@ from sie_server.adapters.gliformer.output_schema import (
compile_output_schema,
shape_structured_output,
)
+from sie_server.adapters.gliformer.relation_decoding import make_relation_decode
+from sie_server.adapters.gliformer.span_decoding import (
+ PROPOSAL_UNITS,
+ candidate_units,
+ decoding_row,
+ document_allowances,
+ pair_spans,
+ propose_spans,
+ select_spans,
+)
+from sie_server.adapters.gliformer.structuring_decoding import make_structuring_decode
from sie_server.core.extract_cost import MAX_EXTRACT_LABELS
from sie_server.core.inference_output import EncodeOutput, ExtractItemError, ExtractOutput
from sie_server.types.inputs import InvalidInputError, Item
@@ -52,12 +67,12 @@ _ERR_RELATIONS_OPTION = "GLiFormer takes relation types as options.relation_labe
_SNAPSHOT_IGNORE_PATTERNS = ["*.gif"]
# Lowest threshold for requests that decode spans (entities, relations,
-# output_schema fields). GLiFormer's span decoder pairs every start above the
-# threshold with every end above it in Python, so a near-zero threshold turns
-# decoding quadratic in words x labels (seconds at a few hundred words); the
-# relation head decodes its entities the same way. Classification decoding is
-# a sigmoid and a filter per label, so classification-only requests accept any
-# threshold.
+# output_schema fields). Span decoding keeps at most MAX_SPAN_CANDIDATES
+# (span_decoding) candidates per document, but candidates multiply as the
+# threshold falls (an entity-dense 2048-word document with 64 labels has 691
+# at 0.5 and 1334 at 0.1), and the floor keeps ordinary documents well inside
+# that bound. Classification decoding is a sigmoid and a filter per label, so
+# classification-only requests accept any threshold.
_MIN_SPAN_THRESHOLD = 0.1
# GLiFormer's classification decoder reads a threshold of 0 as "unset" and
# falls back to 0.5, so 0 is passed on as the smallest positive threshold.
@@ -96,6 +111,19 @@ _MAX_TYPE_GROUPS = 64
# Marks an item whose model output could not be used.
_ITEM_ERROR = "__gliformer_item_error__"
+# Span decoding work each document may do, in span_decoding's allowance units
+# (at most about 7 microseconds of host work each on an L4 host, 1.3 at the
+# median): a floor plus an allowance per billed token of that document. A
+# document that needs more keeps the best-first prefix of each stage it can
+# afford (see span_decoding).
+# Measured with both checkpoints on 4,416 documents (short records, 2048-word
+# entity-dense text, prose, a list of names, repeated text, and 64-word
+# windows of them) and 12 tasks up to 64 labels, 20 relation types, and
+# records schemas with 16 fields or two record types: at threshold 0.5 every
+# document used at most 21% of its allowance; at 0.1 the heaviest, 64 words
+# of names with two record types, used 29,739 of 29,952 units.
+_DECODE_FLOOR = 4096
+_DECODE_UNITS_PER_TOKEN = 256
# Distinct task prompts whose token counts are kept. A prompt depends only on
# the request's task arguments, so a repeated task skips rebuilding and
@@ -119,6 +147,7 @@ def _import_gliformer() -> ModuleType:
import gliformer # ty:ignore[unresolved-import]
_drop_builtin_auto_model_overrides()
+ _bound_span_decoding()
return gliformer
@@ -158,6 +187,330 @@ def _drop_builtin_auto_model_overrides() -> None:
raise RuntimeError(f"AutoModel for {config_class.__name__} still resolves to a gliformer class")
+def _bound_span_decoding() -> None:
+ """Replace GLiFormer's span decoding hot spots with bounded, equivalent code, or fail.
+
+ Every BIO span decoder in the package (entities, the relation head's
+ entity candidates, structuring fields) pairs starts with ends in
+ ``SpanDecoder._calculate_span_score``, one document row at a time from
+ ``SpanDecoder.decode_bio_spans_batch``, and removes overlaps in
+ ``SpanDecoder.greedy_search``; the structuring head proposes spans with
+ GLiNER's ``extract_spans_from_tokens`` and turns them into records in
+ ``StructuringDecoder.decode``, and the relation decoder reads its scores
+ cell by cell in ``JointRelexDecoder.decode``. All of these work pair by
+ pair in Python. The
+ replacements return the same spans in the same order with the same
+ scores, and bound how many candidates a document row can produce (see
+ ``span_decoding`` and ``structuring_decoding``). The relation head builds
+ a new span decoder for every forward pass, so methods are replaced on the
+ classes.
+
+ Raises:
+ RuntimeError: A replaced function is missing, or no longer has the
+ parameters (and, in the exactly pinned gliformer package, the
+ source) that its replacement was verified against.
+ """
+ span_decoder = importlib.import_module("gliformer.tasks.span_decoder")
+ structuring_model = importlib.import_module("gliformer.tasks.structuring.model")
+ structuring_decoder = importlib.import_module("gliformer.tasks.structuring.decoder")
+ span_class = span_decoder.Span
+
+ def calculate_span_score(
+ self: Any,
+ start_idx: Any,
+ end_idx: Any,
+ scores_inside: torch.Tensor,
+ scores_start: torch.Tensor,
+ scores_end: torch.Tensor,
+ id_to_classes: Mapping[int, Any],
+ threshold: float,
+ max_width: int | None = None,
+ ) -> list[Any]:
+ _ = self
+ return pair_spans(
+ start_idx,
+ end_idx,
+ scores_inside,
+ scores_start,
+ scores_end,
+ id_to_classes,
+ threshold,
+ make_span=span_class,
+ max_width=max_width,
+ )
+
+ def greedy_search(self: Any, spans: list[Any], flat_ner: bool = True, multi_label: bool = False) -> list[Any]:
+ _ = self
+ return select_spans(spans, flat_ner, multi_label)
+
+ def decode_bio_spans_batch(
+ self: Any,
+ logits: torch.Tensor,
+ id_to_classes: Any,
+ batch_size: int,
+ threshold: float,
+ flat_ner: bool = True,
+ multi_label: bool = False,
+ ) -> list[list[Any]]:
+ # The package's loop, with each row marked so that its pairing draws
+ # on that document's allowance.
+ all_spans = []
+ for i in range(batch_size):
+ id_to_class_i = self._get_id_to_class(id_to_classes, i)
+ with decoding_row(i):
+ spans = self.decode_bio_spans(logits[i], id_to_class_i, threshold, flat_ner, multi_label)
+ all_spans.append(spans)
+ return all_spans
+
+ _replace_package_function(
+ span_decoder.SpanDecoder,
+ "_calculate_span_score",
+ calculate_span_score,
+ source_sha256="5e05a885577dbedbf52f3d98ad391e7cb37b7762d518b12d82a338cd2976f546",
+ )
+ _replace_package_function(
+ span_decoder.SpanDecoder,
+ "greedy_search",
+ greedy_search,
+ source_sha256="8a08975bc767870ef5e3ed9bc9ec1d2284c19c0604a9eed48480b922dbc099ad",
+ )
+ _replace_package_function(
+ span_decoder.SpanDecoder,
+ "decode_bio_spans_batch",
+ decode_bio_spans_batch,
+ source_sha256="fc2eab7aa5798d5ce07763ac451528b64fd9f4b670f684b9fd7a4813969ceba6",
+ )
+ _replace_package_function(
+ structuring_decoder.StructuringDecoder,
+ "decode",
+ make_structuring_decode(span_class, structuring_decoder.unflatten_by_batch_origin),
+ source_sha256="079bfd5f322bc10981c4150b708da41fbba6cb3742ae5e0daa4e9a4e3f31859c",
+ )
+ joint_relex_decoder = importlib.import_module("gliformer.tasks.joint_relex.decoder")
+ ner_decoder = importlib.import_module("gliformer.tasks.ner.decoder")
+ _replace_package_function(
+ joint_relex_decoder.JointRelexDecoder,
+ "decode",
+ make_relation_decode(ner_decoder.NERDecoder.decode, joint_relex_decoder.unflatten_by_batch_origin),
+ source_sha256="37d5f8ca90c546ef639e58ede17778565c233c87e1576ed9c65e2f4891c69948",
+ )
+ original_proposals = getattr(structuring_model, "extract_spans_from_tokens", None)
+ if getattr(original_proposals, "_sie_bounded", False):
+ original_proposals = original_proposals._sie_original # ty:ignore[unresolved-attribute]
+ if not callable(original_proposals):
+ raise RuntimeError("GLiFormer's structuring head has no span proposal function to bound")
+
+ def extract_spans_from_tokens(
+ scores: torch.Tensor, labels: torch.Tensor | None = None, threshold: float = 0.5
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ return propose_spans(scores, labels, threshold, original=original_proposals)
+
+ # Every gliformer module that imported GLiNER's proposal function gets the
+ # bounded one; only the structuring head calls it in gliformer 0.1.2.
+ # gliner is pinned by range, and images resolve it from the index, so its
+ # source is not hashed: loading checks the replacement's behaviour
+ # against it instead (see _verify_bounded_decoding).
+ for module_name in _PROPOSAL_MODULES:
+ module = importlib.import_module(module_name)
+ if getattr(module, "extract_spans_from_tokens", None) is not None:
+ _replace_package_function(module, "extract_spans_from_tokens", extract_spans_from_tokens)
+ _assert_bounded_decoding()
+
+
+# gliformer modules that bind GLiNER's span proposal function at import.
+_PROPOSAL_MODULES = (
+ "gliformer.tasks.structuring.model",
+ "gliformer.tasks.joint_relex.model",
+ "gliformer.tasks.anchored_extraction",
+ "gliformer.tasks.open_relex.model",
+)
+# gliformer's task decoders, imported so that their classes can be checked.
+_DECODER_MODULES = (
+ "gliformer.tasks.ner.decoder",
+ "gliformer.tasks.joint_relex.decoder",
+ "gliformer.tasks.open_relex.decoder",
+ "gliformer.tasks.structuring.decoder",
+)
+
+
+def _assert_bounded_decoding() -> None:
+ """Fail unless nothing in gliformer can still reach the unbounded functions.
+
+ Raises:
+ RuntimeError: A span decoder subclass overrides a replaced method, a
+ structuring decoder subclass overrides ``decode``, or a gliformer
+ module still binds GLiNER's own proposal function.
+ """
+ span_decoder = importlib.import_module("gliformer.tasks.span_decoder")
+ structuring_decoder = importlib.import_module("gliformer.tasks.structuring.decoder")
+ joint_relex_decoder = importlib.import_module("gliformer.tasks.joint_relex.decoder")
+ for module_name in _DECODER_MODULES:
+ importlib.import_module(module_name)
+ for base, names in (
+ (span_decoder.SpanDecoder, ("_calculate_span_score", "greedy_search", "decode_bio_spans_batch")),
+ (structuring_decoder.StructuringDecoder, ("decode",)),
+ (joint_relex_decoder.JointRelexDecoder, ("decode",)),
+ ):
+ for subclass in _subclasses(base):
+ overridden = [name for name in names if name in vars(subclass)]
+ if overridden:
+ raise RuntimeError(
+ f"GLiFormer's {subclass.__module__}.{subclass.__qualname__} overrides {overridden}, "
+ "which the adapter bounds"
+ )
+ proposals: Any = importlib.import_module("gliformer.tasks.structuring.model").extract_spans_from_tokens
+ original = getattr(proposals, "_sie_original", None)
+ for module_name, module in list(sys.modules.items()):
+ if module is None or not (module_name == "gliformer" or module_name.startswith("gliformer.")):
+ continue
+ if any(value is original for value in vars(module).values()):
+ raise RuntimeError(f"GLiFormer's {module_name} still binds GLiNER's unbounded span proposal function")
+
+
+def _verify_bounded_decoding(model: Any) -> None:
+ """Fail unless each replacement matches the function it replaces on a fixed input.
+
+ The input is small, so no bound applies, and it has ties, padding, nested
+ and overlapping spans, and scores exactly at the threshold. This is what
+ keeps a gliner release that changes proposal semantics from loading, since
+ gliner is pinned by range and not hashed.
+
+ Raises:
+ RuntimeError: A replacement's output differs from the original's.
+ """
+ span_decoder = importlib.import_module("gliformer.tasks.span_decoder")
+ structuring_model = importlib.import_module("gliformer.tasks.structuring.model")
+ structuring_decoder = importlib.import_module("gliformer.tasks.structuring.decoder")
+ _ = model
+ # The replaced code reads no configuration, so a blank one keeps the check
+ # independent of the checkpoint.
+ decoder = span_decoder.SpanDecoder(SimpleNamespace())
+ generator = torch.Generator().manual_seed(0)
+ logits = torch.randn(2, 24, 3, 3, generator=generator) * 3
+ logits[:, 2:6, 0, :] = 4.0 # a run of saturated, tied scores
+ logits[:, 4, 1, 2] = torch.tensor(0.3).logit() # inside exactly at the threshold
+ logits[1, 18:] = float("-inf") # padding
+
+ def check(name: str, original: Any, replacement: Any, same: Callable[[Any, Any], bool] = operator.eq) -> None:
+ if not same(original, replacement):
+ raise RuntimeError(f"GLiFormer's {name} no longer matches its bounded replacement")
+
+ names = {0: "a", 1: "b", 2: "c"}
+ for threshold in (0.3, 0.5):
+ start, end, inside = logits[0].permute(2, 0, 1)
+ args = (
+ decoder._get_indices_above_threshold(start, threshold),
+ decoder._get_indices_above_threshold(end, threshold),
+ torch.sigmoid(inside),
+ torch.sigmoid(start),
+ torch.sigmoid(end),
+ names,
+ threshold,
+ )
+ pairing = vars(span_decoder.SpanDecoder)["_calculate_span_score"]
+ spans = pairing(decoder, *args)
+ check("span pairing", pairing._sie_original(decoder, *args), spans)
+ greedy = vars(span_decoder.SpanDecoder)["greedy_search"]
+ for flat_ner in (True, False):
+ for multi_label in (True, False):
+ check(
+ "overlap removal",
+ greedy._sie_original(decoder, list(spans), flat_ner, multi_label),
+ greedy(decoder, list(spans), flat_ner, multi_label),
+ )
+ batch = vars(span_decoder.SpanDecoder)["decode_bio_spans_batch"]
+ for flat_ner in (True, False):
+ check(
+ "batch span decoding",
+ batch._sie_original(decoder, logits, names, 2, threshold, flat_ner, False),
+ batch(decoder, logits, names, 2, threshold, flat_ner, False),
+ )
+ proposals = vars(structuring_model)["extract_spans_from_tokens"]
+ check(
+ "span proposal",
+ proposals._sie_original(logits, None, threshold),
+ proposals(logits, None, threshold),
+ lambda a, b: all(torch.equal(x, y) for x, y in zip(a, b, strict=True)),
+ )
+ records = SimpleNamespace(
+ structuring_logits=torch.randn(1, 4, 6, generator=generator) * 2,
+ structuring_field_logits=torch.randn(1, 6, 3, generator=generator) * 2,
+ structuring_span_idx=torch.tensor([[[0, 1], [0, 3], [2, 2], [2, 5], [4, 4], [0, 1]]]),
+ structuring_span_mask=torch.tensor([[True, True, True, True, True, False]]),
+ structuring_anchor_mask=torch.tensor([[True, True, False, True]]),
+ structuring_batch_origin=torch.arange(1),
+ batch_size=1,
+ )
+ joint_relex_decoder = importlib.import_module("gliformer.tasks.joint_relex.decoder")
+ relation_decoder = joint_relex_decoder.JointRelexDecoder(SimpleNamespace())
+ relations = SimpleNamespace(
+ ner_logits=logits,
+ ner_batch_origin=torch.arange(2),
+ span_logits=None,
+ span_idx=None,
+ span_mask=None,
+ joint_rel_logits=torch.randn(2, 6, 3, generator=generator) * 2,
+ joint_rel_idx=torch.tensor([[[0, 1], [1, 0], [0, 2], [2, 1], [1, 2], [5, 0]]] * 2),
+ joint_rel_mask=torch.tensor([[True, True, True, True, True, False], [True, False, True, True, True, True]]),
+ joint_rel_batch_origin=torch.arange(2),
+ batch_size=2,
+ )
+ relation_decode = vars(joint_relex_decoder.JointRelexDecoder)["decode"]
+ words = [[f"w{i}" for i in range(24)]] * 2
+ for threshold in (0.3, 0.5):
+ kwargs = {"threshold": threshold, "texts": words}
+ check(
+ "relation decoding",
+ relation_decode._sie_original(relation_decoder, relations, **kwargs),
+ relation_decode(relation_decoder, relations, **kwargs),
+ )
+ record_decoder = structuring_decoder.StructuringDecoder(SimpleNamespace())
+ decode = vars(structuring_decoder.StructuringDecoder)["decode"]
+ for flat_ner in (True, False):
+ kwargs = {"threshold": 0.3, "flat_ner": flat_ner, "texts": [[f"w{i}" for i in range(8)]]}
+ check(
+ "record decoding",
+ decode._sie_original(record_decoder, records, **kwargs),
+ decode(record_decoder, records, **kwargs),
+ )
+
+
+def _subclasses(cls: type) -> list[type]:
+ found = []
+ for subclass in cls.__subclasses__():
+ found.append(subclass)
+ found.extend(_subclasses(subclass))
+ return found
+
+
+def _replace_package_function(
+ owner: Any, name: str, replacement: Callable[..., Any], *, source_sha256: str | None = None
+) -> None:
+ """Set ``owner.name`` to ``replacement`` once, if the original still matches.
+
+ Raises:
+ RuntimeError: ``owner.name`` is missing, takes other parameters than
+ ``replacement``, or its source no longer hashes to ``source_sha256``.
+ """
+ original: Any = getattr(owner, name, None)
+ label = f"{getattr(owner, '__name__', owner)}.{name}"
+ if not callable(original):
+ raise RuntimeError(f"GLiFormer's {label} is missing")
+ if getattr(original, "_sie_bounded", False):
+ return
+ if tuple(inspect.signature(original).parameters) != tuple(inspect.signature(replacement).parameters):
+ raise RuntimeError(f"GLiFormer's {label} changed its parameters")
+ if source_sha256 is not None:
+ try:
+ source = inspect.getsource(original)
+ except (OSError, TypeError) as exc:
+ raise RuntimeError(f"GLiFormer's {label} source cannot be verified") from exc
+ if hashlib.sha256(source.encode()).hexdigest() != source_sha256:
+ raise RuntimeError(f"GLiFormer's {label} changed; its bounded replacement must be verified again")
+ vars(replacement).update(_sie_bounded=True, _sie_original=original)
+ setattr(owner, name, replacement)
+
+
class _NonFiniteScoresError(RuntimeError):
"""The model produced NaN or +inf scores for at least one document in a pass."""
@@ -219,11 +572,31 @@ class GLiFormerAdapter(BaseAdapter):
``options["threshold"]`` (default 0.5) applies to every task in the
request. Requests that extract entities, relations, or span-valued
- ``output_schema`` fields need at least 0.1: below that, GLiFormer's span
- decoding grows quadratically with the document and label count.
- Classification-only requests (``classification_task``, ``label_groups``,
- or an ``output_schema`` of root enums only) accept any threshold from 0,
- where every question gets its best answer.
+ ``output_schema`` fields need at least 0.1. Classification-only requests
+ (``classification_task``, ``label_groups``, or an ``output_schema`` of
+ root enums only) accept any threshold from 0, where every question gets
+ its best answer.
+
+ Span decoding is bounded per document: at most 4096 candidate spans for
+ entities and relation endpoints, 2048 structuring proposals, 65,536
+ record field spans across all record slots, and 65,536 relations whose
+ heads and tails span at most 262,144 words. Beyond that a document keeps
+ the candidates overlap removal would take first (best score first, and
+ among equal scores in GLiFormer's own order), so it loses only results
+ that rank below every kept one; nothing in the output marks such a
+ document. The measured documents stay below every bound, so their results
+ are unchanged. Each document of a batch decodes as it would alone: the
+ padding of shorter documents never forms spans or lowers scores.
+
+ Each document's span decoding also draws on its own allowance: 4,096
+ work units plus 256 per billed token of that document. A unit is at most
+ about 7 microseconds of host work: one candidate span or record field
+ span, two per relation, 64 per structuring proposal or relation entity
+ candidate, and a fraction of a unit per score cell of the document that
+ a stage reads (a whole unit when it searches for a cut). A stage that
+ cannot afford everything keeps the best-first prefix it can afford, as
+ at the fixed bounds; the document still succeeds and bills normally, and
+ other documents are unaffected.
``options["relation_threshold"]`` raises the minimum score for relations
only. GLiFormer decodes entities and relations with one threshold, so it
@@ -356,6 +729,7 @@ class GLiFormerAdapter(BaseAdapter):
model.eval()
_skip_redundant_eval(model)
model.model.register_forward_hook(_upcast_score_outputs)
+ _mask_padded_words(model.model)
_limit_relation_entities(model.model)
embedding_config = getattr(model.config, "embedding_config", None)
@@ -371,6 +745,11 @@ class GLiFormerAdapter(BaseAdapter):
# tokenizer leaves unbounded; share the extraction budget instead.
tokenizer.model_max_length = int(model.config.max_len)
+ # Loading the checkpoint imports the task decoders; check them too.
+ _assert_bounded_decoding()
+ _verify_bounded_decoding(model)
+ _probe_forward(model)
+
self._model = model
self._tokenizer = tokenizer
self._normalize_structures = gliformer.processing.schema.normalize_structuring_schemas
@@ -474,6 +853,7 @@ class GLiFormerAdapter(BaseAdapter):
[texts[index] for index in indices],
task_kwargs[types],
[lengths[index] for index in indices],
+ [_DECODE_FLOOR + _DECODE_UNITS_PER_TOKEN * counts[index] for index in indices],
structures=structures,
threshold=threshold,
flat_ner=flat_ner,
@@ -527,6 +907,7 @@ class GLiFormerAdapter(BaseAdapter):
texts: list[str],
task_kwargs: dict[str, Any],
lengths: list[int],
+ allowances: list[int],
*,
structures: dict[str, Any] | None,
threshold: float,
@@ -534,7 +915,10 @@ class GLiFormerAdapter(BaseAdapter):
multi_label: bool,
max_items: int | None,
) -> list[dict[str, Any]]:
- """Run ``GLiFormer.inference`` in bounded chunks; one raw result per text."""
+ """Run ``GLiFormer.inference`` in bounded chunks; one raw result per text.
+
+ ``allowances`` holds each text's span decoding allowance, in units.
+ """
formatter = self._build_formatter(structures) if structures and self._build_formatter else None
rows: list[dict[str, Any]] = [{} for _ in texts]
with self._tokenizer_guard():
@@ -543,6 +927,7 @@ class GLiFormerAdapter(BaseAdapter):
texts,
chunk,
task_kwargs,
+ allowances,
threshold=threshold,
flat_ner=flat_ner,
multi_label=multi_label,
@@ -556,6 +941,7 @@ class GLiFormerAdapter(BaseAdapter):
texts: list[str],
chunk: list[int],
task_kwargs: dict[str, Any],
+ allowances: list[int],
**inference_kwargs: Any,
) -> list[dict[str, Any]]:
"""Run ``chunk``, isolating documents whose scores are non-finite.
@@ -568,7 +954,7 @@ class GLiFormerAdapter(BaseAdapter):
"""
def attempt(part: list[int]) -> list[dict[str, Any]] | None:
- return self._forward(texts, part, task_kwargs, **inference_kwargs)
+ return self._forward(texts, part, task_kwargs, allowances, **inference_kwargs)
def isolate(part: list[int]) -> list[dict[str, Any]]:
if len(part) == 1:
@@ -588,11 +974,16 @@ class GLiFormerAdapter(BaseAdapter):
texts: list[str],
chunk: list[int],
task_kwargs: dict[str, Any],
+ allowances: list[int],
**inference_kwargs: Any,
) -> list[dict[str, Any]] | None:
- """One forward pass; ``None`` when it produced non-finite scores."""
+ """One forward pass; ``None`` when it produced non-finite scores.
+
+ Each document starts the pass with its full allowance, so what it
+ keeps depends only on the document itself.
+ """
try:
- with torch.inference_mode():
+ with torch.inference_mode(), document_allowances([allowances[index] for index in chunk]):
results = self._model.inference(
[texts[index] for index in chunk],
**task_kwargs,
@@ -732,12 +1123,115 @@ def _skip_redundant_eval(model: Any) -> None:
model.eval = eval_if_training
+# Heads that run an NER pass for their own entity candidates, and the method
+# that returns it.
+_NER_CONSUMERS = {"joint_relex": "_forward_ner", "structuring": "_forward_entity_ner"}
+
+
+# A short batch that runs every head whose output the hooks check: entities
+# and relations through the relation head's NER pass, and a structuring field
+# through the structuring head's. Two lengths, so the padding mask runs too.
+_PROBE_TEXTS = ["Ada Lovelace worked with Charles Babbage in London.", "Ada lived in London."]
+_PROBE_TASKS = {
+ "entities": None,
+ "classes": None,
+ "joint_relations": {None: {"entities": ["person", "city"], "relations": ["lives in"]}},
+ "structures": {"$root": {"name": "str"}},
+}
+
+
+def _probe_forward(model: Any) -> None:
+ """Run one small extraction so a checkpoint the hooks cannot handle fails at load.
+
+ Raises:
+ RuntimeError: A hook rejected the checkpoint's outputs, for example
+ NER logits of an unexpected shape.
+ """
+ with torch.inference_mode():
+ model.inference(list(_PROBE_TEXTS), **_PROBE_TASKS, threshold=0.5, batch_size=len(_PROBE_TEXTS))
+
+
+def _mask_padded_words(model: Any) -> None:
+ """Keep the padding of shorter documents out of span decoding.
+
+ A forward pass pads every document to the longest one in its chunk, and
+ the NER head scores padded word positions with logit 0: probability 0.5
+ for start, end, and inside. Below a 0.5 threshold the span decoder then
+ pairs every padded position with every other, quadratic in the padding
+ (about 100 s for 40 short records at threshold 0.3), only for the mapping
+ step to drop those spans. At any threshold, a span that ends a shorter
+ document took the padding's 0.5 as its right neighbour and was reported
+ with score 0.5. Padded positions get logit -inf instead, so each document
+ decodes as it would alone.
+
+ The relation and structuring heads run an NER pass for their own entity
+ candidates. When they reuse the standalone NER head, its hook covers
+ them; a head with an NER head of its own gets its NER pass masked too.
+
+ Raises:
+ RuntimeError: The checkpoint has no NER head, or a relation or
+ structuring head runs an NER pass this cannot mask.
+ """
+ heads = getattr(model, "heads", None)
+ if heads is None or "ner" not in heads:
+ raise RuntimeError("GLiFormer checkpoint has no NER head to mask")
+ ner_head = heads["ner"]
+ ner_head.register_forward_hook(_mask_padded_ner_logits)
+ for name, method in _NER_CONSUMERS.items():
+ if name not in heads:
+ continue
+ head = heads[name]
+ if getattr(head, "_owns_ner_head", None) is False and vars(head).get("_reused_ner_head") is ner_head:
+ continue
+ ner_pass = getattr(head, method, None)
+ if getattr(head, "_owns_ner_head", None) is not True or not callable(ner_pass):
+ raise RuntimeError(f"GLiFormer {name} head runs an NER pass the adapter cannot mask")
+ vars(head)[method] = _masked_ner_pass(ner_pass)
+
+
+def _masked_ner_pass(ner_pass: Callable[..., Any]) -> Callable[..., Any]:
+ """``ner_pass`` with its output's padded positions masked."""
+
+ def masked(*args: Any, **kwargs: Any) -> Any:
+ return _mask_padded_ner_logits(None, args, ner_pass(*args, **kwargs))
+
+ return masked
+
+
+def _mask_padded_ner_logits(_module: Any, _args: Any, output: Any) -> Any:
+ """Forward hook: set the NER logits of padded word positions to -inf.
+
+ Raises:
+ RuntimeError: The head returned logits without a word mask of the
+ same batch and length.
+ """
+ logits = getattr(output, "logits", None)
+ if not isinstance(logits, torch.Tensor):
+ return output
+ extra = getattr(output, "extra", None)
+ mask = extra.get("mask") if isinstance(extra, Mapping) else None
+ if not isinstance(mask, torch.Tensor) or logits.dim() != 4 or tuple(mask.shape) != tuple(logits.shape[:2]):
+ raise RuntimeError("GLiFormer NER logits came without a matching word mask")
+ padded = ~mask.bool()
+ if bool(padded.any()):
+ output.logits = logits.masked_fill(padded[:, :, None, None], float("-inf"))
+ return output
+
+
def _limit_relation_entities(model: Any) -> None:
- """Keep only the most confident entities as relation candidates.
+ """Bound the relation head's entity candidates, and budget their cost.
+
+ - Only the most confident entities are relation candidates. The package
+ ranks the decoded entities and slices the kept ones into compact
+ tensors before it builds entity pairs, so the pair tensors never grow
+ past this many entities per document.
+ - The head ranks each decoded entity with a few small tensor operations
+ in Python before it applies these bounds, so each candidate span it
+ pairs costs ``PROPOSAL_UNITS`` of its document's allowance.
- The package ranks the decoded entities and slices the kept ones into
- compact tensors before it builds entity pairs, so the pair tensors never
- grow past this many entities per document.
+ Raises:
+ RuntimeError: The checkpoint has no joint relation head, or it no
+ longer decodes its entity candidates in the method this charges.
"""
heads = getattr(model, "heads", None)
if heads is None or "joint_relex" not in heads:
@@ -745,6 +1239,15 @@ def _limit_relation_entities(model: Any) -> None:
head = heads["joint_relex"]
current = getattr(head, "max_relation_entities", None)
head.max_relation_entities = _MAX_RELATION_ENTITIES if current is None else min(current, _MAX_RELATION_ENTITIES)
+ decode = getattr(head, "_decode_relation_entity_spans", None)
+ if not callable(decode):
+ raise RuntimeError("GLiFormer's relation head no longer decodes entity candidates where the adapter expects")
+
+ def charged(*args: Any, **kwargs: Any) -> Any:
+ with candidate_units(PROPOSAL_UNITS):
+ return decode(*args, **kwargs)
+
+ vars(head)["_decode_relation_entity_spans"] = charged
def _format_row(row: dict[str, Any], formatter: Any) -> dict[str, Any]:
diff --git a/packages/sie_server/src/sie_server/adapters/gliformer/relation_decoding.py b/packages/sie_server/src/sie_server/adapters/gliformer/relation_decoding.py
new file mode 100644
index 000000000..952b9eb0c
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliformer/relation_decoding.py
@@ -0,0 +1,252 @@
+"""Bounded relation decoding for GLiFormer's joint relation head.
+
+GLiFormer's ``JointRelexDecoder.decode`` reads each document's relation
+scores one cell at a time in Python, over every entity pair and relation
+type: 100 entities and 20 types are 198,000 cells, about half a second per
+document even when no cell passes the threshold. Every relation it keeps
+also copies its head and tail text.
+
+:func:`make_relation_decode` builds a drop-in ``decode`` that finds the
+passing cells with array operations and returns the same relations, in the
+same order, with the same scores. It also bounds each document's relations:
+at most ``max_relations`` of them, whose heads and tails together span at
+most ``max_words`` words, and no more than the document's allowance affords.
+Past a bound, a document keeps the best-first prefix: the highest scores
+first, and among equal scores the package's own order.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import Any
+
+import numpy as np
+import torch
+
+from sie_server.adapters.gliformer.span_decoding import Allowance, row_allowance
+
+# Relations one document keeps. The joint head scores at most 100 entities, so
+# 100 x 99 ordered pairs x 20 relation types = 198,000 cells can pass.
+MAX_RELATIONS = 65536
+# Words of head and tail text across one document's relations. Each relation
+# copies both endpoints' text, and endpoints can be long.
+MAX_RELATION_WORDS = 262144
+# Allowance units per kept relation (building it) and per scored cell.
+RELATION_UNITS = 2
+_CELLS_PER_UNIT = 1024
+
+
+def make_relation_decode(
+ ner_decode: Callable[..., Any],
+ unflatten_by_batch_origin: Callable[..., Any],
+ *,
+ max_relations: int = MAX_RELATIONS,
+ max_words: int = MAX_RELATION_WORDS,
+) -> Callable[..., Any]:
+ """A replacement for ``gliformer.tasks.joint_relex.decoder.JointRelexDecoder.decode``.
+
+ Args:
+ ner_decode: ``NERDecoder.decode``, which the relation decoder extends.
+ unflatten_by_batch_origin: The package's helper of that name.
+ max_relations: Most relations per document.
+ max_words: Most head and tail words across a document's relations.
+
+ Returns:
+ The ``decode`` method.
+ """
+
+ def decode(
+ self: Any,
+ model_output: Any,
+ classes_mapping: Any = None,
+ threshold: float | None = None,
+ flat_ner: bool = True,
+ multi_label: bool = False,
+ texts: Any = None,
+ **kwargs: Any,
+ ) -> list[list[dict]]:
+ """Decode joint relex predictions into relation triples with entity spans."""
+ if model_output.joint_rel_logits is None or model_output.joint_rel_idx is None:
+ return []
+
+ if threshold is None:
+ threshold = self.threshold
+
+ # 1. Decode NER entities first (returns B x groups x spans)
+ ner_id_to_classes = self._get_ner_id_to_classes(classes_mapping)
+ entities = ner_decode(
+ self,
+ model_output,
+ classes_mapping=ner_id_to_classes,
+ threshold=threshold,
+ flat_ner=flat_ner,
+ multi_label=multi_label,
+ **kwargs,
+ )
+
+ # Flatten back to BN-indexed list of span lists for per-group entity lookup
+ flat_entities = [spans for batch_groups in entities for spans in batch_groups]
+
+ # 2. Build relation class mappings
+ rel_id_to_classes = self._get_rel_id_to_classes(classes_mapping)
+ entity_index_maps = self._build_entity_index_maps(
+ flat_entities,
+ getattr(model_output, "joint_rel_entity_spans", None),
+ getattr(model_output, "joint_rel_entity_class_idx", None),
+ ner_id_to_classes,
+ )
+
+ # 3. Decode relation triples
+ probs = torch.sigmoid(model_output.joint_rel_logits)
+ pair_idx = model_output.joint_rel_idx
+ pair_mask = model_output.joint_rel_mask
+ batch_origin = getattr(model_output, "joint_rel_batch_origin", None)
+ flat_triples = []
+ for bn in range(probs.shape[0]):
+ batch_entities = flat_entities[bn] if bn < len(flat_entities) else []
+ source_batch_idx = bn
+ if batch_origin is not None and bn < batch_origin.numel():
+ source_batch_idx = int(batch_origin[bn].item())
+ rel_map = (
+ rel_id_to_classes[bn]
+ if isinstance(rel_id_to_classes, list) and bn < len(rel_id_to_classes)
+ else rel_id_to_classes
+ )
+ entity_index_map = entity_index_maps[bn] if bn < len(entity_index_maps) else None
+ flat_triples.append(
+ _row_relations(
+ self,
+ probs[bn],
+ pair_idx[bn],
+ None if pair_mask is None else pair_mask[bn],
+ threshold,
+ rel_map,
+ entity_index_map,
+ batch_entities,
+ texts,
+ source_batch_idx,
+ allowance=row_allowance(bn),
+ max_relations=max_relations,
+ max_words=max_words,
+ )
+ )
+
+ # Unflatten BN -> B
+ return unflatten_by_batch_origin(
+ flat_triples,
+ model_output.joint_rel_batch_origin,
+ model_output.batch_size,
+ )
+
+ return decode
+
+
+def _row_relations(
+ decoder: Any,
+ probs: torch.Tensor,
+ pair_idx: torch.Tensor,
+ pair_mask: torch.Tensor | None,
+ threshold: float,
+ rel_map: Any,
+ entity_index_map: dict[int, int] | None,
+ entities: list[Any],
+ texts: Any,
+ source_batch_idx: int,
+ *,
+ allowance: Allowance | None,
+ max_relations: int,
+ max_words: int,
+) -> list[dict]:
+ """One document row's relation triples, in the package's order (pair, then type).
+
+ A cell passes when its probability is not at or below the threshold,
+ compared in double precision as the package compares ``.item()`` values;
+ its pair is not masked out; and its type is named. Pairs whose endpoints
+ do not map to decoded entities are dropped, as in the package.
+ """
+ pair_count, type_count = probs.shape
+ if allowance is not None:
+ # Only this document's own pairs are charged: the pair axis is padded
+ # to the document with the most pairs in the batch.
+ pairs_here = pair_count if pair_mask is None else int(pair_mask.sum())
+ allowance.spend(-(-(pairs_here * type_count) // _CELLS_PER_UNIT))
+ passing = ~(probs.detach().to(device="cpu", dtype=torch.float64) <= threshold)
+ if pair_mask is not None:
+ passing &= pair_mask.detach().cpu().bool()[:, None]
+ if rel_map:
+ named = torch.tensor([index in rel_map for index in range(type_count)], dtype=torch.bool)
+ passing &= named[None, :]
+ pairs, types = (part.numpy() for part in passing.nonzero(as_tuple=True))
+ if pairs.size == 0:
+ return []
+ scores = probs.detach().to(device="cpu", dtype=torch.float32).numpy()[pairs, types]
+ ends = pair_idx.detach().cpu().numpy()[pairs]
+ heads, tails = ends[:, 0].astype(np.int64), ends[:, 1].astype(np.int64)
+ if entity_index_map is not None:
+ size = max(1, int(max(heads.max(), tails.max(), max(entity_index_map, default=-1))) + 1)
+ lookup = np.full(size, -1, dtype=np.int64)
+ for model_idx, decoded_idx in entity_index_map.items():
+ if 0 <= model_idx < size:
+ lookup[model_idx] = decoded_idx
+ heads = np.where(heads >= 0, lookup[np.clip(heads, 0, size - 1)], -1)
+ tails = np.where(tails >= 0, lookup[np.clip(tails, 0, size - 1)], -1)
+ mapped = (heads >= 0) & (tails >= 0)
+ pairs, types, scores, heads, tails = pairs[mapped], types[mapped], scores[mapped], heads[mapped], tails[mapped]
+ if pairs.size == 0:
+ return []
+
+ # Endpoint widths, for the text bound; ids outside the decoded list
+ # resolve to empty endpoints, as in the package.
+ widths = np.asarray([span.end - span.start + 1 for span in entities] + [0], dtype=np.int64)
+ head_words = widths[np.where((heads >= 0) & (heads < len(entities)), heads, len(entities))]
+ tail_words = widths[np.where((tails >= 0) & (tails < len(entities)), tails, len(entities))]
+ limit = max_relations if allowance is None else min(max_relations, allowance.affordable(RELATION_UNITS))
+ keep = _best_first(scores, head_words + tail_words, limit, max_words)
+ if allowance is not None:
+ allowance.spend(RELATION_UNITS * int(keep.size))
+
+ resolved: dict[int, dict[str, Any]] = {}
+
+ def endpoint(entity_id: int) -> dict[str, Any]:
+ base = resolved.get(entity_id)
+ if base is None:
+ if 0 <= entity_id < len(entities):
+ entity = entities[entity_id]
+ base = {
+ "start": entity.start,
+ "end": entity.end,
+ "text": decoder.resolve_span_text(texts, source_batch_idx, entity.start, entity.end),
+ "type": entity.entity_type,
+ "entity_idx": entity_id,
+ }
+ else:
+ base = {"start": -1, "end": -1, "text": "", "type": "", "entity_idx": entity_id}
+ resolved[entity_id] = base
+ return dict(base)
+
+ triples = []
+ for index in keep.tolist():
+ rel_name = rel_map.get(int(types[index]), str(int(types[index]))) if rel_map else str(int(types[index]))
+ triples.append(
+ {
+ "head": endpoint(int(heads[index])),
+ "tail": endpoint(int(tails[index])),
+ "relation": rel_name,
+ "score": float(scores[index]),
+ }
+ )
+ return triples
+
+
+def _best_first(scores: np.ndarray, words: np.ndarray, limit: int, max_words: int) -> np.ndarray:
+ """Positions of the kept relations, in their original order.
+
+ Relations are taken best score first (stable), and taking stops at the
+ first one that would exceed ``limit`` relations or ``max_words`` words.
+ """
+ if scores.size <= limit and int(words.sum()) <= max_words:
+ return np.arange(scores.size)
+ ranked = np.argsort(-scores, kind="stable")[:limit]
+ fits = np.cumsum(words[ranked]) <= max_words
+ taken = ranked[: int(np.argmin(fits)) if not fits.all() else ranked.size]
+ return np.sort(taken)
diff --git a/packages/sie_server/src/sie_server/adapters/gliformer/span_decoding.py b/packages/sie_server/src/sie_server/adapters/gliformer/span_decoding.py
new file mode 100644
index 000000000..f2093b382
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliformer/span_decoding.py
@@ -0,0 +1,542 @@
+"""Bounded span decoding for GLiFormer's BIO extraction heads.
+
+GLiFormer finds entity, relation-endpoint, and structuring spans from
+per-word start, end, and inside scores. Its span decoder
+(``SpanDecoder._calculate_span_score``) pairs every start above the threshold
+with every end above it in Python, testing each same-label pair with tensor
+operations, and removes overlaps (``greedy_search``) by testing each span
+against every kept one. The structuring head proposes spans with GLiNER's
+``extract_spans_from_tokens``, which builds a starts x ends matrix and keeps
+every pair whose range stays inside, then processes each proposal in Python.
+All of this grows with the product of start and end counts, which a low
+threshold on a long, entity-dense document turns into seconds or minutes.
+
+:func:`pair_spans`, :func:`select_spans`, and :func:`propose_spans` return
+the same spans, in the same order and with the same scores, from vectorized
+array operations whose cost grows with the number of spans they return, and
+they bound that number per document row. When more candidates pass the
+threshold than a row may keep, the row keeps the ones overlap removal would
+take first: best score first, and among equal scores in the package's own
+order. Overlap removal keeps spans best first, so a cut changes the entities
+only by leaving out spans that rank below every kept one.
+
+Work is also bounded per document (:func:`document_allowances`): each
+document gets an allowance of work units, at most about 7 microseconds of
+host time apiece, from its own billed tokens. Every kept candidate, proposal,
+and bounded search draws on the allowance of the document it belongs to, and
+a stage that cannot afford everything keeps the best-first prefix it can
+afford, exactly as it does at the fixed bounds. One document's allowance
+never depends on the other documents decoded with it.
+"""
+
+from __future__ import annotations
+
+import bisect
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from contextlib import contextmanager
+from contextvars import ContextVar
+from typing import Any
+
+import numpy as np
+import torch
+
+# Candidate entity or relation-endpoint spans one document row keeps. Measured
+# with both checkpoints on 2048-word documents at the 0.1 threshold floor with
+# 64 labels: at most 903 for prose and 1768 for a list of names; repetitive
+# text can produce hundreds of thousands.
+MAX_SPAN_CANDIDATES = 4096
+# Structuring span proposals one document row keeps. Each one is pooled,
+# scored against every record slot, and walked in Python by the structuring
+# head. Measured with both checkpoints on the same documents: at most 612 at
+# threshold 0.5 and 1184 at 0.1 (a list of names, 64 fields).
+MAX_STRUCTURING_PROPOSALS = 2048
+
+# Allowance units (at most about 7 microseconds of host work each, measured
+# on an L4 host). A structuring proposal or a relation entity candidate costs its
+# head far more than a span: it is pooled, scored, and walked in Python.
+PROPOSAL_UNITS = 64
+# One unit per this many score cells for the pass that counts candidates.
+_COUNT_CELLS_PER_UNIT = 32
+
+_FLOAT32_BITS_ONE = int(np.float32(1.0).view(np.int32))
+
+
+class Allowance:
+ """Work units one document may still spend on span decoding."""
+
+ __slots__ = ("remaining",)
+
+ def __init__(self, units: int) -> None:
+ self.remaining = units
+
+ def affordable(self, unit_cost: int, reserve: int = 0) -> int:
+ """How many items at ``unit_cost`` fit after setting ``reserve`` units aside."""
+ return max(0, (self.remaining - reserve) // unit_cost)
+
+ def spend(self, units: int) -> None:
+ self.remaining = max(0, self.remaining - units)
+
+
+_ALLOWANCES: ContextVar[list[Allowance] | None] = ContextVar("gliformer_document_allowances", default=None)
+_ROW: ContextVar[int | None] = ContextVar("gliformer_decoding_row", default=None)
+_CANDIDATE_UNITS: ContextVar[int] = ContextVar("gliformer_candidate_units", default=1)
+
+
+@contextmanager
+def document_allowances(units: Sequence[int]) -> Iterator[list[Allowance]]:
+ """Give each document of a forward pass, in order, its own allowance."""
+ allowances = [Allowance(value) for value in units]
+ token = _ALLOWANCES.set(allowances)
+ try:
+ yield allowances
+ finally:
+ _ALLOWANCES.reset(token)
+
+
+@contextmanager
+def decoding_row(row: int) -> Iterator[None]:
+ """Mark span pairing in this context as decoding document row ``row``."""
+ token = _ROW.set(row)
+ try:
+ yield
+ finally:
+ _ROW.reset(token)
+
+
+@contextmanager
+def candidate_units(units: int) -> Iterator[None]:
+ """Charge each paired candidate span ``units`` in this context."""
+ token = _CANDIDATE_UNITS.set(units)
+ try:
+ yield
+ finally:
+ _CANDIDATE_UNITS.reset(token)
+
+
+def row_allowance(row: int | None = None) -> Allowance | None:
+ """The allowance of document ``row`` (default: the row being decoded), if allowances apply.
+
+ Raises:
+ RuntimeError: Allowances apply but the row is unknown or is not one of
+ the pass's documents.
+ """
+ allowances = _ALLOWANCES.get()
+ if allowances is None:
+ return None
+ index = _ROW.get() if row is None else row
+ if index is None or not 0 <= index < len(allowances):
+ raise RuntimeError("GLiFormer decoded a row that is not one of the pass's documents")
+ return allowances[index]
+
+
+def pair_spans(
+ start_idx: tuple[list[int], list[int]] | list[list[int]],
+ end_idx: tuple[list[int], list[int]] | list[list[int]],
+ scores_inside: torch.Tensor,
+ scores_start: torch.Tensor,
+ scores_end: torch.Tensor,
+ id_to_classes: Mapping[int, Any],
+ threshold: float,
+ *,
+ make_span: Callable[..., Any],
+ max_width: int | None = None,
+ max_candidates: int = MAX_SPAN_CANDIDATES,
+) -> list[Any]:
+ """Pair start and end positions into scored spans, like ``_calculate_span_score``.
+
+ A span's score is the minimum of its start, end, and inside probabilities
+ and of one minus the inside probability just outside each end.
+
+ Args:
+ start_idx: ``[positions, labels]`` whose start probability passed the
+ threshold, in row-major (position, label) order.
+ end_idx: The same for end probabilities.
+ scores_inside: ``(L, C)`` inside probabilities.
+ scores_start: ``(L, C)`` start probabilities.
+ scores_end: ``(L, C)`` end probabilities.
+ id_to_classes: Label id to label name; when non-empty, starts of other
+ labels are skipped.
+ threshold: Every inside probability of a span must reach it.
+ make_span: Builds one span from ``start``, ``end``, ``entity_type``
+ and ``score`` keyword arguments.
+ max_width: Longest span in positions, if bounded.
+ max_candidates: Most spans returned; see the module docstring. Each
+ costs one unit of the request budget.
+
+ Returns:
+ Spans ordered by start position, then label, then end position.
+ """
+ start_positions, start_labels = (list(part) for part in start_idx)
+ end_positions, end_labels = (list(part) for part in end_idx)
+ if not start_positions or not end_positions:
+ return []
+ s_pos = np.asarray(start_positions, dtype=np.int64)
+ s_lab = np.asarray(start_labels, dtype=np.int64)
+ if id_to_classes:
+ known = np.fromiter((label in id_to_classes for label in start_labels), dtype=bool, count=len(start_labels))
+ s_pos, s_lab = s_pos[known], s_lab[known]
+ # The same element-wise operations as the package's decoder, on the same
+ # tensors, so comparisons and complements round exactly as they do there.
+ span_start, span_end, label, score = _bounded_pairs(
+ s_pos,
+ s_lab,
+ np.asarray(end_positions, dtype=np.int64),
+ np.asarray(end_labels, dtype=np.int64),
+ bad=(scores_inside < threshold).detach().cpu().numpy(),
+ inside=_as_float32(scores_inside),
+ start_scores=_as_float32(scores_start),
+ end_scores=_as_float32(scores_end),
+ outside=_as_float32(1.0 - scores_inside),
+ max_width=max_width,
+ max_candidates=max_candidates,
+ allowance=row_allowance(),
+ unit_cost=_CANDIDATE_UNITS.get(),
+ )
+ names: dict[int, Any] = {}
+ spans = []
+ for st, ed, lab, value in zip(span_start.tolist(), span_end.tolist(), label.tolist(), score.tolist(), strict=True):
+ name = names.get(lab)
+ if name is None:
+ name = names[lab] = id_to_classes.get(lab, str(lab))
+ spans.append(make_span(start=st, end=ed, entity_type=name, score=value))
+ return spans
+
+
+def propose_spans(
+ scores: torch.Tensor,
+ labels: torch.Tensor | None = None,
+ threshold: float = 0.5,
+ *,
+ original: Callable[..., tuple[torch.Tensor, torch.Tensor]],
+ max_candidates: int = MAX_STRUCTURING_PROPOSALS,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ """Span proposals from BIO logits, like GLiNER's ``extract_spans_from_tokens``.
+
+ GLiFormer's structuring head proposes every span whose start, end, and
+ every inside probability exceed the threshold, for any label, and scores
+ each proposal against every record slot. A proposal's rank here is the
+ minimum of those probabilities, the same value the head uses to accept a
+ field for it.
+
+ Args:
+ scores: ``(B, L, C, 3)`` start/end/inside logits.
+ labels: Gold BIO labels (training); proposals then come from
+ ``original`` unchanged.
+ threshold: Probability every start, end, and inside score must exceed.
+ original: GLiNER's function, for the labelled case.
+ max_candidates: Most proposals per row; see the module docstring.
+ Each costs ``PROPOSAL_UNITS`` of the request budget.
+
+ Returns:
+ ``(span_idx, span_mask)``: ``(B, N, 2)`` start/end positions and the
+ ``(B, N)`` mask of real proposals, N at least 1.
+ """
+ if labels is not None:
+ return original(scores, labels, threshold)
+ batch = scores.shape[0]
+ # The same element-wise operations as GLiNER, on the same tensors.
+ probs = torch.sigmoid(scores)
+ start_mask = probs[..., 0] > threshold
+ end_mask = probs[..., 1] > threshold
+ inside_mask = probs[..., 2] > threshold
+ rows = []
+ for row in range(batch):
+ starts = start_mask[row].nonzero(as_tuple=False).cpu().numpy()
+ ends = end_mask[row].nonzero(as_tuple=False).cpu().numpy()
+ if starts.size == 0 or ends.size == 0:
+ rows.append((np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64)))
+ continue
+ row_probs = _as_float32(probs[row])
+ span_start, span_end, _, _ = _bounded_pairs(
+ starts[:, 0],
+ starts[:, 1],
+ ends[:, 0],
+ ends[:, 1],
+ bad=(~inside_mask[row]).cpu().numpy(),
+ inside=np.ascontiguousarray(row_probs[..., 2]),
+ start_scores=np.ascontiguousarray(row_probs[..., 0]),
+ end_scores=np.ascontiguousarray(row_probs[..., 1]),
+ outside=None,
+ max_width=None,
+ max_candidates=max_candidates,
+ allowance=row_allowance(row),
+ unit_cost=PROPOSAL_UNITS,
+ )
+ rows.append((span_start, span_end))
+ width = max(1, max((len(span_start) for span_start, _ in rows), default=0))
+ span_idx = torch.zeros(batch, width, 2, dtype=torch.long, device=scores.device)
+ span_mask = torch.zeros(batch, width, dtype=torch.bool, device=scores.device)
+ for row, (span_start, span_end) in enumerate(rows):
+ if len(span_start):
+ pairs = torch.from_numpy(np.stack([span_start, span_end], axis=1))
+ span_idx[row, : len(span_start)] = pairs.to(scores.device)
+ span_mask[row, : len(span_start)] = True
+ return span_idx, span_mask
+
+
+def _bounded_pairs(
+ s_pos: np.ndarray,
+ s_lab: np.ndarray,
+ e_pos: np.ndarray,
+ e_lab: np.ndarray,
+ *,
+ bad: np.ndarray,
+ inside: np.ndarray,
+ start_scores: np.ndarray,
+ end_scores: np.ndarray,
+ outside: np.ndarray | None,
+ max_width: int | None,
+ max_candidates: int,
+ allowance: Allowance | None = None,
+ unit_cost: int = 1,
+) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
+ """Same-label (start, end) pairs whose range has no ``bad`` position, at most ``max_candidates``.
+
+ Pairs come in start order, then by end position. A pair's score is the
+ minimum of its start, end, and inside scores and, with ``outside``, of the
+ outside scores next to it. When more pairs qualify, the result is the
+ first ``max_candidates`` pairs of a stable best-score-first ordering, in
+ their original order: every pair above a score cut, then pairs scoring
+ just below it in their original order.
+
+ With an ``allowance``, counting the pairs costs one unit per 32 score
+ cells up to one past the last candidate, each kept pair ``unit_cost``
+ units, and finding a cut one unit per such cell; the row keeps as many
+ pairs as its allowance affords, the same best-first prefix, and none if
+ it cannot afford the cut.
+
+ Returns:
+ ``(span_start, span_end, label, score)`` arrays.
+ """
+ empty = np.empty(0, dtype=np.int64)
+ if s_pos.size == 0 or e_pos.size == 0:
+ return empty, empty, empty, np.empty(0, dtype=np.float32)
+ # Candidates lie within the document: the padding after a shorter
+ # document scores zero and never passes. Reading only the positions up to
+ # one past the last candidate gives the same pairs and scores, and makes
+ # the work, and its cost, depend on the document alone rather than on the
+ # longest document it is batched with.
+ document_reach = int(max(s_pos.max(), e_pos.max())) + 2
+ extent = min(inside.shape[0], document_reach)
+ bad, inside = bad[:extent], inside[:extent]
+ start_scores, end_scores = start_scores[:extent], end_scores[:extent]
+ if outside is not None:
+ outside = outside[:extent]
+ length, labels = inside.shape
+ positions = np.arange(length, dtype=np.int64)[:, None]
+ infinite = np.float32(np.inf)
+ start_val = start_scores[s_pos, s_lab]
+ end_val = end_scores[e_pos, e_lab]
+ if outside is not None:
+ start_val = np.minimum(start_val, np.where(s_pos > 0, outside[np.maximum(s_pos - 1, 0), s_lab], infinite))
+ end_val = np.minimum(
+ end_val, np.where(e_pos + 1 < length, outside[np.minimum(e_pos + 1, length - 1), e_lab], infinite)
+ )
+ stride = length + 1
+ uncut: list[tuple[np.ndarray, np.ndarray, np.ndarray]] = []
+
+ def reach(cut: np.float32 | None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Kept starts and ends at score ``cut``, and each start's exclusive end limit."""
+ if cut is None and uncut:
+ return uncut[0]
+ if cut is None:
+ s_keep = np.ones(s_pos.size, dtype=bool)
+ e_keep = np.ones(e_pos.size, dtype=bool)
+ limit_bad = _next_true(bad, positions, length)
+ else:
+ s_keep = start_val >= cut
+ e_keep = end_val >= cut
+ limit_bad = _next_true(bad | (inside < cut), positions, length)
+ limit = limit_bad[s_pos, s_lab]
+ if max_width is not None:
+ limit = np.minimum(limit, s_pos + max_width)
+ result = (s_keep, e_keep, np.maximum(limit, s_pos))
+ if cut is None:
+ uncut.append(result)
+ return result
+
+ def per_start(cut: np.float32 | None) -> np.ndarray:
+ """Pairs per start at score ``cut``: kept ends in each kept start's range, from prefix sums."""
+ s_keep, e_keep, limit = reach(cut)
+ ends = np.zeros((length + 1, labels), dtype=np.int64)
+ ends[e_pos[e_keep] + 1, e_lab[e_keep]] = 1 # (position, label) pairs are distinct
+ np.cumsum(ends, axis=0, out=ends)
+ return np.where(s_keep, ends[limit, s_lab] - ends[s_pos, s_lab], 0)
+
+ def pairs(cut: np.float32 | None, chosen: np.ndarray | None = None) -> tuple[np.ndarray, np.ndarray]:
+ """Owning start index and end position of the pairs at score ``cut``, in order."""
+ s_keep, e_keep, limit = reach(cut)
+ keys = np.sort(e_lab[e_keep] * stride + e_pos[e_keep])
+ starts = np.flatnonzero(s_keep if chosen is None else s_keep & chosen)
+ lab = s_lab[starts]
+ low = np.searchsorted(keys, lab * stride + s_pos[starts], side="left")
+ high = np.searchsorted(keys, lab * stride + limit[starts], side="left")
+ counts = high - low
+ total = int(counts.sum())
+ owner = np.repeat(starts, counts)
+ offsets = np.arange(total, dtype=np.int64) - np.repeat(np.cumsum(counts) - counts, counts)
+ return owner, keys[np.repeat(low, counts) + offsets] - s_lab[owner] * stride
+
+ def scores(owner: np.ndarray, span_end: np.ndarray) -> np.ndarray:
+ span_start, label = s_pos[owner], s_lab[owner]
+ # Minimum inside score over each span, from one reduction over the
+ # label-major scores (padded so every range end is a valid index).
+ flat = np.append(inside.T.ravel(), np.float32(0.0))
+ bounds = np.empty(2 * owner.size, dtype=np.int64)
+ bounds[0::2] = label * length + span_start
+ bounds[1::2] = label * length + span_end + 1
+ score = np.minimum.reduceat(flat, bounds)[0::2] if owner.size else np.empty(0, dtype=np.float32)
+ score = np.minimum(score, start_val[owner])
+ score = np.minimum(score, end_scores[span_end, label])
+ if outside is not None:
+ right = np.where(span_end + 1 < length, outside[np.minimum(span_end + 1, length - 1), label], infinite)
+ score = np.minimum(score, right)
+ return score
+
+ total = int(per_start(None).sum())
+ cells = document_reach * labels # the same whether or not the row ends with the document
+ limit = max_candidates
+ if allowance is not None:
+ allowance.spend(-(-cells // _COUNT_CELLS_PER_UNIT))
+ limit = min(limit, allowance.affordable(unit_cost))
+ if total <= limit:
+ owner, span_end = pairs(None)
+ else:
+ if allowance is not None:
+ limit = min(max_candidates, allowance.affordable(unit_cost, reserve=cells))
+ if limit == 0:
+ return empty, empty, empty, np.empty(0, dtype=np.float32)
+ allowance.spend(cells)
+ cut = _score_cut(lambda value: int(per_start(value).sum()), limit)
+ above = per_start(cut)
+ owner, span_end = pairs(cut)
+ missing = limit - int(above.sum())
+ cut_bits = int(np.float32(cut).view(np.int32))
+ if missing > 0 and cut_bits > 0:
+ # Pairs scoring exactly the next float32 below the cut, in order.
+ below = np.int32(cut_bits - 1).view(np.float32)
+ reached = np.cumsum(per_start(below) - above)
+ chosen = np.arange(s_pos.size) <= np.searchsorted(reached, missing)
+ tie_owner, tie_end = pairs(below, chosen)
+ tied = scores(tie_owner, tie_end) < cut
+ tie_owner, tie_end = tie_owner[tied][:missing], tie_end[tied][:missing]
+ owner = np.concatenate([owner, tie_owner])
+ span_end = np.concatenate([span_end, tie_end])
+ order = np.lexsort((span_end, owner))
+ owner, span_end = owner[order], span_end[order]
+ if allowance is not None:
+ allowance.spend(unit_cost * owner.size)
+ if owner.size == 0:
+ return empty, empty, empty, np.empty(0, dtype=np.float32)
+ return s_pos[owner], span_end, s_lab[owner], scores(owner, span_end)
+
+
+def _as_float32(tensor: torch.Tensor) -> np.ndarray:
+ """Contiguous host float32 copy; exact for float16, bfloat16, and float32 values."""
+ return np.ascontiguousarray(tensor.detach().to(device="cpu", dtype=torch.float32).numpy())
+
+
+def _next_true(mask: np.ndarray, positions: np.ndarray, length: int) -> np.ndarray:
+ """Per column, the first row at or after each row where ``mask`` holds, else ``length``."""
+ marked = np.where(mask, positions, length)
+ return np.minimum.accumulate(marked[::-1], axis=0)[::-1]
+
+
+def _score_cut(count: Callable[[np.float32], int], max_candidates: int) -> np.float32:
+ """Lowest score cut that leaves at most ``max_candidates`` candidates.
+
+ A candidate's score is a minimum of per-position scores, so it reaches a
+ cut exactly when each of them does, and ``count`` needs no enumeration.
+ The count only falls as the cut rises, so the lowest passing cut is found
+ by bisecting the float32 bit patterns of [0, 1] (about 30 counts).
+ """
+ low_bits, high_bits = 0, _FLOAT32_BITS_ONE + 1 # nothing scores above 1
+ while low_bits < high_bits:
+ middle = (low_bits + high_bits) // 2
+ if count(np.int32(middle).view(np.float32)) <= max_candidates:
+ high_bits = middle
+ else:
+ low_bits = middle + 1
+ return np.int32(low_bits).view(np.float32)
+
+
+def select_spans(spans: list[Any], flat_ner: bool = True, multi_label: bool = False) -> list[Any]:
+ """Remove overlapping spans best first, exactly like the package's ``greedy_search``.
+
+ The package tests each span against every span kept so far. Kept flat
+ spans never overlap one another (except for exact repeats of the same
+ boundaries, with ``multi_label``), so a flat test only needs the kept span
+ starting last at or before the candidate's end: a binary search. Nested
+ mode summarizes kept spans per position (see :func:`_select_nested`).
+
+ Args:
+ spans: Candidate spans with ``start``, ``end``, and ``score``.
+ flat_ner: Reject any overlap; otherwise only partial overlaps (nested
+ spans are kept).
+ multi_label: Keep spans with the same boundaries as a kept span.
+
+ Returns:
+ The kept spans, ordered by start position.
+ """
+ if not spans:
+ return []
+ ranked = sorted(spans, key=lambda item: -item.score)
+ kept = _select_flat(ranked, multi_label) if flat_ner else _select_nested(ranked, multi_label)
+ kept.sort(key=lambda item: item.start)
+ return kept
+
+
+def _select_flat(ranked: list[Any], multi_label: bool) -> list[Any]:
+ # Distinct kept boundaries, sorted; they are pairwise disjoint.
+ starts: list[int] = []
+ ends: list[int] = []
+ kept: list[Any] = []
+ for span in ranked:
+ start, end = span.start, span.end
+ index = bisect.bisect_right(starts, end) - 1
+ if index >= 0 and ends[index] >= start:
+ # Overlaps the kept span at ``index`` (the only one it can reach).
+ if not (multi_label and starts[index] == start and ends[index] == end):
+ continue
+ kept.append(span)
+ continue
+ starts.insert(index + 1, start)
+ ends.insert(index + 1, end)
+ kept.append(span)
+ return kept
+
+
+def _select_nested(ranked: list[Any], multi_label: bool) -> list[Any]:
+ """Nested-mode overlap removal: reject a span that crosses a kept one.
+
+ Two spans cross when they overlap and neither contains the other: a kept
+ ``(a, b)`` crosses ``(s, e)`` exactly when ``a < s <= b < e`` or
+ ``s < a <= e < b``. Per position, the kept spans are summarized by the
+ smallest start of those ending there and the largest end of those
+ starting there, so each test is two range reductions over at most the
+ span's width, and each kept span updates two cells.
+ """
+ if not ranked:
+ return []
+ low = min(span.start for span in ranked)
+ size = max(span.end for span in ranked) - low + 2
+ start_by_end = np.full(size, size, dtype=np.int64) # smallest kept start ending at each position
+ end_by_start = np.full(size, -1, dtype=np.int64) # largest kept end starting at each position
+ boundaries: set[tuple[int, int]] = set()
+ kept: list[Any] = []
+ for span in ranked:
+ start, end = span.start - low, span.end - low
+ if (start, end) in boundaries:
+ # A repeat of a kept span crosses nothing that span does not.
+ if multi_label:
+ kept.append(span)
+ continue
+ if end > start and (
+ int(start_by_end[start:end].min()) < start or int(end_by_start[start + 1 : end + 1].max()) > end
+ ):
+ continue
+ start_by_end[end] = min(start_by_end[end], start)
+ end_by_start[start] = max(end_by_start[start], end)
+ boundaries.add((start, end))
+ kept.append(span)
+ return kept
diff --git a/packages/sie_server/src/sie_server/adapters/gliformer/structuring_decoding.py b/packages/sie_server/src/sie_server/adapters/gliformer/structuring_decoding.py
new file mode 100644
index 000000000..dfbe6cf07
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/gliformer/structuring_decoding.py
@@ -0,0 +1,311 @@
+"""Bounded record decoding for GLiFormer's structuring head.
+
+GLiFormer's ``StructuringDecoder.decode`` turns the structuring head's
+outputs into records: for every record slot (anchor) it keeps the entity
+proposals whose membership probability passes the threshold and, for each,
+the fields whose probability passes it, then removes overlapping spans. It
+does this one slot, proposal, and field at a time with tensor indexing in
+Python: about 30 microseconds per slot and proposal on CPU, so a dense
+document with a few hundred proposals across the checkpoint's 100 slots
+takes seconds.
+
+:func:`make_structuring_decode` builds a drop-in ``decode`` that selects the
+same spans with array operations, in the same order and with the same
+scores, and keeps at most ``max_spans`` of them per document across all
+slots: the ones each slot's overlap removal would take first (best score
+first, and among equal scores in the package's order). Overlap removal
+keeps spans best first, so a cut changes a slot's fields only by leaving out
+spans that rank below every kept one. Everything else is the package's own
+code, unchanged.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from typing import Any
+
+import numpy as np
+import torch
+
+from sie_server.adapters.gliformer.span_decoding import _FLOAT32_BITS_ONE, Allowance, _score_cut, row_allowance
+
+# Record-slot field spans one document keeps across all slots. Each open slot
+# pairs every member proposal with every field, so real documents produce far
+# more of these than entity spans: measured with both checkpoints on
+# 2048-word documents, up to 15,291 at threshold 0.5 and 58,890 at 0.1 (a
+# list of names with a records schema).
+MAX_RECORD_SPANS = 65536
+# Words of field text one document's records may hold after overlap removal.
+# Each field copies its span's words, and nested overlap removal
+# (flat_ner=false) can keep every span of a nested chain, so without a bound
+# the text alone grows with spans x document length. Flat single-label
+# removal keeps disjoint spans per slot: at most 100 slots x 2048 words.
+MAX_RECORD_WORDS = 262144
+
+
+def make_structuring_decode(
+ make_span: Callable[..., Any],
+ unflatten_by_batch_origin: Callable[..., Any],
+ *,
+ max_spans: int = MAX_RECORD_SPANS,
+ max_words: int = MAX_RECORD_WORDS,
+) -> Callable[..., Any]:
+ """A replacement for ``gliformer.tasks.structuring.decoder.StructuringDecoder.decode``.
+
+ Args:
+ make_span: The package's ``Span`` class.
+ unflatten_by_batch_origin: The package's helper of that name.
+ max_spans: Most field spans per document, across its record slots.
+ max_words: Most words of field text per document, across its slots.
+
+ Returns:
+ The ``decode`` method.
+ """
+
+ def decode(
+ self: Any,
+ model_output: Any,
+ classes_mapping: Any = None,
+ threshold: float | None = None,
+ flat_ner: bool = True,
+ multi_label: bool = False,
+ texts: Any = None,
+ objectness_threshold: float | None = None,
+ preserve_empty_records: bool = False,
+ **kwargs: Any,
+ ) -> Any:
+ """Decode typed NER spans into unordered record-anchor groups.
+
+ Field logits have shape ``(BN, E, C)`` and independent
+ anchor-membership logits have shape ``(BN, A, E)``.
+ """
+ _ = kwargs
+ membership_logits = getattr(model_output, self.span_logits_attr, None)
+ field_logits = getattr(model_output, self.field_logits_attr, None)
+ span_idx = getattr(model_output, self.span_idx_attr, None)
+ span_mask = getattr(model_output, self.span_mask_attr, None)
+ if membership_logits is None or span_idx is None or span_mask is None:
+ return []
+
+ if membership_logits.dim() != 3:
+ raise ValueError(f"structuring_logits must have shape (BN, A, E), got {tuple(membership_logits.shape)}")
+ if field_logits is None or field_logits.dim() != 3:
+ raise ValueError("structuring_field_logits must have shape (BN, E, C)")
+
+ batch_groups, anchor_count, entity_count = membership_logits.shape
+ if field_logits.shape[:2] != (batch_groups, entity_count):
+ raise ValueError(
+ "structuring field logits must share the membership "
+ f"(BN, E) axes; got {tuple(field_logits.shape[:2])} and "
+ f"{(batch_groups, entity_count)}"
+ )
+ if span_idx.dim() != 3 or span_idx.shape != (batch_groups, entity_count, 2):
+ raise ValueError(f"structuring_span_idx must have shape (BN, E, 2), got {tuple(span_idx.shape)}")
+ if span_mask.shape != (batch_groups, entity_count):
+ raise ValueError(f"structuring_span_mask must have shape (BN, E), got {tuple(span_mask.shape)}")
+
+ class_count = field_logits.shape[2]
+ membership_probs = torch.sigmoid(membership_logits)
+ field_probs = torch.sigmoid(field_logits)
+ context = self._prepare_decode_context(
+ model_output,
+ classes_mapping,
+ batch_groups=batch_groups,
+ anchor_count=anchor_count,
+ device=membership_logits.device,
+ threshold=threshold,
+ objectness_threshold=objectness_threshold,
+ )
+
+ flat_results = []
+ for batch_idx in range(batch_groups):
+ text_idx = int(context.batch_origin[batch_idx].item())
+ field_id_to_class = (
+ context.id_to_fields[batch_idx]
+ if batch_idx < len(context.id_to_fields) and context.id_to_fields[batch_idx]
+ else {idx: str(idx) for idx in range(class_count)}
+ )
+ valid_entities = torch.where(span_mask[batch_idx, :entity_count].bool())[0]
+ anchor_entries = []
+ group_context = (
+ context.multi_level_contexts[batch_idx] if batch_idx < len(context.multi_level_contexts) else None
+ )
+ slot_spans = _slot_spans(
+ membership_probs[batch_idx],
+ field_probs[batch_idx],
+ span_idx[batch_idx],
+ valid_entities,
+ None if context.anchor_mask is None else context.anchor_mask[batch_idx],
+ context.threshold,
+ field_id_to_class,
+ make_span=make_span,
+ max_spans=max_spans,
+ allowance=row_allowance(batch_idx),
+ )
+ kept = _within_word_limit(
+ [(anchor_idx, self.greedy_search(spans, flat_ner, multi_label)) for anchor_idx, spans in slot_spans],
+ max_words,
+ )
+ for anchor_idx, spans in kept:
+ fields = self._spans_to_fields(spans, texts, text_idx)
+ anchor_entries.append(
+ {
+ "anchor_index": anchor_idx,
+ "fields": fields,
+ "presence_is_reliable": bool(
+ context.reliable_presence_mask is not None
+ and context.reliable_presence_mask[batch_idx, anchor_idx]
+ ),
+ }
+ )
+ flat_results.append(
+ self._finalize_anchor_group(
+ anchor_entries,
+ relation_scores=(
+ context.relation_scores[batch_idx] if context.relation_scores is not None else None
+ ),
+ context=group_context,
+ preserve_empty_records=preserve_empty_records,
+ )
+ )
+
+ return unflatten_by_batch_origin(flat_results, context.batch_origin, context.batch_size)
+
+ return decode
+
+
+def _slot_spans(
+ membership_probs: torch.Tensor,
+ field_probs: torch.Tensor,
+ span_idx: torch.Tensor,
+ valid_entities: torch.Tensor,
+ anchor_mask: torch.Tensor | None,
+ threshold: float,
+ field_id_to_class: dict[int, str],
+ *,
+ make_span: Callable[..., Any],
+ max_spans: int,
+ allowance: Allowance | None = None,
+) -> list[tuple[int, list[Any]]]:
+ """Each open slot's candidate field spans, in the package's order.
+
+ For one document row: ``membership_probs`` is ``(A, E)``, ``field_probs``
+ ``(E, C)`` and ``span_idx`` ``(E, 2)``. A slot takes a proposal whose
+ membership is not at or below the threshold, and a field of it whose
+ probability is above the threshold and that has a name; the span's score
+ is the smaller of the two probabilities. Spans come by slot, then by
+ proposal, then by field id, as the package builds them.
+
+ When more than ``max_spans`` spans qualify, the document keeps the first
+ ``max_spans`` of a stable best-score-first ordering: every span above a
+ score cut, then spans scoring just below it in their order. With an
+ ``allowance``, each kept span costs a unit and finding a cut one unit
+ per four membership and field cells, and the document keeps only as many
+ spans as its allowance affords, the same best-first prefix.
+ """
+ anchor_count = membership_probs.shape[0]
+ class_count = field_probs.shape[1]
+ # The same comparisons as the package's decoder, on the same tensors.
+ member = (~(membership_probs[:, valid_entities] <= threshold)).cpu().numpy()
+ named = np.fromiter((idx in field_id_to_class for idx in range(class_count)), dtype=bool, count=class_count)
+ fields = (field_probs[valid_entities] > threshold).cpu().numpy() & named
+ membership = membership_probs[:, valid_entities].detach().to(device="cpu", dtype=torch.float32).numpy()
+ probability = field_probs[valid_entities].detach().to(device="cpu", dtype=torch.float32).numpy()
+ bounds = span_idx[valid_entities].cpu().numpy()
+ open_slots = np.ones(anchor_count, dtype=bool) if anchor_mask is None else anchor_mask.bool().cpu().numpy()
+ slots = np.flatnonzero(open_slots)
+ member, membership = member[slots], membership[slots]
+ names = [field_id_to_class.get(idx) for idx in range(class_count)]
+
+ def masks(cut: np.float32 | None) -> tuple[np.ndarray, np.ndarray]:
+ if cut is None:
+ return member, fields
+ return member & (membership >= cut), fields & (probability >= cut)
+
+ def per_slot(cut: np.float32 | None) -> np.ndarray:
+ """Spans per open slot at score ``cut``: members times their passing fields."""
+ slot_members, entity_fields = masks(cut)
+ return slot_members.astype(np.int64) @ entity_fields.sum(axis=1, dtype=np.int64)
+
+ def slot_spans(position: int, cut: np.float32 | None) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ slot_members, entity_fields = masks(cut)
+ members = np.flatnonzero(slot_members[position])
+ entity, field = np.nonzero(entity_fields[members])
+ entity = members[entity]
+ return entity, field, np.minimum(membership[position, entity], probability[entity, field])
+
+ counts = per_slot(None)
+ total = int(counts.sum())
+ limit = max_spans if allowance is None else min(max_spans, allowance.affordable(1))
+ cut: np.float32 | None = None
+ quota = np.full(slots.size, -1, dtype=np.int64) # spans tied just below the cut each slot keeps
+ if total > limit:
+ cut_cost = (member.size + fields.size) // 4
+ if allowance is not None:
+ limit = min(max_spans, allowance.affordable(1, reserve=cut_cost))
+ if limit == 0:
+ return [(anchor_idx, []) for anchor_idx in slots.tolist()]
+ allowance.spend(cut_cost)
+ cut = _score_cut(lambda value: int(per_slot(value).sum()), limit)
+ above = per_slot(cut)
+ missing = limit - int(above.sum())
+ cut_bits = int(np.float32(cut).view(np.int32))
+ quota[:] = 0
+ if missing > 0 and 0 < cut_bits <= _FLOAT32_BITS_ONE + 1:
+ ties = per_slot(np.int32(cut_bits - 1).view(np.float32)) - above
+ before = np.cumsum(ties) - ties
+ quota = np.clip(missing - before, 0, ties)
+
+ result = []
+ for position, anchor_idx in enumerate(slots.tolist()):
+ if cut is None:
+ entity, field, score = slot_spans(position, None)
+ else:
+ entity, field, score = slot_spans(position, cut)
+ if quota[position] > 0:
+ below = np.int32(int(np.float32(cut).view(np.int32)) - 1).view(np.float32)
+ tie_entity, tie_field, tie_score = slot_spans(position, below)
+ tied = np.flatnonzero(tie_score < cut)[: quota[position]]
+ entity = np.concatenate([entity, tie_entity[tied]])
+ field = np.concatenate([field, tie_field[tied]])
+ score = np.concatenate([score, tie_score[tied]])
+ order = np.lexsort((field, entity))
+ entity, field, score = entity[order], field[order], score[order]
+ spans = [
+ make_span(start=start, end=end, entity_type=names[label], score=value)
+ for start, end, label, value in zip(
+ bounds[entity, 0].tolist(), bounds[entity, 1].tolist(), field.tolist(), score.tolist(), strict=True
+ )
+ ]
+ result.append((anchor_idx, spans))
+ if allowance is not None:
+ allowance.spend(sum(len(spans) for _, spans in result))
+ return result
+
+
+def _within_word_limit(slots: list[tuple[int, list[Any]]], max_words: int) -> list[tuple[int, list[Any]]]:
+ """Drop the lowest-scoring kept fields until their text fits ``max_words``.
+
+ Fields are ranked best score first, and among equal scores by slot and
+ then position; the best ones whose words add up to at most ``max_words``
+ stay, in their original order.
+ """
+ words = sum(span.end - span.start + 1 for _, spans in slots for span in spans)
+ if words <= max_words:
+ return slots
+ ranked = sorted(
+ ((slot, index, span) for slot, (_, spans) in enumerate(slots) for index, span in enumerate(spans)),
+ key=lambda entry: -entry[2].score,
+ )
+ keep: set[tuple[int, int]] = set()
+ used = 0
+ for slot, index, span in ranked:
+ width = span.end - span.start + 1
+ if used + width > max_words:
+ break
+ used += width
+ keep.add((slot, index))
+ return [
+ (anchor_idx, [span for index, span in enumerate(spans) if (slot, index) in keep])
+ for slot, (anchor_idx, spans) in enumerate(slots)
+ ]
diff --git a/packages/sie_server/tests/adapters/test_gliformer.py b/packages/sie_server/tests/adapters/test_gliformer.py
index 358370c1a..842ef7781 100644
--- a/packages/sie_server/tests/adapters/test_gliformer.py
+++ b/packages/sie_server/tests/adapters/test_gliformer.py
@@ -17,6 +17,7 @@ import torch
import yaml
from pydantic import BaseModel
from sie_server.adapters.gliformer import adapter as adapter_module
+from sie_server.adapters.gliformer import span_decoding
from sie_server.adapters.gliformer.adapter import GLiFormerAdapter
from sie_server.adapters.gliformer.output_schema import compile_output_schema, shape_structured_output
from sie_server.core.inference_output import ExtractItemError
@@ -816,6 +817,47 @@ def test_inference_is_split_into_padded_token_chunks() -> None:
assert output.input_token_counts == [5, 5, 5]
+def test_each_document_decodes_within_its_own_allowance() -> None:
+ texts = ["Alice works here", "a much longer text about Bob who works there", "Carol stays home"]
+ adapter, model = _adapter({})
+ seen = []
+
+ def inference(batch: list[str], **_: Any) -> dict[str, Any]:
+ allowances = span_decoding._ALLOWANCES.get()
+ seen.append([allowance.remaining for allowance in allowances])
+ # A hostile first document spends its whole allowance; the others
+ # are unaffected.
+ span_decoding.row_allowance(0).spend(10**9)
+ return {"ner": [[_ner(text, text.split()[0], "person")] for text in batch]}
+
+ model.inference.side_effect = inference
+ output = adapter.extract([Item(text=text) for text in texts], labels=["person"])
+
+ counts = output.input_token_counts
+ floor, rate = adapter_module._DECODE_FLOOR, adapter_module._DECODE_UNITS_PER_TOKEN
+ assert seen == [[floor + rate * count for count in counts]]
+ assert output.errors is None
+ assert [[entity["text"] for entity in entities] for entities in output.entities] == [["Alice"], ["a"], ["Carol"]]
+ assert span_decoding._ALLOWANCES.get() is None
+
+
+def test_a_documents_allowance_does_not_depend_on_its_batch() -> None:
+ adapter, model = _adapter({}, inference_batch_tokens=16)
+ seen: dict[str, int] = {}
+
+ def inference(batch: list[str], **_: Any) -> dict[str, Any]:
+ for text, allowance in zip(batch, span_decoding._ALLOWANCES.get(), strict=True):
+ seen.setdefault(text, allowance.remaining)
+ assert seen[text] == allowance.remaining
+ return {"ner": [[] for _ in batch]}
+
+ model.inference.side_effect = inference
+ adapter.extract([Item(text="Alice works here")], labels=["person"])
+ adapter.extract([Item(text="Bob works there"), Item(text="Alice works here")], labels=["person"])
+ adapter.extract([Item(text=t) for t in ["one two three", "Alice works here", "x y z"]], labels=["person"])
+ assert len(seen) == 4
+
+
def test_documents_are_billed_up_to_the_window_left_by_the_prompt() -> None:
adapter, _ = _adapter({"ner": [[], []]}, max_len=10)
@@ -870,17 +912,44 @@ def test_outputs_are_decoded_from_host_memory() -> None:
assert result["batch_size"] == 1
+def _relation_head(**kwargs: Any) -> SimpleNamespace:
+ def decode(ner_scores: Any, *_: Any, **__: Any) -> Any:
+ mask = torch.tensor([[True, True, False]])
+ return torch.zeros(1, 3, 2, dtype=torch.long), mask, torch.zeros(1, 3, dtype=torch.long)
+
+ return SimpleNamespace(**kwargs, _decode_relation_entity_spans=decode)
+
+
@pytest.mark.parametrize(("current", "expected"), [(None, 100), (40, 40), (500, 100)])
def test_relation_candidates_are_limited_at_load(current: int | None, expected: int) -> None:
- head = SimpleNamespace(max_relation_entities=current)
+ head = _relation_head(max_relation_entities=current)
adapter_module._limit_relation_entities(SimpleNamespace(heads={"joint_relex": head, "ner": object()}))
assert head.max_relation_entities == expected
+def test_relation_candidates_cost_proposal_units() -> None:
+ head = _relation_head(max_relation_entities=None)
+ units = []
+
+ def decode(ner_scores: Any, *_: Any, **__: Any) -> Any:
+ units.append(span_decoding._CANDIDATE_UNITS.get())
+ return None
+
+ head._decode_relation_entity_spans = decode
+ adapter_module._limit_relation_entities(SimpleNamespace(heads={"joint_relex": head, "ner": object()}))
+ head._decode_relation_entity_spans(torch.zeros(1))
+ assert units == [span_decoding.PROPOSAL_UNITS]
+ assert span_decoding._CANDIDATE_UNITS.get() == 1
+
+
def test_relation_limit_fails_closed_without_a_relation_head() -> None:
for model in (SimpleNamespace(heads={"ner": object()}), SimpleNamespace()):
with pytest.raises(RuntimeError, match="no joint relation head"):
adapter_module._limit_relation_entities(model)
+ with pytest.raises(RuntimeError, match="no longer decodes entity candidates"):
+ adapter_module._limit_relation_entities(
+ SimpleNamespace(heads={"joint_relex": SimpleNamespace(max_relation_entities=None)})
+ )
def test_supplied_entity_label_order_does_not_create_groups() -> None:
@@ -1163,6 +1232,12 @@ def test_encode_rejects_non_dense_outputs() -> None:
# -- Loading ---------------------------------------------------------------------------
+def _fake_heads() -> dict[str, Any]:
+ ner_head = MagicMock()
+ relation_head = _relation_head(max_relation_entities=None, _owns_ner_head=False, _reused_ner_head=ner_head)
+ return {"ner": ner_head, "joint_relex": relation_head}
+
+
def _fake_gliformer_module(model: MagicMock) -> ModuleType:
module = ModuleType("gliformer")
module.GLiFormer = MagicMock() # type: ignore[attr-defined]
@@ -1186,8 +1261,9 @@ def _fake_gliformer_module(model: MagicMock) -> ModuleType:
def test_load_pins_snapshot_and_places_model(device: str, precision: str | None, dtype: torch.dtype) -> None:
model = MagicMock()
model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))
- relation_head = SimpleNamespace(max_relation_entities=None)
- model.model.heads = {"joint_relex": relation_head}
+ ner_head = MagicMock()
+ relation_head = _relation_head(max_relation_entities=None, _owns_ner_head=False, _reused_ner_head=ner_head)
+ model.model.heads = {"joint_relex": relation_head, "ner": ner_head}
set_eval_mode = model.eval
tokenizer = model.data_processor.transformer_tokenizer
precision_kwargs = {} if precision is None else {"compute_precision": precision}
@@ -1202,6 +1278,9 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
with (
patch.dict(sys.modules, {"gliformer": module}),
+ patch.object(adapter_module, "_bound_span_decoding") as bound_span_decoding,
+ patch.object(adapter_module, "_assert_bounded_decoding") as assert_bounded,
+ patch.object(adapter_module, "_verify_bounded_decoding") as verify_bounded,
patch.object(adapter_module, "snapshot_download", return_value="/staged/gliformer") as download,
):
adapter.load(device)
@@ -1220,6 +1299,15 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
model.to.assert_called_once_with(device=device, dtype=dtype)
set_eval_mode.assert_called_once_with()
model.model.register_forward_hook.assert_called_once_with(adapter_module._upcast_score_outputs)
+ ner_head.register_forward_hook.assert_called_once_with(adapter_module._mask_padded_ner_logits)
+ bound_span_decoding.assert_called_once_with()
+ assert_bounded.assert_called_once_with()
+ verify_bounded.assert_called_once_with(model)
+ # One small extraction at load, through every head the hooks check.
+ probe = model.inference.call_args
+ assert probe.args[0] == adapter_module._PROBE_TEXTS
+ assert probe.kwargs["joint_relations"] is not None
+ assert probe.kwargs["structures"] is not None
assert relation_head.max_relation_entities == 100
assert tokenizer.model_max_length == 2048
assert adapter._tokenizer is tokenizer
@@ -1234,7 +1322,7 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
def test_per_request_eval_walks_the_model_only_when_it_is_training() -> None:
model = MagicMock()
model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))
- model.model.heads = {"joint_relex": SimpleNamespace(max_relation_entities=None)}
+ model.model.heads = _fake_heads()
set_eval_mode = model.eval
set_eval_mode.side_effect = lambda: setattr(model, "training", False) or model
model.train.side_effect = lambda mode: setattr(model, "training", mode) or model
@@ -1242,6 +1330,9 @@ def test_per_request_eval_walks_the_model_only_when_it_is_training() -> None:
adapter = GLiFormerAdapter("/local/checkpoint")
with (
patch.dict(sys.modules, {"gliformer": _fake_gliformer_module(model)}),
+ patch.object(adapter_module, "_bound_span_decoding"),
+ patch.object(adapter_module, "_assert_bounded_decoding"),
+ patch.object(adapter_module, "_verify_bounded_decoding"),
patch.object(adapter_module.Path, "is_dir", return_value=True),
):
adapter.load("cpu")
@@ -1271,13 +1362,34 @@ def test_per_request_eval_shortcut_does_not_keep_the_model_alive() -> None:
assert released() is None
+def test_load_fails_when_the_probe_forward_is_rejected() -> None:
+ model = MagicMock()
+ model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))
+ model.model.heads = _fake_heads()
+ model.inference.side_effect = RuntimeError("GLiFormer NER logits came without a matching word mask")
+ adapter = GLiFormerAdapter("/local/checkpoint")
+ with (
+ patch.dict(sys.modules, {"gliformer": _fake_gliformer_module(model)}),
+ patch.object(adapter_module, "_bound_span_decoding"),
+ patch.object(adapter_module, "_assert_bounded_decoding"),
+ patch.object(adapter_module, "_verify_bounded_decoding"),
+ patch.object(adapter_module.Path, "is_dir", return_value=True),
+ pytest.raises(RuntimeError, match="word mask"),
+ ):
+ adapter.load("cpu")
+ assert adapter._model is None
+
+
def test_load_rejects_embedding_dimension_mismatch() -> None:
model = MagicMock()
model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))
- model.model.heads = {"joint_relex": SimpleNamespace(max_relation_entities=None)}
+ model.model.heads = _fake_heads()
adapter = GLiFormerAdapter("/local/checkpoint", dense_dim=1024)
with (
patch.dict(sys.modules, {"gliformer": _fake_gliformer_module(model)}),
+ patch.object(adapter_module, "_bound_span_decoding"),
+ patch.object(adapter_module, "_assert_bounded_decoding"),
+ patch.object(adapter_module, "_verify_bounded_decoding"),
patch.object(adapter_module.Path, "is_dir", return_value=True),
pytest.raises(ValueError, match="dimension mismatch"),
):
@@ -1344,6 +1456,14 @@ def test_importing_gliformer_through_the_adapter_keeps_transformers_auto_models(
"from gliformer.backbones import LayoutDebertaConfig, LayoutDebertaModel\n"
"assert MODEL_MAPPING[Qwen3Config] is Qwen3Model, MODEL_MAPPING[Qwen3Config]\n"
"assert MODEL_MAPPING[LayoutDebertaConfig] is LayoutDebertaModel\n"
+ "from gliformer.tasks.span_decoder import SpanDecoder\n"
+ "assert SpanDecoder._calculate_span_score._sie_bounded is True\n"
+ "import importlib\n"
+ "from sie_server.adapters.gliformer import adapter\n"
+ "for name in adapter._PROPOSAL_MODULES:\n"
+ " module = importlib.import_module(name)\n"
+ " assert module.extract_spans_from_tokens._sie_bounded is True, name\n"
+ "adapter._assert_bounded_decoding()\n"
)
result = subprocess.run( # noqa: S603 — fixed interpreter and script
[sys.executable, "-c", script], capture_output=True, text=True, timeout=600, check=False
diff --git a/packages/sie_server/tests/adapters/test_gliformer_span_decoding.py b/packages/sie_server/tests/adapters/test_gliformer_span_decoding.py
new file mode 100644
index 000000000..7f9e07686
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_gliformer_span_decoding.py
@@ -0,0 +1,883 @@
+"""Bounded GLiFormer span decoding: same spans as the package, at bounded cost (no model weights)."""
+
+from __future__ import annotations
+
+import gc
+import importlib
+import random
+import sys
+import time
+from dataclasses import astuple
+from types import ModuleType, SimpleNamespace
+from typing import Any
+
+import numpy as np
+import pytest
+import torch
+from gliner.modeling.utils import extract_spans_from_tokens
+from sie_server.adapters.gliformer import adapter as adapter_module
+from sie_server.adapters.gliformer import relation_decoding, span_decoding, structuring_decoding
+from sie_server.adapters.gliformer.span_decoding import MAX_SPAN_CANDIDATES, pair_spans, propose_spans, select_spans
+
+# Import the package the way the adapter does (without its AutoModel
+# overrides); that also installs the bounded decoding on its span decoder.
+adapter_module._import_gliformer()
+upstream = importlib.import_module("gliformer.tasks.span_decoder")
+assert upstream.SpanDecoder._calculate_span_score._sie_bounded is True
+assert upstream.SpanDecoder.greedy_search._sie_bounded is True
+structuring_model = importlib.import_module("gliformer.tasks.structuring.model")
+assert structuring_model.extract_spans_from_tokens._sie_original is extract_spans_from_tokens
+# The package's own methods, kept on the replacements.
+_UPSTREAM_PAIRING = upstream.SpanDecoder._calculate_span_score._sie_original
+_UPSTREAM_GREEDY = upstream.SpanDecoder.greedy_search._sie_original
+_DECODER = upstream.SpanDecoder(SimpleNamespace())
+
+
+def _bio_scores(seed: int, length: int, labels: int, dtype: torch.dtype) -> torch.Tensor:
+ """(L, C, 3) start/end/inside logits with entity-like runs and noise."""
+ generator = torch.Generator().manual_seed(seed)
+ logits = torch.randn(length, labels, 3, generator=generator) * 2.5
+ for label in range(labels):
+ for _ in range(max(1, length // 6)):
+ start = int(torch.randint(0, length, (1,), generator=generator))
+ end = min(length - 1, start + int(torch.randint(0, 6, (1,), generator=generator)))
+ logits[start, label, 0] += 4
+ logits[end, label, 1] += 4
+ logits[start : end + 1, label, 2] += 4
+ return logits.to(dtype)
+
+
+def _inputs(logits: torch.Tensor, threshold: float) -> tuple[Any, ...]:
+ """Arguments of ``_calculate_span_score`` exactly as ``decode_bio_spans`` builds them."""
+ scores_start, scores_end, scores_inside = logits.permute(2, 0, 1)
+ return (
+ _DECODER._get_indices_above_threshold(scores_start, threshold),
+ _DECODER._get_indices_above_threshold(scores_end, threshold),
+ torch.sigmoid(scores_inside),
+ torch.sigmoid(scores_start),
+ torch.sigmoid(scores_end),
+ )
+
+
+def _as_tuples(spans: list[Any]) -> list[tuple[Any, ...]]:
+ return [astuple(span) for span in spans]
+
+
+def _upstream(logits: torch.Tensor, id_to_classes: dict[int, Any], threshold: float, **kwargs: Any) -> list[Any]:
+ return _UPSTREAM_PAIRING(_DECODER, *_inputs(logits, threshold), id_to_classes, threshold, **kwargs)
+
+
+def _bounded(logits: torch.Tensor, id_to_classes: dict[int, Any], threshold: float, **kwargs: Any) -> list[Any]:
+ return pair_spans(*_inputs(logits, threshold), id_to_classes, threshold, make_span=upstream.Span, **kwargs)
+
+
[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])
[email protected]("threshold", [0.1, 0.3, 0.5, 0.7])
[email protected]("seed", range(6))
+def test_pairing_matches_the_package_span_for_span(seed: int, threshold: float, dtype: torch.dtype) -> None:
+ logits = _bio_scores(seed, length=40 + 7 * seed, labels=1 + seed % 4, dtype=dtype)
+ labels = logits.shape[1]
+ for id_to_classes in ({i: f"label {i}" for i in range(labels)}, {0: "only the first"}, {}):
+ expected = _upstream(logits, id_to_classes, threshold)
+ actual = _bounded(logits, id_to_classes, threshold)
+ # Same spans, same order, bit-identical scores and types.
+ assert _as_tuples(actual) == _as_tuples(expected)
+ assert all(type(a.score) is type(e.score) and type(a.start) is int for a, e in zip(actual, expected))
+
+
[email protected]("max_width", [0, 1, 3, 12])
+def test_pairing_matches_the_package_with_a_width_limit(max_width: int) -> None:
+ probabilities = torch.sigmoid(_bio_scores(11, length=60, labels=1, dtype=torch.float32)[:, 0, :])
+ # The single-label path: probabilities in, indices recomputed from logits.
+ start = _DECODER._get_indices_above_threshold(probabilities[:, 0:1].logit(), 0.2)
+ end = _DECODER._get_indices_above_threshold(probabilities[:, 1:2].logit(), 0.2)
+ args = (start, end, probabilities[:, 2:3], probabilities[:, 0:1], probabilities[:, 1:2], {0: ""}, 0.2)
+ expected = _UPSTREAM_PAIRING(_DECODER, *args, max_width=max_width)
+ assert _as_tuples(pair_spans(*args, make_span=upstream.Span, max_width=max_width)) == _as_tuples(expected)
+
+
+def test_scores_at_the_threshold_compare_as_the_package_does() -> None:
+ # Inside exactly at the threshold passes (the test is "< threshold");
+ # start and end exactly at it do not ("> threshold").
+ threshold = 0.3
+ at = torch.tensor(threshold, dtype=torch.float32).logit()
+ logits = torch.full((6, 1, 3), -8.0)
+ logits[1, 0, 0] = logits[4, 0, 1] = 5.0
+ logits[1:5, 0, 2] = at
+ logits[2, 0, 0] = at
+ expected = _upstream(logits, {0: "x"}, threshold)
+ assert expected
+ assert _as_tuples(_bounded(logits, {0: "x"}, threshold)) == _as_tuples(expected)
+
+
+def _head(items: list[Any], limit: int) -> list[Any]:
+ """The first ``limit`` items overlap removal would take (stable, best score first), in their order."""
+ taken = set(sorted(range(len(items)), key=lambda index: -items[index].score)[:limit])
+ return [item for index, item in enumerate(items) if index in taken]
+
+
[email protected]("limit", [1, 7, 50, 200])
[email protected]("seed", range(4))
+def test_capped_pairing_keeps_the_best_candidates_in_order(seed: int, limit: int) -> None:
+ logits = _bio_scores(seed, length=120, labels=3, dtype=torch.float32)
+ names = {0: "a", 1: "b", 2: "c"}
+ full = _upstream(logits, names, 0.1)
+ assert len(full) > limit
+ capped = _bounded(logits, names, 0.1, max_candidates=limit)
+ assert _as_tuples(capped) == _as_tuples(_head(full, limit))
+ # Overlap removal takes spans best first, so the capped result is the
+ # head of the full one: the spans it would have kept first.
+ for flat_ner in (True, False):
+ for multi_label in (True, False):
+ kept = select_spans(capped, flat_ner, multi_label)
+ everything = _UPSTREAM_GREEDY(_DECODER, full, flat_ner, multi_label)
+ head = {id(span) for span in _head(full, limit)}
+ assert _as_tuples(kept) == _as_tuples([span for span in everything if id(span) in head])
+
+
+def test_capped_pairing_keeps_tied_candidates_in_the_package_order() -> None:
+ # Three identical one-word entities tie: a cap of 2 keeps the first two.
+ logits = torch.full((5, 1, 3), -8.0)
+ for position in (0, 2, 4):
+ logits[position, 0] = 6.0
+ names = {0: "x"}
+ assert [span.start for span in _bounded(logits, names, 0.5)] == [0, 2, 4]
+ assert [span.start for span in _bounded(logits, names, 0.5, max_candidates=2)] == [0, 2]
+ assert [span.start for span in _bounded(logits, names, 0.5, max_candidates=1)] == [0]
+
+
+def test_capped_pairing_fills_the_cap_from_a_large_tie() -> None:
+ # Saturated scores: every start, end, and inside probability is 1, so all
+ # spans away from the edges tie at 0 (their outside neighbour is 1).
+ logits = torch.full((300, 2, 3), 30.0)
+ names = {0: "a", 1: "b"}
+ full = _upstream(logits[:60], names, 0.5)
+ assert len({span.score for span in full}) == 2
+ for limit in (1, 2, 3, 100, 1000):
+ assert _as_tuples(_bounded(logits[:60], names, 0.5, max_candidates=limit)) == _as_tuples(_head(full, limit))
+ assert len(_bounded(logits, names, 0.5)) == MAX_SPAN_CANDIDATES
+
+
+def _random_spans(seed: int, count: int, length: int) -> list[Any]:
+ """Spans with short and long widths, repeated boundaries, and tied scores."""
+ rng = random.Random(seed) # noqa: S311 -- reproducible test data
+ spans = []
+ for _ in range(count):
+ start = rng.randrange(length)
+ end = min(length - 1, start + rng.choice((0, 0, 1, 2, 5, 20)))
+ score = rng.choice((0.5, 0.75, 0.9)) if rng.random() < 0.3 else rng.random()
+ spans.append(upstream.Span(start=start, end=end, entity_type=rng.choice("abc"), score=score))
+ return spans
+
+
[email protected]("multi_label", [False, True])
[email protected]("flat_ner", [True, False])
[email protected]("seed", range(8))
+def test_overlap_removal_matches_the_package(seed: int, flat_ner: bool, multi_label: bool) -> None:
+ spans = _random_spans(seed, count=10 + 40 * seed, length=5 + 30 * seed)
+ expected = _UPSTREAM_GREEDY(_DECODER, list(spans), flat_ner, multi_label)
+ assert select_spans(list(spans), flat_ner, multi_label) == expected
+ assert select_spans([], flat_ner, multi_label) == []
+
+
[email protected]("multi_label", [False, True])
+def test_nested_overlap_removal_matches_the_package_on_chains_and_crossings(multi_label: bool) -> None:
+ rng = random.Random(7) # noqa: S311 -- reproducible test data
+ # Fully nested chains, their crossings, and long spans, with ties.
+ spans = [upstream.Span(start=i, end=400 - i, entity_type="a", score=rng.choice((0.5, 0.9))) for i in range(200)]
+ spans += [upstream.Span(start=i + 1, end=401 - i, entity_type="b", score=rng.random()) for i in range(200)]
+ spans += [upstream.Span(start=i, end=i, entity_type="c", score=rng.random()) for i in range(0, 400, 7)]
+ spans += [upstream.Span(start=s, end=s, entity_type="d", score=0.5) for s in (3, 3, 5)]
+ rng.shuffle(spans)
+ assert select_spans(list(spans), False, multi_label) == _UPSTREAM_GREEDY(_DECODER, list(spans), False, multi_label)
+
+
+def test_fully_nested_spans_are_removed_quickly() -> None:
+ spans = [upstream.Span(start=i, end=8190 - i, entity_type="a", score=1.0 - i / 8192) for i in range(4095)]
+ kept = select_spans(spans, False, False)
+ assert len(kept) == 4095
+
+
+def test_overlap_removal_through_the_decoder_class_uses_the_bounded_code() -> None:
+ spans = _random_spans(1, count=60, length=40)
+ assert _DECODER.greedy_search(spans, False, True) == _UPSTREAM_GREEDY(_DECODER, spans, False, True)
+
+
+def test_worst_case_document_is_bounded() -> None:
+ # Every position of every label passes: ~134M same-label pairs uncapped.
+ logits = 1.0 + 3.0 * torch.rand(2048, 64, 3, generator=torch.Generator().manual_seed(0))
+ spans = _bounded(logits, {i: str(i) for i in range(64)}, 0.1)
+ assert MAX_SPAN_CANDIDATES // 2 < len(spans) <= MAX_SPAN_CANDIDATES
+ assert select_spans(spans, True, True)
+
+
+def test_pairing_without_starts_or_ends_returns_nothing() -> None:
+ logits = torch.full((4, 2, 3), -8.0)
+ assert _bounded(logits, {0: "a", 1: "b"}, 0.5) == []
+
+
+# -- Per-document allowances --------------------------------------------------------
+
+
+def _row_inputs(logits: torch.Tensor, threshold: float) -> tuple[Any, ...]:
+ return _inputs(logits, threshold)
+
+
+def test_allowances_belong_to_rows() -> None:
+ assert span_decoding.row_allowance() is None # outside a forward pass
+ with span_decoding.document_allowances([5, 7]) as allowances:
+ with span_decoding.decoding_row(1):
+ assert span_decoding.row_allowance() is allowances[1]
+ assert span_decoding.row_allowance(0) is allowances[0]
+ with pytest.raises(RuntimeError, match="not one of the pass's documents"):
+ span_decoding.row_allowance()
+ with span_decoding.decoding_row(2), pytest.raises(RuntimeError, match="not one of the pass's documents"):
+ span_decoding.row_allowance()
+ allowance = span_decoding.Allowance(10)
+ assert allowance.affordable(3) == 3
+ assert allowance.affordable(3, reserve=5) == 1
+ allowance.spend(25)
+ assert allowance.remaining == 0
+
+
+def _cells(logits: torch.Tensor, threshold: float) -> int:
+ """Score cells a row is charged for: its labels, up to one past its last start or end."""
+ probs = torch.sigmoid(logits.float())
+ passing = ((probs[..., 0] > threshold) | (probs[..., 1] > threshold)).any(dim=1)
+ return (int(passing.nonzero().max()) + 2) * logits.shape[1]
+
+
+def test_pairing_within_an_allowance_keeps_the_best_first_prefix() -> None:
+ logits = _bio_scores(2, length=80, labels=3, dtype=torch.float32)
+ names = {0: "a", 1: "b", 2: "c"}
+ full = _upstream(logits, names, 0.1)
+ cells = _cells(logits, 0.1)
+ count_cost = -(-cells // 32)
+ with span_decoding.document_allowances([10**9, count_cost + len(full), count_cost + cells + 10, 50]) as rows:
+ results = []
+ for row in range(4):
+ with span_decoding.decoding_row(row):
+ results.append(_bounded(logits, names, 0.1))
+ # Plenty, or exactly enough: everything, at one unit per span plus the count.
+ assert _as_tuples(results[0]) == _as_tuples(full)
+ assert 10**9 - rows[0].remaining == count_cost + len(full)
+ assert _as_tuples(results[1]) == _as_tuples(full)
+ assert rows[1].remaining == 0
+ # Enough for the cut and 10 spans: the head of the full result.
+ assert _as_tuples(results[2]) == _as_tuples(_head(full, 10))
+ assert rows[2].remaining == 0
+ # Not enough to find a cut: nothing, and only the count is spent.
+ assert results[3] == []
+ assert rows[3].remaining == 50 - count_cost
+
+
+def test_candidate_units_raise_the_cost_of_each_span() -> None:
+ logits = _bio_scores(4, length=40, labels=2, dtype=torch.float32)
+ names = {0: "a", 1: "b"}
+ full = _upstream(logits, names, 0.2)
+ with span_decoding.document_allowances([10**9]) as rows, span_decoding.decoding_row(0):
+ with span_decoding.candidate_units(64):
+ _bounded(logits, names, 0.2)
+ assert 10**9 - rows[0].remaining == -(-_cells(logits, 0.2) // 32) + 64 * len(full)
+
+
+def test_proposals_within_an_allowance_keep_the_best_first_prefix() -> None:
+ scores = _bio_scores(8, length=30, labels=3, dtype=torch.float32).unsqueeze(0)
+ ranked = _ranked_proposals(scores[0], 0.1)
+ cells = _cells(scores[0], 0.1)
+ units = -(-cells // 32) + cells + span_decoding.PROPOSAL_UNITS * 5
+ with span_decoding.document_allowances([units]) as rows:
+ kept = _proposals(*_propose(scores, 0.1))[0]
+ assert len(ranked) > 5
+ assert kept == [(item.start, item.end) for item in _head(ranked, 5)]
+ assert rows[0].remaining == 0
+
+
+def _padded(logits: torch.Tensor, positions: int) -> torch.Tensor:
+ """``logits`` followed by padded positions, as the padding mask leaves them."""
+ padding = torch.full((positions, *logits.shape[1:]), float("-inf"), dtype=logits.dtype)
+ return torch.cat([logits, padding])
+
+
[email protected]("units", [10**9, 300])
+def test_pairing_costs_the_same_however_far_the_batch_pads_the_document(units: int) -> None:
+ logits = _bio_scores(5, length=40, labels=3, dtype=torch.float32)
+ names = {0: "a", 1: "b", 2: "c"}
+ kept, spent = [], []
+ for row_logits in (logits, _padded(logits, 400)):
+ with span_decoding.document_allowances([units]) as rows, span_decoding.decoding_row(0):
+ kept.append(_as_tuples(_bounded(row_logits, names, 0.1)))
+ spent.append(units - rows[0].remaining)
+ assert kept[0]
+ assert kept[0] == kept[1]
+ assert spent[0] == spent[1]
+ assert units > 10**6 or len(kept[0]) < len(_upstream(logits, names, 0.1))
+
+
+def test_proposals_cost_the_same_however_far_the_batch_pads_the_document() -> None:
+ logits = _bio_scores(6, length=30, labels=3, dtype=torch.float32)
+ kept, spent = [], []
+ for row_logits in (logits, _padded(logits, 300)):
+ with span_decoding.document_allowances([10**9]) as rows:
+ kept.append(_proposals(*_propose(row_logits.unsqueeze(0), 0.1))[0])
+ spent.append(10**9 - rows[0].remaining)
+ assert kept[0]
+ assert kept[0] == kept[1]
+ assert spent[0] == spent[1]
+
+
+# -- Structuring span proposals ---------------------------------------------------
+
+
+def _propose(scores: torch.Tensor, threshold: float, **kwargs: Any) -> tuple[torch.Tensor, torch.Tensor]:
+ return propose_spans(scores, None, threshold, original=extract_spans_from_tokens, **kwargs)
+
+
+def _proposals(span_idx: torch.Tensor, span_mask: torch.Tensor) -> list[list[tuple[int, int]]]:
+ return [[tuple(pair) for pair in idx[mask].tolist()] for idx, mask in zip(span_idx, span_mask, strict=True)]
+
+
[email protected]("dtype", [torch.float32, torch.float16])
[email protected]("threshold", [0.1, 0.3, 0.5])
[email protected]("seed", range(4))
+def test_proposals_match_gliner(seed: int, threshold: float, dtype: torch.dtype) -> None:
+ scores = torch.stack([_bio_scores(seed * 3 + row, length=50, labels=3, dtype=torch.float32) for row in range(3)])
+ scores[1, 30:] = float("-inf") # a padded row
+ scores = scores.to(dtype)
+ expected_idx, expected_mask = extract_spans_from_tokens(scores, None, threshold)
+ actual_idx, actual_mask = _propose(scores, threshold)
+ assert torch.equal(actual_mask, expected_mask)
+ assert torch.equal(actual_idx, expected_idx)
+ assert actual_idx.dtype == expected_idx.dtype
+ assert actual_mask.dtype == expected_mask.dtype
+
+
+def test_proposals_without_candidates_match_gliner() -> None:
+ scores = torch.full((2, 6, 2, 3), -8.0)
+ for actual, expected in zip(_propose(scores, 0.5), extract_spans_from_tokens(scores, None, 0.5), strict=True):
+ assert torch.equal(actual, expected)
+
+
+def test_labelled_proposals_use_gliner_unchanged() -> None:
+ scores = _bio_scores(1, length=20, labels=2, dtype=torch.float32).unsqueeze(0)
+ labels = (torch.rand(scores.shape, generator=torch.Generator().manual_seed(1)) > 0.5).float()
+ for actual, expected in zip(
+ propose_spans(scores, labels, 0.5, original=extract_spans_from_tokens),
+ extract_spans_from_tokens(scores, labels, 0.5),
+ strict=True,
+ ):
+ assert torch.equal(actual, expected)
+
+
+def _ranked_proposals(scores: torch.Tensor, threshold: float) -> list[Any]:
+ """GLiNER's proposals for one row, in its order, each with the head's field score."""
+ probs = torch.sigmoid(scores)
+ start, end, inside = probs[..., 0] > threshold, probs[..., 1] > threshold, probs[..., 2] > threshold
+ ends = end.nonzero().tolist()
+ ranked = []
+ for s_pos, label in start.nonzero().tolist():
+ for e_pos, e_label in ends:
+ if e_label == label and e_pos >= s_pos and bool(inside[s_pos : e_pos + 1, label].all()):
+ value = min(
+ float(probs[s_pos, label, 0]),
+ float(probs[e_pos, label, 1]),
+ float(probs[s_pos : e_pos + 1, label, 2].min()),
+ )
+ ranked.append(SimpleNamespace(start=s_pos, end=e_pos, score=value))
+ return ranked
+
+
[email protected]("limit", [1, 10, 60])
+def test_capped_proposals_keep_the_best_in_order(limit: int) -> None:
+ scores = _bio_scores(8, length=90, labels=3, dtype=torch.float32).unsqueeze(0)
+ ranked = _ranked_proposals(scores[0], 0.1)
+ assert [(item.start, item.end) for item in ranked] == _proposals(*extract_spans_from_tokens(scores, None, 0.1))[0]
+ assert len(ranked) > limit
+ kept = _proposals(*_propose(scores, 0.1, max_candidates=limit))[0]
+ assert kept == [(item.start, item.end) for item in _head(ranked, limit)]
+
+
+def test_worst_case_proposals_are_bounded() -> None:
+ scores = (1.0 + 3.0 * torch.rand(1, 2048, 16, 3, generator=torch.Generator().manual_seed(0))).float()
+ _, span_mask = _propose(scores, 0.1)
+ assert 0 < int(span_mask.sum()) <= MAX_SPAN_CANDIDATES
+
+
+# -- Structuring records ----------------------------------------------------------
+
+structuring_decoder = importlib.import_module("gliformer.tasks.structuring.decoder")
+_UPSTREAM_STRUCTURING_DECODE = structuring_decoder.StructuringDecoder.decode._sie_original
+_STRUCTURING = structuring_decoder.StructuringDecoder(SimpleNamespace())
+
+
+def _structuring_output(seed: int, *, groups: int = 2, slots: int = 6, entities: int = 24, fields: int = 4) -> Any:
+ generator = torch.Generator().manual_seed(seed)
+ starts = torch.randint(0, 30, (groups, entities, 1), generator=generator)
+ widths = torch.randint(0, 4, (groups, entities, 1), generator=generator)
+ return SimpleNamespace(
+ structuring_logits=torch.randn(groups, slots, entities, generator=generator) * 2,
+ structuring_field_logits=torch.randn(groups, entities, fields, generator=generator) * 2,
+ structuring_span_idx=torch.cat([starts, starts + widths], dim=-1),
+ structuring_span_mask=torch.rand(groups, entities, generator=generator) > 0.2,
+ structuring_anchor_mask=torch.rand(groups, slots, generator=generator) > 0.3,
+ structuring_batch_origin=torch.arange(groups),
+ batch_size=groups,
+ )
+
+
[email protected]("threshold", [0.1, 0.3, 0.5])
[email protected](("flat_ner", "multi_label"), [(True, False), (True, True), (False, False)])
[email protected]("seed", range(4))
+def test_structuring_decode_matches_the_package(seed: int, threshold: float, flat_ner: bool, multi_label: bool) -> None:
+ output = _structuring_output(seed)
+ texts = [[f"w{i}" for i in range(40)] for _ in range(2)]
+ kwargs = {"threshold": threshold, "flat_ner": flat_ner, "multi_label": multi_label, "texts": texts}
+ expected = _UPSTREAM_STRUCTURING_DECODE(_STRUCTURING, output, **kwargs)
+ assert expected
+ assert any(expected[0])
+ assert _STRUCTURING.decode(output, **kwargs) == expected
+
+
+def test_structuring_decode_without_outputs_matches_the_package() -> None:
+ empty = SimpleNamespace(structuring_logits=None, structuring_span_idx=None, structuring_span_mask=None)
+ assert _STRUCTURING.decode(empty) == _UPSTREAM_STRUCTURING_DECODE(_STRUCTURING, empty) == []
+
+
+def _slot_args(seed: int, *, slots: int = 4, entities: int = 40, fields: int = 5, saturate: bool = False) -> tuple:
+ output = _structuring_output(seed, groups=1, slots=slots, entities=entities, fields=fields)
+ membership = torch.sigmoid(output.structuring_logits[0])
+ field_probs = torch.sigmoid(output.structuring_field_logits[0])
+ if saturate:
+ membership = torch.ones_like(membership)
+ field_probs = torch.ones_like(field_probs)
+ return (
+ membership,
+ field_probs,
+ output.structuring_span_idx[0],
+ torch.where(output.structuring_span_mask[0])[0],
+ None,
+ 0.1,
+ {i: f"f{i}" for i in range(fields)},
+ )
+
+
[email protected]("saturate", [False, True])
[email protected]("limit", [1, 5, 30, 100])
+def test_capped_documents_keep_each_slots_best_spans(limit: int, saturate: bool) -> None:
+ args = _slot_args(3, saturate=saturate)
+ full = structuring_decoding._slot_spans(*args, make_span=upstream.Span, max_spans=10**9)
+ capped = structuring_decoding._slot_spans(*args, make_span=upstream.Span, max_spans=limit)
+ flat = [(slot, span) for slot, spans in full for span in spans]
+ assert len(flat) > limit
+ head = {id(span) for span in _head([span for _, span in flat], limit)}
+ assert [slot for slot, _ in capped] == [slot for slot, _ in full]
+ for (_, everything), (_, kept) in zip(full, capped, strict=True):
+ # Each slot keeps the head of its own best-first order...
+ assert _as_tuples(kept) == _as_tuples([span for span in everything if id(span) in head])
+ # ...so its overlap removal keeps the head of the full result.
+ assert _as_tuples(select_spans(kept, False, False)) == _as_tuples(
+ [span for span in _UPSTREAM_GREEDY(_DECODER, everything, False, False) if id(span) in head]
+ )
+ assert sum(len(spans) for _, spans in capped) == limit
+
+
+def test_record_spans_are_bounded_per_document_not_per_slot() -> None:
+ args = _slot_args(5, slots=100, entities=64, fields=8, saturate=True)
+ capped = structuring_decoding._slot_spans(*args, make_span=upstream.Span, max_spans=1000)
+ assert sum(len(spans) for _, spans in capped) == 1000
+ assert len(capped) == 100
+
+
+def test_record_text_is_bounded_per_document() -> None:
+ span = upstream.Span
+ slots = [
+ (0, [span(start=0, end=99, entity_type="a", score=0.9), span(start=0, end=9, entity_type="a", score=0.5)]),
+ (1, [span(start=0, end=49, entity_type="b", score=0.7), span(start=60, end=60, entity_type="b", score=0.6)]),
+ ]
+ assert structuring_decoding._within_word_limit(slots, 161) is slots
+ # 100 + 50 words fit in 155; the next best (1 word, score 0.6) fits too; the last (10 words) does not.
+ kept = structuring_decoding._within_word_limit(slots, 155)
+ assert [(slot, [(s.start, s.end) for s in spans]) for slot, spans in kept] == [
+ (0, [(0, 99)]),
+ (1, [(0, 49), (60, 60)]),
+ ]
+ assert structuring_decoding._within_word_limit(slots, 50) == [(0, []), (1, [])]
+
+
+def test_fully_nested_records_stay_within_the_text_bound() -> None:
+ spans = [(i, 8190 - i) for i in range(4095)]
+ count = len(spans)
+ output = SimpleNamespace(
+ structuring_logits=torch.full((1, 3, count), 4.0),
+ structuring_field_logits=torch.full((1, count, 1), 4.0),
+ structuring_span_idx=torch.tensor([spans]),
+ structuring_span_mask=torch.ones(1, count, dtype=torch.bool),
+ structuring_batch_origin=torch.arange(1),
+ batch_size=1,
+ )
+ records = _STRUCTURING.decode(output, threshold=0.1, flat_ner=False, texts=[[f"w{i}" for i in range(8191)]])
+ fields = [field for group in records[0] for record in group for field in record]
+ words = sum(field["end"] - field["start"] + 1 for field in fields)
+ assert 0 < words <= structuring_decoding.MAX_RECORD_WORDS
+
+
+def test_record_spans_within_an_allowance_keep_each_slots_best_spans() -> None:
+ args = _slot_args(3)
+ full = structuring_decoding._slot_spans(*args, make_span=upstream.Span, max_spans=10**9)
+ flat = [span for _, spans in full for span in spans]
+ proposals = len(args[3])
+ cut_cost = (4 * proposals + proposals * 5) // 4 # open slots x proposals + proposals x fields, over 4
+ allowance = span_decoding.Allowance(cut_cost + 30)
+ capped = structuring_decoding._slot_spans(*args, make_span=upstream.Span, max_spans=10**9, allowance=allowance)
+ head = {id(span) for span in _head(flat, 30)}
+ for (_, everything), (_, kept) in zip(full, capped, strict=True):
+ assert _as_tuples(kept) == _as_tuples([span for span in everything if id(span) in head])
+ assert allowance.remaining == 0
+
+
+# -- Replacing the package's functions ---------------------------------------------
+
+
+def test_package_functions_are_replaced_once_with_their_originals_kept() -> None:
+ owner = SimpleNamespace()
+
+ def original(scores, labels=None, threshold=0.5):
+ return "original"
+
+ def replacement(scores, labels=None, threshold=0.5):
+ return "replacement"
+
+ owner.extract = original
+ adapter_module._replace_package_function(owner, "extract", replacement)
+ assert owner.extract is replacement
+ assert replacement._sie_original is original
+ adapter_module._replace_package_function(owner, "extract", lambda scores, labels=None, threshold=0.5: None)
+ assert owner.extract is replacement
+
+
+def test_package_function_replacement_fails_closed() -> None:
+ def original(scores, labels=None, threshold=0.5):
+ return None
+
+ def other_parameters(scores, threshold=0.5):
+ return None
+
+ with pytest.raises(RuntimeError, match="is missing"):
+ adapter_module._replace_package_function(SimpleNamespace(), "extract", original)
+ with pytest.raises(RuntimeError, match="changed its parameters"):
+ adapter_module._replace_package_function(SimpleNamespace(extract=original), "extract", other_parameters)
+ with pytest.raises(RuntimeError, match="must be verified again"):
+ adapter_module._replace_package_function(
+ SimpleNamespace(extract=original),
+ "extract",
+ lambda scores, labels=None, threshold=0.5: None,
+ source_sha256="0" * 64,
+ )
+
+
+def test_the_package_functions_are_bounded_after_import() -> None:
+ assert upstream.SpanDecoder._calculate_span_score._sie_bounded is True
+ assert upstream.SpanDecoder.greedy_search._sie_bounded is True
+ assert structuring_decoder.StructuringDecoder.decode._sie_bounded is True
+ assert structuring_model.extract_spans_from_tokens._sie_bounded is True
+ # Importing again leaves the replacements in place.
+ replaced = upstream.SpanDecoder._calculate_span_score
+ adapter_module._import_gliformer()
+ assert upstream.SpanDecoder._calculate_span_score is replaced
+
+
+def test_every_gliformer_binding_of_the_proposal_function_is_bounded() -> None:
+ for name in adapter_module._PROPOSAL_MODULES:
+ module = importlib.import_module(name)
+ if hasattr(module, "extract_spans_from_tokens"):
+ assert module.extract_spans_from_tokens._sie_bounded is True
+ adapter_module._assert_bounded_decoding()
+
+
+def test_bounded_decoding_check_rejects_an_override() -> None:
+ class _Overriding(upstream.SpanDecoder):
+ def greedy_search(self, spans, flat_ner=True, multi_label=False):
+ return spans
+
+ try:
+ with pytest.raises(RuntimeError, match="overrides"):
+ adapter_module._assert_bounded_decoding()
+ finally:
+ del _Overriding
+ gc.collect()
+ adapter_module._assert_bounded_decoding()
+
+
+def test_bounded_decoding_check_rejects_a_leftover_binding(monkeypatch: pytest.MonkeyPatch) -> None:
+ leftover = ModuleType("gliformer.tasks.leftover")
+ leftover.extract_spans_from_tokens = extract_spans_from_tokens
+ monkeypatch.setitem(sys.modules, "gliformer.tasks.leftover", leftover)
+ with pytest.raises(RuntimeError, match="still binds"):
+ adapter_module._assert_bounded_decoding()
+
+
+def test_replacements_are_verified_against_the_package_at_load() -> None:
+ adapter_module._verify_bounded_decoding(None)
+
+
[email protected]("target", ["propose_spans", "pair_spans", "select_spans", "make_structuring_decode"])
+def test_verification_fails_closed_when_a_replacement_differs(monkeypatch: pytest.MonkeyPatch, target: str) -> None:
+ # Swap the real implementation behind one installed replacement for one
+ # that drops its last result, as a changed package would look.
+ if target == "make_structuring_decode":
+ decode = structuring_decoder.StructuringDecoder.decode
+
+ def changed(self: Any, *args: Any, **kwargs: Any) -> Any:
+ return [[group[:-1] for group in item] for item in decode(self, *args, **kwargs)]
+
+ changed._sie_original = decode._sie_original
+ changed._sie_bounded = True
+ monkeypatch.setattr(structuring_decoder.StructuringDecoder, "decode", changed)
+ elif target == "propose_spans":
+ real = adapter_module.propose_spans
+
+ def changed(*args: Any, **kwargs: Any) -> Any:
+ span_idx, span_mask = real(*args, **kwargs)
+ return span_idx, span_mask & False
+
+ monkeypatch.setattr(adapter_module, target, changed)
+ else:
+ real = getattr(adapter_module, target)
+ monkeypatch.setattr(adapter_module, target, lambda *args, **kwargs: real(*args, **kwargs)[:-1])
+ with pytest.raises(RuntimeError, match="no longer matches its bounded replacement"):
+ adapter_module._verify_bounded_decoding(None)
+
+
+# -- Padding --------------------------------------------------------------------
+
+
+def _head_output(logits: torch.Tensor, mask: torch.Tensor | None) -> SimpleNamespace:
+ return SimpleNamespace(logits=logits, extra={} if mask is None else {"mask": mask})
+
+
+def test_padded_positions_are_masked_and_decode_as_the_document_alone() -> None:
+ alone = _bio_scores(5, length=9, labels=2, dtype=torch.float32)
+ # Batched with a longer document: the head scores padding with logit 0.
+ padded = torch.zeros(2, 20, 2, 3)
+ padded[0, :9] = alone
+ padded[1] = _bio_scores(6, length=20, labels=2, dtype=torch.float32)
+ mask = torch.zeros(2, 20, dtype=torch.long)
+ mask[0, :9] = 1
+ mask[1] = 1
+ names = {0: "a", 1: "b"}
+ for threshold in (0.1, 0.3, 0.5):
+ unmasked = _upstream(padded[0], names, threshold)
+ assert any(span.end >= 9 or span.score == 0.5 for span in unmasked) or threshold == 0.5
+ output = adapter_module._mask_padded_ner_logits(None, (), _head_output(padded.clone(), mask))
+ assert torch.equal(output.logits[1], padded[1])
+ assert bool(torch.isneginf(output.logits[0, 9:]).all())
+ assert _as_tuples(_upstream(output.logits[0], names, threshold)) == _as_tuples(
+ _upstream(alone, names, threshold)
+ )
+
+
+def test_padding_mask_leaves_unpadded_batches_alone() -> None:
+ logits = torch.randn(2, 5, 3, 3)
+ output = _head_output(logits, torch.ones(2, 5, dtype=torch.bool))
+ assert adapter_module._mask_padded_ner_logits(None, (), output).logits is logits
+ empty = SimpleNamespace(logits=None, extra={})
+ assert adapter_module._mask_padded_ner_logits(None, (), empty) is empty
+
+
[email protected]("mask", [None, torch.ones(2, 4, dtype=torch.bool), torch.ones(5, dtype=torch.bool)])
+def test_padding_mask_fails_closed_without_a_matching_word_mask(mask: torch.Tensor | None) -> None:
+ with pytest.raises(RuntimeError, match="word mask"):
+ adapter_module._mask_padded_ner_logits(None, (), _head_output(torch.zeros(2, 5, 3, 3), mask))
+
+
+def test_padding_mask_is_installed_on_the_ner_head() -> None:
+ ner_head = torch.nn.Identity()
+ reusing = SimpleNamespace(_owns_ner_head=False, _reused_ner_head=ner_head)
+ model = SimpleNamespace(heads={"ner": ner_head, "joint_relex": reusing, "structuring": reusing})
+ adapter_module._mask_padded_words(model)
+ assert list(ner_head._forward_hooks.values()) == [adapter_module._mask_padded_ner_logits]
+ assert "_forward_entity_ner" not in vars(reusing)
+ with pytest.raises(RuntimeError, match="no NER head"):
+ adapter_module._mask_padded_words(SimpleNamespace(heads={}))
+
+
+def test_padding_mask_covers_a_head_with_its_own_ner_pass() -> None:
+ padded = torch.zeros(1, 6, 2, 3)
+ mask = torch.tensor([[1, 1, 1, 0, 0, 0]])
+ calls = []
+
+ class _StructuringHead:
+ _owns_ner_head = True
+
+ def _forward_entity_ner(self, shared: Any, flat_inputs: Any, **kwargs: Any) -> Any:
+ calls.append((shared, flat_inputs, kwargs))
+ return _head_output(padded.clone(), mask)
+
+ head = _StructuringHead()
+ adapter_module._mask_padded_words(SimpleNamespace(heads={"ner": torch.nn.Identity(), "structuring": head}))
+ output = head._forward_entity_ner("shared", "inputs", threshold=0.3)
+ assert calls == [("shared", "inputs", {"threshold": 0.3})]
+ assert bool(torch.isneginf(output.logits[0, 3:]).all())
+ assert torch.equal(output.logits[0, :3], padded[0, :3])
+
+
+ "head",
+ [
+ SimpleNamespace(_owns_ner_head=False, _reused_ner_head=torch.nn.Identity()),
+ SimpleNamespace(_owns_ner_head=True),
+ SimpleNamespace(),
+ ],
+)
+def test_padding_mask_fails_closed_on_an_ner_pass_it_cannot_reach(head: Any) -> None:
+ with pytest.raises(RuntimeError, match="cannot mask"):
+ adapter_module._mask_padded_words(SimpleNamespace(heads={"ner": torch.nn.Identity(), "joint_relex": head}))
+
+
+# -- Relations --------------------------------------------------------------------
+
+joint_relex_decoder = importlib.import_module("gliformer.tasks.joint_relex.decoder")
+_UPSTREAM_RELATION_DECODE = joint_relex_decoder.JointRelexDecoder.decode._sie_original
+_RELATIONS = joint_relex_decoder.JointRelexDecoder(SimpleNamespace())
+
+
+def _relation_output(
+ seed: int,
+ *,
+ rows: int = 2,
+ length: int = 30,
+ labels: int = 3,
+ pairs: int = 40,
+ types: int = 4,
+ entity_spans: bool = False,
+) -> SimpleNamespace:
+ generator = torch.Generator().manual_seed(seed)
+ ner = torch.stack(
+ [_bio_scores(seed * 5 + row, length=length, labels=labels, dtype=torch.float32) for row in range(rows)]
+ )
+ idx = torch.randint(0, 12, (rows, pairs, 2), generator=generator)
+ output = SimpleNamespace(
+ ner_logits=ner,
+ ner_batch_origin=torch.arange(rows),
+ span_logits=None,
+ span_idx=None,
+ span_mask=None,
+ joint_rel_logits=torch.randn(rows, pairs, types, generator=generator) * 2,
+ joint_rel_idx=idx,
+ joint_rel_mask=torch.rand(rows, pairs, generator=generator) > 0.2,
+ joint_rel_batch_origin=torch.arange(rows),
+ batch_size=rows,
+ )
+ if entity_spans:
+ starts = torch.randint(0, length - 3, (rows, 12, 1), generator=generator)
+ output.joint_rel_entity_spans = torch.cat(
+ [starts, starts + torch.randint(0, 3, (rows, 12, 1), generator=generator)], -1
+ )
+ return output
+
+
[email protected]("entity_spans", [False, True])
[email protected]("threshold", [0.1, 0.3, 0.5])
[email protected]("seed", range(5))
+def test_relation_decoding_matches_the_package(seed: int, threshold: float, entity_spans: bool) -> None:
+ output = _relation_output(seed, entity_spans=entity_spans)
+ texts = [[f"w{i}" for i in range(30)] for _ in range(2)]
+ for flat_ner in (True, False):
+ kwargs = {"threshold": threshold, "flat_ner": flat_ner, "texts": texts}
+ expected = _UPSTREAM_RELATION_DECODE(_RELATIONS, output, **kwargs)
+ assert _RELATIONS.decode(output, **kwargs) == expected
+ assert entity_spans or any(expected)
+
+
+def test_relation_decoding_without_relation_outputs_matches_the_package() -> None:
+ empty = SimpleNamespace(joint_rel_logits=None, joint_rel_idx=None)
+ assert _RELATIONS.decode(empty) == _UPSTREAM_RELATION_DECODE(_RELATIONS, empty) == []
+
+
+def _flat(relations: list) -> list[dict]:
+ return [triple for item in relations for group in item for triple in group]
+
+
[email protected]("limit", [1, 5, 40])
+def test_capped_relations_keep_the_best_first_prefix(limit: int) -> None:
+ output = _relation_output(1, rows=1, pairs=60, types=6)
+ kwargs = {"threshold": 0.1, "texts": [[f"w{i}" for i in range(30)]]}
+ full = _flat(_UPSTREAM_RELATION_DECODE(_RELATIONS, output, **kwargs))
+ assert len(full) > limit
+ capped = _flat(
+ relation_decoding.make_relation_decode(
+ importlib.import_module("gliformer.tasks.ner.decoder").NERDecoder.decode,
+ joint_relex_decoder.unflatten_by_batch_origin,
+ max_relations=limit,
+ )(_RELATIONS, output, **kwargs)
+ )
+ expected = [triple for triple in full if id(triple) in {id(t.triple) for t in _head(_scored(full), limit)}]
+ assert capped == expected
+
+
+def _scored(triples: list[dict]) -> list[Any]:
+ return [SimpleNamespace(score=triple["score"], triple=triple) for triple in triples]
+
+
+def test_relation_text_is_bounded_per_document() -> None:
+ output = _relation_output(2, rows=1, pairs=60, types=6)
+ kwargs = {"threshold": 0.1, "texts": [[f"w{i}" for i in range(30)]]}
+ full = _flat(_UPSTREAM_RELATION_DECODE(_RELATIONS, output, **kwargs))
+ words = [t["head"]["end"] - t["head"]["start"] + 1 + t["tail"]["end"] - t["tail"]["start"] + 1 for t in full]
+ budget = sum(words) // 3
+ capped = _flat(
+ relation_decoding.make_relation_decode(
+ importlib.import_module("gliformer.tasks.ner.decoder").NERDecoder.decode,
+ joint_relex_decoder.unflatten_by_batch_origin,
+ max_words=budget,
+ )(_RELATIONS, output, **kwargs)
+ )
+ ranked = sorted(range(len(full)), key=lambda index: -full[index]["score"])
+ taken, used = set(), 0
+ for index in ranked:
+ if used + words[index] > budget:
+ break
+ used += words[index]
+ taken.add(index)
+ assert capped == [triple for index, triple in enumerate(full) if index in taken]
+ assert 0 < len(capped) < len(full)
+
+
+def test_relations_within_an_allowance_keep_the_best_first_prefix() -> None:
+ output = _relation_output(3, rows=1, pairs=60, types=6)
+ kwargs = {"threshold": 0.1, "texts": [[f"w{i}" for i in range(30)]]}
+ with span_decoding.document_allowances([10**9]) as rows:
+ full = _flat(_RELATIONS.decode(output, **kwargs))
+ spent = 10**9 - rows[0].remaining
+ kept_units = relation_decoding.RELATION_UNITS * len(full)
+ # Just enough for everything but the last few relations.
+ with span_decoding.document_allowances([spent - kept_units + relation_decoding.RELATION_UNITS * 4]) as rows:
+ capped = _flat(_RELATIONS.decode(output, **kwargs))
+ head = {id(item.triple) for item in _head(_scored(full), 4)}
+ assert capped == [triple for triple in full if id(triple) in head]
+ assert rows[0].remaining == 0
+
+
+def test_relations_cost_the_same_however_far_the_batch_pads_the_pairs() -> None:
+ output = _relation_output(7, rows=1, pairs=60, types=6)
+ padded = _relation_output(7, rows=1, pairs=60, types=6)
+ padded.joint_rel_logits = torch.cat([output.joint_rel_logits, torch.full((1, 500, 6), 3.0)], 1)
+ padded.joint_rel_idx = torch.cat([output.joint_rel_idx, torch.zeros(1, 500, 2, dtype=torch.long)], 1)
+ padded.joint_rel_mask = torch.cat([output.joint_rel_mask, torch.zeros(1, 500, dtype=torch.bool)], 1)
+ kwargs = {"threshold": 0.1, "texts": [[f"w{i}" for i in range(30)]]}
+ kept, spent = [], []
+ for relation_output in (output, padded):
+ with span_decoding.document_allowances([10**9]) as rows:
+ kept.append(_RELATIONS.decode(relation_output, **kwargs))
+ spent.append(10**9 - rows[0].remaining)
+ assert _flat(kept[0])
+ assert kept[0] == kept[1]
+ assert spent[0] == spent[1]
+
+
+def test_relation_cells_that_all_fail_decode_quickly() -> None:
+ output = _relation_output(4, rows=1, pairs=9900, types=20)
+ output.joint_rel_logits = torch.full((1, 9900, 20), -9.0)
+ start = time.perf_counter()
+ assert _flat(_RELATIONS.decode(output, threshold=0.5, texts=[[f"w{i}" for i in range(30)]])) == []
+ assert time.perf_counter() - start < 5