# SPDX-License-Identifier: Apache-2.0 """Clean-room fp32 CPU reference of all-MiniLM-L6-v2 (BERT post-LN encoder + mean pooling + L2 normalize). No transformers / sentence-transformers dependency: plain torch ops on the safetensors weights, in the official order (``modeling_bert.py`` eager attention with an additive ``finfo.min`` key mask, exact-erf GELU, LayerNorm eps 1e-12).""" from __future__ import annotations import math from typing import Dict, List, Sequence, Tuple import numpy as np from ..weights import HEAD_DIM, HEADS, HIDDEN, LAYERS, LN_EPS def forward_e(weights: Dict, e, mask) -> "torch.Tensor": # noqa: F821 """Encoder from the summed embeddings ``e`` [B, S, 384] fp32 and ``mask`` [B, S] (1 = token) -> last hidden state [B, S, 384] fp32 (``hidden=True``: also every layer's output).""" return _forward(weights, e, mask)[0] def _forward(weights: Dict, e, mask, keep_hidden: bool = False): import torch import torch.nn.functional as F W = weights x = F.layer_norm(e, (HIDDEN,), W["embeddings.LayerNorm.weight"], W["embeddings.LayerNorm.bias"], LN_EPS) hs = [x] if keep_hidden else None B, S, _ = x.shape add = (1.0 - mask.to(torch.float32))[:, None, None, :] * torch.finfo(torch.float32).min for l in range(LAYERS): p = f"encoder.layer.{l}." def lin(t, n): return F.linear(t, W[p + n + ".weight"], W[p + n + ".bias"]) q = lin(x, "attention.self.query").view(B, S, HEADS, HEAD_DIM).transpose(1, 2) k = lin(x, "attention.self.key").view(B, S, HEADS, HEAD_DIM).transpose(1, 2) v = lin(x, "attention.self.value").view(B, S, HEADS, HEAD_DIM).transpose(1, 2) s = torch.matmul(q, k.transpose(2, 3)) * (HEAD_DIM ** -0.5) + add a = torch.matmul(torch.softmax(s, dim=-1), v).transpose(1, 2).reshape(B, S, HIDDEN) u = lin(a, "attention.output.dense") + x h = F.layer_norm(u, (HIDDEN,), W[p + "attention.output.LayerNorm.weight"], W[p + "attention.output.LayerNorm.bias"], LN_EPS) f = F.gelu(lin(h, "intermediate.dense")) x = F.layer_norm(lin(f, "output.dense") + h, (HIDDEN,), W[p + "output.LayerNorm.weight"], W[p + "output.LayerNorm.bias"], LN_EPS) if keep_hidden: hs.append(x) return x, hs def encode_ids(weights: Dict, host_emb, id_lists: Sequence[Sequence[int]], keep_hidden: bool = False ) -> Tuple[np.ndarray, List[np.ndarray], List]: """Padded-batch forward of id lists -> (pooled_sum [B, 384], token embeddings per text [n_b, 384], hidden).""" import torch B = len(id_lists) S = max(len(x) for x in id_lists) e = np.zeros((B, S, HIDDEN), dtype=np.float32) mask = np.zeros((B, S), dtype=np.float32) for b, ids in enumerate(id_lists): host_emb.fill(e[b], 0, ids) mask[b, : len(ids)] = 1.0 with torch.inference_mode(): x, hs = _forward(weights, torch.from_numpy(e), torch.from_numpy(mask), keep_hidden) tok = x.numpy() toks = [tok[b, : len(ids)].copy() for b, ids in enumerate(id_lists)] pooled = np.stack([t.astype(np.float64).sum(0) for t in toks]).astype(np.float32) return pooled, toks, hs class CpuEngine: """The ``cpu`` engine: same interface as the device engines (``run(id_lists) -> (pooled_sum, tokens)``).""" name = "cpu" def __init__(self, weights: Dict, host_emb, threads: int = 0): import torch self.weights, self.host_emb = weights, host_emb if threads: torch.set_num_threads(int(threads)) def run(self, id_lists, want_tokens: bool = False): pooled, toks, _ = encode_ids(self.weights, self.host_emb, id_lists) return pooled, (toks if want_tokens else None) def describe(self): return {"engine": "cpu"} def close(self): pass