diff --git a/ext/CUDACoreExt/conversion.jl b/ext/CUDACoreExt/conversion.jl index 39f02e2..809357b 100644 --- a/ext/CUDACoreExt/conversion.jl +++ b/ext/CUDACoreExt/conversion.jl @@ -41,7 +41,7 @@ using Microfloats using Microfloats: Microfloat, cvt, cvt_generic, cvt_twiddle, cvt_lanes, - OverflowPolicy, Saturating, BFloat16, bitwidth, + OverflowPolicy, Saturating, BFloat16, raw_bits, from_raw_bits, throw_negative_unsigned, throw_no_nan, Float8_E4M3FN, Float8_E5M2, Float8_E8M0FNU, Float6_E2M3FN, Float6_E3M2FN, Float4_E2M1FN @@ -164,18 +164,16 @@ end # nibble per lane in a single byte, which is `NVector{T,2}`. @inline narrow_lanes(::Type{T}, ::Val{false}, bits::UInt16) where T = - (reinterpret(T, bits % UInt8), reinterpret(T, (bits >> 8) % UInt8)) + (from_raw_bits(T, bits % UInt8), from_raw_bits(T, (bits >> 8) % UInt8)) @inline narrow_lanes(::Type{T}, ::Val{true}, bits::UInt16) where T = - (reinterpret(T, (bits % UInt8) & 0x0f), reinterpret(T, (bits % UInt8) >> 4)) + (from_raw_bits(T, (bits % UInt8) & 0x0f), from_raw_bits(T, (bits % UInt8) >> 4)) -# Sources may carry set bits above the format's width (they are ignored by -# every Microfloats operation), while the hardware requires them to be zero. -@inline lane_bits(x::T) where T<:Microfloat = - reinterpret(UInt8, x) & (0xff >> (8 - bitwidth(T))) +# `raw_bits` clears any bits above the format's width, which the hardware +# requires to be zero. @inline narrow_pair(::Val{false}, lo::Microfloat, hi::Microfloat) = - UInt16(lane_bits(lo)) | (UInt16(lane_bits(hi)) << 8) + UInt16(raw_bits(lo)) | (UInt16(raw_bits(hi)) << 8) @inline narrow_pair(::Val{true}, lo::Microfloat, hi::Microfloat) = - UInt16(lane_bits(lo) | (lane_bits(hi) << 4)) + UInt16(raw_bits(lo) | (raw_bits(hi) << 4)) const Half = Union{Float16,BFloat16} @inline half_pair(lo::H, hi::H) where H<:Half = diff --git a/src/Microfloat.jl b/src/Microfloat.jl index 9997cce..88705d4 100644 --- a/src/Microfloat.jl +++ b/src/Microfloat.jl @@ -6,6 +6,10 @@ import Base: signbit, exponent Abstract supertype for byte-sized floating-point numbers. Concrete subtypes are 8-bit primitive types declared via [`@microfloat`](@ref). +A type narrower than 8 bits keeps its value in the low bits of the byte. +Operations ignore the bits above, which `reinterpret` can set, and never set +them themselves. `===` alone still compares the whole byte. + # Examples ```jldoctest julia> Float8_E4M3 <: Microfloat @@ -21,13 +25,22 @@ sign_mask(::Type{T}) where T<:Microfloat = UInt8((0x01 << sign_bits(T) - 0x01) < exponent_mask(::Type{T}) where T<:Microfloat = UInt8((0x01 << exponent_bits(T) - 0x01) << significand_bits(T)) significand_mask(::Type{T}) where T<:Microfloat = UInt8(0x01 << significand_bits(T) - 0x01) -Base.reinterpret(::Type{Unsigned}, x::Microfloat) = reinterpret(UInt8, x) +value_mask(::Type{T}) where T<:Microfloat = 0xff >> (8 - bitwidth(T)) + +# A microfloat's value is the low `bitwidth(T)` bits of its byte. The bits +# above it can be set by `reinterpret(T, ::UInt8)`, so every operation reads +# values through `raw_bits`, which ignores them, and builds values through +# `from_raw_bits` from bits that fit the width. +raw_bits(x::T) where T<:Microfloat = reinterpret(UInt8, x) & value_mask(T) +from_raw_bits(::Type{T}, bits::UInt8) where T<:Microfloat = reinterpret(T, bits) + +Base.reinterpret(::Type{Unsigned}, x::Microfloat) = raw_bits(x) -signbit(x::Microfloat) = sign_bits(typeof(x)) > 0 && !iszero(reinterpret(Unsigned, x) & sign_mask(typeof(x))) +signbit(x::Microfloat) = sign_bits(typeof(x)) > 0 && !iszero(raw_bits(x) & sign_mask(typeof(x))) function exponent(x::T) where T<:Microfloat (isnan(x) || isinf(x)) && throw(DomainError(x, "Cannot be NaN or Inf.")) iszero(x) && throw(DomainError(x, "Cannot be ±0.0.")) - raw = reinterpret(Unsigned, x) + raw = raw_bits(x) biased = Int((raw & exponent_mask(T)) >> significand_bits(T)) biased == 0 || return biased - exponent_bias(T) sig = raw & significand_mask(T) @@ -107,31 +120,31 @@ Base.floatmax(::Type{T}) where T<:Microfloat = _floatmax(non_finite_behavior(T), # IEEE function _isinf(::Type{IEEE}, x::T) where T<:Microfloat - raw = reinterpret(Unsigned, x) + raw = raw_bits(x) (raw & exponent_mask(T)) == exponent_mask(T) && iszero(raw & significand_mask(T)) end function _isnan(::Type{IEEE}, x::T) where T<:Microfloat - raw = reinterpret(Unsigned, x) + raw = raw_bits(x) (raw & exponent_mask(T)) == exponent_mask(T) && !iszero(raw & significand_mask(T)) end -_inf(::Type{IEEE}, ::Type{T}) where T<:Microfloat = reinterpret(T, exponent_mask(T)) +_inf(::Type{IEEE}, ::Type{T}) where T<:Microfloat = from_raw_bits(T, exponent_mask(T)) _nan(::Type{IEEE}, ::Type{T}) where T<:Microfloat = - reinterpret(T, exponent_mask(T) | (UInt8(0x01) << (significand_bits(T) - 1))) + from_raw_bits(T, exponent_mask(T) | (UInt8(0x01) << (significand_bits(T) - 1))) _floatmax(::Type{IEEE}, ::Type{T}) where T<:Microfloat = - reinterpret(T, (exponent_mask(T) - (UInt8(0x01) << significand_bits(T))) | significand_mask(T)) + from_raw_bits(T, (exponent_mask(T) - (UInt8(0x01) << significand_bits(T))) | significand_mask(T)) # NanOnlyAllOnes _isinf(::Type{NanOnlyAllOnes}, ::Microfloat) = false function _isnan(::Type{NanOnlyAllOnes}, x::T) where T<:Microfloat - raw = reinterpret(Unsigned, x) + raw = raw_bits(x) (raw & ~sign_mask(T)) == (exponent_mask(T) | significand_mask(T)) end _inf(::Type{NanOnlyAllOnes}, ::Type{T}) where T<:Microfloat = throw(DomainError(T, "$T has no Inf")) _nan(::Type{NanOnlyAllOnes}, ::Type{T}) where T<:Microfloat = - reinterpret(T, exponent_mask(T) | significand_mask(T)) + from_raw_bits(T, exponent_mask(T) | significand_mask(T)) _floatmax(::Type{NanOnlyAllOnes}, ::Type{T}) where T<:Microfloat = - reinterpret(T, (exponent_mask(T) | significand_mask(T)) - UInt8(0x01)) + from_raw_bits(T, (exponent_mask(T) | significand_mask(T)) - UInt8(0x01)) # FiniteOnly _isinf(::Type{FiniteOnly}, ::Microfloat) = false @@ -141,7 +154,7 @@ _inf(::Type{FiniteOnly}, ::Type{T}) where T<:Microfloat = _nan(::Type{FiniteOnly}, ::Type{T}) where T<:Microfloat = throw(DomainError(T, "$T has no NaN")) _floatmax(::Type{FiniteOnly}, ::Type{T}) where T<:Microfloat = - reinterpret(T, exponent_mask(T) | significand_mask(T)) + from_raw_bits(T, exponent_mask(T) | significand_mask(T)) # ───────────────────────── generic Base methods ────────────────────────── @@ -150,24 +163,24 @@ Base.typemin(::Type{T}) where T<:Microfloat = Base.typemax(::Type{T}) where T<:Microfloat = hasinf(T) ? inf(T) : floatmax(T) function Base.floatmin(::Type{T}) where T<:Microfloat - significand_bits(T) == 0 && return reinterpret(T, 0x00) + significand_bits(T) == 0 && return from_raw_bits(T, 0x00) bits = UInt8(0x01) << significand_bits(T) - hasinf(T) && bits == reinterpret(Unsigned, inf(T)) && + hasinf(T) && bits == raw_bits(inf(T)) && throw(DomainError(T, "$T has no normal values")) - return reinterpret(T, bits) + return from_raw_bits(T, bits) end -Base.zero(::Type{T}) where T<:Microfloat = reinterpret(T, 0x00) +Base.zero(::Type{T}) where T<:Microfloat = from_raw_bits(T, 0x00) Base.one(::Type{T}) where T<:Microfloat = T(true) Base.eps(x::Microfloat) = max(x - prevfloat(x), nextfloat(x) - x) Base.eps(T::Type{<:Microfloat}) = eps(one(T)) -Base.abs(x::T) where T<:Microfloat = reinterpret(T, reinterpret(Unsigned, x) & ~sign_mask(T)) +Base.abs(x::T) where T<:Microfloat = from_raw_bits(T, raw_bits(x) & ~sign_mask(T)) Base.iszero(x::T) where T<:Microfloat = significand_bits(T) == 0 ? false : abs(x) === zero(T) Base.:(-)(x::T) where T<:Microfloat = sign_bits(T) == 0 ? throw_negate_unsigned(T, x) : - reinterpret(T, sign_mask(T) ⊻ reinterpret(Unsigned, x)) + from_raw_bits(T, sign_mask(T) ⊻ raw_bits(x)) Base.Bool(x::T) where T<:Microfloat = iszero(x) ? false : isone(x) ? true : throw(InexactError(:Bool, Bool, x)) Base.precision(::Type{T}) where T<:Microfloat = significand_bits(T) + 1 @@ -182,9 +195,9 @@ for M in (:FromZero, :NearestTiesAway, :NearestTiesUp) end Base.issubnormal(x::T) where T<:Microfloat = - 0x00 < (reinterpret(Unsigned, x) & ~sign_mask(T)) <= (UInt8(0x01) << significand_bits(T)) - 0x01 + 0x00 < (raw_bits(x) & ~sign_mask(T)) <= (UInt8(0x01) << significand_bits(T)) - 0x01 -ispositive(x::T) where T<:Microfloat = iszero(reinterpret(Unsigned, x) & sign_mask(T)) +ispositive(x::T) where T<:Microfloat = iszero(raw_bits(x) & sign_mask(T)) function Base.nextfloat(x::T) where T<:Microfloat if isnan(x) @@ -192,11 +205,13 @@ function Base.nextfloat(x::T) where T<:Microfloat elseif isinf(x) return ispositive(x) ? inf(T) : -floatmax(T) elseif iszero(x) - return reinterpret(T, 0x01) + return from_raw_bits(T, 0x01) elseif ispositive(x) - return reinterpret(T, reinterpret(Unsigned, x) + 0x01) + # Without Inf, floatmax is as far as it goes, like Inf in Base. + !hasinf(T) && raw_bits(x) == raw_bits(floatmax(T)) && return floatmax(T) + return from_raw_bits(T, raw_bits(x) + 0x01) else - return reinterpret(T, reinterpret(Unsigned, x) - 0x01) + return from_raw_bits(T, raw_bits(x) - 0x01) end end @@ -207,13 +222,14 @@ function Base.prevfloat(x::T) where T<:Microfloat return ispositive(x) ? floatmax(T) : -inf(T) elseif iszero(x) sign_bits(T) == 0 && return x - return reinterpret(T, sign_mask(T) | 0x01) + return from_raw_bits(T, sign_mask(T) | 0x01) elseif ispositive(x) - raw = reinterpret(Unsigned, x) + raw = raw_bits(x) raw == 0x00 && sign_bits(T) == 0 && return x - return reinterpret(T, raw - 0x01) + return from_raw_bits(T, raw - 0x01) else - return reinterpret(T, reinterpret(Unsigned, x) + 0x01) + !hasinf(T) && raw_bits(x) == raw_bits(-floatmax(T)) && return -floatmax(T) + return from_raw_bits(T, raw_bits(x) + 0x01) end end diff --git a/src/conversion.jl b/src/conversion.jl index 3692c8f..fae98e5 100644 --- a/src/conversion.jl +++ b/src/conversion.jl @@ -181,7 +181,7 @@ function _round_to_microfloat(::Type{T}, x::Float32, rshift::F, throw_negative_unsigned(T, x) end # A signed zero keeps its sign; unsigned formats have an empty sign mask. - iszero(x) && return reinterpret(T, signbit(x) ? sign_mask(T) : 0x00) + iszero(x) && return from_raw_bits(T, signbit(x) ? sign_mask(T) : 0x00) f32_raw = reinterpret(UInt32, x) f32_exp = Int((f32_raw >> 23) & UInt32(0x000000ff)) @@ -235,7 +235,7 @@ function _round_to_microfloat(::Type{T}, x::Float32, rshift::F, t_raw |= (((f32_raw >> 31) % UInt8) << (exponent_bits(T) + significand_bits(T))) & sign_mask(T) - return apply_overflow_policy(reinterpret(T, t_raw), x, mode, policy) + return apply_overflow_policy(from_raw_bits(T, t_raw), x, mode, policy) end # ───────────────────────── branch-free narrowing ────────────────────────── @@ -295,7 +295,7 @@ end # The magnitude of floatmax(T) and whether |x| exceeds it, which includes ±Inf # and NaN. The Float32 bits of floatmax(T) fold to a constant. @inline function exceeds_floatmax(::Type{T}, x::Float32) where T<:Microfloat - max_mag = reinterpret(UInt8, floatmax(T)) & ~sign_mask(T) + max_mag = raw_bits(floatmax(T)) & ~sign_mask(T) return max_mag, reinterpret(UInt32, abs(x)) > reinterpret(UInt32, cvt_generic(Float32, floatmax(T))) end @@ -356,9 +356,9 @@ end ovf_mag = if !(policy isa Overflowing) max_mag elseif hasinf(T) - ifelse(sentinel, reinterpret(UInt8, inf(T)), max_mag) + ifelse(sentinel, raw_bits(inf(T)), max_mag) elseif hasnan(T) - ifelse(sentinel, reinterpret(UInt8, nan(T)), max_mag) + ifelse(sentinel, raw_bits(nan(T)), max_mag) else max_mag end @@ -366,9 +366,9 @@ end sign_bits(T) == 1 && (r |= ifelse(neg, sign_mask(T), 0x00)) if hasnan(T) nan_result = isnan_x | (over & sentinel & !hasinf(T)) - r = ifelse(nan_result, reinterpret(UInt8, nan(T)), r) + r = ifelse(nan_result, raw_bits(nan(T)), r) end - return reinterpret(T, r) + return from_raw_bits(T, r) end cvt_twiddle(::Type{T}, x::Float32, mode::RoundingMode, policy::OverflowPolicy) where T<:Microfloat = @@ -469,7 +469,7 @@ cvt_generic(::Type{T}, x::Float32, mode::RoundingMode, ::OverflowPolicy) where T # boundary has subnormals flushed to zero on CPUs with native BF16 # instructions (e.g. Zen 4), which corrupts E8M0's 2^-127. function _to_bfloat16_bits(x::T) where {T<:Microfloat} - t_raw = reinterpret(UInt8, x) + t_raw = raw_bits(x) t_sign = (sign_bits(T) == 1) && (t_raw & (UInt8(1) << (exponent_bits(T) + significand_bits(T))) != 0) t_exponent_field = Int((t_raw >> significand_bits(T)) & UInt8((1 << exponent_bits(T)) - 1)) @@ -649,11 +649,11 @@ function cvt_generic_table(::Type{T}, ::Type{S}, mode::RoundingMode, policy::Ove table = UInt8[] for raw in 0:(1 << bitwidth(S)) - 1 y = try - cvt_generic(T, Float32(reinterpret(S, raw % UInt8)), mode, policy) + cvt_generic(T, Float32(from_raw_bits(S, raw % UInt8)), mode, policy) catch return nothing end - push!(table, reinterpret(UInt8, y)) + push!(table, raw_bits(y)) end return table end @@ -769,7 +769,7 @@ function twiddle_expr(tw::Twiddle{U}, ::Type{S}, head_expr = nothing) where {U, for p in (tw.head > 0 ? tw.pieces : tw.pieces[2:end]) ex = :(ifelse(i >= $(U(p[1])), $(piece_expr(:i, p)), $ex)) end - body = :(raw = reinterpret(UInt8, x); i = $U(raw & $(tw.mask)); t = $ex) + body = :(raw = $raw_bits(x); i = $U(raw & $(tw.mask)); t = $ex) if tw.shift !== nothing s = :($U(raw & $(sign_mask(S)))) push!(body.args, :(t |= $(tw.shift >= 0 ? :($s << $(tw.shift)) : :($s >> $(-tw.shift))))) @@ -795,9 +795,9 @@ function cvt_expr(::Type{T}, ::Type{S}, ::Type{M}, ::Type{P} ) where {T<:Microfloat, S<:Microfloat, M<:RoundingMode, P<:OverflowPolicy} table = cvt_generic_table(T, S, M.instance, P.instance) table === nothing && return :($cvt_generic($T, Float32(x), mode, policy)) - lookup = :(reinterpret($T, $(Tuple(table))[Int(reinterpret(UInt8, x) & $(UInt8(length(table) - 1))) + 1])) + lookup = :($from_raw_bits($T, $(Tuple(table))[Int($raw_bits(x)) + 1])) tw = twiddle_fit(table, S, sign_bits(T) == 1 ? bitwidth(T) - 1 : nothing) - return twiddle_or(lookup, tw, :(reinterpret($T, $(twiddle_expr(tw, S))))) + return twiddle_or(lookup, tw, :($from_raw_bits($T, $(twiddle_expr(tw, S))))) end # ───────────────────────── generated widening ────────────────────────── @@ -825,7 +825,7 @@ end function widen_expr(::Type{F}, ::Type{S}) where {F<:WideFloat, S<:Microfloat} F === Float64 && return :(Float64($cvt(Float32, x))) U = wide_bits(F) - table = [reinterpret(U, cvt_generic(F, reinterpret(S, raw % UInt8))) for raw in 0:(1 << bitwidth(S)) - 1] + table = [reinterpret(U, cvt_generic(F, from_raw_bits(S, raw % UInt8))) for raw in 0:(1 << bitwidth(S)) - 1] head = significand_bits(S) > 0 ? (1 << significand_bits(S), i -> widen_subnormal(F, S, i)) : nothing tw = twiddle_fit(table, S, 8 * sizeof(U) - 1; head) twiddle = :(reinterpret($F, $(twiddle_expr(tw, S, :($widen_subnormal($F, $S, i)))))) diff --git a/src/macro.jl b/src/macro.jl index 0d90e92..0f4bd47 100644 --- a/src/macro.jl +++ b/src/macro.jl @@ -92,11 +92,11 @@ macro microfloat(name, kwargs...) $mod.float_bits(::Type{$T}) = ($S, $E, $M) $mod.non_finite_behavior(::Type{$T}) = $nonfinite_expr $mod.overflow_policy(::Type{$T}) = $overflow_expr - let lookup = Tuple($_to_bfloat16_bits(reinterpret($T, i % UInt8)) for i in 0:$(2^N - 1)) - $mod.to_bfloat16_bits(x::$T) = lookup[reinterpret(UInt8, x) + 0x0001] + let lookup = Tuple($_to_bfloat16_bits($from_raw_bits($T, i % UInt8)) for i in 0:$(2^N - 1)) + $mod.to_bfloat16_bits(x::$T) = lookup[$raw_bits(x) + 0x0001] end - let strings = Tuple($_shortest_decimal_string(reinterpret($T, i % UInt8)) for i in 0:$(2^N - 1)) - $mod.decimal_string(x::$T) = strings[reinterpret(UInt8, x) + 0x0001] + let strings = Tuple($_shortest_decimal_string($from_raw_bits($T, i % UInt8)) for i in 0:$(2^N - 1)) + $mod.decimal_string(x::$T) = strings[$raw_bits(x) + 0x0001] end # The generated body names the argument `x`, so it escapes hygiene. Base.@generated function $mod.cvt(::Type{F}, $(esc(:x))::$T) where F<:$WideFloat diff --git a/test/high_bits.jl b/test/high_bits.jl new file mode 100644 index 0000000..245f34a --- /dev/null +++ b/test/high_bits.jl @@ -0,0 +1,76 @@ +using Microfloats: raw_bits + +# Bits above a type's width, which `reinterpret` can set, must not change any +# result, nor reach the bits of one. +@testset "Bits above the width" begin + same(a, b) = raw_bits(a) === raw_bits(b) + + for T in TYPES + N = bitwidth(T) + N == 8 && continue + for raw in 0x00:UInt8(2^N - 1), high in (0x01, 0xff) + x = reinterpret(T, raw) + y = reinterpret(T, raw | (high << N)) + + @test raw_bits(y) === raw + @test reinterpret(Unsigned, y) === raw + @test repr(y) == repr(x) + + @test isnan(y) == isnan(x) + @test isinf(y) == isinf(x) + @test iszero(y) == iszero(x) + @test signbit(y) == signbit(x) + @test issubnormal(y) == issubnormal(x) + @test y ≡ x + @test hash(y) == hash(x) + + @test same(abs(y), abs(x)) + sign_bits(T) == 1 && @test same(-y, -x) + @test same(nextfloat(y), nextfloat(x)) + @test same(prevfloat(y), prevfloat(x)) + + for F in (Float16, BFloat16, Float32, Float64) + @test F(y) === F(x) + end + @test Microfloats.cvt_generic(Float32, y) === Microfloats.cvt_generic(Float32, x) + @test same(Float8_E4M3FN(y), Float8_E4M3FN(x)) + @test same(T(Float32(y)), T(Float32(x))) + end + end +end + +# Nor do operations ever set them. +@testset "Results fit the width" begin + fits(y) = reinterpret(UInt8, y) >> bitwidth(typeof(y)) == 0 + sources = Float32[0, -0.0, 1e-30, -1e-30, 0.3, -0.3, 1, -1, 1e30, -1e30, Inf, -Inf, NaN] + + for T in TYPES + N = bitwidth(T) + N == 8 && continue + for f in (floatmax, typemax, typemin, zero, one) + @test fits(f(T)) + end + for raw in 0x00:UInt8(2^N - 1) + x = reinterpret(T, raw) + @test fits(abs(x)) + sign_bits(T) == 1 && @test fits(-x) + @test fits(nextfloat(x)) + @test fits(prevfloat(x)) + @test fits(T(Float32(x))) + end + for f in sources, mode in (RoundNearest, RoundToZero, RoundUp, RoundDown) + y = try + T(f, mode) + catch + continue + end + @test fits(y) + end + end + + # Without Inf, the ends are floatmax and -floatmax, as Inf and -Inf are in Base. + @testset "nextfloat and prevfloat stop at the ends" for T in TYPES + @test nextfloat(typemax(T)) === typemax(T) + @test prevfloat(typemin(T)) === typemin(T) + end +end diff --git a/test/runtests.jl b/test/runtests.jl index ec705c2..a1c4570 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -65,6 +65,7 @@ import CUDACore @testset "Microfloats.jl" begin include("basic.jl") + include("high_bits.jl") include("cvt.jl") include("overflow.jl") include("floatmin.jl")