blob: 102ad09832c0c9c59263ef761dbc8e6546811df0 [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
5
Matteo Martincighe011d202019-11-28 11:35:47 +00006#include <armnnUtils/FloatingPointConverter.hpp>
arovir01616e7752018-10-01 17:08:59 +01007
Narumol Prangnawarat88325222020-03-06 14:45:57 +00008#include "BFloat16.hpp"
arovir01616e7752018-10-01 17:08:59 +01009#include "Half.hpp"
telsoa01c577f2c2018-08-31 09:22:23 +010010
Jim Flynn39faea82023-09-17 09:02:23 +010011#include <armnn/Exceptions.hpp>
Narumol Prangnawaratac2770a2020-04-01 16:51:23 +010012#include <armnn/utility/Assert.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010013
14namespace armnnUtils
15{
16
17void FloatingPointConverter::ConvertFloat32To16(const float* srcFloat32Buffer,
18 size_t numElements,
19 void* dstFloat16Buffer)
20{
Jim Flynn39faea82023-09-17 09:02:23 +010021 if (srcFloat32Buffer == nullptr)
22 {
23 throw armnn::InvalidArgumentException("ConvertFloat32To16: source float32 buffer pointer is null");
24 }
25 if (dstFloat16Buffer == nullptr)
26 {
27 throw armnn::InvalidArgumentException("ConvertFloat32To16: destination float16 buffer pointer is null");
28 }
telsoa01c577f2c2018-08-31 09:22:23 +010029
Ryan OSheaf4bfa6a2020-06-10 11:33:37 +010030 armnn::Half* pHalf = static_cast<armnn::Half*>(dstFloat16Buffer);
telsoa01c577f2c2018-08-31 09:22:23 +010031
32 for (size_t i = 0; i < numElements; i++)
33 {
34 pHalf[i] = armnn::Half(srcFloat32Buffer[i]);
Narumol Prangnawarat9f62d332023-07-11 16:49:00 +010035 if (isinf(pHalf[i]))
36 {
37 // If the value of converted Fp16 is infinity, round to the closest finite Fp16 value.
38 pHalf[i] = copysign(std::numeric_limits<armnn::Half>::max(), pHalf[i]);
39 }
telsoa01c577f2c2018-08-31 09:22:23 +010040 }
41}
42
43void FloatingPointConverter::ConvertFloat16To32(const void* srcFloat16Buffer,
44 size_t numElements,
45 float* dstFloat32Buffer)
46{
Jim Flynn39faea82023-09-17 09:02:23 +010047 if (srcFloat16Buffer == nullptr)
48 {
49 throw armnn::InvalidArgumentException("ConvertFloat16To32: source float16 buffer pointer is null");
50 }
51 if (dstFloat32Buffer == nullptr)
52 {
53 throw armnn::InvalidArgumentException("ConvertFloat16To32: destination float32 buffer pointer is null");
54 }
telsoa01c577f2c2018-08-31 09:22:23 +010055
Ryan OSheaf4bfa6a2020-06-10 11:33:37 +010056 const armnn::Half* pHalf = static_cast<const armnn::Half*>(srcFloat16Buffer);
telsoa01c577f2c2018-08-31 09:22:23 +010057
58 for (size_t i = 0; i < numElements; i++)
59 {
60 dstFloat32Buffer[i] = pHalf[i];
61 }
62}
63
telsoa01c577f2c2018-08-31 09:22:23 +010064} //namespace armnnUtils