1use serde::{Deserialize, Serialize};
5use std::borrow::Borrow;
6
7pub const DEFAULT_RHO_DENOM: usize = 256;
13
14const NUM_ENTANGLEMENTS: usize = 64;
20
21#[derive(Clone, Debug, Serialize, Deserialize)]
32pub struct EntangledHVec {
33 pub(crate) dim: usize,
34 pub(crate) indices: Vec<u32>,
36}
37
38impl EntangledHVec {
39 pub fn new_deterministic(dim: usize, seed: u64) -> Self {
44 let active_count = (dim / DEFAULT_RHO_DENOM).max(1);
45 let mut indices = Vec::with_capacity(active_count);
46
47 let per_group = active_count / NUM_ENTANGLEMENTS;
48 if per_group > 0 {
49 for e in 0..NUM_ENTANGLEMENTS {
50 let group_seed = hash_u64(seed, e as u64);
51 for p in 0..per_group {
52 let idx = hash_u64(group_seed, p as u64) % dim as u64;
53 indices.push(idx as u32);
54 }
55 }
56 } else {
57 for p in 0..active_count {
59 let idx = hash_u64(seed, p as u64) % dim as u64;
60 indices.push(idx as u32);
61 }
62 }
63
64 indices.sort_unstable();
65 indices.dedup();
66
67 backfill_collisions(&mut indices, active_count, dim, seed);
68
69 Self { dim, indices }
70 }
71
72 pub fn new_with_density(dim: usize, density_denom: usize, seed: u64) -> Self {
73 let active_count = (dim / density_denom.max(1)).max(1);
74 let mut indices = Vec::with_capacity(active_count);
75
76 for p in 0..active_count {
77 let idx = hash_u64(seed, p as u64) % dim as u64;
78 indices.push(idx as u32);
79 }
80
81 indices.sort_unstable();
82 indices.dedup();
83
84 backfill_collisions(&mut indices, active_count, dim, seed);
85
86 Self { dim, indices }
87 }
88
89 pub fn from_indices(indices: Vec<u32>, dim: usize) -> Self {
92 debug_assert!(
93 indices.windows(2).all(|w| w[0] < w[1]),
94 "from_indices: indices must be sorted and deduplicated"
95 );
96 debug_assert!(
97 indices.last().is_none_or(|&last| (last as usize) < dim),
98 "from_indices: indices must be within [0, dim)"
99 );
100 Self { dim, indices }
101 }
102
103 pub fn from_dense(dense: &[f32], target_dim: usize) -> Self {
106 let active_count = (target_dim / DEFAULT_RHO_DENOM).max(1);
107 if dense.is_empty() {
108 return Self {
109 dim: target_dim,
110 indices: Vec::new(),
111 };
112 }
113
114 let vals: Vec<f64> = dense.iter().map(|&v| f64::from(v)).collect();
123 let mut terms = vec![0.0f64; vals.len()];
124 let mut projections: Vec<(u32, f64)> = (0..target_dim.div_ceil(2))
125 .map(|i| {
126 let mut kept = 0usize;
127 for (j, &val) in vals.iter().enumerate() {
128 let r = hash_u64(i as u64, j as u64) % 6;
129 terms[kept] = if r == 5 { -val } else { val };
130 kept += usize::from((r == 0) | (r == 5));
131 }
132 let mut dot_product = 0.0f64;
133 for &t in &terms[..kept] {
134 dot_product += t;
135 }
136 let index = i * 2 + usize::from(dot_product < 0.0);
137 (
138 index.min(target_dim.saturating_sub(1)) as u32,
139 dot_product.abs(),
140 )
141 })
142 .collect();
143
144 if projections.len() > active_count {
145 projections.select_nth_unstable_by(active_count - 1, |a, b| {
146 b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)
147 });
148 projections.truncate(active_count);
149 }
150
151 let mut indices: Vec<u32> = projections.into_iter().map(|(idx, _)| idx).collect();
152 indices.sort_unstable();
153
154 Self {
155 dim: target_dim,
156 indices,
157 }
158 }
159
160 pub fn from_scalar(value: f64, min_val: f64, max_val: f64, target_dim: usize) -> Self {
170 let range = max_val - min_val;
171 let normalized = if range.abs() < f64::EPSILON {
172 0.5
173 } else {
174 ((value - min_val) / range).clamp(0.0, 1.0)
175 };
176 let active_count = (target_dim / DEFAULT_RHO_DENOM).max(1);
177
178 let max_offset = (target_dim - active_count) as f64;
179 let start_offset = (normalized * max_offset).round() as usize;
180
181 const PERM_PRIME: u64 = 0x9E3779B97F4A7C55;
185
186 let mut indices = Vec::with_capacity(active_count);
187 for i in 0..active_count {
188 let logical_idx = (start_offset + i) as u64;
189 let idx = (logical_idx.wrapping_mul(PERM_PRIME) % target_dim as u64) as u32;
190 indices.push(idx);
191 }
192
193 indices.sort_unstable();
194 indices.dedup();
196
197 Self {
198 dim: target_dim,
199 indices,
200 }
201 }
202
203 pub fn indices(&self) -> &[u32] {
205 &self.indices
206 }
207
208 pub fn to_deltas(&self) -> Vec<u32> {
211 if self.indices.is_empty() {
212 return Vec::new();
213 }
214 let mut deltas = Vec::with_capacity(self.indices.len());
215 deltas.push(self.indices[0]);
216 for i in 1..self.indices.len() {
217 deltas.push(self.indices[i] - self.indices[i - 1]);
218 }
219 deltas
220 }
221
222 pub fn from_deltas(deltas: &[u32], dim: usize) -> Self {
224 if deltas.is_empty() {
225 return Self {
226 dim,
227 indices: Vec::new(),
228 };
229 }
230 let mut indices = Vec::with_capacity(deltas.len());
231 let mut current: u32 = 0;
232 for &d in deltas {
233 current = match current.checked_add(d) {
234 Some(v) if (v as usize) < dim => v,
235 _ => break,
236 };
237 indices.push(current);
238 }
239 Self { dim, indices }
240 }
241
242 pub fn hamming(&self, other: &Self) -> u32 {
244 let intersection =
245 super::intersection::sparse_intersection_count(&self.indices, &other.indices);
246 (self.indices.len() + other.indices.len() - 2 * intersection) as u32
247 }
248
249 pub fn similarity(&self, other: &Self) -> f64 {
253 let intersection =
254 super::intersection::sparse_intersection_count(&self.indices, &other.indices);
255 let union = self.indices.len() + other.indices.len() - intersection;
256 if union == 0 {
257 return 1.0;
258 }
259 intersection as f64 / union as f64
260 }
261
262 pub fn bind(&self, other: &Self) -> Self {
265 let indices = sorted_symmetric_difference(&self.indices, &other.indices);
266 Self {
267 dim: self.dim,
268 indices,
269 }
270 }
271
272 pub fn permute(&self, shifts: usize) -> Self {
274 if self.dim == 0 {
275 return self.clone();
276 }
277 let dim = self.dim as u32;
278 let shift = (shifts % self.dim) as u32;
279 let mut indices: Vec<u32> = self
280 .indices
281 .iter()
282 .map(|&idx| (idx + shift) % dim)
283 .collect();
284 indices.sort_unstable();
285 Self {
286 dim: self.dim,
287 indices,
288 }
289 }
290
291 pub fn hash_permute(&self, seed: u64) -> Self {
301 if self.dim == 0 {
302 return self.clone();
303 }
304 let d = self.dim as u64;
305 let mut indices: Vec<u32> = self
306 .indices
307 .iter()
308 .map(|&idx| (hash_u64(idx as u64, seed) % d) as u32)
309 .collect();
310 indices.sort_unstable();
311 indices.dedup();
312 Self {
313 dim: self.dim,
314 indices,
315 }
316 }
317
318 pub fn bundle<V: Borrow<Self>>(vectors: &[V]) -> Self {
321 if vectors.is_empty() {
322 return Self {
323 dim: 0,
324 indices: Vec::new(),
325 };
326 }
327 let dim = vectors[0].borrow().dim;
328 let n = vectors.len();
329 let threshold = (n as u32).div_ceil(2);
330 let target_count = (dim / DEFAULT_RHO_DENOM).max(1);
331
332 if let Some(selected) = count_majority(vectors, dim, threshold) {
333 return Self::from_selected(selected, dim, target_count);
334 }
335
336 let mut all_indices: Vec<u32> = vectors
337 .iter()
338 .flat_map(|v| v.borrow().indices.iter().copied())
339 .collect();
340 all_indices.sort_unstable();
341
342 if all_indices.is_empty() {
343 return Self {
344 dim,
345 indices: Vec::new(),
346 };
347 }
348
349 let mut selected: Vec<(u32, u32)> = Vec::new();
350
351 let mut current = all_indices[0];
352 let mut count: u32 = 1;
353 for &idx in &all_indices[1..] {
354 if idx == current {
355 count += 1;
356 } else {
357 if count >= threshold {
358 selected.push((current, count));
359 }
360 current = idx;
361 count = 1;
362 }
363 }
364 if count >= threshold {
365 selected.push((current, count));
366 }
367 Self::from_selected(selected, dim, target_count)
368 }
369
370 pub(crate) fn from_selected(
374 mut selected: Vec<(u32, u32)>,
375 dim: usize,
376 target_count: usize,
377 ) -> Self {
378 if selected.len() > target_count {
379 selected.select_nth_unstable_by(target_count - 1, |a, b| b.1.cmp(&a.1));
380 selected.truncate(target_count);
381 }
382
383 let mut indices: Vec<u32> = selected.into_iter().map(|(idx, _)| idx).collect();
384 indices.sort_unstable();
385
386 Self { dim, indices }
387 }
388
389 pub fn bundle_bloom<V: Borrow<Self>>(vectors: &[V]) -> Self {
398 if vectors.is_empty() {
399 return Self {
400 dim: 0,
401 indices: Vec::new(),
402 };
403 }
404 let dim = vectors[0].borrow().dim;
405
406 let mut all_indices: Vec<u32> = vectors
407 .iter()
408 .flat_map(|v| v.borrow().indices.iter().copied())
409 .collect();
410 all_indices.sort_unstable();
411 all_indices.dedup();
412
413 Self {
414 dim,
415 indices: all_indices,
416 }
417 }
418
419 pub fn containment_similarity(&self, other: &Self) -> f64 {
425 if self.indices.is_empty() {
426 return 1.0;
427 }
428 let intersection =
429 super::intersection::sparse_intersection_count(&self.indices, &other.indices);
430 intersection as f64 / self.indices.len() as f64
431 }
432
433 pub fn corrected_containment(&self, bloom_bundle: &Self) -> f64 {
440 let raw = self.containment_similarity(bloom_bundle);
441 let density = bloom_bundle.indices.len() as f64 / bloom_bundle.dim.max(1) as f64;
442 if density >= 1.0 - 1e-15 {
443 return 0.0;
444 }
445 ((raw - density) / (1.0 - density)).max(0.0)
446 }
447
448 pub fn bind_ordered(&self, other: &Self) -> Self {
454 self.permute(1).bind(other)
455 }
456
457 pub fn unbind_ordered_left(&self, other: &Self) -> Self {
460 let xored = self.bind(other);
461 xored.permute(self.dim - 1)
462 }
463
464 pub fn bundle_dp<V: Borrow<Self>>(vectors: &[V], epsilon: f64) -> Self {
467 let dim = vectors.first().map_or(0, |v| v.borrow().dim);
468 Self::bundle_dp_in_space(vectors, epsilon, dim)
469 }
470
471 pub(crate) fn dp_scale(dim: usize, epsilon: f64) -> Option<f64> {
472 let scale = (dim / DEFAULT_RHO_DENOM).max(1) as f64 / epsilon;
473 (epsilon.is_finite() && epsilon > 0.0 && scale > 0.0 && scale <= f64::MAX / 64.0)
475 .then_some(scale)
476 }
477
478 pub(crate) fn bundle_dp_in_space<V: Borrow<Self>>(
479 vectors: &[V],
480 epsilon: f64,
481 dim: usize,
482 ) -> Self {
483 assert!(
484 epsilon.is_finite() && epsilon > 0.0,
485 "epsilon must be finite and positive"
486 );
487 assert!(
488 vectors.iter().all(|v| v.borrow().dim == dim),
489 "bundle dimensions must match"
490 );
491 if dim == 0 {
492 return Self::from_indices(Vec::new(), 0);
493 }
494 let scale =
495 Self::dp_scale(dim, epsilon).expect("epsilon is outside the supported numeric range");
496 let contribution_limit = (dim / DEFAULT_RHO_DENOM).max(1);
497 let mut counts = vec![0.0; dim];
498 for vector in vectors {
499 for &index in vector.borrow().indices.iter().take(contribution_limit) {
500 counts[index as usize] += 1.0;
501 }
502 }
503 use rand::SeedableRng;
504 let mut rng = rand::rngs::StdRng::try_from_rng(&mut rand::rngs::SysRng)
505 .expect("operating system randomness unavailable");
506 let mut scores: Vec<(u32, f64)> = counts
507 .into_iter()
508 .enumerate()
509 .map(|(i, count)| (i as u32, count + laplace_sample(&mut rng, scale)))
510 .collect();
511 scores.select_nth_unstable_by(contribution_limit - 1, |a, b| {
512 b.1.total_cmp(&a.1).then(a.0.cmp(&b.0))
513 });
514 scores.truncate(contribution_limit);
515 let mut indices: Vec<u32> = scores.into_iter().map(|(index, _)| index).collect();
516 indices.sort_unstable();
517 Self::from_indices(indices, dim)
518 }
519}
520
521const BUNDLE_COUNTING_MAX_DIM: usize = 1 << 16;
524
525thread_local! {
526 static BUNDLE_COUNTS: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) };
528}
529
530fn count_majority<V: Borrow<EntangledHVec>>(
535 vectors: &[V],
536 dim: usize,
537 threshold: u32,
538) -> Option<Vec<(u32, u32)>> {
539 if dim > BUNDLE_COUNTING_MAX_DIM {
540 return None;
541 }
542 let mut total = 0usize;
543 for v in vectors {
544 let indices = &v.borrow().indices;
545 if indices.iter().any(|&idx| idx as usize >= dim) {
548 return None;
549 }
550 total += indices.len();
551 }
552 BUNDLE_COUNTS.with(|counts| {
553 let mut counts = counts.borrow_mut();
554 if counts.len() < dim {
555 counts.resize(dim, 0);
556 }
557 let counts = &mut counts[..dim];
558 debug_assert!(counts.iter().all(|&c| c == 0));
559 for v in vectors {
560 for &idx in &v.borrow().indices {
561 counts[idx as usize] += 1;
562 }
563 }
564 let mut selected = Vec::new();
565 if total < dim {
566 for v in vectors {
569 for &idx in &v.borrow().indices {
570 let n = std::mem::take(&mut counts[idx as usize]);
571 if n >= threshold {
572 selected.push((idx, n));
573 }
574 }
575 }
576 selected.sort_unstable_by_key(|&(idx, _)| idx);
577 } else {
578 for (idx, slot) in counts.iter_mut().enumerate() {
579 let n = std::mem::take(slot);
580 if n >= threshold {
581 selected.push((idx as u32, n));
582 }
583 }
584 }
585 Some(selected)
586 })
587}
588
589fn laplace_sample(rng: &mut impl rand::RngExt, scale: f64) -> f64 {
591 let u = loop {
592 let sample = rng.random::<f64>() - 0.5;
593 if sample.abs() < 0.5 {
594 break sample;
595 }
596 };
597 -scale * u.signum() * (1.0 - 2.0 * u.abs()).ln()
598}
599
600fn backfill_collisions(indices: &mut Vec<u32>, active_count: usize, dim: usize, seed: u64) {
604 let mut counter = 0u64;
605 while indices.len() < active_count && (counter as usize) < active_count * 10 {
606 let idx = (hash_u64(seed.wrapping_add(0xDEAD), counter) % dim as u64) as u32;
607 counter += 1;
608 if let Err(pos) = indices.binary_search(&idx) {
609 indices.insert(pos, idx);
610 }
611 }
612}
613
614pub fn hash_u64(a: u64, b: u64) -> u64 {
618 let mut z = a.wrapping_mul(0x9E3779B97F4A7C15).wrapping_add(b);
619 z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
620 z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);
621 z ^ (z >> 31)
622}
623
624pub(crate) fn sorted_symmetric_difference(a: &[u32], b: &[u32]) -> Vec<u32> {
626 let mut result = Vec::with_capacity(a.len() + b.len());
627 let mut i = 0;
628 let mut j = 0;
629 while i < a.len() && j < b.len() {
630 match a[i].cmp(&b[j]) {
631 std::cmp::Ordering::Less => {
632 result.push(a[i]);
633 i += 1;
634 }
635 std::cmp::Ordering::Greater => {
636 result.push(b[j]);
637 j += 1;
638 }
639 std::cmp::Ordering::Equal => {
640 i += 1;
641 j += 1;
642 }
643 }
644 }
645 result.extend_from_slice(&a[i..]);
646 result.extend_from_slice(&b[j..]);
647 result
648}
649
650pub(crate) fn sorted_symmetric_difference_count(a: &[u32], b: &[u32]) -> usize {
652 let mut count = 0;
653 let mut i = 0;
654 let mut j = 0;
655 while i < a.len() && j < b.len() {
656 match a[i].cmp(&b[j]) {
657 std::cmp::Ordering::Less => {
658 count += 1;
659 i += 1;
660 }
661 std::cmp::Ordering::Greater => {
662 count += 1;
663 j += 1;
664 }
665 std::cmp::Ordering::Equal => {
666 i += 1;
667 j += 1;
668 }
669 }
670 }
671 count += a.len() - i;
672 count += b.len() - j;
673 count
674}
675
676#[cfg(test)]
677mod tests {
678 use super::*;
679
680 #[test]
681 fn self_similarity_and_containment_are_one() {
682 let v = EntangledHVec::new_deterministic(16384, 42);
683 assert!(
684 (v.similarity(&v) - 1.0).abs() < 0.0001,
685 "Self-similarity should be 1.0"
686 );
687 assert!(
688 (v.containment_similarity(&v) - 1.0).abs() < 0.0001,
689 "Self-containment should be 1.0"
690 );
691 }
692
693 #[test]
694 fn test_entangled_random_pair_distance() {
695 let a = EntangledHVec::new_deterministic(16384, 1);
696 let b = EntangledHVec::new_deterministic(16384, 2);
697 let sim = a.similarity(&b);
698 assert!(
699 sim < 0.05,
700 "Random sparse pair Jaccard {:.4} should be near 0",
701 sim
702 );
703 }
704
705 #[test]
706 fn test_entangled_bind_involution() {
707 let a = EntangledHVec::new_deterministic(16384, 1);
708 let b = EntangledHVec::new_deterministic(16384, 2);
709 let ab = a.bind(&b);
710 let recovered = ab.bind(&b);
711 assert_eq!(recovered.indices, a.indices);
712 }
713
714 #[test]
715 fn test_entangled_bundle_majority() {
716 let dim = 16384;
717 let base = EntangledHVec::new_deterministic(dim, 100);
718 let mut vecs = vec![base.clone(); 5];
719 vecs.push(EntangledHVec::new_deterministic(dim, 200));
720 vecs.push(EntangledHVec::new_deterministic(dim, 300));
721 let bundled = EntangledHVec::bundle(&vecs);
722 let sim_base = bundled.similarity(&base);
723 let sim_random = bundled.similarity(&EntangledHVec::new_deterministic(dim, 400));
724 assert!(
725 sim_base > sim_random,
726 "Bundle should be closer to majority element"
727 );
728 }
729
730 #[test]
731 fn test_from_dense_produces_sparse() {
732 let dense: Vec<f32> = (0..128).map(|i| (i as f32 - 64.0) / 64.0).collect();
733 let e = EntangledHVec::from_dense(&dense, 10000);
734 assert_eq!(e.dim, 10000);
735 let expected = 10000 / 256;
736 assert_eq!(e.indices.len(), expected);
737 }
738
739 #[test]
740 #[should_panic(expected = "epsilon is outside the supported numeric range")]
741 fn dp_rejects_finite_scales_whose_inverse_cdf_can_overflow() {
742 let vectors = [EntangledHVec::from_indices(vec![1], 256)];
743 EntangledHVec::bundle_dp(&vectors, 1e-308);
744 }
745
746 #[test]
747 fn test_bundle_dp_high_epsilon_is_valid_and_matches_deterministic() {
748 let dim = 16384;
749 let base = EntangledHVec::new_deterministic(dim, 100);
750 let vecs = vec![base.clone(); 7];
751 let det = EntangledHVec::bundle(&vecs);
752 let dp = EntangledHVec::bundle_dp(&vecs, 1000.0);
753 assert_eq!(dp.dim, dim);
754 assert!(!dp.indices.is_empty());
755 assert!(dp.indices.windows(2).all(|w| w[0] < w[1]));
756 let sim = det.similarity(&dp);
757 assert!(
758 sim > 0.8,
759 "High-epsilon DP bundle should closely match deterministic: {:.4}",
760 sim
761 );
762 }
763
764 #[test]
765 fn test_bundle_dp_low_epsilon_adds_noise() {
766 let dim = 16384;
767 let base = EntangledHVec::new_deterministic(dim, 100);
768 let noise = EntangledHVec::new_deterministic(dim, 200);
769 let vecs = vec![base.clone(), base.clone(), base.clone(), noise];
770 let det = EntangledHVec::bundle(&vecs);
771 let mut diffs = 0;
772 for _ in 0..5 {
773 let dp = EntangledHVec::bundle_dp(&vecs, 0.1);
774 if dp.indices != det.indices {
775 diffs += 1;
776 }
777 }
778 assert!(diffs > 0, "Low-epsilon DP should produce varied outputs");
779 }
780
781 #[test]
782 fn test_bloom_bundle_capacity() {
783 let dim = 16384;
784 let vecs: Vec<EntangledHVec> = (0..200)
785 .map(|i| EntangledHVec::new_deterministic(dim, i * 100))
786 .collect();
787 let bundle = EntangledHVec::bundle_bloom(&vecs);
788 assert_eq!(bundle.dim, dim);
789 for (i, v) in vecs.iter().enumerate() {
790 let sim = v.containment_similarity(&bundle);
791 assert!(
792 sim > 0.9,
793 "Item {} containment in bundle of 200 should be >0.9, got {:.4}",
794 i,
795 sim
796 );
797 }
798 let noise = EntangledHVec::new_deterministic(dim, 999999);
799 let noise_sim = noise.containment_similarity(&bundle);
800 assert!(
801 noise_sim < 0.9,
802 "Non-member containment should be low, got {:.4}",
803 noise_sim
804 );
805 }
806
807 #[test]
808 fn test_bind_ordered_is_non_commutative_and_invertible() {
809 let a = EntangledHVec::new_deterministic(16384, 1);
810 let b = EntangledHVec::new_deterministic(16384, 2);
811 let ab = a.bind_ordered(&b);
812 let ba = b.bind_ordered(&a);
813 assert_ne!(
814 ab.indices, ba.indices,
815 "bind_ordered must be non-commutative"
816 );
817 let recovered = ab.unbind_ordered_left(&b);
818 assert_eq!(
819 recovered.indices, a.indices,
820 "unbind_ordered_left should recover A"
821 );
822 }
823
824 #[test]
825 fn test_from_scalar_locality() {
826 let dim = 16384;
827 let base_val = 0.5;
828 let v_base = EntangledHVec::from_scalar(base_val, 0.0, 1.0, dim);
829 assert_eq!(v_base.dim, dim);
830 assert!(!v_base.indices.is_empty());
831
832 let mut prev_sim = 1.0;
833 for i in 1..20 {
834 let offset = i as f64 * 0.02;
835 let v_curr = EntangledHVec::from_scalar(base_val + offset, 0.0, 1.0, dim);
836 let sim = v_base.similarity(&v_curr);
837
838 assert!(
839 sim <= prev_sim,
840 "Monotonicity violation at offset {}: sim={:.4} was prev={:.4}",
841 offset,
842 sim,
843 prev_sim
844 );
845 prev_sim = sim;
846 }
847 }
848
849 fn from_dense_reference(dense: &[f32], target_dim: usize) -> EntangledHVec {
851 let active_count = (target_dim / DEFAULT_RHO_DENOM).max(1);
852 if dense.is_empty() {
853 return EntangledHVec {
854 dim: target_dim,
855 indices: Vec::new(),
856 };
857 }
858 let mut projections: Vec<(u32, f64)> = (0..target_dim.div_ceil(2))
859 .map(|i| {
860 let mut dot_product = 0.0f64;
861 for (j, &val) in dense.iter().enumerate() {
862 let r = hash_u64(i as u64, j as u64) % 6;
863 if r == 0 {
864 dot_product += val as f64;
865 } else if r == 5 {
866 dot_product -= val as f64;
867 }
868 }
869 let index = i * 2 + usize::from(dot_product < 0.0);
870 (
871 index.min(target_dim.saturating_sub(1)) as u32,
872 dot_product.abs(),
873 )
874 })
875 .collect();
876 if projections.len() > active_count {
877 projections.select_nth_unstable_by(active_count - 1, |a, b| {
878 b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)
879 });
880 projections.truncate(active_count);
881 }
882 let mut indices: Vec<u32> = projections.into_iter().map(|(idx, _)| idx).collect();
883 indices.sort_unstable();
884 EntangledHVec {
885 dim: target_dim,
886 indices,
887 }
888 }
889
890 fn bundle_reference(vectors: &[EntangledHVec]) -> Vec<u32> {
892 let dim = vectors[0].dim;
893 let threshold = (vectors.len() as u32).div_ceil(2);
894 let mut all: Vec<u32> = vectors
895 .iter()
896 .flat_map(|v| v.indices.iter().copied())
897 .collect();
898 all.sort_unstable();
899 let mut selected: Vec<(u32, u32)> = Vec::new();
900 for run in all.chunk_by(|a, b| a == b) {
901 if run.len() as u32 >= threshold {
902 selected.push((run[0], run.len() as u32));
903 }
904 }
905 let target = (dim / DEFAULT_RHO_DENOM).max(1);
906 if selected.len() > target {
907 selected.select_nth_unstable_by(target - 1, |a, b| b.1.cmp(&a.1));
908 selected.truncate(target);
909 }
910 let mut indices: Vec<u32> = selected.into_iter().map(|(i, _)| i).collect();
911 indices.sort_unstable();
912 indices
913 }
914
915 #[test]
916 fn bundle_matches_sorting_reference() {
917 for dim in [1usize, 2, 255, 256, 257, 1024, 16384, 65535, 65536, 65537] {
920 for n in [1usize, 2, 3, 4, 7, 10, 64] {
921 for overlap in [0u64, 3] {
922 let vectors: Vec<EntangledHVec> = (0..n as u64)
923 .map(|i| {
924 let seed = if overlap > 0 { i % overlap } else { i };
925 EntangledHVec::new_with_density(dim, 16, seed * 7919 + dim as u64)
926 })
927 .collect();
928 assert_eq!(
929 EntangledHVec::bundle(&vectors).indices,
930 bundle_reference(&vectors),
931 "dim {dim} n {n} overlap {overlap}"
932 );
933 }
934 }
935 }
936 let bad = vec![
938 EntangledHVec {
939 dim: 8,
940 indices: vec![1, 9],
941 },
942 EntangledHVec {
943 dim: 8,
944 indices: vec![1, 9],
945 },
946 ];
947 assert_eq!(EntangledHVec::bundle(&bad).indices, bundle_reference(&bad));
948 }
949
950 #[test]
951 fn from_dense_matches_reference() {
952 let mut state = 0x1234_5678_9ABC_DEF0u64;
953 let mut next = move || {
954 state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
955 hash_u64(state, 0)
956 };
957 let unit = |x: u64| (x >> 11) as f64 / (1u64 << 53) as f64;
958 let mut cases = 0usize;
959 for emb in [64usize, 384, 768, 1536] {
960 for (d, n) in [(4096usize, 100usize), (16384, 30), (65536, 3)] {
961 for k in 0..n {
962 let v: Vec<f32> = (0..emb)
963 .map(|_| {
964 let r = next();
965 match k % 6 {
966 0 | 1 => (unit(r) * 2.0 - 1.0) as f32,
967 2 if k < 6 => 0.0,
968 2 | 3 => (r % 3) as f32 - 1.0,
969 4 => 0.5,
970 _ => match r % 5 {
971 0 => f32::MAX,
972 1 => f32::MIN,
973 2 => f32::MIN_POSITIVE / 4.0,
974 3 => -0.0,
975 _ => 0.0,
976 },
977 }
978 })
979 .collect();
980 let got = EntangledHVec::from_dense(&v, d);
981 let want = from_dense_reference(&v, d);
982 assert_eq!(got.dim, want.dim);
983 assert_eq!(got.indices, want.indices, "emb={emb} D={d} case={k}");
984 cases += 1;
985 }
986 }
987 }
988 assert!(cases >= 500);
989 }
990}