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
use std::io::{Read, Seek, SeekFrom, Write};
use std::mem::size_of;

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use ndarray::{Array2, ArrayView2, ArrayViewMut2, CowArray, Ix1};

use super::{Storage, StorageView, StorageViewMut};
use crate::chunks::io::{ChunkIdentifier, ReadChunk, TypeId, WriteChunk};
use crate::error::{Error, Result};
use crate::util::padding;

#[cfg(feature = "memmap")]
mod mmap {
    use std::fs::File;
    #[cfg(target_endian = "little")]
    use std::io::Write;
    use std::io::{BufReader, Seek, SeekFrom};
    use std::mem::size_of;

    use crate::chunks::io::MmapChunk;
    #[cfg(target_endian = "big")]
    use byteorder::ByteOrder;
    use byteorder::{LittleEndian, ReadBytesExt};
    use memmap::{Mmap, MmapOptions};
    use ndarray::{ArrayView2, CowArray, Ix1};
    use ndarray::{Dimension, Ix2};

    #[cfg(target_endian = "little")]
    use super::NdArray;
    #[cfg(target_endian = "little")]
    use crate::chunks::io::WriteChunk;
    use crate::chunks::io::{ChunkIdentifier, TypeId};
    use crate::chunks::storage::Storage;
    #[cfg(target_endian = "little")]
    use crate::chunks::storage::StorageView;
    use crate::error::{Error, Result};
    use crate::util::padding;

    /// Memory-mapped matrix.
    #[derive(Debug)]
    pub struct MmapArray {
        map: Mmap,
        shape: Ix2,
    }

    impl Storage for MmapArray {
        fn embedding(&self, idx: usize) -> CowArray<f32, Ix1> {
            #[allow(clippy::cast_ptr_alignment,unused_mut)]
        let mut embedding =
            // Alignment is ok, padding guarantees that the pointer is at
            // a multiple of 4.
            unsafe { ArrayView2::from_shape_ptr(self.shape, self.map.as_ptr() as *const f32) }
                .row(idx)
                .to_owned();

            #[cfg(target_endian = "big")]
            LittleEndian::from_slice_f32(
                embedding
                    .as_slice_mut()
                    .expect("Cannot borrow vector as mutable slice"),
            );

            CowArray::from(embedding)
        }

        fn shape(&self) -> (usize, usize) {
            self.shape.into_pattern()
        }
    }

    #[cfg(target_endian = "little")]
    impl StorageView for MmapArray {
        fn view(&self) -> ArrayView2<f32> {
            // Alignment is ok, padding guarantees that the pointer is at
            // a multiple of 4.
            #[allow(clippy::cast_ptr_alignment)]
            unsafe {
                ArrayView2::from_shape_ptr(self.shape, self.map.as_ptr() as *const f32)
            }
        }
    }

    impl MmapChunk for MmapArray {
        fn mmap_chunk(read: &mut BufReader<File>) -> Result<Self> {
            ChunkIdentifier::ensure_chunk_type(read, ChunkIdentifier::NdArray)?;

            // Read and discard chunk length.
            read.read_u64::<LittleEndian>()
                .map_err(|e| Error::io_error("Cannot read embedding matrix chunk length", e))?;

            let rows = read.read_u64::<LittleEndian>().map_err(|e| {
                Error::io_error("Cannot read number of rows of the embedding matrix", e)
            })? as usize;
            let cols = read.read_u32::<LittleEndian>().map_err(|e| {
                Error::io_error("Cannot read number of columns of the embedding matrix", e)
            })? as usize;
            let shape = Ix2(rows, cols);

            // The components of the embedding matrix should be of type f32.
            f32::ensure_data_type(read)?;

            let n_padding = padding::<f32>(read.seek(SeekFrom::Current(0)).map_err(|e| {
                Error::io_error("Cannot get file position for computing padding", e)
            })?);
            read.seek(SeekFrom::Current(n_padding as i64))
                .map_err(|e| Error::io_error("Cannot skip padding", e))?;

            // Set up memory mapping.
            let matrix_len = shape.size() * size_of::<f32>();
            let offset = read.seek(SeekFrom::Current(0)).map_err(|e| {
                Error::io_error(
                    "Cannot get file position for memory mapping embedding matrix",
                    e,
                )
            })?;
            let mut mmap_opts = MmapOptions::new();
            let map = unsafe {
                mmap_opts
                    .offset(offset)
                    .len(matrix_len)
                    .map(&read.get_ref())
                    .map_err(|e| Error::io_error("Cannot memory map embedding matrix", e))?
            };

            // Position the reader after the matrix.
            read.seek(SeekFrom::Current(matrix_len as i64))
                .map_err(|e| Error::io_error("Cannot skip embedding matrix", e))?;

            Ok(MmapArray { map, shape })
        }
    }

    #[cfg(target_endian = "little")]
    impl WriteChunk for MmapArray {
        fn chunk_identifier(&self) -> ChunkIdentifier {
            ChunkIdentifier::NdArray
        }

        fn write_chunk<W>(&self, write: &mut W) -> Result<()>
        where
            W: Write + Seek,
        {
            NdArray::write_ndarray_chunk(self.view(), write)
        }
    }
}

#[cfg(feature = "memmap")]
pub use mmap::MmapArray;

/// In-memory `ndarray` matrix.
#[derive(Clone, Debug)]
pub struct NdArray {
    inner: Array2<f32>,
}

impl NdArray {
    pub fn new(arr: Array2<f32>) -> Self {
        NdArray { inner: arr }
    }

    fn write_ndarray_chunk<W>(data: ArrayView2<f32>, write: &mut W) -> Result<()>
    where
        W: Write + Seek,
    {
        write
            .write_u32::<LittleEndian>(ChunkIdentifier::NdArray as u32)
            .map_err(|e| Error::io_error("Cannot write embedding matrix chunk identifier", e))?;
        let n_padding =
            padding::<f32>(write.seek(SeekFrom::Current(0)).map_err(|e| {
                Error::io_error("Cannot get file position for computing padding", e)
            })?);
        // Chunk size: rows (u64), columns (u32), type id (u32),
        //             padding ([0,4) bytes), matrix.
        let chunk_len = size_of::<u64>()
            + size_of::<u32>()
            + size_of::<u32>()
            + n_padding as usize
            + (data.nrows() * data.ncols() * size_of::<f32>());
        write
            .write_u64::<LittleEndian>(chunk_len as u64)
            .map_err(|e| Error::io_error("Cannot write embedding matrix chunk length", e))?;
        write
            .write_u64::<LittleEndian>(data.nrows() as u64)
            .map_err(|e| {
                Error::io_error("Cannot write number of rows of the embedding matrix", e)
            })?;
        write
            .write_u32::<LittleEndian>(data.ncols() as u32)
            .map_err(|e| {
                Error::io_error("Cannot write number of columns of the embedding matrix", e)
            })?;
        write
            .write_u32::<LittleEndian>(f32::type_id())
            .map_err(|e| Error::io_error("Cannot write embedding matrix type identifier", e))?;

        // Write padding, such that the embedding matrix starts on at
        // a multiple of the size of f32 (4 bytes). This is necessary
        // for memory mapping a matrix. Interpreting the raw u8 data
        // as a proper f32 array requires that the data is aligned in
        // memory. However, we cannot always memory map the starting
        // offset of the matrix directly, since mmap(2) requires a
        // file offset that is page-aligned. Since the page size is
        // always a larger power of 2 (e.g. 2^12), which is divisible
        // by 4, the offset of the matrix with regards to the page
        // boundary is also a multiple of 4.

        let padding = vec![0; n_padding as usize];
        write
            .write_all(&padding)
            .map_err(|e| Error::io_error("Cannot write padding", e))?;

        for row in data.outer_iter() {
            for col in row.iter() {
                write
                    .write_f32::<LittleEndian>(*col)
                    .map_err(|e| Error::io_error("Cannot write embedding matrix component", e))?;
            }
        }

        Ok(())
    }
}

impl From<Array2<f32>> for NdArray {
    fn from(arr: Array2<f32>) -> Self {
        NdArray::new(arr)
    }
}

impl From<NdArray> for Array2<f32> {
    fn from(arr: NdArray) -> Self {
        arr.inner
    }
}

impl Storage for NdArray {
    fn embedding(&self, idx: usize) -> CowArray<f32, Ix1> {
        CowArray::from(self.inner.row(idx))
    }

    fn shape(&self) -> (usize, usize) {
        self.inner.dim()
    }
}

impl StorageView for NdArray {
    fn view(&self) -> ArrayView2<f32> {
        self.inner.view()
    }
}

impl StorageViewMut for NdArray {
    fn view_mut(&mut self) -> ArrayViewMut2<f32> {
        self.inner.view_mut()
    }
}

impl ReadChunk for NdArray {
    fn read_chunk<R>(read: &mut R) -> Result<Self>
    where
        R: Read + Seek,
    {
        ChunkIdentifier::ensure_chunk_type(read, ChunkIdentifier::NdArray)?;

        // Read and discard chunk length.
        read.read_u64::<LittleEndian>()
            .map_err(|e| Error::io_error("Cannot read embedding matrix chunk length", e))?;

        let rows = read
            .read_u64::<LittleEndian>()
            .map_err(|e| Error::io_error("Cannot read number of rows of the embedding matrix", e))?
            as usize;
        let cols = read.read_u32::<LittleEndian>().map_err(|e| {
            Error::io_error("Cannot read number of columns of the embedding matrix", e)
        })? as usize;

        // The components of the embedding matrix should be of type f32.
        f32::ensure_data_type(read)?;

        let n_padding =
            padding::<f32>(read.seek(SeekFrom::Current(0)).map_err(|e| {
                Error::io_error("Cannot get file position for computing padding", e)
            })?);
        read.seek(SeekFrom::Current(n_padding as i64))
            .map_err(|e| Error::io_error("Cannot skip padding", e))?;

        let mut data = vec![0f32; rows * cols];
        read.read_f32_into::<LittleEndian>(&mut data)
            .map_err(|e| Error::io_error("Cannot read embedding matrix", e))?;

        Ok(NdArray {
            inner: Array2::from_shape_vec((rows, cols), data).map_err(Error::Shape)?,
        })
    }
}

impl WriteChunk for NdArray {
    fn chunk_identifier(&self) -> ChunkIdentifier {
        ChunkIdentifier::NdArray
    }

    fn write_chunk<W>(&self, write: &mut W) -> Result<()>
    where
        W: Write + Seek,
    {
        Self::write_ndarray_chunk(self.inner.view(), write)
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Cursor, Read, Seek, SeekFrom};

    use byteorder::{LittleEndian, ReadBytesExt};
    use ndarray::Array2;

    use crate::chunks::io::{ReadChunk, WriteChunk};
    use crate::chunks::storage::{NdArray, StorageView};

    const N_ROWS: usize = 100;
    const N_COLS: usize = 100;

    fn test_ndarray() -> NdArray {
        let test_data = Array2::from_shape_fn((N_ROWS, N_COLS), |(r, c)| {
            r as f32 * N_COLS as f32 + c as f32
        });

        NdArray::new(test_data)
    }

    fn read_chunk_size(read: &mut impl Read) -> u64 {
        // Skip identifier.
        read.read_u32::<LittleEndian>().unwrap();

        // Return chunk length.
        read.read_u64::<LittleEndian>().unwrap()
    }

    #[test]
    fn ndarray_correct_chunk_size() {
        let check_arr = test_ndarray();
        let mut cursor = Cursor::new(Vec::new());
        check_arr.write_chunk(&mut cursor).unwrap();
        cursor.seek(SeekFrom::Start(0)).unwrap();

        let chunk_size = read_chunk_size(&mut cursor);
        assert_eq!(
            cursor.read_to_end(&mut Vec::new()).unwrap(),
            chunk_size as usize
        );
    }

    #[test]
    fn ndarray_write_read_roundtrip() {
        let check_arr = test_ndarray();
        let mut cursor = Cursor::new(Vec::new());
        check_arr.write_chunk(&mut cursor).unwrap();
        cursor.seek(SeekFrom::Start(0)).unwrap();
        let arr = NdArray::read_chunk(&mut cursor).unwrap();
        assert_eq!(arr.view(), check_arr.view());
    }
}