Cosa fa
- Batch in layout structure-of-arrays e array-of-structures
- Scalare, SSE2, SSE4.1 e AVX2, scelti una sola volta
- Bit identici su ogni percorso (niente FMA, di proposito)
- Approssimazioni veloci con l'errore misurato su ogni float del dominio
- Quaternione, trasformazione, piano, raggio, AABB, sfera, frustum
- Layer C per i tipi
Misurato
- i7-6700, Release, AVX2 contro scalare, 512 punti in L1, GCC 15.2 / MSVC 19.51. <code>TransformPoints</code>: 4.4x e 4.2x. In structure-of-arrays: 7.4x e 6.4x
- <code>NormalizeBatchSoa</code>: 9.0x e 8.1x
- Prodotto scalare e vettoriale su punti interleaved: 2.7x e da 1.9x a 2.2x, distanza interleaved 2.8x su MSVC. Obiettivo da 3x a 4x non raggiunto (le varianti structure-of-arrays arrivano da 4.1x a 4.8x)
Limiti noti
- Niente doppia precisione. AVX-512 è implementato e gira solo su richiesta, perché il suo guadagno non è mai stato misurato. Niente NEON
Ethereal::Math, Ethereal::Vector, Ethereal::Matrix
---
The page's claim, resolved on the code side
The product page says "SIMD math: vectors and matrices", and the module did not have a single line of SIMD. The spec gave two ways out: implement it or correct the text. It was implemented. What the page can say now, with the numbers below, is "batch SIMD math". The single-element types (CVector3D, CMatrix4x4) remain scalar on purpose (see the next section). The page itself is outside this repository. The exact text is a product decision (TO DECIDE).
---
Where the SIMD lives: in the batch functions
A float4 wrapped in an __m128 looks fast and usually comes out slower, because each access to a component pays for a load, a shuffle and an extract. That is why CVector3D and CMatrix4x4 stay plain floats, constexpr and trivially copyable, and the gain is in batch.hpp: transforming, normalizing and multiplying thousands at once.
#include <ethereal/cpp/math/math_inc.hpp>
namespace Mth = Ethereal::Math;
Mth::TransformPoints( M, points, out ); // std::span, no allocation
Mth::NormalizeBatch( normals, normals ); // output same as input: allowed
// The fastest path: structure of arrays (x, y, z separate), with no shuffling at all.
Mth::TransformPointsSoa( M, Mth::SSoaConstVector3( x, y, z ), Mth::SSoaVector3{ ox, oy, oz }, n );
Mth::TransformPointsSoaAligned32( M, ... ); // pointers aligned to 32: the requirement is in the name
Mth::DotBatchSoa( A, B, n, out ); // and the rest of the vector operations, also in SoA| Function | Bit-for-bit equal to |
|---|---|
TransformPoints, TransformPointsSoa, ...Aligned32 | CMatrix4x4::TransformPoint (divides by w) |
TransformDirections | CMatrix4x4::TransformDirection |
MultiplyBatch | CMatrix4x4::operator* |
NormalizeBatch, DotBatch, CrossBatch, LengthBatch and the ...Soa variants | the CVector3D methods |
DistanceBatch, LerpBatch and the ...Soa variants | Geometry::Distance3D, Interpolation::Lerp per component |
AosToSoa, SoaToAos | copy |
The structure-of-arrays variants (NormalizeBatchSoa, DotBatchSoa, CrossBatchSoa, LengthBatchSoa, DistanceBatchSoa, LerpBatchSoa) are new since batch 3. They exist because the light operations over interleaved points do not reach 3x (see "The gains").
Each function processes the smallest of the sizes it receives. Output equal to input is allowed. Partial overlap is not. The only difference in behavior is a near-zero w: TransformPoint asserts |w| > EPSILON and stops the program, and the batch gives what IEEE division gives.
---
The dispatch: resolved once
The first call chooses the path through Cpu::ActiveSimdLevel() and stores a table of pointers. From then on a public function is one load and one indirect jump. Checked in the generated code (GCC 15.2, -O3):
NormalizeBatch: mov g_pActive(%rip),%rax ; the active table
cmp / cmovbe ; min( In.size(), Out.size() ), branchless
mov 0x28(%rax),%rax ; the table entry
jmp *%rax ; tail jump to the kernelThere is no query to the processor and no "have I resolved it yet?". The pointer starts out pointing to a table of resolvers, and each resolver writes the right table and continues. BatchPath() declares the path that was chosen (Scalar, Sse2, Sse41, Avx2, Avx512), and Detail::ForceBatchPath pins it for the test suite and for measuring. Without that, on a machine with AVX2 the scalar and SSE2 code would never run.
| Path | Status |
|---|---|
| Scalar | ✅ (also the one for ARM) |
| SSE2 | ✅ x86-64 baseline, also the one for SSSE3 |
| SSE4.1 | ✅ the SSE2 lane with selection through blendvps. Gains 10% to 20% over SSE2 in the approximations (where there are selections) and ties on the rest. Also the one for SSE4.2 |
| AVX2 | ✅ /arch:AVX2 / -mavx2, only after Cpu confirms AVX2 and XGETBV |
| AVX-512 (F) | ⚠️ implemented and checked, but not chosen on its own. See below |
| AVX (without 2) | ❌ not implemented: AVX1 has no 256-bit integers, which the approximations use, and machines with AVX1 and without AVX2 (Sandy/Ivy Bridge, 2011 to 2012) run SSE4.1 |
| FMA | ❌ on purpose: it changes the bits (rounds once instead of twice). If it comes, it is another function with another name |
| NEON | ❌ not implemented: there is no ARM machine or ARM emulator on this machine (the owner decided not to install one). On ARM the scalar path runs |
AVX-512. Sixteen floats per register, with the F subset only (the bitwise operations on floats, which belong to DQ, are done on integers, and selection uses the mask registers). It gives the same bits as the other paths, and the entire batch test suite passes on it. It ran on Intel's emulator (SDE 10.13.1, -skx), with the GCC binary and the MSVC one, and the emulator counted the 512-bit instructions executed (32 thousand in the InPlace test alone). What is not known is whether it gains: this machine (i7-6700) has no AVX-512, and the emulator does not measure time. The first processors with AVX-512 lower their frequency with 512-bit instructions, and a path that may come out slower is not turned on by default without a number. That is why dispatch stops at AVX2, and AVX-512 runs only when requested (Detail::ForceBatchPath( Cpu::ESimdLevel::Avx512 )), and only where Platform::CpuFacts confirms usable AVX-512F (the instruction and the ZMM state saved by the system). TO DECIDE / measure: on a machine with AVX-512, run math.batch.measurements with AVX-512 forced and, if it gains, turn it on in the dispatch.
Cpu::ESimdLevel gained the value Avx512 (7), but the Cpu ladder (DetectedSimdLevel, ActiveSimdLevel) still stops at AVX2. The existing modules ask "is it AVX2?" (the Encoding C layer even publishes the value), and on a machine with AVX-512 they would no longer find their path.
---
Determinism: the paths give the same bits
Each kernel is written once (src/cpp/math/batch_generic.inl) over a "lane" with the same IEEE operations (addition, subtraction, multiplication, division and square root, correctly rounded), without FMA, in the exact order of the scalar code that already existed. The five translation units (scalar, SSE2, SSE4.1, AVX2, AVX-512) instantiate that text with their lane, and the remainder of a vector path is literally the scalar code. Result: all paths give the same bits, and the same ones as the methods of the types.
Where the arithmetic is component by component before summing (the dot product, the distance, the length), it is done on the registers as they come from memory, and the result is deinterleaved afterward: (x·x' + y·y') + z·z', with the same products and the same order of additions, only done before the values change places.
The conditions:
- No FMA contraction. The batch units compile with
-ffp-contract=off(GCC in GNU mode contracts by default, and with-march=nativeit would have FMA for that). MSVC does not contract without/fp:contractor/fp:fast. **User code that calls theinlinemethods of the types compiles with the user's own options**: with-march=native -ffp-contract=fast, the user'sTransformPointmay stop matching the batch. The test suite compiles the oracle with contraction turned off. - NaN: the promise is "NaN on both sides". The payload may differ.
- Rounding mode and FTZ/DAZ are those of the process. On x86-64 the scalar code also runs on SSE, so the paths change together. The test suite turns on FTZ+DAZ and checks that they stay equal.
- Subnormals are not flushed to zero by any path (no FTZ).
- The
Fast*approximations give the same bits for the single value and for the batch, on every path and on every x86-64 machine: they do not usersqrtps/rcpps, whose bits differ between Intel and AMD.
---
The fast approximations
None of them is the exact function. Each one has its own name (nothing depends on -ffast-math), and the published error is measured on every float in the domain, without sampling (tools/math_check/exhaustive_error.cpp, 49 s on 8 threads). The test suite asserts the same bounds on a sample of 2 million.
| Function | Domain | Maximum measured error | Floats swept | Gain over std:: (AVX2, 4,096 values, GCC / MSVC) | ||
|---|---|---|---|---|---|---|
FastInvSqrt | positive normals | 4.735e-6 relative | all in [1, 4) (the estimate repeats every 2 exponents) + the two extremes | 7.5x / 7.1x over 1/std::sqrt | ||
FastSin | \ | x\ | ≤ 8192 | 7.77e-8 absolute | 2,348,810,242 (all) | 9.4x / 15.9x |
FastCos | \ | x\ | ≤ 8192 | 7.82e-8 absolute | 2,348,810,242 (all) | 9.7x / 15.3x |
FastExp | [-87.68, 88.37] | 8.16e-8 relative (normal result) | 2,237,667,740 (all) | 4.0x / 6.6x | ||
FastLog | positive normals | 8.12e-8 relative | 2,130,706,432 (all) | 2.6x / 4.0x | ||
FastAtan2 | finite | 2.78e-7 absolute, 2.34e-7 relative | 2^28 random pairs (the domain is flat) | 10.6x / 15.8x | ||
FastNormalize | as Normalized | 4.8e-6 per component (that of FastInvSqrt) | sample | n/a | ||
FastDistance | normal d² | 4.8e-6 relative | sample | n/a |
Sine and cosine publish the absolute error. Near the zeros of sin and cos the relative error grows without bound in any approximation that reduces the argument in float (measured: 8e-5 near x = 6715), and publishing that number would mislead in one direction or the other.
Outside the domain the result is defined and tested (and the same on every path): FastLog(±0) = -inf, FastLog(+inf) = +inf, negative and NaN give NaN. FastSin(-0) = -0, NaN and ±inf give NaN. FastExp saturates (it gives neither 0 nor +inf). FastAtan2(±0, -0) = ±π, the two infinities give NaN. FastInvSqrt(0) is large and finite. Subnormals give wrong values in the functions that read the exponent (FastInvSqrt, FastLog): they are outside the domain, and that is documented.
---
The gains, measured
Machine: the development one (i7-6700, AVX2), GCC 15.2 on WSL2 and MSVC 19.51 on Windows, Release. ns per element, the best of 21 measurements (three full runs of math.batch.measurements, seven repetitions of at least 2 ms each), and the gain of AVX2 over the scalar path (which compiles without auto-vectorization, to be truly scalar). The full table, with SSE2, SSE4.1 and out of cache, comes out of the test.
The sizes: 512 points fit in the L1 cache with the inputs and the output of the heaviest operation (18 KiB). 4,096 fit only in L2. The light operations are bound by the cache they read from, and the gain changes with that, which is why both are published.
Vector and matrix operations, 512 points (in L1):
| Operation | Scalar GCC | AVX2 GCC | Scalar MSVC | AVX2 MSVC | Naive loop (GCC / MSVC) |
|---|---|---|---|---|---|
TransformPoints (interleaved) | 4.09 | 0.92 (4.4x) | 3.97 | 0.94 (4.2x) | 6.29 / 4.49 |
TransformPointsSoa | 4.07 | 0.55 (7.4x) | 4.01 | 0.62 (6.4x) | n/a |
NormalizeBatch | 4.38 | 0.97 (4.5x) | 4.21 | 0.99 (4.3x) | 2.46 / 3.30 |
MultiplyBatch (per matrix) | 17.8 | 2.43 (7.3x) | 14.0 | 3.25 (4.3x) | 4.97 / 17.9 |
LerpBatch | 1.39 | 0.23 (5.9x) | 1.59 | 0.30 (5.2x) | n/a |
LengthBatch | 1.12 | 0.30 (3.7x) | 1.03 | 0.30 (3.4x) | 0.49 / 1.64 |
DistanceBatch | 1.55 | 0.47 (3.3x) | 1.40 | 0.50 (2.8x) | n/a |
DotBatch | 0.92 | 0.35 (2.7x) | 0.98 | 0.36 (2.7x) | 0.96 / 2.05 |
CrossBatch | 1.52 | 0.80 (1.9x) | 1.79 | 0.81 (2.2x) | 1.79 / 2.65 |
NormalizeBatchSoa | 4.26 | 0.47 (9.0x) | 3.93 | 0.49 (8.1x) | n/a |
DotBatchSoa | 0.97 | 0.23 (4.2x) | 0.97 | 0.23 (4.2x) | n/a |
CrossBatchSoa | 1.53 | 0.35 (4.4x) | 1.65 | 0.34 (4.8x) | n/a |
LengthBatchSoa | 1.12 | 0.21 (5.5x) | 0.98 | 0.20 (4.8x) | n/a |
DistanceBatchSoa | 1.58 | 0.29 (5.5x) | 1.39 | 0.29 (4.8x) | n/a |
LerpBatchSoa | 1.39 | 0.34 (4.1x) | 1.52 | 0.35 (4.3x) | n/a |
The same, 4,096 points (in L2), AVX2 GCC / MSVC:
TransformPoints3.9x / 4.1xTransformPointsSoa7.4x / 6.5xNormalizeBatch4.4x / 4.2xMultiplyBatch5.8x / 4.2xLerpBatch3.6x / 4.3xLengthBatch3.1x / 3.0xDistanceBatch2.9x / 2.6xDotBatch1.9x / 2.4xCrossBatch1.8x / 2.2x- in structure of arrays:
NormalizeBatchSoa9.4x / 8.6x,DotBatchSoa3.1x / 3.2x,CrossBatchSoa3.0x / 3.4x,LengthBatchSoa5.3x / 4.6x,DistanceBatchSoa4.7x / 4.3x,LerpBatchSoa2.7x / 3.1x
The approximations gain 7.5x to 14x in L1 and L2 (table in "The fast approximations"), and keep gaining out of cache, because there the arithmetic still weighs more than memory.
What this means:
- The 3x to 4x target is met in L1 on everything, except the dot product and the cross product over interleaved points (2.7x and 1.9x to 2.2x) and the interleaved distance on MSVC (2.8x). Those are the operations with the least arithmetic per point, and what costs is deinterleaving: seven shuffles per register, all on the same processor port. The structure-of-arrays variants of the same operations give 4.1x to 9x, and that is why they exist. It is the path the documentation tells you to use for these operations.
- In L2 the light operations lose gain:
DotBatchSoadrops to 3.1x,LerpBatchSoato 2.7x / 3.1x, and the interleavedDotBatchandCrossBatchstay below 2.5x. The cause is the L2 bandwidth (LerpBatchSoareads 24 bytes and writes 12 per point). The kernel is not the limit. - Out of cache (1M points) the light operations are memory-bound, and SIMD gains nothing: measured from 0.9x to 1.6x. The transformations gain 2.5x to 2.7x, and the approximations 3x to 14x.
- Against user code the gain depends on the user's compiler. GCC auto-vectorizes the naive
operator*loop (4.97 ns), and against thatMultiplyBatchgains 2x. MSVC does not vectorize it (17.9 ns), and the gain is 5.5x. - Alignment: the aligned load instruction gains nothing. With the same addresses,
...Aligned32and the unaligned one measure the same (0.55 against 0.55 ns on GCC, 0.62 against 0.62 on MSVC, 4,096 points). What costs is the data being misaligned: 4 bytes out of place take the same operation to 1.03 to 1.08 ns. - The position of the arrays relative to one another matters, and more than alignment. With the six arrays of
TransformPointsSoa(4,096 points) at different offsets modulo 4 KiB: 0.54 ns. With all six at the same offset ("4K aliasing", what comes from allocating power-of-two arrays one after another): 0.71 ns. One combination of offsets (0, 672, 1344, 2016, 2688, 3360) gave 1.07 ns for another reason, which was not isolated. InLerpBatchSoawith 512 points: 0.34 to 0.36 ns separated, 0.48 to 0.58 ns adjacent. The measurement pins one offset for each array, from one of the common positions (Placeintests/math_batch_measurements.cpp), and prints the adjacent case at the end. - What changed in the kernels (batch 3, second pass): deinterleaving went from nine to seven shuffles per register. The dot product, the distance and the length compute the products and the differences before deinterleaving, and deinterleave one result instead of two inputs.
LerpBatchprocesses the interleaved floats as a single stream, without deinterleaving anything.LerpBatchwent from 2.0x to 5.9x, the distance from 2.5x to 3.3x, the dot product from 2.0x to 2.7x. Reading the streams shifted by 1 and 2 floats instead of shuffling was also tried: it measured slower (the dot product at 1.3x, because of loads that cross cache lines) and was left out.
---
Primitives (primitives.hpp)
SQuaternion, STransform, SPlane, SRay, SAabb, SSphere, SFrustum: constructible in constexpr, trivially copyable, with the conventions of CMatrix4x4 (right-handed, column vectors, q * p applies p first). The quaternion is checked against CMatrix4x4::Rotate on 2,000 axes and angles, composition against the matrix product, STransform against T * R * S built with the usual matrices, and the frustum against a LookAt + Perspective camera with known bounds. Intersections: ray and plane, ray and box (slabs), ray and sphere, sphere and box, frustum and point/sphere/box (conservative, and that is documented).
Double precision does not exist, neither in the vectors nor in the primitives. CVector3D is float only, and turning it into a template would change the public API. It remains to be done, and it is recorded here.
---
Implementation status (spec §5)
| Criterion | Status |
|---|---|
| Claim resolved | ✅ implemented. The page text ("batch") is a product decision, outside this repository |
| 3x to 4x gain | ⚠️ met in L1 on everything except the interleaved dot and cross products (2.7x and 1.9x to 2.2x) and the interleaved distance on MSVC (2.8x). The structure-of-arrays variants of those operations give 4.1x to 9x. In L2 the light operations drop (bandwidth), and out of cache nothing light gains. See "The gains" |
| Dispatch once, no per-call query | ✅ checked in the generated code (load + indirect jump). Concurrent resolution under TSan |
| Differential | ✅ bit for bit against the methods of the types, 1M vectors and 128K matrices per path and operation (including the SoA variants), fixed seed. Plus ETL_DIFFERENTIAL over arbitrary bytes. AVX-512 on Intel's emulator (GCC and MSVC binaries) |
| Specials | ✅ NaN, ±inf, subnormals, ±0 (20³ combinations): the same bits on every path, also with FTZ+DAZ |
| Remainder | ✅ every size from 0 to 32 (two AVX-512 widths) × 4 offsets, with a sentinel |
| Alignment | ✅ unaligned is correct. ⚠️ "aligned is faster" only holds for the data: the aligned instruction gains nothing (see above) |
| Error of the approximations | ✅ measured on every float in the domain and published. The test suite asserts it |
| Determinism across ISAs | ✅ bit-for-bit identical on the five paths, under the conditions listed above. No FMA on purpose |
| Dispatch: SSE2, SSE4.1, AVX, AVX2, FMA, AVX-512, NEON | ✅ SSE2, SSE4.1, AVX2. ⚠️ AVX-512 implemented and checked, but only on request (gain not measured: no machine). ❌ AVX1, FMA (on purpose) and NEON (no ARM here). See "The dispatch" |
| Conventions | ✅ written in CMatrix4x4 and asserted in MathConventions |
RotateLeft | ✅ already fixed in Bits (&31 + std::rotl). The one in aead.cpp was not (the comment said it was) and was fixed, with a regression static_assert in aead, hash and checksum, and the run-time test MathComplete.RotateLeftAtRuntime |
| Zero allocations | ✅ ETL_EXPECT_NO_ALLOC on every function, including the first call (the one that resolves) |
| Sanitizers | ✅ ASan+UBSan and TSan (GCC 15.2): zero reports |
| Whole test suite | ✅ full ctest after this: GCC 118/118, MSVC 122/122. Zero new warnings on both |
Types (§2.1): CVector2D/3D/4D, CMatrix2x2/3x3/4x4 exist, and now the seven primitives. The double variants are missing (see above). Complements (§2.5): AngleBetween (2D and 3D, through atan2( |a×b|, a·b ), exact also at small angles, where acos loses the digits). NormalizeAngle and WrapAngle already existed. The constants already covered π, roots, logarithms, conversions and tolerances, and nothing was added without a concrete request.
Defects found along the way: PrevPowerOfTwo( 2^40 ) gave 1 (the 64-bit argument was truncated to 32 before the logarithm, found by MSVC warning C4244, fixed and tested). The comment of CMatrix4x4 said "row-major (or column-major, by convention)" about a type that has always been column-major.
How the tests were checked
Twenty-five planted defects (tools/math_check/mutants_math.py), all caught. The four for AVX-512 run the test suite inside Intel's emulator:
| Planted defect | Caught by |
|---|---|
FMA turned on in AVX2 (-mfma -ffp-contract=fast) | 6 tests: the differential, the specials, the remainder, SoA, the approximations |
SSE2 deinterleave with a wrong index (the x) | 4 tests |
AVX2 deinterleave with a wrong index (the y) | 3 tests |
| dot product: the sum reassociated after deinterleaving | the differential and the remainder |
distance: the z component with the a of another component | 6 tests |
streamed LerpBatch: the last float of the remainder is not written | the remainder (sentinel), the byte differential, InPlace |
SoA: cross product with y swapped, dot product that reads A twice, NormalizeBatchSoa threshold | the differential against the methods (and the remainder) |
SSE4.1 Select (blendvps) with the sides swapped | 5 tests |
| dispatch: SSE4.1 receives the SSE2 table | PathDeclaredAndResolvedOnce |
| dispatch: AVX-512 forced without checking the processor | the test suite dies with an illegal instruction (code 132) on this machine without AVX-512 |
AVX-512: deinterleave and interleave with a wrong index, swapped Select, order of the additions in the multiplication | 3 to 5 tests each, inside the emulator |
| AVX2 high half swapped on write | 3 tests |
Normalize threshold (EPS instead of EPS²) | the differential against Normalized |
| reassociation of a sum in the transformation | the differential and the remainder |
SSE2 Select with the sides swapped | 5 tests |
| dispatch that gives AVX2 to a caller asking for SSE2 | PathDeclaredAndResolvedOnce (without it, SSE2 would drop off the list silently) |
| order of the additions in the AVX2 multiplication | the differential against operator* |
FastExp with a ceiling that lets the exponent overflow | SpecialsAsDocumented |
FastLog(0) no longer gives -inf | SpecialsAsDocumented |
One equivalent defect survives, as it should: putting the last full block in the scalar remainder does not change a bit (the remainder is the same code), only the speed.