Spaces:
Build error
Build error
File size: 4,104 Bytes
0ca462b | 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 | #![allow(dead_code)]
//! Utility functions for IntentForge v2
/// Binary quantization for vectors
/// Converts f32 vector to binary representation (1 bit per dimension)
pub fn binary_quantize(vector: &[f32]) -> Vec<u8> {
let num_bytes = vector.len().div_ceil(8);
let mut bytes = vec![0u8; num_bytes];
for (i, &val) in vector.iter().enumerate() {
if val > 0.0 {
bytes[i / 8] |= 1 << (i % 8);
}
}
bytes
}
/// Convert binary quantized vector back to approximate f32
pub fn binary_dequantize(bytes: &[u8], original_dim: usize) -> Vec<f32> {
let mut vector = Vec::with_capacity(original_dim);
for i in 0..original_dim {
let byte = bytes.get(i / 8).copied().unwrap_or(0);
let bit = (byte >> (i % 8)) & 1;
vector.push(if bit == 1 { 1.0 } else { -1.0 });
}
vector
}
/// Compute cosine similarity between two vectors
pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
if a.len() != b.len() {
return 0.0;
}
let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm_a == 0.0 || norm_b == 0.0 {
return 0.0;
}
dot / (norm_a * norm_b)
}
/// Compute Hamming distance between two byte slices
pub fn hamming_distance(a: &[u8], b: &[u8]) -> usize {
a.iter()
.zip(b.iter())
.map(|(&x, &y)| (x ^ y).count_ones() as usize)
.sum()
}
/// Compute SimHash for text (64-bit) using k-shingling
pub fn compute_simhash(text: &str) -> u64 {
let shingles = generate_shingles(text, 3);
let mut bit_counts = [0i32; 64];
for shingle in &shingles {
let hash = hash_shingle(shingle);
for bit in 0..64u32 {
if (hash >> bit) & 1 == 1 {
bit_counts[bit as usize] += 1;
} else {
bit_counts[bit as usize] -= 1;
}
}
}
let mut simhash: u64 = 0;
for bit in 0..64u32 {
if bit_counts[bit as usize] > 0 {
simhash |= 1u64 << bit;
}
}
simhash
}
/// Generate character-level k-shingles from text
fn generate_shingles(text: &str, k: usize) -> Vec<String> {
let normalized: String = text
.to_lowercase()
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
if normalized.len() < k {
return vec![normalized];
}
normalized
.as_bytes()
.windows(k)
.map(|w| String::from_utf8_lossy(w).to_string())
.collect()
}
/// Hash a shingle string to u64
fn hash_shingle(s: &str) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
s.hash(&mut hasher);
hasher.finish()
}
/// Compute SimHash Hamming distance between two u64 values
pub fn simhash_distance(a: u64, b: u64) -> u32 {
(a ^ b).count_ones()
}
/// Normalize a vector to unit length
pub fn normalize(vector: &[f32]) -> Vec<f32> {
let norm: f32 = vector.iter().map(|x| x * x).sum::<f32>().sqrt();
if norm == 0.0 {
return vector.to_vec();
}
vector.iter().map(|&x| x / norm).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_binary_quantize() {
let vector = vec![0.5, -0.3, 0.8, -0.1, 0.2];
let quantized = binary_quantize(&vector);
assert_eq!(quantized.len(), 1);
// First 3 bits should be 1, 0, 1 (positive, negative, positive)
assert_eq!(quantized[0] & 0b00000101, 0b00000101);
}
#[test]
fn test_cosine_similarity() {
let a = vec![1.0, 0.0, 0.0];
let b = vec![1.0, 0.0, 0.0];
let sim = cosine_similarity(&a, &b);
assert!((sim - 1.0).abs() < 1e-6);
}
#[test]
fn test_normalize() {
let vector = vec![3.0, 4.0];
let normalized = normalize(&vector);
let norm: f32 = normalized.iter().map(|x| x * x).sum::<f32>().sqrt();
assert!((norm - 1.0).abs() < 1e-6);
}
}
|