Poplar and PopLibs
QuarterFloat.hpp
1// Copyright (c) 2021 Graphcore Ltd. All rights reserved.
2
3#ifndef poplar_QuarterFloat_hpp_
4#define poplar_QuarterFloat_hpp_
5
6#if defined(__IPU__) && defined(__IPU_ARCH_VERSION__) && \
7 __IPU_ARCH_VERSION__ >= 21
8
9#include <ipudef.h>
10
11namespace poplar {
12
13#ifndef __SUPERVISOR__
14inline half toHalf(quarter q, quarter_metadata md) {
15 return quarterToHalf(&q, md);
16}
17
18inline quarter toQuarter(half h, quarter_metadata md) {
19 return halfToQuarter(&h, md);
20}
21#endif // __SUPERVISOR__
22
23} // namespace poplar
24
25#else
26
27// This type does not support any arithmetic operations
28struct quarter {
29 unsigned char value;
30
31 quarter(unsigned x) { value = x; };
32};
33
34typedef struct quarter_metadata {
35 enum format { f143, f152 } fmt;
36 signed char scale;
37} quarter_metadata;
38
39// Some cpp files (example:CastFloatToGf8.cpp) always include ipudef.h
40// To prevent conflict, before including HalfFloat first check if
41// _IPUDEF_H is not defined.
42// __QUARTER_FOR_IPU__ should be defined externally where these declarations
43// are required on Ipu as well as IpuModel
44#if (!defined(__IPU__) && !defined(_IPUDEF_H)) || defined(__QUARTER_FOR_IPU__)
45
46#include <poplar/HalfFloat.hpp>
47
48namespace poplar {
49
50half quarterToHalf(quarter q, quarter_metadata md);
51
52float quarterToFloat(quarter q, quarter_metadata md);
53
54quarter halfToQuarter(half h, quarter_metadata md);
55
56quarter floatToQuarter(float h, quarter_metadata md);
57
58inline half toFloat(quarter q, quarter_metadata md) {
59 return quarterToFloat(q, md);
60}
61
62inline half toHalf(quarter q, quarter_metadata md) {
63 return quarterToHalf(q, md);
64}
65
66template <typename T> inline quarter toQuarter(T val, quarter_metadata md) {
67 return floatToQuarter(val, md);
68}
69
70template <> inline quarter toQuarter<half>(half val, quarter_metadata md) {
71 return floatToQuarter(val, md);
72}
73
74} // namespace poplar
75
76#endif // !defined(_IPUDEF_H)
77
78#endif
79
80typedef unsigned char MetadataType;
81
82namespace poplar {
83
84inline quarter_metadata unpackMetadata(const MetadataType *in) {
85 quarter_metadata out;
86 constexpr auto formatBit = 7;
87 constexpr auto formatBitMask = (1 << formatBit);
88 constexpr auto scaleSignBit = 5;
89 constexpr auto scaleSignBitMask = (1 << scaleSignBit);
90 constexpr auto scaleMask = (1 << (scaleSignBit + 1)) - 1;
91 constexpr auto scaleSignExtendMask = 0xff ^ scaleMask;
92
93 out.fmt =
94 *in & formatBitMask ? quarter_metadata::f143 : quarter_metadata::f152;
95 out.scale = static_cast<char>(*in & scaleMask);
96 if (out.scale & scaleSignBitMask) {
97 out.scale |= scaleSignExtendMask;
98 }
99 return out;
100}
101
102} // namespace poplar
103
104#endif // poplar_QuarterFloat_hpp_
Poplar classes and functions.
Definition: ArrayRef.hpp:14