fern-memory 0.1.0__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.
fern/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Fern — Local Long-Memory MCP Engine (inference runtime)."""
2
+
3
+ __version__ = "0.1.0"
fern/index.py ADDED
@@ -0,0 +1,185 @@
1
+ """Inference-only compositional VSA + lexical diversity archive index for Fern."""
2
+
3
+ import hashlib
4
+ import math
5
+ import re
6
+ import time
7
+ from collections import Counter, defaultdict
8
+ from typing import Dict, List, Optional, Sequence, Set
9
+
10
+ import numpy as np
11
+ import torch
12
+ import torch.nn.functional as F
13
+
14
+ _STOPWORDS = {
15
+ "the", "a", "an", "is", "are", "was", "were", "be", "been", "to", "of", "in", "on", "at",
16
+ "for", "with", "by", "from", "and", "or", "that", "this", "it", "its", "which", "who",
17
+ "what", "where", "when", "does", "did", "do", "city", "country", "company", "person",
18
+ "name", "identify", "find", "their", "main", "has", "as", "into", "about", "currently",
19
+ "latest", "current", "most", "recent", "user", "mention", "say", "tell", "me", "my", "i",
20
+ }
21
+
22
+
23
+ def clean_decoded_span(s: str) -> str:
24
+ return " ".join(s.strip().strip(".,;:!?\"'()[]{}").split())
25
+
26
+
27
+ def index_tokens(text: str) -> List[str]:
28
+ toks = re.findall(r"[a-z0-9]+", text.casefold())
29
+ return [t for t in toks if len(t) >= 2 and t not in _STOPWORDS]
30
+
31
+
32
+ def _deterministic_vsa_vec(s: str, d: int = 256) -> np.ndarray:
33
+ if not s:
34
+ return np.zeros(d, dtype=np.float32)
35
+ words = re.findall(r"[a-z0-9][a-z0-9\-_]*", s.lower())
36
+ if not words:
37
+ return np.zeros(d, dtype=np.float32)
38
+ acc = np.zeros(d, dtype=np.float32)
39
+ for w in words:
40
+ h = hashlib.sha256(("VSA_W::" + w).encode("utf-8")).digest()
41
+ seed = int.from_bytes(h[:8], "little") & 0x7FFFFFFF
42
+ rng = np.random.default_rng(seed)
43
+ v = rng.standard_normal(d).astype(np.float32)
44
+ acc += v / (np.linalg.norm(v) + 1e-8)
45
+ nrm = float(np.linalg.norm(acc))
46
+ return acc / (nrm + 1e-8) if nrm > 1e-6 else np.zeros(d, dtype=np.float32)
47
+
48
+
49
+ def encode_vsa_strings(strings: List[str], d_model: int = 256, device: Optional[torch.device] = None) -> torch.Tensor:
50
+ arr = np.stack([_deterministic_vsa_vec(clean_decoded_span(s) if s else "", d_model) for s in strings], axis=0)
51
+ t = torch.from_numpy(arr)
52
+ return t.to(device) if device is not None else t
53
+
54
+
55
+ class FernArchiveIndex:
56
+ """Bounded lexical + compositional VSA retriever with temporal context & diversity caps."""
57
+
58
+ def __init__(self, device: torch.device, d_vsa: int = 256):
59
+ self.device = device
60
+ self.d_vsa = d_vsa
61
+ self.reset()
62
+
63
+ def reset(self) -> None:
64
+ self.facts: List[str] = []
65
+ self.vsa_vecs: Optional[torch.Tensor] = None
66
+ self.inv_idx: Dict[str, List[int]] = defaultdict(list)
67
+ self.n_docs: int = 0
68
+
69
+ @torch.no_grad()
70
+ def ingest(self, facts: Sequence[str]) -> Dict:
71
+ t0 = time.perf_counter()
72
+ self.reset()
73
+ self.facts = list(facts)
74
+ self.n_docs = len(self.facts)
75
+ if self.n_docs == 0:
76
+ return {"n_facts": 0, "ingest_sec": 0.0}
77
+ for i, txt in enumerate(self.facts):
78
+ for w in set(index_tokens(txt)):
79
+ self.inv_idx[w].append(i)
80
+ vecs = encode_vsa_strings(self.facts, self.d_vsa, self.device).float()
81
+ self.vsa_vecs = F.normalize(vecs + 1e-6, dim=-1).half()
82
+ if self.device.type == "cuda":
83
+ torch.cuda.synchronize()
84
+ return {"n_facts": self.n_docs, "ingest_sec": round(time.perf_counter() - t0, 4)}
85
+
86
+ @torch.no_grad()
87
+ def propose(
88
+ self,
89
+ query: str,
90
+ top_k: int = 24,
91
+ exclude_idxs: Optional[Set[int]] = None,
92
+ anchor_text: Optional[str] = None,
93
+ ref_idx: Optional[int] = None,
94
+ ) -> List[int]:
95
+ if self.n_docs == 0 or self.vsa_vecs is None:
96
+ return []
97
+ excl = exclude_idxs or set()
98
+ q_toks = index_tokens(query)
99
+ a_toks = index_tokens(anchor_text) if anchor_text else []
100
+ a_set = set(a_toks)
101
+
102
+ scores: Dict[int, float] = defaultdict(float)
103
+ a_hits: Dict[int, int] = defaultdict(int)
104
+ n_f = float(max(2, self.n_docs))
105
+
106
+ for w in set(q_toks):
107
+ postings = self.inv_idx.get(w)
108
+ if not postings or len(postings) > 0.35 * self.n_docs:
109
+ continue
110
+ idf = math.log((n_f + 1.0) / (len(postings) + 1.0))
111
+ for idx in postings:
112
+ if idx not in excl:
113
+ scores[idx] += idf
114
+
115
+ exact_anchor_idxs: List[int] = []
116
+ if a_set:
117
+ a_low = anchor_text.strip().casefold()
118
+ for w in a_set:
119
+ postings = self.inv_idx.get(w)
120
+ if not postings or len(postings) > 0.35 * self.n_docs:
121
+ continue
122
+ idf = math.log((n_f + 1.0) / (len(postings) + 1.0)) * 2.5
123
+ for idx in postings:
124
+ if idx not in excl:
125
+ scores[idx] += idf
126
+ a_hits[idx] += 1
127
+ for idx, cnt in a_hits.items():
128
+ if cnt == len(a_set):
129
+ txt_l = self.facts[idx].casefold()
130
+ pos = txt_l.find(a_low)
131
+ if pos >= 0:
132
+ exact_anchor_idxs.append(idx)
133
+ scores[idx] += 3.0
134
+ if pos <= max(28, len(txt_l) // 2):
135
+ scores[idx] += 3.5
136
+
137
+ if ref_idx is not None and exact_anchor_idxs:
138
+ before_ref = sorted([i for i in exact_anchor_idxs if i < ref_idx], reverse=True)[:4]
139
+ after_ref = sorted([i for i in exact_anchor_idxs if i > ref_idx], reverse=True)[:4]
140
+ for rank_i, idx in enumerate(before_ref):
141
+ scores[idx] += 2.5 - 0.3 * rank_i
142
+ for rank_i, idx in enumerate(after_ref):
143
+ scores[idx] += 2.0 - 0.25 * rank_i
144
+
145
+ q_str = f"{anchor_text} {query}" if anchor_text else query
146
+ qv = F.normalize(encode_vsa_strings([q_str], self.d_vsa, self.device).float() + 1e-6, dim=-1).half()
147
+ vsa_sims = torch.matmul(self.vsa_vecs, qv.T).squeeze(-1).float()
148
+ v_vals, v_idxs = torch.topk(vsa_sims, k=min(top_k * 2, self.n_docs))
149
+ for vv, vi in zip(v_vals.tolist(), v_idxs.tolist()):
150
+ if vi not in excl:
151
+ scores[vi] += max(0.0, vv) * 2.5
152
+
153
+ if scores:
154
+ c_list = list(scores.keys())
155
+ for idx, vv in zip(c_list, vsa_sims[c_list].tolist()):
156
+ scores[idx] += max(0.0, vv) * 1.5
157
+
158
+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], -kv[0]))
159
+ out: List[int] = []
160
+ sig_counts: Counter = Counter()
161
+ overflow: List[int] = []
162
+ min_df = max(3, int(0.002 * self.n_docs))
163
+ for idx, _ in ranked:
164
+ txt = self.facts[idx]
165
+ toks_l = re.findall(r"[a-z]+", txt.casefold())
166
+ sig = tuple(w for w in toks_l if w not in a_set and len(self.inv_idx.get(w, ())) >= min_df)[:6]
167
+ if sig and sig_counts[sig] >= 4:
168
+ overflow.append(idx)
169
+ continue
170
+ sig_counts[sig] += 1
171
+ out.append(idx)
172
+ if len(out) >= top_k:
173
+ break
174
+ if len(out) < top_k:
175
+ for idx in overflow:
176
+ out.append(idx)
177
+ if len(out) >= top_k:
178
+ break
179
+ if len(out) < top_k:
180
+ for idx in range(self.n_docs - 1, -1, -1):
181
+ if idx not in excl and idx not in scores:
182
+ out.append(idx)
183
+ if len(out) >= top_k:
184
+ break
185
+ return out