From: Nicolas Patry Date: Fri, 9 May 2025 07:46:35 +0000 (+0200) Subject: Fixing the ml_dtypes potentially missing. (#605) X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=f6f9755793b7a38be0ae30de86db5f9772146fd6;p=safetensors.git Fixing the ml_dtypes potentially missing. (#605) Co-authored-by: Daniel Bershatsky --- diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index be8e94e..2765dc0 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -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(); diff --git a/bindings/python/tests/test_flax_comparison.py b/bindings/python/tests/test_flax_comparison.py index c54241a..ff091a3 100644 --- a/bindings/python/tests/test_flax_comparison.py +++ b/bindings/python/tests/test_flax_comparison.py @@ -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")