Tuning Performance & Subnormals
Why SIMD transcendentals pay extra for IEEE-754 subnormals, when inputs cannot be subnormal, and how to strip unneeded checks
Magemath separates what inputs a kernel accepts from how out-of-bounds lanes behave. Every check, clamp, or rescaling step you turn off disappears at compile time through const dead-code elimination on const CFG: u128.
1. What subnormals are (and why SIMD kernels care)
IEEE-754 f32 anatomy
An IEEE-754 f32 packs a 1-bit sign, an 8-bit biased exponent ((bits >> 23) & 0xff), and a 23-bit fraction:
- Normal numbers have biased exponent
1..=254, representing(-1)^s × 1.fraction × 2^(e - 127). Every normalf32carries an implicit leading1bit in its significand. The smallest positive normal isf32::MIN_POSITIVE = 2^-126 ≈ 1.1754944e-38(0x0080_0000). - Subnormal (denormal) numbers have biased exponent
0and a nonzero fraction (0x0000_0001..=0x007f_ffff), representing(-1)^s × 0.fraction × 2^-126with no implicit leading1. They span1.4012985e-45(2^-149) up to1.1754942e-38, filling the underflow gap betweenf32::MIN_POSITIVEand0.0gradually instead of dropping straight to zero.
Why fast SIMD transcendentals break on subnormals without extra work
Vector log2, ln, log10, powf, and cbrt extract the binary exponent directly from the float's magnitude bits.
- On a normal float,
abs_bits >> 23gives the biased exponent in one vector shift. - On any nonzero subnormal from
1.17e-38down to1.40e-45, the 8-bit exponent field is0.bits >> 23reads0regardless of how many leading zeros sit in the 23-bit fraction, so an unrescaledlog2polynomial treats1e-42(≈ 2^-139.5) as if it were near2^-127and returns~ -127instead of-139.5. (exp2(x)andexp(x)do not extract the input's exponent — for any subnormalx,2^x ≈ 1 + x ln 2rounds directly to1.0onMidp, soExpfOptionsneeds no subnormal pre-pass.)
logf and powf multiply subnormal lanes by 2^23 before extracting the exponent and compensate for that shift afterward. cbrtf places the subnormal fraction bits at the exponent of 1.0, then subtracts 1.0. This gives the magnitude scaled by 2^126 exactly. The cube-root graph compensates by subtracting 42 from its output exponent. Vectors without zeros or subnormals skip this normalization.
When you cannot have subnormals vs when you can
In most media, imaging, and ML pipelines, nonzero subnormals are impossible by representation:
u8pixels divided by255.0: smallest nonzero value is1.0 / 255.0 = 3.9216e-3(~2^-8).u16pixels divided by65535.0: smallest nonzero value is1.0 / 65535.0 = 1.5259e-5(~2^-16, matching the1.0 / 65_536.0lower bound ofPowfDomain::SdrGamma,HdrGamma, andLogfDomain::Hdr).- 24-bit PCM audio (
2^-23 ≈ 1.192e-7) or clamped linear light (>= 1e-6): the smallest nonzero magnitude is more than 30 orders of magnitude abovef32::MIN_POSITIVE(1.175e-38).
Subnormals do appear and are worth handling in:
- Unthresholded exponential decay (IIR audio filters or reverb tails decaying toward silence without a zero gate).
- Products or ratios of unnormalized scientific quantities (for example squaring
1e-20before a log or cube root). - Arbitrary untrusted
f32streams where lossless IEEE classification across the entiref32bit space is part of the API contract (*Domain::AllFloatsor.admit_subnormals()).
Comparing the three Subnormals policies
PowfOptions::new(), LogfOptions::new(), Log1pfOptions::new(), and CbrtfOptions::new() all default to Subnormals::FlushOrClamp so checked evaluation does not fail if floating-point noise near zero produces a stray subnormal:
| Policy | Builder method | Behavior under Validation::Checked | Behavior under AssumeValid |
|---|---|---|---|
Subnormals::FlushOrClamp (default) | .flush_or_clamp_subnormals() | Flushes to signed zero when the domain admits it, or clamps to the applicable normal bound | Caller supplies values within the post-flush domain |
Subnormals::Reject | .reject_subnormals() | Rejects nonzero subnormals with an exact lane mask or slice index | Caller supplies normal values or admitted zeros |
Subnormals::Normalize | .admit_subnormals() | Normalizes subnormals for accuracy down to 2^-149. log1pf uses the identity at subnormal inputs | Keeps subnormal support |
CbrtfDomain::Bounded can flush subnormals during output reconstruction because it admits zero of either sign. For a custom interval such as .input_range(0.01, 4.0), the bounds already rule out subnormals.
use magemath::cbrtf::{Cbrtf, CbrtfDomain, CbrtfErrorKind, CbrtfOptions};
// Default on SignedUnit is Subnormals::FlushOrClamp: flushes ±subnormal -> ±0.0
const FLUSH: u128 = CbrtfOptions::new()
.domain(CbrtfDomain::SignedUnit)
.bits();
const REJECT: u128 = CbrtfOptions::new()
.domain(CbrtfDomain::SignedUnit)
.reject_subnormals()
.bits();
const NORMALIZE: u128 = CbrtfOptions::new()
.domain(CbrtfDomain::SignedUnit)
.admit_subnormals()
.bits();
let sub = f32::from_bits(4); // 2^-147 ≈ 5.605e-45 (nonzero subnormal)
// 1. FlushOrClamp (default): maps -sub to -0.0 without failing Checked validation
assert_eq!(Cbrtf::<FLUSH>::scalar(-sub).unwrap().to_bits(), (-0.0_f32).to_bits());
// 2. Reject: flags nonzero subnormals as InvalidInput
assert_eq!(Cbrtf::<REJECT>::scalar(sub).unwrap_err().kind, CbrtfErrorKind::InvalidInput);
// 3. Normalize preserves the exact root of 2^-147.
let exact = Cbrtf::<NORMALIZE>::scalar(sub).unwrap();
let expected = f32::from_bits((127 - 49) << 23);
assert_eq!(exact.to_bits(), expected.to_bits());
2. Step-by-step knob guide for skipping unneeded checks
All timings below are whole-slice runs (4,096 f32 values, 16-lane AVX-512 Execution::Upgrade, no -C target-cpu) on AMD Ryzen 9 9950X3D from benchmarks/magemath_slices_2026-11-17/RESULTS.md (cb7c9580ca62).
Step 1: Narrow the *Domain (or bf16 range) to elide reduction and clamp stages
Tightening the domain does more than change what Checked rejects — when the domain bounds prove an internal overflow clamp, integer 2^k reconstruction, or Kahan branch is unreachable, Magemath drops those vector instructions at compile time:
ExpfDomain::NormalOutput([-126.0, 127.0]forexp2,[-87.0, 88.0]forexp): elides the internal[-126, 128]output underflow/overflow clamp (343.2 nsvs464.3 nsonExpfDomain::Finite,-26.1%,1.35xfaster).- Watch out for the
127.5endpoint:.input_range(-126.0, 127.5)runs in570.3 ns(+22.8%slower thanFinite). BecauseMidpsplitsxwithround_ties_even(x),round_ties_even(127.5) == 128.0, which would overflow(xi + 127) << 23if unclamped. Any upper bound>= 127.5forces the kernel to keep its internalxi.min(127.0)clamp plus the custom[lo, hi]range check. Keep customexp2upper bounds strictly below127.5(note.input_range(lo, hi)rounds outward tobf16viafloor_bf16/ceil_bf16).
- Watch out for the
ExpfDomain::SingleOctave([-0.5, 0.5]forexp2,[-0.34657356, 0.34657356]forexp):round_ties_even(x)is identically0, so the kernel dropsround,sub, float-to-int conversion, bit-shift, and2^kscale multiplication completely —257.4 nschecked (1.80xfaster thanFinite) and181.0 nsunchecked (2.56xfaster,<= 0.78 ULP).LogfDomain::SingleOctave([√2/2, √2]=[0.70710677, 1.4142134]onMidp): the unbiased binary exponent is0across the entire interval, eliding integer exponent extraction andi32 -> f32conversion —318.2 nschecked (1.35xfaster thanPositiveNormals429.2 ns) and217.1 nsunchecked (1.98xfaster thanPositiveNormals,2.65xfaster than.admit_subnormals()).Log1pfDomain::AroundZero([-0.25, 0.25]):1 + xstays inside[0.75, 1.25], eliding both integer exponent extraction and the1 + x >= 2Kahan compensation branch —533.5 nschecked (1.59xfaster thanGreaterThanNegOne849.7 ns) and347.5 nsunchecked (2.45xfaster).PowfDomaintransfer presets &.const_exponent(n):UnitEncode,SdrGamma({+0.0} ∪ [2^-16, 1.0]),HdrGamma({+0.0} ∪ [2^-16, 2^16]), andPqRatio([107/128, 1.0], exponent[0, 80]) statically bound|n * log2(x)| <= 125.0, eliding per-laneOutsideApproximationRangechecks (830.4 nsonHdrGammavs1.33 µson unrangedNonNegative). Adding.const_exponent(n)removes runtime exponent validation and lowers algebraic exponents (0, 0.25, ±0.5, ±1, 1.5, ±2, 3, 4) directly to IEEEsqrt,mul, anddivinstructions (251.8 nsfor0.5,365.6 nsfor2.0).
use magemath::expf::{Expf, ExpfDomain, ExpfOptions};
use magemath::log1pf::{Log1pf, Log1pfDomain, Log1pfOptions};
use magemath::powf::{Powf, PowfDomain, PowfOptions};
// SingleOctave [-0.5, 0.5]: elides output clamps and integer 2^k reconstruction
const SMALL_EXP2: u128 = ExpfOptions::new()
.domain(ExpfDomain::SingleOctave)
.assume_in_bounds()
.bits();
// AroundZero [-0.25, 0.25]: elides exponent extraction and Kahan 1+x >= 2 branch
const SMALL_LOG1P: u128 = Log1pfOptions::new()
.domain(Log1pfDomain::AroundZero)
.assume_in_bounds()
.bits();
// Algebraic const_exponent(0.5): lowers directly to IEEE hardware sqrt
const UNIT_SQRT: u128 = PowfOptions::new()
.domain(PowfDomain::Unit)
.const_exponent(0.5)
.bits();
assert_eq!(Expf::<SMALL_EXP2>::exp2_infallible(0.0), 1.0);
assert_eq!(Log1pf::<SMALL_LOG1P>::scalar_infallible(0.0), 0.0);
assert_eq!(Powf::<UNIT_SQRT>::scalar_const(0.25).unwrap(), 0.5);Step 2: Pick the lightest Validation mode your caller contract justifies
Validation variant | Builder method | Return type | Out-of-bounds finite / ±inf | NaN input | When to pick it |
|---|---|---|---|---|---|
Checked (default) | .error_on_out_of_bounds() / .checked() | Result<_, Error> | Rejects vector (lane_mask) or slice (index) | Rejects | Untrusted external inputs or boundary assertions |
ClampOutOfBounds | .clamp_out_of_bounds() | Infallible | Clamps into [lo, hi] (and saturates Midp/Lowp powf output) | Propagates NaN -> NaN | Noisy upstream floats (for example filter overshoot below 0.0 or above 1.0) where NaN must remain NaN |
ClampFinite | .clamp_finite() | Infallible | Same domain clamp as ClampOutOfBounds | Unspecified float (no UB) | Upstream already excluded NaN (for example decoded integer pixels + bicubic ringing), skipping the NaN mask save and restore |
AssumeValid | .assume_in_bounds() / .unchecked() | Infallible | Unspecified float (never memory UB; #![forbid(unsafe_code)]) | Unspecified float | Caller just clamped or normalized the lanes (20%–49% faster than Checked across families) |
use archmage::ScalarToken;
use magetypes::simd::generic::f32x4;
use magemath::SimdMath;
use magemath::expf::{Expf, ExpfDomain, ExpfErrorKind, ExpfOptions};
const CHECKED: u128 = ExpfOptions::new().domain(ExpfDomain::SignedUnit).bits();
const CLAMP_NAN: u128 = ExpfOptions::new()
.domain(ExpfDomain::SignedUnit)
.clamp_out_of_bounds()
.bits();
const CLAMP_FINITE: u128 = ExpfOptions::new()
.domain(ExpfDomain::SignedUnit)
.clamp_finite()
.bits();
// Checked rejects out-of-bounds lanes and reports every failing lane in `lane_mask`:
let v = f32x4::from_array_t(ScalarToken, [0.0, 2.5, -0.5, f32::NAN]);
let err = v.try_exp2_with::<CHECKED>().unwrap_err();
assert_eq!(err.kind, ExpfErrorKind::InvalidInput);
assert_eq!(err.lane_mask, 0b1010); // lanes 1 and 3 failed [-1.0, 1.0]
// ClampOutOfBounds clamps 2.5 -> 1.0 (2^1 = 2.0) and preserves NaN -> NaN:
let clamped = v.exp2::<CLAMP_NAN>().to_array();
assert_eq!(clamped[1], 2.0);
assert!(clamped[3].is_nan());
// ClampFinite skips saving/restoring the NaN mask when inputs are known finite:
let finite = f32x4::from_array_t(ScalarToken, [-5.0, 0.0, 0.5, 5.0]);
let fast_clamped = finite.exp2::<CLAMP_FINITE>().to_array();
assert_eq!(fast_clamped[0], 0.5);
assert_eq!(fast_clamped[3], 2.0);
assert_eq!(Expf::<CLAMP_FINITE>::exp2_infallible(10.0), 2.0);Step 3: Choose Portability::BitExact vs Portability::BackendDependent
Portability::BitExact(default,.bit_exact()): evaluates one fused polynomial graph across every target so x86 AVX2, x86 AVX-512, AArch64 NEON, WASM SIMD128, andScalarTokenproduce bit-for-bit identical accepted outputs. On x86 V3/V4 and AArch64 NEON, hardware FMA already rounds once in a single instruction, soBitExactcosts nothing extra on native desktop, server, and mobile SIMD tiers. OnScalarToken(without compile-time FMA) and strictWasm128Token(orrelaxed-simdengines whose cached startup probe rounds twice),BitExactruns vectorized branchless software single-rounding FMA (f64product with round-to-odd adjustment on rare halfway/subnormal lanes).Portability::BackendDependent(.backend_dependent()): evaluates polynomials withmul_add_relaxed(1-instruction FMA on x86 V3/V4 and NEON, plaina * b + conScalarTokenand strict WASM, and platformstdf32::powfonHighppowf). Switch to.backend_dependent()when 1–3 ULP cross-ISA drift on scalar/WASM fallbacks is acceptable and WASM or scalar fallback speed matters.
WASM portability (BackendDependent vs BitExact)
For WASM throughput, choose .backend_dependent() when your pipeline permits
cross-ISA rounding differences. The options builders default to BitExact
for reproducible output. On strict SIMD128, or when the relaxed-SIMD
engine rounds relaxed_madd twice, BitExact needs software single-rounding
FMA. Packed BitExact took roughly 10–60× as long as BackendDependent
in sampled strict WASM profiles. For example, strict Midp exp2 on a
single octave took 17.336 vs 0.281 ns/lane on Wasmtime 40.0.1 with a
Ryzen 9 9950X3D and 4,096 inputs.
If you need BitExact on strict or unfused WASM, start with a scalar slice
using .caller() and slice_with_token(ScalarToken, ...). The single-lane
f32 software FMA promotes to f64 and handles rounding at the midpoint.
In the 4,096-element Midp slice probes, it ran 1.4–2.7× as fast as the
packed WASM_SOFTWARE TwoSum path across the five families. Strict
powf took 13.243 vs 31.849 ns/lane in the follow-up benchmark,
and the standalone probe's opt-level = 3 code section went from 57,182
to 43,335 bytes. With fusing relaxed SIMD, the four-lane Midp BitExact
slices in the follow-up used a single-rounding relaxed_madd and took
0.234–1.001 ns/lane. The Highp powf software path instead uses
binary64 FMA and has a separate cost profile.
At commit 4bd1b8ddbe4e, SIMD-enabled builds use eight-lane Midp slices
and select packed software arithmetic for unfused BitExact. The measured
four-lane slice change selects W128 for BackendDependent and fusing
BitExact, and selects a one-lane scalar slice for strict or unfused
BitExact. Explicit SimdMath calls use the vector width chosen by the
caller. WASM slice implementation
Which entry point should you call?
| Work | Entry point |
|---|---|
| Fused row loop | Use SimdMath with .caller(), starting with four lanes on WASM, eight on V3 or NEON, and sixteen on V4/V4x. Use matching *_with_token scalar calls for the tail, or load_padded_t and store_prefix with valid padding on a lane-wise kernel. |
| Standalone buffer, plane, or LUT pass | Call Powf::<CFG>::slice or slice_const once per buffer. Use the matching *_slice for other functions. Execution::Upgrade can select 16-lane AVX-512. In builds with the WASM slice change, the slice call selects four lanes or the scalar fallback described above. |
| Single element or cold path | Call *_with_token with .caller(). In the eight-element scalar powf control, the entire stripped WASM module was 625 bytes at opt-level = "z". |
Several Highp exponents | Share the slice entry's structural options. In the no-std scalar probe for 2.4, 1 / 2.4, 2.2 and 1 / 2.2, four configurations used 1.03–1.07× the bytes of one across x86-64 and WASM at opt-level = 3 and "z". |
Midp can specialize .const_exponent(n) in the inline graph. The
shared-exponent probe added about 1–2 cycles per lane to some inlined
Zen 5 vector callers. Its bulk slice timings were close. Use
.slice(src, dst, exp) with one configuration when keeping code size down
across many Midp exponents. Scalar and Highp codegen change
Step 4: Choose Precision and Execution
- Precision (
Lowp,Midp,Highp):Midp(default,.midp()): refitted degree-6exp2(<= 1.9 ULPbelow127.5,<= 0.78 ULPonSingleOctave), degree-6 odd-rationallog2/ln/log10(<= 4.5 ULPover positive normals,<= 2.9 ULPonSingleOctave), Kahan-compensatedlog1p(<= 2.9 ULParound zero), division-free Estrincbrt(1.47 ULP maximum measured inBitExact), and 100% exact 8/10/12-bit sRGB round-trips onpowf.Lowp(.lowp()): refitted degree-3exp2(<= 0.030%relative error on[-126, 127.99]), rationalP2/Q2log2(~6e-6absolute error), and division-free Hornercbrt(180.67 ULP maximum measured inBitExact). Note thatLowplog1phas a~1.3e-6polynomial intercept on tiny positive normals near zero (while preserving0.0and admitted subnormals), so keepMidpwhen tiny normal signs near zero matter.Highp(.highp(),powfonly ): table-based binary64 polynomial underBitExact, orstdf32::powfunderBackendDependent(requiresstd). Required forPowfDomain::AllFloats.
- Execution (
UpgradevsCaller):Execution::Upgrade(default,.upgrade()): upgrades once per operation when runtime CPU detection (std) exposes a wider or faster tier — notably wideningScalarTokenandX64V3Tokenslice calls to 16-lane AVX-512zmmloops whenavx512is enabled, while keeping isolated 4/8-laneMidp/LowpV3vector calls inline.Execution::Caller(.caller()): disables autonomous runtime tier upgrades so inlineSimdMathvector calls and*_with_tokenscalar tails inside your own#[attune]loop stay locked to the caller's token.
Next: see Magetypes Fast Paths & Contract Tiers for the same check-skipping discipline on primitive vector conversions, reciprocals, min/max/clamp, FMA reductions, and #[attune] boundaries.