thalam 0.1.0__py3-none-win_amd64.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.
thalam/__init__.py ADDED
@@ -0,0 +1,380 @@
1
+ """Python wrapper for Thalam (pure-Rust SIMD-accelerated liquid-spiking HDC runtime)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import os
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import Literal, Sequence
11
+
12
+ EncodingMode = Literal["phase", "isi-chain"]
13
+
14
+
15
+ class _CConfig(ctypes.Structure):
16
+ _fields_ = [
17
+ ("seed", ctypes.c_uint64),
18
+ ("fan_out", ctypes.c_uint32),
19
+ ("exc_ratio", ctypes.c_float),
20
+ ("base_delay_us", ctypes.c_uint32),
21
+ ("delay_jitter_us", ctypes.c_uint32),
22
+ ("ood_threshold", ctypes.c_float),
23
+ ("phase_window_us", ctypes.c_uint64),
24
+ ("decay_interval_us", ctypes.c_uint64),
25
+ ("decay_shift", ctypes.c_uint8),
26
+ ("plasticity_enabled", ctypes.c_uint8),
27
+ ("encoding_mode", ctypes.c_uint8),
28
+ ("_pad", ctypes.c_uint8),
29
+ ("max_events_per_step", ctypes.c_uint32),
30
+ ("stdp_learning_rate", ctypes.c_float),
31
+ ("refractory_us", ctypes.c_uint64),
32
+ ("theta_jump", ctypes.c_float),
33
+ ("_pad2", ctypes.c_uint32),
34
+ ("isi_min_us", ctypes.c_uint64),
35
+ ("isi_max_us", ctypes.c_uint64),
36
+ ]
37
+
38
+
39
+ class _CQueryMatch(ctypes.Structure):
40
+ _fields_ = [
41
+ ("class_id", ctypes.c_uint16),
42
+ ("is_unknown", ctypes.c_uint8),
43
+ ("_pad", ctypes.c_uint8),
44
+ ("distance", ctypes.c_float),
45
+ ("surprise", ctypes.c_float),
46
+ ]
47
+
48
+
49
+ class _CTelemetry(ctypes.Structure):
50
+ _fields_ = [
51
+ ("spikes_emitted", ctypes.c_uint64),
52
+ ("query", _CQueryMatch),
53
+ ]
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class EngineConfig:
58
+ """Configuration for ``ThalamEngine``."""
59
+
60
+ seed: int = 0x5EED_CAFE_BABE_0001
61
+ fan_out: int = 4
62
+ exc_ratio: float = 0.80
63
+ base_delay_us: int = 600
64
+ delay_jitter_us: int = 400
65
+ ood_threshold: float = 0.470
66
+ phase_window_us: int = 100_000
67
+ decay_interval_us: int = 15_000
68
+ decay_shift: int = 3
69
+ max_events_per_step: int = 128
70
+ stdp_learning_rate: float = 0.08
71
+ plasticity_enabled: bool = True
72
+ refractory_us: int = 2_000
73
+ theta_jump: float = 0.35
74
+ encoding: EncodingMode = "phase"
75
+ isi_min_us: int = 1_500
76
+ isi_max_us: int = 10_000
77
+
78
+ @classmethod
79
+ def temporal_rhythm_preset(cls) -> EngineConfig:
80
+ """Frozen v2 preset for order-sensitive inter-spike interval classification."""
81
+ return cls(
82
+ fan_out=4,
83
+ plasticity_enabled=False,
84
+ refractory_us=100,
85
+ theta_jump=0.05,
86
+ ood_threshold=0.36,
87
+ encoding="isi-chain",
88
+ isi_min_us=1_500,
89
+ isi_max_us=10_000,
90
+ )
91
+
92
+ def _to_c(self) -> _CConfig:
93
+ return _CConfig(
94
+ seed=self.seed,
95
+ fan_out=self.fan_out,
96
+ exc_ratio=self.exc_ratio,
97
+ base_delay_us=self.base_delay_us,
98
+ delay_jitter_us=self.delay_jitter_us,
99
+ ood_threshold=self.ood_threshold,
100
+ phase_window_us=self.phase_window_us,
101
+ decay_interval_us=self.decay_interval_us,
102
+ decay_shift=self.decay_shift,
103
+ plasticity_enabled=1 if self.plasticity_enabled else 0,
104
+ encoding_mode=1 if self.encoding == "isi-chain" else 0,
105
+ _pad=0,
106
+ max_events_per_step=self.max_events_per_step,
107
+ stdp_learning_rate=self.stdp_learning_rate,
108
+ refractory_us=self.refractory_us,
109
+ theta_jump=self.theta_jump,
110
+ _pad2=0,
111
+ isi_min_us=self.isi_min_us,
112
+ isi_max_us=self.isi_max_us,
113
+ )
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class QueryMatch:
118
+ class_id: int
119
+ distance: float
120
+ is_unknown: bool
121
+ surprise: float
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class StepTelemetry:
126
+ spikes_emitted: int
127
+ query: QueryMatch
128
+
129
+
130
+ def _lib_filename() -> str:
131
+ if sys.platform == "darwin":
132
+ return "libthalam_ffi.dylib"
133
+ if sys.platform == "win32":
134
+ return "thalam_ffi.dll"
135
+ return "libthalam_ffi.so"
136
+
137
+
138
+ def _resolve_library_path(explicit_path: str | Path | None = None) -> Path:
139
+ if explicit_path is not None:
140
+ return Path(explicit_path)
141
+ env_path = os.environ.get("THALAM_LIB_PATH")
142
+ if env_path:
143
+ return Path(env_path)
144
+
145
+ name = _lib_filename()
146
+ pkg_dir = Path(__file__).resolve().parent
147
+ repo_root = pkg_dir.parent.parent
148
+ candidates = [
149
+ pkg_dir / name,
150
+ repo_root / "target" / "release" / name,
151
+ repo_root / "target" / "debug" / name,
152
+ ]
153
+ for path in candidates:
154
+ if path.exists():
155
+ return path
156
+ raise FileNotFoundError(
157
+ f"Could not find {name}. Build it with `cargo build --release -p thalam-ffi` "
158
+ "or set THALAM_LIB_PATH."
159
+ )
160
+
161
+
162
+ _CACHED_LIB: ctypes.CDLL | None = None
163
+
164
+
165
+ def _load_lib(lib_path: str | Path | None = None) -> ctypes.CDLL:
166
+ global _CACHED_LIB
167
+ if _CACHED_LIB is not None and lib_path is None:
168
+ return _CACHED_LIB
169
+
170
+ path = _resolve_library_path(lib_path)
171
+ lib = ctypes.CDLL(str(path))
172
+
173
+ lib.thalam_default_config.argtypes = []
174
+ lib.thalam_default_config.restype = _CConfig
175
+
176
+ lib.thalam_new.argtypes = [ctypes.POINTER(_CConfig)]
177
+ lib.thalam_new.restype = ctypes.c_void_p
178
+
179
+ lib.thalam_free.argtypes = [ctypes.c_void_p]
180
+ lib.thalam_free.restype = None
181
+
182
+ lib.thalam_reset_window.argtypes = [ctypes.c_void_p, ctypes.c_uint64]
183
+ lib.thalam_reset_window.restype = ctypes.c_int32
184
+
185
+ lib.thalam_ingest_event.argtypes = [
186
+ ctypes.c_void_p,
187
+ ctypes.c_uint32,
188
+ ctypes.c_float,
189
+ ctypes.c_uint64,
190
+ ctypes.POINTER(_CTelemetry),
191
+ ]
192
+ lib.thalam_ingest_event.restype = ctypes.c_int32
193
+
194
+ lib.thalam_ingest_batch.argtypes = [
195
+ ctypes.c_void_p,
196
+ ctypes.POINTER(ctypes.c_uint32),
197
+ ctypes.POINTER(ctypes.c_float),
198
+ ctypes.POINTER(ctypes.c_uint64),
199
+ ctypes.c_size_t,
200
+ ctypes.POINTER(_CTelemetry),
201
+ ]
202
+ lib.thalam_ingest_batch.restype = ctypes.c_int32
203
+
204
+ lib.thalam_teach_current.argtypes = [ctypes.c_void_p, ctypes.c_uint16, ctypes.c_uint8]
205
+ lib.thalam_teach_current.restype = ctypes.c_int32
206
+
207
+ lib.thalam_query_current.argtypes = [ctypes.c_void_p, ctypes.POINTER(_CQueryMatch)]
208
+ lib.thalam_query_current.restype = ctypes.c_int32
209
+
210
+ lib.thalam_query_distances.argtypes = [
211
+ ctypes.c_void_p,
212
+ ctypes.POINTER(ctypes.c_float),
213
+ ctypes.c_size_t,
214
+ ctypes.POINTER(_CQueryMatch),
215
+ ]
216
+ lib.thalam_query_distances.restype = ctypes.c_int32
217
+
218
+ lib.thalam_corrupt_prototypes.argtypes = [ctypes.c_void_p, ctypes.c_float, ctypes.c_uint64]
219
+ lib.thalam_corrupt_prototypes.restype = ctypes.c_int32
220
+
221
+ lib.thalam_clear_memory.argtypes = [ctypes.c_void_p]
222
+ lib.thalam_clear_memory.restype = ctypes.c_int32
223
+
224
+ lib.thalam_active_classes.argtypes = [ctypes.c_void_p]
225
+ lib.thalam_active_classes.restype = ctypes.c_size_t
226
+
227
+ lib.thalam_total_spikes.argtypes = [ctypes.c_void_p]
228
+ lib.thalam_total_spikes.restype = ctypes.c_uint64
229
+
230
+ if lib_path is None:
231
+ _CACHED_LIB = lib
232
+ return lib
233
+
234
+
235
+ class ThalamEngine:
236
+ """Closed-loop Thalam runtime (`128` neurons, `16` classes, `32` time levels)."""
237
+
238
+ def __init__(
239
+ self,
240
+ config: EngineConfig | None = None,
241
+ *,
242
+ lib_path: str | Path | None = None,
243
+ ) -> None:
244
+ self._lib = _load_lib(lib_path)
245
+ cfg = (config or EngineConfig())._to_c()
246
+ handle = self._lib.thalam_new(ctypes.byref(cfg))
247
+ if not handle:
248
+ raise RuntimeError("thalam_new returned null handle")
249
+ self._handle: int | None = handle
250
+
251
+ def _require_handle(self) -> int:
252
+ if self._handle is None:
253
+ raise RuntimeError("ThalamEngine has already been closed")
254
+ return self._handle
255
+
256
+ def close(self) -> None:
257
+ if self._handle is not None:
258
+ self._lib.thalam_free(self._handle)
259
+ self._handle = None
260
+
261
+ def __enter__(self) -> ThalamEngine:
262
+ return self
263
+
264
+ def __exit__(self, exc_type: object, exc: object, tb: object) -> None:
265
+ self.close()
266
+
267
+ def __del__(self) -> None:
268
+ self.close()
269
+
270
+ def reset_window(self, t_us: int) -> None:
271
+ rc = self._lib.thalam_reset_window(self._require_handle(), int(t_us))
272
+ if rc != 0:
273
+ raise RuntimeError(f"thalam_reset_window failed with code {rc}")
274
+
275
+ def ingest_event(self, channel: int, value: float, now_us: int) -> StepTelemetry:
276
+ out = _CTelemetry()
277
+ rc = self._lib.thalam_ingest_event(
278
+ self._require_handle(),
279
+ int(channel),
280
+ float(value),
281
+ int(now_us),
282
+ ctypes.byref(out),
283
+ )
284
+ if rc != 0:
285
+ raise RuntimeError(f"thalam_ingest_event failed with code {rc}")
286
+ return _convert_telemetry(out)
287
+
288
+ def ingest_batch(self, events: Sequence[tuple[int, float, int]]) -> StepTelemetry:
289
+ """Ingest a sequence of ``(channel, value, timestamp_us)`` tuples in one FFI call."""
290
+ n = len(events)
291
+ channels = (ctypes.c_uint32 * n)()
292
+ values = (ctypes.c_float * n)()
293
+ timestamps = (ctypes.c_uint64 * n)()
294
+ for i, (ch, val, ts) in enumerate(events):
295
+ channels[i] = int(ch)
296
+ values[i] = float(val)
297
+ timestamps[i] = int(ts)
298
+
299
+ out = _CTelemetry()
300
+ rc = self._lib.thalam_ingest_batch(
301
+ self._require_handle(),
302
+ channels,
303
+ values,
304
+ timestamps,
305
+ n,
306
+ ctypes.byref(out),
307
+ )
308
+ if rc != 0:
309
+ raise RuntimeError(f"thalam_ingest_batch failed with code {rc}")
310
+ return _convert_telemetry(out)
311
+
312
+ def teach_current(self, class_id: int, weight: int = 2) -> None:
313
+ rc = self._lib.thalam_teach_current(self._require_handle(), int(class_id), int(weight))
314
+ if rc != 0:
315
+ raise RuntimeError(f"thalam_teach_current failed with code {rc}")
316
+
317
+ def query_current(self) -> QueryMatch:
318
+ out = _CQueryMatch()
319
+ rc = self._lib.thalam_query_current(self._require_handle(), ctypes.byref(out))
320
+ if rc != 0:
321
+ raise RuntimeError(f"thalam_query_current failed with code {rc}")
322
+ return _convert_match(out)
323
+
324
+ def query_distances(self, max_classes: int = 16) -> tuple[QueryMatch, list[float]]:
325
+ buf = (ctypes.c_float * max_classes)()
326
+ out = _CQueryMatch()
327
+ rc = self._lib.thalam_query_distances(
328
+ self._require_handle(),
329
+ buf,
330
+ max_classes,
331
+ ctypes.byref(out),
332
+ )
333
+ if rc != 0:
334
+ raise RuntimeError(f"thalam_query_distances failed with code {rc}")
335
+ return _convert_match(out), [float(buf[i]) for i in range(max_classes)]
336
+
337
+ def corrupt_prototypes(self, flip_ratio: float, seed: int = 0xCAFE_BABE) -> None:
338
+ rc = self._lib.thalam_corrupt_prototypes(
339
+ self._require_handle(), float(flip_ratio), int(seed)
340
+ )
341
+ if rc != 0:
342
+ raise RuntimeError(f"thalam_corrupt_prototypes failed with code {rc}")
343
+
344
+ def clear_memory(self) -> None:
345
+ rc = self._lib.thalam_clear_memory(self._require_handle())
346
+ if rc != 0:
347
+ raise RuntimeError(f"thalam_clear_memory failed with code {rc}")
348
+
349
+ @property
350
+ def active_classes(self) -> int:
351
+ return int(self._lib.thalam_active_classes(self._require_handle()))
352
+
353
+ @property
354
+ def total_spikes(self) -> int:
355
+ return int(self._lib.thalam_total_spikes(self._require_handle()))
356
+
357
+
358
+ def _convert_match(m: _CQueryMatch) -> QueryMatch:
359
+ return QueryMatch(
360
+ class_id=int(m.class_id),
361
+ distance=float(m.distance),
362
+ is_unknown=bool(m.is_unknown),
363
+ surprise=float(m.surprise),
364
+ )
365
+
366
+
367
+ def _convert_telemetry(t: _CTelemetry) -> StepTelemetry:
368
+ return StepTelemetry(
369
+ spikes_emitted=int(t.spikes_emitted),
370
+ query=_convert_match(t.query),
371
+ )
372
+
373
+
374
+ __all__ = [
375
+ "EncodingMode",
376
+ "EngineConfig",
377
+ "QueryMatch",
378
+ "StepTelemetry",
379
+ "ThalamEngine",
380
+ ]
thalam/thalam_ffi.dll ADDED
Binary file
@@ -0,0 +1,122 @@
1
+ Metadata-Version: 2.1
2
+ Name: thalam
3
+ Version: 0.1.0
4
+ Summary: Pure-Rust SIMD-accelerated liquid-spiking hyperdimensional computing runtime
5
+ Home-page: https://github.com/shadowinfa/thalam
6
+ License: MIT OR Apache-2.0
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+
10
+ # Thalam
11
+
12
+ **Pure-Rust `#![no_std]`, SIMD-Accelerated Liquid-Spiking Hyperdimensional Computing Runtime**
13
+
14
+ Thalam fuses continuous-time Spiking Liquid Time-Constant (`sLTC`) dynamics with 10,240-bit binary Hyperdimensional Computing (HDC) into a closed-loop, zero-GPU cognitive core that fits in **`< 256 KB`**, learns new temporal patterns in **1 shot (`< 1 µs`)**, flags out-of-distribution (OOD) anomalies at **$5\sigma$**, and maintains **100% recall under 30% RAM bit-corruption**.
15
+
16
+ ---
17
+
18
+ ## Architecture
19
+
20
+ ```text
21
+ Irregular Event Stream (channel, value, timestamp_us)
22
+ │
23
+ ▼
24
+ ┌─────────────────────────────────────────────────────────────────────┐
25
+ │ 1. SENSORY CORTEX (thalam-liquid) │
26
+ │ • Closed-form continuous-time sLTC ODE (zero Euler drift) │
27
+ │ • Homeostatic adaptive firing thresholds │
28
+ │ • Bounded min-heap spike scheduler & 3-factor STDP │
29
+ └──────────────────┬─────────────────────────────────▲────────────────┘
30
+ │ Sparse spikes: (neuron_id, t) │ Surprise M(t)
31
+ ▼ │
32
+ ┌─────────────────────────────────────────────────────────────────────┐
33
+ │ 2. TEMPORAL BRIDGE (thalam-engine + thalam-hv) │
34
+ │ • Binds B[i] ⊗ LevelBasis(Δt) into 20 KB LeakyBundler │
35
+ └──────────────────┬──────────────────────────────────────────────────┘
36
+ │ 10,240-bit HyperVec (1,280 B = 20 cache lines)
37
+ ▼
38
+ ┌─────────────────────────────────────────────────────────────────────┐
39
+ │ 3. COGNITIVE CORTEX (thalam-memory) │
40
+ │ • 4-bit bit-sliced saturating prototypes (zero binarize() pass) │
41
+ │ • SIMD XOR + POPCNT (< 35 ns/vector on NEON) │
42
+ │ • 5σ OOD novelty detector + 1-shot online learning │
43
+ └─────────────────────────────────────────────────────────────────────┘
44
+ ```
45
+
46
+ ---
47
+
48
+ ## Workspace Crates
49
+
50
+ | Crate / Package | `#![no_std]` | Description |
51
+ | :--- | :---: | :--- |
52
+ | `crates/thalam-hv` | Yes | 10,240-bit cache-aligned `HyperVec` (NEON/AVX2/WASM SIMD128), `LevelBasis`, `LeakyBundler` |
53
+ | `crates/thalam-liquid` | Yes | Event-driven `LiquidNeuron` (`sLTC`), bounded `EventQueue`, CSR `LiquidNetwork`, 3-factor STDP |
54
+ | `crates/thalam-memory` | Yes | 4-bit bit-sliced `AssociativeMemory` (`planes[3]` = live prototype) + optional `alloc` exact store |
55
+ | `crates/thalam-engine` | Yes | Closed-loop `ThalamEngine` orchestrator + chaos/recall proof suite |
56
+ | `crates/thalam-bench` | — | Criterion SIMD microbenchmarks |
57
+ | `crates/thalam-wasm` | — | `wasm32` (`+simd128`) zero-copy linear-memory telemetry bridge (`~22 KB` gzipped) |
58
+ | `ui/` | — | SolidJS + TypeScript + WebGPU "Living Connectome & Hypercube" Observatory |
59
+
60
+ ---
61
+
62
+ ## Quick Start
63
+
64
+ ```rust
65
+ use thalam_engine::{EngineConfig, ThalamEngine};
66
+
67
+ // Fits in < 256 KB with zero heap allocation inside the engine
68
+ type EdgeBrain = ThalamEngine<128, 1024, 512, 32, 16>;
69
+
70
+ let mut brain = Box::new(EdgeBrain::new(EngineConfig::default()));
71
+
72
+ // Ingest irregular (channel, impulse, timestamp_us) events
73
+ let _ = brain.ingest_event(4, 3.2, 10_000);
74
+ let _ = brain.ingest_event(7, 2.8, 12_500);
75
+
76
+ // 1-shot online learning
77
+ brain.teach_current(0, 2);
78
+
79
+ // Query with 5σ OOD novelty detection
80
+ let m = brain.query_current();
81
+ assert!(!m.is_unknown);
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Build, Test & Observatory
87
+
88
+ ```bash
89
+ # Format, lint (zero panics/unwraps), and run unit + chaos proof tests
90
+ cargo fmt --check
91
+ cargo clippy --workspace --all-targets -- -D warnings
92
+ cargo test --workspace
93
+
94
+ # Verify bare-metal #![no_std] compilation (RISC-V)
95
+ cargo check -p thalam-hv -p thalam-liquid -p thalam-memory -p thalam-engine \
96
+ --target riscv32imac-unknown-none-elf
97
+
98
+ # Run Criterion SIMD benchmarks
99
+ cargo bench -p thalam-bench --bench core_bench
100
+
101
+ # Build WASM SIMD128 bundle + launch WebGPU Observatory (http://localhost:5173)
102
+ RUSTFLAGS="-C target-feature=+simd128" wasm-pack build crates/thalam-wasm \
103
+ --target web --release --out-dir ../../ui/src/wasm
104
+ cd ui && pnpm install && pnpm dev
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Observed Benchmarks (Apple Silicon NEON)
110
+
111
+ | Operation | Median Latency |
112
+ | :--- | :---: |
113
+ | `HyperVec::hamming_bits` (10,240b POPCNT) | **32.7 ns** |
114
+ | `BitSlicedSlot::bundle_unit` (4-bit 64-wide) | **142.0 ns** |
115
+ | `AssociativeMemory::query` (64 classes) | **2.20 µs** |
116
+ | `sLTC propagate_spike` (fan-out 32) | **203.0 ns** |
117
+
118
+ ---
119
+
120
+ ## License
121
+
122
+ Dual-licensed under **MIT OR Apache-2.0**.
@@ -0,0 +1,5 @@
1
+ thalam/__init__.py,sha256=Jut5uFUOKbeZ6J0QIt4JdkpWUN7KLsIDL0ZwL0UhSvg,12342
2
+ thalam/thalam_ffi.dll,sha256=pfJeC73hoAFhcxuwK-DqDLZX_P7y4w8M4dgFiUlBb5I,164864
3
+ thalam-0.1.0.dist-info/METADATA,sha256=3Be_3WMKxNskjFzCdtgJlEe_OxOWI2nDhmCCSqNPIgw,5767
4
+ thalam-0.1.0.dist-info/WHEEL,sha256=sLR-U0fuaBfT5EXPRIw9bGbch_qItHJNmntc4xTg0Ps,96
5
+ thalam-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: thalam-build-wheel
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64