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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
// SPDX-License-Identifier: Apache-2.0
use crate::dataset::Dataset;
use crate::ftype::FileType;
use crate::hash::{FxBuildHasher, FxHashMap, hash_bytes};
use crate::{Bytes, MAX_RECURSION_DEPTH};
use std::fs::File;
use std::io::{self, BufRead, BufReader, Lines, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::model::LogisticRegression;
use anyhow::{Result, anyhow, bail, ensure};
use dashmap::DashMap;
use rayon::prelude::*;
use walkdir::WalkDir;
/// Largest chunk read when walking a file's n-gram windows.
///
/// The buffer is sized to the file when the file is smaller. Reading 4 KiB at a time, as this
/// used to, costs a syscall per 4 KiB — millions of them over a large corpus.
pub(crate) const WINDOW_BUFFER_SIZE: u32 = 1 << 20;
/// Visit every `n`-byte window of a file, in order.
///
/// Reads in large chunks, carrying the last `n - 1` bytes of each chunk forward so the windows
/// straddling a chunk boundary are still seen. The three copies of this logic that preceded it
/// each read 4 KiB at a time and re-seeked backwards to overlap the chunks, costing three
/// syscalls per 4 KiB, and two of them dropped the final window of the file.
///
/// # Errors
///
/// Returns an error if the file can't be read, or if `visit` fails.
pub(crate) fn for_each_window<F>(path: &Path, n: u16, mut visit: F) -> Result<()>
where
F: FnMut(&[u8]) -> Result<()>,
{
ensure!(n > 0, "N-gram size must be greater than zero.");
let file_size = path.metadata()?.len();
if file_size < u64::from(n) {
// Nothing to look at: the file is shorter than one window.
return Ok(());
}
let n_usize = n as usize;
let capacity = usize::try_from(file_size)
.unwrap_or(WINDOW_BUFFER_SIZE as usize)
.min(WINDOW_BUFFER_SIZE as usize)
.max(n_usize);
let mut buffer = vec![0u8; capacity];
let mut reader = BufReader::with_capacity(capacity, File::open(path)?);
let mut filled = 0usize;
loop {
let read = reader.read(&mut buffer[filled..])?;
if read == 0 {
break;
}
filled += read;
if filled < n_usize {
continue;
}
for window in buffer[..filled].windows(n_usize) {
visit(window)?;
}
// Keep the tail that could still begin a window spanning into the next chunk.
let carry = n_usize - 1;
buffer.copy_within(filled - carry..filled, 0);
filled = carry;
}
Ok(())
}
// The output is wrapped in a Result to allow matching on errors.
// Returns an Iterator to the Reader of the lines of the file.
// https://doc.rust-lang.org/rust-by-example/std_misc/file/read_lines.html
fn read_lines<P: AsRef<Path>>(filename: P) -> io::Result<Lines<BufReader<File>>> {
let file = File::open(filename)?;
Ok(BufReader::new(file).lines())
}
pub(crate) fn stride_from_line(line: &str) -> Result<u16> {
line.split(':')
.nth(1)
.ok_or_else(|| anyhow!("Invalid stride"))?
.trim()
.parse()
.map_err(Into::into)
}
/// N-grams as read from a file
#[derive(Clone)]
pub struct NgramsFile {
/// N-grams and their index position
///
/// Keyed with [`crate::hash::FxHasher`]: this map is probed once per byte of every sample
/// during featurization, where SipHash costs more than the lookup itself.
pub ngrams: FxHashMap<Bytes, usize>,
/// File type represented by the n-grams
pub ftype: FileType,
/// Convenience: keep track of the size of the n-grams (value of `n`)
pub n: u16,
/// Stride
pub s: u16,
}
impl NgramsFile {
/// Load the n-grams from an existing model or from a plain text file.
///
/// # Errors
///
/// An error results if:
/// * The file cannot be read
/// * The file type is not specified
/// * The n-grams aren't hexidecimal
/// * The n-grams are different sizes
pub fn load<P: AsRef<Path>>(ngrams_file: P) -> Result<Self> {
if let Ok(model) = LogisticRegression::load(ngrams_file.as_ref()) {
return Ok(model.into());
}
let mut file_type = FileType::NotSet;
let mut n = 0;
let mut s = 0;
let mut ngrams = FxHashMap::default();
let lines = read_lines(&ngrams_file)?;
let mut ngram_counter = 0;
let mut line_counter = 0u32;
for line in lines.map_while(Result::ok) {
if line.starts_with("# File type:") {
if let Ok(ftype) = Dataset::file_type_from_line(&line) {
file_type = ftype;
}
line_counter += 1;
continue;
}
if line.starts_with("# Stride:") {
s = stride_from_line(&line)?;
line_counter += 1;
continue;
}
// Ignore other metadata
if line.starts_with('#') {
line_counter += 1;
continue;
}
let line = if let Some(l) = line.split(',').next() {
l
} else {
&line
};
if !line.len().is_multiple_of(2) {
bail!("Line {line_counter} {line} has odd number of characters.");
}
if n == 0 {
n = u16::try_from(line.len())? / 2;
} else if u16::try_from(line.len())? / 2 != n {
bail!(
"Line {line_counter} {line} has unexpected length of {} bytes, expected {n}",
line.len() / 2
);
}
match hex::decode(line) {
Ok(ngram) => {
ngrams.insert(ngram, ngram_counter);
ngram_counter += 1;
}
Err(e) => bail!("Line {line_counter} has non-hexidecimal ngram {line}: {e}"),
}
line_counter += 1;
}
ensure!(
!ngrams.is_empty(),
"No n-grams read from {}.",
ngrams_file.as_ref().display()
);
ensure!(
file_type != FileType::NotSet,
"No file type specified in n-grams file."
);
Ok(Self {
ngrams,
ftype: file_type,
n,
s,
})
}
/// Convert the n-gram map into a vector, preserving their order
#[must_use]
pub fn into_vec(self) -> Vec<Bytes> {
let mut ngrams_vec = vec![Vec::new(); self.ngrams.len()];
for (ngram, index) in self.ngrams {
ngrams_vec[index] = ngram;
}
ngrams_vec
}
/// Borrow the n-grams in index order.
///
/// Unlike [`NgramsFile::into_vec`] this clones nothing, which matters when there are a
/// million of them: cloning the map to consume it costs tens of megabytes and as long as
/// writing the header it feeds.
#[must_use]
pub fn as_vec(&self) -> Vec<&Bytes> {
let mut ngrams_vec: Vec<&Bytes> = Vec::new();
ngrams_vec.resize(self.ngrams.len(), &EMPTY_NGRAM);
for (ngram, index) in &self.ngrams {
if let Some(slot) = ngrams_vec.get_mut(*index) {
*slot = ngram;
}
}
ngrams_vec
}
}
/// Placeholder for an index no n-gram claims, which [`NgramsFile::load`] never leaves behind.
static EMPTY_NGRAM: Bytes = Vec::new();
/// N-gramming object
pub struct Ngrammer {
/// Size of the byte sequence
pub(crate) n: u16,
/// Number of n-grams to keep
pub(crate) k: usize,
/// N-gram stride: roughly one n-gram in `s` is sampled
pub(crate) s: u16,
/// Largest hash an n-gram can have and still be sampled, `u64::MAX / s`
pub(crate) keep_below: u64,
/// File paths to be viewed
pub(crate) paths: Vec<PathBuf>,
/// Expected file type
pub(crate) ftype: FileType,
/// N-grams discovered, keyed with [`crate::hash::FxHasher`] like the rest of the n-gram maps
pub(crate) ngrams: DashMap<Bytes, usize, FxBuildHasher>,
}
impl Ngrammer {
/// The size of the array for storing hashes of found n-grams
#[cfg(not(feature = "low-memory"))]
pub const COUNTS: usize = 2_000_000;
/// The size of the array for storing hashes of found n-grams on low-memory systems
#[cfg(feature = "low-memory")]
pub const COUNTS: usize = 100_000;
/// Number of `u64` words needed for a bitset with one bit per [`Self::COUNTS`] bucket
const BITSET_WORDS: usize = Self::COUNTS.div_ceil(u64::BITS as usize);
/// The hash bucket of an n-gram, or `None` if the stride leaves it out.
///
/// The n-gram is sampled when its hash is in the lowest `1 / stride` of the range. The
/// survivors are then stretched back over the whole range and mapped onto [`Self::COUNTS`]
/// by multiply-shift, so every bucket is used whatever the stride. Choosing on
/// `bucket % stride` instead, as this used to, left all but one bucket in `stride` empty.
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn select_hash(hash: u64, stride: u16, keep_below: u64) -> Option<usize> {
if hash > keep_below {
return None;
}
// Cannot overflow: `hash <= u64::MAX / stride`.
let stretched = hash * u64::from(stride);
Some(((u128::from(stretched) * Self::COUNTS as u128) >> u64::BITS) as usize)
}
/// The hash bucket of an n-gram, or `None` if the stride leaves it out.
#[inline]
fn select(&self, window: &[u8]) -> Option<usize> {
Self::select_hash(hash_bytes(window), self.s, self.keep_below)
}
/// Return an n-gram calculation object and the number of files skipped if their types
/// didn't match, if the `skip_unknown` variable was true.
///
/// # Errors
///
/// An error will occur if:
/// * the provided directory path doesn't exist, isn't a directory, or can't be traversed,
/// * the n-gram size `n` is less than 2,
/// * the n-grams to keep `k` is less than 10,
/// * the stride `s` is less than 1,
/// * the file type isn't provided and the file types observed aren't the same without the
/// `skip_unknown` parameter being true
/// * the file type isn't provided and it can't be detected
pub fn new(
ftype: Option<FileType>,
dir: &Path,
n: u16,
k: usize,
s: u16,
verbose: bool,
skip_unknowns: bool,
) -> Result<(Self, u32)> {
ensure!(s > 0, "N-gram stride must be greater than zero.");
ensure!(n > 1, "N-gram size must be greater than one.");
ensure!(k > 9, "N-grams to keep must be ten or greater.");
ensure!(
dir.exists(),
"Provided path {} does not exist.",
dir.display()
);
ensure!(
dir.is_dir(),
"Provided path {} is not a directory.",
dir.display()
);
let mut paths = Vec::new();
let mut skipped = 0u32;
let allow_downgrade = ftype.is_none();
let mut ftype = ftype.unwrap_or(FileType::NotSet);
for entry in WalkDir::new(dir)
.max_depth(MAX_RECURSION_DEPTH)
.follow_links(true)
.into_iter()
.flatten()
{
if entry.file_type().is_file() {
if ftype != FileType::NotSet && !ftype.matches_path(entry.path())? {
if let Ok(Some(detected)) = FileType::from_path(entry.path()) {
if detected == FileType::DsStore {
continue;
}
// User had entered `None`, so we can see if a downgrade is possible.
if allow_downgrade {
let new_type = ftype.downgrade(detected)?;
if verbose {
println!(
"{}: Downgrading from {ftype} to {new_type}",
entry.path().display()
);
}
ftype = new_type;
} else if skip_unknowns {
skipped += 1;
} else {
bail!(
"File {} detected as {detected} which does not match expected type {ftype:?}",
entry.path().display()
);
}
} else if skip_unknowns {
skipped += 1;
} else {
// The encountered file doesn't match the expected type, and we
// couldn't figure out this file's type
bail!(
"File {} does not match expected type {ftype:?}",
entry.path().display()
);
}
} else if ftype == FileType::NotSet {
if let Some(detected_type) = FileType::from_path(entry.path())? {
if detected_type == FileType::DsStore {
continue;
}
ftype = detected_type;
if verbose {
println!(
"{}: Detected file type {detected_type}",
entry.path().display()
);
}
} else if skip_unknowns {
skipped += 1;
} else {
bail!("Unknown file type for {}", entry.path().display());
}
}
// If we're here, all type checks have passed.
paths.push(entry.into_path());
}
}
ensure!(!paths.is_empty(), "No files found!");
ensure!(
ftype != FileType::NotSet,
"No file type specified in n-grams file."
);
Ok((
Self {
n,
k,
s,
keep_below: u64::MAX / u64::from(s),
paths,
ftype,
ngrams: DashMap::default(),
},
skipped,
))
}
/// Find the n-grams storing the results internally
///
/// N-grams are only held for the `k` fullest hash buckets, and no more than [`Self::COUNTS`] of
/// them in all, so that is the most that are ever found, even if `k` asks for more.
#[allow(clippy::cast_possible_truncation)]
pub fn find(&mut self) {
let data: Vec<AtomicUsize> = (0..Self::COUNTS).map(|_| AtomicUsize::new(0)).collect();
self.paths.par_iter().for_each(|p| {
// Each file contributes one count per bucket it touches. The stride was already
// applied when the bitset was built, so every set bit is counted.
for (word_index, word) in self.find_ngram(p).unwrap_or_default().iter().enumerate() {
let mut word = *word;
while word != 0 {
let bucket = word_index * u64::BITS as usize + word.trailing_zeros() as usize;
data[bucket].fetch_add(1, Ordering::Relaxed);
// Clear the lowest set bit.
word &= word - 1;
}
}
});
// Keep the counts of the `k` fullest buckets and zero the rest, so that a non-zero count
// is what marks a bucket as kept. A bucket's count is at most the number of files, so a
// histogram that size finds the k-th largest without copying the counts to sort them.
if self.k < Self::COUNTS {
let mut histogram = vec![0usize; self.paths.len() + 1];
for count in &data {
histogram[count.load(Ordering::Relaxed)] += 1;
}
// Walk down from the fullest buckets to the count the k-th one has. Buckets above
// it are all kept; those level with it only until `k` is reached.
let mut min_count = 0;
let mut ties_left = self.k;
for (count, buckets) in histogram.iter().enumerate().rev() {
min_count = count;
if *buckets >= ties_left {
break;
}
ties_left -= buckets;
}
for count in &data {
let value = count.load(Ordering::Relaxed);
if value == min_count && ties_left > 0 {
ties_left -= 1;
} else if value <= min_count {
count.store(0, Ordering::Relaxed);
}
}
}
// Candidates are every n-gram of a kept bucket, collisions included, up to `COUNTS` of
// them: past that no more are taken, so the map can't outgrow the counts however large
// `n` or `k` are. A slot is reserved in `held` before an n-gram is inserted, which makes
// the limit exact rather than something the threads can race past.
//
// This used to have no limit, which for a `k` at or past `COUNTS` meant every distinct
// n-gram in the corpus, and ran out of memory.
let candidates: DashMap<Bytes, usize, FxBuildHasher> = DashMap::default();
let held = AtomicUsize::new(0);
self.paths.par_iter().for_each(|p| {
let walked = for_each_window(p, self.n, |window| {
// Buckets are shared with n-grams the stride left out, so those have to be
// turned away here too, not just left uncounted.
let Some(bucket) = self.select(window) else {
return Ok(());
};
let count = data[bucket].load(Ordering::Relaxed);
// Nothing is allocated or looked up past this point unless the bucket was
// kept, which keeps the per-window cost to a hash and a load.
if count == 0 || candidates.contains_key(window) {
return Ok(());
}
// The count only ever overshoots by threads about to back out, so the n-grams
// actually inserted stay within the limit.
if held.fetch_add(1, Ordering::Relaxed) >= Self::COUNTS
|| candidates.insert(window.to_vec(), count).is_some()
{
// Full, or another thread inserted the same n-gram first: hand the slot back.
held.fetch_sub(1, Ordering::Relaxed);
}
Ok(())
});
if let Err(e) = walked {
eprintln!("Failed to read {}: {e}", p.display());
}
});
// Only `k` buckets were kept, but n-grams that share one are all candidates, so there
// can be more than `k` of them. Take the k most frequent, which is what "top k n-grams"
// means and what the caller asked for.
let mut ranked: Vec<(Bytes, usize)> = candidates.into_iter().collect();
if ranked.len() > self.k {
// Partition around the k-th highest count rather than sorting all of them, breaking
// ties on the n-gram itself so the same candidates always yield the same n-grams.
ranked.select_nth_unstable_by(self.k, |(a_ngram, a), (b_ngram, b)| {
b.cmp(a).then_with(|| a_ngram.cmp(b_ngram))
});
ranked.truncate(self.k);
}
let kept_ngrams: DashMap<Bytes, usize, FxBuildHasher> =
DashMap::with_capacity_and_hasher(ranked.len(), FxBuildHasher::default());
for (ngram, count) in ranked {
kept_ngrams.insert(ngram, count);
}
self.ngrams = kept_ngrams;
}
/// Return a bitset marking every hash bucket this file has an n-gram in.
#[allow(clippy::cast_possible_truncation)]
fn find_ngram(&self, path: &Path) -> Result<Vec<u64>> {
let mut buckets = vec![0u64; Self::BITSET_WORDS];
for_each_window(path, self.n, |window| {
let Some(bucket) = self.select(window) else {
return Ok(());
};
buckets[bucket / u64::BITS as usize] |= 1 << (bucket % u64::BITS as usize);
Ok(())
})?;
Ok(buckets)
}
/// Save the n-grams as a plain text file
///
/// # Errors
///
/// An error occurs if the file cannot be opened or cannot be written.
pub fn save<P: AsRef<Path>>(&self, path: P, with_counts: bool) -> Result<()> {
let mut output = File::create(path)?;
writeln!(
output,
"# File type: {}\n# Original files: {}\n# Stride: {}",
self.ftype,
self.paths.len(),
self.s
)?;
if self.s > 1 {
writeln!(output, "# Stride: {}", self.s)?;
}
for entry in &self.ngrams {
if with_counts {
writeln!(output, "{},{}", hex::encode(entry.key()), entry.value())?;
} else {
writeln!(output, "{}", hex::encode(entry.key()))?;
}
}
output.flush()?;
Ok(())
}
/// Return the n-grams discovered
#[inline]
#[must_use]
pub fn ngrams(&self) -> &DashMap<Bytes, usize, FxBuildHasher> {
&self.ngrams
}
/// Return the expected or discovered file type
#[inline]
#[must_use]
pub fn ftype(&self) -> FileType {
self.ftype
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Write `files` into a fresh directory and return an [`Ngrammer`] over them.
fn ngrammer(name: &str, files: &[Vec<u8>], n: u16, k: usize) -> Ngrammer {
ngrammer_strided(name, files, n, k, 1)
}
/// Like [`ngrammer`], with a stride other than 1.
fn ngrammer_strided(name: &str, files: &[Vec<u8>], n: u16, k: usize, s: u16) -> Ngrammer {
let dir = std::env::temp_dir().join(name);
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let paths = files
.iter()
.enumerate()
.map(|(i, contents)| {
let path = dir.join(format!("{i}.bin"));
std::fs::write(&path, contents).unwrap();
path
})
.collect();
Ngrammer {
n,
k,
paths,
s,
keep_below: u64::MAX / u64::from(s),
ftype: FileType::ELF,
ngrams: DashMap::default(),
}
}
/// Deterministic filler bytes, distinct per `seed`.
fn noise(seed: u64, len: usize) -> Vec<u8> {
let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
(0..len)
.map(|_| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state.to_le_bytes()[4]
})
.collect()
}
#[test]
fn keeps_exactly_k_and_prefers_common() {
let shared = b"\x7fSHARED-NGRAM-IN-EVERY-FILE!".to_vec();
let files: Vec<Vec<u8>> = (0..4)
.map(|i| {
let mut contents = noise(i + 1, 256);
contents.extend_from_slice(&shared);
contents
})
.collect();
let mut ngrammer = ngrammer("mm_ngram_top_k", &files, 8, 10);
ngrammer.find();
assert_eq!(ngrammer.ngrams().len(), 10);
// Every window of the shared tail is in all four files, so those outrank the noise.
for entry in ngrammer.ngrams() {
assert_eq!(*entry.value(), 4, "{}", hex::encode(entry.key()));
assert!(shared.windows(8).any(|w| w == entry.key().as_slice()));
}
}
#[test]
fn candidates_never_exceed_counts() {
// More distinct n-grams than there are buckets, and a `k` that asks for all of them.
let distinct = Ngrammer::COUNTS + Ngrammer::COUNTS / 2;
let files: Vec<Vec<u8>> = (0..4u64)
.map(|i| noise(i + 100, distinct / 4 + 3))
.collect();
let mut ngrammer = ngrammer("mm_ngram_bounded", &files, 4, usize::MAX);
ngrammer.find();
assert!(!ngrammer.ngrams().is_empty());
assert!(ngrammer.ngrams().len() <= Ngrammer::COUNTS);
}
#[test]
#[allow(clippy::cast_possible_truncation)]
fn colliding_ngrams_are_both_kept() {
// Two different n-grams that land in the same bucket.
let mut seen: FxHashMap<usize, [u8; 4]> = FxHashMap::default();
let (first, second) = (0u32..)
.find_map(|i| {
let ngram = i.to_be_bytes();
let bucket = Ngrammer::select_hash(hash_bytes(&ngram), 1, u64::MAX)?;
seen.insert(bucket, ngram).map(|earlier| (earlier, ngram))
})
.unwrap();
let files = vec![first.to_vec(), second.to_vec(), first.to_vec()];
let mut ngrammer = ngrammer("mm_ngram_collisions", &files, 4, 2);
ngrammer.find();
assert_eq!(ngrammer.ngrams().len(), 2);
assert!(ngrammer.ngrams().contains_key(first.as_slice()));
assert!(ngrammer.ngrams().contains_key(second.as_slice()));
}
#[test]
fn same_corpus_same_ngrams() {
let files: Vec<Vec<u8>> = (0..8).map(|i| noise(i + 7, 8192)).collect();
let mut first = ngrammer("mm_ngram_repeat_a", &files, 3, 50);
first.find();
let mut second = ngrammer("mm_ngram_repeat_b", &files, 3, 50);
second.find();
let mut a: Vec<Bytes> = first.ngrams().iter().map(|e| e.key().clone()).collect();
let mut b: Vec<Bytes> = second.ngrams().iter().map(|e| e.key().clone()).collect();
a.sort();
b.sort();
assert_eq!(a.len(), 50);
assert_eq!(a, b);
}
#[test]
fn stride_keeps_only_sampled_ngrams() {
// With a stride, buckets off the stride used to leave their bit set, spinning forever.
let stride = 7u16;
let files: Vec<Vec<u8>> = (0..4).map(|i| noise(i + 40, 4096)).collect();
let mut ngrammer = ngrammer_strided("mm_ngram_stride", &files, 4, 100, stride);
ngrammer.find();
assert!(!ngrammer.ngrams().is_empty());
for entry in ngrammer.ngrams() {
assert!(
ngrammer.select(entry.key()).is_some(),
"{} was not sampled",
hex::encode(entry.key())
);
}
}
#[test]
#[allow(clippy::cast_precision_loss)]
fn stride_samples_evenly_and_fills_every_bucket() {
let stride = 7u16;
let keep_below = u64::MAX / u64::from(stride);
let total = 100_000u64;
let buckets: Vec<usize> = (0..total)
.filter_map(|i| Ngrammer::select_hash(hash_bytes(&i.to_le_bytes()), stride, keep_below))
.collect();
// About one hash in `stride` is sampled.
let expected = total as f64 / f64::from(stride);
let kept = buckets.len() as f64;
assert!(
(kept - expected).abs() < expected * 0.1,
"kept {kept}, expected {expected}"
);
// The sampled ones spread over the whole array, not only the strided buckets.
assert!(buckets.iter().all(|b| *b < Ngrammer::COUNTS));
let max = buckets.iter().copied().max().unwrap();
assert!(max > Ngrammer::COUNTS / 100 * 99, "largest bucket {max}");
for residue in 0..usize::from(stride) {
assert!(
buckets.iter().any(|b| b % usize::from(stride) == residue),
"no bucket = {residue} mod {stride}"
);
}
}
#[test]
#[allow(clippy::cast_possible_truncation)]
fn every_bucket_is_reachable_at_any_stride() {
// The cap on sampled hashes must not shrink the array: for every bucket there is a
// sampled hash that lands in it, however large the stride.
for stride in [1u16, 2, 7, 16, 1000, u16::MAX] {
let keep_below = u64::MAX / u64::from(stride);
for bucket in 0..Ngrammer::COUNTS {
// Smallest stretched value multiply-shift maps to `bucket`, then the smallest
// sampled hash that stretches to at least that.
let first = ((bucket as u128) << u64::BITS).div_ceil(Ngrammer::COUNTS as u128);
let hash = first.div_ceil(u128::from(stride)) as u64;
assert_eq!(
Ngrammer::select_hash(hash, stride, keep_below),
Some(bucket),
"stride {stride}, bucket {bucket}"
);
}
// And the largest sampled hash lands in the last bucket.
assert_eq!(
Ngrammer::select_hash(keep_below, stride, keep_below),
Some(Ngrammer::COUNTS - 1),
"stride {stride}"
);
}
}
#[test]
fn stride_from_ngram_line() {
let line = "# Stride: 4";
let stride = stride_from_line(line).unwrap();
assert_eq!(stride, 4);
}
}