Spaces:
Paused
Paused
Full-vocab HVM cache (128K tokens) via chunked bf16 projection
Browse files- bqsm_assist/hyper_vocab_memory.py +42 -11
- hyper_vocab_memory.py +42 -11
bqsm_assist/hyper_vocab_memory.py
CHANGED
|
@@ -112,14 +112,33 @@ def osc_vector(tok, cache):
|
|
| 112 |
return v if v is not None else np.zeros(N_OSC, dtype=np.complex64)
|
| 113 |
|
| 114 |
|
| 115 |
-
def build_cache(token_ids):
|
| 116 |
-
"""Encode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
cache = {}
|
| 118 |
-
for
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return cache
|
| 124 |
|
| 125 |
|
|
@@ -151,10 +170,22 @@ for fp in corpus_files:
|
|
| 151 |
for q in test_queries:
|
| 152 |
used_ids.update(encode(q))
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
# Burn-in + build sparse "following" index (skip-gram, distance-decayed)
|
| 160 |
from collections import Counter, defaultdict
|
|
|
|
| 112 |
return v if v is not None else np.zeros(N_OSC, dtype=np.complex64)
|
| 113 |
|
| 114 |
|
| 115 |
+
def build_cache(token_ids, chunk=4096, label=""):
|
| 116 |
+
"""Encode token IDs into normalized complex oscillator states (batched).
|
| 117 |
+
|
| 118 |
+
Reads the bf16 embedding matrix via mmap in chunks, projects each chunk,
|
| 119 |
+
and stores a compact complex64 vector per token. Full vocab (~128K) is
|
| 120 |
+
~262 MB of cache — built chunk-wise so peak memory stays ~100 MB."""
|
| 121 |
+
si, v = st.idx["model.embed_tokens.weight"]
|
| 122 |
+
mm, st_off = st.shards[si]
|
| 123 |
+
D_emb = v["shape"][1]
|
| 124 |
+
a, b = v["data_offsets"]
|
| 125 |
+
base = st_off + a
|
| 126 |
+
ids = list(token_ids)
|
| 127 |
cache = {}
|
| 128 |
+
for i in range(0, len(ids), chunk):
|
| 129 |
+
batch = ids[i:i + chunk]
|
| 130 |
+
lo, hi = batch[0], batch[-1]
|
| 131 |
+
off = base + lo * D_emb * 2
|
| 132 |
+
raw = np.asarray(mm[off: off + (hi - lo + 1) * D_emb * 2])
|
| 133 |
+
E = ((raw.view(np.uint16).astype(np.uint32) << 16)
|
| 134 |
+
).view(np.float32).reshape(hi - lo + 1, D_emb)
|
| 135 |
+
P = E[[t - lo for t in batch]] @ PROJ.T # [batch, 2*N_OSC]
|
| 136 |
+
P /= (np.linalg.norm(P, axis=1, keepdims=True) + 1e-8)
|
| 137 |
+
C = (P[:, :N_OSC] + 1j * P[:, N_OSC:]).astype(np.complex64)
|
| 138 |
+
for j, t in enumerate(batch):
|
| 139 |
+
cache[t] = C[j]
|
| 140 |
+
if label and (i == 0 or (i + chunk) >= len(ids)):
|
| 141 |
+
print(f" {label} {min(i + chunk, len(ids))}/{len(ids)}", flush=True)
|
| 142 |
return cache
|
| 143 |
|
| 144 |
|
|
|
|
| 170 |
for q in test_queries:
|
| 171 |
used_ids.update(encode(q))
|
| 172 |
|
| 173 |
+
# Full-dictionary coverage: encode the entire vocab so ANY token the model
|
| 174 |
+
# emits can be scored/recalled. Corpus-derived associations still come from
|
| 175 |
+
# `used_ids`, but every token now has a hypervector. BQSM_FULL_VOCAB=off
|
| 176 |
+
# reverts to the corpus-subset cache for fast smoke tests.
|
| 177 |
+
FULL_VOCAB = os.environ.get("BQSM_FULL_VOCAB", "on") != "off"
|
| 178 |
+
if FULL_VOCAB:
|
| 179 |
+
V = st.idx["model.embed_tokens.weight"][1]["shape"][0]
|
| 180 |
+
print(f"encoding full vocab ({V} tokens) — one-time, ~30s...")
|
| 181 |
+
t0 = time.time()
|
| 182 |
+
cache = build_cache(range(V), label="vocab")
|
| 183 |
+
print(f" {time.time()-t0:.1f}s ({len(cache)} tokens cached)")
|
| 184 |
+
else:
|
| 185 |
+
print(f"encoding {len(used_ids)} distinct tokens (corpus + queries)...")
|
| 186 |
+
t0 = time.time()
|
| 187 |
+
cache = build_cache(sorted(used_ids))
|
| 188 |
+
print(f" {time.time()-t0:.1f}s")
|
| 189 |
|
| 190 |
# Burn-in + build sparse "following" index (skip-gram, distance-decayed)
|
| 191 |
from collections import Counter, defaultdict
|
hyper_vocab_memory.py
CHANGED
|
@@ -112,14 +112,33 @@ def osc_vector(tok, cache):
|
|
| 112 |
return v if v is not None else np.zeros(N_OSC, dtype=np.complex64)
|
| 113 |
|
| 114 |
|
| 115 |
-
def build_cache(token_ids):
|
| 116 |
-
"""Encode
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
cache = {}
|
| 118 |
-
for
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
return cache
|
| 124 |
|
| 125 |
|
|
@@ -151,10 +170,22 @@ for fp in corpus_files:
|
|
| 151 |
for q in test_queries:
|
| 152 |
used_ids.update(encode(q))
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
# Burn-in + build sparse "following" index (skip-gram, distance-decayed)
|
| 160 |
from collections import Counter, defaultdict
|
|
|
|
| 112 |
return v if v is not None else np.zeros(N_OSC, dtype=np.complex64)
|
| 113 |
|
| 114 |
|
| 115 |
+
def build_cache(token_ids, chunk=4096, label=""):
|
| 116 |
+
"""Encode token IDs into normalized complex oscillator states (batched).
|
| 117 |
+
|
| 118 |
+
Reads the bf16 embedding matrix via mmap in chunks, projects each chunk,
|
| 119 |
+
and stores a compact complex64 vector per token. Full vocab (~128K) is
|
| 120 |
+
~262 MB of cache — built chunk-wise so peak memory stays ~100 MB."""
|
| 121 |
+
si, v = st.idx["model.embed_tokens.weight"]
|
| 122 |
+
mm, st_off = st.shards[si]
|
| 123 |
+
D_emb = v["shape"][1]
|
| 124 |
+
a, b = v["data_offsets"]
|
| 125 |
+
base = st_off + a
|
| 126 |
+
ids = list(token_ids)
|
| 127 |
cache = {}
|
| 128 |
+
for i in range(0, len(ids), chunk):
|
| 129 |
+
batch = ids[i:i + chunk]
|
| 130 |
+
lo, hi = batch[0], batch[-1]
|
| 131 |
+
off = base + lo * D_emb * 2
|
| 132 |
+
raw = np.asarray(mm[off: off + (hi - lo + 1) * D_emb * 2])
|
| 133 |
+
E = ((raw.view(np.uint16).astype(np.uint32) << 16)
|
| 134 |
+
).view(np.float32).reshape(hi - lo + 1, D_emb)
|
| 135 |
+
P = E[[t - lo for t in batch]] @ PROJ.T # [batch, 2*N_OSC]
|
| 136 |
+
P /= (np.linalg.norm(P, axis=1, keepdims=True) + 1e-8)
|
| 137 |
+
C = (P[:, :N_OSC] + 1j * P[:, N_OSC:]).astype(np.complex64)
|
| 138 |
+
for j, t in enumerate(batch):
|
| 139 |
+
cache[t] = C[j]
|
| 140 |
+
if label and (i == 0 or (i + chunk) >= len(ids)):
|
| 141 |
+
print(f" {label} {min(i + chunk, len(ids))}/{len(ids)}", flush=True)
|
| 142 |
return cache
|
| 143 |
|
| 144 |
|
|
|
|
| 170 |
for q in test_queries:
|
| 171 |
used_ids.update(encode(q))
|
| 172 |
|
| 173 |
+
# Full-dictionary coverage: encode the entire vocab so ANY token the model
|
| 174 |
+
# emits can be scored/recalled. Corpus-derived associations still come from
|
| 175 |
+
# `used_ids`, but every token now has a hypervector. BQSM_FULL_VOCAB=off
|
| 176 |
+
# reverts to the corpus-subset cache for fast smoke tests.
|
| 177 |
+
FULL_VOCAB = os.environ.get("BQSM_FULL_VOCAB", "on") != "off"
|
| 178 |
+
if FULL_VOCAB:
|
| 179 |
+
V = st.idx["model.embed_tokens.weight"][1]["shape"][0]
|
| 180 |
+
print(f"encoding full vocab ({V} tokens) — one-time, ~30s...")
|
| 181 |
+
t0 = time.time()
|
| 182 |
+
cache = build_cache(range(V), label="vocab")
|
| 183 |
+
print(f" {time.time()-t0:.1f}s ({len(cache)} tokens cached)")
|
| 184 |
+
else:
|
| 185 |
+
print(f"encoding {len(used_ids)} distinct tokens (corpus + queries)...")
|
| 186 |
+
t0 = time.time()
|
| 187 |
+
cache = build_cache(sorted(used_ids))
|
| 188 |
+
print(f" {time.time()-t0:.1f}s")
|
| 189 |
|
| 190 |
# Burn-in + build sparse "following" index (skip-gram, distance-decayed)
|
| 191 |
from collections import Counter, defaultdict
|