floats

package module
v0.44.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: BSD-3-Clause Imports: 6 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-simd/floats

floats

CI coverage Go Reference

SIMD-accelerated reductions over []float32 and []float64 — the dot product, sum, min, max, Euclidean (L2) distance and cosine similarity that sit at the heart of vector search, embeddings and numerics, plus the float64 Axpy/Xpby/AxpyDot/Scale updates behind iterative solvers and the Mul/Axpby3/Clamp/MaxAbs kernels of splitting QP solvers, and the NumPy-exact SumPairwise and unfused AxpyNoFMA/AxpyDiffNoFMA/… kernels (bit-identical to np.sum and to a + F*(b - c)). Pure Go: CGO_ENABLED=0, stable Go, no GOEXPERIMENT. The hot reduction loops are real FMA SIMD on all six 64-bit Go targets, assembly generated by go-asmgen — on a plain go build.

import "github.com/go-simd/floats"

sim := floats.CosineSimilarity(query, doc)        // []float64 relevance score
d   := floats.Float32Distance(embA, embB)         // []float32 L2 distance
dp  := floats.Dot(a, b)                            // a·b

API

For []float64 (top-level) and []float32 (the Float32* functions):

float64 float32 meaning
Dot(a, b) Float32Dot(a, b) a·b = Σ aᵢbᵢ
Sum(a) Float32Sum(a) Σ aᵢ
Min(a) / Max(a) Float32Min(a) / Float32Max(a) min / max element (NaN-propagating; -0 < +0 as NumPy: max of a mix with a +0 is +0, min of a mix with a -0 is -0)
Distance(a, b) Float32Distance(a, b) ‖a−b‖₂ = √Σ(aᵢ−bᵢ)²
CosineSimilarity(a, b) Float32CosineSimilarity(a, b) a·b / (‖a‖₂‖b‖₂)

Dot, Distance and CosineSimilarity require len(a) == len(b) and panic otherwise; Min/Max panic on an empty slice; Sum of an empty slice is 0. The float32 dot/sum/squared-difference are accumulated in float32; cosine and distance take the final square root in float64 for accuracy.

Elementwise updates (BLAS level 1, float64)

The in-place updates that iterative solvers (CG, GMRES), Householder QR and LU elimination spend their time in:

function computes
Axpy(alpha, x, y) y[i] = math.FMA(alpha, x[i], y[i]) (y += αx)
Xpby(x, beta, y) y[i] = math.FMA(beta, y[i], x[i]) (y = x + βy)
AxpyDot(alpha, x, y, w) Axpy, then returns Σ y[i]*w[i] over the updated y, in one pass
Scale(alpha, x) x[i] *= alpha
// one conjugate-gradient step
floats.Axpy(alpha, p, x)              // x += αp
rr := floats.AxpyDot(-alpha, ap, r, r) // r -= αAp, rr = r·r
floats.Xpby(r, rr/rrOld, p)            // p = r + βp

They operate on the first len(x) elements and panic if y (or w) is shorter. y may be the same slice as x or w; partially overlapping slices are not supported.

Bit-identical on every architecture. Each updated element is rounded once, exactly as math.FMA rounds it: VFMADD on amd64 (AVX2+FMA), VFMLA/FMADDD on arm64, the math.FMA loop everywhere else (one hardware FMA instruction on ppc64le, s390x, riscv64 and loong64). The updated slice never depends on the architecture or the CPU features detected at run time (NaN payloads aside). This is not the unfused y[i] + alpha*x[i] that amd64 Go code computes, so replacing such a loop can change the last bit; the fused result is the more accurate one. AxpyDot's returned sum is a reduction and follows the lane-order rules of Floating-point determinism.

arch elementwise kernel
amd64 AVX2+FMA, ×4 unrolled (16 elements/iteration), gated on HasAVX2 && HasFMA
arm64 NEON, ×4 unrolled (8 elements/iteration, four-register VLD1/VST1)
ppc64le, s390x, riscv64, loong64 portable math.FMA loop: no kernel until one is measured on the real silicon, as for the reductions
Gather kernels (index list, float64)

The free-set operations of bound-constrained solvers (L-BFGS-B subspace minimisation, active-set QP): vectors read through a list of active indices.

function computes
DotIdx(a, b, idx) Σₖ a[idx[k]]*b[idx[k]]
DotGather(a, idx, d) Σₖ a[idx[k]]*d[k] (d contiguous, a gathered)
AxpyGather(alpha, a, idx, d) d[k] = math.FMA(alpha, a[idx[k]], d[k]) for every k

They are portable Go (no assembly yet; a SIMD gather can replace them behind the same signatures). They panic if an index is out of range or len(d) < len(idx). Repeated and unordered indices are allowed.

Accuracy contract. The two sums use four FMA accumulators over lane-blocked groups of four indices (k mod 4), combined as (s0+s1)+(s2+s3): they are not summed left to right, so the last bit differs from the obvious loop. The stated bound, asserted against a 300-bit math/big oracle, is |result − exact| ≤ n·ε·Σₖ|aᵢbᵢ| with ε = 2⁻⁵² (plus an absolute 2⁻¹⁰⁷⁴ term per element when products underflow to subnormals). AxpyGather rounds each element once and is bit-identical everywhere.

Products, combinations, clamping, infinity norm (float64)

The vector kernels of splitting solvers (ADMM / OSQP-style quadratic programming): the product with a diagonal, the three-term update, the projection onto a box and the ∞-norm of a residual.

function computes
Mul(dst, a, b) dst[i] = a[i]*b[i]
Axpby3(dst, alpha, a, beta, b, gamma, c) dst[i] = math.FMA(gamma, c[i], math.FMA(beta, b[i], alpha*a[i])) (αa + βb + γc, fused)
Clamp(dst, v, lo, hi) dst[i] = min(max(v[i], lo[i]), hi[i]), with the exact NaN and signed-zero rules below
MaxAbs(v) the largest abs(v[i]) (the ∞-norm); 0 for an empty slice
MaxAbsMul(v, w) max(abs(v[i])*w[i]), the weighted max-norm of ODE error control, folded with C's fmax from +0 (a NaN product loses), bit-identical to that loop; NEON on arm64, AVX2 on amd64, portable loop elsewhere; 0.17–0.43 of NumPy's time (arm64, one core)
// one ADMM-style step: z = Π_[l,u](α·Ax + (1−α)·z_prev + y/ρ)
floats.Axpby3(t, alpha, ax, 1-alpha, zPrev, 1, yOverRho)
floats.Clamp(z, t, l, u)
rNorm := floats.MaxAbs(r)

Like the updates above they work on the first len(a) (len(v)) elements, panic if another slice is shorter, and allow dst to be the same slice as an input. All four are bit-identical on every architecture: Mul is one IEEE multiply per element; Axpby3 is fused — two math.FMA steps after the rounded product alpha*a[i], so it differs from the unfused alpha*a[i] + beta*b[i] + gamma*c[i] by at most a few ULP of Σ|terms| (the tests check that tolerance and also that the fused form is what runs); Clamp and MaxAbs round nothing.

Clamp is r := v[i]; if lo[i] > r { r = lo[i] }; if hi[i] < r { r = hi[i] }: a NaN v[i] comes out unchanged (same bits, either sign); a NaN bound is ignored (that side is unbounded); lo[i] > hi[i] gives hi[i]; signed zeros compare equal, so the result is v[i] unless a strict bound replaces it. MaxAbs returns math.NaN() if any element is NaN (either sign, quiet or signaling) and +Inf if there is an infinity and no NaN; an all-zero slice gives +0.

arch kernels
amd64 AVX2+FMA, ×4 unrolled (VMULPD, VFMADD231PD, VMAXPD/VMINPD with the operand order that gives the strict compare, VANDPD + VMAXPD + an unordered-compare NaN mask), same HasAVX2 && HasFMA gate
arm64 NEON, ×4 unrolled (VFMUL, VFMLA, VFCMGT + VBIT — not FMAX/FMIN, which treat NaN bounds and signed zeros differently —, VFABS + VFMAX)
ppc64le, s390x, riscv64, loong64 the portable loops, as for the updates above (Mul has a kernel there, see below)
OverlapWindow, Float32OverlapWindow: windowed overlap-add of lapped transforms
function computes (n = len(a), j = n-1-i)
OverlapWindow(dst, a, b, win) / Float32OverlapWindow(...) dst[i] = a[i]*win[2n-1-i] - b[j]*win[i], dst[2n-1-i] = a[i]*win[i] + b[j]*win[2n-1-i] for i < n

The inner loop of the synthesis of every MDCT codec (AAC, Vorbis, Opus CELT, AC-3, MP3): the second half of the previous block and the first half of this one are combined under a window, so that the time-domain aliasing cancels. b, win and dst are read and written from both ends, which the auto-vectoriser cannot do; the kernels reverse a register instead. The contract is a bound, not bit identity: each output is within 2 units of the last place of its two products' magnitudes of the exact value (TestOverlapWindowBound against a 200-bit computation, float32 and float64, every size from 1 to 1024). arm64 NEON (VREV64+VEXT, VFMUL, VFMLS/VFMLA; 4 float32 or 2 float64 lanes) and amd64 AVX2+FMA (VPERMILPS + VPERM2F128 or VPERMPD, VFNMADD231/VFMADD231; 8 or 4 lanes), generated by go-asmgen (overlap_*_gen.go); the portable loop elsewhere and on an amd64 CPU without AVX2+FMA. On an Apple M4 Max, 1024 steps: float32 764 to 212 ns (3.6x), float64 789 to 377 ns (2.1x) against the portable loop. Wanted by go-avkit/decode (AAC) and go-fft's TDAC helper.

CMulGather, CMulScatter: the twiddle passes of the DCT-IV and the MDCT
function computes (n = len(tw), a complex number is two consecutive float64)
CMulGather(dst, x, tw) for m < n/2: dst[2m] = x[2m]*tw[2m] - x[n-1-2m]*tw[2m+1], dst[2m+1] = x[2m]*tw[2m+1] + x[n-1-2m]*tw[2m]
CMulScatter(dst, c, tw, f) z = tw[m]*c[m] (complex), dst[2m] = f*Re z, dst[n-1-2m] = -f*Im z
CMulGatherFrom32(dst, x, tw) CMulGather with x float32, widened in the kernel
CMulScatterTo32(dst, c, tw, f) CMulScatter with dst float32, each output rounded once

A DCT-IV of even length is an n/2-point complex FFT between two passes over the data: the real input is read as complex pairs of its even samples and its odd samples from the end, multiplied by a table; the FFT's output is multiplied by a table and written back, real parts to the even positions and negated imaginary parts to the odd ones from the end. Those passes are more than half of a small DCT-IV or MDCT (go-fft/fft#132: 45 of 103 ns at 64 points, 750 of 1,300 ns at 1,024) and a stride-2 deinterleave plus a lane reversal is what the auto-vectoriser does not do. The float32 forms keep the data float32 and the arithmetic float64 (go-fft's DCTMixed/MDCTMixed) with the conversion fused in. The contract is a bound, not bit identity (TestCMulGatherBound, TestCMulScatterBound against a 200-bit computation, every even size from 2 to 2,048): each output within 4 units of the last place of its two products' magnitudes of the exact value, plus half a float32 ulp for a float32 output. arm64 NEON (VLD1+VUZP, VZIP+VST1, VEXT, VFMLS/VFMLA, VFCVTL/VFCVTN; two complex numbers per step) and amd64 AVX2+FMA (VSHUFPD+VPERMPD, VUNPCK+ VPERM2F128, VFNMADD231PD/VFMADD231PD, VCVTPS2PD/VCVTPD2PS; four complex numbers per step), generated by go-asmgen (twiddle_*_gen.go); the portable loops elsewhere and on an amd64 CPU without AVX2+FMA. On an Apple M4 Max, 1,024 points (512 complex numbers): CMulGather 533 to 219 ns and CMulScatter 538 to 214 ns against the portable loop (2.4x and 2.5x); 64 points 33 to 18 and 33 to 14 ns.

MDCTFold, MDCTUnfold: the fold and unfold of the MDCT and the IMDCT
function computes (N = len(x), m = N/2, h = N/4, i < h)
MDCTFold(dst, x) dst[i] = -(x[m+h-1-i] + x[m+h+i]), dst[h+i] = x[i] - x[m-1-i]
MDCTUnfold(dst, u) dst[i] = u[h+i], dst[m-1-i] = -u[h+i], dst[m+h-1-i] = -u[i], dst[m+h+i] = -u[i] (m = len(u))
MDCTFoldFrom32(dst, x) the fold with x float32, widened (the sum is float64)
MDCTUnfoldTo32(dst, u) the unfold with each output rounded to float32

An MDCT is a DCT-IV on a folded copy of the block, an IMDCT a DCT-IV followed by the inverse arrangement (Wikipedia's fold (a, b, c, d) -> (-c_r - d, a - b_r)); every MDCT codec does both, around the twiddle passes of CMulGather/CMulScatter. Both read and write forward and reversed runs of consecutive elements, which the compiler does not vectorise and a lane reversal does. Each output is one addition, subtraction or negation, nothing fused, so the kernels equal the portable loops exactly (TestMDCTFoldExact against a 200-bit computation, every block length from 4 to 4,096, and FuzzMDCTFold). dst must not overlap its operand, not even exactly: checked, panics. arm64 NEON (VLD1, VEXT, VFADD/VFSUB/VFNEG; 2 lanes) and amd64 AVX2 (VPERMPD $0x1B, VADDPD/VSUBPD, an XOR for the sign; 4 lanes), generated by go-asmgen (fold_*_gen.go); the portable loops elsewhere and on an amd64 CPU without AVX2+FMA. On an Apple M4 Max, a 2,048-sample block: fold 376 to 113 ns (3.3x), unfold 355 to 160 ns (2.2x); 128 samples 23 to 15 ns and 22 to 15 ns (load 9).

SquaredMagnitude: the power pass of a periodogram

SquaredMagnitude(dst, c, s) writes dst[k] = (c[2k]² + c[2k+1]²)·s for the n = len(dst) complex numbers held as consecutive (re, im) pairs in c: the last pass of a PSD, a spectrogram or a power spectrum. A loop in Go reads the pairs with a stride of two; the kernels deinterleave four (AVX2) or two (NEON) bins per step. The contract is a bound, not bit identity: the squares and their sum are non-negative, so every output is within 4 units of the last place of the exact value (the portable loop rounds four times, a kernel fuses the second square with the sum), asserted by TestSquaredMagnitudeBound against a 200-bit computation at every length from 1 to 70 and at the sizes of a spectrogram, with a fuzz target. dst must not overlap c, not even exactly: checked, panics. arm64 NEON (VUZP1/VUZP2, VFMUL, VFMLA) and amd64 AVX2+FMA (VSHUFPD+VPERMPD, VFMADD231PD), generated by go-asmgen (sqmag_*_gen.go); the portable loop elsewhere and on an amd64 CPU without AVX2+FMA. On an Apple M4 Max, 129 bins (a 256-point real transform): 85 to 25 ns (3.4x); 1,025 bins 654 to 169 ns (3.9x) (load 17). Wanted by go-fft's PSD and Spectrogram (go-fft/fft#123).

MirrorCombine, MirrorCombineSplit: the pair pass of a real transform

For a spectrum z of n complex numbers ((re, im) pairs), k = 1 .. n-1: u = z[k] + conj(z[n-k]), v = -i (z[k] - conj(z[n-k])), r[k] = w1[k] u + w2[k] v (complex products). MirrorCombine stores r[k] as complex number k of dst; MirrorCombineSplit stores dst[k] = Re r[k] and dst[2n-k] = -Im r[k], the layout of a DCT-II. It is the post-pass of Makhoul's DCT-II and the pre-pass of the DCT-III (go-fft/fft#162) and, with other weights, the untangle of a real FFT. Within a bound, not bit for bit (the kernel fuses the products): 4 eps of |w1||u| + |w2||v| against a 300-bit oracle, at every length from 0 to 130 and at 255, 256, 257, 1000, 4097, with a fuzz target. dst must not overlap an input (checked, panics, nothing written); len(z) must be even and w1, w2, dst at least as long. amd64 AVX2+FMA (VFMADDSUB231PD, two values of k per step), generated by go-asmgen (mirror_amd64_gen.go); the portable loop elsewhere, arm64 included (no NEON kernel yet).

CMulZipRev: a mirrored-halves gather with a complex multiply

CMulZipRev(dst, x, y, w) writes, for j < m = len(dst)/2, dst[j] = w[j] * (x[j] - i y[m-1-j]): the real parts are one contiguous run, the imaginary parts another read from its end, w is a table of m complex numbers (pairs). It is the pre-pass of Makhoul's DCT-III (go-fft/fft#162), before MirrorCombine. Within a bound, not bit for bit (the kernel fuses the products): 4 eps of |w||(x, y')| plus an absolute floor of 64 smallest subnormals, against a 300-bit oracle, at every length from 0 to 130 and at 255, 256, 257, 1000, 4097, with a fuzz target whose corpus entry fails the bound without the floor. dst must not overlap x, y or w (checked, panics, nothing written). amd64 AVX2+FMA (VPERMPD reversal, VUNPCKLPD/HPD, VFMADDSUB231PD, four numbers per step), generated by go-asmgen (cmulziprev_amd64_gen.go, gated in CI like mirror_amd64.s); the portable loop elsewhere, arm64 included.

ConjReverse: the conjugate mirror of a Hermitian spectrum

ConjReverse(dst, src) writes the n = len(dst)/2 complex numbers held as consecutive (re, im) pairs in src, conjugated and in reverse order: dst[2k] = src[2(n-1-k)], dst[2k+1] = -src[2(n-1-k)+1]. It is the mirror X[N-k] = conj(X[k]) that turns the N/2+1 bins of a real transform into the full spectrum. Every output is a copy or a negation, so the result is exact, not within a bound: TestConjReverseExact compares bits (signed zeros and NaN payloads included) at every length from 0 to 70 and at the sizes of a transform's mirror, with a fuzz target. dst must not overlap src, not even exactly: checked, panics; len(dst) must be even. arm64 NEON (four registers of VLD1, VEOR with the sign of the imaginary lane, VST1) and amd64 AVX2 (VPERMPD half swap, VXORPD), generated by go-asmgen (conjrev_*_gen.go); the portable loop elsewhere and on an amd64 CPU without AVX2+FMA. On a Ryzen 9 7950X, 511 numbers (the mirror of a 1,024-point real transform): 378 to 52 ns (7.2x); 2,047 numbers 1,513 to 385 ns (3.9x). Wanted by go-fft's FFTReal (go-fft/fft#122).

MulAddRows: the window sum of a polyphase bank

MulAddRows(dst, a, lda, b, ldb, rows) computes dst[j] += Σ_k a[k*lda+j]*b[k*ldb+j] for k < rows and j < len(dst): output j is a sum of products of two matrices read down a column, the window stage of an MDCT or QMF synthesis bank (64 columns, 10 rows). A Go loop over the rows loads and stores the accumulator once per row; the kernel holds a block of dst in registers across all the rows (NEON 16, 4, 2 then 1 column, AVX2 16, 4 then 1), so a, b and dst are each loaded once. Every term is one fused multiply-add in increasing k, starting from the value dst[j] holds, so the result is bit-identical on every architecture (kernel and math.FMA loop do the same operations in the same order, as Axpy does): TestMulAddRowsExact compares bits at every column count from 1 to 70 and the sizes of a bank, with padded and zero strides, TestMulAddRowsAgainstExact holds it to rows+1 units of the last place of the sum of magnitudes against a 300-bit computation (the measured worst is 2 units for ten rows), plus a fuzz target and guard pages. dst must not overlap the elements of a or b that are read: checked, panics. arm64 NEON (VLD1.P, VFMLA) and amd64 AVX2+FMA (VFMADD231PD), generated by go-asmgen (mulrows_*_gen.go); the portable loop elsewhere and on an amd64 CPU without AVX2+FMA. Wanted by go-avkit/decode's SBR synthesis bank (go-avkit/decode#77).

MulAddRows32: the window sum of a float32 polyphase bank

MulAddRows32(dst, a, lda, b, ldb, rows) is MulAddRows on float32 data, eight (AVX2) or four (NEON) columns to a register: dst[j] += Σ_k a[k*lda+j]*b[k*ldb+j], the block of dst held in registers across all rows. Every term is one fused float32 multiply-add in increasing k, so the stated contract is an error bound, not bit identity with another code: |dst[j] - exact| <= rows·2^-24·(|dst0[j]| + Σ|a·b|)·(1 + rows·2^-24), asserted against a math/big computation at every shape by TestMulAddRows32AgainstExact, plus a fuzz target, guard pages, and asserted panic messages (TestMulAddRows32PanicsAndBounds). On one Zen 4 core a 64-column, 10-row bank takes 13.7 ns against 23.8 ns for the float64 MulAddRows on the same shape. dst must not overlap the elements read of a or b: checked, panics. amd64 AVX2+FMA and arm64 NEON, generated by go-asmgen (mulrows32_*_gen.go); the portable loop elsewhere. Wanted by go-avkit/decode's float32 SBR synthesis bank (go-avkit/decode#77).

AllPass3: the all-pass rows of the Parametric Stereo decorrelator

AllPass3(out, in, t, old, cur) computes, for each row k of a slot of complex samples, x = Phi*in, then three Schroeder links in series (p = Q_l*old_l, c = x + C_l*p written to cur_l, x = p - C_l*c) and out = x: the all-pass half of the HE-AAC v2 decorrelator (ISO/IEC 14496-3). The rotations and real coefficients are the seven tables of AllPassRows; the caller resolves the ring pointers old and cur. The kernel does two rows per AVX2 register (one per NEON register) and keeps all three links in registers. Every complex product is one rounded product and one fused sum, so kernels and the portable math.FMA loop are bit-identical on every architecture; the stated error bound (a few units of 2^-53 times the largest magnitude of the chain, recurrence in the source) is asserted for out and every cur_l against a 200-bit math/big computation by TestAllPass3Bound and FuzzAllPass3 (worst measured 0.61 of the bound), plus guard pages and overlap checks (a written slice overlapping another operand panics). On amd64 (AVX2+FMA, 34 rows) about 2.3x faster than the complex128 Go loop. arm64 NEON and amd64 AVX2+FMA generated by go-asmgen (allpass_*_gen.go). Wanted by go-avkit/decode#77.

NewAllPass3Plan(t, out, in, inStride, w, wStride) is the same kernel for a decorrelator that calls it once per slot: the tables, the output, the input ring and the three link rings are proved once (lengths, strides, no overlap between written and other memory), and plan.Run(inSlot, oldSlot, curSlot) names the memory by slot numbers, so a call only checks eight integer ranges (it panics on a slot out of range or a link that reads the slot it writes). plan.Out() is the output. In go-avkit/decode this is about 1.2 % of an HE-AAC v2 decode, where the per-call proof of AllPass3 cost more than it saved.

NewAllPass3TickPlan(…, inDelay) and plan.RunTick(t) go one step further for a decorrelator driven by a tick counter: link l, whose ring holds m slots, reads slot (t+1) mod m and writes slot t mod m, and the input is slot (t - inDelay) mod s. The slots follow from t and from sizes proved at construction, so a call checks nothing and cannot panic for any t (a negative t reduces as uint(t) does). For t >= 0 it is bit-identical to Run on those slots. Wanted by go-avkit/decode#77.

AllPass3Split32: the float32 split-plane form of AllPass3

AllPass3Split32(out, in, t, old, cur) is AllPass3 on float32 split planes (Split32{Re, Im}, separate real and imaginary slices) with the seven tables of AllPassRows32: eight rows per AVX2+FMA register (masked tail), four per NEON register, a portable loop elsewhere and without AVX2+FMA. The contract is a stated bound, not bit identity: every link's error in modulus is at most u(|C||p| + |c|) with u = 2^-24, and a complex product adds 3u|a||d| (recurrence in the source), asserted for out and every cur_l against a 200-bit math/big computation by TestAllPass3Split32Bound and FuzzAllPass3Split32 (worst measured 0.68 of the bound), plus guard pages at every row count 1 to 40 and overlap checks (a written slice overlapping another operand panics). NewAllPass3TickPlan32(…) and plan.RunTick(t) are the proved-memory, tick-driven form, as NewAllPass3TickPlan, with no per-call check. On amd64 the rows after the last full block of eight are one more full block over the last eight rows (recomputing up to seven rows to the same values; VMASKMOVPS stores are slow on Zen 4), so only fewer than eight rows use a masked block. Measured on one Zen 4 core, 34 rows: the float32 RunTick 35 ns against 53.6 ns for the float64 AllPass3Plan.RunTick (1.5x), the bare kernel 34.6 ns (BenchmarkAllPass3Split32). The checked call does a quadratic overlap proof (138 ns, against 74 ns for the float64 AllPass3): use the plan in a loop. arm64 NEON and amd64 AVX2+FMA generated by go-asmgen (allpass32_*_gen.go). Wanted by go-avkit/decode#77.

PSMixPlan32: the PS mixing of a whole slot in one call

NewPSMixPlan32(runs, nBands) proves a slot's list of runs (PSMixRun{Start, End, Band, Src}: consecutive rows that share the gains of one band and the decorrelated source Src 0 to 2) once; plan.Run(gains, tg, s, d, l, r) then computes, for every row of every run, l = gLs*s + gLd*tg*d and r = gRs*s + gRd*tg*d on float32 split planes (gains holds four values per band, tg the transient gain per band). The runs of PS are short (about 3.5 rows), so the kernel takes the whole slot per call: AVX2+FMA (eight rows per register) and NEON (four) by go-asmgen (psmix32_*_gen.go), a portable loop elsewhere and without AVX2+FMA. A run shorter than a vector is one full vector that writes up to 7 rows past its end (masked stores are slow on Zen 4), overwritten by the next run, so the operands need 7 elements of slack past the last row, which Run checks. The contract is a stated bound: each output within 3u(|gXs s| + |gXd tg d|) per component, u = 2^-24, asserted against a 200-bit math/big computation by TestPSMixPlan32Bound and FuzzPSMixPlan32 (worst measured 0.89 of the bound), plus guard pages. Benchmark: BenchmarkPSMix32. Wanted by go-avkit/decode#77.

CDotC: the conjugated complex dot product

CDotC(a, b) returns Σ conj(a_k)·b_k (the BLAS zdotc) as (re, im) for the n = len(a)/2 complex numbers held as consecutive (re, im) pairs: the lag-k correlation of a complex sequence with itself, the covariance estimate of a linear predictor (the SBR inverse-filtering predictor of go-avkit/decode, go-avkit/decode#77). The sum of squared magnitudes of a complex slice needs no kernel: Dot(a, a) over the same float64 view is Σ (re² + im²). A Go loop is one dependent chain per accumulator; the kernels run a block of four complex numbers per step with the second sum on the swapped parts of b (NEON VFMLA on VEXT-swapped registers, AVX2 VFMADD231PD on VPERMILPD-swapped ones) and fold the lanes at the end. The contract is a bound, not bit identity: both parts are reordered and fused, so each is within (2n+2)·2^-53 (the portable path, one serial chain of 2n fused steps; reached by an adversarial input, so not improvable) or (n/4+8)·2^-53 (the vector paths) of the sum of the absolute values of its products of the exact value, asserted against a 300-bit computation at every length from 0 to 70 complex numbers and at the sizes of a transform by TestCDotCBound, by TestCDotCAdversarial (same-sign rounding errors, and massive cancellation), with a fuzz target and guard pages. len(a) must be even and b at least as long (panics). amd64 AVX2 tests run on a CI runner and fail, not skip, when AVX2+FMA is missing there (TestCDotCAVX2Dispatch); the portable loop elsewhere and on an amd64 CPU without it. Measured, 38 complex numbers (one SBR predictor lag): Ryzen 9 7950X 47 to 10.7 ns (4.4x), M4 Max 47 to 18 ns (2.6x).

CMulTo: the pointwise complex product

CMulTo(dst, a, b []complex128) writes dst[i] = a[i]*b[i] for i < len(dst) (NumPy's multiply on complex128): the chirp and spectral products of Bluestein's algorithm, the filter of a frequency-domain convolution. It panics, before writing anything, if a or b is shorter than dst; dst may be a or b exactly (in place), any other overlap is undefined. The AVX2+FMA kernel takes four numbers per step with one multiply and one VFMADDSUB231PD per two numbers (real part fma(ar, br, -(ai*bi))), then finishes the last two and one itself, in one call; the arm64 kernel is the scalar loop in assembly (FMADDD, FMSUBD, paired loads and stores, no bounds checks), not NEON, which lost to Go's loop below 64 numbers on Neoverse; the s390x kernel (vector facility, z13 and later) holds one complex number per register, four per step (VFMDB, VFMADB on the swapped parts, a sign vector for the real part), from 20 numbers; the ppc64le kernel (VSX, POWER8 and later, from 35 numbers) splits two numbers into real and imaginary vectors (XXPERMDI, XVMULDP, XVMSUBADP, XVMADDADP, then XXPERMDI back), four per step with the next step's loads issued before the current step's arithmetic, and the last n mod 4 numbers done first so that their latency hides behind the loop, which counts on CTR (a compare-and-branch exit was mispredicted once per call from 96 numbers on, 3 to 8 % slower than Go's loop there); the one-number-per-register form lost to Go's loop by 11 to 30 % on POWER9, and the unpipelined pair form by 1 to 4 % above 64 numbers (Go's loop there has its bounds checks eliminated); other CPUs run Go's complex product. The contract is a bound, not bit identity: each part is within 2 eps (2^-52) of |a|·|b| of the exact product, plus 64 smallest subnormals when a product underflows (the fused and the unfused forms both meet it), asserted against a 300-bit math/big oracle by TestCMulToOracle, with in-place, panic-before-write, guard-page, noescape and fuzz tests. Measured on one core (Zen 4, interleaved, median of 21 rounds, load below 1), against the scalar Go loop: 5.7 ns against 10.9 at 16 numbers, 13.4 against 39.9 at 64, 295 against 630 at 1024 (1.9x to 3x); against go-fft's former unfused AVX2 kernel it is 0.2 ns faster at 16, 0.5 at 32, 0.8 at 64, 1.4 at 128, 2.6 at 256, 8.5 at 512 and 2 ns (0.7 %) slower at 1024 (memory bound). The v0.32.0 kernel with its Go tail was 6.7 ns at 16. np.multiply there was 772 ns at 1024 numbers (earlier measurement). Neoverse-N2 (GitHub arm64 runner, load 0.3, interleaved): 16.0 ns against 19.9 for the Go loop at 16 numbers (23.1 for the v0.32.0 NEON kernel), 55.8 against 72.5 at 64, 857 against 1135 at 1024. s390x (z17, load 0.0, interleaved, A/A agrees): 30.1 ns against 40.0 for the Go loop at 32 numbers, 50.0 against 76.4 at 64, 696 against 1157 at 1024 (1.7x); at 16 numbers the loop runs (21.5 against 21.8). POWER8E (cfarm112, one pinned core): 70.2 against 83.5 at 32, 108.6 against 143.8 at 64, 1270 against 1954 at 1024 (1.5x). POWER9 (cfarm29, one pinned core): 58.9 against 70.3 at 32, 107.7 against 117.4 at 64, 1690 against 1753 at 1024 (3.6 %); at 16 numbers the loop runs on both (the wrapper costs 2.6 ns over the bare loop on POWER9).

Elementwise Add, Sub, Div, Sqrt, ClampScalar (float64)
function computes
Add(dst, a, b) / Sub(dst, a, b) / Div(dst, a, b) dst[i] = a[i] + b[i] / a[i] - b[i] / a[i] / b[i]
Sqrt(dst, src) dst[i] = math.Sqrt(src[i])
ClampScalar(dst, v, lo, hi) dst[i] = min(max(v[i], lo), hi) with Clamp's exact NaN and signed-zero rules, scalar bounds (np.clip(v, lo, hi))

The float64 elementwise kernels go-ndarray kept privately (K1 of the go-scikit performance campaign: a kernel lives once, in the lowest library every user can import). Each element is one IEEE operation or a comparison, never a fused instruction, so the results are bit-identical to the scalar Go loop and to NumPy on every architecture (np.add, np.subtract, np.divide, np.sqrt, np.clip). amd64 (AVX2, the usual gate) runs VADDPD/VSUBPD/VDIVPD/VSQRTPD, arm64 NEON VFADD/VFSUB/VFDIV/VFSQRT, both ×4 unrolled and generated by go-asmgen (binop_*_gen.go). An amd64 CPU without AVX2+FMA runs SSE2 kernels (ADDPD, SUBPD, MULPD, DIVPD, SQRTPD, MAXPD/MINPD for ClampScalar; SSE2 is the amd64 baseline, no feature test; sse2_amd64_gen.go), also bit-identical; CI forces that path on its AVX2 hosts (TestSSE2ForcedPath). ppc64le (VSX), loong64 (LASX, gated on the CPU), riscv64 (RVV 1.0, gated) and s390x (the z13 vector facility) run XVADDDP/XVADDD/VFADDVV/VFADB and their siblings (lanes_<arch>_gen.go; on a native IBM z17, Add and Mul are 2.2x the compiler loops, Div, Sqrt and SumPairwise 1.0-1.1x, never slower); the remaining architectures run the portable loops. Like Mul they work on the first len(a) elements, panic if another slice is shorter, allow dst to alias an input, never read or write past a slice (guard-page tests).

Elementwise Add32, Sub32, Mul32, Div32, Sqrt32 (float32)
function computes
Add32(dst, a, b) / Sub32 / Mul32 / Div32 dst[i] = a[i] + b[i] / a[i] - b[i] / a[i] * b[i] / a[i] / b[i]
Sqrt32(dst, src) dst[i] = float32(math.Sqrt(float64(src[i])))

The single-precision siblings of Add, Sub, Mul, Div, Sqrt, wanted by go-ndarray to delete its private SSE2 copies. Each element is one IEEE-754 binary32 operation (the exact correctly rounded result, no fused instruction), bit-identical to the scalar Go loop and to NumPy's float32 ufuncs, up to the payload of a NaN an operation itself creates. Sqrt32 is proved correctly rounded over all 2^32 float32 bit patterns on amd64 and arm64 (TestSqrt32Exhaustive, about 2 s per kernel on a many-core machine, skipped with -short) against an oracle that uses no square root: the result must lie between the neighbouring midpoints, checked by squaring them exactly in float64. On the emulated architectures (loong64, ppc64le, riscv64, s390x) the same test checks every 1021st bit pattern (about 4.2 million), plus the specials of TestSqrt32Specials. Like the float64 functions they work on the first len(a) (len(src)) elements, panic if another slice is shorter and allow dst to alias an input. amd64: AVX2 (VADDPS ..., 32 elements per iteration, the usual gate), SSE2 (ADDPS ..., the amd64 baseline) on a CPU without AVX2+FMA; arm64: NEON (VFADD ... on .S4, 16 elements per iteration); loong64: LSX (VFADDS ..., gated on LASX like the float64 kernels); ppc64le: VSX (XVADDSP ..., POWER8 baseline, gated on hasVSX); riscv64: RVV 1.0 (VFADDVV ... on 32-bit elements, strip-mined, any VLEN, gated on V); s390x: vector-enhancements facility 1 (VFASB ..., z14 or later, gated on hasVXE); on a CPU without the feature, or for an empty slice, the portable loop. Generated by go-asmgen (binop32_<arch>_gen.go, regenerated and diffed in CI); the portable loops elsewhere. On amd64, Add32, Sub32 and Mul32 switch from the AVX2 to the SSE2 kernel from 65536 elements (binop32SSEFrom): past the L2 cache the loop is bound by memory and on Zen 3 (EPYC 7773X) the 128-bit loop is 7-10 % faster (Add32 n=1e6 165 us against 181 us); Div32 has no such switch. On Zen 3 (CPUID family 19h, detected at start-up) its AVX2 kernel loads each 8-float operand as two 128-bit halves (VMOVUPS, VINSERTF128) feeding 256-bit VDIVPS, and stores them as halves, which is 6-8 % faster than whole-register moves past L2 (EPYC 7773X, n=1e6 164 us against 178 us, same core, interleaved rounds). NumPy 2.5.4 read 174 us in that run and 166-168 us in three later ones on the same host, so at n=1e6 Div32 is 2-5 % faster than NumPy, not a fixed margin: the host's run-to-run spread is about 5 %, the minimum of every caller is 162-164 us; on Zen 4 that shape is 9-13 % slower, so other CPUs keep the whole-register AVX2 kernel (Ryzen 9 7950X n=1e6 83 us, NumPy 92 us). Results are bit-identical either way. The loong64, ppc64le, riscv64 and s390x kernels are unmeasured on hardware (the QEMU lanes check them, they are not timings). go test -bench Binop32 times each kernel against the scalar loop; the NumPy rows of bench/perf are deferred (see docs/perf-exempt.md).

Elementwise Abs, Neg, Square, Floor, Ceil, Trunc, RoundEven (float64)
function computes NumPy
Abs(dst, src) dst[i] = math.Abs(src[i]) np.abs
Neg(dst, src) dst[i] = -src[i] np.negative
Square(dst, src) dst[i] = src[i] * src[i] np.square
Floor(dst, src) dst[i] = math.Floor(src[i]) np.floor
Ceil(dst, src) dst[i] = math.Ceil(src[i]) np.ceil
Trunc(dst, src) dst[i] = math.Trunc(src[i]) np.trunc
RoundEven(dst, src) dst[i] = math.RoundToEven(src[i]), halfway to even np.rint, np.round

The operations go-ndarray still ran as scalar Go loops (go-ndarray/ndarray#118). Each is exact: the result is the Go expression's, bit for bit, on every input and every architecture: ±0 keep their sign (Ceil(-0.5) is -0), ±Inf and |x| ≥ 2⁵² (already integers) pass through, subnormals are handled, and a NaN stays a NaN. Abs and Neg only touch the sign bit, so every NaN keeps its exact bits; the others return a quiet NaN's sign and payload unchanged (a signalling NaN may be returned quieted and may differ from the math function on the same machine, which is pure Go on some targets; riscv64 arithmetic returns the canonical NaN). Same shape as Sqrt: they work on the first len(src) elements, panic if len(dst) < len(src), allow dst to be src (exact overlap only), never read or write past a slice.

Kernels, generated by go-asmgen (round_<arch>_gen.go), each doing the whole blocks of eight elements with the Go code finishing the last seven:

target Abs, Neg Square Floor, Ceil, Trunc, RoundEven
amd64 AVX2 VANDPD / VXORPD with sign masks VMULPD VROUNDPD imm 9 / 10 / 11 / 8
amd64 without AVX2+FMA SSE2 ANDPD / XORPD MULPD scalar loop (SSE2 has no ROUNDPD)
arm64 NEON FABS / FNEG FMUL FRINTM / FRINTP / FRINTZ / FRINTN
ppc64le VSX xvabsdp / xvnegdp xvmuldp xvrdpim / xvrdpip / xvrdpiz / xvrdpic
s390x vector facility VFLPDB / VFLCDB VFMDB VFIDB M5 7 / 6 / 5 / 4
loong64 LASX XVAND.V / XVXOR.V with sign masks XVMULD XVFRINTRM / RP / RZ / RNE
riscv64 RVV vfsgnjx / vfsgnjn vfmul scalar loop

xvrdpi rounds halfway cases away from zero, so RoundEven uses xvrdpic, which rounds in the current mode (FPSCR.RN, round to nearest even; Go never changes it, but cgo code calling fesetround could). riscv64 keeps the four rounding functions scalar: RVV 1.0 has no vector round-to-integral instruction, and a float to integer to float round trip is wrong for |x| ≥ 2⁶³, for NaN and for -0; an exact guarded version was not attempted because it could be tested only under QEMU, which cannot say whether it is faster. Every other target runs the portable loops. Tests: an edge table (±0, ±Inf, NaN of every kind, subnormals, halfway cases and their neighbours, the binades around 2⁵² and 2⁶³) placed at every position of every length 0 to 33 and four alignments, a random differential test over lengths 0 to 257, an oracle that does not use package math (integer truncation), aliasing, panics, guard pages, a CPU-gate-off rerun on amd64, ppc64le, loong64 and riscv64, and FuzzRound with a committed corpus.

One Zen 3 core (AMD EPYC 7773X, GCC Compile Farm cfarm420, taskset -c 9, GOMAXPROCS=1, 1-minute load 2.7, -count=3 medians), the AVX2 kernel against the scalar Go loop on 1,000 and 100,000 float64, ns per call:

op n = 1e3 kernel loop n = 1e5 kernel loop
Abs 112.7 703 6.2× 23 306 64 487 2.8×
Neg 90.6 641 7.1× 23 174 64 440 2.8×
Square 88.6 650 7.3× 23 598 63 857 2.7×
Floor 89.9 941 10.5× 23 266 78 229 3.4×
Ceil 89.8 957 10.7× 23 076 75 551 3.3×
Trunc 89.8 948 10.6× 23 263 75 250 3.2×
RoundEven 89.8 951 10.6× 23 986 85 731 3.6×

At 1e5 (800 kB read and 800 kB written per call) the seven kernels all take the same 23 µs (34 GB/s of source bytes), so they are bound by the cache, not by the instruction; the ratio against the loop is what a single pass leaves. Not yet timed against NumPy: the bench/perf rows wait for a valid run (1-minute load below 8), see docs/perf-exempt.md. The other architectures were verified for correctness only (QEMU), not timed.

Pairwise Maximum, Minimum (float64)
function computes NumPy
Maximum(dst, a, b) dst[i] = max(a[i], b[i]) (the Go builtin) np.maximum
Minimum(dst, a, b) dst[i] = min(a[i], b[i]) (the Go builtin) np.minimum

The "K1 remainder" of go-ndarray/ndarray#98 (and #118), which ran them as scalar loops. The contract is the language's rule, the one runtime/minmax.go spells out, the same on every kernel, bit for bit (and, where no kernel runs, the builtin loop itself):

  • NaN: a NaN in either operand gives that NaN unchanged (sign, payload, quiet bit: a signalling NaN stays signalling); two NaNs give b[i]. max(NaN, +Inf) is NaN.
  • Zeros: max(-0, +0) and max(+0, -0) are +0 (the bitwise AND of the two zeros), min of them is -0 (the OR), whatever the operand order. (NumPy returns a when a >= b, so for a (-0, +0) pair it returns the first operand; this does not.)
  • Otherwise the larger (smaller) operand.

One documented difference from the compiled scalar loop: the Go compiler's own max may quiet a signalling NaN or pick the other operand of two NaNs where the target's instruction does (FMAX on arm64; on amd64 the compiler lowers max to -min(-x, -y) with MINSD, MINSD and POR, cmd/compile/internal/ssa/_gen/AMD64.rules lines 196 to 199), so the payload of a NaN result can differ from the builtin's on those machines (TestPairwiseBuiltin counts them, per 65536 random pairs, with one NaN operand / two: arm64 Maximum 432 / 131, Minimum 424 / 131; amd64 Maximum 471 / 99, Minimum 502 / 92, the native amd64 CI job). The number results, the zeros and the fact of a NaN are identical. Same shape as Add: the first len(a) elements, a panic if b or dst is shorter, dst may be a or b (exact overlap only), nothing read or written past a slice. No float32 variant (the float32 siblings of Add, Mul and Sqrt are Add32, Mul32, Sqrt32).

MAXPD/MINPD, FMAX, vfmax and the others cannot give the rule directly (MAXPD returns the second operand for a NaN or two zeros, FMAX picks its own NaN, vfmax returns the number), so each kernel is a compare-and-select or an FMAX plus a fix-up, generated by go-asmgen (maxmin_<arch>_gen.go), doing the whole blocks of eight elements with the Go code finishing the last seven:

target how
amd64 AVX2 VCMPPD (a<b, unordered b, a==b), VBLENDVPD twice, VANDPD / VORPD for the zeros
amd64 without AVX2+FMA the same in SSE2 (CMPPD, ANDPD / ANDNPD / ORPD)
arm64 NEON FMAX / FMIN (right for numbers and zeros), FCMEQ of each operand with itself and two BSL put the NaN back
ppc64le VSX xvcmpgtdp, xvcmpeqdp, xxsel, xxland / xxlor
s390x vector facility VFCHDB, VFCEDB, VSEL, VN / VO (z13, no VFMAX)
loong64 LASX XVFCMP.CLT/CEQ/CUN.D, XVBITSEL.V, XVAND.V / XVOR.V
riscv64 RVV vmflt, vmfne, vmfeq, vmor.mm, vmerge, vand / vor
fallback (no kernel) builtin max / min (the compiler's own lowering)

Manuals: the Intel SDM pages for CMPPD, BLENDVPD, MAXPD (felixcloutier.com mirror) and the RISC-V V 1.0 specification (v-spec.adoc) were opened. The Arm ARM (JavaScript page), the Power ISA, the z/Architecture Principles of Operation (over the fetch limit) and the LoongArch manual (581 KB, the compare section not reached) were not: those four rest on execution evidence, the edge tables below, run natively on Apple silicon (arm64) and under QEMU (ppc64le power8 and power9, s390x max and z13, loong64 la464, riscv64 at VLEN 128, 256 and 512), as for RoundEven. The loong64 and ppc64le compare instructions have no Go mnemonic and are WORDs with their mnemonic in a comment.

Tests: every pair of an edge table (±0 both orders, ±Inf, quiet and signalling NaNs of both signs with payloads, subnormals, equal neighbours) at every position of every length 0 to 33 and four alignments, random bit patterns with planted ties, zeros and NaNs over lengths 0 to 257, dst aliasing a, b or both, panics, guard pages, a CPU-gate-off rerun (SSE2 on amd64, the portable loop elsewhere), an oracle that is the language rule written independently of the kernels' reference and checked against the builtin, and FuzzPairwise with a committed corpus.

One Zen 3 core (AMD EPYC 7773X, GCC Compile Farm cfarm420, taskset -c 9, GOMAXPROCS=1, 1-minute load 2.3 to 2.6, 7 interleaved rounds, medians), the AVX2 kernel against the compiled scalar max / min loop, ns per call:

op n = 1e3 kernel loop n = 1e5 kernel loop
Maximum 195.6 976.5 5.0× 34 142 100 820 3.0×
Minimum 176.6 694.6 3.9× 33 203 67 510 2.0×

Where no kernel runs (an architecture without one, loong64 without LASX, riscv64 without V, ppc64le before POWER8) Maximum and Minimum are the builtin loop itself, dst[i] = max(a[i], b[i]), the compiler's own lowering: exactly what go-ndarray ran, so nothing there is slower or different than before (its NaN payload is the target's; on riscv64 the builtin returns the canonical NaN, seen under QEMU). The last seven elements of a kernel call use a rule loop (the builtin for two numbers, the NaN rule when the result is a NaN) so that one call follows one rule; the tests hold the fallback to the builtin bit for bit for every number and to "is a NaN" for a NaN (under QEMU the loong64 builtin was seen to pick a different operand of two NaNs in the loop and in a test closure, so its NaN payload is not even stable per call site). Not yet timed against NumPy (docs/perf-exempt.md); the other targets were verified for correctness only.

Exp, Log (float64) and Float32Exp, Float32Log
function computes parity with NumPy
Exp(dst, src) / Log(dst, src) exp / log of every src[i], float64, 0.511 / 0.519 ULP (Arm optimized-routines, MIT) tolerance (ULP-bounded, not NumPy's bits)
Float32Exp(dst, src) / Float32Log(dst, src) the correctly rounded float32 exp / log correct rounding is the reference: every float32 input rounds as the exact value does (proven over all 2^32 inputs by the env-gated TestExp32CorrectlyRounded / TestLog32CorrectlyRounded, NDARRAY_EXHAUSTIVE=1, a 300-bit reference and a certifier; every 65537th input without it); labelled tolerance against NumPy, whose float32 exp/log are not correctly rounded

Moved here from go-ndarray's internal/kernels (K1 of the go-scikit performance campaign), with the kernels written there: the AVX2 float32 exp/log (go-ndarray#94), the AVX2 float64 log (go-ndarray#96) and the NEON float32 exp/log (go-ndarray#95). The float32 functions compute in float64 and round once: expCR is Arm's correctly rounded expf (optimized-routines, MIT; math.FMA exactly where cr_expf fuses) and logCR is CORE-MATH's correctly rounded logf (MIT; every product wrapped in float64(...) so no architecture fuses it). Bit-identity to those Go transcriptions is the oracle: the AVX2 (amd64) and NEON (arm64) kernels run the same operations in the same order, and a block of 8 holding a lane they do not finish (a NaN or |x| > 512 for exp; a non-positive-normal input or bounds that round apart for log) is not stored, it is handed back to Go. Float64 Log has an AVX2 kernel (blocks of 4, handed back likewise) on amd64; float64 Exp and Log on arm64 and every other architecture, and the float32 functions on the other four, run the Go loops. The NEON kernels use instructions Go's assembler spells only as WORD in go-asmgen's output (FCVTL/FCVTN, UXTL/SXTL, SCVTF, FACGE, CMGT, BIC); go tool objdump on the test binary shows each disassembling to the mnemonic its comment claims. Nothing allocates. Timing against NumPy is deferred (bench/perf).

Unfused, NumPy-exact updates (float64)
function computes (NumPy expression)
AxpyNoFMA(alpha, x, y) y[i] = y[i] + alpha*x[i] (y + alpha*x)
XpbyNoFMA(x, beta, y) y[i] = x[i] + beta*y[i] (x + beta*y)
Axpby3NoFMA(dst, alpha, a, beta, b, gamma, c) dst[i] = alpha*a[i] + beta*b[i] + gamma*c[i], left to right
AxpyRowsNoFMA(a, x, ldx, y) y[j] = (((y[j] + a[0]*x[j]) + a[1]*x[ldx+j]) + …), unfused, rows in increasing order: the bits of len(a) AxpyNoFMA calls with y loaded and stored once — one row of an exact matrix product (2.1× the AxpyNoFMA loop at 100×100, M4 Max)
AxpyDiffNoFMA(dst, a, f, b, c) dst[i] = a[i] + f*(b[i] - c[i]) — the differential-evolution mutation (rand/1, best/1; dst = a = c = b gives b += f*(x - b) of rand-to-best/1)
Polyval(dst, x, c) dst[i] = polyval(x[i], c), numpy.polynomial.polynomial.polyval(x, c, tensor=False): c0 = c[-1] + x*0; c0 = c[-i] + c0*x
Chebval(dst, x, c) dst[i] = chebval(x[i], c), numpy.polynomial.chebyshev.chebval(x, c, tensor=False): Clenshaw, x2 = 2*x, c0 = c[-i] - c1; c1 = tmp + c1*x2, then c0 + c1*x

Axpy, Xpby and Axpby3 are fused: one rounding per element, which is the more accurate result and what BLAS does, but not what NumPy does. NumPy never fuses: y + alpha*x is two ufunc calls, a multiply that rounds into a temporary and an add that rounds again, and a + F*(b - c) is three. A solver validated by exact equality against SciPy (differential evolution, basin hopping) has to take that path, so these kernels round every product and every sum on its own, in the order NumPy evaluates the temporaries, and are bit-identical to the NumPy expression on every architecture (the payload of a NaN that an operation itself creates, Inf - Inf or 0*Inf, aside; a NaN that is the only NaN operand keeps its sign and payload, as in NumPy).

amd64 (AVX2, same gate as the other kernels) uses VMULPD/VADDPD/VSUBPD and arm64 VFMUL/VFADD/VFSUB — never a fused instruction; both are ×4 unrolled with a 1-vector loop and a scalar tail, never read or write past a slice (guard page tests), and allow dst to be the very slice of an input. The portable code (ppc64le, s390x, riscv64, loong64, 32-bit) writes every product through an explicit float64(...) conversion, which the Go specification says prevents the compiler from fusing x*y + z; without it a plain Go loop is not NumPy's arithmetic on those architectures (nor on arm64).

Validated against NumPy 2.5.4 on 13 088 committed fixture cases (the inputs are regenerated from seeds, the fixture holds a SHA-256 prefix of NumPy's result bits per case): the four kernels × ten input families (uniform, wide exponent, cancellation in b - c, rounding ties, ±0, -0 only, +Inf, one NaN, ±Inf / NaN of both signs / ±0) × every length 0..300 and the block boundaries, plus 1e3 / 4097 / 100 001 — 0 mismatches on arm64 and on amd64, from the same fixture. A planted fused variant (math.FMA) differs from the fixture in 1 400 to 1 800 cases per operation, and planted reordered variants (a + (F*b - F*c), right-to-left sums) in 700 to 2 800, so the fixture can tell them apart. Regenerate with NOFMA_REGEN=1 go test -run RegenerateNoFMA . (needs uv, or NUMPY_PYTHON). FuzzNoFMAKernels checks the SIMD kernels against the portable loops.

Reproducing np.sum: SumPairwise (float64)
function computes
SumPairwise(a) Σ a[i], bit-identical to np.sum(a) for a contiguous 1-D float64 array; +0 for an empty slice

Sum adds in the lane order of the SIMD kernels, which is fast but is not NumPy's order, so its last bits differ from np.sum. When a result must be reproducible against NumPy (a stopping test comparing np.std of a population with a tolerance, a regression against a NumPy oracle), use SumPairwise. It is NumPy's pairwise summation, transcribed from DOUBLE_pairwise_sum (numpy/_core/src/umath/loops_utils.h.src, v2.5.3): fewer than 8 elements are added left to right from -0; up to PW_BLOCKSIZE = 128 elements are summed with eight independent accumulators, folded as ((r0+r1)+(r2+r3)) + ((r4+r5)+(r6+r7)), then the non-multiple-of-8 rest is added one by one; a longer block is split at n/2 rounded down to a multiple of 8 and the two halves are added. np.add.reduce then adds the result to its initial +0, so a slice holding only -0 sums to +0, as in NumPy.

It is bit-identical on every architecture: the order is fixed in the code, not by the width of a vector register, and no step is a fused multiply-add. The 8..128-element blocks run in SIMD on amd64 (AVX2: the eight accumulators r[0..7] are two 4-lane YMM registers, VADDPD per step, the fold ((r0+r1)+(r2+r3)) + ((r4+r5)+(r6+r7)) by VHADDPD + VEXTRACTF128 + VADDSD) and arm64 (NEON: four 2-lane registers, VFADD per step, the fold by VFADDP), and on ppc64le (VSX), loong64 (LASX), riscv64 (RVV, one vl=8 group) and s390x (VX), with the same accumulator-per-lane structure: every lane receives exactly the additions NumPy's scalar code performs on its r[j], so the bits do not change. The recursion, the n < 8 start from -0, the n % 8 tail and the initial +0 stay as above; the other architectures run the portable Go block, which is also the reference the tests compare the SIMD blocks against (TestSumPairwiseSIMDMatchesReference, every length 0..700 at eight start offsets, on raw bit patterns).

Validated against NumPy 2.5.4 on 6 990 committed fixture cases: every length 0..300 for nine value families (uniform, wide exponent, cancellation, ties at the rounding edge, ±0, -0 only, +Inf, one NaN of either sign, a mix of ±Inf / NaN / ±0), both sides of every block boundary 128·2^j ± 12 up to j = 13, and 1e5 / 1e6 / 2^20 with odd lengths around them — 0 mismatches. A NaN result is compared bit for bit when exactly one NaN enters the sum; with several NaNs (or +Inf and -Inf) which NaN comes out is hardware-dependent (in NumPy as here), so only "is NaN" is compared. The fixtures are regenerated with SUMPW_REGEN=1 go test -run Regenerate . (needs uv); FuzzSumPairwise checks against an independent index-based transcription.

Why this library

The Go SIMD-float landscape, compared:

dot/dist/cosine float32 amd64 arm64 ppc64le / s390x / riscv64 / loong64
gonum/floats dot, L2 only ✗ (float64 only) SSE ✗ ✗
viterin/vek ✓ ✓ AVX2+FMA ✗ ✗
kelindar/simd ✗ (sum/min/max only) ✓ AVX2 NEON ✗
go-simd/floats ✓ ✓ AVX2+FMA NEON ✓ (all four)

This is the only pure-Go float reduction library that ships the full vector-search API (dot / Euclidean / cosine) for both float32 and float64 on all six of Go's 64-bit SIMD architectures.

How the SIMD is built

Every kernel is an FMA-based vectorised reduction: a multi-lane accumulator folded with a fused multiply-add at the vector stride, then a horizontal reduce and a scalar tail.

arch ISA FMA op notes
amd64 AVX2 + FMA3 VFMADD231P{S,D} runtime-gated on cpu.X86.HasAVX2 && HasFMA; scalar fallback otherwise. Dot, Sum, Distance and the float32 forms run eight independent vector accumulators (the FMA/ADD latency of 4 cycles, 2 ports, otherwise caps one chain at a quarter of the issue width); CDotC runs eight too. Measured on a Zen 4 core, single-threaded, old/new: Dot n=1000 3.2x, n=4096 1.9x, n=1e6 1.6x; Sum 4.3x / 5.0x / 2.5x; Float32Dot 2.5x / 3.4x / 1.7x; Float32Sum 3.5x / 5.1x / 2.6x; n <= 16 is within 0.2-0.5 ns of before. The summation order is therefore unspecified: the contract is the bound gamma_n * sum|terms|, asserted against a 512-bit math/big oracle (TestReductionsMeetErrorBound)
arm64 NEON VFMLA Dot, Sum, Distance and the float32 forms run eight independent accumulators (16 float64 or 32 float32 per iteration; a shorter input skips the unrolled loop and its fold); baseline, no gate. Measured on a GitHub ubuntu-24.04-arm runner (Neoverse), old/new interleaved in one job, A/A within 1.00-1.04: Sum n=1000 3.4x, n=4096 3.5x, n=1e6 1.8x; Distance 1.7x / 1.8x / 1.2x; Float32Sum 3.1x / 3.3x / 1.7x; Float32Dot 1.2x / 1.2x / 1.0x; Dot is load-bound and unchanged (0.98-1.07x); n <= 16 is no slower than before
riscv64 RVV VFMUL+VFREDOSUMVS length-agnostic VSETVLI stripmining; gated on cpu.RISCV64.HasV
s390x vector facility (big-endian) VFMADB, VFMASB all six reductions (float64 and float32 Dot, Sum, SumSqDiff) run eight independent accumulators; the float64 kernels are the z13 baseline, the float32 ones need the vector-enhancements facility 1 (z14, gated on hasVXE, else the lane-blocked scalar reference) and their .SB ops (VFASB, VFSSB, VFMASB) are WORD-encoded because the released assembler has none; float64 below 16 elements uses a four-accumulator Go loop (n=8 Dot 7.5 to 6.2 ns, n=12 11.8 to 7.4 ns). Measured on z17, old/new: Dot n=1000 2.0x, Sum 5.9x, Distance 3.2x, Float32Dot 27x, Float32Sum 47x (see below)
ppc64le VSX XVMADDASP, XVMADDADP all six reductions run eight independent accumulators; the XV* ops are WORD-encoded (not in the released assembler) and use only ISA-2.06/2.07 VSX, gated on cpu.PPC64.IsPOWER8; float64 below 16 elements uses a four-accumulator Go loop (n=8 Sum 13.8 to 11.9 ns, n=12 21.5 to 13.4 ns). Measured on POWER9, old/new: Dot n=1000 2.2x, Sum 2.8x, Float32Dot 2.1x, Float32Sum 2.4x (see below)
loong64 LSX (float32 only) vfmadd.s vfmadd.s is WORD-encoded (no Go mnemonic yet); add/sub/xor use VADDF/VSUBF/VXORV. float64 routes to the gc-autovectorized loop. LA464 baseline, no gate

The .s files are committed; regenerate with go run *_gen.go (the generators are build-tagged //go:build ignore). All six are validated in CI — amd64/arm64 natively, the other four under QEMU (tonistiigi/binfmt) — at 100 % test coverage, with differential tests and FuzzDot/FuzzDistance/FuzzAxpy against the scalar reference on every architecture. The elementwise kernels are also checked bit for bit against math.FMA for every length 0..257 at four element offsets, and run on slices placed right against PROT_NONE guard pages so that a vector load past either end would fault.

Floating-point determinism

A SIMD reduction does not add its terms left-to-right: it keeps several independent accumulator lanes (for instruction-level parallelism) and folds them at the end, so its rounding differs from a naïve scalar loop. For dot / distance / cosine, bit-exactness against a naïve loop is neither meaningful nor required — correctness to a few ULP is.

So the reference the tests and fuzzers check against (dotLanes, sumSqDiffLanes, …) reduces in the same lane-blocked order the kernels use, and each kernel is required to match it to a tight, documented relative tolerance (1e-12 for float64, 1e-5 for float32) on every architecture. The differential tests and fuzzers enforce this, making the results deterministic and consistent across arches.

Performance

Apple M-series (arm64, native), go test -bench, ns/op (lower is better); simd is this library, naive is the textbook left-to-right Go loop (which the Go compiler already turns into a pipelined scalar FMADD loop):

op n=8 n=64 n=512 n=4096
Dot float64 simd 7.6 14.3 71.7 539
Dot float64 naive 2.4 18.5 152 1075
Float32Dot simd 9.5 11.7 39.4 276

The SIMD dot product is ~2× the compiler's scalar loop on medium/large vectors (≈57 GB/s float64, ≈59 GB/s float32 at n=512), and loses only on tiny inputs (n≤8) where the unroll/setup overhead dominates — the regime where you would not reach for SIMD anyway.

Elementwise updates

Median ns/op of 3 runs (-cpu 1 -benchtime 200ms, lower is better). naive is the loop callers write by hand (y[i] += alpha*x[i], …), single core:

op n Apple M4 Max simd naive speedup AMD EPYC 7763 (CI) simd naive speedup
Axpy 1e3 185 381 2.06× 121 634 5.25×
Axpy 1e5 22 992 40 087 1.74× 20 258 63 152 3.12×
Axpy 1e6 270 906 449 693 1.66× 201 142 631 576 3.14×
Xpby 1e3 184 368 2.01× 121 633 5.25×
Xpby 1e5 22 888 36 138 1.58× 20 373 63 207 3.10×
Xpby 1e6 234 768 387 107 1.65× 201 311 631 323 3.14×
AxpyDot 1e3 231 1 223 5.30× 160 933 5.85×
AxpyDot 1e5 33 085 160 507 4.85× 31 208 94 524 3.03×
AxpyDot 1e6 439 445 1 279 334 2.91× 301 463 946 170 3.14×
Scale 1e3 101 362 3.57× 83 633 7.67×
Scale 1e5 15 753 35 058 2.23× 11 967 62 810 5.25×
Scale 1e6 158 718 351 821 2.22× 108 396 629 221 5.80×

Mul, Axpby3, Clamp, MaxAbs against NumPy 2.5.4, measured on 2026-11-01 on the M4 Max (Python 3.12.12, python -m timeit), one core, median ns/op of 9 interleaved rounds (a Go benchmark run, then NumPy's, for every row), 1-minute load 2.7, with the former bench/numpycmp tool (retired: it compared Go's mean ns/op with timeit's best of 5, two statistics in one ratio). The tool is now refbench in bench/perf: every public function against NumPy 2.5.4 (pinned in bench/perf/refs.txt), calibrated loops timed in their own process, rounds alternating, the same input bytes on both sides (go test -run TestDataHash -floats.hash compares their SHA-256), the median and quartiles, refusing at a 1-minute load of 8 or above; docs/perf-table.md is generated from docs/perf.json, and its timing is deferred (load about 33 when it was migrated, allocation counts only). cd bench/perf && go test -run TestPerf . checks allocations, the table and that every public function has a case. NumPy statements of the table below: np.multiply(a, b, out=d), d[:] = 0.5*a - 1.5*b + 2.5*c, np.clip(a, lo, hi, out=d), np.abs(a).max().

op n floats Go loop NumPy vs Go loop vs NumPy
Mul 1e3 104 324 269 3.12× 2.59×
Mul 1e5 19 793 32 252 20 100 1.63× 1.02×
Mul 1e6 198 848 294 678 195 000 1.48× 0.98×
Axpby3 1e3 164 405 2 030 2.47× 12.39×
Axpby3 1e5 26 418 41 437 82 600 1.57× 3.13×
Axpby3 1e6 266 062 422 107 820 000 1.59× 3.08×
Clamp 1e3 193 2 651 1 190 13.76× 6.18×
Clamp 1e5 26 385 277 483 58 200 10.52× 2.21×
Clamp 1e6 265 349 2 783 761 576 000 10.49× 2.17×
MaxAbs 1e3 70 882 535 12.54× 7.61×
MaxAbs 1e5 7 139 89 699 20 500 12.56× 2.87×
MaxAbs 1e6 72 323 894 855 203 000 12.37× 2.81×

Axpby3, Clamp and MaxAbs beat NumPy by 2.2 to 12×. Mul is a pure streaming multiply (three arrays, 2.4 MB at 1e5 and 24 MB at 1e6, so it runs at cache and memory bandwidth) and ties NumPy there: an earlier 7-round run read 0.94× and 1.00× on the same two rows, the other 9-round run 1.02× and 0.98×, so the ±3% is run-to-run noise, not a gap that code can close; both are one load, one multiply and one store per element and the kernel is already unrolled 8 wide. At n = 1e3 Mul is 2.6× faster than NumPy (no dispatch overhead).

The M4 Max runs were on a shared workstation (1-minute load ≈ 6), the EPYC ones on a shared GitHub Actions runner (ubuntu-latest), so treat the absolute numbers as indicative. Every row is a win. The ubuntu-24.04-arm runner (Neoverse) measured 1.34–2.83× over the same benchmarks. ppc64le, s390x, riscv64 and loong64 run the scalar math.FMA loop and were not measured.

Honesty note on the other arches. amd64's AVX2+FMA kernel is validated for correctness on real x86 (an AVX2/FMA-capable VM) but the native-hardware throughput numbers are pending (the CI/dev x86 runner used here is TCG-emulated, so its timings are not representative). riscv64 and loong64 are QEMU-validated for correctness; native-hardware performance numbers are pending access to that hardware. s390x is now measured on real z15 (below).

ppc64le — measured on real POWER9 (GCC Compile Farm cfarm433, go1.26.4, 2026-06-27, Dot throughput MB/s, higher is better):

n float64 (autovectorized) float64 if it used VSX float32 VSX float32 naive
8 5700 2520 1755 2100
512 8700 6200 6340 4100
4096 9030 6200 6650 4150

That table is the single-accumulator generation: one xvmaddasp/xvmaddadp chain has a latency of 6-7 cycles and the float64 VSX kernel lost to the autovectorized loop (0.82×). Every kernel now keeps eight accumulators, and float64 has VSX kernels again, used from 16 elements up. Measured on cfarm433 (POWER9, one core, go1.26.4, 2026-11-22, ns/op, old → new, BenchmarkReduce):

n Dot Sum Distance Float32Dot Float32Sum
64 68 → 40 65 → 35 69 → 48 60 → 42 51 → 35
1000 788 → 355 934 → 281 795 → 495 599 → 345 596 → 251
4096 3589 → 1609 3264 → 1075 3232 → 1918 2706 → 1262 2397 → 829
1e6 781 → 740 µs 779 → 263 µs 784 → 734 µs 587 → 306 µs 587 → 198 µs

Dot and Distance at n=1e6 read two 8 MB arrays and sit at memory bandwidth (about 21 GB/s, 1.05×). For n ≤ 8 float64 pays the dispatch check, 3-5 ns. The hasVSX gate is POWER8+ (the kernels use ISA-2.06/2.07 VSX only). Correctness on ppc64le is validated under QEMU and on real POWER9 silicon.

s390x (IBM z15, VXE2, measured 2026-07-03) — linux1, go1.26.4, -count=6, Dot throughput GB/s, higher is better. At that time the single-accumulator VFMADB float64 Dot kernel lost to the autovectorized loop (VX 11.6 GB/s vs 20.6 GB/s = 0.56×), so Dot was routed to the loop, and float32 used the lane-blocked scalar reference.

All six reductions now run eight accumulators, and float32 has VX kernels (VFASB, VFSSB, VFMASB, WORD-encoded). Measured on a z17 (linux1, one core pinned, steal 0, host idle, go1.26.4, 2026-11-22, ns/op, old → new, BenchmarkReduce):

n Dot Sum Distance Float32Dot Float32Sum
64 27 → 17 32 → 11 48 → 28 210 → 18 200 → 16
1000 386 → 191 624 → 106 644 → 204 2849 → 105 2898 → 61
4096 1494 → 762 2612 → 387 2626 → 776 11673 → 385 11888 → 219
1e6 369 → 239 µs 642 → 142 µs 639 → 236 µs 2892 → 120 µs 2889 → 66 µs

float64 below 16 elements keeps the plain loops (the kernel's setup costs 1-3 ns there); Dot at n=16 is 1.7 ns slower than the loop. Correctness on s390x is validated under QEMU and on real z17 silicon (the whole suite, including TestReductionsMeetErrorBound).

Changes in v0.26.0

  • Maximum and Minimum (float64, dst[i] = max(a[i], b[i]) / min, the Go builtins): the pairwise elementwise kernels go-ndarray still ran as scalar loops (go-ndarray/ndarray#98, #118). NaN-propagating, max(-0, +0) is +0 and min(-0, +0) is -0 in either operand order; bit-identical to the builtin for numbers and zeros on every target. NaN results: with a vector kernel a NaN operand is returned unchanged (b[i] if both are NaNs); where no kernel runs the functions are the builtin loop, whose NaN choice is target-dependent. AVX2 and SSE2, NEON, VSX, the s390x vector facility, LASX and RVV kernels (compare-and-select; FMAX plus a NaN fix-up on arm64). One Zen 3 core, 1e5 float64: 2.0 to 3.0x the scalar loop, 3.9 to 5.0x at 1e3. Documented difference: the payload of a NaN result may differ from the compiler's own max on arm64 and amd64. Tests: edge pairs at every position, random differential, aliasing, guard pages, FuzzPairwise with a committed corpus.

Changes in v0.23.0

  • Abs, Neg, Square, Floor, Ceil, Trunc and RoundEven (float64, dst[i] = f(src[i])): the elementwise operations go-ndarray still ran as scalar loops (go-ndarray/ndarray#118), bit-identical to the Go expression on every input. AVX2 (VROUNDPD, sign masks; SSE2 for Abs, Neg, Square without AVX2+FMA), NEON, VSX, the s390x vector facility and LASX kernels; riscv64 RVV for Abs, Neg and Square, the rounding functions stay scalar there. One Zen 3 core, 1e5 float64: 2.7 to 3.6x the scalar loop, 6 to 11x at 1e3. Tests: edge table at every position, random differential, independent oracle, guard pages, FuzzRound with a committed corpus; the four QEMU lanes of CI run them.

Changes in v0.15.0

  • Float32Max and Float32Min run AVX2 kernels on amd64 from 32 elements up, behind the same AVX2+FMA gate as the other AVX2 kernels; the SSE2 kernels of v0.14.0 stay as the fallback (and below 32 elements). Contract unchanged (floats#46). One Zen 3 core (AMD EPYC 7773X), n = 1048576: 87.6 -> 67 us (Max), 90 -> 65 us (Min); n = 16384: 1.40 -> 0.77 us and 1.32 -> 0.74 us.

Changes in v0.14.0

  • Float32Max and Float32Min run SIMD kernels, moved here from go-ndarray's internal/kernels so the kernel lives once (go-ndarray/ndarray#98): SSE2 (amd64, baseline), NEON (arm64, from 16 elements), LSX (loong64, gated on LASX), VSX (ppc64le, gated on POWER8+), RVV (riscv64, gated on V) and VXE (s390x, z14+, from 16 elements); every other target, and every CPU without the extension, runs a four-chain loop. The contract is unchanged and bit-for-bit the sequential loop's (and numpy.max/numpy.min's): NaN if any element is NaN, -0 below +0, a panic on an empty slice. Tests: NaN and zeros at every position of every length up to 100 (every lane and tail slot), PROT_NONE fences on amd64 and arm64, a CPU-gate-off rerun on the four QEMU targets, and FuzzExtrema32 (nightly in fuzz.yml, seed corpus in CI).
  • The s390x CI lane runs QEMU's max CPU model (the float32 kernels need z14).

Changes in v0.12.0

  • Polyval(dst, x, c) and Chebval(dst, x, c): Horner and Clenshaw evaluation of one series at many points, in the order of numpy.polynomial 2.5.4 (polynomial/polynomial.py polyval, polynomial/chebyshev.py chebval), unfused, bit-identical to NumPy's result (fixtures built in a linux/amd64 container). AVX2, SSE2 (no AVX2+FMA) and NEON kernels; ppc64le, s390x, riscv64, loong64 and the 32-bit targets run the portable loop (#30).

Changes in v0.10.0

  • Max, Min, Float32Max, Float32Min order -0 < +0 like NumPy and Go's max/min (#32).
  • amd64 CPUs without AVX2+FMA run SSE2 kernels for Add, Sub, Mul, Div, Sqrt, ClampScalar (#31).
  • ppc64le, loong64, riscv64 and s390x run the SumPairwise block and the float64 Add, Sub, Mul, Div, Sqrt kernels (#30; Max/Min kernels on those architectures remain open).

License

BSD-3-Clause. © The go-simd authors.

Documentation

Overview

Package floats provides SIMD-accelerated reductions over float32 and float64 slices — the dot product, sum, min, max, Euclidean (L2) distance and cosine similarity that sit at the heart of vector search, embeddings and numerics. It is pure Go (CGO_ENABLED=0, stable Go, no GOEXPERIMENT): the hot reduction loops are SIMD assembly generated by go-asmgen on all six of Go's 64-bit SIMD targets — amd64 (AVX2+FMA), arm64 (NEON FMLA), ppc64le (VSX), s390x (vector facility), riscv64 (RVV) and loong64 (LSX) — with a portable scalar fallback everywhere else, all on a plain `go build`.

Operations

For both []float32 (the Float32 functions) and []float64:

Dot(a, b)              a·b = Σ aᵢbᵢ
Sum(a)                 Σ aᵢ
Min(a) / Max(a)        the minimum / maximum element
Distance(a, b)         ‖a−b‖₂ = √Σ(aᵢ−bᵢ)²
CosineSimilarity(a, b) a·b / (‖a‖₂‖b‖₂)

Dot, Distance and CosineSimilarity require len(a) == len(b) and panic otherwise. Min and Max panic on an empty slice. Sum of an empty slice is 0.

For []float64, the in-place elementwise updates (BLAS level 1) behind iterative solvers, QR and LU:

Axpy(α, x, y)          yᵢ = fma(α, xᵢ, yᵢ)          (y += αx)
Xpby(x, β, y)          yᵢ = fma(β, yᵢ, xᵢ)          (y = x + βy)
AxpyDot(α, x, y, w)    y += αx, then returns Σ yᵢwᵢ  (one pass)
Scale(α, x)            xᵢ = α·xᵢ

They operate on the first len(x) elements and panic if y (or w) is shorter. Unlike the reductions, the updated slices are bit-identical on every architecture: each element is rounded once, exactly as math.FMA rounds it (AVX2 FMA on amd64, NEON FMLA on arm64, the math.FMA loop elsewhere). Only AxpyDot's returned sum is a reduction and follows the rules below.

SumPairwise(a) is NumPy's np.sum(a) for a contiguous float64 array, bit for bit on every architecture (scalar, pairwise, block 128, eight accumulators); unlike Sum it does not follow the lane order below.

Floating-point determinism

A SIMD reduction does not add its terms left-to-right: it keeps several independent accumulator lanes (for instruction-level parallelism) and folds them together at the end, so the rounding differs from a naïve scalar loop. To stay deterministic and architecture-independent, the scalar reference used internally and by the tests (sumLanes / dotLanes / …) reduces in the *same* lane-blocked order the kernels use (laneCount lanes), and the SIMD result is required to agree with it to a tight, documented ULP bound across every architecture (the differential tests and FuzzDot/FuzzDistance enforce this). For the similarity use case (cosine / Euclidean distance) bit-exact equality with a naïve scalar loop is neither required nor meaningful; correctness to a few ULP is.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs added in v0.23.0

func Abs(dst, src []float64)

Abs computes dst[i] = math.Abs(src[i]) for i < len(src). It panics if len(dst) < len(src).

func Add added in v0.8.0

func Add(dst, a, b []float64)

Add computes dst[i] = a[i] + b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func Add32 added in v0.30.0

func Add32(dst, a, b []float32)

Add32 computes dst[i] = a[i] + b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func AllPass3 added in v0.29.0

func AllPass3(out, in []complex128, t *AllPassRows, old, cur *[3][]complex128)

AllPass3 computes the decorrelator rows described above for k < len(out). It panics if an operand is shorter than len(out) or a written slice overlaps another operand.

func AllPass3Split32 added in v0.43.0

func AllPass3Split32(out, in Split32, t *AllPassRows32, old, cur *[3]Split32)

AllPass3Split32 computes the decorrelator rows described above for k < len(out.Re). It panics if an operand is shorter than that or a written slice overlaps another operand.

func Axpby3 added in v0.5.0

func Axpby3(dst []float64, alpha float64, a []float64, beta float64, b []float64, gamma float64, c []float64)

Axpby3 computes the three-term combination

dst[i] = alpha*a[i] + beta*b[i] + gamma*c[i]

for i < len(a), fused: dst[i] = math.FMA(gamma, c[i], math.FMA(beta, b[i], alpha*a[i])) — see the package notes above. It panics if len(b), len(c) or len(dst) is less than len(a).

func Axpby3NoFMA added in v0.7.0

func Axpby3NoFMA(dst []float64, alpha float64, a []float64, beta float64, b []float64, gamma float64, c []float64)

Axpby3NoFMA computes dst[i] = alpha*a[i] + beta*b[i] + gamma*c[i] for i < len(a), unfused and left to right, as NumPy evaluates alpha*a + beta*b + gamma*c: ((alpha*a[i]) + (beta*b[i])) + (gamma*c[i]), five roundings. It is the unfused counterpart of Axpby3. It panics if len(b), len(c) or len(dst) is less than len(a).

func Axpy added in v0.4.0

func Axpy(alpha float64, x, y []float64)

Axpy computes y[i] += alpha*x[i] for i < len(x), fused: y[i] = math.FMA(alpha, x[i], y[i]). Elements of y past len(x) are left untouched. It panics if len(y) < len(x).

func AxpyDiffNoFMA added in v0.7.0

func AxpyDiffNoFMA(dst, a []float64, f float64, b, c []float64)

AxpyDiffNoFMA computes dst[i] = a[i] + f*(b[i] - c[i]) for i < len(a): the difference, the product and the sum each rounded in turn, as NumPy evaluates a + F*(b - c). It is the mutation step of differential evolution (rand/1, best/1 and the second half of rand-to-best/1; for b += F*(x - b) pass dst = a = c = b). It panics if len(b), len(c) or len(dst) is less than len(a).

func AxpyDot added in v0.4.0

func AxpyDot(alpha float64, x, y, w []float64) float64

AxpyDot computes y[i] += alpha*x[i] for i < len(x) exactly as Axpy does and returns Σ y[i]*w[i] over the updated elements, in one pass over the three slices — the residual update and its norm in conjugate gradient (r -= αAp; rr = r·r is AxpyDot(-α, Ap, r, r)). It panics if len(y) < len(x) or len(w) < len(x).

func AxpyGather added in v0.17.0

func AxpyGather(alpha float64, a []float64, idx []int, d []float64)

AxpyGather does d[k] = fma(alpha, a[idx[k]], d[k]) for every k (each element rounded once, bit-identical on every architecture). It panics if an index is out of range or len(d) < len(idx).

func AxpyNoFMA added in v0.7.0

func AxpyNoFMA(alpha float64, x, y []float64)

AxpyNoFMA computes y[i] = y[i] + alpha*x[i] for i < len(x) with two roundings, the product first: NumPy's y + alpha*x. Elements of y past len(x) are left untouched. It panics if len(y) < len(x).

func AxpyRowsNoFMA added in v0.13.0

func AxpyRowsNoFMA(a []float64, x []float64, ldx int, y []float64)

AxpyRowsNoFMA applies len(a) unfused AXPY updates to y in one pass: for j < len(y),

y[j] = (((y[j] + a[0]*x[0*ldx+j]) + a[1]*x[1*ldx+j]) + ...) + a[r-1]*x[(r-1)*ldx+j]

with r = len(a), every product rounded before its addition and the rows added in increasing order. The result is bit-identical to r successive AxpyNoFMA(a[k], x[k*ldx:k*ldx+len(y)], y) calls, but a block of y stays in registers across all r rows, so y is loaded and stored once instead of r times. It is the row of an exact matrix product C = A*B in i-k-j order: pass a = A[i,:], x = B (row-major, ldx = its row stride), y = C[i,:], and the entry is the left-to-right sum in increasing k that NumPy's matmul loop (and any reference that does not fuse) computes.

x holds row k at x[k*ldx:]; it must not overlap y. It panics if ldx < 0 or if x is shorter than (len(a)-1)*ldx + len(y). With len(a) == 0 or len(y) == 0 it does nothing (and checks nothing).

func CDotC added in v0.24.0

func CDotC(a, b []float64) (re, im float64)

CDotC returns the real and imaginary parts of Σ conj(a_k)·b_k for the n = len(a)/2 complex numbers a_k = (a[2k], a[2k+1]), b_k = (b[2k], b[2k+1]). It panics if len(a) is odd or len(b) < len(a).

func CMulGather added in v0.18.0

func CMulGather(dst, x, tw []float64)

CMulGather writes the pre-twiddle of a DCT-IV: see the formulas above.

func CMulGatherFrom32 added in v0.18.0

func CMulGatherFrom32(dst []float64, x []float32, tw []float64)

CMulGatherFrom32 is CMulGather with x read as float32 and widened.

func CMulScatter added in v0.18.0

func CMulScatter(dst, c, tw []float64, f float64)

CMulScatter writes the post-twiddle of a DCT-IV: see the formulas above.

func CMulScatterTo32 added in v0.18.0

func CMulScatterTo32(dst []float32, c, tw []float64, f float64)

CMulScatterTo32 is CMulScatter with each output rounded to float32.

func CMulTo added in v0.31.0

func CMulTo(dst, a, b []complex128)

CMulTo writes dst[i] = a[i]*b[i] for i < len(dst). It panics, before writing anything, if len(a) or len(b) is less than len(dst).

func CMulZipRev added in v0.28.0

func CMulZipRev(dst, x, y, w []float64)

CMulZipRev writes dst[j] = w[j] * (x[j] - i y[m-1-j]) for j < m = len(dst)/2.

func Ceil added in v0.23.0

func Ceil(dst, src []float64)

Ceil computes dst[i] = math.Ceil(src[i]) for i < len(src): the smallest integer not below the value; Ceil(-0.5) is -0 (np.ceil). It panics if len(dst) < len(src).

func Chebval added in v0.12.0

func Chebval(dst, x, c []float64)

Chebval computes dst[i] = sum c[k]*T_k(x[i]) for i < len(x) by Clenshaw's recurrence in NumPy's order (numpy.polynomial.chebyshev.chebval). It panics if len(dst) < len(x) or len(c) == 0. Elements of dst past len(x) are left untouched.

func Clamp added in v0.5.0

func Clamp(dst, v, lo, hi []float64)

Clamp projects v onto the box [lo, hi] elementwise, min(max(v[i], lo[i]), hi[i]), for i < len(v):

r := v[i]; if lo[i] > r { r = lo[i] }; if hi[i] < r { r = hi[i] }; dst[i] = r

Exact semantics, identical on every architecture:

  • a NaN v[i] propagates unchanged (same bits, whatever its sign);
  • a NaN bound is ignored, as if that side were infinite;
  • lo[i] > hi[i] gives hi[i] (the upper bound wins);
  • signed zeros are compared as equal, so Clamp(-0, +0, hi) keeps -0 and Clamp(+0, -0, hi) keeps +0: the result is v[i] unless a strict bound replaces it.

It panics if len(lo), len(hi) or len(dst) is less than len(v). For one-sided bounds pass ±Inf.

func ClampScalar added in v0.8.0

func ClampScalar(dst, v []float64, lo, hi float64)

ClampScalar limits every element of v to [lo, hi], like np.clip with scalar bounds and like Clamp with the same bounds at every index:

r := v[i]; if lo > r { r = lo }; if hi < r { r = hi }; dst[i] = r

A NaN v[i] passes through unchanged (same bits); a NaN bound is ignored (that side is unbounded); lo > hi gives hi; signed zeros compare equal, so the result is v[i] unless a strict bound replaces it. It panics if len(dst) < len(v).

func ConjReverse added in v0.21.0

func ConjReverse(dst, src []float64)

ConjReverse writes the n = len(dst)/2 complex numbers (src[2k], src[2k+1]) conjugated and in reverse order into dst.

func CosineSimilarity

func CosineSimilarity(a, b []float64) float64

CosineSimilarity returns a·b / (‖a‖₂‖b‖₂), a value in [-1, 1] measuring the angle between a and b — the standard relevance score for embedding vectors. It panics if len(a) != len(b). If either vector has zero magnitude the result is NaN (0/0), matching the mathematical definition.

func Distance

func Distance(a, b []float64) float64

Distance returns the Euclidean (L2) distance ‖a−b‖₂ = √Σ(aᵢ−bᵢ)². It panics if len(a) != len(b).

func Div added in v0.8.0

func Div(dst, a, b []float64)

Div computes dst[i] = a[i] / b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func Div32 added in v0.30.0

func Div32(dst, a, b []float32)

Div32 computes dst[i] = a[i] / b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func Dot

func Dot(a, b []float64) float64

Dot returns the dot product a·b = Σ aᵢbᵢ. It panics if len(a) != len(b).

func DotGather added in v0.17.0

func DotGather(a []float64, idx []int, d []float64) float64

DotGather returns Σ a[idx[k]]·d[k] (d is contiguous, a is gathered). It panics if an index is out of range or len(d) < len(idx).

func DotIdx added in v0.17.0

func DotIdx(a, b []float64, idx []int) float64

DotIdx returns Σ a[idx[k]]·b[idx[k]]. It panics if an index is out of range.

func Exp added in v0.9.0

func Exp(dst, src []float64)

Exp writes exp(src[i]) into dst[i] for i < len(src), accurate to 0.511 ULP (Arm documents 0.509 with FMA): a ULP-bounded exp, not NumPy's bits (tolerance parity). It panics if len(dst) < len(src). Moved here from go-ndarray's internal/kernels (K1 of the go-scikit performance campaign). exp1 is too large to inline, and a call per element cost half the time, so the common case (2^-54 <= |x| < 512) is exp1's main path written out in the loop; everything else calls exp1. TestExpLoopMatchesExp1 holds the two to the same bits.

func Float32CosineSimilarity

func Float32CosineSimilarity(a, b []float32) float32

Float32CosineSimilarity returns a·b / (‖a‖₂‖b‖₂) over float32 slices — the relevance score for float32 embedding vectors. It panics if len(a) != len(b). If either vector has zero magnitude the result is NaN.

func Float32Distance

func Float32Distance(a, b []float32) float32

Float32Distance returns the Euclidean (L2) distance ‖a−b‖₂ over float32 slices. The squared-difference sum is accumulated in float32 and the square root taken in float64 for accuracy. It panics if len(a) != len(b).

func Float32Dot

func Float32Dot(a, b []float32) float32

Float32Dot returns the dot product a·b = Σ aᵢbᵢ over float32 slices, accumulated in float32. It panics if len(a) != len(b).

func Float32Exp added in v0.9.0

func Float32Exp(dst, src []float32)

Float32Exp writes the correctly rounded float32 exp(src[i]) into dst[i] for i < len(src) (every float32 input rounds as the exact value does: proven over all 2^32 by TestExp32CorrectlyRounded, which is env-gated). Both operations are computed in float64 and rounded once: expCR, Arm's correctly rounded expf (optimized-routines, MIT), on an AVX2+FMA kernel on amd64 and a NEON kernel on arm64, in Go elsewhere. Nothing is allocated. Moved here from go-ndarray's internal/kernels with the AVX2 kernel of go-ndarray#94 and the NEON kernel of go-ndarray#95. It panics if len(dst) < len(src).

func Float32Log added in v0.9.0

func Float32Log(dst, src []float32)

Float32Log writes the correctly rounded float32 log(src[i]) into dst[i] for i < len(src) (proven over all 2^32 inputs by TestLog32CorrectlyRounded, which is env-gated): logCR, CORE-MATH's correctly rounded logf (MIT), on an AVX2 kernel on amd64 and a NEON kernel on arm64, in Go elsewhere. log(±0) = -Inf, log(+Inf) = +Inf, negative and NaN inputs give NaN. Nothing is allocated. Moved here from go-ndarray's internal/kernels with the kernels of go-ndarray#94 and #95. It panics if len(dst) < len(src).

func Float32Max

func Float32Max(a []float32) float32

Float32Max returns the largest element of a. It panics if a is empty. If a contains a NaN the result is NaN, and +0 orders above -0, as numpy.max. Same kernels as Float32Min.

func Float32Min

func Float32Min(a []float32) float32

Float32Min returns the smallest element of a. It panics if a is empty. If a contains a NaN the result is NaN, and -0 orders below +0, as numpy.min. SIMD kernels on amd64 (SSE2), arm64 (NEON), loong64 (LSX), ppc64le (VSX), riscv64 (RVV) and s390x (VXE); the four-chain loop elsewhere. The result is bit-for-bit the sequential loop's.

func Float32OverlapWindow added in v0.16.0

func Float32OverlapWindow(dst, a, b, win []float32)

Float32OverlapWindow is OverlapWindow on float32 values, computed in float32.

func Float32Sum

func Float32Sum(a []float32) float32

Float32Sum returns Σ aᵢ over a float32 slice, accumulated in float32. The sum of an empty slice is 0.

func Floor added in v0.23.0

func Floor(dst, src []float64)

Floor computes dst[i] = math.Floor(src[i]) for i < len(src): the largest integer not above the value, ±0, ±Inf and NaN unchanged (np.floor). It panics if len(dst) < len(src).

func Log added in v0.9.0

func Log(dst, src []float64)

Log writes log(src[i]) into dst[i] for i < len(src), accurate to 0.519 ULP (0.507 near 1): a ULP-bounded log, not NumPy's bits (tolerance parity): on the AVX2 kernel where there is one (explog_amd64.go), on logScalar otherwise and for the blocks the kernel hands back. It panics if len(dst) < len(src). Moved here from go-ndarray's internal/kernels, with the AVX2 kernel of go-ndarray#96.

func MDCTFold added in v0.19.0

func MDCTFold(dst, x []float64)

MDCTFold writes the fold of the N = len(x) samples of x into dst[:N/2].

func MDCTFoldFrom32 added in v0.19.0

func MDCTFoldFrom32(dst []float64, x []float32)

MDCTFoldFrom32 is MDCTFold with x read as float32 and widened.

func MDCTUnfold added in v0.19.0

func MDCTUnfold(dst, u []float64)

MDCTUnfold writes the unfolding of the M = len(u) values of u into dst[:2M].

func MDCTUnfoldTo32 added in v0.19.0

func MDCTUnfoldTo32(dst []float32, u []float64)

MDCTUnfoldTo32 is MDCTUnfold with each output rounded to float32.

func Max

func Max(a []float64) float64

Max returns the largest element of a. It panics if a is empty. If a contains a NaN the result is NaN. Signed zeros are ordered -0 < +0, as NumPy's np.max and Go's builtin max: the maximum of any mix containing a +0 is +0.

func MaxAbs added in v0.5.0

func MaxAbs(v []float64) float64

MaxAbs returns the infinity norm max |v[i]|, and 0 for an empty slice. If any element is NaN (of either sign) it returns NaN (math.NaN()); ±Inf elements give +Inf.

func MaxAbsMul added in v0.25.0

func MaxAbsMul(v, w []float64) float64

MaxAbsMul returns max over i of |v[i]|*w[i], folded with C's fmax from +0:

  • a NaN product (a NaN element, or Inf*0) is ignored, as fmax ignores a NaN argument; the result is NaN never (unlike MaxAbs, which propagates it);
  • the fold starts at +0 and a product replaces the running maximum when it is greater or equal, so a negative product (w < 0) never wins over the seed and the sign of a zero result is that of the last zero product seen, +0 if there is none: exactly the loop `m = fmax(m, |v[i]|*w[i])` with m = +0;
  • it returns +0 for an empty slice.

It panics if len(w) < len(v). Only the first len(v) elements of w are read.

func Maximum added in v0.26.0

func Maximum(dst, a, b []float64)

Maximum computes dst[i] = max(a[i], b[i]) for i < len(a), the Go builtin max: NaN-propagating, +0 above -0, np.maximum up to the choice of NaN and the order of a (-0, +0) pair. With a vector kernel a NaN operand is returned unchanged and, if both are NaNs, b[i]'s; where no kernel runs it is the builtin loop, whose NaN choice is target-dependent (see README). It panics if len(b) < len(a) or len(dst) < len(a).

func Min

func Min(a []float64) float64

Min returns the smallest element of a. It panics if a is empty. If a contains a NaN the result is NaN. Signed zeros are ordered -0 < +0, as NumPy's np.min and Go's builtin min: the minimum of any mix containing a -0 is -0.

func Minimum added in v0.26.0

func Minimum(dst, a, b []float64)

Minimum computes dst[i] = min(a[i], b[i]) for i < len(a), the Go builtin min: NaN-propagating, -0 below +0, np.minimum up to the choice of NaN and the order of a (-0, +0) pair. With a vector kernel a NaN operand is returned unchanged and, if both are NaNs, b[i]'s; where no kernel runs it is the builtin loop, whose NaN choice is target-dependent (see README). It panics if len(b) < len(a) or len(dst) < len(a).

func MirrorCombine added in v0.27.0

func MirrorCombine(dst, z, w1, w2 []float64)

MirrorCombine writes r[k], k = 1 .. n-1, as complex numbers into dst[2k], dst[2k+1].

func MirrorCombineSplit added in v0.27.0

func MirrorCombineSplit(dst, z, w1, w2 []float64)

MirrorCombineSplit writes Re r[k] to dst[k] and -Im r[k] to dst[2n-k], k = 1 .. n-1.

func Mul added in v0.5.0

func Mul(dst, a, b []float64)

Mul computes dst[i] = a[i]*b[i] for i < len(a). Elements of dst and b past len(a) are left untouched. It panics if len(b) < len(a) or len(dst) < len(a).

func Mul32 added in v0.30.0

func Mul32(dst, a, b []float32)

Mul32 computes dst[i] = a[i] * b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func MulAddRows added in v0.22.0

func MulAddRows(dst, a []float64, lda int, b []float64, ldb int, rows int)

MulAddRows computes dst[j] += Σ_{k<rows} a[k*lda+j]*b[k*ldb+j] for every j < len(dst), each term a fused multiply-add in increasing k. rows = 0 or an empty dst do nothing. It panics if rows, lda or ldb is negative, if a or b is shorter than the contract says or the index would overflow, or if dst overlaps the elements read of a or b.

func MulAddRows32 added in v0.33.0

func MulAddRows32(dst, a []float32, lda int, b []float32, ldb int, rows int)

MulAddRows32 computes dst[j] += Σ_{k<rows} a[k*lda+j]*b[k*ldb+j] for every j < len(dst), in float32. rows = 0 or an empty dst do nothing. It panics if rows, lda or ldb is negative, if a or b is shorter than the contract says or the index would overflow, or if dst overlaps the elements read of a or b.

func Neg added in v0.23.0

func Neg(dst, src []float64)

Neg computes dst[i] = -src[i] for i < len(src): the sign bit is flipped, also for zeros, infinities and NaNs. It panics if len(dst) < len(src).

func OverlapWindow added in v0.16.0

func OverlapWindow(dst, a, b, win []float64)

OverlapWindow computes the windowed overlap-add of a and b under win into dst for n = len(a): dst has at least 2n elements, b at least n and win at least 2n. It writes dst[:2n] and panics if a slice is too short.

func Polyval added in v0.12.0

func Polyval(dst, x, c []float64)

Polyval computes dst[i] = p(x[i]) for i < len(x), where p is the polynomial c[0] + c[1]*t + ... + c[len(c)-1]*t^(len(c)-1) evaluated by Horner's rule in NumPy's order (numpy.polynomial.polynomial.polyval). It panics if len(dst) < len(x) or len(c) == 0 (NumPy raises IndexError). Elements of dst past len(x) are left untouched.

func RoundEven added in v0.23.0

func RoundEven(dst, src []float64)

RoundEven computes dst[i] = math.RoundToEven(src[i]) for i < len(src): the nearest integer, halfway cases to the even one (np.rint, and np.round with no decimals). It panics if len(dst) < len(src).

func Scale added in v0.4.0

func Scale(alpha float64, x []float64)

Scale computes x[i] *= alpha for every element of x.

func Sqrt added in v0.8.0

func Sqrt(dst, src []float64)

Sqrt computes dst[i] = math.Sqrt(src[i]) for i < len(src): the correctly rounded square root, sqrt(-x) = NaN, sqrt(-0) = -0, sqrt(+Inf) = +Inf. It panics if len(dst) < len(src).

func Sqrt32 added in v0.30.0

func Sqrt32(dst, src []float32)

Sqrt32 computes dst[i] = float32(math.Sqrt(float64(src[i]))) for i < len(src): the correctly rounded square root, sqrt(-x) = NaN, sqrt(-0) = -0, sqrt(+Inf) = +Inf. It panics if len(dst) < len(src).

func Square added in v0.23.0

func Square(dst, src []float64)

Square computes dst[i] = src[i] * src[i] for i < len(src), one rounding per element (np.square). It panics if len(dst) < len(src).

func SquaredMagnitude added in v0.20.0

func SquaredMagnitude(dst, c []float64, s float64)

SquaredMagnitude writes dst[k] = (re_k² + im_k²)·s for the n = len(dst) complex numbers (re_k, im_k) = (c[2k], c[2k+1]).

func Sub added in v0.8.0

func Sub(dst, a, b []float64)

Sub computes dst[i] = a[i] - b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func Sub32 added in v0.30.0

func Sub32(dst, a, b []float32)

Sub32 computes dst[i] = a[i] - b[i] for i < len(a). It panics if len(b) < len(a) or len(dst) < len(a).

func Sum

func Sum(a []float64) float64

Sum returns Σ aᵢ. The sum of an empty slice is 0.

func SumPairwise added in v0.6.0

func SumPairwise(a []float64) float64

SumPairwise returns Σ aᵢ computed exactly as NumPy computes np.sum(a) for a contiguous one-dimensional float64 array: the same pairwise summation, with the same block size, the same eight-accumulator unrolling and the same order of partial sums. The result is bit-identical to np.sum(a) — on every architecture, because the order is fixed by this code rather than by the width of a vector register, and no step is a fused multiply-add.

It is the function to use when a result must be reproducible against NumPy (for instance a stopping test that compares np.std of a population with a tolerance). It is not the same as Sum, whose lane-blocked order trades reproducibility for speed on the SIMD kernels.

The sum of an empty slice is +0, and so is the sum of a slice holding only -0 (the reduction starts from +0), as in NumPy. NaN and ±Inf propagate by IEEE 754 rules; when several NaNs are summed which payload survives is, as in NumPy, up to the hardware.

The 8..128-element blocks at the leaves of the recursion run in SIMD on amd64 (AVX2: the eight accumulators r[0..7] are two 4-lane YMM registers) and arm64 (NEON: four 2-lane registers); every lane receives exactly the additions NumPy's scalar code performs on the matching r[j], so the bits do not change. Elsewhere the portable Go block (pairwiseBlockRef) runs; it is also the reference the tests compare the SIMD blocks against.

func Trunc added in v0.23.0

func Trunc(dst, src []float64)

Trunc computes dst[i] = math.Trunc(src[i]) for i < len(src): the integer part, rounding toward zero, with the sign of the value (Trunc(-0.5) is -0) (np.trunc). It panics if len(dst) < len(src).

func Xpby added in v0.4.0

func Xpby(x []float64, beta float64, y []float64)

Xpby computes y[i] = x[i] + beta*y[i] for i < len(x), fused: y[i] = math.FMA(beta, y[i], x[i]). It is the search-direction update of conjugate gradient (p = r + βp). It panics if len(y) < len(x).

func XpbyNoFMA added in v0.7.0

func XpbyNoFMA(x []float64, beta float64, y []float64)

XpbyNoFMA computes y[i] = x[i] + beta*y[i] for i < len(x) with two roundings, the product first: NumPy's x + beta*y. It panics if len(y) < len(x).

Types

type AllPass3Plan added in v0.33.0

type AllPass3Plan struct {
	// contains filtered or unexported fields
}

AllPass3Plan is a set of memory proved for AllPass3. It is not safe for concurrent use.

func NewAllPass3Plan added in v0.33.0

func NewAllPass3Plan(t *AllPassRows, out, in []complex128, inStride int, w [3][]complex128, wStride [3]int) (*AllPass3Plan, error)

NewAllPass3Plan proves the memory of n = len(t.Phi) rows and returns the plan. It returns an error, and no plan, if

  • any table of t does not hold n elements, or n is 0,
  • out holds fewer than n elements,
  • a stride is below n, or a ring holds fewer than one slot (the input) or two slots (a link ring: one slot to read and another to write),
  • any of out and the three link rings (the written memory) overlaps any other of them, the input ring or a table. The tables and the input ring may overlap one another: they are only read.

The slices are kept: the caller must not reslice them elsewhere to write the proved memory while a plan uses it through another name; the plan guarantees that its own calls never write outside out and the link rings.

func NewAllPass3TickPlan added in v0.41.0

func NewAllPass3TickPlan(t *AllPassRows, out, in []complex128, inStride int, w [3][]complex128, wStride [3]int, inDelay int) (*AllPass3Plan, error)

NewAllPass3TickPlan is NewAllPass3Plan for a decorrelator driven by a tick counter: the plan keeps inDelay, the age in ticks of the input slot that RunTick reads. It refuses, besides the cases of NewAllPass3Plan, an inDelay that is negative or not below the number of slots of the input ring.

func (*AllPass3Plan) Out added in v0.33.0

func (p *AllPass3Plan) Out() []complex128

Out is the output of the last Run: n elements, owned by the plan's caller.

func (*AllPass3Plan) Rows added in v0.33.0

func (p *AllPass3Plan) Rows() int

Rows is the number of rows n of the plan.

func (*AllPass3Plan) Run added in v0.33.0

func (p *AllPass3Plan) Run(inSlot int, oldSlot, curSlot [3]int)

Run computes the rows of one slot: the input is slot inSlot of the input ring, link l reads its state in slot oldSlot[l] of its ring and writes the new one to slot curSlot[l], and the result goes to Out. It panics, before reading or writing anything, if a slot number is out of range or a link reads the slot it writes.

func (*AllPass3Plan) RunTick added in v0.41.0

func (p *AllPass3Plan) RunTick(t int)

RunTick is Run for tick t: link l, whose ring holds m slots, reads slot (t+1) mod m and writes slot t mod m; the input is slot (t - inDelay) mod s of the input ring of s slots (inDelay is 0 for a plan from NewAllPass3Plan). The slots follow from t and from sizes proved at construction (every ring of a link holds at least two slots, so no link reads the slot it writes, and every slot is in range), so a call checks nothing and cannot panic for any t, negative or not. For t >= 0 the result is bit-identical to Run on those slots; a negative t reduces as uint(t) does, memory-safe but not continuous.

type AllPass3Plan32 added in v0.43.0

type AllPass3Plan32 struct {
	// contains filtered or unexported fields
}

AllPass3Plan32 is a set of memory proved for AllPass3Split32. It is not safe for concurrent use.

func NewAllPass3TickPlan32 added in v0.43.0

func NewAllPass3TickPlan32(t *AllPassRows32, out, in Split32, inStride int, w [3]Split32, wStride [3]int, inDelay int) (*AllPass3Plan32, error)

NewAllPass3TickPlan32 proves the memory of n = len(t.PhiRe) rows for a decorrelator driven by a tick counter, and returns the plan. It returns an error, and no plan, if

  • any table of t does not hold n elements, or n is 0,
  • a plane of out holds fewer than n elements,
  • the two planes of a ring differ in length, a stride is below n, or a ring holds fewer than one slot (the input) or two slots (a link ring: one to read and another to write),
  • inDelay is negative or not below the number of slots of the input ring,
  • any of out and the three link rings (the written memory, every plane) overlaps any other of them, the input ring or a table. The tables and the input ring may overlap one another: they are only read.

The slices are kept: the caller must not reslice them elsewhere to write the proved memory while a plan uses it through another name; the plan guarantees that its own calls never write outside out and the link rings.

func (*AllPass3Plan32) Out added in v0.43.0

func (p *AllPass3Plan32) Out() Split32

Out is the output of the last RunTick: n elements per plane, owned by the plan's caller.

func (*AllPass3Plan32) Rows added in v0.43.0

func (p *AllPass3Plan32) Rows() int

Rows is the number of rows n of the plan.

func (*AllPass3Plan32) RunTick added in v0.43.0

func (p *AllPass3Plan32) RunTick(t int)

RunTick computes the rows of tick t: link l, whose ring holds m slots, reads slot (t+1) mod m and writes slot t mod m; the input is slot (t - inDelay) mod s of the input ring of s slots; the result goes to Out. The slots follow from t and from sizes proved at construction (every ring of a link holds at least two slots, so no link reads the slot it writes, and every slot is in range), so a call checks nothing and cannot panic for any t, negative or not; a negative t reduces as uint(t) does, memory-safe but not continuous.

type AllPassRows added in v0.29.0

type AllPassRows struct {
	Phi, Q0, Q1, Q2 []complex128
	C0, C1, C2      []float64
}

AllPassRows holds the constants of the rows of a layout: Phi the rotation of the pre-delay, Q_l the rotation of link l, C_l its real coefficient.

type AllPassRows32 added in v0.43.0

type AllPassRows32 struct {
	PhiRe, PhiIm, Q0Re, Q0Im, Q1Re, Q1Im, Q2Re, Q2Im []float32
	C0, C1, C2                                       []float32
}

AllPassRows32 holds the constants of the rows of a layout: Phi the rotation of the pre-delay, Q_l the rotation of link l (each as two planes), C_l its real coefficient.

type PSMixPlan32 added in v0.44.0

type PSMixPlan32 struct {
	// contains filtered or unexported fields
}

PSMixPlan32 is a list of runs proved once, for Run. It is immutable and may be shared by goroutines, as long as the planes they pass are not.

func NewPSMixPlan32 added in v0.44.0

func NewPSMixPlan32(runs []PSMixRun, nBands int) (*PSMixPlan32, error)

NewPSMixPlan32 checks the runs for nBands bands and returns the plan. It returns an error, and no plan, if there is no run, nBands is not positive, a run is empty or negative, has a band outside [0, nBands) or a source outside [0, 3), or starts before the end of the run that precedes it (the runs must be in increasing row order and must not overlap), or a row number is 2^30 or more.

func (*PSMixPlan32) Run added in v0.44.0

func (p *PSMixPlan32) Run(gains, tg []float32, s Split32, d *[3]Split32, l, r Split32)

Run mixes the runs of the plan: gains holds four values per band (gLs, gLd, gRs, gRd of band b at 4b..4b+3), tg one transient gain per band, s the mono rows, d the three decorrelated sources and l and r the outputs. It panics if gains or tg is shorter than the plan's bands need, or a plane shorter than maxEnd+7 elements (a source that no run uses may be empty).

func (*PSMixPlan32) Runs added in v0.44.0

func (p *PSMixPlan32) Runs() int

Runs is the number of runs of the plan.

type PSMixRun added in v0.44.0

type PSMixRun struct{ Start, End, Band, Src int }

PSMixRun is rows [Start, End) of a slot that share the gains of parameter band Band and the decorrelated signal of source Src (0, 1 or 2).

type Split32 added in v0.43.0

type Split32 struct{ Re, Im []float32 }

Split32 is a complex slice in two float32 planes: element k is complex(Re[k], Im[k]).

Directories

Path Synopsis
bench
numpycmp module
perf module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址