Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
perf(server): build GLiNER encoders on the target device (#863)
Shai Shmuel4ddaaba309d5
diff --git a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py b/packages/sie_server/src/sie_server/adapters/gliner/__init__.pyindex 08f9f69b6..19c78ea18 100644--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py@@ -204,10 +204,31 @@ class GLiNERAdapter(BaseAdapter):if self._revision is not None:load_kwargs["revision"] = self._revisioninstall_transformers_security_fixes()- self._model = GLiNER.from_pretrained(- self._model_name_or_path,- **load_kwargs,- )+ # gliner initialises the encoder from its config before reading the+ # checkpoint, so build it where the weights end up. The fp32 model and+ # checkpoint are both resident there until the cast below; a device+ # without room for that peak still gets the CPU-built model.+ # safetensors reads a bare "cuda" as cuda:0, whatever the current device.+ build_device = f"cuda:{torch.cuda.current_device()}" if device == "cuda" else device+ self._model = None+ try:+ with torch.device(build_device):+ self._model = GLiNER.from_pretrained(+ self._model_name_or_path,+ map_location=build_device,+ **load_kwargs,+ )+ except RuntimeError as exc:+ if not _is_out_of_memory(exc):+ raise+ if self._model is None:+ if device.startswith("cuda"):+ torch.cuda.empty_cache()+ with torch.device("cpu"):+ self._model = GLiNER.from_pretrained(+ self._model_name_or_path,+ **load_kwargs,+ )# Move to device with precisionif device == "cpu":@@ -708,6 +729,11 @@ def _best_relations(relations: list[dict[str, Any]]) -> list[dict[str, Any]]:return list(best.values())+def _is_out_of_memory(exc: RuntimeError) -> bool:+ # MPS allocator exhaustion is a plain RuntimeError, not torch.OutOfMemoryError.+ return isinstance(exc, torch.OutOfMemoryError) or "out of memory" in str(exc).lower()++def _cap_relation_candidates(model: Any, limit: int) -> None:"""Keep at most ``limit`` entity candidates per item for relation scoring.diff --git a/packages/sie_server/tests/adapters/test_gliner_load_device.py b/packages/sie_server/tests/adapters/test_gliner_load_device.pynew file mode 100644index 000000000..d24f8f8e7--- /dev/null+++ b/packages/sie_server/tests/adapters/test_gliner_load_device.py@@ -0,0 +1,95 @@+"""GLiNER adapter builds the model on the target device, with a CPU fallback on OOM."""++from __future__ import annotations++import sys+from types import ModuleType+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+import torch+from sie_server.adapters.gliner import GLiNERAdapter+++class FakeGLiNER:+ def __init__(self) -> None:+ self.config = MagicMock(relations_layer=None, max_len=384)+ self.config.encoder_config = {"model_type": "bert"}+ self.model = MagicMock()+ self.data_processor = MagicMock()+ self.data_processor.transformer_tokenizer = MagicMock(model_max_length=512)++ def to(self, *args: Any, **kwargs: Any) -> FakeGLiNER:+ return self+++def load_with(monkeypatch: pytest.MonkeyPatch, from_pretrained: MagicMock, device: str) -> GLiNERAdapter:+ module = ModuleType("gliner")+ module.GLiNER = MagicMock(from_pretrained=from_pretrained) # ty:ignore[unresolved-attribute]+ monkeypatch.setitem(sys.modules, "gliner", module)+ adapter = GLiNERAdapter("fake/gliner", revision="0" * 40)+ with (+ patch("sie_server.adapters.gliner.install_transformers_security_fixes"),+ patch("sie_server.adapters.gliner.bound_gliner_words", return_value=False),+ patch("sie_server.adapters.gliner.gliner_prompt_counter", return_value=lambda *_: 0),+ ):+ adapter.load(device)+ return adapter+++def test_gliner_builds_the_model_on_the_target_device(monkeypatch: pytest.MonkeyPatch) -> None:+ seen: list[torch.device] = []++ def from_pretrained(*_args: Any, **_kwargs: Any) -> FakeGLiNER:+ seen.append(torch.get_default_device())+ return FakeGLiNER()++ load_with(monkeypatch, MagicMock(side_effect=from_pretrained), "cpu")++ assert seen == [torch.device("cpu")]+++def test_gliner_passes_the_device_as_map_location(monkeypatch: pytest.MonkeyPatch) -> None:+ from_pretrained = MagicMock(return_value=FakeGLiNER())++ load_with(monkeypatch, from_pretrained, "cpu")++ assert from_pretrained.call_args.kwargs["map_location"] == "cpu"+ assert from_pretrained.call_args.kwargs["revision"] == "0" * 40+++ "error",+ [torch.OutOfMemoryError("CUDA out of memory"), RuntimeError("MPS backend out of memory (MPS allocated: 7.9 GB)")],+)+def test_gliner_falls_back_to_cpu_construction_when_the_device_is_full(+ monkeypatch: pytest.MonkeyPatch, error: RuntimeError+) -> None:+ model = FakeGLiNER()+ seen: list[torch.device] = []++ def from_pretrained_once_full(*_args: Any, **_kwargs: Any) -> FakeGLiNER:+ if not seen:+ seen.append(torch.get_default_device())+ raise error+ seen.append(torch.get_default_device())+ return model++ from_pretrained = MagicMock(side_effect=from_pretrained_once_full)++ adapter = load_with(monkeypatch, from_pretrained, "cpu")++ assert from_pretrained.call_count == 2+ assert "map_location" not in from_pretrained.call_args_list[1].kwargs+ assert seen == [torch.device("cpu"), torch.device("cpu")]+ assert adapter._model is model+++def test_gliner_propagates_other_load_errors(monkeypatch: pytest.MonkeyPatch) -> None:+ from_pretrained = MagicMock(side_effect=RuntimeError("size mismatch for token_rep_layer"))++ with pytest.raises(RuntimeError, match="size mismatch"):+ load_with(monkeypatch, from_pretrained, "cpu")++ assert from_pretrained.call_count == 1diff --git a/packages/sie_server/tests/config/test_gliner_pii_profile.py b/packages/sie_server/tests/config/test_gliner_pii_profile.pyindex b84f50c90..461ac4d63 100644--- a/packages/sie_server/tests/config/test_gliner_pii_profile.py+++ b/packages/sie_server/tests/config/test_gliner_pii_profile.py@@ -66,7 +66,7 @@ def test_pii_cuda_load_uses_full_precision(mocked_gliner: tuple[Mock, Mock]) ->factory, model = mocked_glineradapter = load_adapter(load_model_config(_CONFIG), _MODELS, device="cuda:0")adapter.load("cuda:0")- factory.assert_called_once_with(_MODEL, revision=_REVISION)+ factory.assert_called_once_with(_MODEL, map_location="cuda:0", revision=_REVISION)model.to.assert_called_once_with("cuda:0", dtype=torch.float32)