File size: 2,310 Bytes
3bc7886
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""static_embed.py PASSAGES.parquet [...] - first-stage engram keys with sentence-transformers/static-retrieval-mrl-en-v1
(Apache-2.0): mean of per-token static vectors (no special tokens), Matryoshka-truncated to DIM, L2-normalised, float16 ->
emb_static/<name>.npy + .pid.npy. CPU only, ~100x cheaper than a transformer encoder, so the whole of Wikipedia indexes on the
spare cores while Beam keeps both GPUs; the cross-encoder re-rank recovers precision (10-19). Also importable: embed(texts)."""
import os, sys, time
import numpy as np
from tokenizers import Tokenizer
from safetensors.numpy import load_file
S = "/mnt/optane/hf-cache/hub/models--sentence-transformers--static-retrieval-mrl-en-v1/snapshots/f60985c706f192d45d218078e49e5a8b6f15283a/0_StaticEmbedding"
DIM = int(os.environ.get("DIM", 256))
TOK = Tokenizer.from_file(f"{S}/tokenizer.json"); TOK.no_padding(); TOK.no_truncation()
W = load_file(f"{S}/model.safetensors")["embedding.weight"][:, :DIM].astype(np.float32)


def embed(texts, maxlen=512):
    enc = TOK.encode_batch(texts, add_special_tokens=False)
    E = np.empty((len(texts), DIM), np.float32)
    for i, e in enumerate(enc):
        ids = e.ids[:maxlen]
        E[i] = W[ids].mean(0) if ids else 0
    E /= np.linalg.norm(E, axis=1, keepdims=True) + 1e-12
    return E


if __name__ == "__main__":
    import pyarrow.parquet as pq
    out = os.environ.get("OUT", "/mnt/optane/engram/emb_static"); os.makedirs(out, exist_ok=True)
    for src in sys.argv[1:]:
        name = os.path.basename(src)[:-8]
        if os.path.exists(f"{out}/{name}.npy"):
            continue
        t0 = time.time(); pf = pq.ParquetFile(src); n = pf.metadata.num_rows   # streamed: ~8 GB is all Beam leaves free
        E = np.lib.format.open_memmap(f"{out}/{name}.tmp.npy", "w+", np.float16, (n, DIM)); P = np.empty(n, np.int64); i = 0
        for b in pf.iter_batches(batch_size=8192, columns=["pid", "text"]):
            E[i:i + b.num_rows] = embed(b.column("text").to_pylist()); P[i:i + b.num_rows] = b.column("pid").to_numpy(); i += b.num_rows
        E.flush(); del E
        np.save(f"{out}/{name}.pid.npy", P); os.replace(f"{out}/{name}.tmp.npy", f"{out}/{name}.npy"); txt = P
        print(f"{time.strftime('%H:%M:%S')} {name}: {len(txt)} passages in {time.time() - t0:.0f} s", flush=True)