From: Nicolas Patry Date: Mon, 31 Jul 2023 14:41:25 +0000 (+0200) Subject: Adding `slice` `get_dtype()` method to get the dtype directly on slices. (#303) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=1a65a3fdebcf280ef0ca32934901d3e2ad3b2c65;p=safetensors.git Adding `slice` `get_dtype()` method to get the dtype directly on slices. (#303) --- diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 9215383..5e56d7a 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -693,6 +693,26 @@ impl PySafeSlice { Ok(shape) } + /// Returns the dtype of the full underlying tensor + /// + /// Returns: + /// (`str`): + /// The dtype of the full tensor + /// + /// Example: + /// ```python + /// from safetensors import safe_open + /// + /// with safe_open("model.safetensors", framework="pt", device=0) as f: + /// tslice = f.get_slice("embedding") + /// dtype = tslice.get_dtype() # "F32" + /// ``` + pub fn get_dtype(&self, py: Python) -> PyResult { + let dtype = self.info.dtype; + let dtype: PyObject = format!("{:?}", dtype).into_py(py); + Ok(dtype) + } + pub fn __getitem__(&self, slices: Slice) -> PyResult { let slices: Vec<&PySlice> = match slices { Slice::Slice(slice) => vec![slice], diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index fb22d28..d2a3878 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -207,7 +207,10 @@ class SliceTestCase(unittest.TestCase): def test_deserialization_slice(self): with safe_open(self.local, framework="pt") as f: - tensor = f.get_slice("test")[:, :, 1:2] + _slice = f.get_slice("test") + self.assertEqual(_slice.get_shape(), [1, 2, 3]) + self.assertEqual(_slice.get_dtype(), "F32") + tensor = _slice[:, :, 1:2] self.assertEqual( tensor.numpy().tobytes(),