| 102 | } |
| 103 | |
| 104 | void Fp8E5M2::SetFloat(float f) |
| 105 | { |
| 106 | FloatCast fp32 = {.f = f}; |
| 107 | data = {.byte = 0}; |
| 108 | // Set sign bit. |
| 109 | data.components.sign = fp32.components.sign; |
| 110 | |
| 111 | // If f is nan or inf, set exponent to all 1's. |
| 112 | if (std::isnan(f)) { |
| 113 | data.components.exponent = (0x1 << fp8ExponentBits) - 1; |
| 114 | data.components.mantissa = 1; |
| 115 | } else if (std::isinf(f)) { |
| 116 | data.components.exponent = (0x1 << fp8ExponentBits) - 1; |
| 117 | data.components.mantissa = 0; |
| 118 | } else if (f == 0) { |
| 119 | data.components.exponent = 0; |
| 120 | data.components.mantissa = 0; |
| 121 | } else { |
| 122 | int32_t unbiasedExponent = fp32.components.exponent - fp32ExponentBias; |
| 123 | // Float is normal or denormal, check the exponent and set it. |
| 124 | // For now, we throw on over/underflows. There are alternative ways to handle |
| 125 | // this (round to zero). |
| 126 | if (unbiasedExponent > fp8ExponentBias) { |
| 127 | throw std::range_error("Fp8E5M2 SetFloat exponent overflow."); |
| 128 | } else if (unbiasedExponent < (-1 * fp8ExponentBias - int32_t(fp8MantissaBits) + 1)) { |
| 129 | throw std::range_error("Fp8E5M2 SetFloat exponent underflow."); |
| 130 | } |
| 131 | HandleFp32ToFp8ExponentMantissa<Fp8E5M2, Fp8E5M2::Cast>(data, fp32); |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | void Fp8E4M3FN::SetFloat(float f) |
| 136 | { |