Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 : #ifndef BFLOAT16_H
11 : #define BFLOAT16_H
12 :
13 : #include "hifloat.h"
14 :
15 : namespace Adx {
16 : constexpr int32_t BF16_EXPONENT_BIAS = 127U;
17 :
18 : class BFloat16 {
19 : public:
20 : explicit BFloat16(uint16_t v = 0) : val(v) {}
21 :
22 8 : float GetValue() const {
23 8 : if (val == 0xFF80) {
24 1 : return -std::numeric_limits<float>::infinity();
25 7 : } else if (val == 0x7F80) {
26 1 : return std::numeric_limits<float>::infinity();
27 : } else {
28 6 : int32_t symbol = val >= 0x8000 ? -1 : 1;
29 6 : int32_t exponentVal = (val % 0x8000 / 0x0080);
30 6 : float mantissaVal = (val % 0x8000 % 0x0080) / static_cast<float>(0x0080);
31 6 : if ((exponentVal == 0xFF) && (mantissaVal > 0)) {
32 1 : return std::numeric_limits<float>::quiet_NaN();
33 : }
34 5 : float value = 0.0;
35 5 : if (exponentVal == 0) {
36 1 : value = static_cast<float>(symbol * pow(BASE_NUM, 1 - BF16_EXPONENT_BIAS) * mantissaVal);
37 : } else {
38 4 : value = static_cast<float>(symbol * pow(BASE_NUM, exponentVal - BF16_EXPONENT_BIAS) * (mantissaVal + 1));
39 : }
40 5 : return value;
41 : }
42 : }
43 :
44 : private:
45 : uint16_t val;
46 : };
47 : } // namespace Adx
48 :
49 : #endif // BFLOAT16_H
|