1 /* Copyright 2019 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/lite/delegates/gpu/gl/float16_conversions.h" 17 18 #include <cstdint> 19 #include <variant> 20 #include <vector> 21 22 #include "fp16.h" // from @FP16 23 #include "absl/types/variant.h" 24 #include "tensorflow/lite/delegates/gpu/common/data_type.h" 25 #include "tensorflow/lite/delegates/gpu/common/tensor.h" 26 27 namespace tflite { 28 namespace gpu { 29 namespace gl { 30 namespace { 31 32 // Performs in-place conversion of float32 into float16 ToFloat16(std::vector<uint8_t> * values)33bool ToFloat16(std::vector<uint8_t>* values) { 34 if (values->size() % sizeof(float) != 0) { 35 return false; 36 } 37 38 uint16_t* store_f16 = reinterpret_cast<uint16_t*>(values->data()); 39 const float* load_f32 = reinterpret_cast<const float*>(values->data()); 40 const float* end_load_f32 = 41 reinterpret_cast<const float*>(values->data() + values->size()); 42 43 while (load_f32 != end_load_f32) { 44 *store_f16++ = fp16_ieee_from_fp32_value(*load_f32++); 45 } 46 47 values->resize(values->size() / 2); 48 return true; 49 } 50 51 struct ConverterToFloat16 { operator ()tflite::gpu::gl::__anon916b008b0111::ConverterToFloat1652 bool operator()(ObjectData& data) const { // NOLINT 53 return ToFloat16(&data); 54 } 55 operator ()tflite::gpu::gl::__anon916b008b0111::ConverterToFloat1656 bool operator()(ObjectRef& buffer) const { // NOLINT 57 return true; 58 } 59 }; 60 61 } // namespace 62 MaybeConvertToFloat16(Object * object)63bool MaybeConvertToFloat16(Object* object) { 64 if (object->data_type == DataType::FLOAT32 && 65 std::visit(ConverterToFloat16(), object->object)) { 66 object->data_type = DataType::FLOAT16; 67 return true; 68 } 69 return false; 70 } 71 72 } // namespace gl 73 } // namespace gpu 74 } // namespace tflite 75