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
//! Backing storage for a loaded model's bytes.
//!
//! A model file is opened once, up front, and every tensor's raw bytes are
//! served as a slice into that single buffer. [`ByteSource`] is the enum
//! that decides *how* those bytes are held in memory.
use File;
use Path;
use ;
/// Either a memory-mapped file or a fully-read buffer.
///
/// # Why prefer `mmap`
///
/// A 7B-parameter model in `f16` is already ~14 GiB on disk. Reading that
/// into a `Vec<u8>` means the OS page cache holds one copy and the process
/// heap holds a second, doubling peak memory for no benefit — the loader
/// never needs the *whole* file resident at once, only whichever tensor a
/// caller is currently consuming. Memory-mapping lets the OS page tensor
/// data in on first touch and evict it under memory pressure, which a
/// `Vec<u8>` cannot do.
///
/// # Why not *only* `mmap`
///
/// `mmap`-ing a file is refused by some platforms/filesystems for empty
/// files, and [`memmap2::Mmap::map`] is `unsafe`: the OS gives no guarantee
/// the file won't be truncated or overwritten by another process while it
/// is mapped, which would turn a read into a segfault or torn data rather
/// than a clean I/O error. Both are edge cases worth tolerating rather than
/// treating as load failures, so [`ByteSource::open`] falls back to reading
/// the file fully into a `Vec<u8>` whenever `mmap` cannot be used. This
/// crate accepts that reduced (but well-understood and documented) safety
/// margin in exchange for not doubling memory on the common path; a future
/// caller that cannot accept it at all is free to force the `Owned` path by
/// constructing one directly once such a constructor is needed.
pub