DEM Audiocaroli Documentation
APIGitHub

Reduced Precision and the GPU


On this page

Everything in caroli is computed in double precision by default. Three kinds of calculation can run in less, at the user's request, because they are bound by memory traffic or by dense arithmetic that single precision halves: the fronts of nested dissection on the CPU, the Chebyshev expansions (kernel polynomial moments, time propagation) on the GPU, and the quantum walks on either. None of them is trusted blindly: the checked entry points recompute a sample of the work in f64, measure the difference, report it, and fall back to double precision when it exceeds a tolerance the user sets. This page describes what runs in reduced precision, the arithmetic, the checks, and the speed and accuracy measured; read it before choosing anything but the default.

Apple's GPUs have no f64 arithmetic. On them caroli offers f32, about \(10^{-6}\) relative, and double-single, an unevaluated sum of two f32, about \(10^{-14}\) relative. The CUDA backend runs in f64.


Transport in single precision

What runs in f32

caroli_green's Precision is Double (the default) or Single, an experimental option for previews. With Single, the nested-dissection solvers (Nested dissection) eliminate every front below the root in complex f32, through the Field trait of Dense linear algebra: Accelerate's cgetrf, cgetrs and cgemm on macOS, faer elsewhere. A front is assembled in f32 from the Hamiltonian and the energy, and its Schur complement \(S = F_{22} - F_{21} F_{11}^{-1} F_{12}\) is handed to its parent in f32.

What stays in f64:

  • the lead self-energies, computed by mode matching (Lead modes) in double precision;
  • the root of the elimination: the children's Schur complements are converted to f64 there, and the root front, with the lead slices, the variables delayed up to it and the final solve that gives \(G_{LR}\), is assembled and solved in f64;
  • the Caroli trace \(T = \mathrm{Tr}\,[\Gamma_L G_{LR} \Gamma_R G_{LR}^{\dagger}]\).

A separator block whose LU has a pivot below \(10^{-5}\) times its largest entry is numerically singular in f32 and is delayed to the parent front, as in double precision with the threshold \(10^{-11}\).

Checked runs

checked runs a batch of points (energies, disorder configurations) in the precision of PrecisionOptions and checks it against double precision:

  1. Every point runs in the chosen precision, in parallel.
  2. One point in every (indices \(0, k, 2k, \dots\) for every \(= k\), so at least one) is recomputed in f64, and so is every point that failed in reduced precision. The distance between the two values of a point is measured by a function the caller gives: \(\lvert T_{32} - T_{64} \rvert\) for transmissions.
  3. If the largest distance exceeds the tolerance, or a point failed in f64 only (a NaN distance), the whole batch is recomputed in f64.
  4. The checked points return their f64 values either way.

PrecisionOptions::single() recomputes one point in fifty and accepts differences up to \(10^{-2}\). NestedTwoTerminal::transmissions_checked applies this to a list of energies; transmission_with_precision (two terminals) and transmissions_with_precision (many terminals) run one point unchecked. The PrecisionReport gives the precision of the results returned (Double after a fallback), the number of points checked, the median and the largest difference among them, the number of points that failed in f32, and why the batch was recomputed if it was.

The check samples the batch; it does not bound every point. A point between two samples can differ by more than the tolerance without being seen, which the tails below make likely in wide samples.

Speed

A front's Schur step is 2.7 to 3.7 times faster in f32 (fronts of 128 to 2048 variables, M5). The whole solve gains less: the small fronts, the assembly, the root and the lead modes do not speed up. On the benchmark problems, one thread, M5 (ARCHITECTURE.md, item 12):

Problemf64f32GainLargest \(\lvert \Delta T \rvert\)
Square lattice, disorder, \(W = 256\)67.7 ms45.2 ms1.50×\(4.9 \cdot 10^{-3}\)
Square lattice, disorder, \(W = 512\)373 ms241 ms1.55×0.13
Long strip, \(W = 128\)178 ms113 ms1.57×\(3.6 \cdot 10^{-2}\)
Four-terminal cross, \(W = 256\)216 ms150 ms1.44×0.46
BHZ, \(W = 256\)2.91 s2.69 s1.08×\(2.2 \cdot 10^{-2}\)
Graphene, \(W = 256\)303 ms259 ms1.17×\(1.4 \cdot 10^{-2}\)

BHZ and graphene spend most of their time on the lead modes, always in f64. On all the threads the gain is 1.4 to 1.9.

Accuracy

On the spin blocks of the BHZ ribbons of the thesis conductance maps (examples/nd_precision.rs of caroli-validation: disordered samples of length 256, same-g and opposite-g impurities, 6 energies per disorder strength), the difference \(\lvert T_{32} - T_{64} \rvert\) per block, and the gain on all the threads:

\(W\)Median99 %LargestLargest on the plateausGain
64\(1.4 \cdot 10^{-5}\)\(9.0 \cdot 10^{-3}\)\(3.2 \cdot 10^{-2}\)\(3.7 \cdot 10^{-3}\)1.7–1.8×
128\(1.8 \cdot 10^{-5}\)\(2.7 \cdot 10^{-2}\)\(6.2 \cdot 10^{-2}\)\(8.2 \cdot 10^{-3}\)1.9×
256\(3.5 \cdot 10^{-5}\)\(3.2 \cdot 10^{-1}\)\(3.7 \cdot 10^{-1}\)\(7.2 \cdot 10^{-3}\)1.4–1.8×

The median stays near \(10^{-5}\), a few hundred times the rounding unit of f32. The largest errors grow with the width and reach 0.4 at \(W = 256\).

Why the errors have tails

Nested dissection eliminates closed subdomains of the device at a real energy \(E\): the separator block \(F_{11}\) of a front comes from the resolvent matrix \(E - H_D\) of a piece \(D\) of the sample with no lead attached, and it becomes singular when \(E\) crosses an eigenvalue of \(H_D\). The relative error of a solve with a matrix of condition number \(\kappa\) is of order \(\kappa u\), with \(u\) the rounding unit: \(u = 6 \cdot 10^{-8}\) in f32, \(1.1 \cdot 10^{-16}\) in f64. Within \(\delta\) of an eigenvalue, \(\kappa\) is of the order of the bandwidth over \(\delta\). Most energies are far from every eigenvalue of every front, and the error stays at the median; a few fall close to one, and the f32 Schur complement of that front keeps too few digits. The more fronts a sample has, the more such near-coincidences, hence the tails that grow with \(W\). In f64 the same \(\kappa\) costs \(5 \cdot 10^8\) times less.

The pivot test catches the worst blocks: a pivot below \(\tau\) times the largest entry signals a condition number of order \(1/\tau\) or more, and the block is delayed to a larger front. A stricter test restores much of the accuracy, a largest \(\lvert \Delta T \rvert\) of \(8.5 \cdot 10^{-3}\) at \(W = 64\) with \(\tau = 10^{-3}\), but the delayed variables pile up towards the root, which grows and runs in f64. The same-g ribbon then runs slower than in double precision: 1.4 times at \(W = 128\) with \(\tau = 10^{-3}\), 3 times at \(W = 256\) with \(\tau = 3 \cdot 10^{-4}\). The f32 threshold stays at \(10^{-5}\), where f32 is never slower than f64.

What was tried and left out

  • The recursive Green's function in f32 (examples/rgf_precision.rs) is more accurate: a largest \(\lvert \Delta T \rvert\) of \(1.0 \cdot 10^{-2}\) at \(W = 64\) and \(2.5 \cdot 10^{-2}\) at \(W = 128\), \(2.4 \cdot 10^{-4}\) on the plateaus at \(W = 64\); one step of refinement of each inversion, \(X \leftarrow X + X(1 - AX)\) with the residual in f64, brings the error to about \(10^{-4}\). Its sweep costs \(O(L W^3)\) against \(O(L W^2)\) for nested dissection, so it is not offered.
  • Mixed precision, f32 inversions refined with an f64 residual, was designed for a GPU without f64. On a CPU the products of the Schur updates, which dominate, would have to stay in f64 for the refinement to help, which leaves almost no gain.
  • Dense transport on the GPU. Measured on an M5: f32 products on the GPU (Metal Performance Shaders, each complex matrix embedded as a real one of twice the size) are 4 times faster than Accelerate's f64 complex products from \(n = 1024\) up, and the LU 1.6 times at \(n = 1024\) and 3 to 5 times from \(n = 2048\); below \(n = 512\) there is no gain. Only the top fronts of the largest samples are that large, so the gain would be about 2 on those, with the f32 errors above. It is not implemented: a CUDA card with fast f64 is the better target for transport.

The GPU kernels

caroli-gpu runs the Chebyshev recursions that dominate the spectral and dynamical methods on a sparse Hamiltonian, rescaled into \((-1, 1)\) as in Conventions: \(\tilde H = (H - e_0)/\Delta E\).

Kernel polynomial moments

The moments \(\mu_n = g_n \cdot \overline{\langle r \rvert T_n(\tilde H) \lvert r \rangle}\), averaged over the start vectors \(r\) and damped by the kernel \(g_n\) (Kernel polynomial method), come from the recursion

$$ \lvert t_0 \rangle = \lvert r \rangle, \qquad \lvert t_1 \rangle = \tilde H \lvert r \rangle, \qquad \lvert t_{n+1} \rangle = 2 \tilde H \lvert t_n \rangle - \lvert t_{n-1} \rangle, $$

with \(\lvert t_n \rangle = T_n(\tilde H) \lvert r \rangle\). Since \(T_m T_n = (T_{m+n} + T_{\lvert m - n \rvert})/2\) and \(\tilde H\) is Hermitian, two moments come from each vector:

$$ \mu_{2n} = 2 \langle t_n \vert t_n \rangle - \mu_0, \qquad \mu_{2n+1} = 2 \langle t_n \vert t_{n+1} \rangle - \mu_1, $$

before the kernel is applied: \(N\) moments take \(N/2\) products with \(\tilde H\), as in caroli_kpm::block_moments on the CPU.

Each step is one fused kernel, kpm_step: it computes \(\lvert t_{n+1} \rangle\) and, in the same pass, each threadgroup's share of \(\langle t_n \vert t_n \rangle\) and \(\langle t_n \vert t_{n+1} \rangle\). A second kernel, reduce_partials, adds the shares of all the threadgroups in a fixed order, in double-single whatever the precision of the vectors (in f64 on CUDA). A whole expansion runs on the GPU; only the sums come back.

Time propagation

A step of the propagation \(\psi(t + \delta t) = e^{-iH\delta t} \psi(t)\) is the Chebyshev series of Time evolution,

$$ e^{-iH\delta t} = e^{-i e_0 \delta t} \sum_{k=0}^{K} (2 - \delta_{k0})\, (-i)^k J_k(\Delta E\, \delta t)\, T_k(\tilde H), $$

truncated where the Bessel functions \(J_k\) fall below a tolerance. propagate_init sets the accumulator to \(c_0 \psi\); each propagate_step computes the next \(T_k(\tilde H)\psi\) and adds \(c_k T_k(\tilde H)\psi\) to the accumulator in the same pass. At the end of a step the accumulator becomes the next \(\psi\): the state stays on the GPU for the whole run, and only the final state comes back.

Layout

  • The Hamiltonian is a CSR matrix (row pointers, columns, values) uploaded once, with 32-bit indices.
  • Several vectors go through each step together (the random vectors of a stochastic trace, several wave packets), stored interleaved: entry \(i\) of vector \(v\) at \(i \cdot m + v\) for \(m\) vectors.
  • One thread per entry, 256 threads per threadgroup. The threads of a row are neighbours, so they read the row of the matrix together.
  • On Metal, the dispatches are encoded 256 per command buffer and the CPU waits for the last; the buffers are in memory shared with the CPU, which reads the results without a copy.

Metal: f32 and double-single

The Metal kernels, instantiated for f32 and for double-single, are compiled from source when the device is opened, without fast math (MTLMathMode::Safe): the double-single arithmetic needs exact IEEE rounding and fused multiply-adds.

A double-single number is an unevaluated sum \(x = x_h + x_l\) of two f32, \(x_l\) holding the bits of \(x\) that \(x_h\) cannot. With 24 bits each, the pair carries about 48 bits, a rounding unit of \(2^{-48} \approx 3.6 \cdot 10^{-15}\), in the exponent range of f32 (values below about \(10^{-31}\) lose digits, as \(x_l\) becomes subnormal). An f64 enters as \(x_h = \mathrm{fl}_{32}(x)\), \(x_l = \mathrm{fl}_{32}(x - x_h)\), and comes back as \(x_h + x_l\) in f64.

The arithmetic rests on three error-free transformations, which return a rounded result and its exact rounding error, with \(\mathrm{fl}\) the f32 rounding of each operation:

$$ \mathrm{TwoSum}(a, b):\quad s = \mathrm{fl}(a + b),\quad v = \mathrm{fl}(s - a),\quad e = \mathrm{fl}\big(\mathrm{fl}(a - \mathrm{fl}(s - v)) + \mathrm{fl}(b - v)\big), \qquad s + e = a + b, $$

$$ \mathrm{FastTwoSum}(a, b):\quad s = \mathrm{fl}(a + b),\quad e = \mathrm{fl}\big(b - \mathrm{fl}(s - a)\big), \qquad s + e = a + b \quad \text{if } \lvert a \rvert \ge \lvert b \rvert, $$

$$ \mathrm{TwoProd}(a, b):\quad p = \mathrm{fl}(ab),\quad e = \mathrm{fma}(a, b, -p), \qquad p + e = ab . $$

The sum of \(x\) and \(y\) adds the high parts and the low parts each with TwoSum, folds the error of the first into the second, and renormalises twice with FastTwoSum, so that the result is again a non-overlapping pair. The product takes TwoProd of the high parts, adds the cross terms \(x_h y_l + x_l y_h\) to its error with two fused multiply-adds, and renormalises; the term \(x_l y_l\), of relative size \(2^{-48}\), is dropped. A double-single product costs seven f32 operations and a sum twenty, and each real number moves 8 bytes, as in f64. Complex numbers are pairs of either type.

PrecisionRelative accuracyBytes per complex numberTests (\(\max \lvert \Delta\mu_n \rvert / \mu_0\), \(\lVert \Delta\psi \rVert\))
f32 (Precision::Single)about \(10^{-6}\)8below \(10^{-4}\)
Double-single (Precision::DoubleSingle)about \(10^{-14}\)16below \(10^{-11}\)
f64 (CUDA)\(10^{-16}\)16below \(10^{-12}\)

The tests (tests/metal.rs, tests/cuda.rs of caroli-gpu) compare with the f64 CPU code on a disordered BHZ torus (Anderson disorder of width 2, \(\lambda = 0.1\)): 400 Jackson-damped moments from three random-phase vectors on a \(24 \times 24\) torus, and 20 propagation steps of \(\delta t = 0.5\) for two interleaved copies of a wave packet on a \(16 \times 16\) torus. They are skipped where there is no device.

CUDA: f64

With the cuda feature, the same kernels, written in CUDA C, are compiled at run time by NVRTC, and the CUDA driver and NVRTC are loaded when the device is opened: building needs no CUDA toolkit, running needs an NVIDIA driver. The algorithms and the layout are those of the Metal kernels, in f64 throughout. CudaDevice::new checks that both libraries are present before touching them, since the loader would otherwise abort the process. The backend compiles and passes Clippy in the CI, but it has not yet been run on NVIDIA hardware.

Runs checked against the CPU

caroli_gpu::Options chooses the Device, the CPU (f64) or the GPU in a Precision, and the largest relative error accepted, measured against the CPU on a sample of the work. Options::exploration() is f32 with \(10^{-3}\), Options::accurate() double-single with \(10^{-9}\), Options::cpu() the CPU. Every run returns a Report: where it ran, the deviation measured (scaled to the whole run where it grows with it), and why the CPU took over if it did.

CalculationCheckFallback
KPM moments, caroli_kpm::accelerated::moments (used by Spectrum::device)The GPU computes the moments of every start vector. One vector in fifty, evenly spaced, at least one, is recomputed in f64 on the CPU and alone on the GPU; the deviation is \(\max_n \lvert \mu_n^{\mathrm{GPU}} - \mu_n^{\mathrm{CPU}} \rvert / \lvert \mu_0^{\mathrm{CPU}} \rvert\)Above the tolerance, for a NaN, or if the GPU fails: the CPU computes everything
Propagation, caroli_dynamics::accelerated::propagateCalibration: the first 2 % of the steps (1 to 50) on the CPU in f64 and on the GPU from the same state; their distance relative to \(\lVert \psi \rVert\), scaled linearly to the whole run, predicts the final error. Then the norm of every wave function at the endA predicted error above the tolerance: the CPU does the rest. A norm drift above it, or a GPU failure: the CPU redoes the whole run
Quantum walk, caroli_walk::gpu::evolveThe same calibration (1 to 200 steps), then \(\lVert \psi \rVert^2\) summed in f64 at every checkpointf32 gives way to double-single, then to the CPU; a drift sends the run back to the CPU from the last good checkpoint (Quantum walks)

The linear scaling of a calibration is an estimate from above when the error of each step stays the same. The evolution is unitary, so an error made at one step is carried forward without growing: after \(t\) steps the errors add up to at most \(t\) times that of one step, and to about \(\sqrt t\) times when they are uncorrelated. The calibration also keeps its CPU steps: the GPU continues from the exact state.

With a single start vector, the KPM check costs a full CPU run: for a local density of states, the sites should go through as a batch of start vectors.

The tests of caroli-kpm and caroli-dynamics assert, on a Mac with a GPU: double-single within \(10^{-10}\) of the CPU for 256 moments of 60 random vectors on a ring of 4096 sites, and for 100 propagation steps of two wave packets on a ring of 2048 sites; f32 within \(10^{-4}\) and \(10^{-3}\) with the exploration tolerance; an impossible tolerance sends the run back to the CPU, which returns the exact result. Without a GPU they check that the run falls back to the CPU.

What the GPU of Apple silicon brings

WorkloadMeasuredWhy
KPM moments, a torus of a million orbitals (M5)4 times faster than 10 CPU cores in f32, 2 times in double-singlef32 halves the memory traffic; at the traffic of f64 (double-single), the GPU still runs these sparse products twice as fast as the CPU cores
Quantum walk, ring of 19 nodes (M4 Pro)2.5 ms per step in f32 on the GPU and on 14 CPU threads, 5.3 ms in double-single on the GPU and in f64 on the CPUBound by memory: the CPU and the GPU share the same memory and reach the same bandwidth, about 230 GB/s on the M4 Pro; what halves the time is f32, on either
Quantum walks small enough for the GPU's cache (\(n \le 15\))The GPU 2 to 4 times faster than the CPU in f32The state stays in the cache
Dense transport (fronts, lead modes)Not on the GPUOnly the largest fronts would gain, about 2 times in f32 with the f32 errors above; a GPU with fast f64 is the better target
Operators through FFTs on toriNot on the GPU

The numbers are those of ARCHITECTURE.md and of the quantum walk benchmark (Validation and benchmarks).

Unsafe code

The calls into Metal (Objective-C, through the objc2 crates) and into the CUDA driver are unsafe by nature. Three modules of caroli-gpu hold them, metal, metal_walk (macOS) and cuda (feature cuda); they are the only ones allowed unsafe against the workspace's unsafe_code = "deny", and each of their unsafe blocks, 24 in all, says in a SAFETY comment why it is sound:

  • a buffer created from a slice: the pointer is valid for its length, and Metal copies the bytes before returning;
  • the arguments bound to a kernel: they are the buffers and parameters the kernel expects, and the buffers outlive the command buffer (bind is itself an unsafe fn with that contract);
  • a shared buffer read as a slice: it holds that many numbers, written by commands that have completed; or written through &mut self, so that no command is running;
  • a CUDA launch: the arguments match the kernel's signature and its indices stay within the buffers; the library checks only try to open a shared library.

The workspace lint clippy::undocumented_unsafe_blocks flags a block without a reason. The CI runs Clippy on macOS, where the Metal modules exist, and on Linux with the cuda feature, with warnings as errors. The quantum-walk kernels on the CPU, the scans and the checked runs are safe Rust.

In the code

ItemWhat it does
Precision, PrecisionOptions, PrecisionReport, checkedTransport fronts in f32, checked batches (caroli_green)
NestedTwoTerminal::transmissions_checked, transmission_with_precision, NestedMultiTerminal::transmissions_with_precisionThe solvers' entries in reduced precision
Fieldc64 and c32 for the eliminations (caroli_dense)
MetalDevice, MetalOperator (kpm_moments, propagate)Metal kernels, f32 or double-single (macOS)
CudaDevice, CudaOperatorCUDA kernels, f64 (feature cuda)
caroli_gpu::Precision, Device, Options, Report, GpuErrorChoice of device and precision, report of a checked run
caroli_kpm::accelerated::moments, caroli_dynamics::accelerated::propagate, caroli_walk::gpu::evolveChecked runs

The timing example of the KPM kernels is examples/bench.rs in caroli-gpu; those of transport in single precision are nd_precision and rgf_precision in caroli-validation.

References

  • T. J. Dekker, A floating-point technique for extending the available precision, Numer. Math. 18, 224 (1971). Double-length arithmetic from pairs of floating-point numbers, FastTwoSum.
  • D. E. Knuth, The Art of Computer Programming, vol. 2, Seminumerical Algorithms, 3rd ed., Addison-Wesley, 1997, § 4.2.2. TwoSum.
  • Y. Hida, X. S. Li, D. H. Bailey, Algorithms for quad-double precision floating point arithmetic, Proc. 15th IEEE Symposium on Computer Arithmetic, 155 (2001). The double-double addition and multiplication followed by the double-single kernels.
  • A. Weiße, G. Wellein, A. Alvermann, H. Fehske, The kernel polynomial method, Rev. Mod. Phys. 78, 275 (2006). Chebyshev moments, their doubling relations, the Jackson kernel.
  • H. Tal-Ezer, R. Kosloff, An accurate and efficient scheme for propagating the time dependent Schrödinger equation, J. Chem. Phys. 81, 3967 (1984). The Chebyshev propagator.