From 488d945cc55ae48af70e13b5a351226ef5cc7758 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Tue, 28 Feb 2023 16:19:40 +0100 Subject: [PATCH] Faster GPU Loads ?? (#184) * Faster GPU Loads ?? Beats my expectations. I wonder what I did do to not see this perf bottleneck/improvements. * Pyslice still not fixed on PyO3. * Upgrade PyO3. * Using newer pyo3. * Make benches Windows friendly. --- bindings/python/Cargo.toml | 3 +- bindings/python/benches/test_flax.py | 7 +- bindings/python/benches/test_paddle.py | 7 +- bindings/python/benches/test_pt.py | 19 +- bindings/python/benches/test_tf.py | 7 +- bindings/python/src/lib.rs | 328 ++++--------------------- 6 files changed, 77 insertions(+), 294 deletions(-) diff --git a/bindings/python/Cargo.toml b/bindings/python/Cargo.toml index 5bceff2..a509cae 100644 --- a/bindings/python/Cargo.toml +++ b/bindings/python/Cargo.toml @@ -9,10 +9,9 @@ name = "safetensors_rust" crate-type = ["cdylib"] [dependencies] -pyo3 = { version = "0.17.2", features = ["extension-module"] } +pyo3 = { version = "0.18.1", features = ["extension-module"] } memmap2 = "0.5" serde_json = "1.0" -libloading = "0.7" [dependencies.safetensors] version = "*" diff --git a/bindings/python/benches/test_flax.py b/bindings/python/benches/test_flax.py index f7edc2c..835c94d 100644 --- a/bindings/python/benches/test_flax.py +++ b/bindings/python/benches/test_flax.py @@ -1,3 +1,4 @@ +import os import tempfile import jax.numpy as jnp @@ -38,10 +39,11 @@ def load(filename): def test_flax_flax_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: serialized = msgpack_serialize(weights) f.write(serialized) result = benchmark(load, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] @@ -51,9 +53,10 @@ def test_flax_flax_load(benchmark): def test_flax_sf_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] diff --git a/bindings/python/benches/test_paddle.py b/bindings/python/benches/test_paddle.py index ed98830..0c49f1e 100644 --- a/bindings/python/benches/test_paddle.py +++ b/bindings/python/benches/test_paddle.py @@ -1,3 +1,4 @@ +import os import tempfile import numpy as np @@ -32,9 +33,10 @@ def create_gpt2(n_layers: int): def test_paddle_paddle_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: paddle.save(weights, f.name) result = benchmark(paddle.load, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] @@ -44,9 +46,10 @@ def test_paddle_paddle_load(benchmark): def test_paddle_sf_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] diff --git a/bindings/python/benches/test_pt.py b/bindings/python/benches/test_pt.py index 7e50c4c..ea67705 100644 --- a/bindings/python/benches/test_pt.py +++ b/bindings/python/benches/test_pt.py @@ -1,3 +1,4 @@ +import os import tempfile import pytest @@ -32,9 +33,10 @@ def create_gpt2(n_layers: int): def test_pt_pt_load_cpu(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: torch.save(weights, f) result = benchmark(torch.load, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] @@ -44,9 +46,10 @@ def test_pt_pt_load_cpu(benchmark): def test_pt_sf_load_cpu(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] @@ -57,9 +60,10 @@ def test_pt_sf_load_cpu(benchmark): def test_pt_pt_load_gpu(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: torch.save(weights, f) result = benchmark(torch.load, f.name, map_location="cuda:0") + os.unlink(f.name) for k, v in weights.items(): v = v.cuda() @@ -71,9 +75,10 @@ def test_pt_pt_load_gpu(benchmark): def test_pt_sf_load_gpu(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name, device="cuda:0") + os.unlink(f.name) for k, v in weights.items(): v = v.cuda() @@ -85,9 +90,10 @@ def test_pt_sf_load_gpu(benchmark): def test_pt_pt_load_mps(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: torch.save(weights, f) result = benchmark(torch.load, f.name, map_location="mps") + os.unlink(f.name) for k, v in weights.items(): v = v.to(device="mps") @@ -99,9 +105,10 @@ def test_pt_pt_load_mps(benchmark): def test_pt_sf_load_mps(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name, device="mps") + os.unlink(f.name) for k, v in weights.items(): v = v.to(device="mps") diff --git a/bindings/python/benches/test_tf.py b/bindings/python/benches/test_tf.py index a3fcc14..d81effd 100644 --- a/bindings/python/benches/test_tf.py +++ b/bindings/python/benches/test_tf.py @@ -1,3 +1,4 @@ +import os import tempfile import h5py @@ -54,9 +55,10 @@ def create_gpt2(n_layers: int): def test_tf_tf_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: _save(f.name, weights) result = benchmark(_load, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] @@ -66,9 +68,10 @@ def test_tf_tf_load(benchmark): def test_tf_sf_load(benchmark): # benchmark something weights = create_gpt2(12) - with tempfile.NamedTemporaryFile() as f: + with tempfile.NamedTemporaryFile(delete=False) as f: save_file(weights, f.name) result = benchmark(load_file, f.name) + os.unlink(f.name) for k, v in weights.items(): tv = result[k] diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 012c70e..0e4624d 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -1,6 +1,5 @@ #![deny(missing_docs)] //! Dummy doc -use libloading::{Library, Symbol}; use memmap2::{Mmap, MmapOptions}; use pyo3::exceptions::{PyException, PyFileNotFoundError}; use pyo3::once_cell::GILOnceCell; @@ -18,25 +17,10 @@ use std::ops::Bound; use std::path::PathBuf; use std::sync::Arc; -#[repr(C)] -enum cudaMemcpyKind { - _HostToHost = 0, - HostToDevice = 1, - _DeviceToHost = 2, - _Default = 3, -} - -type MemcpyFn = unsafe extern "C" fn( - dst: *mut std::ffi::c_void, - src: *const std::ffi::c_void, - count: usize, - kind: cudaMemcpyKind, -) -> std::ffi::c_uint; static TORCH_MODULE: GILOnceCell> = GILOnceCell::new(); static NUMPY_MODULE: GILOnceCell> = GILOnceCell::new(); static TENSORFLOW_MODULE: GILOnceCell> = GILOnceCell::new(); static FLAX_MODULE: GILOnceCell> = GILOnceCell::new(); -static CUDA_MEMCPY: GILOnceCell>> = GILOnceCell::new(); fn prepare(tensor_dict: HashMap) -> PyResult>> { let mut tensors = HashMap::new(); @@ -276,154 +260,6 @@ impl IntoPy for Device { } } -fn create_empty_tensor_pt<'a>( - module: &'a PyModule, - shape: &[usize], - dtype: Dtype, - device: &Device, -) -> PyResult<&'a PyAny> { - let py = module.py(); - let shape = shape.to_vec(); - let empty = module.getattr(intern!(py, "empty"))?; - let dtype: PyObject = get_pydtype(module, dtype)?; - let shape: PyObject = shape.into_py(py); - let device: PyObject = device.clone().into_py(py); - let kwargs = [ - (intern!(py, "dtype"), dtype), - (intern!(py, "device"), device), - ] - .into_py_dict(py); - let tensor = empty.call((shape,), Some(kwargs))?; - - Ok(tensor) -} - -fn find_cudart(module: &PyModule) -> Option { - let var = std::env::var("SAFETENSORS_FAST_GPU").ok()?; - if var != "1" { - return None; - } - - let path: PyResult = module - .getattr(intern!(module.py(), "_C")) - .ok()? - .getattr(intern!(module.py(), "__file__")) - .ok()? - .extract(); - - #[cfg(not(target_os = "windows"))] - let lib = { - let path = path.ok()?; - // SAFETY: This is unsafe because the library might run arbitrary code - // So it's really important to make sure we are targeting the correct - // library. - unsafe { Library::new(path).ok()? } - }; - - #[cfg(target_os = "windows")] - let lib = { - let mut path = path.ok()?; - path.pop(); - path.push("lib"); - let paths = std::fs::read_dir(path).ok()?; - let cudart_paths: Vec<_> = paths - .into_iter() - .filter_map(|p| { - let p = p.ok()?.path(); - let filename = p.file_name()?.to_string_lossy(); - if filename.starts_with("cudart") { - Some(p) - } else { - None - } - }) - .collect(); - let cudart_path = cudart_paths.get(0)?; - Library::from(libloading::os::windows::Library::open_already_loaded(cudart_path).ok()?) - }; - - Some(lib) -} - -fn find_cuda_memcpy<'py>(module: &PyModule) -> Option> { - let cudart = find_cudart(module)?; - // Leaking the library so that the reference becomes static - let cudart = Box::leak(Box::new(cudart)); - // SAFETY: This is unsafe because the library might run arbitrary code - // So it's really important to make sure we are targeting the correct - // library. - let cuda_memcpy = unsafe { cudart.get(b"cudaMemcpy").ok() }; - cuda_memcpy -} - -fn create_cuda_unsafe_tensor( - module: &PyModule, - cuda_memcpy: &Symbol, - info: &TensorInfo, - device: &Device, - data: &[u8], -) -> PyResult { - let tensor = create_empty_tensor_pt(module, &info.shape, info.dtype, device)?; - - let data_ptr_fn = tensor.getattr("data_ptr")?; - let data_ptr: usize = data_ptr_fn.call0()?.extract()?; - check_cuda(cuda_memcpy, data_ptr, data, module); - let tensor: PyObject = tensor.into_py(module.py()); - Ok(tensor) -} - -fn check_cuda(cuda_memcpy: &Symbol, dst: usize, src: &[u8], module: &PyModule) { - let dst = dst as *mut std::ffi::c_void; - let count = src.len(); - let src_ptr = src.as_ptr() as *const std::ffi::c_void; - // SAFETY: Here we have a correct library, we successfully called memcpy, - // but somehow the call failed. This is really worrying since Pytorch is - // responsible for allocating the memory. - let out = unsafe { cuda_memcpy(dst, src_ptr, count, cudaMemcpyKind::HostToDevice) }; - if out != 0 { - let string = match get_error_string(module, out) { - Ok(string) => string, - Err(_) => format!("{out}"), - }; - println!( - "We tried to set your tensor fast, but there was a cuda error, This could have corrupted your GPU ram, aborting to prevent further errors {string:?}" - ); - std::process::abort(); - } -} - -fn create_cuda_unsafe_tensor_from_slice( - module: &PyModule, - cuda_memcpy: &Symbol, - shape: &[usize], - dtype: Dtype, - device: &Device, - iterator: safetensors::slice::SliceIterator, -) -> PyResult { - let tensor = create_empty_tensor_pt(module, shape, dtype, device)?; - - let mut offset = 0; - let data_ptr_fn = tensor.getattr("data_ptr")?; - let data_ptr: usize = data_ptr_fn.call0()?.extract()?; - for slice in iterator { - let len = slice.len(); - check_cuda(cuda_memcpy, data_ptr + offset, slice, module); - offset += len; - } - let tensor: PyObject = tensor.into_py(module.py()); - Ok(tensor) -} - -fn get_error_string(module: &PyModule, out: u32) -> PyResult { - module - .getattr(intern!(module.py(), "cuda"))? - .getattr(intern!(module.py(), "CudaError"))? - .call1((out.into_py(module.py()),))? - .getattr(intern!(module.py(), "__str__"))? - .call0()? - .extract() -} - enum Storage { Mmap(Mmap), /// Torch specific mmap @@ -518,15 +354,11 @@ impl Open { } }; - if let (Device::Cuda(_), Framework::Pytorch) = (&device, &framework) { - let module: &PyModule = get_module(py, &TORCH_MODULE)?; - CUDA_MEMCPY.get_or_init(py, || find_cuda_memcpy(module)); - } Ok(()) })?; - let storage = match (&framework, &device) { - (Framework::Pytorch, Device::Cpu) => Python::with_gil(|py| -> PyResult { + let storage = match &framework { + Framework::Pytorch => Python::with_gil(|py| -> PyResult { let module = get_module(py, &TORCH_MODULE)?; let version: String = module.getattr(intern!(py, "__version__"))?.extract()?; @@ -622,26 +454,15 @@ impl Open { let data = &mmap[info.data_offsets.0 + self.offset..info.data_offsets.1 + self.offset]; - Python::with_gil(|py| -> PyResult { - match (&self.device, &self.framework, CUDA_MEMCPY.get(py)) { - (Device::Cuda(_), Framework::Pytorch, Some(Some(cuda_memcpy))) => { - let module = get_module(py, &TORCH_MODULE)?; - create_cuda_unsafe_tensor(module, cuda_memcpy, info, &self.device, data) - } - _ => { - let array: PyObject = - Python::with_gil(|py| PyByteArray::new(py, data).into_py(py)); - - create_tensor( - &self.framework, - info.dtype, - &info.shape, - array, - &self.device, - ) - } - } - }) + let array: PyObject = Python::with_gil(|py| PyByteArray::new(py, data).into_py(py)); + + create_tensor( + &self.framework, + info.dtype, + &info.shape, + array, + &self.device, + ) } Storage::TorchStorage(storage) => { Python::with_gil(|py| -> PyResult { @@ -655,7 +476,7 @@ impl Open { let start = (info.data_offsets.0 + self.offset) as isize; let stop = (info.data_offsets.1 + self.offset) as isize; - let slice = pyslice_new(py, start, stop, 1); + let slice = PySlice::new(py, start, stop, 1); let storage: &PyObject = storage .get(py) .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; @@ -665,13 +486,20 @@ impl Open { .getattr(intern!(py, "__getitem__"))? .call1((slice,))?; - let tensor = torch + let mut tensor = torch .getattr(intern!(py, "asarray"))? .call((storage_slice,), Some(kwargs))? .getattr(intern!(py, "view"))? .call((), Some(view_kwargs))? .getattr(intern!(py, "reshape"))? .call1((shape,))?; + if self.device != Device::Cpu { + let device: PyObject = self.device.clone().into_py(py); + let kwargs = PyDict::new(py); + tensor = tensor + .getattr(intern!(py, "to"))? + .call((device,), Some(kwargs))?; + } Ok(tensor.into_py(py)) // torch.asarray(storage[start + n : stop + n], dtype=torch.uint8).view(dtype=dtype).reshape(shape) }) @@ -812,49 +640,10 @@ impl safe_open { } pub fn __enter__(slf: Py) -> Py { - // SAFETY: This code is extremely important to the GPU fast load. - // Cuda uses a context to select the device you are writing on. - // PyTorch uses this function to create and use said context. - // Without this, we instantiate the empty buffer on the correct GPU - // But we fail to override the proper memory location since the context - // is removed by python. - // Using this sets the Cuda context once and for all for the entirety - // of the context manager lifecycle. - Python::with_gil(|py| -> PyResult<()> { - let _self: &safe_open = &slf.borrow(py); - let inner = _self.inner()?; - if let (Device::Cuda(_), Framework::Pytorch) = (&inner.device, &inner.framework) { - let module = get_module(py, &TORCH_MODULE)?; - let device: PyObject = inner.device.clone().into_py(py); - let torch_device = module - .getattr(intern!(py, "cuda"))? - .getattr(intern!(py, "device"))?; - let lock = torch_device.call1((device,))?; - lock.call_method0(intern!(py, "__enter__"))?; - } - Ok(()) - }) - .ok(); slf } pub fn __exit__(&mut self, _exc_type: PyObject, _exc_value: PyObject, _traceback: PyObject) { - if let Some(inner) = &self.inner { - if let (Device::Cuda(_), Framework::Pytorch) = (&inner.device, &inner.framework) { - Python::with_gil(|py| -> PyResult<()> { - let module = get_module(py, &TORCH_MODULE)?; - let device: PyObject = inner.device.clone().into_py(py); - let torch_device = module - .getattr(intern!(py, "cuda"))? - .getattr(intern!(py, "device"))?; - let none = py.None(); - let lock = torch_device.call1((device,))?; - lock.call_method1(intern!(py, "__exit__"), (&none, &none, &none))?; - Ok(()) - }) - .ok(); - } - } self.inner = None; } } @@ -930,40 +719,25 @@ impl PySafeSlice { let mut offset = 0; let length = iterator.remaining_byte_len(); - Python::with_gil( - |py| match (&self.device, &self.framework, CUDA_MEMCPY.get(py)) { - (Device::Cuda(_), Framework::Pytorch, Some(Some(cuda_memcpy))) => { - let module = get_module(py, &TORCH_MODULE)?; - create_cuda_unsafe_tensor_from_slice( - module, - cuda_memcpy, - &newshape, - self.info.dtype, - &self.device, - iterator, - ) - } - _ => { - let array: PyObject = - PyByteArray::new_with(py, length, |bytes: &mut [u8]| { - for slice in iterator { - let len = slice.len(); - bytes[offset..offset + slice.len()].copy_from_slice(slice); - offset += len; - } - Ok(()) - })? - .into_py(py); - create_tensor( - &self.framework, - self.info.dtype, - &newshape, - array, - &self.device, - ) - } - }, - ) + Python::with_gil(|py| { + let array: PyObject = + PyByteArray::new_with(py, length, |bytes: &mut [u8]| { + for slice in iterator { + let len = slice.len(); + bytes[offset..offset + slice.len()].copy_from_slice(slice); + offset += len; + } + Ok(()) + })? + .into_py(py); + create_tensor( + &self.framework, + self.info.dtype, + &newshape, + array, + &self.device, + ) + }) } Storage::TorchStorage(storage) => Python::with_gil(|py| -> PyResult { let torch = get_module(py, &TORCH_MODULE)?; @@ -976,7 +750,7 @@ impl PySafeSlice { let start = (self.info.data_offsets.0 + self.offset) as isize; let stop = (self.info.data_offsets.1 + self.offset) as isize; - let slice = pyslice_new(py, start, stop, 1); + let slice = PySlice::new(py, start, stop, 1); let storage: &PyObject = storage .get(py) .ok_or_else(|| SafetensorError::new_err("Could not find storage"))?; @@ -987,7 +761,7 @@ impl PySafeSlice { .call1((slice,))?; let slices = slices.into_py(py); - let tensor = torch + let mut tensor = torch .getattr(intern!(py, "asarray"))? .call((storage_slice,), Some(kwargs))? .getattr(intern!(py, "view"))? @@ -996,25 +770,19 @@ impl PySafeSlice { .call1((shape,))? .getattr(intern!(py, "__getitem__"))? .call1((slices,))?; + if self.device != Device::Cpu { + let device: PyObject = self.device.clone().into_py(py); + let kwargs = PyDict::new(py); + tensor = tensor + .getattr(intern!(py, "to"))? + .call((device,), Some(kwargs))?; + } Ok(tensor.into_py(py)) }), } } } -// TODO Remove this once https://github.com/PyO3/pyo3/issues/2768 is released -fn pyslice_new(py: Python<'_>, start: isize, stop: isize, step: isize) -> &PySlice { - let slice: &PySlice = unsafe { - let ptr = pyo3::ffi::PySlice_New( - pyo3::ffi::PyLong_FromSsize_t(start), - pyo3::ffi::PyLong_FromSsize_t(stop), - pyo3::ffi::PyLong_FromSsize_t(step), - ); - py.from_owned_ptr(ptr) - }; - slice -} - fn get_module<'a>( py: Python<'a>, cell: &'static GILOnceCell>, -- 2.43.0