DylanCouzon commited on
Commit
8312f3f
·
verified ·
1 Parent(s): 1365b4a

Ship int8 safetensors with per-row scales for FastEmbed

Browse files

Stores the released int8 rows as and their per-row scales as , so FastEmbed's static path reproduces the released encoder exactly. Restores to the released version; FastEmbed now handles special tokens and sqrt pooling itself.

model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:10a13ff3791bf5bbad0c33e5ed3d8d13ed95f0ab92174b5ffdb36026fc7fd965
3
- size 62509144
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa798c355d9bc602f8314d7ca411c27467787cee19ad15e25390c2f9aaec37d0
3
+ size 31376776
scripts/convert-to-safensors.py CHANGED
@@ -9,7 +9,9 @@ import numpy as np
9
  from safetensors.numpy import save_file
10
 
11
  d = np.load("model.npz")
12
- W = np.ascontiguousarray(d["rows_fp16"]) # (30522, 1024) float16
13
- assert W.shape == (30522, 1024) and W.dtype == np.float16
 
14
 
15
- save_file({"embeddings": W}, "model.safetensors")
 
 
9
  from safetensors.numpy import save_file
10
 
11
  d = np.load("model.npz")
12
+ W = np.ascontiguousarray(d["rows_int8"]) # (30522, 1024) int8, the released table
13
+ scale = d["int8_scale"].astype(np.float32) # (30522,) per-row dequantization scale
14
+ assert W.shape == (30522, 1024) and W.dtype == np.int8 and scale.shape == (30522,)
15
 
16
+ # FastEmbed's static models multiply each token's row by `weights`, which dequantizes it.
17
+ save_file({"embeddings": W, "weights": scale}, "model.safetensors")
scripts/test-safentesor.py CHANGED
@@ -2,28 +2,30 @@
2
  #
3
  # /// script
4
  # requires-python = ">=3.12"
5
- # dependencies = ["statembed-py", "numpy", "tokenizers"]
6
  # ///
7
 
 
 
8
  import sys
9
  from pathlib import Path
10
 
11
- from statembed_py import StaticEmbedding
 
12
 
13
  model_dir = Path(__file__).parents[1]
14
  sys.path.insert(0, str(model_dir))
15
 
16
  from zero_encoder import ZeroQueryEncoder
17
 
18
- model = ZeroQueryEncoder(".", variant="fp16", add_special_tokens=False)
19
- other_emb = model.encode(["hello world"]).tolist()[0]
20
-
21
- model = StaticEmbedding(model_dir=".", normalize=True)
22
-
23
- emb = model.embed_text("hello world")
24
-
25
- import numpy as np
26
-
27
- a, b = np.asarray(emb), np.asarray(other_emb)
28
- print(f"cosine similarity: {float(a @ b):.6f}")
29
- print(f"max abs diff: {float(np.abs(a - b).max()):.8f}")
 
2
  #
3
  # /// script
4
  # requires-python = ">=3.12"
5
+ # dependencies = ["safetensors", "numpy", "tokenizers"]
6
  # ///
7
 
8
+ # Checks that model.safetensors, pooled by the model card's rule, gives the released vectors.
9
+
10
  import sys
11
  from pathlib import Path
12
 
13
+ import numpy as np
14
+ from safetensors.numpy import load_file
15
 
16
  model_dir = Path(__file__).parents[1]
17
  sys.path.insert(0, str(model_dir))
18
 
19
  from zero_encoder import ZeroQueryEncoder
20
 
21
+ model = ZeroQueryEncoder(model_dir, variant="int8")
22
+ t = load_file(model_dir / "model.safetensors")
23
+ texts = ["hello world", "data data data pipeline", "🤗 emoji query", ""]
24
+
25
+ for text, released in zip(texts, model.encode(texts)):
26
+ # special and unknown tokens included, a token seen c times weighs sqrt(c)
27
+ ids, counts = np.unique(model.tokenizer.encode(text).ids, return_counts=True)
28
+ v = (np.sqrt(counts) * t["weights"][ids]) @ t["embeddings"][ids].astype(np.float32)
29
+ v /= np.linalg.norm(v)
30
+ assert np.abs(v - released).max() < 1e-6, text
31
+ print("model.safetensors matches the released int8 encoder")
 
zero_encoder.py CHANGED
@@ -28,7 +28,7 @@ class ZeroQueryEncoder:
28
  int8 was measured quality-free against it (upper bound 0.00013 nDCG@10).
29
  """
30
 
31
- def __init__(self, model_dir, variant="int8", add_special_tokens=True):
32
  d = Path(model_dir)
33
  self.config = json.loads((d / "config.json").read_text())
34
  pre = self.config["preproc"]
@@ -45,10 +45,6 @@ class ZeroQueryEncoder:
45
  else:
46
  raise ValueError(f"variant must be 'int8' or 'fp16', got {variant!r}")
47
  self.variant = variant
48
- # static embedding models tend to have this
49
- # set to False, whereas most other models
50
- # default to True
51
- self.add_special_tokens = add_special_tokens
52
 
53
  self.tokenizer = Tokenizer.from_file(str(d / "tokenizer.json"))
54
  n = self.tokenizer.get_vocab_size(with_added_tokens=True)
@@ -79,7 +75,7 @@ class ZeroQueryEncoder:
79
  if isinstance(texts, str):
80
  texts = [texts]
81
  out = np.empty((len(texts), self.dim), dtype=np.float32)
82
- for i, enc in enumerate(self.tokenizer.encode_batch(texts, add_special_tokens=self.add_special_tokens)):
83
  out[i] = self._encode_ids(enc.ids)
84
  return out
85
 
 
28
  int8 was measured quality-free against it (upper bound 0.00013 nDCG@10).
29
  """
30
 
31
+ def __init__(self, model_dir, variant="int8"):
32
  d = Path(model_dir)
33
  self.config = json.loads((d / "config.json").read_text())
34
  pre = self.config["preproc"]
 
45
  else:
46
  raise ValueError(f"variant must be 'int8' or 'fp16', got {variant!r}")
47
  self.variant = variant
 
 
 
 
48
 
49
  self.tokenizer = Tokenizer.from_file(str(d / "tokenizer.json"))
50
  n = self.tokenizer.get_vocab_size(with_added_tokens=True)
 
75
  if isinstance(texts, str):
76
  texts = [texts]
77
  out = np.empty((len(texts), self.dim), dtype=np.float32)
78
+ for i, enc in enumerate(self.tokenizer.encode_batch(texts)):
79
  out[i] = self._encode_ids(enc.ids)
80
  return out
81