1 /* Copyright 2022 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #ifndef TENSORFLOW_PYTHON_LIB_CORE_FLOAT_E4M3B11_H_ 17 #define TENSORFLOW_PYTHON_LIB_CORE_FLOAT_E4M3B11_H_ 18 19 #include <stdint.h> 20 21 #include <cmath> 22 #include <cstring> 23 #include <memory> 24 25 namespace tensorflow { 26 27 uint8_t float_to_float8_e4m3b11(float v); 28 float float8_e4m3b11_to_float(uint8_t v); 29 30 class float8_e4m3b11 { 31 public: 32 // Exponent: 4, Mantissa: 3, bias: 11 float8_e4m3b11()33 float8_e4m3b11() {} float8_e4m3b11(float v)34 float8_e4m3b11(float v) : rep_(float_to_float8_e4m3b11(v)) {} // NOLINT 35 36 operator float() const { // NOLINT: Allow implicit conversion to float, 37 // because it is lossless. 38 return float8_e4m3b11_to_float(rep_); 39 } 40 41 float8_e4m3b11 operator-() const { 42 if ((rep_ & 0x7f) == 0x00) { 43 return *this; 44 } // nan or 0. 45 float8_e4m3b11 result = *this; 46 result.rep_ = result.rep_ ^ 0x80; 47 return result; 48 } 49 rep()50 uint8_t rep() const { return rep_; } 51 FromRep(uint8_t rep)52 static float8_e4m3b11 FromRep(uint8_t rep) { 53 float8_e4m3b11 result; 54 memcpy(&result, &rep, sizeof(float8_e4m3b11)); 55 return result; 56 } 57 58 private: 59 uint8_t rep_; 60 }; 61 62 } // namespace tensorflow 63 64 #endif // TENSORFLOW_PYTHON_LIB_CORE_FLOAT_E4M3B11_H_ 65