290 lines
9.3 KiB
Rust
290 lines
9.3 KiB
Rust
//! Read-only memory mapping of a model file.
|
|
//!
|
|
//! The runtime reads 12 GB of weights straight from the page cache instead of copying them. This is
|
|
//! the one `unsafe` surface for that. The safe API hands out `&[u8]` borrowed from the mapping; the
|
|
//! known limitation of every file mapping applies: if another process truncates the file while it is
|
|
//! mapped, access can fault. Model files are treated as immutable while the runtime holds them (the
|
|
//! file is opened with sharing that denies writers where the OS supports it).
|
|
|
|
use std::io;
|
|
use std::path::Path;
|
|
|
|
/// A read-only view of a whole file.
|
|
pub struct Mapping {
|
|
ptr: *const u8,
|
|
len: usize,
|
|
imp: imp::Handle,
|
|
}
|
|
|
|
// SAFETY: the mapping is read-only and never mutated through this type; the pointer stays valid for
|
|
// the lifetime of the value, so sharing and sending it between threads is sound.
|
|
unsafe impl Send for Mapping {}
|
|
// SAFETY: see above; only shared reads exist.
|
|
unsafe impl Sync for Mapping {}
|
|
|
|
impl Mapping {
|
|
/// Map `path` read-only. An empty file maps to an empty slice.
|
|
pub fn open(path: &Path) -> io::Result<Self> {
|
|
imp::open(path)
|
|
}
|
|
|
|
pub fn as_bytes(&self) -> &[u8] {
|
|
if self.len == 0 {
|
|
return &[];
|
|
}
|
|
// SAFETY: `ptr` points to `len` readable bytes that live until `drop`.
|
|
unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
|
|
}
|
|
|
|
/// Read one byte of every 4 KiB page so the operating system maps the whole file into this
|
|
/// process now instead of on first use (a soft page fault per page otherwise). Returns a checksum
|
|
/// of the bytes read so the work cannot be optimised away. Does not pin the pages.
|
|
pub fn touch_pages(&self) -> u64 {
|
|
self.as_bytes()
|
|
.iter()
|
|
.step_by(4096)
|
|
.fold(0u64, |acc, b| acc.wrapping_add(u64::from(*b)))
|
|
}
|
|
|
|
pub fn len(&self) -> usize {
|
|
self.len
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.len == 0
|
|
}
|
|
}
|
|
|
|
impl Drop for Mapping {
|
|
fn drop(&mut self) {
|
|
imp::close(self.ptr, self.len, &self.imp);
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Debug for Mapping {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
f.debug_struct("Mapping").field("len", &self.len).finish()
|
|
}
|
|
}
|
|
|
|
#[cfg(windows)]
|
|
mod imp {
|
|
use super::Mapping;
|
|
use std::io;
|
|
use std::os::windows::ffi::OsStrExt;
|
|
use std::path::Path;
|
|
|
|
pub struct Handle {
|
|
mapping: isize,
|
|
}
|
|
|
|
unsafe extern "system" {
|
|
fn CreateFileW(
|
|
name: *const u16,
|
|
access: u32,
|
|
share: u32,
|
|
security: *mut u8,
|
|
disposition: u32,
|
|
flags: u32,
|
|
template: isize,
|
|
) -> isize;
|
|
fn GetFileSizeEx(file: isize, size: *mut i64) -> i32;
|
|
fn CreateFileMappingW(
|
|
file: isize,
|
|
attrs: *mut u8,
|
|
protect: u32,
|
|
hi: u32,
|
|
lo: u32,
|
|
name: *const u16,
|
|
) -> isize;
|
|
fn MapViewOfFile(mapping: isize, access: u32, hi: u32, lo: u32, bytes: usize) -> *mut u8;
|
|
fn UnmapViewOfFile(base: *const u8) -> i32;
|
|
fn CloseHandle(handle: isize) -> i32;
|
|
}
|
|
|
|
const GENERIC_READ: u32 = 0x8000_0000;
|
|
const FILE_SHARE_READ: u32 = 1;
|
|
const OPEN_EXISTING: u32 = 3;
|
|
const FILE_ATTRIBUTE_NORMAL: u32 = 0x80;
|
|
const PAGE_READONLY: u32 = 2;
|
|
const FILE_MAP_READ: u32 = 4;
|
|
const INVALID_HANDLE_VALUE: isize = -1;
|
|
|
|
pub fn open(path: &Path) -> io::Result<Mapping> {
|
|
let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
|
|
// SAFETY: `wide` is a NUL-terminated UTF-16 string; other arguments are plain values.
|
|
let file = unsafe {
|
|
CreateFileW(
|
|
wide.as_ptr(),
|
|
GENERIC_READ,
|
|
FILE_SHARE_READ,
|
|
std::ptr::null_mut(),
|
|
OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL,
|
|
0,
|
|
)
|
|
};
|
|
if file == INVALID_HANDLE_VALUE {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
let result = map_read_only(file);
|
|
// The mapping object keeps the file alive; the file handle is no longer needed.
|
|
// SAFETY: closing the handle created above.
|
|
unsafe { CloseHandle(file) };
|
|
result
|
|
}
|
|
|
|
/// Map the whole file behind the open handle `file` read-only (an empty file maps nothing).
|
|
fn map_read_only(file: isize) -> io::Result<Mapping> {
|
|
let mut size: i64 = 0;
|
|
// SAFETY: `file` is a valid handle and `size` is writable.
|
|
if unsafe { GetFileSizeEx(file, &mut size) } == 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
let len = usize::try_from(size).map_err(|_| io::Error::other("file too large"))?;
|
|
if len == 0 {
|
|
return Ok(Mapping {
|
|
ptr: std::ptr::NonNull::dangling().as_ptr(),
|
|
len: 0,
|
|
imp: Handle { mapping: 0 },
|
|
});
|
|
}
|
|
view_whole_file(file, len)
|
|
}
|
|
|
|
/// An anonymous read-only mapping object over `file` and a view of all `len` bytes of it.
|
|
fn view_whole_file(file: isize, len: usize) -> io::Result<Mapping> {
|
|
// SAFETY: `file` is a valid handle; a null name creates an anonymous mapping object.
|
|
let mapping =
|
|
unsafe { CreateFileMappingW(file, std::ptr::null_mut(), PAGE_READONLY, 0, 0, std::ptr::null()) };
|
|
if mapping == 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
// SAFETY: `mapping` is a valid mapping handle; length 0 maps the whole file.
|
|
let ptr = unsafe { MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0) };
|
|
if ptr.is_null() {
|
|
let e = io::Error::last_os_error();
|
|
// SAFETY: closing the handle created above.
|
|
unsafe { CloseHandle(mapping) };
|
|
return Err(e);
|
|
}
|
|
Ok(Mapping {
|
|
ptr,
|
|
len,
|
|
imp: Handle { mapping },
|
|
})
|
|
}
|
|
|
|
pub fn close(ptr: *const u8, len: usize, handle: &Handle) {
|
|
if len == 0 {
|
|
return;
|
|
}
|
|
// SAFETY: `ptr` is the base returned by MapViewOfFile and `handle.mapping` the mapping handle.
|
|
unsafe {
|
|
UnmapViewOfFile(ptr);
|
|
CloseHandle(handle.mapping);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
mod imp {
|
|
use super::Mapping;
|
|
use std::fs::File;
|
|
use std::io;
|
|
use std::os::fd::AsRawFd;
|
|
use std::path::Path;
|
|
|
|
pub struct Handle;
|
|
|
|
unsafe extern "C" {
|
|
fn mmap(addr: *mut u8, len: usize, prot: i32, flags: i32, fd: i32, offset: i64) -> *mut u8;
|
|
fn munmap(addr: *mut u8, len: usize) -> i32;
|
|
}
|
|
|
|
const PROT_READ: i32 = 1;
|
|
const MAP_PRIVATE: i32 = 2;
|
|
|
|
pub fn open(path: &Path) -> io::Result<Mapping> {
|
|
let file = File::open(path)?;
|
|
let len = usize::try_from(file.metadata()?.len()).map_err(|_| io::Error::other("file too large"))?;
|
|
if len == 0 {
|
|
return Ok(Mapping {
|
|
ptr: std::ptr::NonNull::dangling().as_ptr(),
|
|
len: 0,
|
|
imp: Handle,
|
|
});
|
|
}
|
|
// SAFETY: valid descriptor and length; a failed call returns MAP_FAILED (all bits set).
|
|
let ptr = unsafe { mmap(std::ptr::null_mut(), len, PROT_READ, MAP_PRIVATE, file.as_raw_fd(), 0) };
|
|
if ptr as isize == -1 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
Ok(Mapping {
|
|
ptr,
|
|
len,
|
|
imp: Handle,
|
|
})
|
|
}
|
|
|
|
pub fn close(ptr: *const u8, len: usize, _handle: &Handle) {
|
|
if len > 0 {
|
|
// SAFETY: `ptr` and `len` are exactly the values returned by and passed to mmap.
|
|
unsafe { munmap(ptr as *mut u8, len) };
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::Write;
|
|
|
|
fn temp_file(name: &str, bytes: &[u8]) -> std::path::PathBuf {
|
|
let path =
|
|
std::env::temp_dir().join(format!("leleka-mapping-{name}-{}", std::process::id()));
|
|
let mut f = std::fs::File::create(&path).unwrap();
|
|
f.write_all(bytes).unwrap();
|
|
path
|
|
}
|
|
|
|
#[test]
|
|
fn maps_a_file_and_reads_it_back() {
|
|
let data: Vec<u8> = (0..200_000u32).map(|i| (i * 31 % 251) as u8).collect();
|
|
let path = temp_file("data", &data);
|
|
let m = Mapping::open(&path).unwrap();
|
|
assert_eq!(m.len(), data.len());
|
|
assert_eq!(m.as_bytes(), &data[..]);
|
|
drop(m);
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_file_maps_to_an_empty_slice_and_a_missing_file_errors() {
|
|
let path = temp_file("empty", b"");
|
|
let m = Mapping::open(&path).unwrap();
|
|
assert!(m.is_empty());
|
|
assert_eq!(m.as_bytes(), &[] as &[u8]);
|
|
drop(m);
|
|
std::fs::remove_file(&path).unwrap();
|
|
assert!(Mapping::open(&path).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn the_mapping_can_be_shared_between_threads() {
|
|
let path = temp_file("threads", &vec![7u8; 100_000]);
|
|
let m = std::sync::Arc::new(Mapping::open(&path).unwrap());
|
|
let handles: Vec<_> = (0..4)
|
|
.map(|_| {
|
|
let m = m.clone();
|
|
std::thread::spawn(move || m.as_bytes().iter().map(|b| u64::from(*b)).sum::<u64>())
|
|
})
|
|
.collect();
|
|
for h in handles {
|
|
assert_eq!(h.join().unwrap(), 700_000);
|
|
}
|
|
drop(m);
|
|
std::fs::remove_file(path).unwrap();
|
|
}
|
|
}
|