[C++] add float16 to c++
Feature Request
Add full IEEE 754 half-precision floating point (float16, binary16) support to Fory/FDL, including a complete C++ runtime implementation that uses a strong type float16_t (internally storing uint16_t bits), plus exhaustive tests for conversion/rounding/NaN/subnormal semantics.
Is your feature request related to a problem? Please describe
We want to use float16 in FDL to reduce payload size and memory footprint and to interoperate with other ecosystems (ML/graphics/etc.) where half precision is common. Currently Fory supports float32/float64 but not float16.
C++ does not have a universally-available standard float16 primitive type (support varies across compilers/architectures). To guarantee portability and consistent cross-language semantics, we need a first-party implementation that:
- stores IEEE 754 binary16 exactly (2 bytes),
- has well-defined IEEE conversion/rounding behavior,
- exposes a single strong type
float16_tin public APIs (no passing rawuint16_tbits around).
Describe the solution you'd like
1) FDL / Type System
- Introduce a new primitive type:
float16. - Treat
float16as a true primitive (likefloat32/float64), usable in:- message fields
- repeated fields
- map values (and optionally keys if numeric keys are allowed; if not allowed today, keep consistent)
- unions (if primitives are allowed)
- Document the exact definition: IEEE 754 binary16 (“half precision”) per: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
2) Wire Format / Serialization Semantics
- Encode
float16as 2 bytes representing the raw IEEE 754 binary16 bit pattern. - Define endianness exactly (match existing float32/float64 endianness rules).
- NaN/Inf/±0/subnormal must round-trip correctly at the bit level.
- If the framework canonicalizes NaNs today for float32/float64, specify whether float16 should:
- preserve payload bits (preferred if feasible), or
- canonicalize to a single quiet NaN pattern (acceptable but must be documented and consistent across languages).
- If the framework canonicalizes NaNs today for float32/float64, specify whether float16 should:
3) C++ Runtime (core requirement): float16_t strong type only
Provide a public strong type float16_t. All runtime APIs must accept/return float16_t only (no uint16_t parameters in public APIs).
3.1 Type definition
- Provide a trivial, standard-layout type:
struct float16_t { uint16_t bits; };
- Storage remains exactly 16 bits (2 bytes), with no heap allocation.
- Provide explicit bit access only via named methods (still returning
uint16_tis OK, but APIs should passfloat16_t):uint16_t to_bits() const;static float16_t from_bits(uint16_t bits);
3.2 Conversions (IEEE 754 compliant)
static float16_t from_float(float f);- Convert float32 -> binary16 using IEEE 754 rules and round-to-nearest, ties-to-even.
- Must correctly handle:
- NaN (produce a NaN in half; preserve payload if feasible, otherwise canonicalize; ensure quiet NaN if required)
- ±Inf
- ±0 (preserve sign)
- normalized values
- subnormals (gradual underflow)
- overflow -> ±Inf
- underflow -> subnormal/±0
float to_float() const;- Convert binary16 -> float32 (exact for all half values).
3.3 Classification (IEEE-consistent)
All take float16_t:
static bool is_nan(float16_t h);static bool is_inf(float16_t h);and/orstatic bool is_inf(float16_t h, int sign);(sign: +1/-1/0)static bool is_zero(float16_t h);(treat +0/-0 as zero)static bool signbit(float16_t h);static bool is_subnormal(float16_t h);static bool is_normal(float16_t h);static bool is_finite(float16_t h);
3.4 Arithmetic (explicit methods)
C++ supports operator overloading, we should add operator overloading, and add explicit functions/methods so semantics are obvious and consistent with other languages:
static float16_t add(float16_t a, float16_t b);static float16_t sub(float16_t a, float16_t b);static float16_t mul(float16_t a, float16_t b);static float16_t div(float16_t a, float16_t b);static float16_t neg(float16_t a);static float16_t abs(float16_t a);
Optional math parity (if needed by users):
sqrt,min,max,copysign,floor,ceil,trunc,round,round_to_even
Implementation rule for arithmetic (unless full half-FPU emulation is desired):
- compute in float32 and round back to half each operation:
return from_float(a.to_float() op b.to_float());
3.5 Comparisons
Provide IEEE-consistent comparisons using float16_t only:
static bool equal(float16_t a, float16_t b);- NaN != NaN
- +0 == -0
static bool less(float16_t a, float16_t b);- if NaN involved => false
static bool less_eq(float16_t a, float16_t b);static bool greater(float16_t a, float16_t b);static bool greater_eq(float16_t a, float16_t b);static int compare(float16_t a, float16_t b);- Define NaN behavior explicitly (unordered). If a total ordering is needed, add:
static int total_order_compare(float16_t a, float16_t b);(optional)
- Define NaN behavior explicitly (unordered). If a total ordering is needed, add:
3.6 Formatting
static std::string to_string(float16_t h);(format viah.to_float())
3.7 Codegen requirement (C++)
- Generated C++ fields for
float16must usefloat16_t, notuint16_t. - Repeated
float16should usestd::vector<float16_t>(or existing Fory container type).
3.8 Serialization boundary (still uses bits, but not in public API)
- Serializer/deserializer should read/write the underlying 16-bit pattern.
- It is acceptable for the codec implementation (internal) to access
h.to_bits()/from_bits(...), but public helper APIs must not take rawuint16_t.
4) Compiler / Reflection Integration
- Update the FDL parser/type system so
float16is treated as a primitive type. - Ensure reflection/dynamic serialization recognizes
float16_tas thefloat16primitive (distinct fromuint16_tinteger). - Clarify schema evolution:
- If
float16 <-> float32evolution is allowed, document conversion behavior/rounding; otherwise enforce strict matching.
- If
5) Codegen & Type Mappings Across Languages
- C++:
float16_tstrong type withuint16_tinternal bits storage and IEEE conversions. - Other languages: implement mappings in future PRs, but wire format must remain IEEE binary16 bits.
6) Tests (must be exhaustive)
-
Conversion tests (C++)
- ±0, ±Inf, NaN
- max finite 65504
- min normal 2^-14
- min subnormal 2^-24
- values around rounding boundaries
- explicit ties-to-even cases (inputs exactly halfway between two representable half values)
- overflow -> Inf, underflow -> subnormal/0
- Optional stress: iterate all 65536 half bit patterns:
h = float16_t::from_bits(bits);h2 = float16_t::from_float(h.to_float());- Verify bit preservation for all non-NaN values; for NaN validate the chosen policy (preserve payload vs canonicalize).
-
Serializer/deserializer tests
- Ensure wire output matches expected 16-bit patterns for known values.
- Round-trip for messages containing float16 fields, repeated float16 fields, maps with float16 values, optional fields, etc.
-
Cross-language golden tests
- Can be implemented in a future PR; must validate binary compatibility and NaN policy consistency.
Describe alternatives you've considered
- Store
float16asfloatin C++ and convert tofloat16only during serialization.
- Rejected: changes in-memory footprint, delays rounding to serialization time, and can produce cross-language semantic differences.
- Rely on compiler-specific half types (
__fp16,_Float16) directly in public APIs.
- Rejected: portability concerns and inconsistent behavior across platforms; we still want a stable
float16_tstrong type withuint16_tstorage.
- Use third-party half libraries.
- Possible, but we prefer a first-party minimal implementation to guarantee exact IEEE behavior, rounding mode, and avoid extra dependencies.
Additional context
#3099
Hi, @chaokunyang, could i take this issue, it will be my first task in getting started with fory!
Great! @VKttZXvC Assigned to you
Hi @chaokunyang and @VKttZXvC, just a polite check in about the project, if it's alright I would love to collaborate with you and work on this issue as my first contribution.
@VKttZXvC Are you still working on it? If not, @Gouharkhalid will take it over
Hey @chaokunyang any updates on this issue, I would like to contribute to this issue.
@Gouharkhalid Assigned to you
Hi @chaokunyang,
I’m interested in contributing to the C++ runtime and noticed this float16 issue. I’ve recently been contributing to Apache GraphAr (incubating) and would like to get more involved with Fury’s C++ side as well.
Since this issue is already assigned to @Gouharkhalid, please let me know if there are related tasks or smaller pieces of the C++ runtime work where I could help. I’d be happy to contribute.
Thanks!
@Gouharkhalid, @shivendra-dev54, I'll ping u both on slack and let's discuss, I've already made an implementation plan and just started on it but would love to collaborate on it in case there are better ideas.