From e19f55e4bf2e7576eb24447bccfab893759bf263 Mon Sep 17 00:00:00 2001 From: Arseny Kapoulkine Date: Thu, 18 Jan 2024 04:21:01 -0800 Subject: [PATCH] Implement PyTorch support for float8 types (F8_E5M2 and F8_E4M3) (#404) * 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 | 10 ++++++++++ bindings/python/src/lib.rs | 4 ++++ bindings/python/tests/test_pt_comparison.py | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/bindings/python/py_src/safetensors/torch.py b/bindings/python/py_src/safetensors/torch.py index 7fa5967..22915c9 100644 --- a/bindings/python/py_src/safetensors/torch.py +++ b/bindings/python/py_src/safetensors/torch.py @@ -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 diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index ec82e1c..3ea62ff 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -49,6 +49,8 @@ fn prepare(tensor_dict: HashMap) -> PyResult 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 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:?}" diff --git a/bindings/python/tests/test_pt_comparison.py b/bindings/python/tests/test_pt_comparison.py index d4fa0ec..0f3821b 100644 --- a/bindings/python/tests/test_pt_comparison.py +++ b/bindings/python/tests/test_pt_comparison.py @@ -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), -- 2.43.0