intentforge / src /utils /mod.rs
Likhith Sai Seemala
Deploy IntentForge v2 to HF Spaces
0ca462b
Raw History Blame
4.1 kB
#![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);
}
}