]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Implement PyTorch support for float8 types (F8_E5M2 and F8_E4M3) (#404)
authorArseny Kapoulkine <arseny.kapoulkine@gmail.com>
Thu, 18 Jan 2024 12:21:01 +0000 (04:21 -0800)
committerGitHub <noreply@github.com>
Thu, 18 Jan 2024 12:21:01 +0000 (13:21 +0100)
* Implement PyTorch support for float8 types (F8_E5M2 and F8_E4M3)

Note that PyTorch name for e4m3 type has an extra "fn" prefix to match
MLIR, but the format should be the same ("fn" means "finite").

We also test that -0.5 roundtrips in both formats, which makes sure that
the format is preserved properly - both types are single-byte and have
the same representation for zero, but different representations for
-0.5.

* Transparently support PyTorch before 2.1 by ignoring float8 formats

bindings/python/py_src/safetensors/torch.py
bindings/python/src/lib.rs
bindings/python/tests/test_pt_comparison.py

index 7fa596750e888f13de5c2163a6361dce456b86a6..22915c98a5e002e829c67739499b355c406c9e6d 100644 (file)
@@ -337,6 +337,9 @@ def load(data: bytes) -> Dict[str, torch.Tensor]:
     flat = deserialize(data)
     return _view2torch(flat)
 
+# torch.float8 formats require 2.1; we do not support these dtypes on earlier versions
+_float8_e4m3fn = getattr(torch, "float8_e4m3fn", None)
+_float8_e5m2 = getattr(torch, "float8_e5m2", None)
 
 _SIZE = {
     torch.int64: 8,
@@ -349,6 +352,8 @@ _SIZE = {
     torch.int8: 1,
     torch.bool: 1,
     torch.float64: 8,
+    _float8_e4m3fn: 1,
+    _float8_e5m2: 1,
 }
 
 _TYPES = {
@@ -365,6 +370,8 @@ _TYPES = {
     "I8": torch.int8,
     "U8": torch.uint8,
     "BOOL": torch.bool,
+    "F8_E4M3": _float8_e4m3fn,
+    "F8_E5M2": _float8_e5m2,
 }
 
 
@@ -432,6 +439,9 @@ def _tobytes(tensor: torch.Tensor, name: str) -> bytes:
             torch.int8: np.int8,
             torch.bool: bool,
             torch.float64: np.float64,
+            # XXX: This is ok because both have the same width and byteswap is a no-op anyway
+            _float8_e4m3fn: np.uint8,
+            _float8_e5m2: np.uint8,
         }
         npdtype = NPDTYPES[tensor.dtype]
         # Not in place as that would potentially modify a live running model
index ec82e1cc876eabccf53bde8faed2b56676c22811..3ea62ff1340386f32c55e77ab341e642e4c85e84 100644 (file)
@@ -49,6 +49,8 @@ fn prepare(tensor_dict: HashMap<String, &PyDict>) -> PyResult<HashMap<String, Te
                         "float32" => Some(Dtype::F32),
                         "float64" => Some(Dtype::F64),
                         "bfloat16" => Some(Dtype::BF16),
+                        "float8_e4m3fn" => Some(Dtype::F8_E4M3),
+                        "float8_e5m2" => Some(Dtype::F8_E5M2),
                         dtype_str => {
                             return Err(SafetensorError::new_err(format!(
                                 "dtype {dtype_str} is not covered",
@@ -1016,6 +1018,8 @@ fn get_pydtype(module: &PyModule, dtype: Dtype, is_numpy: bool) -> PyResult<PyOb
                     module.getattr(intern!(py, "bool"))?.into()
                 }
             }
+            Dtype::F8_E4M3 => module.getattr(intern!(py, "float8_e4m3fn"))?.into(),
+            Dtype::F8_E5M2 => module.getattr(intern!(py, "float8_e5m2"))?.into(),
             dtype => {
                 return Err(SafetensorError::new_err(format!(
                     "Dtype not understood: {dtype:?}"
index d4fa0ec641050ca05254873a1baf19ea2609a900..0f3821b8bf0bb7bdf1a682fe4c2099fcd3b55a53 100644 (file)
@@ -64,6 +64,24 @@ class TorchTestCase(unittest.TestCase):
         self.assertTrue(torch.equal(data["test2"], reloaded["test2"]))
         self.assertTrue(torch.equal(data["test3"], reloaded["test3"]))
 
+    def test_odd_dtype_fp8(self):
+        if torch.__version__ < "2.1":
+            return # torch.float8 requires 2.1
+
+        data = {
+            "test1": torch.tensor([-0.5], dtype=torch.float8_e4m3fn),
+            "test2": torch.tensor([-0.5], dtype=torch.float8_e5m2),
+        }
+        local = "./tests/data/out_safe_pt_mmap_small.safetensors"
+
+        save_file(data, local)
+        reloaded = load_file(local)
+        # note: PyTorch doesn't implement torch.equal for float8 so we just compare the single element
+        self.assertEqual(data["test1"].dtype, torch.float8_e4m3fn)
+        self.assertEqual(data["test1"].item(), -0.5)
+        self.assertEqual(data["test2"].dtype, torch.float8_e5m2)
+        self.assertEqual(data["test2"].item(), -0.5)
+
     def test_zero_sized(self):
         data = {
             "test": torch.zeros((2, 0), dtype=torch.float),