Width as a type: one crate, every precision, no build profile
STATUS: IMPLEMENTED, branch width-types, released as 0.7.0. Every
phase in the table of section 10 is done (phase 7.5, the inference
extension, in docs/design/INFERENCE_EXTENSION.md). Sections 1 to 9
describe the 0.6.x starting point and the plan as written; the phase notes
record what was built and measured. Migration for users:
docs/UPGRADING_0.7.md.
1. Problem
Today the binary precision of the whole crate is one build-wide choice:
GMATH_PROFILE (or one of the mutually exclusive profile features) becomes
cfg(table_format = "...") in build.rs, and GMATH_FRAC_BITS becomes
frac_config::FRAC_BITS. Cargo builds one copy of g_math per binary, so every
crate in a dependency graph sees the same width. Two libraries that need
different widths cannot share a binary, and when two profile features are
enabled at once build.rs picks one by priority without an error, so one of
them computes at a width it never asked for.
Measured (findings, 2026-10-05): a stripped release binary pays 0.84 MB (Q16.16) to 2.55 MB (Q256.256) for a representative workload; all five widths linked together cost 6.3 MB, about the sum of the parts. Size is not the obstacle. The build-global setting is.
2. Goal and non-goals
Goal: the width is part of the type. Any crate can use any supported width, any number of widths can coexist in one binary, and enabling more widths never changes a result anywhere.
Hard requirements, each with a gate in section 11:
- R-BIT Every operation on
Fixed<S, F>is bit-identical to the same operation in today's crate built with the matching profile (andGMATH_FRAC_BITS = Ffor the 32-bit width). Moving to 0.7.0 opens no numerics epoch. - R-PERF No operation is slower than in the matching profile build beyond measurement noise (criterion, 2 percent band, release, same machine).
- R-FLEX Every configuration supported today stays supported: Q(32-F).F for F in 2..=30, Q32.32, Q64.64, Q128.128, Q256.256, all transcendentals, FASC, decimal, ternary, intervals, predicates, the inference module.
- R-ADD Cargo features only add widths. No feature, environment variable or build script changes the numeric behaviour of a type that is already enabled.
- R-STABLE Stable Rust only. No
generic_const_exprs.
Non-goals for 0.7.0: new fractional splits on the wide widths (for example Q88.40 in i128). The design admits them (section 4.3) but each needs its own mpmath gate, so they come after the migration, one at a time.
3. Shape of the public API
pub struct Fixed<S: Storage, const F: u32> { raw: S } // #[repr(transparent)]
pub type Q16_16 = Fixed<i32, 16>; // any Fixed<i32, F>, 2 <= F <= 30
pub type Q32_32 = Fixed<i64, 32>;
pub type Q64_64 = Fixed<i128, 64>;
pub type Q128_128 = Fixed<I256, 128>;
pub type Q256_256 = Fixed<I512, 256>;
pub struct FixedVector<T: FixedNum> { data: Vec<T> }
pub struct FixedMatrix<T: FixedNum> { rows: usize, cols: usize, data: Vec<T> }
pub struct Interval<T: FixedNum> { lo: T, hi: T }
pub struct ComputeMatrix<T: FixedNum> { data: Vec<T::Compute> }
A consumer writes type Real = g_math::Q64_64; once. Another crate in the same
binary writes type Real = g_math::Fixed<i32, 10>;. Code generic over width is
ordinary Rust: fn norm<T: FixedNum>(v: &FixedVector<T>) -> T.
There is deliberately no default width. A default is the global knob again under a new name; the one-line alias is the whole migration cost for a consumer.
The fallible surface is unchanged in shape: operators panic on overflow,
try_* twins return Err (0.6.4 contract), transcendentals keep their
try_* forms and error variants.
4. The width traits
4.1 WideInt, Storage, CircleStorage (sealed): what a word can do
Three traits in src/fixed_point/width.rs (crate-private until phase 2 makes
the surface public). They absorb what was spread over the BinaryStorage /
ComputeStorage aliases, the Wide trait in imperative/wide_acc.rs and the
near-uniform method surface of the wide integers.
// every integer word: i32, i64, i128, I256, I512, I1024, I2048
pub trait WideInt: Copy + Eq + Ord + Send + Sync + 'static
+ Add<Output = Self> + Sub<Output = Self> + Mul<Output = Self> + Neg<Output = Self>
+ sealed::Sealed
{
const BITS: u32;
fn zero() -> Self;
fn one() -> Self;
fn from_i64(v: i64) -> Self;
fn is_negative(self) -> bool;
fn bit_length(self) -> u32;
fn checked_add_wide(self, o: Self) -> Option<Self>;
fn checked_sub_wide(self, o: Self) -> Option<Self>;
fn checked_neg_wide(self) -> Option<Self>;
fn shl_bits(self, n: u32) -> Self;
fn shr_bits(self, n: u32) -> Self;
fn mul_exact(self, o: Self) -> Self; // budget asserted
fn add_exact(self, o: Self) -> Result<Self, OverflowDetected>;
}
// the five words a value can be stored in: i32, i64, i128, I256, I512
pub trait Storage: WideInt {
type Compute: WideInt; // i32->i64, i64->i128, i128->I256, I256->I512, I512->I1024
type Orient: WideInt; // exact accumulator: i128, I256, I512, I1024, I2048
fn widen(self) -> Self::Compute;
fn mul_wide(self, o: Self) -> Self::Compute; // exact product
fn narrow(c: Self::Compute) -> Option<Self>; // checked
fn orient(self) -> Self::Orient;
fn widen_product(a: Self::Compute, b: Self::Compute) -> Self::Orient;
}
// the four storage words with a second accumulator (not I512)
pub trait CircleStorage: Storage {
type Circle: WideInt;
fn circle(self) -> Self::Circle;
}
Two deviations from the first draft of this section, both forced by the
type chain ending at I2048:
- The integer surface (
WideInt) is separate fromStorage.I1024andI2048are compute and accumulator words only; they have no wider word, so they cannot implement a trait withtype Compute. - The circle accumulator is its own trait instead of
type Circle = ()on the 512-bit word. A boundS: CircleStoragestates the requirement and the compiler names it when it is not met.
Wide in wide_acc.rs is now a re-export of WideInt; exact_product,
widen_storage, widen_product and the acc aliases delegate to Storage,
so the existing suite exercises the trait impls on every profile. The wide
integers gained the missing methods (is_negative, checked_sub,
checked_neg on I1024 and I2048); the shift operators keep their
historical argument types (I256 >> u32, the others usize) and
shl_bits / shr_bits are the uniform form.
4.2 FixedNum (sealed): the kernels of one format
Implemented once per storage word in src/fixed_point/fixed_num.rs:
impl<const F: u32> FixedNum for Fixed<i32, F>, and for the four wide
widths with their single admitted F. All five impls compile in every build.
The trait works on raw words, not on Fixed values, so the profile-bound
layers that have not been made generic yet can call it through
ProfileFormat (the format the build profile selects). Its methods are
exactly the functions that used to carry one cfg arm per profile:
- between the tiers:
upscale_to_compute,downscale_to_storage(nearest, ties toward +infinity),downscale_to_storage_floor,_ceil; - storage tier:
one_storage,try_from_int,try_to_int,float_bits,truncated_raw,try_fixed_multiply,try_fixed_divide; - compute tier:
compute_checked_multiply,compute_checked_divide,make_compute_int,compute_mul_div_int,compute_div_count,compute_ceiling,exp_sentinel_reached, and provided methods written once overWideInt(compute_add,compute_subtract,compute_negate, their checked forms,compute_halve,sinhcosh_at_compute_tier); - the engine routing, twice:
direct_exp...direct_atan2andcompute_pi_halfas the imperative methods call them, andexp_at_compute_tier...pi_half_at_compute_tieras the canonical evaluator calls them.
Every body was moved from its cfg arm by a script that specialises the
old function for one profile, not retyped, and the old free functions now
delegate to the trait. Three facts the move made visible, all preserved
as they were:
- Two routings. The imperative and canonical paths name the same engine
everywhere except atan at Q64.64: the imperative
atanuses the 55-term Q128.128 engine, the canonical path the 33-term one. Their compute-tier values differ (the engine digests differ); whether their rounded storage values ever differ has not been measured. Unifying them is a numerics decision for after 0.7.0, with that measurement first. - Two values of pi/2.
compute_pi_half(imperative acos/asin) is the constant of the format below, upscaled;pi_half_at_compute_tieris the compute tier's own constant. Same remark. - One subtraction form. The 512-bit width computes
a - basa + (-b), which panics forbat the compute minimum even when the difference is representable. It keeps that form (an override in its impl).
The scalar type is generic on top of the kernels
(src/fixed_point/imperative/fixed_point.rs):
impl<S: Storage, const F: u32> Fixed<S, F> where Self: FixedNum<Storage = S> {
pub const ZERO: Self; pub fn one() -> Self; pub fn from_int(v: i32) -> Self;
// conversions, the float boundary, operators and their try_ twins,
// all 18 transcendentals with their try_ twins, sincos, sinhcosh, inv_sqrt
}
pub type FixedPoint = Fixed<BinaryStorage, { frac_config::FRAC_BITS }>;
FixedPoint is now an alias, so the whole crate above the scalar type and
the whole test suite run on the generic code without a change.
Still bound to the profile's format until phase 5, because they evaluate
through the canonical layer: from_str / try_from_str, Display,
try_pow, try_atan2. sincos_wide and sincos_wide_q64 exist on
Fixed<i32, F> and Fixed<i64, 32>, as before.
Resolved in phase 3: the containers keep ONE type parameter with the
scalar as its default, FixedVector<T = FixedPoint> and
FixedMatrix<T = FixedPoint>, and every impl is written on the concrete
scalar, impl<S: Storage, const F: u32> FixedVector<Fixed<S, F>> where Fixed<S, F>: FixedNum<Storage = S>. User code names a width as
FixedVector<Q22_10> and the methods come from that impl; nothing moved
onto a trait. Expression-position constructors whose type is not fixed by
an argument need an annotation (let id: FixedMatrix = FixedMatrix::identity(n)),
which a handful of tests needed. The compute-tier state uses
ComputeMatrix<T: FixedNum = FixedPoint> the same way.
Phase 4a settled the second half of the question, the user-implemented
traits. Manifold, LieGroup, MetricProvider, OdeSystem,
HamiltonianSystem, FiberBundle and BundleConnection take the scalar
as a type parameter with the profile's format as its default,
pub trait Manifold<T: Scalar = FixedPoint>, so impl OdeSystem for Mine
still compiles and impl OdeSystem<Q22_10> for Mine names a width. The
library's own types implement them for every format at once
(impl<S, const F> Manifold<Fixed<S, F>> for Sphere). Scalar is a sealed
trait implemented by every Fixed<S, F>: it carries the operators and
comparisons and, hidden, the three operations the traits' default methods
need (a square root, a matrix inverse, a vector difference), which is what
lets a default body be written against T while every inherent method
stays on Fixed<S, F>. A method with no scalar in its arguments, such as
dimension() on a non-generic manifold, needs the trait named at the call
site (<Sphere as Manifold>::dimension(&s)); a handful of tests did.
Per-format constants became functions of the storage width and the split:
the Rodrigues small-angle threshold is 2^F / 10^k rounded to nearest for k
chosen by the word (3, 5, 10, 20), identical to what from_str made of
the literals, and the curvature differentiation step is 2^-((F + 1) / 3)
on every format (the five profile arms were that formula).
4.3 Admitted fractional splits
F is checked at compile time with an inline const in every constructor path:
impl<S: Storage, const F: u32> Fixed<S, F> {
const VALID: () = assert!(S::admits_frac_bits(F), "unsupported F for this storage");
}
0.7.0 admits exactly today's set: i32 with 2..=30, i64 with 32, i128 with
64, I256 with 128, I512 with 256. Fixed<i128, 40> is a compile error, not
a runtime surprise.
As built: a combination without a FixedNum impl has no methods
(Fixed<i128, 40>::one() does not resolve). For the 32-bit word, where the
impl is generic over F, the range is asserted in the associated constant
FRAC_BITS and every split-dependent kernel reads the split through it, so
Fixed<i32, 31> fails at build time with "F must be between 2 and 30" at
its first use. Both are pinned by compile_fail doctests on Fixed. The
check fires in cargo build and cargo test; cargo check does not
instantiate the constant. The 32-bit mechanism (upshift by 64 - 2F into the Q64.64
engine, shift back) generalises to other splits on other storage words, which is
how splits like Q88.40 can be admitted later, each behind its own gate.
5. Kernels: one name, one meaning
The survey found the main hazard: today's wrappers exp_binary_i128,
exp_binary_i256 and their siblings change meaning per profile
(exp_binary_i128 is native Q64.64 on the Q64.64 profile and upscales to
Q128.128 on the Q128.128 profile). Under types, a function name has one meaning.
- The native engines keep their format names and are compiled for every enabled
width:
exp_q64_64_native,exp_q128_128_native,exp_q256_256_native,exp_q512_512_native, and the same for ln, sqrt, sincos, atan. - The profile-dependent
*_binary_iNand*_compute_tier_iNwrappers are deleted. EachFixedNumimpl calls the native engine of its compute format directly:Fixed<i32, F>andFixed<i64, 32>use Q64.64 (with the existing upshift for i32),Q64_64uses Q128.128,Q128_128uses Q256.256,Q256_256uses Q512.512. That is today's routing, written down once. - The lookup tables are already compiled for every tier in every profile. With width features (section 9) they are included only for enabled widths.
Phase 1 result. All 28 engines compile on every profile under one name each:
exp, ln, sqrt, sincos, atan and atan2 at Q64.64, Q128.128, Q256.256 and
Q512.512 (*_native), plus atan_q128_128_compute, atan2_q128_128_compute,
atan_q256_256_compute and atan2_q256_256_compute. The atan engines really
are two per format: _native carries the series terms for the format's own
precision (55 at Q128.128, 105 at Q256.256), _compute carries the terms
needed when that format is the compute tier of the storage format half its
width (33 and 65). They return different integers at the compute tier, so
they stay separate functions and each width keeps the one it uses today. The
sin/cos engines had the same duplication but with identical bodies; those
were merged. engine_identity_tests (in transcendental/mod.rs) pins a
digest of every engine's output on a fixed input set, and the same digests
hold on all five profiles.
6. Constants that depend on F
Associated consts on stable Rust can be computed from F
(const ROUND_BIT: S = 1 << (F - 1)), but types cannot (no
generic_const_exprs). That is enough: every F-dependent quantity today is a
value (FRAC_ROUND_BIT, NATIVE_UPSHIFT, MAX_DECIMAL_DIGITS, convergence
thresholds 2^-(3F/2), stagnation shifts, differentiation steps), and every
type that varies is a function of the storage word only (Compute, Orient,
Circle). Shifts by these consts compile to immediates exactly as the
frac_config consts do today, which is what R-PERF needs.
7. The canonical (FASC) layer
LazyExpr becomes LazyExpr<T: FixedNum>. Literals stay text until
evaluation, so the width is inferred from where the tree is used:
let e = gmath("1.5").exp() + gmath("0.1");
let v = evaluate::<Q64_64>(&e)?; // or: let v: StackValue<Q64_64> = evaluate(&e)?;
StackValue<T>carriesT::Storage/T::Computepayloads. The UGOD ladder (BinaryTier1..6) is already width-independent; the width only sets the top tier, which today is a runtime value (profile_max_binary_tier).- The thread-local evaluator cannot be generic (statics are not monomorphised).
Storagegetsfn with_evaluator<R>(f: impl FnOnce(&mut StackEvaluator<Self>) -> R) -> R, implemented per storage word by a small macro, onethread_local!each. The evaluator's buffer type depends only on the storage word;Fis a const parameter of the evaluation, so all 29 splits of i32 share one buffer. LazyExpr::Value(feeding a result back) holdsStackValue<T>, so a Q64.64 result cannot be fed into a Q16.16 tree by accident; converting is explicit.- Tier-1 arithmetic follows
Fon the 32-bit width today (binary_multiplication.rs,binary_division.rs); it takesFas a const parameter instead of readingfrac_config. DomainMatrix,LazyMatrixExpr,evaluate_matrix,evaluate_sincosfollow the same pattern. Thegmath!macro emits an exact decimal value instead of a width-specificStackValue::Decimal.- Mode routing (
set_gmath_mode) is width-independent and unchanged.
Refined for the build (2026-10-06, after phase 4), in three sub-phases:
- 5a, the format's arms as a trait. Every profile arm in the evaluator
(decimal digit budgets, tier-raw widenings and narrowings, the literal
parser's ranges, the decimal formatter, the compute-tier conversions of
decimal values, the integer and halving helpers) becomes a method or
constant of a crate-private trait
FascFormat: FixedNum, with one impl per format produced by the cfg-specialiser (arms transplanted, not retyped); the old functions delegate throughProfileFormat. Zero behaviour change; gate = the full suite per profile. - 5b, the typed value and the evaluator registry. IMPLEMENTED
(2026-10-06) with one change to the plan above: the evaluator is
StackEvaluator<T: FascFormat>overStackValue<T>(the payload isT::Storage/Compute<T>directly), not aRawValue<S>buffer withFthreaded through every method as a const parameter; that threading would have touched every call in the evaluator for a saving of one buffer per split. The thread-local is a registryVec<(TypeId, Rc<dyn Any>)>with a one-entry last-used cache in front of it (with_evaluator::<T>), so the common path is one type comparison and aRefCellborrow; measured against 0.6.7 (realtime Q22.10, perf3fasc): integer add 194 vs 207 ns, decimal mix 468 vs 466, division 204 vs 218, parse 67 vs 78, exp 1372 vs 1381, display 384 vs 391; without the cache the registry scan cost 13 ns (+6 percent on the cheapest trees).LazyExpr<T>,StackValue<T>andStackEvaluator<T>default to the profile's format, so every existing call compiles unchanged; a result of one format cannot enter a tree of another. New entry pointsevaluate,evaluate_sincos,evaluate_sinhcosh,gmath_parse,gmath,with_evaluator;FascFormatis public and sealed (its items hidden). Prerequisites done in the same step: the decimal compute tier is generic over its compute word (DecimalWord: WideIntwithNarrow,Wide,Hpand the digit budgets, one impl per word, every engine<C: DecimalWord>, a TypeId-keyed thread-local cache for the per-word constants; the profile names remain as aliases) andStorage::Compute: DecimalWord<Narrow = Self>; UGOD tier 1 takes its fraction bits as a parameter (checked_mul_with_frac,multiply_with_tier1_frac), the format suppliesTIER1_FRAC_BITS(Fon a 32-bit word, 16 elsewhere). The seven remaining profile arms (integer literal range, ternary raw, the twoto_rationalarms, the compute-tier divide, the decimal-compute narrowing, the scientific tier-5 ternary) areFascFormatmethods. Gates: the full suite per profile,tests/differential_065_validation.rsFASC section (literals, 676 binary operations, 315 transcendental trees: value, error and panic identical to 0.6.7 on realtime Q22.10 and embedded),tests/fasc_width_validation.rs(six formats interleaved in one build: exact-domain results equal as rationals, transcendentals within 4 storage units plus one decimal unit of the widest). Behaviour change:gmath!integer literals beyond the storage's integer range now fall back to the exact rational like the runtime parser (they wrapped);StackEvaluator::new()takes no profile. - 5c, the matrix layer and the last scalar methods. IMPLEMENTED
(2026-10-10):
LazyMatrixExpr<T = FixedPoint>andDomainMatrix<T: FascFormat = FixedPoint>on the container pattern of phase 3 (the impls onFixed<S, F>),evaluate_matrix;from_str,try_from_str,Display,try_pow,try_atan2on everyFixed<S, F>that is aFascFormat(the literal path throughliteral_to_storage, the canonical fallback throughgmath_parse+evaluate); the profile-bounddecimal_literal::to_storagegone. As in phase 3, the default type does not drive inference on a generic constructor, so a bareDomainMatrix::from_strings(..)names its format (DomainMatrix::<FixedPoint>::); the profile-bound tests were annotated. Thegmath!helpers stay profile-bound (they returnLazyExpr<FixedPoint>) until phase 7 decides the inference story for a literal that is only displayed; an exact-decimal value variant was not added. Gates: the all-widths gate gained a matrix tree on four formats, a decimalDomainMatrixround trip and the scalar paths on six formats; the lib, matrix, differential and ugod suites green on realtime Q22.10 and embedded.
8. Other modules
-
DecimalFixed: arithmetic is already profile-independent (i128 storage, D256 intermediates). Transcendentals pick their compute tier from the profile today (
DECIMAL_COMPUTE_DP9/19/38/77/154), which is why D > 9 is aPrecisionLimiton the realtime profile. Under types the decimal compute tier is a function ofDalone: the narrowest tier whose working precision coversDwith today's guard digits. Results are correctly rounded today, so for every D that some profile serves, the D-selected tier reproduces that profile's output; the gate checks it. -
Geometry, dynamics, tensors (phase 4a, done): traits generic over
T: Scalar, structs that hold scalars generic with the default (Tensor<T = FixedPoint>,OdePoint<T>,Moebius<T>,VectorBundle<T>, ...), structs that hold only dimensions unchanged (Sphere,SO3, ...) with width-generic methods. -
Interval, predicates (phase 4c, done):
Interval<T = FixedPoint>,PdVerdict<T>, the predicates generic over the format.incircleandinsphereare bounded byS: CircleStorage, so on Q256.256 they are absent by trait bound (a compile error naming the reason) instead of by cfg. The directed division, the certified square root (now onWideInt::isqrt, Newton on the word types, the nativeisqrton the primitives) and the storage-unit constants are functions of the word and the split. The profile-bound accumulator module survives only as the reference of its own tests. -
compute_tier, wide (phase 4b, done):
compute_tierkeeps its free functions, generic over the format:exp::<T>(x),sigmoid::<T>(x),to_fixed::<T>(x)onCompute<T>raws,from_fixed(x)inferring the format from its argument.wide(Q64.64 kernels at native precision) stays as is; it was already profile-independent. -
fused (phase 4b, done): every kernel generic over
Fixed<S, F>. The word-specific fast paths (the i64 softmax numerators at F <= 15, the u128 reciprocal root, the AVX2 dot of many keys, the Q64.64 sigmoid and entropy gates on the 32- and 64-bit words) are hidden methods ofStoragewithNone/falsedefaults, so a kernel asks the word for its fast path and takes the generic body otherwise. They work on raw slices and are generic over the split, which keeps the arithmetic of 0.6.7 to the bit. A per-element hook returningOption<Result<..>>costrms_norm5 to 7 percent (the enum per element again, as with the add operator); the hook runs over the slice instead andrms_normis 12 percent faster than 0.6.7. -
tq19 and the inference module (phase 4d, done): activations are
&[Fixed<S, F>]and resultsVec<Fixed<S, F>>(owner decision: the format travels with the data, no turbofish, mixing splits is a compile error; raw buffers are viewed throughFixed::from_raw_slice). Weights, trit codes, Q32.32 scales and the wide outputs stay raw. Two public sealed traits intq19:TqWord(every word; hidden hooks for the i32 AVX2 and exact paths and the per-word scale rounding) andWideOutput(i32 and i64: the wide matvec and the row-scaled forms), somatvec_q2fandRowScaledTQ19are absent on the wide words by trait bound. The five-trit form isFixed<i32, F>only (its raw kernels unchanged, the wide shift32 - F). -
Serialization: today's tag says which storage word, not which
F, so bytes written at Q16.16 read back silently as Q22.10. The 0.7.0 format writes[storage code, F]. Legacy tags stay readable as "storage word, F unknown", accepted only by an explicitfrom_bytes_legacy::<T>(). -
#[repr(transparent)] on
Fixed, with a documented guarantee, so&[Fixed<S, F>]and&[S]views are sound (bytemuck-style casts without the dependency: twounsafefns with the layout argument in their docs).
Refined for the build (2026-10-10, after phase 5), in two sub-phases:
-
6a, the decimal compute word from
D. IMPLEMENTED (2026-10-10, redone 2026-10-14 with the ladder). The decimal engines are generic over their compute word (phase 5b,DecimalWord), soDecimalFixed<D>picks its words through a marker:Dp<D>: DecimalTierwith aFastword and a sureWordone step wider (i128 then I256 up to D = 9, I256 then I512 to 19, I512 then I1024 to 38, I1024 alone to 77); the transcendental block ofDecimalFixedcarries the bound (a generic function overDthat calls one writeswhere Dp<D>: DecimalTier); arithmetic, parsing and formatting stay unbounded. Every transcendental runs on the fast word and moves to the sure word when the fast one overflows (argument or result beyond its range), when the rounding toDis ambiguous (the discarded digits within 10^-4 of the guard range of a boundary: zero, a half or a whole unit) or when a function's own guard asks (tan with |result| above 10^k, k = (guard digits - 2) / 2: next to a pole the quotient's error grows with tan^2 and outruns any rounding margin). The decision depends only on the input, so every build returns the same integer. The rule was measured, not assumed (tests/decimal_tier_by_d_validation.rs: every word at everyDagainst mpmath, 1105 ordinary cases plus 468 next to the singularities and range limits): a word with fewer than about ten guard digits misrounds (i64 at D = 4 by one unit through double rounding, at D = 9 by 20; i128 at D = 19 by 14; I256 at D = 38 by 12); with ten guard digits and no fallback the misses were the overflows (1e30 at D <= 9, sinh(83) at D = 2), two ties (atanh at D = 9, sqrt at D = 19 on I256 itself) and tan next to pi/2 (0.74 at D = 9); with the ladder 1573 of 1573 cases are exact. One formula defect found on the way:atanhformed (1+x)/(1-x) on x itself, a tiny quotient with ten significant digits next to -1; it now works on |x| and negates (0.6.7 has the loss on every profile). Perf (release, one binary per crate, 0.6.7 / tree, ns): compact at parity for D <= 9 (exp 1970 / 1959, ln 739 / 750, sqrt 3952 / 3968, atan 1083 / 1095); embedded 5 to 30 times faster at D <= 9 (ln 22727 / 747, atan 25987 / 1068) and at parity at D = 19; realtime slower at D <= 9 because its i64 word is gone (ln 131 / 750, exp 1356 / 1963, atan 179 / 1095), the price of correct rounding and the full storage range there (0.6.7's realtime results at D = 4 carried double-rounding errors and at D above 9 were coarse; itsPrecisionLimitis gone). Compact and realtime at D = 19 move to I256 (0.6.7 computed D = 19 on i128 with no guard digit, 14 units off). One residual on embedded: exp at D = 19 reads +7 percent with 32-byte branch padding on both crates (sqrt at D = 19 reads -1), and the experiments split it three ways at about 2 percent each: the I256 path as such, the ladder's branch, and the presence of the I512 sure instantiation; the narrowing itself measures equal (760 against 764 ns on I256 values above the i128 boundary, 99 against 100 below it). It is the division-bound I256 engine reacting to code placement, the same class as the sqrt and atan2 reading of phase 5c, and the word-serial division of the ROADMAP follow-up is the fix that shrinks it. Gates: the differential gate per build at nineD(identical outcomes required wherever 0.6.7's word had ten guard digits and is not the fast word itself; elsewhere differences counted and an error-to-value change allowed), the mpmath gate overDin one build, the exp-range references regenerated for theD-selected words (one table for every build, tops at the storage range), the decimal suites with their profile-bound expectations rewritten (the tan pole, the atanh next to one, the huge-ratio atan2, the compute-tier argument cases). -
6b, serialization v2. IMPLEMENTED (2026-10-10, redone 2026-10-14).
to_byteson everyFixed<S, F>writes[0x20 | storage code, F as two big-endian bytes][raw big-endian](codes 1 to 5 for i32, i64, i128, I256, I512;format_tag()returns the three bytes; the first pass wroteFin one byte and the scientific gate caught Q256.256's F = 256 wrapping to 0);from_bytesaccepts only that pair;from_bytes_legacyreads the 0.6.x tags (0x01 to 0x05 and 0x80 | F) when the storage word matches and, where the tag names a split, the split matches too (0x05 is taken for the reader's split, as every realtime split wrote it up to 0.6.4);legacy_tag()is what a 0.6.x build of the format wrote andFixedPoint::profile_tag()keeps returning it. The vector, matrix, tensor, manifold-point and compact forms keep their 0.6.x layout (no tag, elements raw) and are generic over the format through hiddenStorageitems (CODE,BYTES,to_be_vec,from_be_slice);ManifoldPoint<T = FixedPoint>; the serde impls generic. One defect fixed on the way: the compact form of the word's minimum panicked inabsup to 0.6.7, it is now the full class with the two's complement bytes. Gates: the differential gate reads 0.6.7's scalar bytes through the legacy entry and refuses them throughfrom_bytes(and 0.6.7 refuses the new tag), the raw and compact scalar bytes and the vector, matrix, tensor and manifold-point bytes are identical and readable in both directions; the lib,linalg_validation,s1_serialization_extendedanddefects_065pins moved to the new tag. -
7, the library without a profile. Refined for the build (2026-10-14, after phase 6, census on d4c4cf5). What still reads the profile in
src/:ProfileFormat(Fixed<BinaryStorage, FRAC_BITS>from the cfg) behind twelve delegating wrappers (__pre_integer,ternary_to_storage,try_to_binary_storage,decimal_compute_to_binary_storage,downscale_to_storage,make_compute_int,storage_frac_bits,compute_bit_length,narrow_triple_floor/ceil/nearest,divide_to_storage_nearest, linalg'sround_to_storage,upscale_to_compute,compute_zero/add/sub,compute_tier_mul_pair) whose callers are unit tests or one function (compute_tier_trit_dot_raw); the profile-named engine wrappers*_binary_iN,*_compute_tier_iN,pi_half_iN(five engine files plus their re-exports; callers: seven integration tests and the evaluator's unit tests, no library code); theBinaryStorage/ComputeStoragealiases;frac_config(behindFixedPoint,compute_tier::{FRAC_BITS, COMPUTE_FRAC_BITS, ComputeStorage},TIER1_DEFAULT_FRAC_BITS, the realtimeexp_binary_i64upshift, one unit test);DECIMAL_COMPUTE_DP/DECIMAL_STORAGE_MAX_DP/WideComputeindecimal_compute.rs(dead since 5b, the format trait carries them); the per-profile unit test modules of the decimal engines; twoFixedPoint-only impls (FixedVector<FixedPoint>::{length_fused, distance_to}); 46T = FixedPointdefaults. On the test side: 99 integration files, 980 lines namingFixedPoint, 427cfg(table_format)lines in 73 files, 74frac_configreads in 44, 39 reference tables of which 19 are per profile. In three steps:- 7a, the library. IMPLEMENTED (2026-10-14; the record follows the
plan).
ProfileFormatand every wrapper deleted; a live caller becomes generic, a test-only wrapper's tests call the kernel with an explicit format. The engine wrappers deleted (their tests call the format-named engines,exp_q64_64and so on, or theFixedmethods).BinaryStorage,ComputeStorage, thecompute_tierre-exports and the dead decimal constants deleted.TIER1_DEFAULT_FRAC_BITSbecomes the constant 16: the only callers of the no-parameter tier-1 forms are the ladder's own wider tiers and unit tests, the evaluator has passed the format'sTIER1_FRAC_BITSsince 5b. TheFixedPoint-only impls becomeimpl<T: FixedNum>.FixedPoint,frac_configand thetable_formatcfg stay as SCAFFOLDING for the tests (marked in the source as such,build.rsemits nothing else per profile); theT = FixedPointdefaults stay with them until 7c. Gate: the ten-build sweep unchanged, the differential and all-widths suites,PUBLIC_API.mdregenerated, and a grep check thatsrc/outsidecfg(test)names none oftable_format,frac_config,BinaryStorage,ComputeStorage,ProfileFormatbeyond the scaffolding definitions. As built: every one of the 115 engine wrappers and the twelve delegating wrappers was dead or test-only, so the public surface did not move (PUBLIC_API.mdregenerated: no diff); their bodies live on verbatim in the two tests that pinned their per-profile routing (transcendental_ulp_validation,wide_q64_validation), the enginessqrt_q*,sin_q*,atan*_q*arepubin the hidden module likeexp_q*;wide_acc.rswent entirely (its four tests are generic over six formats inkernels); four print-onlytrace_*tests were deleted; the decimal engine unit tests that ran only on embedded run on I256 (and the limb division on I512 and I1024) in every build, so the realtime library test count rose from 332 to 373. Gate script.gates/no_profile_in_lib.py(local): 0 reads outside tests and the marked scaffolding. - 7b, the tests. IN PROGRESS (2026-10-14, one build green per file,
the full-suite runs pending). As built, the mechanism is a macro rather
than generic functions: a suite file is
macro_rules! suite { ($m:ident, $S:ty, $F:literal) => { mod $m { type FixedPoint = Fixed<$S, $F>; const BITS; const FRAC_BITS; <the file's body unchanged> } } }andfor_each_format!(suite)fromtests/common/mod.rsinstantiates it at Q22.10, Q16.16, Q32.32, Q64.64, Q128.128 and Q256.256, so one binary runs the old per-profile body at six formats andFixedPointinside it is the module's alias, not the crate's. Defaulted containers get module aliases (type FixedVector<T = FixedPoint> = ...), defaulted traits are named (Manifold<FixedPoint>), the canonical entry points become their_informs (gmath::<FixedPoint>,evaluate). A profile cfg arm becomes aBITS/FRAC_BITScondition (aletorconstif-chain, an early return in a test, a panic carrying the expected text in a should-panic test); a part written for some words only (32-bit raws, the row-scaled forms, the circle predicates below the 512-bit word, per-word reference tables) becomes a second suite macro instantiated at those words, with the file's non-test items in ashared_items!macro both use; innermacro_rules!move to file level (their metavariables would be read by the suite macro), one per word where the bodies differed. The reference tables that selected by profile (certified_geometry_refs,compute_tier_refs,decimal_exp_range_refs,fasc_ulp_refs_q16,wide_q64_refs) now carry every format's table and select by the including module'sBITSandFRAC_BITS(generators updated). Unit counts across words read the raw bit by bit (raw_units) instead of casting. Eleven print-onlytrace_*files were deleted and the three that asserted became explicit-format pins.differential_065_validationis the one suite that keepscfg(table_format): it mirrors the published crate's build, and its new type is now derived from the old crate's storage word and split (Mirror), not fromfrac_config. - 7b, the plan was. Each integration test generic over
T: FixedNum(orFascFormat), instantiated through onefor_each_format!intests/common/atFixed<i32, 10>,Q16_16,Q32_32,Q64_64,Q128_128,Q256_256, with the realtime splits F = 2..30 as types where a suite had a per-split corpus; a profile cfg arm becomes amatchon(T::Storage::BITS, T::FRAC_BITS)or a per-format table; the per-profile reference tables get a format selector; the differential suite picks its format from the published crate's own constants (g_math_065'sFRAC_BITSand word size), so the profile matrix survives only there. File by file, the scaffolding shrinks as files convert, each file green on the ten builds before the next. - 7c, one build. Scaffolding,
frac_config,FixedPoint, the defaults, the profile features,GMATH_PROFILE/GMATH_FRAC_BITSinbuild.rs,table_formatincheck-cfgall deleted; CI one build per toolchain with--features inference,serde, plus the differential job's five-profile matrix for the published crate. Thew32..w512width features of section 9 are DEFERRED: the full lib's compile time is measured first and recorded; if one build is short the features are not worth their cfg surface. IMPLEMENTED (2026-10-16). As built:FixedPoint,BinaryStorage,ComputeStorage,frac_configand thecompute_tierre-exports deleted; theT = FixedPointdefaults removed; the canonical entry points are the generic forms under the plain names (gmath,evaluate,gmath_parse,evaluate_sincos,evaluate_sinhcosh,evaluate_matrix; the_innames gone), so a tree names its format once (evaluate::<Q64_64>(&e));profile_tagremoved (legacy_tag);build.rsreads no environment and emits no cfg; the profile features and the 42cfg(not(feature = "embedded"))arms (always true without the feature) removed; thegmathCLI computes in Q64.64. The library's unit tests are suite macros at the six formats (for_each_format!inlib.rs), a profile arm anon_words!block kept for its storage words (1108 lib tests, 373 per build before). The differential gate moved to its own unpublished cratedifferential/, whose build script mirrors the published crate'sGMATH_PROFILEascfg(published_profile), so g_math has no 0.6.7 dev-dependency. The realtime splits the CI matrix ran throughGMATH_FRAC_BITSare test-only cfgs:gmath_all_splitsadds F = 8, 12, 20, 24 to every suite,gmath_edge_splitsF = 2, 4, 6, 26, 28, 30 (run for the four split-generic gates). The chain, exp full-range and geometry generators gained the F = 8, 12, 20 tables. Gates: full suite in one build 92/92 binaries, 7103 tests; all splits 89/89 binaries, 11,154 tests (the three correct-rounding gates then 44/44 with the new tables); edge splits 531/531; differential at six published builds (realtime F = 10 and 16, compact, embedded, balanced, scientific) 13/13 each. Compile time, clean, this machine: the whole library with all five widths 38 s release (35 s without features), 10 s debug, against 26 s (embedded) and 33 s (scientific) for 0.6.7 at one profile; the full test build 19.5 min. Thew32..w512features are therefore not added. CI (ci.yml,differential.yml) replaces the eight per-profile workflows. - Kept from the spec: no default width (section 3); the
Q16_16toQ256_256aliases exist since phase 2;gmath!(its feature is not built) emits text;LazyExpr<T>without a default meansevaluate::<Q64_64>names the format at the root of a tree.
- 7a, the library. IMPLEMENTED (2026-10-14; the record follows the
plan).
9. Cargo features
w32, w64, w128, w256, w512, one per storage word, additive. A feature
compiles that width's Storage/FixedNum impls, engines and tables. Default:
all five. A consumer that wants a small build writes
default-features = false, features = ["w32"]. The profile features and
GMATH_PROFILE / GMATH_FRAC_BITS are removed in 0.7.0; build.rs no longer
emits table_format. Two crates enabling different widths get both; nothing
changes for either.
Binary size is pay-per-use regardless of features, because the linker drops unused widths (measured: realtime plus Q64.64 together cost 1.8 MB above std). Features bound compile time, not binary size.
10. Migration plan (each phase green before the next starts)
The trick that keeps every phase verifiable: until phase 7, FixedPoint
remains, defined as Fixed<BinaryStorage, FRAC_BITS> from the old cfg. The
entire existing test suite therefore keeps running per profile against the new
generic code, while new tests exercise all widths in one build.
| Phase | Work | Exit gate |
|---|---|---|
| 0 | Fixes that belong on main regardless (section 12), merged into the branch. DONE: 0.6.5 |
main CI green |
| 1 | Storage trait, uniform wide-integer surface, engines renamed to format names, *_binary_iN meanings frozen. IMPLEMENTED |
full sweep, 5 profiles + F = 8..24, unchanged |
| 2 | Fixed<S, F>, FixedNum, operators, conversions, 18 transcendentals; FixedPoint aliased. IMPLEMENTED |
differential gate (11.1) on scalars, all widths |
| 3 | FixedVector/FixedMatrix/ComputeMatrix, linalg, decompositions, matrix functions. IMPLEMENTED (3a kernels, 3b containers, 3c compute matrix + decompositions + derived, 3d matrix functions + the 32-bit wide matrix) | differential gate on linear algebra |
| 4 | Geometry layers, ODE, tensors (4a, IMPLEMENTED), fused ops, compute_tier (4b, IMPLEMENTED), Interval, predicates (4c, IMPLEMENTED), tq19 (4d, IMPLEMENTED) | differential gate, certified-geometry gates |
| 5 | FASC generic (LazyExpr<T>, StackValue<T>, per-format evaluators), canonical API. IMPLEMENTED (5a format trait, 5b typed value + registry, 5c matrix layer + scalar string paths) |
differential gate on the FASC corpus |
| 6 | DecimalFixed compute tier by D (6a); serialization v2 (6b). IMPLEMENTED | decimal gates per D, legacy-read tests |
| 7 | Remove profiles, frac_config, table_format; tests generic over width; CI one build per toolchain. IMPLEMENTED (7a library, 7b tests, 7c one build, 2026-10-16) |
full gate set in one build |
| 7.5 | The inference module (tq19) moved to the separate crate g_math_inference; inference feature and rayon removed from the core; Compute<T> and the wide integers exported. IMPLEMENTED (2026-10-17) |
extension tests equal to the moved ones; differential of the extension against 0.6.7 at six builds; core full suite |
| 8 | Docs (README, guides, PUBLIC_API regen, CHANGELOG, CONTRACT, ROADMAP, crate docs, panic texts), upgrade guide docs/UPGRADING_0.7.md, 0.7.0. IMPLEMENTED (2026-10-17) |
doc tests of every guide example, release checklist |
11. Acceptance gates
11.1 Differential bit-identity (R-BIT)
g_math 0.6.5 from crates.io is a renamed dev-dependency (g_math_065).
0.6.5 still reads GMATH_PROFILE / GMATH_FRAC_BITS; the branch crate
ignores them. So one test binary built with GMATH_PROFILE=p compares the old
crate at profile p against the new crate's matching type on the same inputs:
every public scalar function, the linear algebra and geometry surface, FASC
expressions and decimal functions, on the existing mpmath corpora plus a seeded
random corpus. Required result: zero differing bits, including identical Err
variants. Run for the five profiles and for F = 2..30 on the 32-bit width.
As built for the scalar surface: tests/differential_065_validation.rs.
Inputs are raw integers of every magnitude (random bit length, random sign)
plus the extremes; each call's outcome is a value, an error variant or a
panic, and all three must match. It runs with the ordinary suite on every
profile and split. tests/width_types_validation.rs is the other half that
only this design allows: every width in one binary, the same generic code
checked for exact identities at ten formats, and each narrower format
compared with Q256.256 (at most one unit apart; measured: exact on 136 to
141 of 141 cases per format).
11.2 Precision gates
The existing mpmath gates (fasc_ulp_validation, one_rounding_validation,
decimal, certified geometry, decomposition corpora, wide tier) become generic
over width and run for every width in one build.
11.3 Performance (R-PERF)
Criterion benches for the scalar operators, the 18 transcendentals, dot,
matvec, LU, SVD, softmax, tq19 matvec, FASC evaluate, per width, run against
g_math_065 in the matching profile on the same machine. Any regression beyond
2 percent blocks the phase.
Measured for the scalar layer after phase 2 (2026-10-06, against crates.io 0.6.7). Method that works: one binary per crate with the same harness, best of 25 rounds, five alternating process runs, minimum per op. A harness that links both crates into one binary is unusable at this resolution: code alignment moved 0.6.7's own numbers by 20 to 60 percent between builds in which 0.6.7 did not change, and sub-nanosecond operations quantise to whole cycles. Two real costs were found and removed before parity was reached:
- The 32-bit engine wrappers had become generic functions instantiated in
the consumer crate with a runtime shift; made generic over the split
again so the upshift is an immediate (
fixed_num::c32). - The IEEE bit assembler and
float_bitswere private and inlined in 0.6.5 and became cross-crate calls; marked inline (to_f64was 2x slower).
Result: transcendentals at parity or faster on realtime, compact and
embedded (sqrt, atan, asin 9 to 18 percent faster on the narrow profiles;
compact sincos 47 percent faster, it now uses the fused engine);
to_f64 at parity or 11 to 27 percent faster; mul, div, add, sub at
parity; from_int / to_int within one cycle per call in either direction.
The inference kernels are measured when their phase lands.
Measured for the containers and linear algebra after phase 3 (2026-10-06,
realtime Q22.10, same method, scratch perf3/src/bin/lin.rs): dot of 3,
32 and 1024 elements 7, 13 and 0 percent faster; 64x64 matvec within 1.4
percent; 16x16 matmul 20 percent faster (the generic dot kernel); LU, QR,
Cholesky, Jacobi eigen, SVD, matrix exp and sqrt all within 2 percent
(LU 8x8 read +3.2 percent plain and -0.8 percent under LTO, the
measurement band). Two real costs were found and removed:
- The generic
Add/Suboperators calledtry_add(...).expect(...); in 0.6.7 LLVM folded theResultto a single overflow branch, in the generic instantiation it materialised the enum per element (shift, cmov, compare, shift back: 64-element vector add +47 percent under LTO). The operators now match on the checked word directly; vector add is at parity under LTO and 38 percent faster without it. transposethroughfrom_fn+getkept one bounds check per element that 0.6.7's codegen had hoisted; written with explicit indexing it is 25 percent faster without LTO and at parity under LTO. Under LTO the harness first read +22 percent, which vanished once the call was isolated behind a never-inlined wrapper: inlining context inside the harness, not the library.
Phase 3 changed no scalar kernel; the scalar div re-read +7.7 percent at
Q22.10 without LTO, +2.8 under LTO, +1.6 at Q16.16 and -0.8 on compact,
which is the band of a 14 ns operation in this method.
Measured for the canonical layer after phase 5 (2026-10-06 to 2026-10-10,
realtime Q22.10, compact, embedded, balanced; same method, scratch
perf3/src/bin/fasc.rs): the cheapest tree (an integer add, 207 ns in
0.6.7) read +6.2 percent with the evaluator registry alone and -6 percent
with a one-entry last-used cache in front of it; decimal mix and chain,
division, parse, exp and display at parity or faster on every profile;
after 5c from_str, Display and try_pow within 1 percent, from_str
of a fraction 11 percent faster. One false regression was chased to the
end: sqrt and atan2 read +28 to +31 percent at Q22.10 on the tree
while the engine and the I256 division it runs are byte-identical in both
binaries, and a bisect over the phase commits is bimodal (phase 4b and 5a
at parity, phase 2, 4a, 5b and 5c slow) with no engine change between
them. With -C llvm-args=-x86-branches-within-32B-boundaries both crates
read the same (the tree 2 to 3 percent faster) and both 10 to 25 percent
faster than unpadded: the bit-serial I256 division (256 data-dependent
branches per quotient, 7 quotients per square root) is branch-bound and
its cost follows the consumer's link layout on Skylake-family cores. The
balanced sqrt note of phase 5b (I512, same shape) is the same effect.
The lasting fix is a word-serial division (ROADMAP follow-up), not a
change to the generic layers.
11.4 Size
The 2026-10-05 probe (sizeprobe, allprobe) rerun on the new crate: per-width
cost at most the 0.6.5 profile cost, all-widths cost at most the five-copy
measurement.
12. What changes on main before the branch lands
Defects and additive APIs that are independent of the width design ship from
main as 0.6.x and are merged into this branch, so consumers are not held
hostage to the refactor. Every item below was verified on 0.6.4 (5d0ecb2)
before being listed; the probes live in the 2026-10-05 session scratchpad.
12.1 Defects (found or confirmed 2026-10-05; fixed in 0.6.5 unless noted)
0.6.5 is the foundation this branch builds on. D1 to D5, D7 and D8 are fixed
there (gate tests/defects_065_validation.rs); the infallible tq19 forms
panic and no try_ twins were added; D3 keeps 0x05 for Q16.16 and writes
0x80 | F for other realtime splits; D6 was resolved by correcting the
documentation, and making the compute-tier decimal intermediates half-even
stays open for 0.7.0 behind an output-difference measurement.
| # | Defect | Evidence | Fix |
|---|---|---|---|
| D1 | tq19 narrowing wraps silently: ops.rs narrow_to_storage and shift_right_frac_and_narrow use as casts; scalar accumulators use plain + |
trit_dot(&[1,1], &[2^30, 2^30]) = -2^31 (true 2^31); tq19_dot(&[MAX_RAW; 8], &[i32::MAX; 8]) = -436426 |
checked narrowing, panic in infallible forms, try_ twins; breaks the 0.4.28-0.4.31 rule otherwise |
| D2 | fused::rms_norm_factor_eps_wide (and the storage-eps form) with negative eps returns Ok(0) |
sqrt_binary_i64 returns the sentinel i64::MIN for negative input; the caller checks only for zero |
Err(DomainError); audit every caller of the sentinel |
| D3 | Serialization tag records the storage word but not F: Q16.16 bytes load silently as Q22.10 |
serialization.rs PROFILE_TAG 0x05 for every split |
new tag carrying F; legacy tag read only when the reader's F is 16 or through an explicit legacy call (owner decision: persisted data exists) |
| D4 | Two profile features enabled at once: build.rs picks by priority, no error |
build.rs feature cascade |
compile_error on conflicting profile features or on env/feature disagreement |
| D5 | Decimal UGOD tier 6 multiply and divide narrow I1024 to I512 with as_i512 (low words) |
decimal_multiplication.rs, decimal_division.rs |
checked narrowing, rational fallback like the binary ladder top; probably unreachable through FASC today, fixed anyway |
| D6 | Docs say decimal rounding is half-even wherever it occurs; decimal compute-tier mul/div/div_int round half away from zero |
decimal_compute.rs |
make them half-even (moves FASC decimal-compute chains by at most one compute-tier unit before the final rounding; measure output change first) or correct the docs; owner decision |
| D7 | Currency / HighPrecisionCurrency listed public in PUBLIC_API.md but reachable only through a doc-hidden path |
fixed_point/mod.rs re-exports |
re-export at g_math::fixed_point |
| D8 | Undocumented Err conditions of fused::softmax, softmax_mix, rms_norm_factor_eps_wide |
doc comments | state each condition with its width envelope (for example softmax_mix numerator overflow at n * 2^(31+F) >= 2^63) |
Minor: DecimalFixed::convert_with_rounding has no try_ twin (panics on
upscale overflow); a whitespace-only decimal string reports InvalidFormat
rather than EmptyString; the tq19 module docs name a parallel feature that
does not exist.
12.2 Additive APIs requested by consumers, verified as sound
A1 to A9 shipped in 0.6.5 with the defect fixes (the five-trit matrices on the realtime profile only; caller-provided output buffers not included). Each was compared bit for bit with the downstream code it replaces. Under this design they are ported in phase 4 like the rest of the fused and inference surface.
| # | API | Why it is sound | Width relevance |
|---|---|---|---|
| A1 | Decimal rounding mode: RoundingMode for DecimalFixed::try_mul_with, try_div_with, convert_with_rounding_mode, mul_div; default stays half-even, so no existing result moves |
tie direction is policy, not arithmetic; the exact quotient is already computed (one rounding), only the tie decision changes; half-away is applied to the magnitude so f(-x) = -f(x) survives |
none: decimal arithmetic is profile-independent today |
| A2 | DecimalFixed::mul_div(self, num, den) with one rounding from the exact a * b / c |
the two-step form (product at 6 dp, divide, narrow to 2 dp) differs from single rounding on 22 of 1,200,000 VAT cases, all at two-decimal rates, measured in an exact-rational model and on the crate | none |
| A3 | Documented contract: try_div rounds once from the exact quotient |
verified end to end, including the D256 path | none |
| A4 | #[repr(transparent)] on FixedPoint and documented FixedVector layout, with safe slice views |
one non-ZST field; size 4 / align 4 measured on Q22.10; adds a layout commitment, changes no value | carried into Fixed<S, F> (section 8) |
| A5 | Bounded unchecked dot: if len * max|a| * max|b| < 2^(2·BITS-1) sum without per-term checks, else the checked loop |
no partial sum can overflow in any order under the bound; identical integer and identical panic otherwise; measured 3-4x faster per 128-element dot with native codegen | written once over Storage::BITS |
| A6 | fused::softmax_mix body without the i128 detour, a weights-free variant, a flat-buffer variant; dot_many over one key buffer |
a port of the requested body matched today's on 3,000 of 3,000 random cases (outputs and weights); (e*v + 2^9) >> 10 equals compute_multiply(e, v << 10) algebraically |
generic over F |
| A7 | Five-trit row-scaled projection matrices beside RowScaledTQ19 (i8 code in [-121, 121], Q32.32 row scale, matvec families, AVX2 with scalar fallback, stable byte layout) |
same contract shape as RowScaledTQ19; independent of storage width except the q2f shift and the AVX2 split for 32-bit activations |
belongs to the generic inference module |
| A8 | Exact bit-pattern decoders (bf16, binary16 to fixed raws) and quantisers for the ternary formats | integer shifts only; exhaustive over 65,536 patterns | generic over F |
| A9 | Fused RMS norm application (normalised weighted vector, in place and out of place), pair rotation (rotate_pairs with a rotary prefix), caller-buffer batch forms |
compositions of existing contracted ops with one rounding each | generic over F |
Declined or held, with the reason:
- Importing a non-correctly-rounded kernel bit-identically. A requested
Q.40 exp truncates at every step: at most 5 units at Q.40, correctly rounded
on 2,651 of 4,000 inputs. It cannot sit under this crate's correctly-rounded
contract. Measured alternative:
floor(wide::exp_q64(x << 24) >> 44)equals the requested kernel's Q.20 output on 10,000,000 of 10,000,000 inputs (and both are correct there), so a consumer that only consumes Q.20 can switch without a numerics epoch. The sigmoid, softplus and silu compositions at Q.40 were not compared yet; each needs the same measurement before a decision. - A truncating decimal-literal parser. The crate parses literals to
nearest, ties toward +inf (0.6.4, bit-identical to
from_str). A consumer parser that truncates differs on ordinary inputs ("0.0007" at F = 10: 1 vs 0). Adopting the crate parser is a numerics epoch for that consumer; the crate does not add a second rounding rule for literals. - A SiLU saturation request. Stale: fixed in 0.4.29;
fused::silureturns 0 for every input from -20 down to the most negative raw at F = 10 and F = 16, and is correctly rounded on a 3,000-sample mpmath check. A consumer-side clamp at +-12 is exact only at F = 10 (it disagrees with the exact result on 321,712 of 8.4 million raws at F = 16) and should be removed rather than generalised. - A public path for the realtime compute-tier exp. Already exists:
g_math::compute_tier::exp(featureinference) is bit-identical by construction and on 200,000 probed inputs.
13. How the inference module fits the width design
The inference kernels are where the width design pays off first: they already combine a 32-bit storage split, a 64-bit compute tier, Q32.32 scales and Q64.64 wide kernels in one consumer, which is a multi-width program written by hand today. Under section 4:
- Storage-side kernels (A5-A9, tq19, the five-trit format) are generic over
Fixed<i32, F>and, where meaningful,Fixed<i64, 32>. The AVX2 paths are selected byT::Storage = i32, not by profile. - A wide state tier (for example Q.40 in i128) becomes an admitted split of
i128after 0.7.0, with its own mpmath gate. Until then the measuredwide::*_q64plus explicit narrowing is the supported route. - Kernels added on
mainbefore the branch lands are written againstBinaryStorage/FRAC_BITSlike the code around them, and ported toT: FixedNumin phase 4 with the differential gate proving the port changed no bit.