# SPDX-License-Identifier: Apache-2.0 """Python API: ``MiniLM`` (sentence-transformers/all-MiniLM-L6-v2 on one Tenstorrent Blackhole p150). from tt_minilm.api import MiniLM with MiniLM.from_pretrained() as m: # weights (pinned HF revision) -> device (ETH, 12x10) -> warm-up emb = m.encode(["A man is playing a guitar.", "A man plays an instrument."]) # [2, 384] float32, unit norm sim = emb @ emb.T ``encode`` matches ``SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2").encode(texts)`` (mean pooling over [CLS] + word pieces + [SEP], L2 normalized, 256-token truncation). Options: ``normalize``, ``pooling`` (``mean``, ``cls``, ``max``, ``none`` = token embeddings), ``max_length`` and ``truncate`` (``right``, ``left``, ``error``). Engines: ``mk`` (megakernel, default), ``ttnn``, ``cpu`` (fp32 reference, no device). Importing has no side effects. """ from __future__ import annotations import dataclasses import os import threading import time import warnings from typing import Dict, List, Optional, Sequence, Union import numpy as np from . import __version__ from . import config as C from .host import POOLING, HostEmbeddings, finish from .tokenizer import TRUNCATE, Tokenizer, TooLong from .weights import ALLOW_PATTERNS, HF_REPO, HF_REVISION, HIDDEN, load_weights, read_facts __all__ = ["MiniLM", "InputError", "resolve_weights"] class InputError(ValueError): """A client mistake (HTTP 400).""" def resolve_weights(model_id: Optional[str] = None, *, revision: Optional[str] = None, weights_dir: Optional[str] = None) -> str: """weights_dir > MINILM_WEIGHTS_DIR > a local directory ``model_id`` > the HF snapshot of ``model_id`` (default the pinned sentence-transformers/all-MiniLM-L6-v2 revision; offline: the local HF cache).""" for d in (weights_dir, os.environ.get("MINILM_WEIGHTS_DIR")): if d: if not os.path.isfile(os.path.join(d, "model.safetensors")): raise FileNotFoundError(f"{d}: no model.safetensors") return d mid = model_id or HF_REPO if os.path.isdir(mid) and os.path.isfile(os.path.join(mid, "model.safetensors")): return mid from huggingface_hub import snapshot_download rev = revision or (HF_REVISION if mid == HF_REPO else None) try: return snapshot_download(mid, revision=rev, allow_patterns=ALLOW_PATTERNS) except Exception: # noqa: BLE001 -- offline: the cache return snapshot_download(mid, revision=rev, allow_patterns=ALLOW_PATTERNS, local_files_only=True) class MiniLM: MODEL_NAME = C.MODEL_NAME DIM = HIDDEN def __init__(self, model_dir: str, *, config: Optional[C.ServeConfig] = None, device=None, engine: Optional[str] = None, own_device: bool = False): self.config = config or C.ServeConfig() self.model_dir = model_dir self.facts = read_facts(model_dir) self.max_seq_len = min(self.config.max_seq_len, self.facts.max_seq_length) self.tokenizer = Tokenizer(model_dir, self.max_seq_len) t0 = time.perf_counter() W = load_weights(model_dir) self.host_emb = HostEmbeddings(W) self.device = device self._own_device = own_device self.engine_name = engine or self.config.engine self.fallback: Optional[str] = None self._lock = threading.RLock() self._closed = False self.engine = self._make_engine(W) self.build_s = time.perf_counter() - t0 self.warm_s = 0.0 self.runs = 0 # ------------------------------------------------------------------ construction def _make_engine(self, W): cfg = self.config if self.engine_name == "cpu": from .reference.model import CpuEngine return CpuEngine(W, self.host_emb, threads=cfg.cpu_threads) if self.device is None: raise ValueError(f"engine {self.engine_name!r} needs a device") if self.engine_name == "mk": from .tt.mk.engine import MkEngine, MkUnavailable try: return MkEngine(self.device, W, self.host_emb, trace=cfg.trace, fidelity=cfg.fidelity, allgather=cfg.allgather) except MkUnavailable as e: self.fallback = f"mk unavailable ({e}); using ttnn" warnings.warn(self.fallback, RuntimeWarning) self.engine_name = "ttnn" from .tt.ttnn_engine import TtnnEngine return TtnnEngine(self.device, W, self.host_emb, batch_buckets=cfg.batch_buckets, seq_buckets=cfg.seq_buckets, trace=cfg.trace) @classmethod def from_pretrained(cls, model_id: Optional[str] = None, *, revision: Optional[str] = None, weights_dir: Optional[str] = None, engine: Optional[str] = None, device=None, dispatch: Optional[str] = None, config: Optional[C.ServeConfig] = None, warmup: Optional[bool] = None) -> "MiniLM": cfg = config or C.resolve_config() if engine is not None: cfg = dataclasses.replace(cfg, engine=engine) d = resolve_weights(model_id or cfg.model_id, revision=revision or cfg.revision, weights_dir=weights_dir or cfg.weights_dir) own = False if cfg.engine != "cpu" and device is None: from .device import open_device device = open_device(dispatch=dispatch or cfg.dispatch) own = True try: m = cls(d, config=cfg, device=device, own_device=own) if cfg.warmup if warmup is None else warmup: m.warmup() return m except BaseException: if own: from .device import close_device close_device(device) raise # ------------------------------------------------------------------ inference def tokenize(self, texts: Sequence[str], max_length: Optional[int] = None, truncate: str = "right" ) -> List[List[int]]: if truncate not in TRUNCATE: raise InputError(f"truncate {truncate!r}: expected one of {', '.join(TRUNCATE)}") ml = self.max_seq_len if max_length is None else int(max_length) if not 2 <= ml <= self.max_seq_len: raise InputError(f"max_length {ml}: outside [2, {self.max_seq_len}]") try: return self.tokenizer.encode(list(texts), ml, truncate) except TooLong as e: raise InputError(str(e)) from None def embed_ids(self, id_lists: Sequence[Sequence[int]], *, pooling: str = "mean", normalize: bool = True, timing: Optional[Dict] = None): """Embeddings of tokenized texts (each ``[CLS] ... [SEP]``, <= max_seq_len ids): [n, 384] float32, or a list of [n_i, 384] arrays for ``pooling='none'``. Device batches of <= max_batch texts.""" if pooling not in POOLING: raise InputError(f"pooling {pooling!r}: expected one of {', '.join(POOLING)}") if self._closed: raise RuntimeError("model is closed") want_tok = pooling != "mean" mb = self.config.max_batch pooled_parts, tok_parts = [], [] t_dev = 0.0 for i in range(0, len(id_lists), mb): part = id_lists[i:i + mb] t0 = time.perf_counter() with self._lock: pooled, toks = self.engine.run(part, want_tokens=want_tok) self.runs += 1 t_dev += time.perf_counter() - t0 pooled_parts.append(np.asarray(pooled, dtype=np.float32)[: len(part)]) if want_tok: tok_parts.extend(toks) if timing is not None: timing["device_ms"] = timing.get("device_ms", 0.0) + 1e3 * t_dev pooled = np.concatenate(pooled_parts, 0) if pooled_parts else np.zeros((0, HIDDEN), np.float32) return finish(pooled, [len(x) for x in id_lists], tok_parts if want_tok else None, pooling, normalize) def encode(self, texts: Union[str, Sequence[str]], *, normalize: bool = True, pooling: str = "mean", max_length: Optional[int] = None, truncate: str = "right", timing: Optional[Dict] = None): single = isinstance(texts, str) tl = [texts] if single else list(texts) if not tl: return np.zeros((0, HIDDEN), np.float32) for i, t in enumerate(tl): if not isinstance(t, str): raise InputError(f"input {i} is not a string") t0 = time.perf_counter() ids = self.tokenize(tl, max_length, truncate) t1 = time.perf_counter() out = self.embed_ids(ids, pooling=pooling, normalize=normalize, timing=timing) if timing is not None: timing["tokenize_ms"] = 1e3 * (t1 - t0) timing["total_ms"] = 1e3 * (time.perf_counter() - t0) timing["tokens"] = [len(x) for x in ids] if single: return out[0] return out def warmup(self) -> float: t0 = time.perf_counter() ids = self.tokenize(["warm-up", "a longer warm-up sentence for the encoder " * 40]) self.embed_ids(ids[:1]) self.embed_ids(ids, pooling="cls") if self.engine_name == "ttnn": with self._lock: self.engine.warm() self.warm_s = time.perf_counter() - t0 return self.warm_s # ------------------------------------------------------------------ info / lifecycle @property def info(self) -> Dict: d = {"model": self.MODEL_NAME, "version": __version__, "dim": HIDDEN, "engine": self.engine_name, "engine_detail": self.engine.describe(), "fallback": self.fallback, "max_seq_len": self.max_seq_len, "max_batch": self.config.max_batch, "pooling_default": "mean", "normalize_default": True, "weights_dir": self.model_dir, "build_s": round(self.build_s, 3), "warmup_s": round(self.warm_s, 3), "runs": self.runs, "config": self.config.as_dict()} if self.device is not None: try: from .device import describe_device d["device"] = describe_device(self.device) except Exception: # noqa: BLE001 d["device"] = {} return d @property def closed(self) -> bool: return self._closed def close(self) -> None: with self._lock: if self._closed: return self._closed = True try: self.engine.close() finally: if self._own_device and self.device is not None: from .device import close_device close_device(self.device) self.device = None def __enter__(self): return self def __exit__(self, *exc): self.close()