binaryheap #1

Merged
Ghost merged 2 commits from binaryheap into main 2023-05-01 13:44:06 +00:00
2 changed files with 76 additions and 41 deletions

67
sparse_vector/README.md Normal file
View File

@ -0,0 +1,67 @@
# Sparse Vector Implementations
This repository aims at comparing various implementations of sparse vectors.
## What is a sparse vector?
A sparse vector is a vector in which most of its elements are zero.
That makes is easier to store because the many zero elements must not be stored.
Though this comes a the cost that we may need to decide between memory saving and computation time.
## Implementations overview
* Hashmap
* Index Array
* Compressed Index Array
* Binary Heap
### Index Array
We can omit all zero elements by storing an index array alongside all non zero values. Each value will be associated with an index in from the index array. This model is only efficient in memory size when the amount of zero elements is at least 50%. Since I used `usize` to store the indices, which is equal to a `u64` in 64-bit architectures, The required memory is:
```
mem(N) = non_zero_elements * (8 Bytes + 8 Bytes)
```
One significant downside is the cost of finding each corresponding entry when performing calculations such as the dot product. For this I used a binary search which gives a nive speedup.
### Hashmap Implementation
This implementation uses a hashmap to associate a value with its corresponding index in the vectors column. In Theory this should be as efficient in memory size as the previous array index method.
But in comparision this method requires signifacantly more memory since a hashmap allocates more memory than it can fill in order to reduce collisions.
It has one significant benefit, that being speed in calculations. Looking up values in a hashmap is generally faster than performing a binary seach. Also inserting and deleting is an O(1) operation.
### Compressed Index Array
In order to reduce the size required to store the indices of each value we can compress them by only storing the relative offset to the previous value:
| Uncompressed Index | 0 | 7 | 13 | 33 | 45 | 47 | 48 | 57 | ... | 34567 |
| -------------------- | --- | --- | ---- | ---- | ---- | ---- | ---- | ---- | ----- | ------- |
| Compressed Index | 0 | 7 | 6 | 20 | 12 | 2 | 1 | 9 | ... | 23 |
This yields smaller values. Thus we can savely reduce the bandwidth of available bits to store.
In this implementation I reduced to size from 64 to 16 bit. This makes memory usage a lot smaller, but computation gets a lot heavier, since all values have to be decompressed on the fly. A possible improvement would be to cache uncompressed values. May be worth investigating futher.
### Binary Heap
The binary heap has the advantage of being fast with inserting, removing and looking up values.
We use indices again to sort the values of the vector into to binary heap.
## Comparision
The following values were achieved by using a randomly initialized vector with a length of 10^10 elements from which 2% were non zero. The dot product implementation was single threaded.
| Implementation | Size on Heap (GB) | Runtime of dot product (s) |
| :----------------------- | ------------------- | ---------------------------- |
| Naive | 80 | N/A |
| Index Array | 3.6 | 6.254261896 |
| Hashmap | 5.4 | 0.732189927 |
| Compressed Index Array | 2.0 | > 120 |
| Binary Heap | 1.3 | 2.089960966 |

View File

@ -1,10 +1,7 @@
use std::ops::{Add, Mul, Sub};
use std::thread;
use std::collections::BTreeMap;
use std::time::Instant;
use bytesize::ByteSize;
use futures::executor::block_on;
use rand::Rng;
use futures::future::{join_all};
use jemalloc_ctl::{stats, epoch};
#[global_allocator]
@ -12,8 +9,7 @@ static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
/// Only stores more efficiently when at least 50% of all elements are zeros
pub struct SparseVec {
values: Vec<f64>,
indices: Vec<usize>,
map: BTreeMap<usize, f64>
}
impl SparseVec {
@ -21,9 +17,8 @@ impl SparseVec {
pub fn dot(&self, other: &SparseVec) -> f64 {
let mut sum = 0.0;
for index in 0..other.indices.len() {
// exponential search for an element in the second vector to have the same index
sum += binary_search(self.indices[index], &other.indices, &other.values) * self.values[index];
for (k, v) in self.map.iter() {
sum += v * other.map.get(k).unwrap_or(&0.0);
}
sum
@ -32,49 +27,22 @@ impl SparseVec {
pub fn new(elements: usize, non_null: f64) -> Self {
let non_zero_elements = (elements as f64 * non_null) as usize;
let mut values = Vec::with_capacity(non_zero_elements);
let mut indices = Vec::with_capacity(non_zero_elements);
let mut map = BTreeMap::new();
let mut rng = rand::thread_rng();
for i in 0..non_zero_elements {
values.push(0.5);
let idx = i as f32 / non_zero_elements as f32 * (elements as f32 - 4.0) + rng.gen_range(0.0..3.0);
indices.push(idx as usize);
map.insert(idx as usize, 0.5);
}
Self {
values,
indices
map
}
}
}
#[inline]
fn binary_search(target: usize, indices: &[usize], values: &[f64]) -> f64 {
let mut range = 0..indices.len();
loop {
let mut median = (range.end - range.start) >> 1;
if median == 0 {
break;
}
median += range.start;
if indices[median] == target {
return values[median];
}
if indices[median] > target {
range.end = median;
} else {
range.start = median;
}
}
0.0
}
macro_rules! time {
($name:literal, $block:expr) => {{
let start = Instant::now();
@ -99,7 +67,7 @@ fn main() {
println!("Estimated size on heap: {}", ByteSize::b((non_zero_elements * heap_element_size) as u64));
println!("Size on stack: {} B", std::mem::size_of::<SparseVec>());
let mut vec: SparseVec;
let vec: SparseVec;
time!("Sparse vector creation", {
// generate a vector