Icodetools commited on
Commit
32ee3f8
·
verified ·
1 Parent(s): 54248ab

LittlePotion: 1 BPW Model2Vec embeddings (931 KB and 164 KB)

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ littlepotion-164kb.lbit filter=lfs diff=lfs merge=lfs -text
37
+ littlepotion-931kb.lbit filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ base_model: minishlab/potion-base-8M
3
+ license: mit
4
+ library_name: model2vec
5
+ tags:
6
+ - embeddings
7
+ - static-embeddings
8
+ - model2vec
9
+ - quantization
10
+ - 1-bit
11
+ - littlebit
12
+ ---
13
+
14
+ # LittlePotion: 1 BPW embeddings in 931 KB and 164 KB
15
+
16
+ LittlePotion is [potion-base-8M](https://huggingface.co/minishlab/potion-base-8M) squeezed down to 1 bit per weight using LittleBit, a compression method from Samsung Research. There's also a second, even smaller model at 164 KB.
17
+
18
+ *This is an unofficial compressed version. It's not affiliated with MinishLab, and all credit for the original model goes to them (see below).*
19
+
20
+ ## What's in here
21
+
22
+ | File | What it is |
23
+ |---|---|
24
+ | `littlepotion-931kb.lbit` | potion-base-8M at 1 bit per weight (931 KB) |
25
+ | `littlepotion-164kb.lbit` | a vocab-quantized Model2Vec model at 1 bit per weight (164 KB) |
26
+ | `tokenizer.json` | tokenizer for the 931 KB model |
27
+ | `tokenizer-164kb.json` | tokenizer for the 164 KB model |
28
+ | `littlepotion.py` | small loader for both |
29
+ | `benchmark.py` | checks the numbers below yourself |
30
+
31
+ ## How to use it
32
+
33
+ ```python
34
+ from huggingface_hub import snapshot_download
35
+ import sys
36
+
37
+ path = snapshot_download("MisasAI/LittlePotion")
38
+ sys.path.insert(0, path)
39
+ from littlepotion import load
40
+
41
+ model = load(f"{path}/littlepotion-931kb.lbit") # or littlepotion-164kb.lbit
42
+ vecs = model.encode(["The cat sat on the mat.", "A kitten rested on the rug."])
43
+ print(vecs @ vecs.T) # higher = more similar
44
+ ```
45
+
46
+ You need `torch`, `safetensors` and `tokenizers`. If `model2vec` is installed you get a normal `StaticModel` back, otherwise a small stand-in with the same `encode()`. The loader picks the right tokenizer for each file automatically.
47
+
48
+ ## How it works
49
+
50
+ A Model2Vec model is basically one big table, one row of numbers per word piece. LittleBit rewrites that table as two much smaller tables made only of +1 and -1 (one bit each), plus a few scaling numbers. Squashing it like that breaks it at first, so it's retrained afterwards until it gives nearly the same answers as the original.
51
+
52
+ ## How good is it?
53
+
54
+ **931 KB (potion-base-8M)**
55
+
56
+ | | Size | STS-B | SICK-R | SciFact |
57
+ |---|---|---|---|---|
58
+ | original potion-base-8M | 15 MB | 0.754 | 0.647 | 0.505 |
59
+ | LittlePotion 931 KB | 931 KB | 0.737 | 0.625 | 0.453 |
60
+ | kept | 16x smaller | 98% | 97% | 90% |
61
+
62
+ STS-B and SICK-R test "are these two sentences about the same thing?" (Spearman). SciFact tests search (nDCG@10). Search drops more because this one was only retrained for similarity.
63
+
64
+ **164 KB**
65
+
66
+ This one started from a 748 KB Model2Vec model where words share 2,000 vectors instead of each having their own. The shared vectors are at 1 bit per weight, and the word-to-vector lookup is packed into 11 bits. It was retrained in short stages using Ettin rerankers and bge-small as teachers, keeping a stage only if it helped.
67
+
68
+ | | Size | own test queries | SciFact | STS-B |
69
+ |---|---|---|---|---|
70
+ | original | 748 KB | 0.426 | 0.373 | 0.724 |
71
+ | LittlePotion 164 KB | 164 KB | 0.454 | 0.363 | 0.716 |
72
+
73
+ If you don't need things this small, normal 4-bit potion (about 4 MB) is basically lossless and simpler. LittlePotion is for when every kilobyte counts.
74
+
75
+ ## Check it yourself
76
+
77
+ ```
78
+ pip install torch safetensors tokenizers datasets scipy huggingface_hub
79
+ python benchmark.py
80
+ ```
81
+
82
+ ## Credits
83
+
84
+ - **potion-base-8M and Model2Vec** by Stephan Tulkens and Thomas van Dongen, MinishLab (MIT). LittlePotion is just their work, compressed.
85
+ - **LittleBit** by Lee, Kim, You and Kim, Samsung Research, NeurIPS 2025 ([arXiv:2506.13771](https://arxiv.org/abs/2506.13771)). This is an independent implementation from the paper, not Samsung's code.
86
+ - **Teachers** for the 164 KB model: Ettin rerankers (`cross-encoder/ettin-reranker-*-v1`, Apache-2.0) and BAAI bge-small-en-v1.5 (MIT).
87
+
88
+ ```bibtex
89
+ @software{minishlab2024model2vec,
90
+ author = {Stephan Tulkens and {van Dongen}, Thomas},
91
+ title = {Model2Vec: Fast State-of-the-Art Static Embeddings},
92
+ year = {2024},
93
+ publisher = {Zenodo},
94
+ doi = {10.5281/zenodo.17270888},
95
+ url = {https://github.com/MinishLab/model2vec},
96
+ license = {MIT}
97
+ }
98
+
99
+ @inproceedings{lee2025littlebit,
100
+ author = {Banseok Lee and Dongkyu Kim and Youngcheon You and Youngmin Kim},
101
+ title = {LittleBit: Ultra Low-Bit Quantization via Latent Factorization},
102
+ booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
103
+ year = {2025},
104
+ eprint = {2506.13771},
105
+ archivePrefix = {arXiv}
106
+ }
107
+ ```
benchmark.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark LittlePotion. Downloads the test sets (and original potion-base-8M) from Hugging Face.
2
+
3
+ python benchmark.py # both models
4
+ python benchmark.py littlepotion-931kb.lbit # just one
5
+
6
+ Tasks: STS-B and SICK-R test (sentence similarity, Spearman), SciFact test (search, nDCG@10).
7
+ """
8
+ import math, os, sys, torch, torch.nn.functional as F
9
+ from datasets import load_dataset
10
+ from huggingface_hub import hf_hub_download
11
+ from safetensors.torch import load_file
12
+ from scipy.stats import spearmanr
13
+ from tokenizers import Tokenizer
14
+
15
+ HERE = os.path.dirname(os.path.abspath(__file__))
16
+ sys.path.insert(0, HERE)
17
+ from littlepotion import decode, _DEFAULT_TOKENIZER
18
+
19
+ files = sys.argv[1:] or ["littlepotion-931kb.lbit", "littlepotion-164kb.lbit"]
20
+
21
+ stsb = load_dataset("sentence-transformers/stsb", split="test")
22
+ sick = load_dataset("mteb/sickr-sts", split="test")
23
+ corpus = load_dataset("mteb/scifact", "corpus", split="corpus")
24
+ qtext = {str(x["_id"]): x["text"] for x in load_dataset("mteb/scifact", "queries", split="queries")}
25
+ qrel = {}
26
+ for r in load_dataset("mteb/scifact", "default", split="test"):
27
+ if r["score"] > 0: qrel.setdefault(str(r["query-id"]), set()).add(str(r["corpus-id"]))
28
+ queries = [(k, qtext[k]) for k in qrel]
29
+ docs = [(str(c["_id"]), (c.get("title") or "") + " " + c["text"]) for c in corpus]
30
+
31
+ def scores(W, tok):
32
+ def enc(texts):
33
+ flat, offs = [], []
34
+ for e in tok.encode_batch(list(texts), add_special_tokens=False):
35
+ offs.append(len(flat)); flat.extend(e.ids or [0])
36
+ return F.normalize(F.embedding_bag(torch.tensor(flat), W, torch.tensor(offs), mode="mean"), dim=-1)
37
+ sts = lambda ds: spearmanr((enc(ds["sentence1"]) * enc(ds["sentence2"])).sum(1), ds["score"]).correlation
38
+ top = (enc([q for _, q in queries]) @ enc([t for _, t in docs]).T).topk(10, dim=1).indices
39
+ nd = sum(sum(1 / math.log2(k + 2) for k, di in enumerate(top[i].tolist()) if docs[di][0] in qrel[q]) /
40
+ sum(1 / math.log2(k + 2) for k in range(min(len(qrel[q]), 10))) for i, (q, _) in enumerate(queries)) / len(queries)
41
+ return sts(stsb), sts(sick), nd
42
+
43
+ rows = []
44
+ if any("931" in f for f in files):
45
+ W = load_file(hf_hub_download("minishlab/potion-base-8M", "model.safetensors"))["embeddings"].float()
46
+ rows.append(("original potion-base-8M", scores(W, Tokenizer.from_file(os.path.join(HERE, "tokenizer.json")))))
47
+ for f in files:
48
+ W, fmt = decode(os.path.join(HERE, f))
49
+ tok = Tokenizer.from_file(os.path.join(HERE, _DEFAULT_TOKENIZER[fmt]))
50
+ rows.append((f"{f} ({os.path.getsize(os.path.join(HERE, f)) / 1024:.0f} KB)", scores(torch.tensor(W), tok)))
51
+
52
+ print(f"\n{'model':38s} {'STS-B':>7s} {'SICK-R':>7s} {'SciFact':>8s}")
53
+ for name, r in rows:
54
+ print(f"{name:38s} {r[0]:7.4f} {r[1]:7.4f} {r[2]:8.4f}")
littlepotion-164kb.lbit ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:71e1e53673d592601c8753472db51585218f4693031037f00f5306aab16ff95b
3
+ size 164255
littlepotion-931kb.lbit ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f051d12771cf6466b0bc21132086025fb3742f0a692e413560ada96e2ee6f70e
3
+ size 954456
littlepotion.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """LittlePotion loader: 1-bit-per-weight Model2Vec embeddings (LittleBit compression).
2
+
3
+ from littlepotion import load
4
+
5
+ model = load("littlepotion-931kb.lbit") # potion-base-8M, 931 KB
6
+ model = load("littlepotion-164kb.lbit") # vocab-quantized Model2Vec, 164 KB
7
+ vecs = model.encode(["hello world", "another sentence"])
8
+
9
+ Returns a model2vec StaticModel if model2vec is installed, otherwise a minimal encoder with the
10
+ same encode(): mean of token vectors, L2-normalised. Requires torch, safetensors, tokenizers.
11
+ """
12
+ import os
13
+ import numpy as np
14
+ import torch
15
+ from safetensors import safe_open
16
+ from safetensors.torch import load_file
17
+
18
+ _SH = torch.tensor([7, 6, 5, 4, 3, 2, 1, 0], dtype=torch.uint8)
19
+ _DEFAULT_TOKENIZER = {"littlebit-model2vec-v1": "tokenizer.json",
20
+ "littlebit-model2vec-vq-v1": "tokenizer-164kb.json"}
21
+
22
+
23
+ def _signs(packed, r):
24
+ """uint8 [rows, ceil(r/8)] -> float ±1 [rows, r]; bit 1 = +1, first value in the top bit."""
25
+ return ((packed.unsqueeze(-1) >> _SH) & 1).view(packed.shape[0], -1)[:, :r].float() * 2 - 1
26
+
27
+
28
+ def _ints(packed, nbits, n):
29
+ """little-endian bit stream of n unsigned ints, nbits each."""
30
+ bits = ((packed.long().unsqueeze(1) >> torch.arange(8)) & 1).view(-1)[: n * nbits].view(n, nbits)
31
+ return (bits << torch.arange(nbits)).sum(-1)
32
+
33
+
34
+ def _littlebit(x, prefix, r):
35
+ """Sum of the LittleBit paths: diag(h) sign(U) diag(l) sign(V)^T diag(g)."""
36
+ W = 0
37
+ for p in ("pri", "res"):
38
+ if f"{prefix}.{p}.U_bits" not in x:
39
+ continue
40
+ h, g, l = (x[f"{prefix}.{p}.{s}"].float() for s in "hgl")
41
+ W = W + (h[:, None] * _signs(x[f"{prefix}.{p}.U_bits"], r) * l) @ (_signs(x[f"{prefix}.{p}.V_bits"], r) * g[:, None]).T
42
+ return W
43
+
44
+
45
+ def decode(path):
46
+ """Rebuild the dense [vocab, 256] token-vector table. Returns (numpy array, format name)."""
47
+ with safe_open(path, "pt") as f:
48
+ meta = f.metadata()
49
+ x, fmt, r = load_file(path), meta["format"], int(meta["rank"])
50
+ if fmt == "littlebit-model2vec-v1": # one table, one row per token
51
+ W = _littlebit(x, "embeddings", r)
52
+ elif fmt == "littlebit-model2vec-vq-v1": # shared vectors + token->vector lookup + per-token scale
53
+ C = _littlebit(x, "centroids", r)
54
+ mapping = _ints(x["mapping_bits"], int(meta["map_bits"]), int(meta["vocab"]))
55
+ W = x["weights"].float()[:, None] * C[mapping]
56
+ else:
57
+ raise ValueError(f"unknown format {fmt!r}")
58
+ return W.numpy().astype(np.float32), fmt
59
+
60
+
61
+ class _Simple:
62
+ """Minimal Model2Vec-style encoder: mean of token vectors, L2-normalised."""
63
+ def __init__(self, W, tok):
64
+ self.W, self.tok = W, tok
65
+
66
+ def encode(self, texts):
67
+ if isinstance(texts, str):
68
+ texts = [texts]
69
+ out = []
70
+ for e in self.tok.encode_batch(texts, add_special_tokens=False):
71
+ v = self.W[e.ids].mean(0) if e.ids else np.zeros(self.W.shape[1], np.float32)
72
+ out.append(v / (np.linalg.norm(v) + 1e-12))
73
+ return np.stack(out)
74
+
75
+
76
+ def load(path, tokenizer_path=None):
77
+ from tokenizers import Tokenizer
78
+ W, fmt = decode(path)
79
+ tokenizer_path = tokenizer_path or os.path.join(os.path.dirname(os.path.abspath(path)), _DEFAULT_TOKENIZER[fmt])
80
+ tok = Tokenizer.from_file(tokenizer_path)
81
+ try:
82
+ from model2vec import StaticModel
83
+ return StaticModel(vectors=W, tokenizer=tok, normalize=True)
84
+ except ImportError:
85
+ return _Simple(W, tok)
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ safetensors
3
+ tokenizers
4
+ numpy
5
+ # for benchmark.py:
6
+ datasets
7
+ scipy
8
+ huggingface_hub
9
+ # optional (load() then returns a model2vec StaticModel):
10
+ # model2vec
tokenizer-164kb.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff