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
use crate::{
dist::l2_norm, multi_probe::QueryDirectedProbe, utils::create_rng, DataPointSlice, FloatSize,
};
use ndarray::prelude::*;
use ndarray_rand::rand_distr::{StandardNormal, Uniform};
use ndarray_rand::RandomExt;
use serde::{Deserialize, Serialize};
pub type HashPrimitive = i8;
pub type Hash = Vec<HashPrimitive>;
pub trait VecHash {
fn hash_vec_query(&self, v: &[f32]) -> Hash;
fn hash_vec_put(&self, v: &[f32]) -> Hash;
fn as_query_directed_probe(&self) -> Option<&dyn QueryDirectedProbe> {
None
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct SignRandomProjections {
hyperplanes: Array2<f32>,
}
impl SignRandomProjections {
pub fn new(k: usize, dim: usize, seed: u64) -> SignRandomProjections {
let mut rng = create_rng(seed);
let hp = Array::random_using((dim, k), StandardNormal, &mut rng);
SignRandomProjections { hyperplanes: hp }
}
fn hash_vec(&self, v: &[f32]) -> Hash {
let mut hash: Hash = vec![0; self.hyperplanes.len_of(Axis(1))];
let v = aview1(v);
for (i, ai) in self.hyperplanes.t().dot(&v).iter().enumerate() {
if ai > &0.0 {
hash[i] = 1
}
}
hash.into_iter().collect()
}
}
impl VecHash for SignRandomProjections {
fn hash_vec_query(&self, v: &[f32]) -> Hash {
self.hash_vec(v)
}
fn hash_vec_put(&self, v: &[f32]) -> Hash {
self.hash_vec(v)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct L2 {
pub a: Array2<f32>,
pub r: f32,
pub b: Array1<f32>,
n_projections: usize,
}
impl L2 {
pub fn new(dim: usize, r: f32, n_projections: usize, seed: u64) -> L2 {
let mut rng = create_rng(seed);
let a = Array::random_using((n_projections, dim), StandardNormal, &mut rng);
let uniform_dist = Uniform::new(0., r);
let b = Array::random_using(n_projections, uniform_dist, &mut rng);
L2 {
a,
r,
b,
n_projections,
}
}
pub(crate) fn hash_vec(&self, v: &DataPointSlice) -> Array1<FloatSize> {
((self.a.dot(&aview1(v)) + &self.b) / self.r).mapv(|x| x.floor())
}
fn hash_and_cast_vec(&self, v: &[f32]) -> Hash {
((self.a.dot(&aview1(v)) + &self.b) / self.r)
.mapv(|x| x.floor() as HashPrimitive)
.to_vec()
}
}
impl VecHash for L2 {
fn hash_vec_query(&self, v: &[f32]) -> Hash {
self.hash_and_cast_vec(v)
}
fn hash_vec_put(&self, v: &[f32]) -> Hash {
self.hash_and_cast_vec(v)
}
fn as_query_directed_probe(&self) -> Option<&dyn QueryDirectedProbe> {
Some(self)
}
}
#[derive(Serialize, Deserialize, Clone)]
pub struct MIPS {
U: f32,
M: f32,
m: usize,
dim: usize,
hasher: L2,
}
impl MIPS {
pub fn new(dim: usize, r: f32, U: f32, m: usize, n_projections: usize, seed: u64) -> MIPS {
let l2 = L2::new(dim + m, r, n_projections, seed);
MIPS {
U,
M: 0.,
m,
dim,
hasher: l2,
}
}
pub fn fit(&mut self, v: &[f32]) {
let mut max_l2 = 0.;
for x in v.chunks(self.dim) {
let l2 = l2_norm(x);
if l2 > max_l2 {
max_l2 = l2
}
}
self.M = max_l2
}
pub fn tranform_put(&self, x: &[f32]) -> Vec<f32> {
let mut x_new = Vec::with_capacity(x.len() + self.m);
if self.M == 0. {
panic!("MIPS is not fitted")
}
for x_i in x {
x_new.push(x_i / self.M * self.U)
}
let norm_sq = l2_norm(&x_new).powf(2.);
for i in 1..(self.m + 1) {
x_new.push(norm_sq.powf(i as f32))
}
x_new
}
pub fn transform_query(&self, x: &[f32]) -> Vec<f32> {
let mut x_new = Vec::with_capacity(x.len() + self.m);
let l2 = l2_norm(x);
for x_i in x {
x_new.push(x_i / l2)
}
for _ in 0..self.m {
x_new.push(0.5)
}
x_new
}
}
impl VecHash for MIPS {
fn hash_vec_query(&self, v: &[f32]) -> Hash {
let q = self.transform_query(v);
self.hasher.hash_vec_query(&q)
}
fn hash_vec_put(&self, v: &[f32]) -> Hash {
let p = self.tranform_put(v);
self.hasher.hash_vec_query(&p)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_l2() {
let l2 = L2::new(5, 2.2, 7, 1);
let h1 = l2.hash_vec_query(&[1., 2., 3., 1., 3.]);
let h2 = l2.hash_vec_query(&[1.1, 2., 3., 1., 3.1]);
let h3 = l2.hash_vec_query(&[100., 100., 100., 100., 100.1]);
println!("close: {:?} distant: {:?}", (&h1, &h2), &h3);
assert_eq!(h1, h2);
assert_ne!(h1, h3);
}
}