Skip to main content

Corpus

Struct Corpus 

Source
pub struct Corpus { /* private fields */ }
Expand description

A corpus of L2-normalised sparse non-negative vectors in CSR form, with dimensions relabelled to a global rank (decreasing max weight). Built once; joinable at any threshold.

Implementations§

Source§

impl Corpus

Source

pub fn len(&self) -> usize

Number of vectors.

Source

pub fn is_empty(&self) -> bool

True if the corpus has no vectors.

Source

pub fn from_token_docs<S: AsRef<str>>(docs: &[Vec<S>]) -> Corpus

Build a corpus from token documents — each document a list of string tokens — as TF-IDF sparse vectors: dim = a distinct token, weight = (token count in doc) × ln(n / df_token) (df = number of documents containing the token). This is the principled input for a Type-3 code-clone join (documents = functions, tokens = canonicalised lines) and the shape most callers actually have. A token appearing in every document gets idf = 0 (contributes nothing), as expected.

Source

pub fn from_rows(rows: &[Vec<(u32, f64)>]) -> Corpus

Build a corpus from raw (dim, weight) rows. Duplicate dims within a row are summed; each row is L2-normalised; dims are relabelled to a global rank by decreasing max weight. Weights are expected non-negative (the prefix-filter bound requires it — IDF weights satisfy this).

Examples found in repository?
examples/simjoin_pypi.rs (line 63)
53fn main() {
54    let path: String = arg(1, "perf-local/pypi-type3.simjoin.bin".to_string());
55    let t: f64 = arg(2, 0.8);
56    let reps: usize = arg(3, 3);
57
58    let rows = load(&path);
59    let n = rows.len();
60    let nnz: usize = rows.iter().map(Vec::len).sum();
61
62    let b0 = Instant::now();
63    let corpus = Corpus::from_rows(&rows);
64    let build_ms = b0.elapsed().as_secs_f64() * 1000.0;
65
66    #[cfg(feature = "profiling")]
67    if std::env::var("STATS").is_ok() {
68        let (ncand, survivors, pairs) = cosine_join_counts(&corpus, t);
69        eprintln!(
70            "STATS n={n} t={t} | candidates={ncand} survivors(cos_full)={survivors} pairs={pairs} \
71             | prune_pass={:.4} survivor_precision={:.3}",
72            survivors as f64 / ncand.max(1) as f64,
73            pairs as f64 / survivors.max(1) as f64,
74        );
75    }
76
77    let mut ms: Vec<f64> = Vec::with_capacity(reps);
78    let mut npairs = 0usize;
79    for _ in 0..reps {
80        let t0 = Instant::now();
81        let pairs = cosine_join(&corpus, t);
82        ms.push(t0.elapsed().as_secs_f64() * 1000.0);
83        npairs = pairs.len();
84        std::hint::black_box(&pairs);
85    }
86    ms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
87    eprintln!(
88        "pypi-type3 n={n} nnz_total={nnz} mean_nnz={:.1} t={t} | build={build_ms:.0}ms | \
89         join: min={:.1}ms median={:.1}ms | pairs={npairs}",
90        nnz as f64 / n as f64,
91        ms[0],
92        ms[reps / 2],
93    );
94}
More examples
Hide additional examples
examples/simjoin_bench.rs (line 83)
74fn main() {
75    let n: usize = arg(1, 100_000);
76    let nnz: usize = arg(2, 14);
77    let ndims: usize = arg(3, 20_000);
78    let t: f64 = arg(4, 0.7);
79    let reps: usize = arg(5, 3);
80
81    let rows = gen(n, nnz, ndims, 0x1234_5678_9abc_def1);
82    let build0 = Instant::now();
83    let corpus = Corpus::from_rows(&rows);
84    let build_ms = build0.elapsed().as_secs_f64() * 1000.0;
85
86    // Strategy diagnostic (profiling builds only): posting touches / candidates / pairs. The
87    // candidates-per-pair ratio decides whether to prune harder or speed the dot up.
88    #[cfg(feature = "profiling")]
89    if std::env::var("STATS").is_ok() {
90        let (ncand, survivors, pairs) = cosine_join_counts(&corpus, t);
91        eprintln!(
92            "STATS n={n} t={t} | candidates={ncand} survivors(cos_full)={survivors} pairs={pairs} \
93             | prune_pass={:.4} cos_full_saved={:.4} survivor_precision={:.3}",
94            survivors as f64 / ncand.max(1) as f64,
95            1.0 - survivors as f64 / ncand.max(1) as f64,
96            pairs as f64 / survivors.max(1) as f64,
97        );
98    }
99
100    let mut ms: Vec<f64> = Vec::with_capacity(reps);
101    let mut npairs = 0usize;
102    for _ in 0..reps {
103        let t0 = Instant::now();
104        let pairs = cosine_join(&corpus, t);
105        ms.push(t0.elapsed().as_secs_f64() * 1000.0);
106        npairs = pairs.len();
107        std::hint::black_box(&pairs);
108    }
109    ms.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
110    eprintln!(
111        "n={n} nnz={nnz} ndims={ndims} t={t} | build={build_ms:.0}ms | join: min={:.1}ms median={:.1}ms | pairs={npairs}",
112        ms[0],
113        ms[reps / 2],
114    );
115}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.