dfrokido commited on
Commit
aa27d87
·
verified ·
1 Parent(s): 0b420b5

Upload build_index.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. build_index.py +73 -0
build_index.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ One-time script: encode 500 MS-MARCO docs with dfrokido/bge-large-e8-snap,
3
+ build float and rfsnap normalized index tensors, save to hf_space/data/index.pt.
4
+
5
+ Run from repo root:
6
+ python hf_space/build_index.py
7
+ """
8
+ from __future__ import annotations
9
+ import json
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from sentence_transformers import SentenceTransformer
16
+
17
+ sys.path.insert(0, str(Path(__file__).parent))
18
+ from e8_utils import nestquant_snap
19
+
20
+ CORPUS_PATH = Path("runs/msmarco_local_100k/corpus.jsonl")
21
+ MODEL_ID = "dfrokido/bge-large-e8-snap"
22
+ N_DOCS = 500
23
+ OUT_PATH = Path("hf_space/data/index.pt")
24
+ BATCH_SIZE = 64
25
+
26
+
27
+ def main():
28
+ OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
29
+
30
+ print(f"Loading {N_DOCS} docs from {CORPUS_PATH}...")
31
+ docs = []
32
+ with open(CORPUS_PATH) as f:
33
+ for i, line in enumerate(f):
34
+ if i >= N_DOCS:
35
+ break
36
+ docs.append(json.loads(line))
37
+ doc_ids = [d["doc_id"] for d in docs]
38
+ doc_texts = [d["text"] for d in docs]
39
+
40
+ device = "cuda" if torch.cuda.is_available() else "cpu"
41
+ print(f"Encoding with {MODEL_ID} on {device}...")
42
+ model = SentenceTransformer(MODEL_ID, device=device)
43
+ emb = model.encode(doc_texts, batch_size=BATCH_SIZE,
44
+ convert_to_tensor=True, show_progress_bar=True)
45
+ emb = F.normalize(emb.float().cpu(), p=2, dim=1)
46
+
47
+ snap_emb = nestquant_snap(emb)
48
+ snap_norm = F.normalize(snap_emb, p=2, dim=1)
49
+ float_norm = emb # already normalized
50
+
51
+ sizes = {
52
+ "float32_mb": emb.numel() * 4 / 1e6,
53
+ "rfsnap_mb": emb.shape[0] * (emb.shape[1] // 8) * 3 / 1e6,
54
+ }
55
+
56
+ payload = {
57
+ "doc_ids": doc_ids,
58
+ "doc_texts": doc_texts,
59
+ "float_norm": float_norm,
60
+ "snap_norm": snap_norm,
61
+ "d_model": emb.shape[1],
62
+ "n_docs": len(docs),
63
+ "sizes": sizes,
64
+ }
65
+ torch.save(payload, OUT_PATH)
66
+ print(f"Saved {OUT_PATH}")
67
+ print(f" float32 index: {sizes['float32_mb']:.2f} MB")
68
+ print(f" rfsnap index: {sizes['rfsnap_mb']:.2f} MB")
69
+ print(f" compression: {sizes['float32_mb']/sizes['rfsnap_mb']:.1f}x")
70
+
71
+
72
+ if __name__ == "__main__":
73
+ main()