Skip to main content

malware_modeler/
row.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Storage for the rows of a [`crate::dataset::Dataset`].
4//!
5//! A feature is the presence or absence of an n-gram, and a sample contains only a tiny
6//! fraction of the n-grams in the feature set — a few thousand out of hundreds of thousands
7//! or a million. A row is therefore stored as the sorted list of the feature indices that are
8//! set, four bytes each, and nothing at all for the features that aren't.
9//!
10//! Because a row records *which* features are present rather than a value per feature, a
11//! dataset value other than zero or one cannot be represented, and is rejected rather than
12//! rounded.
13//!
14//! [`crate::row::DataMatrix`] holds many rows in a handful of large blocks rather than giving each row its
15//! own allocation, which avoids allocator rounding per row and keeps rows that are scanned
16//! together close in memory. Blocks are used in preference to one flat buffer because growing
17//! a single multi-gigabyte buffer by doubling needs half again as much during the copy.
18
19use std::fmt;
20
21use anyhow::{Result, anyhow, bail, ensure};
22use serde::de::{SeqAccess, Visitor};
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24
25/// A feature index.
26///
27/// Datasets are limited to `u32::MAX` features, far beyond the largest n-gram count this
28/// crate is meant for, and half the size of a `usize` on the platforms it runs on.
29type Index = u32;
30
31/// Target size of one storage block, in bytes.
32///
33/// Large enough that per-block allocator overhead is irrelevant, small enough that growing the
34/// matrix never needs a large contiguous reallocation.
35const TARGET_BLOCK_BYTES: usize = 8 * 1024 * 1024;
36
37/// Feature indices held per block.
38const BLOCK_INDICES: usize = TARGET_BLOCK_BYTES / std::mem::size_of::<Index>();
39
40/// Bytes a row with `nonzeros` set features occupies inside a [`DataMatrix`].
41///
42/// A matrix row is a slice of a shared block, so there is no per-row allocation to account
43/// for. Note this depends on how many features are *set*, not on the column count.
44#[inline]
45#[must_use]
46pub const fn bytes_per_row(nonzeros: usize) -> usize {
47    nonzeros * std::mem::size_of::<Index>()
48}
49
50/// Interpret a dataset value as feature presence.
51///
52/// # Errors
53///
54/// Returns an error for anything other than zero or one.
55#[inline]
56fn binary_value(value: f32, index: usize) -> Result<bool> {
57    // Exact comparison is deliberate: a row records presence, so any other value has to be
58    // rejected rather than tolerated within a margin.
59    #[allow(clippy::float_cmp)]
60    let (is_zero, is_one) = (value == 0.0, value == 1.0);
61
62    if is_one {
63        Ok(true)
64    } else if is_zero {
65        Ok(false)
66    } else {
67        bail!(
68            "Value {value} at feature index {index} is not 0 or 1. A dataset row records \
69             whether each n-gram is present, so it cannot hold other values."
70        )
71    }
72}
73
74/// Narrow a column position to an [`Index`].
75#[inline]
76fn to_index(index: usize) -> Result<Index> {
77    Index::try_from(index)
78        .map_err(|_| anyhow!("Feature index {index} exceeds the limit of {}", Index::MAX))
79}
80
81/// A borrowed view of one row's set features.
82///
83/// All the read-only row operations live here, so they are written once and shared by an owned
84/// [`DataRow`] and by a row of a [`DataMatrix`].
85#[derive(Copy, Clone, Debug)]
86pub struct RowSlice<'a> {
87    /// Indices of the set features, sorted ascending and free of duplicates
88    indices: &'a [Index],
89
90    /// Number of feature columns, which bounds the indices
91    len: usize,
92}
93
94impl<'a> RowSlice<'a> {
95    /// Number of feature columns in the row.
96    #[inline]
97    #[must_use]
98    pub const fn len(&self) -> usize {
99        self.len
100    }
101
102    /// Whether the row has no columns.
103    #[inline]
104    #[must_use]
105    pub const fn is_empty(&self) -> bool {
106        self.len == 0
107    }
108
109    /// The set feature indices, ascending.
110    #[inline]
111    #[must_use]
112    pub const fn indices(&self) -> &'a [Index] {
113        self.indices
114    }
115
116    /// Value of the feature at `index`, or `None` if `index` is out of bounds.
117    ///
118    /// Costs a binary search over the set features, unlike the other accessors here. Prefer
119    /// [`RowSlice::iter_nonzero`] when visiting a whole row.
120    #[must_use]
121    pub fn get(&self, index: usize) -> Option<f32> {
122        if index >= self.len {
123            return None;
124        }
125
126        let Ok(needle) = Index::try_from(index) else {
127            return Some(0.0);
128        };
129        Some(f32::from(self.indices.binary_search(&needle).is_ok()))
130    }
131
132    /// Iterate over every feature value, including the zeroes.
133    ///
134    /// Walks the columns in step with the set features, so it costs the column count rather
135    /// than a binary search per column.
136    pub fn iter(self) -> impl Iterator<Item = f32> + 'a {
137        let indices = self.indices;
138        let mut cursor = 0usize;
139
140        (0..self.len).map(move |column| {
141            while cursor < indices.len() && (indices[cursor] as usize) < column {
142                cursor += 1;
143            }
144            f32::from(cursor < indices.len() && indices[cursor] as usize == column)
145        })
146    }
147
148    /// Iterate over the index and value of the set features only.
149    ///
150    /// This is the cheap way to read a row: it visits only what is present.
151    pub fn iter_nonzero(self) -> impl Iterator<Item = (usize, f32)> + 'a {
152        self.indices.iter().map(|index| (*index as usize, 1.0))
153    }
154
155    /// Number of set features in the row.
156    #[inline]
157    #[must_use]
158    pub const fn count_nonzero(&self) -> usize {
159        self.indices.len()
160    }
161
162    /// Sum of the feature values, which for a presence row is the number set.
163    #[must_use]
164    #[allow(clippy::cast_precision_loss)]
165    pub fn sum(&self) -> f32 {
166        self.indices.len() as f32
167    }
168
169    /// Dot product of this row with a weight vector.
170    ///
171    /// Only the set features contribute, so this reads one weight per set feature. Indices
172    /// beyond the end of `weights` are ignored.
173    #[must_use]
174    pub fn dot(&self, weights: &[f32]) -> f32 {
175        self.indices
176            .iter()
177            .filter_map(|index| weights.get(*index as usize))
178            .sum()
179    }
180
181    /// An owned row holding only the features at the given indices, renumbered to their
182    /// positions in `keep`.
183    ///
184    /// `keep` must be sorted ascending. Used to drop the features a trained model found
185    /// unnecessary.
186    #[must_use]
187    pub fn retain_indices(&self, keep: &[usize]) -> DataRow {
188        let remap = Remap::new(self.len, keep);
189        DataRow {
190            indices: remap.apply(self.indices),
191            len: keep.len(),
192        }
193    }
194}
195
196impl PartialEq for RowSlice<'_> {
197    fn eq(&self, other: &Self) -> bool {
198        self.len == other.len && self.indices == other.indices
199    }
200}
201
202/// Rows serialize as a flat sequence of every feature value rather than as indices, so JSON
203/// and TOML datasets stay readable and portable.
204impl Serialize for RowSlice<'_> {
205    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
206        serializer.collect_seq(self.iter())
207    }
208}
209
210/// Old-column to new-column lookup for dropping features.
211struct Remap {
212    /// `by_old[old]` is the new index, or `Index::MAX` if the column was dropped
213    by_old: Vec<Index>,
214}
215
216impl Remap {
217    /// Build a lookup that keeps the columns in `keep`, renumbered to their position in it.
218    fn new(columns: usize, keep: &[usize]) -> Self {
219        let mut by_old = vec![Index::MAX; columns];
220        for (new_index, old_index) in keep.iter().enumerate() {
221            if let Some(slot) = by_old.get_mut(*old_index)
222                && let Ok(new_index) = Index::try_from(new_index)
223            {
224                *slot = new_index;
225            }
226        }
227        Self { by_old }
228    }
229
230    /// Translate a row's indices, dropping the columns that aren't kept.
231    ///
232    /// Stays sorted as long as `keep` was sorted, because the new indices increase with the
233    /// old ones.
234    fn apply(&self, indices: &[Index]) -> Vec<Index> {
235        indices
236            .iter()
237            .filter_map(|old| {
238                let new = *self.by_old.get(*old as usize)?;
239                (new != Index::MAX).then_some(new)
240            })
241            .collect()
242    }
243}
244
245/// One row of features, owning its storage.
246///
247/// A [`DataMatrix`] is the right choice for many rows; this is for the one-off cases, such as
248/// featurizing a single file for inference.
249#[derive(Clone, Debug, Default, PartialEq)]
250pub struct DataRow {
251    /// Indices of the set features, sorted ascending and free of duplicates
252    indices: Vec<Index>,
253
254    /// Number of feature columns
255    len: usize,
256}
257
258impl DataRow {
259    /// A row of `len` columns with nothing set.
260    #[must_use]
261    pub fn zeroed(len: usize) -> Self {
262        Self {
263            indices: Vec::new(),
264            len,
265        }
266    }
267
268    /// Borrow the row.
269    #[inline]
270    #[must_use]
271    pub fn as_slice(&self) -> RowSlice<'_> {
272        RowSlice {
273            indices: &self.indices,
274            len: self.len,
275        }
276    }
277
278    /// Number of feature columns in the row.
279    #[inline]
280    #[must_use]
281    pub const fn len(&self) -> usize {
282        self.len
283    }
284
285    /// Whether the row has no columns.
286    #[inline]
287    #[must_use]
288    pub const fn is_empty(&self) -> bool {
289        self.len == 0
290    }
291
292    /// Value of the feature at `index`, or `None` if `index` is out of bounds.
293    #[inline]
294    #[must_use]
295    pub fn get(&self, index: usize) -> Option<f32> {
296        self.as_slice().get(index)
297    }
298
299    /// Set the feature at `index`.
300    ///
301    /// Idempotent, and accepts the columns in any order — it inserts so as to keep the indices
302    /// sorted, which costs a move of the tail. Prefer [`RowAccumulator`] when setting many.
303    ///
304    /// # Errors
305    ///
306    /// Returns an error if `index` is out of bounds, or if `value` is neither zero nor one. A
307    /// row records which features are present, so it cannot hold another value.
308    pub fn set(&mut self, index: usize, value: f32) -> Result<()> {
309        ensure!(
310            index < self.len,
311            "Feature index {index} is out of bounds for a row of {} features",
312            self.len
313        );
314        let needle = to_index(index)?;
315
316        if binary_value(value, index)? {
317            if let Err(position) = self.indices.binary_search(&needle) {
318                self.indices.insert(position, needle);
319            }
320        } else if let Ok(position) = self.indices.binary_search(&needle) {
321            self.indices.remove(position);
322        }
323
324        Ok(())
325    }
326
327    /// Iterate over every feature value, including the zeroes.
328    pub fn iter(&self) -> impl Iterator<Item = f32> + '_ {
329        self.as_slice().iter()
330    }
331
332    /// Iterate over the index and value of the set features only.
333    pub fn iter_nonzero(&self) -> impl Iterator<Item = (usize, f32)> + '_ {
334        self.as_slice().iter_nonzero()
335    }
336
337    /// Number of set features in the row.
338    #[inline]
339    #[must_use]
340    pub const fn count_nonzero(&self) -> usize {
341        self.indices.len()
342    }
343
344    /// Sum of the feature values.
345    #[must_use]
346    pub fn sum(&self) -> f32 {
347        self.as_slice().sum()
348    }
349
350    /// Dot product of this row with a weight vector.
351    #[must_use]
352    pub fn dot(&self, weights: &[f32]) -> f32 {
353        self.as_slice().dot(weights)
354    }
355
356    /// A new row holding only the features at the given indices, renumbered.
357    #[must_use]
358    pub fn retain_indices(&self, keep: &[usize]) -> Self {
359        self.as_slice().retain_indices(keep)
360    }
361}
362
363impl TryFrom<&[f32]> for DataRow {
364    type Error = anyhow::Error;
365
366    fn try_from(values: &[f32]) -> Result<Self> {
367        let mut indices = Vec::new();
368        for (index, value) in values.iter().enumerate() {
369            if binary_value(*value, index)? {
370                indices.push(to_index(index)?);
371            }
372        }
373
374        Ok(Self {
375            indices,
376            len: values.len(),
377        })
378    }
379}
380
381impl TryFrom<Vec<f32>> for DataRow {
382    type Error = anyhow::Error;
383
384    fn try_from(values: Vec<f32>) -> Result<Self> {
385        Self::try_from(values.as_slice())
386    }
387}
388
389impl Serialize for DataRow {
390    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
391        self.as_slice().serialize(serializer)
392    }
393}
394
395impl<'de> Deserialize<'de> for DataRow {
396    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
397        let values = Vec::<f32>::deserialize(deserializer)?;
398        DataRow::try_from(values).map_err(serde::de::Error::custom)
399    }
400}
401
402/// Builds one row by setting features in any order, any number of times.
403///
404/// Backed by a bitmap over the columns, so setting the same feature repeatedly — which happens
405/// whenever an n-gram occurs more than once in a file — costs nothing and cannot grow without
406/// bound. [`RowAccumulator::build`] then produces the sorted indices.
407///
408/// The bitmap is one bit per column, so it is cheap to reuse across files rather than
409/// reallocate.
410pub struct RowAccumulator {
411    /// One bit per column
412    bits: Vec<u64>,
413
414    /// Number of columns
415    len: usize,
416}
417
418impl RowAccumulator {
419    /// An accumulator for a row of `len` columns.
420    #[must_use]
421    pub fn new(len: usize) -> Self {
422        Self {
423            bits: vec![0u64; len.div_ceil(u64::BITS as usize)],
424            len,
425        }
426    }
427
428    /// Number of columns.
429    #[inline]
430    #[must_use]
431    pub const fn len(&self) -> usize {
432        self.len
433    }
434
435    /// Whether there are no columns.
436    #[inline]
437    #[must_use]
438    pub const fn is_empty(&self) -> bool {
439        self.len == 0
440    }
441
442    /// Mark the feature at `index` as present. Idempotent.
443    ///
444    /// # Errors
445    ///
446    /// Returns an error if `index` is out of bounds.
447    #[inline]
448    pub fn set(&mut self, index: usize) -> Result<()> {
449        ensure!(
450            index < self.len,
451            "Feature index {index} is out of bounds for a row of {} features",
452            self.len
453        );
454        self.bits[index / u64::BITS as usize] |= 1 << (index % u64::BITS as usize);
455        Ok(())
456    }
457
458    /// Clear every feature, keeping the allocation for the next row.
459    pub fn clear(&mut self) {
460        self.bits.fill(0);
461    }
462
463    /// Number of features currently set.
464    #[must_use]
465    pub fn count(&self) -> usize {
466        self.bits
467            .iter()
468            .map(|word| word.count_ones() as usize)
469            .sum()
470    }
471
472    /// The accumulated row, with its indices sorted ascending.
473    #[must_use]
474    pub fn build(&self) -> DataRow {
475        let mut indices = Vec::with_capacity(self.count());
476        for (word_index, word) in self.bits.iter().enumerate() {
477            let mut remaining = *word;
478            while remaining != 0 {
479                let bit = remaining.trailing_zeros() as usize;
480                remaining &= remaining - 1;
481                let index = word_index * u64::BITS as usize + bit;
482                // Bits past `len` live in the final word's padding.
483                if index >= self.len {
484                    break;
485                }
486                if let Ok(index) = Index::try_from(index) {
487                    indices.push(index);
488                }
489            }
490        }
491
492        DataRow {
493            indices,
494            len: self.len,
495        }
496    }
497}
498
499/// Where one row's indices live inside a [`DataMatrix`]'s blocks.
500#[derive(Copy, Clone, Debug)]
501struct RowRef {
502    /// Which block holds the row
503    block: u32,
504
505    /// Offset of the row's first index within that block
506    offset: u32,
507
508    /// Number of set features
509    len: u32,
510}
511
512/// Many rows over the same set of feature columns, stored in a handful of large blocks.
513///
514/// Each row's indices are contiguous within one block. Rows are addressed logically and
515/// reordered by permuting a small table of row descriptors, so shuffling between epochs moves
516/// twelve bytes per row rather than the indices themselves.
517#[derive(Clone, Debug, Default)]
518pub struct DataMatrix {
519    /// Index storage blocks
520    blocks: Vec<Vec<Index>>,
521
522    /// Row descriptors, in logical order
523    rows: Vec<RowRef>,
524
525    /// Number of feature columns
526    row_len: usize,
527
528    /// Scratch buffer for the row currently being built
529    scratch: Vec<Index>,
530}
531
532impl DataMatrix {
533    /// An empty matrix whose rows span `row_len` feature columns.
534    #[must_use]
535    pub fn new(row_len: usize) -> Self {
536        Self {
537            blocks: Vec::new(),
538            rows: Vec::new(),
539            row_len,
540            scratch: Vec::new(),
541        }
542    }
543
544    /// Number of rows.
545    #[inline]
546    #[must_use]
547    pub fn len(&self) -> usize {
548        self.rows.len()
549    }
550
551    /// Whether the matrix has no rows.
552    #[inline]
553    #[must_use]
554    pub fn is_empty(&self) -> bool {
555        self.rows.is_empty()
556    }
557
558    /// Number of feature columns.
559    #[inline]
560    #[must_use]
561    pub const fn row_len(&self) -> usize {
562        self.row_len
563    }
564
565    /// Number of storage blocks allocated.
566    #[inline]
567    #[must_use]
568    pub fn blocks(&self) -> usize {
569        self.blocks.len()
570    }
571
572    /// Total set features across every row.
573    #[must_use]
574    pub fn count_nonzero(&self) -> usize {
575        self.rows.iter().map(|row| row.len as usize).sum()
576    }
577
578    /// Bytes of storage currently allocated for indices and row descriptors.
579    #[must_use]
580    pub fn allocated_bytes(&self) -> usize {
581        self.blocks
582            .iter()
583            .map(|block| block.capacity() * std::mem::size_of::<Index>())
584            .sum::<usize>()
585            + self.rows.capacity() * std::mem::size_of::<RowRef>()
586            + self.scratch.capacity() * std::mem::size_of::<Index>()
587    }
588
589    /// Borrow the logical row at `index`.
590    #[inline]
591    #[must_use]
592    pub fn row(&self, index: usize) -> Option<RowSlice<'_>> {
593        self.slice_of(self.rows.get(index)?)
594    }
595
596    /// Borrow the row a descriptor points at.
597    #[inline]
598    fn slice_of(&self, row: &RowRef) -> Option<RowSlice<'_>> {
599        let start = row.offset as usize;
600        Some(RowSlice {
601            indices: self
602                .blocks
603                .get(row.block as usize)?
604                .get(start..start + row.len as usize)?,
605            len: self.row_len,
606        })
607    }
608
609    /// Iterate over the rows in logical order.
610    pub fn iter(&self) -> impl Iterator<Item = RowSlice<'_>> + '_ {
611        self.rows.iter().filter_map(|row| self.slice_of(row))
612    }
613
614    /// Start a new row. Call [`RowBuilder::finish`] to record it.
615    ///
616    /// # Errors
617    ///
618    /// Returns an error if the matrix already holds `u32::MAX` rows.
619    pub fn row_builder(&mut self) -> Result<RowBuilder<'_>> {
620        ensure!(
621            u32::try_from(self.rows.len()).is_ok(),
622            "A dataset cannot hold more than {} rows",
623            u32::MAX
624        );
625
626        self.scratch.clear();
627        Ok(RowBuilder {
628            matrix: self,
629            sorted: true,
630        })
631    }
632
633    /// Append a copy of `row`.
634    ///
635    /// # Errors
636    ///
637    /// Returns an error if `row` spans a different number of columns, or if the matrix is
638    /// full.
639    pub fn push_row(&mut self, row: RowSlice<'_>) -> Result<()> {
640        ensure!(
641            row.len() == self.row_len,
642            "Row spans {} features, expected {}",
643            row.len(),
644            self.row_len
645        );
646
647        // Already sorted and deduplicated, so it can go straight into a block.
648        self.append(row.indices)
649    }
650
651    /// Copy `indices` into a block and record a row pointing at them.
652    fn append(&mut self, indices: &[Index]) -> Result<()> {
653        let descriptor = self.reserve(indices.len())?;
654        let start = descriptor.offset as usize;
655        self.blocks[descriptor.block as usize][start..start + indices.len()]
656            .copy_from_slice(indices);
657        self.rows.push(descriptor);
658        Ok(())
659    }
660
661    /// Find room for `count` indices and return the descriptor pointing at it.
662    ///
663    /// The space is appended to the current block, or to a fresh one when the row would not
664    /// fit, so a row never straddles a block.
665    fn reserve(&mut self, count: usize) -> Result<RowRef> {
666        let fits = self
667            .blocks
668            .last()
669            .is_some_and(|block| block.len() + count <= block.capacity());
670
671        if !fits {
672            // A row larger than a standard block gets a block sized to it.
673            self.blocks
674                .push(Vec::with_capacity(count.max(BLOCK_INDICES)));
675        }
676
677        let block_index = self.blocks.len() - 1;
678        let block = &mut self.blocks[block_index];
679        let offset = block.len();
680        block.resize(offset + count, 0);
681
682        Ok(RowRef {
683            block: u32::try_from(block_index).map_err(|_| anyhow!("Too many storage blocks"))?,
684            offset: u32::try_from(offset)
685                .map_err(|_| anyhow!("Block offset {offset} is too large"))?,
686            len: u32::try_from(count)
687                .map_err(|_| anyhow!("A row cannot hold more than {} features", u32::MAX))?,
688        })
689    }
690
691    /// Reorder the rows so that logical row `i` becomes what was logical row `permutation[i]`.
692    ///
693    /// Only the row descriptors move; no indices are copied.
694    ///
695    /// # Errors
696    ///
697    /// Returns an error if `permutation` isn't the same length as the matrix.
698    pub fn permute(&mut self, permutation: &[usize]) -> Result<()> {
699        ensure!(
700            permutation.len() == self.rows.len(),
701            "Permutation has {} entries, expected {}",
702            permutation.len(),
703            self.rows.len()
704        );
705
706        self.rows = permutation.iter().map(|from| self.rows[*from]).collect();
707        Ok(())
708    }
709
710    /// Split off the logical rows from `at` onwards into a new matrix.
711    ///
712    /// The rows are copied, because after a shuffle the logical tail is scattered across the
713    /// blocks. The original keeps its blocks allocated, so this does not hand memory back.
714    ///
715    /// # Errors
716    ///
717    /// Returns an error if `at` is beyond the end, or if copying a row fails.
718    pub fn split_off(&mut self, at: usize) -> Result<Self> {
719        ensure!(
720            at <= self.len(),
721            "Split index {at} is beyond the {} rows available",
722            self.len()
723        );
724
725        let mut tail = Self::new(self.row_len);
726        for index in at..self.len() {
727            if let Some(row) = self.row(index) {
728                tail.push_row(row)?;
729            }
730        }
731        self.rows.truncate(at);
732        Ok(tail)
733    }
734
735    /// Rebuild every row to hold only the features at the given indices, renumbered.
736    ///
737    /// `keep` must be sorted ascending. Builds a fresh matrix, so peak memory is the old rows
738    /// plus the new, narrower ones.
739    ///
740    /// # Errors
741    ///
742    /// Returns an error if the rebuilt matrix cannot accept a row, which cannot happen if it
743    /// already holds them.
744    pub fn retain_indices(&mut self, keep: &[usize]) -> Result<()> {
745        let remap = Remap::new(self.row_len, keep);
746        let mut rebuilt = Self::new(keep.len());
747
748        for index in 0..self.len() {
749            let Some(row) = self.row(index) else { continue };
750            rebuilt.append(&remap.apply(row.indices))?;
751        }
752
753        *self = rebuilt;
754        Ok(())
755    }
756
757    /// Sum each feature column across every row.
758    ///
759    /// A single pass over the rows, touching only their set features.
760    #[must_use]
761    pub fn column_sums(&self) -> Vec<f32> {
762        let mut sums = vec![0.0f32; self.row_len];
763        for row in self.iter() {
764            for index in row.indices {
765                if let Some(sum) = sums.get_mut(*index as usize) {
766                    *sum += 1.0;
767                }
768            }
769        }
770        sums
771    }
772}
773
774impl PartialEq for DataMatrix {
775    fn eq(&self, other: &Self) -> bool {
776        self.row_len == other.row_len
777            && self.len() == other.len()
778            && self.iter().zip(other.iter()).all(|(a, b)| a == b)
779    }
780}
781
782/// Collect owned rows into a matrix.
783///
784/// Rows spanning a different number of columns are skipped rather than silently corrupting the
785/// matrix; the parsers check widths explicitly instead of relying on this.
786impl FromIterator<DataRow> for DataMatrix {
787    fn from_iter<I: IntoIterator<Item = DataRow>>(iter: I) -> Self {
788        let mut rows = iter.into_iter();
789        let Some(first) = rows.next() else {
790            return Self::new(0);
791        };
792
793        let mut matrix = Self::new(first.len());
794        let _ = matrix.push_row(first.as_slice());
795        for row in rows {
796            let _ = matrix.push_row(row.as_slice());
797        }
798        matrix
799    }
800}
801
802/// A row being appended to a [`DataMatrix`].
803///
804/// Features are collected into the matrix's scratch buffer, then sorted if needed and moved
805/// into a block by [`RowBuilder::finish`]. Dropping the builder without finishing discards the
806/// row.
807pub struct RowBuilder<'a> {
808    /// The matrix being appended to
809    matrix: &'a mut DataMatrix,
810
811    /// Whether the indices have arrived in ascending order so far
812    sorted: bool,
813}
814
815impl RowBuilder<'_> {
816    /// Record the feature at `index`.
817    ///
818    /// A `value` of zero is ignored, since an unlisted feature is already absent.
819    ///
820    /// # Errors
821    ///
822    /// Returns an error if `index` is out of bounds, or if `value` is neither zero nor one.
823    #[inline]
824    pub fn push(&mut self, index: usize, value: f32) -> Result<()> {
825        ensure!(
826            index < self.matrix.row_len,
827            "Feature index {index} is out of bounds for a dataset of {} features",
828            self.matrix.row_len
829        );
830
831        if !binary_value(value, index)? {
832            return Ok(());
833        }
834
835        let index = to_index(index)?;
836        if self.sorted
837            && self
838                .matrix
839                .scratch
840                .last()
841                .is_some_and(|last| *last >= index)
842        {
843            self.sorted = false;
844        }
845        self.matrix.scratch.push(index);
846        Ok(())
847    }
848
849    /// Finish the row and append it to the matrix.
850    ///
851    /// # Errors
852    ///
853    /// Returns an error if the same feature was recorded twice, or if the matrix is full.
854    pub fn finish(self) -> Result<()> {
855        let matrix = self.matrix;
856
857        // Files list features in ascending order in practice, so the sort is usually skipped.
858        if !self.sorted {
859            matrix.scratch.sort_unstable();
860        }
861
862        // Adjacent equality is enough once sorted, and catches a repeat either way.
863        if let Some([duplicate, _]) = matrix
864            .scratch
865            .windows(2)
866            .find(|pair| pair[0] == pair[1])
867            .and_then(|pair| <&[Index; 2]>::try_from(pair).ok())
868        {
869            bail!("Feature index {duplicate} is listed more than once on the same row");
870        }
871
872        let count = matrix.scratch.len();
873        let descriptor = matrix.reserve(count)?;
874        let start = descriptor.offset as usize;
875        // Split the borrow: the scratch buffer and the blocks are distinct fields.
876        let block = &mut matrix.blocks[descriptor.block as usize];
877        block[start..start + count].copy_from_slice(&matrix.scratch);
878        matrix.rows.push(descriptor);
879        Ok(())
880    }
881}
882
883impl Serialize for DataMatrix {
884    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
885        serializer.collect_seq(self.iter())
886    }
887}
888
889impl<'de> Deserialize<'de> for DataMatrix {
890    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
891        struct MatrixVisitor;
892
893        impl<'de> Visitor<'de> for MatrixVisitor {
894            type Value = DataMatrix;
895
896            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897                f.write_str("a sequence of dataset rows")
898            }
899
900            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
901                use serde::de::Error;
902
903                let mut matrix: Option<DataMatrix> = None;
904                while let Some(row) = seq.next_element::<DataRow>()? {
905                    let matrix = matrix.get_or_insert_with(|| DataMatrix::new(row.len()));
906                    matrix.push_row(row.as_slice()).map_err(A::Error::custom)?;
907                }
908
909                Ok(matrix.unwrap_or_else(|| DataMatrix::new(0)))
910            }
911        }
912
913        deserializer.deserialize_seq(MatrixVisitor)
914    }
915}
916
917#[cfg(test)]
918mod tests {
919    use super::{BLOCK_INDICES, DataMatrix, DataRow, RowAccumulator, RowRef, bytes_per_row};
920
921    #[test]
922    fn binary_round_trip() {
923        let values = [1.0f32, 0.0, 0.0, 1.0, 1.0, 0.0];
924        let row = DataRow::try_from(values.as_slice()).unwrap();
925
926        assert_eq!(row.len(), values.len());
927        assert!(!row.is_empty());
928        assert_eq!(row.iter().collect::<Vec<_>>(), values);
929        assert_eq!(row.count_nonzero(), 3);
930        assert!((row.sum() - 3.0).abs() < 1e-6);
931        assert_eq!(
932            row.iter_nonzero().collect::<Vec<_>>(),
933            vec![(0, 1.0), (3, 1.0), (4, 1.0)]
934        );
935
936        for (index, value) in values.iter().enumerate() {
937            assert_eq!(row.get(index), Some(*value));
938        }
939        assert_eq!(row.get(values.len()), None);
940    }
941
942    #[test]
943    fn dot_matches_naive() {
944        let values = [1.0f32, 0.0, 1.0, 0.0, 1.0];
945        let weights = [0.5f32, -2.0, 0.25, 7.0, -0.75];
946        let row = DataRow::try_from(values.as_slice()).unwrap();
947
948        let naive: f32 = values.iter().zip(&weights).map(|(v, w)| v * w).sum();
949        assert!((row.dot(&weights) - naive).abs() < 1e-6);
950    }
951
952    #[test]
953    fn set_keeps_indices_sorted_and_unique() {
954        let mut row = DataRow::zeroed(70);
955        assert_eq!(row.count_nonzero(), 0);
956
957        // Deliberately out of order.
958        row.set(69, 1.0).unwrap();
959        row.set(0, 1.0).unwrap();
960        row.set(64, 1.0).unwrap();
961        assert_eq!(row.as_slice().indices(), &[0, 64, 69]);
962
963        // Setting the same feature twice must not duplicate it.
964        row.set(64, 1.0).unwrap();
965        assert_eq!(row.count_nonzero(), 3);
966
967        row.set(64, 0.0).unwrap();
968        assert_eq!(row.as_slice().indices(), &[0, 69]);
969
970        // Clearing an absent feature is a no-op, not an error.
971        row.set(5, 0.0).unwrap();
972        assert_eq!(row.count_nonzero(), 2);
973
974        assert!(
975            row.set(70, 1.0).is_err(),
976            "out of bounds index must be rejected"
977        );
978    }
979
980    #[test]
981    fn retain_indices_renumbers() {
982        let row = DataRow::try_from([1.0f32, 0.0, 1.0, 1.0, 0.0].as_slice()).unwrap();
983        let kept = row.retain_indices(&[1, 2, 4]);
984
985        assert_eq!(kept.len(), 3);
986        assert_eq!(kept.iter().collect::<Vec<_>>(), vec![0.0, 1.0, 0.0]);
987        assert_eq!(kept.as_slice().indices(), &[1]);
988    }
989
990    #[test]
991    fn serde_is_a_flat_sequence() {
992        // The on-disk shape is a plain list of values, not indices, so existing JSON and TOML
993        // datasets stay readable.
994        let row = DataRow::try_from([1.0f32, 0.0, 1.0].as_slice()).unwrap();
995        let json = serde_json::to_string(&row).unwrap();
996        assert_eq!(json, "[1.0,0.0,1.0]");
997
998        let back: DataRow = serde_json::from_str(&json).unwrap();
999        assert_eq!(back, row);
1000    }
1001
1002    #[test]
1003    fn non_binary_values_are_rejected_not_rounded() {
1004        let mut row = DataRow::zeroed(3);
1005        let err = row.set(1, 0.5).unwrap_err().to_string();
1006        assert!(err.contains("not 0 or 1"), "unexpected error: {err}");
1007
1008        assert!(DataRow::try_from([0.0f32, 0.5].as_slice()).is_err());
1009    }
1010
1011    #[test]
1012    fn accumulator_deduplicates_and_sorts() {
1013        let mut acc = RowAccumulator::new(200);
1014        assert!(!acc.is_empty());
1015        assert_eq!(acc.len(), 200);
1016
1017        // Out of order, with repeats — what featurizing a file actually produces.
1018        for index in [130usize, 1, 199, 64, 1, 130, 0, 65, 130] {
1019            acc.set(index).unwrap();
1020        }
1021        assert!(acc.set(200).is_err());
1022        assert_eq!(acc.count(), 6);
1023
1024        let row = acc.build();
1025        assert_eq!(row.len(), 200);
1026        assert_eq!(row.as_slice().indices(), &[0, 1, 64, 65, 130, 199]);
1027
1028        acc.clear();
1029        assert_eq!(acc.count(), 0);
1030        assert_eq!(acc.build().count_nonzero(), 0);
1031    }
1032
1033    #[test]
1034    fn accumulator_ignores_padding_bits() {
1035        // Ten columns is less than one 64-bit word, so the word's upper bits are padding.
1036        let mut acc = RowAccumulator::new(10);
1037        for index in 0..10 {
1038            acc.set(index).unwrap();
1039        }
1040        assert_eq!(acc.build().as_slice().indices().len(), 10);
1041        assert!(acc.set(10).is_err());
1042    }
1043
1044    #[test]
1045    fn builder_accepts_unsorted_input() {
1046        let mut matrix = DataMatrix::new(100);
1047        let mut row = matrix.row_builder().unwrap();
1048        for index in [90usize, 3, 50, 0] {
1049            row.push(index, 1.0).unwrap();
1050        }
1051        row.finish().unwrap();
1052
1053        assert_eq!(
1054            matrix.row(0).unwrap().indices(),
1055            &[0, 3, 50, 90],
1056            "indices must come out sorted"
1057        );
1058    }
1059
1060    #[test]
1061    fn builder_rejects_duplicates() {
1062        let mut matrix = DataMatrix::new(100);
1063        let mut row = matrix.row_builder().unwrap();
1064        row.push(7, 1.0).unwrap();
1065        row.push(7, 1.0).unwrap();
1066
1067        let err = row.finish().unwrap_err().to_string();
1068        assert!(err.contains("more than once"), "unexpected error: {err}");
1069    }
1070
1071    #[test]
1072    fn builder_skips_zeroes_and_bounds_checks() {
1073        let mut matrix = DataMatrix::new(10);
1074        let mut row = matrix.row_builder().unwrap();
1075        for index in 0..10 {
1076            row.push(index, f32::from(index % 3 == 0)).unwrap();
1077        }
1078        assert!(row.push(10, 1.0).is_err(), "out of bounds must be rejected");
1079        row.finish().unwrap();
1080
1081        assert_eq!(matrix.row(0).unwrap().indices(), &[0, 3, 6, 9]);
1082        assert_eq!(matrix.count_nonzero(), 4);
1083    }
1084
1085    /// An unfinished row must leave no trace, so a parse error mid-row cannot half-record it.
1086    #[test]
1087    fn dropped_builder_records_nothing() {
1088        let mut matrix = DataMatrix::new(10);
1089        {
1090            let mut row = matrix.row_builder().unwrap();
1091            row.push(3, 1.0).unwrap();
1092        }
1093        assert_eq!(matrix.len(), 0);
1094
1095        let mut row = matrix.row_builder().unwrap();
1096        row.push(5, 1.0).unwrap();
1097        row.finish().unwrap();
1098        assert_eq!(matrix.len(), 1);
1099        assert_eq!(matrix.row(0).unwrap().indices(), &[5]);
1100    }
1101
1102    /// Rows must read back correctly across block boundaries, which is where a wrong block
1103    /// index or offset would show up.
1104    #[test]
1105    fn matrix_spans_many_blocks() {
1106        const FEATURES: usize = 1_000_000;
1107        const PER_ROW: usize = 5000;
1108
1109        let rows = (BLOCK_INDICES / PER_ROW) * 3 + 5;
1110        let mut matrix = DataMatrix::new(FEATURES);
1111
1112        for row_index in 0..rows {
1113            let mut row = matrix.row_builder().unwrap();
1114            for step in 0..PER_ROW {
1115                row.push((row_index + step * 97) % FEATURES, 1.0).unwrap();
1116            }
1117            row.finish().unwrap();
1118        }
1119
1120        assert_eq!(matrix.len(), rows);
1121        assert!(
1122            matrix.blocks() >= 4,
1123            "expected several blocks, got {}",
1124            matrix.blocks()
1125        );
1126
1127        for row_index in 0..rows {
1128            let row = matrix.row(row_index).unwrap();
1129            assert_eq!(row.len(), FEATURES);
1130            assert_eq!(row.count_nonzero(), PER_ROW, "row {row_index}");
1131
1132            let mut expected = (0..PER_ROW)
1133                .map(|step| u32::try_from((row_index + step * 97) % FEATURES).unwrap())
1134                .collect::<Vec<_>>();
1135            expected.sort_unstable();
1136            assert_eq!(row.indices(), expected.as_slice(), "row {row_index}");
1137        }
1138
1139        assert_eq!(matrix.row(rows), None);
1140    }
1141
1142    /// A row with more set features than a standard block holds must still be contiguous.
1143    #[test]
1144    fn matrix_handles_row_larger_than_a_block() {
1145        let features = BLOCK_INDICES * 2;
1146        let mut matrix = DataMatrix::new(features);
1147
1148        let mut row = matrix.row_builder().unwrap();
1149        for index in (0..features).step_by(2) {
1150            row.push(index, 1.0).unwrap();
1151        }
1152        row.finish().unwrap();
1153
1154        let stored = matrix.row(0).unwrap();
1155        assert_eq!(stored.count_nonzero(), features / 2);
1156        assert_eq!(stored.indices().first(), Some(&0));
1157        assert_eq!(
1158            stored.indices().last(),
1159            Some(&u32::try_from(features - 2).unwrap())
1160        );
1161    }
1162
1163    #[test]
1164    fn matrix_permute_reorders_without_copying_indices() {
1165        let mut matrix = DataMatrix::new(8);
1166        for row_index in 0..4 {
1167            let mut row = matrix.row_builder().unwrap();
1168            row.push(row_index, 1.0).unwrap();
1169            row.finish().unwrap();
1170        }
1171
1172        let before = matrix.allocated_bytes();
1173        matrix.permute(&[3, 1, 0, 2]).unwrap();
1174        assert_eq!(
1175            matrix.allocated_bytes(),
1176            before,
1177            "permute must not allocate"
1178        );
1179
1180        let seen = (0..4)
1181            .map(|i| matrix.row(i).unwrap().indices()[0])
1182            .collect::<Vec<_>>();
1183        assert_eq!(seen, vec![3, 1, 0, 2]);
1184
1185        assert!(matrix.permute(&[0, 1]).is_err(), "length must be checked");
1186    }
1187
1188    #[test]
1189    fn matrix_split_off_and_retain() {
1190        let mut matrix = DataMatrix::new(6);
1191        for row_index in 0..10 {
1192            let mut row = matrix.row_builder().unwrap();
1193            row.push(row_index % 6, 1.0).unwrap();
1194            row.finish().unwrap();
1195        }
1196
1197        let tail = matrix.split_off(7).unwrap();
1198        assert_eq!(matrix.len(), 7);
1199        assert_eq!(tail.len(), 3);
1200        assert_eq!(
1201            tail.row(0).unwrap().indices(),
1202            &[u32::try_from(7 % 6).unwrap()]
1203        );
1204
1205        matrix.retain_indices(&[1, 3, 5]).unwrap();
1206        assert_eq!(matrix.row_len(), 3);
1207        assert_eq!(matrix.len(), 7);
1208        // Original row 1 had feature 1 set, which becomes the first kept column.
1209        assert_eq!(matrix.row(1).unwrap().indices(), &[0]);
1210        // Original row 0 had feature 0 set, which was dropped.
1211        assert_eq!(matrix.row(0).unwrap().count_nonzero(), 0);
1212    }
1213
1214    #[test]
1215    fn matrix_column_sums() {
1216        let mut matrix = DataMatrix::new(4);
1217        for pattern in [vec![0usize, 2], vec![2], vec![1, 2, 3]] {
1218            let mut row = matrix.row_builder().unwrap();
1219            for index in pattern {
1220                row.push(index, 1.0).unwrap();
1221            }
1222            row.finish().unwrap();
1223        }
1224
1225        assert_eq!(matrix.column_sums(), vec![1.0, 1.0, 3.0, 1.0]);
1226    }
1227
1228    #[test]
1229    fn matrix_serde_round_trip() {
1230        let mut matrix = DataMatrix::new(4);
1231        for row_index in 0..3 {
1232            let mut row = matrix.row_builder().unwrap();
1233            row.push(row_index, 1.0).unwrap();
1234            row.finish().unwrap();
1235        }
1236
1237        let json = serde_json::to_string(&matrix).unwrap();
1238        let back: DataMatrix = serde_json::from_str(&json).unwrap();
1239        assert_eq!(back, matrix);
1240    }
1241
1242    /// Storage must cost the indices plus a bounded overhead, never a multiple of them.
1243    #[test]
1244    fn matrix_overhead_is_bounded() {
1245        const FEATURES: usize = 1_000_000;
1246        const PER_ROW: usize = 6900;
1247
1248        for rows in [1usize, 10, 400] {
1249            let mut matrix = DataMatrix::new(FEATURES);
1250            for row_index in 0..rows {
1251                let mut row = matrix.row_builder().unwrap();
1252                for step in 0..PER_ROW {
1253                    row.push((row_index + step * 101) % FEATURES, 1.0).unwrap();
1254                }
1255                row.finish().unwrap();
1256            }
1257
1258            let payload = rows * bytes_per_row(PER_ROW);
1259            let actual = matrix.allocated_bytes();
1260            assert!(
1261                actual >= payload,
1262                "{rows} rows: {actual} < payload {payload}"
1263            );
1264
1265            // One partial block, the descriptor table and the scratch buffer.
1266            let slack = BLOCK_INDICES * std::mem::size_of::<u32>()
1267                + rows * std::mem::size_of::<RowRef>() * 2
1268                + bytes_per_row(PER_ROW) * 2;
1269            assert!(
1270                actual - payload <= slack,
1271                "{rows} rows: overhead {} exceeds {slack}",
1272                actual - payload
1273            );
1274        }
1275    }
1276}