slate-memory 0.1.0__tar.gz

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.
@@ -0,0 +1,189 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to the Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by the Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding any notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2026 Matthew Lancaster
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188
+ See the License for the specific language governing permissions and
189
+ limitations under the License.
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.4
2
+ Name: slate-memory
3
+ Version: 0.1.0
4
+ Summary: One-shot attractor memory for LLMs — vector-search accuracy at 98% fewer tokens.
5
+ Author-email: Matthew Lancaster <mattclancaster@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Scriblio/slate-memory
8
+ Project-URL: Documentation, https://github.com/Scriblio/slate-memory#readme
9
+ Keywords: llm,memory,rag,attractor,hopfield,retrieval
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.24
18
+ Provides-Extra: embed
19
+ Requires-Dist: sentence-transformers>=2.0; extra == "embed"
20
+ Dynamic: license-file
21
+
22
+ # slate-memory
23
+
24
+ One-shot attractor memory for LLMs. Vector-search accuracy at 98% fewer tokens.
25
+
26
+ ## The number
27
+
28
+ | Setup | Accuracy | Cost per 1k queries | Latency |
29
+ |---|---|---|---|
30
+ | **haiku + slate** | **100%** | **$0.10** | **0.6s** |
31
+ | opus + full context | 100% | $64.04 | 1.7s |
32
+ | opus bare | 0% | $0.19 | 1.2s |
33
+ | haiku bare | 0% | $0.04 | 0.7s |
34
+
35
+ A cheap model with slate-memory **ties the most expensive model with the entire corpus in context** — at 1/640th the cost. Both models score 0% without memory (facts are synthetic, unknowable parametrically). Benchmark: N=25 questions, K=600 stored facts, hermetic SDK calls. Full methodology and reproduction scripts in [slate-bench](https://github.com/mattlancaster/slate-bench).
36
+
37
+ ## How it works
38
+
39
+ Slate-memory is a [modern Hopfield network](https://arxiv.org/abs/2008.02217) (Ramsauer et al. 2020) — the same math as transformer attention, but used as a memory instead of a layer. Embeddings are sign-projected onto 10,000 bipolar cells (SimHash) and stored one-shot. On recall, the query settles into the nearest stored attractor via softmax-weighted feedback. Two cycles. No training. No index. No database.
40
+
41
+ The attractor dynamics error-correct: noisy, partial, or corrupted queries converge to the exact stored pattern. Verified at 20,000 stored patterns with 25% corruption.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install slate-memory
47
+ ```
48
+
49
+ For the built-in embedder convenience wrapper:
50
+
51
+ ```bash
52
+ pip install slate-memory[embed]
53
+ ```
54
+
55
+ ## Quick start
56
+
57
+ ```python
58
+ from slate_memory import SlateBank
59
+ import numpy as np
60
+
61
+ # Your embeddings (384-dim for MiniLM, 1536 for OpenAI, etc.)
62
+ bank = SlateBank(dim=384)
63
+
64
+ # Commit facts one-shot
65
+ bank.commit(embed("The capital of France is Paris"), {"text": "Paris is the capital of France", "id": "fact-1"})
66
+ bank.commit(embed("Python was created by Guido van Rossum"), {"text": "Guido created Python", "id": "fact-2"})
67
+
68
+ # Recall — even from a noisy or partial query
69
+ winner, ranked, confidence, cycles = bank.recall(embed("What's the capital of France?"))
70
+ print(winner) # {"text": "Paris is the capital of France", "id": "fact-1"}
71
+ print(f"Confidence: {confidence:.3f}, settled in {cycles} cycles")
72
+ ```
73
+
74
+ ### With sentence-transformers
75
+
76
+ ```python
77
+ from slate_memory import SlateBank
78
+ from sentence_transformers import SentenceTransformer
79
+
80
+ model = SentenceTransformer("all-MiniLM-L6-v2")
81
+ bank = SlateBank(dim=384)
82
+
83
+ # Commit
84
+ texts = ["The Earth orbits the Sun", "Water boils at 100°C", "Light travels at 299,792 km/s"]
85
+ for text in texts:
86
+ bank.commit(model.encode(text), {"text": text})
87
+
88
+ # Recall
89
+ query = model.encode("what temperature does water boil")
90
+ winner, ranked, confidence, cycles = bank.recall(query)
91
+ print(winner["text"]) # "Water boils at 100°C"
92
+ ```
93
+
94
+ ### With OpenAI embeddings
95
+
96
+ ```python
97
+ from slate_memory import SlateBank
98
+ from openai import OpenAI
99
+
100
+ client = OpenAI()
101
+ bank = SlateBank(dim=1536) # text-embedding-3-small
102
+
103
+ def embed(text):
104
+ return client.embeddings.create(input=text, model="text-embedding-3-small").data[0].embedding
105
+
106
+ bank.commit(embed("Revenue was $4.2M in Q3"), {"text": "Q3 revenue: $4.2M"})
107
+ winner, _, conf, _ = bank.recall(embed("how much revenue in Q3"))
108
+ ```
109
+
110
+ ## Persistence
111
+
112
+ ```python
113
+ # Save
114
+ bank.save("./my_memory")
115
+
116
+ # Load
117
+ bank2 = SlateBank(dim=384)
118
+ n = bank2.load("./my_memory")
119
+ print(f"Loaded {n} patterns")
120
+ ```
121
+
122
+ The entire memory is two files: `patterns.npy` (the attractor states) and `meta.json` (your metadata). No server. No database. Copy them anywhere.
123
+
124
+ ## API
125
+
126
+ ### `SlateBank(dim, n_cells=10000, beta=60.0, distinctiveness=True, dedup_threshold=0.95, seed=7)`
127
+
128
+ - **dim**: Embedding dimensionality (must match your embedder)
129
+ - **n_cells**: Bipolar cells in the attractor state. 10,000 is verified for up to 20k patterns
130
+ - **beta**: Winner-take-all sharpness. 60.0 is benchmarked; don't change without reason
131
+ - **distinctiveness**: Down-weight cells where all patterns agree. Essential for images; neutral for text
132
+ - **dedup_threshold**: Refuse commits with overlap above this. 0.95 prevents near-duplicates
133
+ - **seed**: RNG seed for the projection matrix. Same seed = same projections = portable patterns
134
+
135
+ ### `bank.commit(embedding, meta) → (bool, str)`
136
+
137
+ One-shot storage. Returns `(True, "committed")` or `(False, "duplicate (...)")`.
138
+
139
+ ### `bank.recall(embedding, top_k=3, max_cycles=5) → (winner, ranked, confidence, cycles)`
140
+
141
+ Full attractor settle. Returns the winner's metadata, top-k ranked results, confidence score, and settle cycles.
142
+
143
+ ### `bank.familiar(embedding) → (meta, score)`
144
+
145
+ Quick overlap check without settling. Use for "have I seen this before?" checks.
146
+
147
+ ### `bank.save(path)` / `bank.load(path)`
148
+
149
+ Persist to / restore from a directory.
150
+
151
+ ## Benchmarks
152
+
153
+ Full retrieval benchmarks across 5 corruption conditions and 4 capacity levels show accuracy parity with exact cosine search (±1 point). The attractor substrate recalls 20,000 random patterns perfectly at 25% corruption. Capacity is limited by embedding discriminability (the embedder), not the attractor.
154
+
155
+ Honest limitations in software: per-query latency is ~35x slower than exact vector search (19ms vs 0.5ms at K=2000) because the projected patterns are 10,000-d vs 384-d. The speed case is the [photonic implementation](https://en.wikipedia.org/wiki/Optical_computing) where recall is one pass of light — that's the roadmap, not the demo.
156
+
157
+ See [slate-bench](https://github.com/mattlancaster/slate-bench) for full reproduction scripts and results.
158
+
159
+ ## License
160
+
161
+ Apache 2.0. Patent pending.
@@ -0,0 +1,140 @@
1
+ # slate-memory
2
+
3
+ One-shot attractor memory for LLMs. Vector-search accuracy at 98% fewer tokens.
4
+
5
+ ## The number
6
+
7
+ | Setup | Accuracy | Cost per 1k queries | Latency |
8
+ |---|---|---|---|
9
+ | **haiku + slate** | **100%** | **$0.10** | **0.6s** |
10
+ | opus + full context | 100% | $64.04 | 1.7s |
11
+ | opus bare | 0% | $0.19 | 1.2s |
12
+ | haiku bare | 0% | $0.04 | 0.7s |
13
+
14
+ A cheap model with slate-memory **ties the most expensive model with the entire corpus in context** — at 1/640th the cost. Both models score 0% without memory (facts are synthetic, unknowable parametrically). Benchmark: N=25 questions, K=600 stored facts, hermetic SDK calls. Full methodology and reproduction scripts in [slate-bench](https://github.com/mattlancaster/slate-bench).
15
+
16
+ ## How it works
17
+
18
+ Slate-memory is a [modern Hopfield network](https://arxiv.org/abs/2008.02217) (Ramsauer et al. 2020) — the same math as transformer attention, but used as a memory instead of a layer. Embeddings are sign-projected onto 10,000 bipolar cells (SimHash) and stored one-shot. On recall, the query settles into the nearest stored attractor via softmax-weighted feedback. Two cycles. No training. No index. No database.
19
+
20
+ The attractor dynamics error-correct: noisy, partial, or corrupted queries converge to the exact stored pattern. Verified at 20,000 stored patterns with 25% corruption.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install slate-memory
26
+ ```
27
+
28
+ For the built-in embedder convenience wrapper:
29
+
30
+ ```bash
31
+ pip install slate-memory[embed]
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ from slate_memory import SlateBank
38
+ import numpy as np
39
+
40
+ # Your embeddings (384-dim for MiniLM, 1536 for OpenAI, etc.)
41
+ bank = SlateBank(dim=384)
42
+
43
+ # Commit facts one-shot
44
+ bank.commit(embed("The capital of France is Paris"), {"text": "Paris is the capital of France", "id": "fact-1"})
45
+ bank.commit(embed("Python was created by Guido van Rossum"), {"text": "Guido created Python", "id": "fact-2"})
46
+
47
+ # Recall — even from a noisy or partial query
48
+ winner, ranked, confidence, cycles = bank.recall(embed("What's the capital of France?"))
49
+ print(winner) # {"text": "Paris is the capital of France", "id": "fact-1"}
50
+ print(f"Confidence: {confidence:.3f}, settled in {cycles} cycles")
51
+ ```
52
+
53
+ ### With sentence-transformers
54
+
55
+ ```python
56
+ from slate_memory import SlateBank
57
+ from sentence_transformers import SentenceTransformer
58
+
59
+ model = SentenceTransformer("all-MiniLM-L6-v2")
60
+ bank = SlateBank(dim=384)
61
+
62
+ # Commit
63
+ texts = ["The Earth orbits the Sun", "Water boils at 100°C", "Light travels at 299,792 km/s"]
64
+ for text in texts:
65
+ bank.commit(model.encode(text), {"text": text})
66
+
67
+ # Recall
68
+ query = model.encode("what temperature does water boil")
69
+ winner, ranked, confidence, cycles = bank.recall(query)
70
+ print(winner["text"]) # "Water boils at 100°C"
71
+ ```
72
+
73
+ ### With OpenAI embeddings
74
+
75
+ ```python
76
+ from slate_memory import SlateBank
77
+ from openai import OpenAI
78
+
79
+ client = OpenAI()
80
+ bank = SlateBank(dim=1536) # text-embedding-3-small
81
+
82
+ def embed(text):
83
+ return client.embeddings.create(input=text, model="text-embedding-3-small").data[0].embedding
84
+
85
+ bank.commit(embed("Revenue was $4.2M in Q3"), {"text": "Q3 revenue: $4.2M"})
86
+ winner, _, conf, _ = bank.recall(embed("how much revenue in Q3"))
87
+ ```
88
+
89
+ ## Persistence
90
+
91
+ ```python
92
+ # Save
93
+ bank.save("./my_memory")
94
+
95
+ # Load
96
+ bank2 = SlateBank(dim=384)
97
+ n = bank2.load("./my_memory")
98
+ print(f"Loaded {n} patterns")
99
+ ```
100
+
101
+ The entire memory is two files: `patterns.npy` (the attractor states) and `meta.json` (your metadata). No server. No database. Copy them anywhere.
102
+
103
+ ## API
104
+
105
+ ### `SlateBank(dim, n_cells=10000, beta=60.0, distinctiveness=True, dedup_threshold=0.95, seed=7)`
106
+
107
+ - **dim**: Embedding dimensionality (must match your embedder)
108
+ - **n_cells**: Bipolar cells in the attractor state. 10,000 is verified for up to 20k patterns
109
+ - **beta**: Winner-take-all sharpness. 60.0 is benchmarked; don't change without reason
110
+ - **distinctiveness**: Down-weight cells where all patterns agree. Essential for images; neutral for text
111
+ - **dedup_threshold**: Refuse commits with overlap above this. 0.95 prevents near-duplicates
112
+ - **seed**: RNG seed for the projection matrix. Same seed = same projections = portable patterns
113
+
114
+ ### `bank.commit(embedding, meta) → (bool, str)`
115
+
116
+ One-shot storage. Returns `(True, "committed")` or `(False, "duplicate (...)")`.
117
+
118
+ ### `bank.recall(embedding, top_k=3, max_cycles=5) → (winner, ranked, confidence, cycles)`
119
+
120
+ Full attractor settle. Returns the winner's metadata, top-k ranked results, confidence score, and settle cycles.
121
+
122
+ ### `bank.familiar(embedding) → (meta, score)`
123
+
124
+ Quick overlap check without settling. Use for "have I seen this before?" checks.
125
+
126
+ ### `bank.save(path)` / `bank.load(path)`
127
+
128
+ Persist to / restore from a directory.
129
+
130
+ ## Benchmarks
131
+
132
+ Full retrieval benchmarks across 5 corruption conditions and 4 capacity levels show accuracy parity with exact cosine search (±1 point). The attractor substrate recalls 20,000 random patterns perfectly at 25% corruption. Capacity is limited by embedding discriminability (the embedder), not the attractor.
133
+
134
+ Honest limitations in software: per-query latency is ~35x slower than exact vector search (19ms vs 0.5ms at K=2000) because the projected patterns are 10,000-d vs 384-d. The speed case is the [photonic implementation](https://en.wikipedia.org/wiki/Optical_computing) where recall is one pass of light — that's the roadmap, not the demo.
135
+
136
+ See [slate-bench](https://github.com/mattlancaster/slate-bench) for full reproduction scripts and results.
137
+
138
+ ## License
139
+
140
+ Apache 2.0. Patent pending.
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "slate-memory"
7
+ version = "0.1.0"
8
+ description = "One-shot attractor memory for LLMs — vector-search accuracy at 98% fewer tokens."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ {name = "Matthew Lancaster", email = "mattclancaster@gmail.com"},
14
+ ]
15
+ keywords = ["llm", "memory", "rag", "attractor", "hopfield", "retrieval"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Developers",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Programming Language :: Python :: 3",
21
+ ]
22
+ dependencies = [
23
+ "numpy>=1.24",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ embed = ["sentence-transformers>=2.0"]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/Scriblio/slate-memory"
31
+ Documentation = "https://github.com/Scriblio/slate-memory#readme"
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["slate_memory*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,13 @@
1
+ """slate-memory — one-shot attractor memory for LLMs and agents.
2
+
3
+ from slate_memory import SlateBank
4
+
5
+ bank = SlateBank()
6
+ bank.commit(embedding, {"text": "Paris is the capital of France"})
7
+ winner, top_k, confidence, cycles = bank.recall(query_embedding)
8
+ """
9
+
10
+ from slate_memory.bank import SlateBank
11
+
12
+ __all__ = ["SlateBank"]
13
+ __version__ = "0.1.0"
@@ -0,0 +1,244 @@
1
+ """SlateBank — one-shot attractor memory with error-correcting recall.
2
+
3
+ Text or image embeddings are sign-projected onto N bipolar cells (SimHash),
4
+ converting cosine similarity into Hamming similarity, and committed one-shot.
5
+ Recall settles the probe into the nearest stored attractor via a softmax-
6
+ weighted (modern Hopfield) feedback update.
7
+
8
+ Benchmarked: accuracy parity with exact vector search; 98% prompt-token
9
+ savings over context stuffing; haiku+slate ties opus+full-context at 1/640th
10
+ the cost.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import threading
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+
22
+ class SlateBank:
23
+ """One-shot attractor memory with error-correcting recall.
24
+
25
+ Parameters
26
+ ----------
27
+ n_cells : int
28
+ Number of bipolar cells in the attractor state. More cells = more
29
+ capacity, but slower recall. 10,000 is the verified sweet spot.
30
+ dim : int
31
+ Dimensionality of input embeddings. Must match your embedder
32
+ (384 for MiniLM, 768 for many others, 1536 for OpenAI).
33
+ beta : float
34
+ Winner-take-all sharpness. Higher = harder selection among stored
35
+ patterns. 60.0 is verified; don't change without benchmarking.
36
+ distinctiveness : bool
37
+ Down-weight cells where all stored patterns agree (shared template
38
+ scaffolding). Essential for visual patterns; neutral for text.
39
+ dedup_threshold : float
40
+ Overlap above which a new commit is refused as a duplicate.
41
+ 0.95 is conservative; lower to allow finer distinctions.
42
+ seed : int
43
+ RNG seed for the projection matrix. Two SlateBank instances with
44
+ the same seed + dim + n_cells produce identical projections, so
45
+ patterns are portable between them.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ n_cells: int = 10_000,
51
+ dim: int = 384,
52
+ beta: float = 60.0,
53
+ distinctiveness: bool = True,
54
+ dedup_threshold: float = 0.95,
55
+ seed: int = 7,
56
+ ):
57
+ rng = np.random.default_rng(seed)
58
+ self._R = rng.standard_normal((n_cells, dim)).astype(np.float32)
59
+ self._n = n_cells
60
+ self._beta = beta
61
+ self._distinctiveness = distinctiveness
62
+ self._dedup_threshold = dedup_threshold
63
+ self._lock = threading.Lock()
64
+ self._patterns: list[np.ndarray] = []
65
+ self._meta: list[dict] = []
66
+ self._P: np.ndarray | None = None
67
+ self._w: np.ndarray | None = None
68
+
69
+ @property
70
+ def count(self) -> int:
71
+ """Number of stored patterns."""
72
+ return len(self._patterns)
73
+
74
+ def _project(self, emb: np.ndarray) -> np.ndarray:
75
+ e = np.asarray(emb, dtype=np.float32).ravel()
76
+ return np.where(self._R @ e >= 0, 1.0, -1.0).astype(np.float32)
77
+
78
+ def _finalize(self) -> None:
79
+ if not self._patterns:
80
+ return
81
+ self._P = np.stack(self._patterns)
82
+ if self._distinctiveness and len(self._patterns) >= 2:
83
+ agree = np.abs(self._P.mean(axis=0))
84
+ w = 1.0 - agree
85
+ s = float(w.sum())
86
+ if s > self._n * 0.05:
87
+ self._w = (w * (self._n / s)).astype(np.float32)
88
+ else:
89
+ self._w = None
90
+ else:
91
+ self._w = None
92
+
93
+ def _overlaps(self, s: np.ndarray) -> np.ndarray:
94
+ if self._w is not None:
95
+ return (self._P @ (self._w * s)) / self._n
96
+ return (self._P @ s) / self._n
97
+
98
+ # ── write ────────────────────────────────────────────────────────────
99
+
100
+ def commit(self, embedding: np.ndarray, meta: dict) -> tuple[bool, str]:
101
+ """Store a pattern one-shot. Returns (committed, reason).
102
+
103
+ Parameters
104
+ ----------
105
+ embedding : array-like
106
+ The embedding vector (must match `dim`).
107
+ meta : dict
108
+ Arbitrary metadata returned on recall (text, id, tags, etc.).
109
+ """
110
+ pat = self._project(embedding)
111
+ with self._lock:
112
+ if self._patterns and self._dedup_threshold < 1.0:
113
+ if self._P is None:
114
+ self._finalize()
115
+ overlaps = (self._P @ pat) / self._n
116
+ best = float(np.max(overlaps))
117
+ if best >= self._dedup_threshold:
118
+ idx = int(np.argmax(overlaps))
119
+ return False, f"duplicate (overlap {best:.3f} with {self._meta[idx].get('id', idx)})"
120
+ self._patterns.append(pat)
121
+ self._meta.append(meta)
122
+ self._P = None
123
+ return True, "committed"
124
+
125
+ def commit_batch(
126
+ self, embeddings: list[np.ndarray], metas: list[dict]
127
+ ) -> list[tuple[bool, str]]:
128
+ """Commit multiple patterns. Dedup checks run against the growing store."""
129
+ results = []
130
+ for emb, meta in zip(embeddings, metas):
131
+ results.append(self.commit(emb, meta))
132
+ return results
133
+
134
+ # ── read ─────────────────────────────────────────────────────────────
135
+
136
+ def recall(
137
+ self, embedding: np.ndarray, top_k: int = 3, max_cycles: int = 5
138
+ ) -> tuple[dict | None, list[dict], float, int]:
139
+ """Settle into the nearest attractor. Returns (winner, ranked, confidence, cycles).
140
+
141
+ Parameters
142
+ ----------
143
+ embedding : array-like
144
+ Query embedding.
145
+ top_k : int
146
+ Number of ranked results to return.
147
+ max_cycles : int
148
+ Maximum settle iterations. Usually converges in 2.
149
+ """
150
+ with self._lock:
151
+ if not self._patterns:
152
+ return None, [], 0.0, 0
153
+ if self._P is None:
154
+ self._finalize()
155
+ s = self._project(embedding)
156
+ initial = self._overlaps(s)
157
+ cycles = 0
158
+ for _ in range(max_cycles):
159
+ o = self._overlaps(s)
160
+ a = np.exp(self._beta * (o - o.max()))
161
+ a /= a.sum()
162
+ s_new = np.where(self._P.T @ a >= 0, 1.0, -1.0).astype(np.float32)
163
+ cycles += 1
164
+ if np.array_equal(s_new, s):
165
+ break
166
+ s = s_new
167
+ final = self._overlaps(s)
168
+ winner = int(np.argmax(final))
169
+ order = np.argsort(-initial)[:top_k]
170
+ ranked = [self._meta[int(i)] for i in order]
171
+ if ranked and ranked[0] != self._meta[winner]:
172
+ ranked = [self._meta[winner]] + [
173
+ m for m in ranked if m != self._meta[winner]
174
+ ][:top_k - 1]
175
+ return self._meta[winner], ranked, float(final[winner]), cycles
176
+
177
+ def familiar(self, embedding: np.ndarray) -> tuple[dict | None, float]:
178
+ """Quick similarity check without full settle. Returns (best_meta, score)."""
179
+ with self._lock:
180
+ if not self._patterns:
181
+ return None, 0.0
182
+ if self._P is None:
183
+ self._finalize()
184
+ s = self._project(embedding)
185
+ o = self._overlaps(s)
186
+ best = int(np.argmax(o))
187
+ return self._meta[best], float(o[best])
188
+
189
+ # ── persistence ──────────────────────────────────────────────────────
190
+
191
+ def save(self, path: str | Path) -> None:
192
+ """Save patterns and metadata to a directory."""
193
+ d = Path(path)
194
+ d.mkdir(parents=True, exist_ok=True)
195
+ with self._lock:
196
+ if self._patterns:
197
+ P = np.stack(self._patterns)
198
+ np.save(str(d / "patterns.npy"), P)
199
+ with open(d / "meta.json", "w", encoding="utf-8") as f:
200
+ json.dump(self._meta, f, ensure_ascii=False, indent=1)
201
+ with open(d / "config.json", "w") as f:
202
+ json.dump({
203
+ "n_cells": self._n,
204
+ "dim": self._R.shape[1],
205
+ "beta": self._beta,
206
+ "seed": 7,
207
+ "distinctiveness": self._distinctiveness,
208
+ "dedup_threshold": self._dedup_threshold,
209
+ "count": len(self._patterns),
210
+ }, f, indent=2)
211
+
212
+ def load(self, path: str | Path) -> int:
213
+ """Load patterns and metadata. Returns number of patterns loaded."""
214
+ d = Path(path)
215
+ if not (d / "patterns.npy").exists():
216
+ return 0
217
+ with self._lock:
218
+ P = np.load(str(d / "patterns.npy"))
219
+ with open(d / "meta.json", encoding="utf-8") as f:
220
+ self._meta = json.load(f)
221
+ n = min(len(P), len(self._meta))
222
+ self._patterns = [P[i] for i in range(n)]
223
+ self._meta = self._meta[:n]
224
+ self._P = None
225
+ return n
226
+
227
+ # ── utility ──────────────────────────────────────────────────────────
228
+
229
+ def list(self, limit: int = 50) -> list[dict]:
230
+ """Return metadata for stored patterns."""
231
+ with self._lock:
232
+ return list(self._meta[:limit])
233
+
234
+ def stats(self) -> dict:
235
+ """Return summary statistics."""
236
+ with self._lock:
237
+ return {
238
+ "count": len(self._patterns),
239
+ "n_cells": self._n,
240
+ "dim": self._R.shape[1],
241
+ "beta": self._beta,
242
+ "distinctiveness": self._distinctiveness,
243
+ "dedup_threshold": self._dedup_threshold,
244
+ }
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.4
2
+ Name: slate-memory
3
+ Version: 0.1.0
4
+ Summary: One-shot attractor memory for LLMs — vector-search accuracy at 98% fewer tokens.
5
+ Author-email: Matthew Lancaster <mattclancaster@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/Scriblio/slate-memory
8
+ Project-URL: Documentation, https://github.com/Scriblio/slate-memory#readme
9
+ Keywords: llm,memory,rag,attractor,hopfield,retrieval
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Classifier: Programming Language :: Python :: 3
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.24
18
+ Provides-Extra: embed
19
+ Requires-Dist: sentence-transformers>=2.0; extra == "embed"
20
+ Dynamic: license-file
21
+
22
+ # slate-memory
23
+
24
+ One-shot attractor memory for LLMs. Vector-search accuracy at 98% fewer tokens.
25
+
26
+ ## The number
27
+
28
+ | Setup | Accuracy | Cost per 1k queries | Latency |
29
+ |---|---|---|---|
30
+ | **haiku + slate** | **100%** | **$0.10** | **0.6s** |
31
+ | opus + full context | 100% | $64.04 | 1.7s |
32
+ | opus bare | 0% | $0.19 | 1.2s |
33
+ | haiku bare | 0% | $0.04 | 0.7s |
34
+
35
+ A cheap model with slate-memory **ties the most expensive model with the entire corpus in context** — at 1/640th the cost. Both models score 0% without memory (facts are synthetic, unknowable parametrically). Benchmark: N=25 questions, K=600 stored facts, hermetic SDK calls. Full methodology and reproduction scripts in [slate-bench](https://github.com/mattlancaster/slate-bench).
36
+
37
+ ## How it works
38
+
39
+ Slate-memory is a [modern Hopfield network](https://arxiv.org/abs/2008.02217) (Ramsauer et al. 2020) — the same math as transformer attention, but used as a memory instead of a layer. Embeddings are sign-projected onto 10,000 bipolar cells (SimHash) and stored one-shot. On recall, the query settles into the nearest stored attractor via softmax-weighted feedback. Two cycles. No training. No index. No database.
40
+
41
+ The attractor dynamics error-correct: noisy, partial, or corrupted queries converge to the exact stored pattern. Verified at 20,000 stored patterns with 25% corruption.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install slate-memory
47
+ ```
48
+
49
+ For the built-in embedder convenience wrapper:
50
+
51
+ ```bash
52
+ pip install slate-memory[embed]
53
+ ```
54
+
55
+ ## Quick start
56
+
57
+ ```python
58
+ from slate_memory import SlateBank
59
+ import numpy as np
60
+
61
+ # Your embeddings (384-dim for MiniLM, 1536 for OpenAI, etc.)
62
+ bank = SlateBank(dim=384)
63
+
64
+ # Commit facts one-shot
65
+ bank.commit(embed("The capital of France is Paris"), {"text": "Paris is the capital of France", "id": "fact-1"})
66
+ bank.commit(embed("Python was created by Guido van Rossum"), {"text": "Guido created Python", "id": "fact-2"})
67
+
68
+ # Recall — even from a noisy or partial query
69
+ winner, ranked, confidence, cycles = bank.recall(embed("What's the capital of France?"))
70
+ print(winner) # {"text": "Paris is the capital of France", "id": "fact-1"}
71
+ print(f"Confidence: {confidence:.3f}, settled in {cycles} cycles")
72
+ ```
73
+
74
+ ### With sentence-transformers
75
+
76
+ ```python
77
+ from slate_memory import SlateBank
78
+ from sentence_transformers import SentenceTransformer
79
+
80
+ model = SentenceTransformer("all-MiniLM-L6-v2")
81
+ bank = SlateBank(dim=384)
82
+
83
+ # Commit
84
+ texts = ["The Earth orbits the Sun", "Water boils at 100°C", "Light travels at 299,792 km/s"]
85
+ for text in texts:
86
+ bank.commit(model.encode(text), {"text": text})
87
+
88
+ # Recall
89
+ query = model.encode("what temperature does water boil")
90
+ winner, ranked, confidence, cycles = bank.recall(query)
91
+ print(winner["text"]) # "Water boils at 100°C"
92
+ ```
93
+
94
+ ### With OpenAI embeddings
95
+
96
+ ```python
97
+ from slate_memory import SlateBank
98
+ from openai import OpenAI
99
+
100
+ client = OpenAI()
101
+ bank = SlateBank(dim=1536) # text-embedding-3-small
102
+
103
+ def embed(text):
104
+ return client.embeddings.create(input=text, model="text-embedding-3-small").data[0].embedding
105
+
106
+ bank.commit(embed("Revenue was $4.2M in Q3"), {"text": "Q3 revenue: $4.2M"})
107
+ winner, _, conf, _ = bank.recall(embed("how much revenue in Q3"))
108
+ ```
109
+
110
+ ## Persistence
111
+
112
+ ```python
113
+ # Save
114
+ bank.save("./my_memory")
115
+
116
+ # Load
117
+ bank2 = SlateBank(dim=384)
118
+ n = bank2.load("./my_memory")
119
+ print(f"Loaded {n} patterns")
120
+ ```
121
+
122
+ The entire memory is two files: `patterns.npy` (the attractor states) and `meta.json` (your metadata). No server. No database. Copy them anywhere.
123
+
124
+ ## API
125
+
126
+ ### `SlateBank(dim, n_cells=10000, beta=60.0, distinctiveness=True, dedup_threshold=0.95, seed=7)`
127
+
128
+ - **dim**: Embedding dimensionality (must match your embedder)
129
+ - **n_cells**: Bipolar cells in the attractor state. 10,000 is verified for up to 20k patterns
130
+ - **beta**: Winner-take-all sharpness. 60.0 is benchmarked; don't change without reason
131
+ - **distinctiveness**: Down-weight cells where all patterns agree. Essential for images; neutral for text
132
+ - **dedup_threshold**: Refuse commits with overlap above this. 0.95 prevents near-duplicates
133
+ - **seed**: RNG seed for the projection matrix. Same seed = same projections = portable patterns
134
+
135
+ ### `bank.commit(embedding, meta) → (bool, str)`
136
+
137
+ One-shot storage. Returns `(True, "committed")` or `(False, "duplicate (...)")`.
138
+
139
+ ### `bank.recall(embedding, top_k=3, max_cycles=5) → (winner, ranked, confidence, cycles)`
140
+
141
+ Full attractor settle. Returns the winner's metadata, top-k ranked results, confidence score, and settle cycles.
142
+
143
+ ### `bank.familiar(embedding) → (meta, score)`
144
+
145
+ Quick overlap check without settling. Use for "have I seen this before?" checks.
146
+
147
+ ### `bank.save(path)` / `bank.load(path)`
148
+
149
+ Persist to / restore from a directory.
150
+
151
+ ## Benchmarks
152
+
153
+ Full retrieval benchmarks across 5 corruption conditions and 4 capacity levels show accuracy parity with exact cosine search (±1 point). The attractor substrate recalls 20,000 random patterns perfectly at 25% corruption. Capacity is limited by embedding discriminability (the embedder), not the attractor.
154
+
155
+ Honest limitations in software: per-query latency is ~35x slower than exact vector search (19ms vs 0.5ms at K=2000) because the projected patterns are 10,000-d vs 384-d. The speed case is the [photonic implementation](https://en.wikipedia.org/wiki/Optical_computing) where recall is one pass of light — that's the roadmap, not the demo.
156
+
157
+ See [slate-bench](https://github.com/mattlancaster/slate-bench) for full reproduction scripts and results.
158
+
159
+ ## License
160
+
161
+ Apache 2.0. Patent pending.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ slate_memory/__init__.py
5
+ slate_memory/bank.py
6
+ slate_memory.egg-info/PKG-INFO
7
+ slate_memory.egg-info/SOURCES.txt
8
+ slate_memory.egg-info/dependency_links.txt
9
+ slate_memory.egg-info/requires.txt
10
+ slate_memory.egg-info/top_level.txt
11
+ tests/test_bank.py
@@ -0,0 +1,4 @@
1
+ numpy>=1.24
2
+
3
+ [embed]
4
+ sentence-transformers>=2.0
@@ -0,0 +1 @@
1
+ slate_memory
@@ -0,0 +1,140 @@
1
+ """Tests for SlateBank — the core attractor memory."""
2
+
3
+ import tempfile
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from slate_memory import SlateBank
10
+
11
+
12
+ @pytest.fixture
13
+ def bank():
14
+ return SlateBank(n_cells=1000, dim=64, seed=42)
15
+
16
+
17
+ @pytest.fixture
18
+ def rng():
19
+ return np.random.default_rng(99)
20
+
21
+
22
+ def _random_emb(rng, dim=64):
23
+ e = rng.standard_normal(dim).astype(np.float32)
24
+ return e / np.linalg.norm(e)
25
+
26
+
27
+ def test_commit_and_recall(bank, rng):
28
+ emb = _random_emb(rng)
29
+ ok, reason = bank.commit(emb, {"id": "a"})
30
+ assert ok
31
+ assert reason == "committed"
32
+ assert bank.count == 1
33
+
34
+ winner, ranked, conf, cycles = bank.recall(emb)
35
+ assert winner["id"] == "a"
36
+ assert conf > 0.9
37
+
38
+
39
+ def test_recall_empty(bank, rng):
40
+ winner, ranked, conf, cycles = bank.recall(_random_emb(rng))
41
+ assert winner is None
42
+ assert ranked == []
43
+
44
+
45
+ def test_noisy_recall(bank, rng):
46
+ emb = _random_emb(rng)
47
+ bank.commit(emb, {"id": "original"})
48
+ noisy = emb + rng.standard_normal(64).astype(np.float32) * 0.3
49
+ winner, _, conf, _ = bank.recall(noisy)
50
+ assert winner["id"] == "original"
51
+
52
+
53
+ def test_multiple_patterns(bank, rng):
54
+ embs = [_random_emb(rng) for _ in range(20)]
55
+ for i, e in enumerate(embs):
56
+ bank.commit(e, {"id": f"fact-{i}"})
57
+ assert bank.count == 20
58
+ for i, e in enumerate(embs):
59
+ winner, _, _, _ = bank.recall(e)
60
+ assert winner["id"] == f"fact-{i}"
61
+
62
+
63
+ def test_dedup_guard(bank, rng):
64
+ emb = _random_emb(rng)
65
+ ok1, _ = bank.commit(emb, {"id": "first"})
66
+ ok2, reason = bank.commit(emb, {"id": "second"})
67
+ assert ok1
68
+ assert not ok2
69
+ assert "duplicate" in reason
70
+ assert bank.count == 1
71
+
72
+
73
+ def test_familiar(bank, rng):
74
+ emb = _random_emb(rng)
75
+ meta, score = bank.familiar(emb)
76
+ assert meta is None
77
+ assert score == 0.0
78
+
79
+ bank.commit(emb, {"id": "x"})
80
+ meta, score = bank.familiar(emb)
81
+ assert meta["id"] == "x"
82
+ assert score > 0.9
83
+
84
+
85
+ def test_save_load(bank, rng):
86
+ for i in range(5):
87
+ bank.commit(_random_emb(rng), {"id": f"p-{i}"})
88
+
89
+ with tempfile.TemporaryDirectory() as d:
90
+ bank.save(d)
91
+ assert (Path(d) / "patterns.npy").exists()
92
+ assert (Path(d) / "meta.json").exists()
93
+
94
+ bank2 = SlateBank(n_cells=1000, dim=64, seed=42)
95
+ n = bank2.load(d)
96
+ assert n == 5
97
+ assert bank2.count == 5
98
+
99
+
100
+ def test_persistence_recall_matches(bank, rng):
101
+ embs = [_random_emb(rng) for _ in range(10)]
102
+ for i, e in enumerate(embs):
103
+ bank.commit(e, {"id": f"r-{i}"})
104
+
105
+ with tempfile.TemporaryDirectory() as d:
106
+ bank.save(d)
107
+ bank2 = SlateBank(n_cells=1000, dim=64, seed=42)
108
+ bank2.load(d)
109
+ for i, e in enumerate(embs):
110
+ w1, _, c1, _ = bank.recall(e)
111
+ w2, _, c2, _ = bank2.recall(e)
112
+ assert w1["id"] == w2["id"]
113
+
114
+
115
+ def test_commit_batch(bank, rng):
116
+ embs = [_random_emb(rng) for _ in range(5)]
117
+ metas = [{"id": f"b-{i}"} for i in range(5)]
118
+ results = bank.commit_batch(embs, metas)
119
+ assert all(ok for ok, _ in results)
120
+ assert bank.count == 5
121
+
122
+
123
+ def test_stats(bank, rng):
124
+ bank.commit(_random_emb(rng), {"id": "s"})
125
+ s = bank.stats()
126
+ assert s["count"] == 1
127
+ assert s["n_cells"] == 1000
128
+ assert s["dim"] == 64
129
+
130
+
131
+ def test_different_dims():
132
+ for dim in [384, 768, 1536]:
133
+ b = SlateBank(dim=dim, n_cells=500)
134
+ rng = np.random.default_rng(0)
135
+ e = rng.standard_normal(dim).astype(np.float32)
136
+ ok, _ = b.commit(e, {"dim": dim})
137
+ assert ok
138
+ w, _, c, _ = b.recall(e)
139
+ assert w["dim"] == dim
140
+ assert c > 0.8