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