]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fixing the ml_dtypes potentially missing. (#605)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 9 May 2025 07:46:35 +0000 (09:46 +0200)
committerGitHub <noreply@github.com>
Fri, 9 May 2025 07:46:35 +0000 (09:46 +0200)
Co-authored-by: Daniel Bershatsky <daniel.bershatsky@gmail.com>
bindings/python/src/lib.rs
bindings/python/tests/test_flax_comparison.py

index be8e94e09b58341b230ab8fd32f963590fcdfeea..2765dc09529aea372810acfa99a29029f192a7d6 100644 (file)
@@ -1057,15 +1057,32 @@ fn create_tensor<'a>(
                     .bind(py),
                 false,
             ),
-            _ => (
-                NUMPY_MODULE
-                    .get()
-                    .ok_or_else(|| {
-                        SafetensorError::new_err(format!("Could not find module {framework:?}",))
-                    })?
-                    .bind(py),
-                true,
-            ),
+            frame => {
+                // Attempt to load the frameworks
+                // Those are needed to prepare the ml dtypes
+                // like bfloat16
+                match frame {
+                    Framework::Tensorflow => {
+                        let _ = PyModule::import(py, intern!(py, "tensorflow"));
+                    }
+                    Framework::Flax => {
+                        let _ = PyModule::import(py, intern!(py, "flax"));
+                    }
+                    _ => {}
+                };
+
+                (
+                    NUMPY_MODULE
+                        .get()
+                        .ok_or_else(|| {
+                            SafetensorError::new_err(
+                                format!("Could not find module {framework:?}",),
+                            )
+                        })?
+                        .bind(py),
+                    true,
+                )
+            }
         };
         let dtype: PyObject = get_pydtype(module, dtype, is_numpy)?;
         let count: usize = shape.iter().product();
index c54241ad5c6fb7d0c3744061d35392f6a0f14146..ff091a3242886993a2e81b6208f21dcaf8c2a5e3 100644 (file)
@@ -1,5 +1,6 @@
 import platform
 import unittest
+import sys
 
 
 if platform.system() != "Windows":
@@ -66,3 +67,11 @@ class LoadTestCase(unittest.TestCase):
         for k, v in weights.items():
             tv = flax_weights[k]
             self.assertTrue(jnp.allclose(v, tv))
+
+    def test_loading_without_ml_dtype(self):
+        # This does not work as we cannot unload
+        # modules, copy this into its own file to test.
+        # https://github.com/huggingface/safetensors/issues/598
+        sys.modules.pop("ml_dtypes", None)
+        with safe_open(self.sf_filename, framework="flax") as f:
+            f.get_tensor("test3")