1 | /* Copyright 2015 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 | #include "tensorflow/core/framework/bfloat16.h" |
17 | |
18 | #include "third_party/eigen3/Eigen/Core" |
19 | |
20 | namespace tensorflow { |
21 | |
22 | void RoundFloatToBFloat16(const float* src, bfloat16* dst, int64_t size) { |
23 | Eigen::Map<const Eigen::ArrayXf> src_eigen(src, size); |
24 | Eigen::Map<Eigen::Array<bfloat16, Eigen::Dynamic, 1>> dst_eigen(dst, size); |
25 | dst_eigen = src_eigen.cast<bfloat16>(); |
26 | } |
27 | |
28 | void FloatToBFloat16(const float* src, bfloat16* dst, int64_t size) { |
29 | for (; size != 0; src++, dst++, size--) { |
30 | #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ |
31 | memcpy(dst, src, sizeof(bfloat16)); |
32 | #else |
33 | memcpy( |
34 | dst, |
35 | reinterpret_cast<const char*>(src) + sizeof(float) - sizeof(bfloat16), |
36 | sizeof(bfloat16)); |
37 | #endif |
38 | } |
39 | } |
40 | |
41 | void BFloat16ToFloat(const bfloat16* src, float* dst, int64_t size) { |
42 | Eigen::Map<const Eigen::Array<bfloat16, Eigen::Dynamic, 1>> src_eigen(src, |
43 | size); |
44 | Eigen::Map<Eigen::ArrayXf> dst_eigen(dst, size); |
45 | dst_eigen = src_eigen.cast<float>(); |
46 | } |
47 | |
48 | } // end namespace tensorflow |
49 | |