]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Adding `slice` `get_dtype()` method to get the dtype directly on slices. (#303)
authorNicolas Patry <patry.nicolas@protonmail.com>
Mon, 31 Jul 2023 14:41:25 +0000 (16:41 +0200)
committerGitHub <noreply@github.com>
Mon, 31 Jul 2023 14:41:25 +0000 (16:41 +0200)
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py

index 92153835a998003acd6795018af34c343ecfbe59..5e56d7a90fcc8b15251e7e86a0f922edad4b634d 100644 (file)
@@ -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<PyObject> {
+        let dtype = self.info.dtype;
+        let dtype: PyObject = format!("{:?}", dtype).into_py(py);
+        Ok(dtype)
+    }
+
     pub fn __getitem__(&self, slices: Slice) -> PyResult<PyObject> {
         let slices: Vec<&PySlice> = match slices {
             Slice::Slice(slice) => vec![slice],
index fb22d288dd9fb971c392822d84b7aef041875570..d2a3878a1c09d50c124d38e2c16cc7de9577c2a4 100644 (file)
@@ -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(),