// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include #include #include #include "core/common/float16.h" #include "core/framework/allocator.h" #include "core/framework/tensor.h" #include "core/mlas/inc/mlas.h" namespace onnxruntime { // Batch-convert a narrow float (MLFloat16 or BFloat16) buffer to f32. // MLFloat16 uses the optimised MLAS vectorised path; BFloat16 uses a portable // scalar loop (upper 16 bits → f32, no hardware bf16 instructions). template void NarrowToFloat(const T* src, float* dst, size_t count) { if constexpr (std::is_same_v) { MlasConvertHalfToFloatBuffer(src, dst, count); } else { static_assert(std::is_same_v); BFloat16ToFloat(src, dst, count); } } // Batch-convert f32 back to a narrow float (MLFloat16 or BFloat16) buffer. // MLFloat16 uses the MLAS vectorised path; BFloat16 uses a portable scalar // round-to-nearest-even loop (no hardware bf16 instructions on AVX2). template void FloatToNarrow(const float* src, T* dst, size_t count) { if constexpr (std::is_same_v) { MlasConvertFloatToHalfBuffer(src, dst, count); } else { static_assert(std::is_same_v); FloatToBFloat16(src, dst, count); } } // Type trait: true for MLFloat16 and BFloat16 — the narrow-float types that // need widen-to-f32 conversion before arithmetic. template inline constexpr bool is_narrow_float_v = std::is_same_v || std::is_same_v; inline void ConvertNarrowFloatToFloatIfNeeded( const Tensor& tensor, AllocatorPtr alloc, IAllocatorUniquePtr& dest, bool& is_packed) { const auto tensor_size = static_cast(tensor.Shape().Size()); if (tensor.GetElementType() == utils::ToTensorProtoElementType()) { auto float_ptr = IAllocator::MakeUniquePtr(alloc, tensor_size, true); if (tensor_size > 0) { NarrowToFloat(tensor.Data(), float_ptr.get(), tensor_size); } dest = std::move(float_ptr); is_packed = true; } else if (tensor.GetElementType() == utils::ToTensorProtoElementType()) { auto float_ptr = IAllocator::MakeUniquePtr(alloc, tensor_size, true); if (tensor_size > 0) { NarrowToFloat(tensor.Data(), float_ptr.get(), tensor_size); } dest = std::move(float_ptr); is_packed = true; } } } // namespace onnxruntime