64 lines
2.0 KiB
Python
64 lines
2.0 KiB
Python
"""The encoder interface and the deterministic order of a request."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Sequence
|
|
from dataclasses import dataclass
|
|
from enum import StrEnum
|
|
from typing import Protocol
|
|
|
|
|
|
class InputKind(StrEnum):
|
|
"""Side of the retrieval pair; see EmbeddingInputKind in the contract."""
|
|
|
|
QUERY = "query"
|
|
DOCUMENT = "document"
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ModelInfo:
|
|
model_id: str
|
|
revision: str
|
|
dimension: int
|
|
max_tokens: int
|
|
prompt_version: str
|
|
|
|
|
|
class Embedder(Protocol):
|
|
"""Encodes texts into L2-normalized float32 vectors."""
|
|
|
|
@property
|
|
def info(self) -> ModelInfo: ...
|
|
|
|
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
|
|
"""Encode one micro-batch; the result follows the order of texts."""
|
|
...
|
|
|
|
|
|
def micro_batches(texts: Sequence[str], size: int) -> list[list[int]]:
|
|
"""Split request positions into micro-batches of similar length.
|
|
|
|
Texts are ordered by length, longest first, with the request position as
|
|
the tie-breaker, so the same request is always split the same way and a
|
|
batch pads as little as possible.
|
|
"""
|
|
order = sorted(range(len(texts)), key=lambda index: (-len(texts[index]), index))
|
|
return [order[start : start + size] for start in range(0, len(order), size)]
|
|
|
|
|
|
def encode_ordered(
|
|
embedder: Embedder, kind: InputKind, texts: Sequence[str], micro_batch: int
|
|
) -> list[list[float]]:
|
|
"""Encode texts in deterministic micro-batches and restore request order."""
|
|
vectors: list[list[float] | None] = [None] * len(texts)
|
|
for batch in micro_batches(texts, micro_batch):
|
|
encoded = embedder.encode_batch(kind, [texts[index] for index in batch])
|
|
for index, vector in zip(batch, encoded, strict=True):
|
|
vectors[index] = vector
|
|
result: list[list[float]] = []
|
|
for encoded_vector in vectors:
|
|
if encoded_vector is None:
|
|
raise RuntimeError("an encoder skipped a text")
|
|
result.append(encoded_vector)
|
|
return result
|