]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Supporting bfloat16 for tensorflow + jax (was failing because of (#382)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 17 Nov 2023 13:31:47 +0000 (14:31 +0100)
committerGitHub <noreply@github.com>
Fri, 17 Nov 2023 13:31:47 +0000 (14:31 +0100)
intermediary numpy).

bindings/python/py_src/safetensors/flax.py
bindings/python/py_src/safetensors/tensorflow.py
bindings/python/src/lib.rs
bindings/python/tests/test_flax_comparison.py
bindings/python/tests/test_tf_comparison.py

index 906ae02c7246b7607231301d540ee0b53de752a0..208264ab020cd05a31d1db8af6ee5fc2f005d436 100644 (file)
@@ -5,7 +5,7 @@ import numpy as np
 
 import jax.numpy as jnp
 from jax import Array
-from safetensors import numpy
+from safetensors import numpy, safe_open
 
 
 def save(tensors: Dict[str, Array], metadata: Optional[Dict[str, str]] = None) -> bytes:
@@ -122,8 +122,11 @@ def load_file(filename: Union[str, os.PathLike]) -> Dict[str, Array]:
     loaded = load_file(file_path)
     ```
     """
-    flat = numpy.load_file(filename)
-    return _np2jnp(flat)
+    result = {}
+    with safe_open(filename, framework="flax") as f:
+        for k in f.keys():
+            result[k] = f.get_tensor(k)
+    return result
 
 
 def _np2jnp(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, Array]:
index 96b704f16c2b6e904ee1710e9c68e8940868ad5c..6b0cbf28b9fd8eb41c298b06fb174318a5fda433 100644 (file)
@@ -4,7 +4,7 @@ from typing import Dict, Optional, Union
 import numpy as np
 import tensorflow as tf
 
-from safetensors import numpy
+from safetensors import numpy, safe_open
 
 
 def save(tensors: Dict[str, tf.Tensor], metadata: Optional[Dict[str, str]] = None) -> bytes:
@@ -121,8 +121,11 @@ def load_file(filename: Union[str, os.PathLike]) -> Dict[str, tf.Tensor]:
     loaded = load_file(file_path)
     ```
     """
-    flat = numpy.load_file(filename)
-    return _np2tf(flat)
+    result = {}
+    with safe_open(filename, framework="tf") as f:
+        for k in f.keys():
+            result[k] = f.get_tensor(k)
+    return result
 
 
 def _np2tf(numpy_dict: Dict[str, np.ndarray]) -> Dict[str, tf.Tensor]:
index d088c2776077599ca07e0123fc22df8469d156e4..f44915cc2ce254554813cd57064c4fd848d38c1e 100644 (file)
@@ -962,7 +962,16 @@ fn get_pydtype(module: &PyModule, dtype: Dtype, is_numpy: bool) -> PyResult<PyOb
         let dtype: PyObject = match dtype {
             Dtype::F64 => module.getattr(intern!(py, "float64"))?.into(),
             Dtype::F32 => module.getattr(intern!(py, "float32"))?.into(),
-            Dtype::BF16 => module.getattr(intern!(py, "bfloat16"))?.into(),
+            Dtype::BF16 => {
+                if is_numpy {
+                    module
+                        .getattr(intern!(py, "dtype"))?
+                        .call1(("bfloat16",))?
+                        .into()
+                } else {
+                    module.getattr(intern!(py, "bfloat16"))?.into()
+                }
+            }
             Dtype::F16 => module.getattr(intern!(py, "float16"))?.into(),
             Dtype::U64 => module.getattr(intern!(py, "uint64"))?.into(),
             Dtype::I64 => module.getattr(intern!(py, "int64"))?.into(),
index fcb0db5d2074357d63d86285773f5c923056ec77..23d6c4bbfca5ad90a7411945f4170d39d1fec839 100644 (file)
@@ -1,8 +1,6 @@
 import platform
 import unittest
 
-import numpy as np
-
 
 if platform.system() != "Windows":
     # This platform is not supported, we don't want to crash on import
@@ -21,6 +19,7 @@ class LoadTestCase(unittest.TestCase):
             "test": jnp.zeros((1024, 1024), dtype=jnp.float32),
             "test2": jnp.zeros((1024, 1024), dtype=jnp.float32),
             "test3": jnp.zeros((1024, 1024), dtype=jnp.float32),
+            "test4": jnp.zeros((1024, 1024), dtype=jnp.bfloat16),
         }
         self.flax_filename = "./tests/data/flax_load.msgpack"
         self.sf_filename = "./tests/data/flax_load.safetensors"
@@ -51,7 +50,7 @@ class LoadTestCase(unittest.TestCase):
 
         for k, v in weights.items():
             tv = flax_weights[k]
-            self.assertTrue(np.allclose(v, tv))
+            self.assertTrue(jnp.allclose(v, tv))
 
     def test_deserialization_safe_open(self):
         weights = {}
@@ -65,4 +64,4 @@ class LoadTestCase(unittest.TestCase):
 
         for k, v in weights.items():
             tv = flax_weights[k]
-            self.assertTrue(np.allclose(v, tv))
+            self.assertTrue(jnp.allclose(v, tv))
index bdaae0612b314d1cd81f954bd79e428373961273..ac41e6f616d2743dada375297d0423bf4f5cfd1c 100644 (file)
@@ -62,6 +62,20 @@ class SafeTestCase(unittest.TestCase):
             tv = tf_weights[k]
             self.assertTrue(np.allclose(v, tv))
 
+    def test_bfloat16(self):
+        data = {
+            "test": tf.zeros((1024, 1024), dtype=tf.bfloat16),
+        }
+        save_file(data, self.sf_filename)
+        weights = {}
+        with safe_open(self.sf_filename, framework="tf") as f:
+            for k in f.keys():
+                weights[k] = f.get_tensor(k)
+
+        for k, v in weights.items():
+            tv = data[k]
+            self.assertTrue(tf.experimental.numpy.allclose(v, tv))
+
     def test_deserialization_safe_open(self):
         weights = {}
         with safe_open(self.sf_filename, framework="tf") as f: