Skip to content

armgit / sie

Public Imported from GitHub
0

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

perf(gliformer): measure each task prompt once and skip the per-request eval() (#365)

svonavad41ba7fb828c
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 4af448f82..cdd3f8e84 100644
--- a/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/gliformer/adapter.py
@@ -3,10 +3,13 @@
from __future__ import annotations
import copy
+import hashlib
import logging
import math
import threading
import warnings
+import weakref
+from collections import OrderedDict
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from numbers import Real
@@ -94,6 +97,11 @@ _MAX_TYPE_GROUPS = 64
# Marks an item whose model output could not be used.
_ITEM_ERROR = "__gliformer_item_error__"
+# 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
+# re-tokenizing it.
+_PROMPT_CACHE_SIZE = 256
+
_IMPORT_LOCK = threading.Lock()
@@ -315,6 +323,7 @@ class GLiFormerAdapter(BaseAdapter):
self._tokenizer: Any = None
self._normalize_structures: Callable[[Any], Any] | None = None
self._build_formatter: Callable[[Any], Any] | None = None
+ self._prompt_counts: OrderedDict[bytes, int] = OrderedDict()
self._device: str | None = None
def load(self, device: str) -> None:
@@ -345,6 +354,7 @@ class GLiFormerAdapter(BaseAdapter):
dtype = torch.float32 if device == "cpu" else self._resolve_dtype()
model.to(device=device, dtype=dtype)
model.eval()
+ _skip_redundant_eval(model)
model.model.register_forward_hook(_upcast_score_outputs)
_limit_relation_entities(model.model)
@@ -365,6 +375,7 @@ class GLiFormerAdapter(BaseAdapter):
self._tokenizer = tokenizer
self._normalize_structures = gliformer.processing.schema.normalize_structuring_schemas
self._build_formatter = gliformer.processing.schema.build_structuring_output_formatter
+ self._prompt_counts = OrderedDict()
self._device = device
def extract(
@@ -602,17 +613,46 @@ class GLiFormerAdapter(BaseAdapter):
return rows
def _prompt_tokens(self, task_kwargs: dict[str, Any]) -> int:
- """Build one task prompt with the package's processor and count its tokens.
+ """Count the tokens of one task prompt, measuring each distinct prompt once.
GLiFormer prepends the same prompt to every document of a task group
and truncates the combined sequence to ``max_len``, so the prompt is
- measured once per group, not per document.
+ measured once per group, not per document. The task arguments hold
+ only strings, lists, dicts and ``None``, so their ``repr`` identifies
+ the prompt, in order. The limits are checked on every request.
Raises:
InvalidInputError: The prompt exceeds ``max_prompt_tokens`` or
leaves no room for a document.
RuntimeError: The package's processor could not build the prompt.
"""
+ cache = self._prompt_counts
+ key = hashlib.sha256(repr(task_kwargs).encode()).digest()
+ count = cache.get(key)
+ if count is None:
+ count = self._measure_prompt(task_kwargs)
+ cache[key] = count
+ if len(cache) > _PROMPT_CACHE_SIZE:
+ cache.popitem(last=False)
+ else:
+ cache.move_to_end(key)
+ if count > self._max_prompt_tokens:
+ raise InvalidInputError(
+ f"GLiFormer task prompt needs {count} tokens; labels, relation types, class labels, and "
+ f"schema fields may take at most {self._max_prompt_tokens}"
+ )
+ model = self._model
+ specials = int(model.data_processor.transformer_tokenizer.num_special_tokens_to_add(pair=False))
+ if count + specials >= int(model.config.max_len):
+ raise InvalidInputError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)
+ return count
+
+ def _measure_prompt(self, task_kwargs: dict[str, Any]) -> int:
+ """Build one task prompt with the package's processor and count its tokens.
+
+ Raises:
+ RuntimeError: The package's processor could not build the prompt.
+ """
model = self._model
processor = model.data_processor
try:
@@ -628,18 +668,9 @@ class GLiFormerAdapter(BaseAdapter):
encoded = processor.transformer_tokenizer(
[prompt_words], is_split_into_words=True, add_special_tokens=False
)
- count = len(encoded["input_ids"][0])
+ return len(encoded["input_ids"][0])
except Exception as exc:
raise RuntimeError("GLiFormer could not build the task prompt") from exc
- if count > self._max_prompt_tokens:
- raise InvalidInputError(
- f"GLiFormer task prompt needs {count} tokens; labels, relation types, class labels, and "
- f"schema fields may take at most {self._max_prompt_tokens}"
- )
- specials = int(processor.transformer_tokenizer.num_special_tokens_to_add(pair=False))
- if count + specials >= int(model.config.max_len):
- raise InvalidInputError(_ERR_PROMPT_EXHAUSTS_DOCUMENT)
- return count
def _document_tokens(self, texts: list[str]) -> list[int]:
"""Document subwords per text before the prompt's share of the window.
@@ -680,6 +711,27 @@ class GLiFormerAdapter(BaseAdapter):
]
+def _skip_redundant_eval(model: Any) -> None:
+ """Make ``model.eval()`` return at once while the model is in eval mode.
+
+ ``GLiFormer.inference`` and ``embed_text`` call ``eval()`` on every
+ request, which walks all of the model's ~600 modules to clear training
+ flags that are already clear. The adapter never switches the model to
+ training, so only a model left in training mode still needs the walk,
+ which is what ``torch.nn.Module.eval`` does: ``train(False)``. The model
+ is held weakly, so the method stored on it adds no reference cycle.
+ """
+ model_ref = weakref.ref(model)
+
+ def eval_if_training() -> Any:
+ current = model_ref()
+ if current is not None and current.training:
+ current.train(False)
+ return current
+
+ model.eval = eval_if_training
+
+
def _limit_relation_entities(model: Any) -> None:
"""Keep only the most confident entities as relation candidates.
diff --git a/packages/sie_server/tests/adapters/test_gliformer.py b/packages/sie_server/tests/adapters/test_gliformer.py
index 038bd7052..358370c1a 100644
--- a/packages/sie_server/tests/adapters/test_gliformer.py
+++ b/packages/sie_server/tests/adapters/test_gliformer.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import subprocess
import sys
import time
+import weakref
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any, Literal
@@ -967,6 +968,69 @@ def test_every_task_group_is_measured_before_inference_runs() -> None:
model.inference.assert_not_called()
+def _prompt_measurements(model: MagicMock) -> int:
+ return sum(sequences == [["P", "P", "P"]] for sequences in model.data_processor.transformer_tokenizer.calls)
+
+
+def test_a_repeated_task_prompt_is_measured_once() -> None:
+ adapter, model = _adapter({"ner": [[]]})
+
+ for text in ("Alice works here", "Bob works there", "Alice works here"):
+ adapter.extract([Item(text=text)], labels=["person", "place"])
+
+ assert _prompt_measurements(model) == 1
+ assert model.inference.call_count == 3
+
+
+def test_task_prompts_are_cached_by_their_exact_task_arguments() -> None:
+ adapter, model = _adapter({"ner": [[]]})
+ requests: list[dict[str, Any]] = [
+ {"labels": ["person", "place"]},
+ {"labels": ["place", "person"]},
+ {"labels": ["person"], "options": {"relation_labels": ["works at"]}},
+ {"options": {"label_groups": {"a": ["x", "y"]}, "threshold": 0.0}},
+ {"options": {"label_groups": {"a": ["y", "x"]}, "threshold": 0.0}},
+ {"options": {"label_groups": {"b": ["x", "y"]}, "threshold": 0.0}},
+ ]
+
+ for request in requests:
+ adapter.extract([Item(text="Alice works here")], **request)
+ assert _prompt_measurements(model) == len(requests)
+
+ for request in requests:
+ adapter.extract([Item(text="Alice works here")], **request)
+ assert _prompt_measurements(model) == len(requests)
+
+
+def test_prompt_limits_are_checked_on_every_request() -> None:
+ adapter, model = _adapter({"ner": [[]]}, max_prompt_tokens=2)
+
+ for _ in range(2):
+ with pytest.raises(InvalidInputError, match="task prompt needs 3 tokens"):
+ adapter.extract([Item(text="Alice works here")], labels=["person"])
+
+ assert _prompt_measurements(model) == 1
+ model.inference.assert_not_called()
+
+
+def test_prompt_cache_keeps_the_most_recently_used_prompts(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(adapter_module, "_PROMPT_CACHE_SIZE", 2)
+ adapter, model = _adapter({"ner": [[]]})
+
+ def request(label: str) -> None:
+ adapter.extract([Item(text="Alice works here")], labels=[label])
+
+ for label in ("a", "b", "a", "c"):
+ request(label)
+ assert len(adapter._prompt_counts) == 2
+ assert _prompt_measurements(model) == 3
+
+ request("a")
+ assert _prompt_measurements(model) == 3
+ request("b")
+ assert _prompt_measurements(model) == 4
+
+
def test_prompt_build_failure_is_an_internal_error() -> None:
adapter, model = _adapter({"ner": [[]]})
model.data_processor.collate_raw_batch.side_effect = KeyError("processor drift")
@@ -1124,6 +1188,7 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
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}
+ set_eval_mode = model.eval
tokenizer = model.data_processor.transformer_tokenizer
precision_kwargs = {} if precision is None else {"compute_precision": precision}
adapter = GLiFormerAdapter(
@@ -1153,7 +1218,7 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
max_length=2048,
)
model.to.assert_called_once_with(device=device, dtype=dtype)
- model.eval.assert_called_once_with()
+ set_eval_mode.assert_called_once_with()
model.model.register_forward_hook.assert_called_once_with(adapter_module._upcast_score_outputs)
assert relation_head.max_relation_entities == 100
assert tokenizer.model_max_length == 2048
@@ -1166,6 +1231,46 @@ def test_load_pins_snapshot_and_places_model(device: str, precision: str | None,
assert adapter._tokenizer is 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)}
+ 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
+ model.training = True
+ adapter = GLiFormerAdapter("/local/checkpoint")
+ with (
+ patch.dict(sys.modules, {"gliformer": _fake_gliformer_module(model)}),
+ patch.object(adapter_module.Path, "is_dir", return_value=True),
+ ):
+ adapter.load("cpu")
+ set_eval_mode.assert_called_once_with()
+
+ # GLiFormer.inference calls eval() on every request.
+ assert model.eval() is model
+ assert model.eval() is model
+ model.train.assert_not_called()
+
+ model.training = True
+ assert model.eval() is model
+ model.train.assert_called_once_with(False)
+ assert model.training is False
+
+
+def test_per_request_eval_shortcut_does_not_keep_the_model_alive() -> None:
+ class _Model:
+ training = False
+
+ model = _Model()
+ adapter_module._skip_redundant_eval(model)
+ released = weakref.ref(model)
+
+ del model
+
+ assert released() is None
+
+
def test_load_rejects_embedding_dimension_mismatch() -> None:
model = MagicMock()
model.config = SimpleNamespace(max_len=2048, embedding_config=SimpleNamespace(projection_dim=768))