coldmemory 0.3.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
coldmemory/hybrid.py ADDED
@@ -0,0 +1,430 @@
1
+ """Optional CPU-only local ONNX bi-encoder dense index for ColdMemory hybrid retrieval.
2
+
3
+ Design invariants:
4
+ - Pure-Python stdlib ColdMemory works with zero external packages when hybrid is disabled or ONNX is absent.
5
+ - Hard-coded to CPUExecutionProvider (never CUDA/GPU).
6
+ - Security & suppression: every candidate is gated against live `corpus.has(key)` AND exact `note.sha256`
7
+ at query time, and all hits still pass through Engine stale-note replacement and live disk SHA-256 re-read.
8
+ - Optional vector cache stores only (model_id, text_sha256) -> float16 vector in an owner-only 0600 file
9
+ opened with O_NOFOLLOW; zero raw note text is persisted in the vector cache.
10
+ """
11
+
12
+ import hashlib
13
+ import os
14
+ import re
15
+ import stat
16
+ import tempfile
17
+ from pathlib import Path
18
+
19
+
20
+ DEFAULT_QUERY_PREFIXES = (
21
+ ("bge", "Represent this sentence for searching relevant passages: "),
22
+ ("arctic", "Represent this sentence for searching relevant passages: "),
23
+ ("e5", "query: "),
24
+ )
25
+
26
+
27
+ def available():
28
+ """True when optional CPU-only ONNX dense retrieval dependencies are importable."""
29
+ try:
30
+ import numpy # noqa: F401
31
+ import onnxruntime # noqa: F401
32
+ import tokenizers # noqa: F401
33
+ except ImportError:
34
+ return False
35
+ return True
36
+
37
+
38
+ def _infer_query_prefix(model_path):
39
+ lower = str(model_path).lower()
40
+ for token, prefix in DEFAULT_QUERY_PREFIXES:
41
+ if token in lower:
42
+ return prefix
43
+ return ""
44
+
45
+
46
+ def _resolve_model_files(model_dir):
47
+ root = Path(model_dir).expanduser().resolve(strict=True)
48
+ if root.is_file() and root.suffix == ".onnx":
49
+ onnx_path = root
50
+ tok_path = root.parent / "tokenizer.json"
51
+ if not tok_path.is_file():
52
+ tok_path = root.parent.parent / "tokenizer.json"
53
+ else:
54
+ onnx_path = None
55
+ for candidate in ("model_quantized.onnx", "model_int8.onnx", "model.onnx", "onnx/model_quantized.onnx", "onnx/model.onnx"):
56
+ path = root / candidate
57
+ if path.is_file():
58
+ onnx_path = path
59
+ break
60
+ tok_path = root / "tokenizer.json"
61
+ if onnx_path is None or not onnx_path.is_file():
62
+ raise FileNotFoundError(f"no ONNX model file found under {model_dir}")
63
+ if not tok_path.is_file():
64
+ raise FileNotFoundError(f"no tokenizer.json found under {model_dir}")
65
+ return onnx_path, tok_path
66
+
67
+
68
+ def model_fingerprint(onnx_path, tok_path, max_length):
69
+ """Hash the model, any external weight files beside it, and the tokenizer."""
70
+ onnx_path = Path(onnx_path)
71
+ weights = sorted(p for p in onnx_path.parent.iterdir() if p.name.startswith(onnx_path.name) and p.is_file())
72
+ digest = hashlib.sha256(f"{max_length}".encode())
73
+ for path in [*weights, Path(tok_path)]:
74
+ with open(path, "rb") as stream:
75
+ digest.update(path.name.encode() + b"\0" + hashlib.file_digest(stream, "sha256").digest())
76
+ return digest.hexdigest()[:16]
77
+
78
+
79
+ def chunk_note(note, target_words=180, overlap_words=35):
80
+ """Return (section, passage_text) pairs. A passage never spans two sections, so its citation is exact.
81
+ Long sections become overlapping word windows."""
82
+ prefix_parts = [note.title]
83
+ if note.date and note.date not in note.title:
84
+ prefix_parts.append(f"({note.date})")
85
+ note_header = " ".join(p for p in prefix_parts if p).strip()
86
+
87
+ raw_sections = []
88
+ for section in note.sections:
89
+ begin, heading, end = section
90
+ body_lines = [line.strip() for line in note.lines[begin:end] if line.strip()]
91
+ if not body_lines:
92
+ continue
93
+ text = "\n".join(body_lines)
94
+ raw_sections.append((section, text, len(text.split())))
95
+
96
+ if not raw_sections:
97
+ return []
98
+
99
+ if len(raw_sections) == 1 and raw_sections[0][2] <= target_words + 60:
100
+ sec, text, _ = raw_sections[0]
101
+ full = f"{note_header}\n{text}" if note_header and note_header not in text[:len(note_header) + 20] else text
102
+ return [(sec, full)]
103
+
104
+ chunks = []
105
+ step = max(1, target_words - overlap_words)
106
+ for sec, text, wcount in raw_sections:
107
+ windows = [text]
108
+ if wcount > target_words + 40:
109
+ words_list = text.split()
110
+ windows = []
111
+ for pos in range(0, len(words_list), step):
112
+ windows.append(" ".join(words_list[pos:pos + target_words]))
113
+ if pos + target_words >= len(words_list):
114
+ break
115
+ chunks += [(sec, f"{note_header}\n{window}" if note_header else window) for window in windows]
116
+ return chunks
117
+
118
+
119
+ class OnnxBiEncoder:
120
+ """CPU-only ONNX Runtime bi-encoder with length-bucketed batching and L2-normalized CLS/mean pooling."""
121
+
122
+ def __init__(self, model_dir, *, query_prefix=None, max_length=256, threads=None, batch_size=64):
123
+ import numpy as np
124
+ import onnxruntime as ort
125
+ from tokenizers import Tokenizer
126
+
127
+ self._np = np
128
+ self.onnx_path, self.tok_path = _resolve_model_files(model_dir)
129
+ self.model_id = model_fingerprint(self.onnx_path, self.tok_path, max_length)
130
+ self.model_bytes = self.onnx_path.stat().st_size
131
+ self.max_length = int(max_length)
132
+ self.batch_size = int(batch_size)
133
+ self.query_prefix = _infer_query_prefix(self.onnx_path.parent) if query_prefix is None else query_prefix
134
+
135
+ self.tokenizer = Tokenizer.from_file(str(self.tok_path))
136
+ opts = ort.SessionOptions()
137
+ opts.intra_op_num_threads = threads or min(os.cpu_count() or 1, 8)
138
+ opts.inter_op_num_threads = 1
139
+ opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
140
+ opts.log_severity_level = 3
141
+ # Hard-coded CPU-only: never touch CUDA / GPU providers
142
+ self.session = ort.InferenceSession(
143
+ str(self.onnx_path),
144
+ sess_options=opts,
145
+ providers=["CPUExecutionProvider"],
146
+ )
147
+ self._input_names = {inp.name for inp in self.session.get_inputs()}
148
+ self._is_embedding_bag = "offsets" in self._input_names
149
+ if not self._is_embedding_bag:
150
+ self.tokenizer.enable_truncation(max_length=self.max_length)
151
+ self.tokenizer.enable_padding(pad_id=0, pad_token="[PAD]")
152
+ else:
153
+ # Static EmbeddingBag models (e.g. potion-retrieval-32M) need no query prefix or padding
154
+ if query_prefix is None:
155
+ self.query_prefix = ""
156
+ self._use_mean = "e5" in str(self.onnx_path).lower() or "minilm" in str(self.onnx_path).lower()
157
+ # Probe dim once
158
+ sample = self._encode_batch(["warmup"])
159
+ self.dim = int(sample.shape[1])
160
+
161
+ def _encode_batch(self, texts):
162
+ np = self._np
163
+ encs = self.tokenizer.encode_batch(texts)
164
+ if self._is_embedding_bag:
165
+ ids = []
166
+ offsets = []
167
+ for enc in encs:
168
+ offsets.append(len(ids))
169
+ ids.extend(enc.ids if enc.ids else [0])
170
+ pooled = self.session.run(
171
+ None,
172
+ {"input_ids": np.array(ids, dtype=np.int64), "offsets": np.array(offsets, dtype=np.int64)},
173
+ )[0]
174
+ pooled = pooled.astype(np.float32, copy=False)
175
+ norms = np.linalg.norm(pooled, axis=1, keepdims=True)
176
+ return pooled / np.maximum(norms, 1e-12)
177
+ ids = np.array([e.ids for e in encs], dtype=np.int64)
178
+ mask = np.array([e.attention_mask for e in encs], dtype=np.int64)
179
+ feed = {"input_ids": ids, "attention_mask": mask}
180
+ if "token_type_ids" in self._input_names:
181
+ feed["token_type_ids"] = np.zeros_like(ids)
182
+ hidden = self.session.run(None, feed)[0]
183
+ if self._use_mean:
184
+ mask_f = mask[:, :, None].astype(np.float32)
185
+ pooled = (hidden * mask_f).sum(axis=1) / np.maximum(mask_f.sum(axis=1), 1e-9)
186
+ else:
187
+ pooled = hidden[:, 0, :]
188
+ pooled = pooled.astype(np.float32, copy=False)
189
+ norms = np.linalg.norm(pooled, axis=1, keepdims=True)
190
+ return pooled / np.maximum(norms, 1e-12)
191
+
192
+ def encode_query(self, query):
193
+ text = f"{self.query_prefix}{query}" if self.query_prefix else query
194
+ return self._encode_batch([text])[0]
195
+
196
+ def encode_passages(self, texts):
197
+ np = self._np
198
+ if not texts:
199
+ return np.zeros((0, self.dim), dtype=np.float32)
200
+ if self._is_embedding_bag:
201
+ step = max(self.batch_size, 512)
202
+ if len(texts) <= step:
203
+ return self._encode_batch(texts)
204
+ parts = [self._encode_batch(texts[i:i + step]) for i in range(0, len(texts), step)]
205
+ return np.vstack(parts)
206
+ if len(texts) <= self.batch_size:
207
+ return self._encode_batch(texts)
208
+ # Sort by char length for bucketed batching (avoids padding short passages to max length)
209
+ order = sorted(range(len(texts)), key=lambda i: len(texts[i]))
210
+ out = np.empty((len(texts), self.dim), dtype=np.float32)
211
+ for start in range(0, len(order), self.batch_size):
212
+ batch_idx = order[start:start + self.batch_size]
213
+ vecs = self._encode_batch([texts[i] for i in batch_idx])
214
+ for pos, orig in enumerate(batch_idx):
215
+ out[orig] = vecs[pos]
216
+ return out
217
+
218
+
219
+ class VectorCache:
220
+ """Owner-only content-addressed vector cache in an owner-only folder. Each record is a 16-byte text hash
221
+ followed by one vector, so the file holds no note text and loading it runs no code."""
222
+
223
+ def __init__(self, folder, model_id, dim, itemsize=2):
224
+ self.path = Path(folder) / f"vectors-{model_id}-f{itemsize * 8}.bin"
225
+ self.record = 16 + dim * itemsize
226
+ self.entries = self._load()
227
+ self.dirty = 0
228
+
229
+ def _check_folder(self):
230
+ info = os.stat(self.path.parent, follow_symlinks=False)
231
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
232
+ raise ValueError("vector cache folder must be an owner-only directory")
233
+
234
+ def _load(self):
235
+ if not self.path.parent.exists():
236
+ return {}
237
+ self._check_folder()
238
+ try:
239
+ fd = os.open(self.path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
240
+ except FileNotFoundError:
241
+ return {}
242
+ except OSError as error:
243
+ raise ValueError("vector cache must be an owner-only regular file") from error
244
+ with open(fd, "rb") as stream:
245
+ info = os.fstat(fd)
246
+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
247
+ raise ValueError("vector cache must be an owner-only regular file")
248
+ data = stream.read()
249
+ if len(data) % self.record:
250
+ raise ValueError("vector cache is damaged")
251
+ return {data[at:at + 16]: data[at + 16:at + self.record] for at in range(0, len(data), self.record)}
252
+
253
+ def get(self, digest):
254
+ return self.entries.get(digest)
255
+
256
+ def put(self, digest, vec_f16_bytes):
257
+ self.entries[digest] = vec_f16_bytes
258
+ self.dirty += 1
259
+
260
+ def save(self):
261
+ if not self.dirty:
262
+ return
263
+ self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
264
+ self._check_folder()
265
+ fd, temp = tempfile.mkstemp(dir=self.path.parent, prefix=f".{self.path.name}.")
266
+ try:
267
+ with open(fd, "wb") as stream:
268
+ stream.writelines(digest + vec for digest, vec in self.entries.items())
269
+ os.replace(temp, self.path)
270
+ except BaseException:
271
+ os.unlink(temp)
272
+ raise
273
+ self.dirty = 0
274
+
275
+
276
+ def _text_digest(text):
277
+ return hashlib.sha256(text.encode("utf-8", "replace")).digest()[:16]
278
+
279
+
280
+ class DenseIndex:
281
+ """Live-verified, suppression-safe dense passage index backed by any encoder implementing
282
+ `encode_query(str) -> float32[D]` and `encode_passages(list[str]) -> float32[N, D]`."""
283
+
284
+ def __init__(self, encoder, *, cache_dir=None, target_words=180, overlap_words=35):
285
+ try:
286
+ import numpy as np
287
+ except ImportError:
288
+ np = None
289
+ self._np = np
290
+ self.encoder = encoder
291
+ self.target_words = target_words
292
+ self.overlap_words = overlap_words
293
+ self.cache = VectorCache(cache_dir, encoder.model_id, encoder.dim, 2 if np is not None else 4) if cache_dir else None
294
+ self.note_shas = {} # key -> sha256
295
+ self.note_chunks = {} # key -> list of (section, vec)
296
+ self.matrix = np.zeros((0, encoder.dim), dtype=np.float32) if np is not None else []
297
+ self.meta = [] # list of (key, sha256, section)
298
+ self._query_memo = None
299
+
300
+ def _to_cache_bytes(self, vec):
301
+ if self._np is not None:
302
+ return self._np.asarray(vec, dtype=self._np.float16).tobytes()
303
+ import array
304
+ return array.array("f", vec).tobytes()
305
+
306
+ def _from_cache_bytes(self, raw):
307
+ if self._np is not None:
308
+ return self._np.frombuffer(raw, dtype=self._np.float16).astype(self._np.float32)
309
+ import array
310
+ arr = array.array("f")
311
+ arr.frombytes(raw)
312
+ return list(arr)
313
+
314
+ def sync(self, corpus):
315
+ """Sync dense vectors strictly to live `corpus.notes`. Deleted/edited notes are purged immediately."""
316
+ np = self._np
317
+ live_notes = corpus.notes
318
+ # Drop any deleted or changed notes immediately
319
+ removed = [k for k, sha in self.note_shas.items() if k not in live_notes or live_notes[k].sha256 != sha]
320
+ for k in removed:
321
+ self.note_shas.pop(k, None)
322
+ self.note_chunks.pop(k, None)
323
+
324
+ todo_notes = [(k, n) for k, n in live_notes.items() if k not in self.note_shas]
325
+ if not removed and not todo_notes:
326
+ return
327
+
328
+ # Gather chunks to encode (reusing content-addressed cache if configured)
329
+ pending_texts = []
330
+ pending_digests = []
331
+ pending_refs = [] # (key, chunk_idx)
332
+ new_chunks = {}
333
+ for key, note in todo_notes:
334
+ chunks = chunk_note(note, self.target_words, self.overlap_words)
335
+ slots = new_chunks[key] = [None] * len(chunks)
336
+ for ci, (sec, text) in enumerate(chunks):
337
+ dig = _text_digest(text)
338
+ cached = self.cache.get(dig) if self.cache else None
339
+ if cached is not None:
340
+ slots[ci] = (sec, self._from_cache_bytes(cached))
341
+ else:
342
+ slots[ci] = (sec, None)
343
+ pending_texts.append(text)
344
+ pending_digests.append(dig)
345
+ pending_refs.append((key, ci))
346
+
347
+ if pending_texts:
348
+ vecs = self.encoder.encode_passages(pending_texts)
349
+ for idx, (key, ci) in enumerate(pending_refs):
350
+ vec = vecs[idx]
351
+ new_chunks[key][ci] = (new_chunks[key][ci][0], vec)
352
+ if self.cache:
353
+ self.cache.put(pending_digests[idx], self._to_cache_bytes(vec))
354
+ if self.cache:
355
+ self.cache.save()
356
+ self.note_chunks.update(new_chunks)
357
+ self.note_shas.update((key, note.sha256) for key, note in todo_notes)
358
+
359
+ # Rebuild contiguous matrix over live notes only
360
+ all_vecs = []
361
+ all_meta = []
362
+ for key in live_notes:
363
+ sha = self.note_shas.get(key)
364
+ if sha != live_notes[key].sha256:
365
+ continue
366
+ for sec, vec in self.note_chunks.get(key, ()):
367
+ if vec is not None:
368
+ all_vecs.append(vec)
369
+ all_meta.append((key, sha, sec))
370
+
371
+ if np is not None:
372
+ self.matrix = np.vstack(all_vecs).astype(np.float32, copy=False) if all_vecs else np.zeros((0, self.encoder.dim), dtype=np.float32)
373
+ else:
374
+ self.matrix = all_vecs
375
+ self.meta = all_meta
376
+ self._query_memo = None
377
+
378
+ def clear_memo(self):
379
+ self._query_memo = None
380
+
381
+ def search(self, query, corpus, limit, *, per_note=1):
382
+ """Return list of (cosine_sim, key, section) strictly gated on live `corpus.has(key)` and exact `sha256`."""
383
+ np = self._np
384
+ if not len(self.meta):
385
+ return []
386
+ if self._query_memo is not None and self._query_memo[0] == query:
387
+ q_vec = self._query_memo[1]
388
+ else:
389
+ raw_q = self.encoder.encode_query(query)
390
+ q_vec = np.asarray(raw_q, dtype=np.float32) if np is not None else list(raw_q)
391
+ self._query_memo = (query, q_vec)
392
+
393
+ if np is not None:
394
+ scores = self.matrix @ q_vec
395
+ order = np.argsort(-scores)
396
+ else:
397
+ scores = [sum(a * b for a, b in zip(row, q_vec)) for row in self.matrix]
398
+ order = sorted(range(len(scores)), key=lambda i: -scores[i])
399
+
400
+ live = corpus.notes
401
+ results = []
402
+ seen_counts = {}
403
+ seen_sections = set()
404
+ for idx in order:
405
+ key, sha, sec = self.meta[int(idx)]
406
+ # Strict suppression gate: deleted or modified notes NEVER escape cached vectors
407
+ if not corpus.has(key) or live[key].sha256 != sha:
408
+ continue
409
+ if per_note is not None and seen_counts.get(key, 0) >= per_note:
410
+ continue
411
+ if (key, sec) in seen_sections:
412
+ continue
413
+ seen_sections.add((key, sec))
414
+ seen_counts[key] = seen_counts.get(key, 0) + 1
415
+ results.append((float(scores[int(idx)]), key, sec))
416
+ if len(results) >= limit:
417
+ break
418
+ return results
419
+
420
+
421
+ def maybe_load_encoder(model_dir=None, *, threads=None):
422
+ """Load an OnnxBiEncoder when explicitly requested or configured via COLDMEMORY_HYBRID_MODEL."""
423
+ if os.environ.get("COLDMEMORY_HYBRID", "").strip().lower() in ("0", "false", "off", "no"):
424
+ return None
425
+ target = model_dir or os.environ.get("COLDMEMORY_HYBRID_MODEL", "").strip()
426
+ if not target:
427
+ return None
428
+ if not available():
429
+ return None
430
+ return OnnxBiEncoder(target, threads=threads)