-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfingerprint.rs
More file actions
575 lines (507 loc) · 16.1 KB
/
Copy pathfingerprint.rs
File metadata and controls
575 lines (507 loc) · 16.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Const-generic binary fingerprint for holographic storage.
//!
//! `Fingerprint<N>` is a fixed-size binary vector of N×64 bits, stored as
//! `[u64; N]`. All holographic operations (XOR bind, Hamming distance,
//! delta layers) operate on this type.
//!
//! Standard sizes:
//! - `Fingerprint<256>` = 2048 bytes = 16384 bits (CogRecord container)
//! - `Fingerprint<128>` = 1024 bytes = 8192 bits
//! - `Fingerprint<1024>` = 8192 bytes = 65536 bits (64K recognition)
use std::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Not};
/// A fixed-size binary fingerprint stored as N words of u64.
///
/// Total bits = N × 64. Total bytes = N × 8.
///
/// The XOR group structure makes this the natural type for holographic
/// delta layers: ground truth is `&self`, writers own their delta as `&mut`.
#[derive(Clone, PartialEq, Eq)]
pub struct Fingerprint<const N: usize> {
pub words: [u64; N],
}
#[allow(clippy::needless_range_loop)]
impl<const N: usize> Fingerprint<N> {
/// Total number of bits in this fingerprint.
pub const BITS: usize = N * 64;
/// Total number of bytes in this fingerprint.
pub const BYTES: usize = N * 8;
/// Zero fingerprint (identity element for XOR).
#[inline]
pub fn zero() -> Self {
Self { words: [0u64; N] }
}
/// All-ones fingerprint.
#[inline]
pub fn ones() -> Self {
Self {
words: [u64::MAX; N],
}
}
/// Create from a word array.
#[inline]
pub fn from_words(words: [u64; N]) -> Self {
Self { words }
}
/// Create from a byte slice. Panics if `bytes.len() < N * 8`.
pub fn from_bytes(bytes: &[u8]) -> Self {
assert!(
bytes.len() >= N * 8,
"need at least {} bytes, got {}",
N * 8,
bytes.len()
);
let mut words = [0u64; N];
for i in 0..N {
let offset = i * 8;
words[i] = u64::from_le_bytes([
bytes[offset],
bytes[offset + 1],
bytes[offset + 2],
bytes[offset + 3],
bytes[offset + 4],
bytes[offset + 5],
bytes[offset + 6],
bytes[offset + 7],
]);
}
Self { words }
}
/// Convert to bytes (little-endian).
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(N * 8);
for w in &self.words {
out.extend_from_slice(&w.to_le_bytes());
}
out
}
/// Get a specific bit (0-indexed).
#[inline]
pub fn get_bit(&self, index: usize) -> bool {
debug_assert!(index < Self::BITS);
let word_idx = index / 64;
let bit_idx = index % 64;
(self.words[word_idx] >> bit_idx) & 1 == 1
}
/// Set a specific bit.
#[inline]
pub fn set_bit(&mut self, index: usize, value: bool) {
debug_assert!(index < Self::BITS);
let word_idx = index / 64;
let bit_idx = index % 64;
if value {
self.words[word_idx] |= 1u64 << bit_idx;
} else {
self.words[word_idx] &= !(1u64 << bit_idx);
}
}
/// Toggle a specific bit.
#[inline]
pub fn toggle_bit(&mut self, index: usize) {
debug_assert!(index < Self::BITS);
let word_idx = index / 64;
let bit_idx = index % 64;
self.words[word_idx] ^= 1u64 << bit_idx;
}
/// Create a random fingerprint from a seed (xorshift128+).
pub fn random(seed: u64) -> Self {
let mut s0 = seed;
let mut s1 = seed.wrapping_mul(0x9E3779B97F4A7C15);
let mut words = [0u64; N];
for word in &mut words {
let mut s = s0;
s0 = s1;
s ^= s << 23;
s ^= s >> 18;
s ^= s1;
s ^= s1 >> 5;
s1 = s;
*word = s0.wrapping_add(s1);
}
Self { words }
}
/// Hamming distance (number of differing bits).
/// Delegates to ndarray's SIMD dispatch (AVX-512 → AVX2 → scalar).
#[inline]
pub fn hamming_distance(&self, other: &Self) -> u32 {
super::bitwise::hamming_distance_raw(self.as_bytes(), other.as_bytes()) as u32
}
/// Alias for `hamming_distance` (ladybug-rs compat).
#[inline]
pub fn hamming(&self, other: &Self) -> u32 {
self.hamming_distance(other)
}
/// XOR bind (ladybug-rs compat). Returns a new fingerprint.
#[inline]
pub fn bind(&self, other: &Self) -> Self {
let mut words = [0u64; N];
for i in 0..N { words[i] = self.words[i] ^ other.words[i]; }
Self { words }
}
/// AND (bitwise intersection).
#[inline]
pub fn and(&self, other: &Self) -> Self {
let mut words = [0u64; N];
for i in 0..N { words[i] = self.words[i] & other.words[i]; }
Self { words }
}
/// Bitwise NOT.
#[inline]
pub fn not(&self) -> Self {
let mut words = [0u64; N];
for i in 0..N { words[i] = !self.words[i]; }
Self { words }
}
/// Density: fraction of set bits (popcount / total bits).
#[inline]
pub fn density(&self) -> f32 {
self.popcount() as f32 / Self::BITS as f32
}
/// Access raw words as slice.
#[inline]
pub fn as_raw(&self) -> &[u64; N] {
&self.words
}
/// Create from content string (SHA-256-like hash expansion).
pub fn from_content(data: &str) -> Self {
let mut h = 0x736f6d6570736575u64;
for (i, b) in data.bytes().enumerate() {
h ^= (b as u64) << ((i % 8) * 8);
h = h.rotate_left(13).wrapping_mul(5).wrapping_add(0xe6546b64);
}
Self::random(h)
}
/// Permute: circular bit shift by `positions` (positive = left).
pub fn permute(&self, positions: i32) -> Self {
let total = Self::BITS as i32;
let shift = ((positions % total) + total) % total;
if shift == 0 { return self.clone(); }
let mut result = Self::zero();
for i in 0..Self::BITS {
if self.get_bit(i) {
let new_pos = ((i as i32 + shift) % total) as usize;
result.set_bit(new_pos, true);
}
}
result
}
/// Hamming weight (number of set bits).
#[inline]
pub fn popcount(&self) -> u32 {
super::bitwise::popcount_raw(self.as_bytes()) as u32
}
/// Returns true if all bits are zero (identity element).
#[inline]
pub fn is_zero(&self) -> bool {
self.words.iter().all(|&w| w == 0)
}
/// Hamming similarity in [0.0, 1.0]. Returns None on zero-width fingerprint.
#[inline]
pub fn similarity(&self, other: &Self) -> Option<f32> {
if Self::BITS == 0 {
return None;
}
Some(1.0 - self.hamming_distance(other) as f32 / Self::BITS as f32)
}
/// Zero-copy view of the fingerprint as a byte slice.
///
/// SAFETY: `[u64; N]` is guaranteed contiguous in memory.
/// `u8` has no alignment requirements stricter than `u64`.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
// SAFETY: [u64; N] is contiguous. u64 is 8-byte aligned; u8 requires
// 1-byte alignment. Pointer cast is always valid. Length N * 8 is exact.
unsafe { std::slice::from_raw_parts(self.words.as_ptr() as *const u8, N * 8) }
}
/// Zero-copy mutable view as byte slice.
#[inline]
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
// SAFETY: Same as as_bytes(). Mutable borrow from &mut self guarantees exclusivity.
unsafe { std::slice::from_raw_parts_mut(self.words.as_mut_ptr() as *mut u8, N * 8) }
}
}
// XOR group operations
#[allow(clippy::needless_range_loop)]
impl<const N: usize> BitXor for Fingerprint<N> {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
let mut words = [0u64; N];
for i in 0..N {
words[i] = self.words[i] ^ rhs.words[i];
}
Self { words }
}
}
#[allow(clippy::needless_range_loop)]
impl<const N: usize> BitXor for &Fingerprint<N> {
type Output = Fingerprint<N>;
#[inline]
fn bitxor(self, rhs: Self) -> Fingerprint<N> {
let mut words = [0u64; N];
for i in 0..N {
words[i] = self.words[i] ^ rhs.words[i];
}
Fingerprint { words }
}
}
impl<const N: usize> BitXorAssign for Fingerprint<N> {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
for i in 0..N {
self.words[i] ^= rhs.words[i];
}
}
}
impl<const N: usize> BitXorAssign<&Fingerprint<N>> for Fingerprint<N> {
#[inline]
fn bitxor_assign(&mut self, rhs: &Self) {
for i in 0..N {
self.words[i] ^= rhs.words[i];
}
}
}
#[allow(clippy::needless_range_loop)]
impl<const N: usize> BitAnd for &Fingerprint<N> {
type Output = Fingerprint<N>;
#[inline]
fn bitand(self, rhs: Self) -> Fingerprint<N> {
let mut words = [0u64; N];
for i in 0..N {
words[i] = self.words[i] & rhs.words[i];
}
Fingerprint { words }
}
}
impl<const N: usize> BitAndAssign<&Fingerprint<N>> for Fingerprint<N> {
#[inline]
fn bitand_assign(&mut self, rhs: &Self) {
for i in 0..N {
self.words[i] &= rhs.words[i];
}
}
}
#[allow(clippy::needless_range_loop)]
impl<const N: usize> BitOr for &Fingerprint<N> {
type Output = Fingerprint<N>;
#[inline]
fn bitor(self, rhs: Self) -> Fingerprint<N> {
let mut words = [0u64; N];
for i in 0..N {
words[i] = self.words[i] | rhs.words[i];
}
Fingerprint { words }
}
}
impl<const N: usize> BitOrAssign<&Fingerprint<N>> for Fingerprint<N> {
#[inline]
fn bitor_assign(&mut self, rhs: &Self) {
for i in 0..N {
self.words[i] |= rhs.words[i];
}
}
}
#[allow(clippy::needless_range_loop)]
impl<const N: usize> Not for &Fingerprint<N> {
type Output = Fingerprint<N>;
#[inline]
fn not(self) -> Fingerprint<N> {
let mut words = [0u64; N];
for i in 0..N {
words[i] = !self.words[i];
}
Fingerprint { words }
}
}
impl<const N: usize> std::fmt::Debug for Fingerprint<N> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Fingerprint<{}>[popcount={}, ", N, self.popcount())?;
let show = N.min(4);
for i in 0..show {
if i > 0 {
write!(f, " ")?;
}
write!(f, "{:016x}", self.words[i])?;
}
if N > 4 {
write!(f, " ...")?;
}
write!(f, "]")
}
}
/// Standard 2048-byte fingerprint (CogRecord container size).
pub type Fingerprint2K = Fingerprint<256>;
/// Standard 1024-byte fingerprint.
pub type Fingerprint1K = Fingerprint<128>;
/// 64K-bit fingerprint (recognition projections).
pub type Fingerprint64K = Fingerprint<1024>;
// ─── Vector width config (LazyLock, switchable) ─────────────────
use std::sync::LazyLock;
/// Supported vector widths for the BindSpace substrate.
///
/// NOTE: 4096 is NOT a vector width — it's the 0xFFF schema/command address
/// space (4096 CAM operations, verb vocabulary). Vectors are 8K or 16K.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u16)]
pub enum VectorWidth {
/// 8,192 bits = 128 words = 1 KB. Deprecated, still referenced in some code.
W8K = 128,
/// 16,384 bits = 256 words = 2 KB. Production default.
W16K = 256,
}
/// Runtime vector configuration. Frozen on first access.
///
/// Like `simd_caps()` — detect once, read everywhere.
/// Controls serialization format, network protocol, and storage layout.
/// Does NOT change the Rust type (use the matching Fingerprint\<N\> alias).
#[derive(Clone, Copy, Debug)]
pub struct VectorConfig {
pub width: VectorWidth,
pub words: usize,
pub bits: usize,
pub bytes: usize,
}
impl VectorConfig {
const fn from_width(w: VectorWidth) -> Self {
let words = w as usize;
VectorConfig { width: w, words, bits: words * 64, bytes: words * 8 }
}
}
static VECTOR_WIDTH: LazyLock<VectorConfig> = LazyLock::new(|| {
let w = std::env::var("NDARRAY_VECTOR_WIDTH")
.ok()
.and_then(|s| match s.as_str() {
"8192" | "8k" | "8K" => Some(VectorWidth::W8K),
"16384" | "16k" | "16K" => Some(VectorWidth::W16K),
_ => None,
})
.unwrap_or(VectorWidth::W16K);
VectorConfig::from_width(w)
});
/// Get the frozen vector width configuration.
///
/// Defaults to 16K (production). Override with `NDARRAY_VECTOR_WIDTH=8192`
/// env var before first access. After first call, width is frozen.
///
/// ```
/// use ndarray::hpc::fingerprint::vector_config;
/// let cfg = vector_config();
/// assert_eq!(cfg.bits, 16_384); // default
/// assert_eq!(cfg.words, 256);
/// assert_eq!(cfg.bytes, 2_048);
/// ```
pub fn vector_config() -> &'static VectorConfig {
&VECTOR_WIDTH
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_zero_identity() {
let a = Fingerprint::<4> {
words: [0xDEAD_BEEF, 0xCAFE_BABE, 0x1234_5678, 0x9ABC_DEF0],
};
let zero = Fingerprint::<4>::zero();
assert_eq!(&a ^ &zero, a);
}
#[test]
fn test_xor_self_inverse() {
let a = Fingerprint::<4> {
words: [0xDEAD_BEEF, 0xCAFE_BABE, 0x1234_5678, 0x9ABC_DEF0],
};
let result = &a ^ &a;
assert!(result.is_zero());
}
#[test]
fn test_xor_associative() {
let a = Fingerprint::<4> {
words: [1, 2, 3, 4],
};
let b = Fingerprint::<4> {
words: [5, 6, 7, 8],
};
let c = Fingerprint::<4> {
words: [9, 10, 11, 12],
};
let ab_c = &(&a ^ &b) ^ &c;
let a_bc = &a ^ &(&b ^ &c);
assert_eq!(ab_c, a_bc);
}
#[test]
fn test_hamming_distance() {
let a = Fingerprint::<2> {
words: [0xFF, 0x00],
};
let b = Fingerprint::<2> {
words: [0x00, 0x00],
};
assert_eq!(a.hamming_distance(&b), 8);
}
#[test]
fn test_hamming_self_zero() {
let a = Fingerprint::<4> {
words: [0xDEAD, 0xBEEF, 0xCAFE, 0xBABE],
};
assert_eq!(a.hamming_distance(&a), 0);
}
#[test]
fn test_popcount() {
let a = Fingerprint::<1> { words: [0xFF] };
assert_eq!(a.popcount(), 8);
let b = Fingerprint::<2> {
words: [0xFF, 0xFF],
};
assert_eq!(b.popcount(), 16);
}
#[test]
fn test_from_to_bytes_roundtrip() {
let original = Fingerprint::<4> {
words: [0xDEAD_BEEF, 0xCAFE_BABE, 0x1234_5678, 0x9ABC_DEF0],
};
let bytes = original.to_bytes();
assert_eq!(bytes.len(), 32);
let restored = Fingerprint::<4>::from_bytes(&bytes);
assert_eq!(original, restored);
}
#[test]
fn test_similarity() {
let a = Fingerprint::<2>::zero();
let b = Fingerprint::<2>::zero();
assert!((a.similarity(&b).unwrap() - 1.0).abs() < f32::EPSILON);
let c = Fingerprint::<2>::ones();
assert!((a.similarity(&c).unwrap() - 0.0).abs() < f32::EPSILON);
}
#[test]
fn test_2k_size() {
assert_eq!(Fingerprint2K::BYTES, 2048);
assert_eq!(Fingerprint2K::BITS, 16384);
}
#[test]
fn test_xor_assign() {
let a = Fingerprint::<2> {
words: [0xFF, 0x00],
};
let b = Fingerprint::<2> {
words: [0x0F, 0xF0],
};
let mut c = a.clone();
c ^= &b;
assert_eq!(c, &a ^ &b);
}
#[test]
fn test_as_bytes_roundtrip() {
let fp = Fingerprint::<4> {
words: [0xDEAD_BEEF, 0xCAFE_BABE, 0x1234_5678, 0x9ABC_DEF0],
};
let bytes = fp.as_bytes();
assert_eq!(bytes.len(), 32);
let restored = Fingerprint::<4>::from_bytes(bytes);
assert_eq!(fp, restored);
}
#[test]
fn test_as_bytes_zero_copy() {
let fp = Fingerprint::<4>::zero();
let bytes_ptr = fp.as_bytes().as_ptr();
let words_ptr = fp.words.as_ptr() as *const u8;
assert_eq!(bytes_ptr, words_ptr, "as_bytes must be zero-copy");
}
}