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
fix(models): serve Iso-ModernColBERT with its PyLate recipe (#436)
svonava422232f17846
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex add2193d1..5fb18f50e 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -495,7 +495,7 @@ document dot products for dense models and MaxSim for late interaction:| `granite-embedding-97m-multilingual-r2` | 0.006 | 57 (0.008) | 0.015 (0.015) || `Reason-ModernColBERT` | 0.007 | 1 (0.007) | 0.022 (0.021) || `mLateOn` | 0.020 | 17 (0.029) | 0.037 (0.046) |-| `Iso-ModernColBERT` | 0.047 | 19 (0.058) | 0.082 (0.100) |+| `Iso-ModernColBERT` | none (bit-identical) | none | 0.20 (0.21) |Graphs meet the rule a GLiClass speed-up ships under (see "When a speed-upships enabled" above), read for scores instead of label probabilities: no@@ -512,6 +512,36 @@ and 0.7644 with graphs, `GTE-ModernColBERT-v1` 0.7573 and 0.7558, and`gte-reranker-modernbert-base` reranking the top 20 of `gte-modernbert-base`0.7760 and 0.7767.+The eager batching noise is largest for `mxbai-edge-colbert-v0-32m` and+`Iso-ModernColBERT` because their profiles compute in bfloat16, whose+significand is three bits shorter than float16's (the other late-interaction+models compute in float16). With more packed rows, cuBLAS picks a different+matrix-multiply kernel; in the forward we traced, the first outputs to differ,+by one unit in the last place, were those of the first layer's attention output+projection. A few document tokens amplify that rounding: punctuation, `[SEP]`+or the `[D] ` marker, close to where the encoder turns a token into an attention+sink. The token builds a large activation in one forward and not in the other,+so its vector turns. Per-token cosine to the one-item forward went as low as+0.82 for `Iso-ModernColBERT` on the abstracts above, while more than 99.8% of+tokens stayed above 0.999 on a sample of mixed lengths. The reference+implementation behaves the same way. PyLate in bfloat16 moves such tokens as+much between a document encoded alone and in a batch; in float32 neither PyLate+nor the Hugging Face forward moves them. In float32 on the CPU, this adapter's+packed forward gives each item the same vectors alone and in any batch, equal+to the Hugging Face forward (`tests/adapters/test_colbert_modernbert_flash_batch_invariance.py`).++`Iso-ModernColBERT` serves the recipe its checkpoint publishes for PyLate, as+`GTE-ModernColBERT-v1` does:++- `[Q] ` and `[D] ` markers;+- queries cut at 32 tokens and documents at 300 (its `long_context` profile+ keeps 8,192);+- the punctuation skiplist, which drops the document vectors that training+ never scores.++Its row above was measured with that recipe. With it, SciFact nDCG@10 rose from+0.7326 to 0.7573 (PyLate: 0.7574 in bfloat16, 0.7584 in float32).+The shipped profiles of every model on these adapters load with `bucketed`graphs: `GTE-ModernColBERT-v1`, `Reason-ModernColBERT`, `mLateOn`,`Iso-ModernColBERT`, `mxbai-edge-colbert-v0-32m`, `gte-modernbert-base`,diff --git a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yamlindex c81a0006b..f3413f5c9 100644--- a/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml+++ b/packages/sie_server/models/topk-io__Iso-ModernColBERT.yaml@@ -26,9 +26,14 @@ profiles:normalize: truequery_max_length: 32skip_special_tokens: false- doc_punctuation_skiplist: false+ query_prefix: '[Q] '+ doc_prefix: '[D] '+ doc_punctuation_skiplist: truecuda_graphs: bucketed- runtime: {}+ runtime:+ # The checkpoint's PyLate recipe (config_sentence_transformers.json).+ query_max_length: 32+ max_seq_length: 300candle:extends: defaultadapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter@@ -49,8 +54,16 @@ profiles:extends: defaultadapter_options:runtime:+ query_max_length: 32+ max_seq_length: 300output_types:- denseoutput_similarity:dense: dotmuvera: {}+ long_context:+ extends: default+ adapter_options:+ runtime:+ query_max_length: 32+ max_seq_length: 8192diff --git a/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_batch_invariance.py b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_batch_invariance.pynew file mode 100644index 000000000..98800bbc8--- /dev/null+++ b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_batch_invariance.py@@ -0,0 +1,221 @@+"""Late-interaction token vectors of the ModernBERT flash adapter, alone and batched.++The adapter packs a request's items into one unpadded token stream and keeps+them apart with ``cu_seqlens``: each item attends only to its own tokens,+within the sliding window on local layers, at positions that restart per+item. In float32 an item's token vectors therefore do not depend on which+other items share its request, and they equal the Hugging Face+``ModernBertModel`` forward of that item through the same head. These CPU+tests check both on tiny models laid out like the served checkpoints, with a+small reference standing in for flash-attn's varlen kernel.++In half precision the vectors do move with the batch: a different number of+packed rows makes cuBLAS pick a different matrix-multiply kernel, which+rounds differently. That is rounding, not the layout these tests pin down.+"""++from __future__ import annotations++import sys+import types+from itertools import pairwise+from typing import Any++import numpy as np+import pytest+import torch+from sie_server.adapters._pylate_dense import apply_dense_chain+from sie_server.adapters.colbert_modernbert_flash.adapter import ColBERTModernBERTFlashAdapter+from sie_server.types.inputs import Item+from tokenizers import Tokenizer, models, pre_tokenizers, processors+from torch.nn import functional+from transformers import ModernBertConfig, ModernBertModel, PreTrainedTokenizerFast++_HIDDEN = 32+_TOKEN_DIM = 8+_MAX_LENGTH = 64+_WORDS = ["the", "a", "patient", "drug", "trial", "dose", "protein", "cell", "gene", "effect", "risk", "study"]+++def _text(i: int) -> str:+ clause = " ".join((_WORDS[i % len(_WORDS)], *_WORDS[: 1 + (7 * i) % len(_WORDS)])) + " ,"+ return " ".join([clause] * (1 + i // 3)) + " ."+++# From two words to past the window: rows of different lengths pack against+# each other, span several sliding windows, and the longest are truncated.+_TEXTS = [_text(i) for i in range(14)]+# Layouts of the served checkpoints, scaled down: which layers attend+# globally, the sliding window, and the RoPE bases of global and local layers.+_LAYOUTS = {+ # GTE-ModernColBERT-v1, Iso-ModernColBERT, Reason-ModernColBERT+ "modernbert-base": {"global_attn_every_n_layers": 3, "local_rope_theta": 10000.0},+ # mxbai-edge-colbert-v0-32m (Ettin), mLateOn (mmBERT)+ "ettin-mmbert": {"global_attn_every_n_layers": 3, "local_rope_theta": 160000.0},+ "all-global": {"global_attn_every_n_layers": 1, "local_rope_theta": 10000.0},+}+++def _reference_varlen(+ query: torch.Tensor,+ key: torch.Tensor,+ value: torch.Tensor,+ cu_seqlens_q: torch.Tensor,+ cu_seqlens_k: torch.Tensor,+ max_seqlen_q: int,+ max_seqlen_k: int,+ *,+ causal: bool = False,+ softmax_scale: float | None = None,+ window_size: tuple[int, int] = (-1, -1),+) -> torch.Tensor:+ """``flash_attn_varlen_func``: attention within each sequence and, if given, its window."""+ assert not causal+ assert torch.equal(cu_seqlens_q, cu_seqlens_k)+ bounds = cu_seqlens_q.tolist()+ assert max(end - start for start, end in pairwise(bounds)) == max_seqlen_q == max_seqlen_k+ out = torch.full_like(query, float("nan"))+ for start, end in pairwise(bounds):+ rows = [t[start:end].transpose(0, 1) for t in (query, key, value)]+ mask = None+ if window_size != (-1, -1):+ positions = torch.arange(end - start)+ mask = (positions[:, None] - positions[None, :]).abs() <= window_size[0]+ attended = functional.scaled_dot_product_attention(*rows, attn_mask=mask, scale=softmax_scale)+ out[start:end] = attended.transpose(0, 1)+ return out++[email protected](autouse=True)+def reference_flash(monkeypatch: pytest.MonkeyPatch) -> None:+ module = types.ModuleType("flash_attn")+ module.flash_attn_varlen_func = _reference_varlen # ty: ignore[unresolved-attribute]+ monkeypatch.setitem(sys.modules, "flash_attn", module)+++def _tokenizer() -> PreTrainedTokenizerFast:+ specials = ["[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", "[Q] ", "[D] "]+ vocab = {token: index for index, token in enumerate([*specials, *_WORDS, ".", ","])}+ backend = Tokenizer(models.WordLevel(vocab, unk_token="[UNK]")) # noqa: S106 -- a vocabulary entry, not a secret+ backend.pre_tokenizer = pre_tokenizers.Whitespace()+ backend.post_processor = processors.TemplateProcessing(+ single="[CLS] $A [SEP]",+ special_tokens=[("[CLS]", vocab["[CLS]"]), ("[SEP]", vocab["[SEP]"])],+ )+ tokenizer = PreTrainedTokenizerFast(+ tokenizer_object=backend,+ pad_token="[MASK]", # noqa: S106 -- the served checkpoints pad with [MASK]+ unk_token="[UNK]", # noqa: S106+ cls_token="[CLS]", # noqa: S106+ sep_token="[SEP]", # noqa: S106+ model_max_length=_MAX_LENGTH,+ )+ tokenizer.add_tokens(["[Q] ", "[D] "])+ return tokenizer+++def _model(layout: str) -> ModernBertModel:+ torch.manual_seed(0)+ config = ModernBertConfig(+ vocab_size=32,+ hidden_size=_HIDDEN,+ intermediate_size=48,+ num_hidden_layers=4,+ num_attention_heads=2,+ local_attention=8,+ global_rope_theta=160000.0,+ max_position_embeddings=_MAX_LENGTH,+ pad_token_id=4,+ reference_compile=False,+ attn_implementation="eager",+ **_LAYOUTS[layout],+ )+ model = ModernBertModel(config).eval()+ # Larger attention logits, so a wrong position, window, RoPE base or+ # neighbouring item changes the outputs visibly.+ with torch.no_grad():+ for name, parameter in model.named_parameters():+ if "Wqkv" in name:+ parameter.mul_(8.0)+ return model+++def _adapter(layout: str) -> ColBERTModernBERTFlashAdapter:+ adapter = ColBERTModernBERTFlashAdapter(+ "tiny",+ token_dim=_TOKEN_DIM,+ compute_precision="float32",+ max_seq_length=_MAX_LENGTH,+ query_max_length=16,+ query_prefix="[Q] ",+ doc_prefix="[D] ",+ skip_special_tokens=False,+ doc_punctuation_skiplist=True,+ )+ torch.manual_seed(1)+ adapter._model, adapter._tokenizer, adapter._device = _model(layout), _tokenizer(), "cpu"+ adapter._dense_chain = [torch.randn(16, _HIDDEN), torch.randn(_TOKEN_DIM, 16)]+ adapter._doc_skiplist_ids = {adapter._tokenizer.convert_tokens_to_ids(t) for t in (".", ",")}+ return adapter+++def _encode(adapter: ColBERTModernBERTFlashAdapter, texts: list[str], *, is_query: bool) -> list[np.ndarray]:+ items = [Item(text=text) for text in texts]+ return adapter.encode(items, ["multivector"], is_query=is_query).multivector+++def _reference(adapter: ColBERTModernBERTFlashAdapter, texts: list[str], *, is_query: bool) -> list[np.ndarray]:+ """The Hugging Face forward of a right-padded batch, through the adapter's head and token filter."""+ tokenizer = adapter._tokenizer+ assert tokenizer is not None+ prefixed = adapter._extract_texts([Item(text=text) for text in texts], None, is_query=is_query)+ batch = tokenizer(+ prefixed,+ max_length=adapter._query_max_length if is_query else adapter._max_seq_length,+ truncation=True,+ padding=True,+ return_tensors="pt",+ )+ with torch.inference_mode():+ hidden = adapter._model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"]).last_hidden_state+ vectors = functional.normalize(apply_dense_chain(hidden, adapter._dense_chain)[..., :_TOKEN_DIM], dim=-1)+ skip = set() if is_query else adapter._doc_skiplist_ids+ out = []+ for row, ids, mask in zip(vectors, batch["input_ids"], batch["attention_mask"], strict=True):+ keep = mask.bool() & torch.tensor([int(i) not in skip for i in ids])+ out.append(row[keep].numpy())+ return out+++def _assert_same(got: list[np.ndarray], want: list[np.ndarray], *, atol: float) -> None:+ assert [g.shape for g in got] == [w.shape for w in want]+ for g, w in zip(got, want, strict=True):+ np.testing.assert_allclose(g, w, atol=atol, rtol=0)++[email protected]("layout", sorted(_LAYOUTS))[email protected]("is_query", [False, True])+def test_token_vectors_do_not_depend_on_the_other_items_in_a_request(layout: str, is_query: bool) -> None:+ adapter = _adapter(layout)+ alone = [_encode(adapter, [text], is_query=is_query)[0] for text in _TEXTS]+ for size in (2, 4, 8):+ batched: list[Any] = [None] * len(_TEXTS)+ # Interleave long and short rows, so each request mixes lengths.+ order = [i for pair in zip(range(7), range(13, 6, -1), strict=True) for i in pair]+ for start in range(0, len(order), size):+ request = order[start : start + size]+ for i, vectors in zip(+ request, _encode(adapter, [_TEXTS[i] for i in request], is_query=is_query), strict=True+ ):+ batched[i] = vectors+ _assert_same(batched, alone, atol=1e-5)++[email protected]("layout", sorted(_LAYOUTS))[email protected]("is_query", [False, True])+def test_token_vectors_match_the_hugging_face_forward(layout: str, is_query: bool) -> None:+ adapter = _adapter(layout)+ want = _reference(adapter, _TEXTS, is_query=is_query)+ assert any(len(w) > 8 for w in want) # rows span more than one sliding window+ _assert_same(_encode(adapter, _TEXTS, is_query=is_query), want, atol=1e-5)+ _assert_same([_encode(adapter, [text], is_query=is_query)[0] for text in _TEXTS], want, atol=1e-5)diff --git a/packages/sie_server/tests/config/test_gte_modern_colbert_profiles.py b/packages/sie_server/tests/config/test_gte_modern_colbert_profiles.pyindex 0c839d4f8..cd3487925 100644--- a/packages/sie_server/tests/config/test_gte_modern_colbert_profiles.py+++ b/packages/sie_server/tests/config/test_gte_modern_colbert_profiles.py@@ -43,7 +43,7 @@ def test_long_context_changes_only_document_length() -> None:[("lightonai__GTE-ModernColBERT-v1.yaml", True),("lightonai__Reason-ModernColBERT.yaml", False),- ("topk-io__Iso-ModernColBERT.yaml", False),+ ("topk-io__Iso-ModernColBERT.yaml", True),],)def test_flash_and_fallback_share_explicit_punctuation_policy(filename: str, expected: bool) -> None:diff --git a/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py b/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.pynew file mode 100644index 000000000..2fa443bab--- /dev/null+++ b/packages/sie_server/tests/config/test_iso_moderncolbert_profiles.py@@ -0,0 +1,54 @@+from __future__ import annotations++from pathlib import Path++import yaml+from sie_server.config.model import ModelConfig++_MODEL_PATH = Path(__file__).resolve().parents[2] / "models" / "topk-io__Iso-ModernColBERT.yaml"+++def _config() -> ModelConfig:+ return ModelConfig.model_validate(yaml.safe_load(_MODEL_PATH.read_text()))+++def test_default_and_muvera_follow_the_published_pylate_recipe() -> None:+ """The checkpoint's ``config_sentence_transformers.json`` (revision a43b93e).++ PyLate marks queries and documents with ``[Q] ``/``[D] `` after ``[CLS]``,+ cuts queries at 32 tokens and documents at 300, and drops the 32+ punctuation skiplist words from document vectors (the training loss never+ saw them, so their vectors are unconstrained).+ """+ config = _config()++ for name in ("default", "muvera"):+ profile = config.resolve_profile(name)+ assert profile.compute_precision == "bfloat16"+ assert profile.loadtime["query_prefix"] == "[Q] "+ assert profile.loadtime["doc_prefix"] == "[D] "+ assert profile.loadtime["doc_punctuation_skiplist"] is True+ assert profile.loadtime["skip_special_tokens"] is False+ assert profile.runtime["query_max_length"] == 32+ assert profile.runtime["max_seq_length"] == 300++ assert config.resolve_profile("muvera").runtime["output_similarity"] == {"dense": "dot"}+++def test_long_context_changes_only_document_length() -> None:+ config = _config()+ default = config.resolve_profile("default")+ long_context = config.resolve_profile("long_context")++ assert long_context.loadtime == default.loadtime+ assert long_context.runtime == dict(default.runtime) | {"max_seq_length": 8192}+++def test_candle_profile_keeps_its_own_options() -> None:+ """The Candle worker refuses the prefix and skiplist options, so its profile declares its own."""+ candle = _config().resolve_profile("candle")++ assert "query_prefix" not in candle.loadtime+ assert "doc_prefix" not in candle.loadtime+ assert "doc_punctuation_skiplist" not in candle.loadtime+ assert candle.loadtime["max_seq_length"] == 8192