Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#pragma once
 
#include <cstddef>
#include <type_traits>
#include <utility>
 
#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 <typename T>
void NarrowToFloat(const T* src, float* dst, size_t count) {
  if constexpr (std::is_same_v<T, MLFloat16>) {
    MlasConvertHalfToFloatBuffer(src, dst, count);
  } else {
    static_assert(std::is_same_v<T, BFloat16>);
    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 <typename T>
void FloatToNarrow(const float* src, T* dst, size_t count) {
  if constexpr (std::is_same_v<T, MLFloat16>) {
    MlasConvertFloatToHalfBuffer(src, dst, count);
  } else {
    static_assert(std::is_same_v<T, BFloat16>);
    FloatToBFloat16(src, dst, count);
  }
}
 
// Type trait: true for MLFloat16 and BFloat16 — the narrow-float types that
// need widen-to-f32 conversion before arithmetic.
template <typename T>
inline constexpr bool is_narrow_float_v = std::is_same_v<T, MLFloat16> ||
                                          std::is_same_v<T, BFloat16>;
 
inline void ConvertNarrowFloatToFloatIfNeeded(
    const Tensor& tensor, AllocatorPtr alloc, IAllocatorUniquePtr<float>& dest, bool& is_packed) {
  const auto tensor_size = static_cast<size_t>(tensor.Shape().Size());
  if (tensor.GetElementType() == utils::ToTensorProtoElementType<MLFloat16>()) {
    auto float_ptr = IAllocator::MakeUniquePtr<float>(alloc, tensor_size, true);
    if (tensor_size > 0) {
      NarrowToFloat(tensor.Data<MLFloat16>(), float_ptr.get(), tensor_size);
    }
    dest = std::move(float_ptr);
    is_packed = true;
  } else if (tensor.GetElementType() == utils::ToTensorProtoElementType<BFloat16>()) {
    auto float_ptr = IAllocator::MakeUniquePtr<float>(alloc, tensor_size, true);
    if (tensor_size > 0) {
      NarrowToFloat(tensor.Data<BFloat16>(), float_ptr.get(), tensor_size);
    }
    dest = std::move(float_ptr);
    is_packed = true;
  }
}
 
}  // namespace onnxruntime