Exact similarity search
Vector search that returns the exact ranking. Use SimilarityIndex(keys, metric="cross", exact=True) on int8 or int16 vectors for retrieval; see Exact vector search for RAG.
similarity_topk(queries, keys, k, metric="cosine", exact=False, eps=1e-08) -> (values, indices)For each query ([D] or [B, D]), the k rows of keys ([N, D]) most similar to it, scored and selected in one pass, so the [B, N] score matrix is never stored.
metric is "cosine", "cross" (the signed cross, sign(q·x) (q·x)² / (Q(q) Q(x)) with Q(x) = x·x: the same ranking as cosine), "spread" (1 − (q·x)² / (Q(q) Q(x)), smallest first) or "dot".
With exact=True the vectors must hold whole numbers (int8 or int16 tensors, or float32 tensors holding whole numbers in that range). The dot products are computed in integers and the ranking is decided by comparing exact fractions, so the result is exact: the same top-k on every CPU and GPU, at every batch size. Ties go to the lowest index. The returned values are recomputed in float64 from the vectors.
Returns (values, indices), like torch.topk. See the guide Exact vector search for RAG.
SimilarityIndex(keys, metric="cosine", exact=False, eps=1e-08)Stored vectors ([N, D]) prepared once for repeated searches. index.search(queries, k) returns (values, indices) exactly as similarity_topk does.
With exact=False the keys are kept as float32 rows on the device that searches them, together with each key's norm. With exact=True the keys must be whole numbers (int8 or int16) and each key's quadrance Q(x) = x·x is stored exactly, so every search is exact.
SimilarityIndex(keys, metric="cross", exact=True) is the recommended exact retrieval index; len(index) is the number of stored vectors.
cross_similarity(x1, x2, dim=1, eps=1e-08) -> TensorThe signed cross sign(u·v) (u·v)² / (Q(u) Q(v)): 1 − spread with the sign of u·v, in [−1, 1]. It is cos θ · |cos θ|, so it ranks pairs exactly as cosine similarity does, and it needs only dot products.
spread(x1, x2, dim=1, eps=1e-08) -> TensorThe spread between vectors along dim: 1 − (u·v)² / (Q(u) Q(v)), where Q(u) = u·u: 0 for parallel vectors (pointing the same way or opposite ways), 1 for perpendicular ones. Computed from dot products alone, so whole-number inputs give an exact fraction.
quadrance(x, dim=-1, keepdim=False)Q(x) = x. x along dim (the squared length).
Riptorch extra: not in stock PyTorch.
spread(u, v, dim=-1, keepdim=False)The spread between vectors u and v: 1 - (u. v)^2 / (Q(u) Q(v)) (rational).
Riptorch extra: not in stock PyTorch.
Settings
Switches that change how results are computed. Each one also has an environment variable (below) that sets it at import.
set_compat(mode)Riptorch's results are correct by default: int8 @ int8 gives exact int32, int16 @ int16 exact int64, int32 and int64 products exact int64, and the other measured improvements listed by torch.improvements().
set_compat("pytorch") (or RIPTORCH_COMPAT=pytorch before import) gives stock PyTorch's behaviour instead: integer products keep the input dtype and wrap modulo 2^bits, int8 @ uint8 raises, float64 runs on the CPU. set_compat("riptorch") returns to the default.
get_compat() -> str"riptorch" (the correct-by-default behaviour) or "pytorch" (stock behaviour), as set_compat set it.
set_matmul(precision)Sets how floating-point matrix multiplies are computed (matmul, linear, convolutions and the attention backward):
"fp32"(default): float32 inputs and float32 accumulation on the fastest hardware, with fused multiply-adds."bf16"or"fp16": mixed precision. Each multiply rounds its inputs to 16 bits and accumulates in float32; weights, gradients and optimizer state stay float32."exact": the unfused reference order (multiply, then add, in a fixed order), so results are the same bits run to run.- On the Apple GPU, also
"fast"(scaled half-precision multiplies that never overflow) and"high"(about twice float32's accuracy at about float32's speed).
RIPTORCH_MATMUL sets it at import. Compiled programs are cached per precision, so you can change it between training steps. See Matmul precision and speed settings.
get_matmul() -> strThe precision set_matmul chose: "fp32" (default), "bf16", "fp16", "exact", "fast" or "high".
set_int_matmul(device)Where exact integer matrix multiplies (int8, uint8, int16 and uint16, in any same-width pair) run:
"auto"(default): the GPU's int8 matrix hardware for large products (from 2²⁴ multiply-adds for 8-bit inputs and 2²⁵ for 16-bit), the CPU's matrix unit below that."gpu"or"cpu": always that side.
The results are the same exact integers either way. RIPTORCH_INT_MATMUL sets it at import.
get_int_matmul() -> strWhere exact integer matmuls run: "auto" (default), "gpu" or "cpu".
set_float64(mode=None, min_work=None)Where float64 work runs on a Mac with an Apple GPU (which has no float64 hardware):
"auto"(default): IEEE float64 on the CPU, unless every operation in a graph is as precise on the GPU."fast": the GPU wherever it is measured faster, using double-float arithmetic (two float32 values per number, about 48 significant bits)."gpu": the GPU whenever the graph can run there."cpu": IEEE float64 on the CPU (PyTorch's behaviour;set_compat("pytorch")also gives it).
min_work is the smallest graph sent to the GPU. A value outside 2⁻⁷⁴ … 2¹⁰⁰ reruns the graph on the CPU in every mode. RIPTORCH_FLOAT64 and RIPTORCH_FLOAT64_MIN_WORK set them at import.
get_float64() -> strWhere float64 graphs run now: "auto", "gpu", "cpu" or "fast".
set_maths(mode=None, *, weight=None, attention=None, loss=None, recenter=None, temperature=None, cayley_eps=None)Chooses the model maths for experiments. "classic" (default, also called "transcendental") is PyTorch's: the exponential softmax, cross-entropy, layer norm, GELU, tanh, sigmoid, Adam and norm clipping.
"rational" keeps every map to order 2 or below: second-order softmax weightings, the Brier score, spread norm, ReLU², softsign, Lion and quadrance clipping. The keyword arguments set one piece at a time: weight (the softmax's weighting map: "exp", "taylor2", "cayley", "square_linear" or "relu_square"), attention, loss ("cross_entropy", "brier" or "spherical"), recenter, temperature and cayley_eps.
Set it before building a model's training step. RIPTORCH_MATHS=rational sets it at import.
get_maths() -> strThe model maths set_maths chose: "transcendental" (the default) or "rational".
maths_config() -> dictThe current set_maths settings as a dict.
Checking where your model runs
What ran where, which matrix unit this machine has, and every default that differs from stock PyTorch.
backend() -> strNames the engine that runs large operations: the Metal GPU on a Mac with one (for example "riptide metal (Apple M1 Pro)"), otherwise "cpu".
matrix_unit() -> strThe CPU matrix unit Riptorch's CPU matrix multiplies run on: "SME" on Apple M4 and later, "AMX" on M1 to M3, "none" elsewhere (the portable kernels).
matrix_unit_modes() -> list[str]The matrix-multiply input and output types this CPU runs on its matrix unit, using all cores, for example "s8s8_i32" (int8 × int8 → int32), "s16s16_i64", "f16_f32" or "bf16_f32".
matrix_unit_status() -> dictThe matrix unit, its modes and whether its library loaded, as one dict (for bug reports).
realizer_report() -> strWhere this process's work ran: how many GPU programs and CPU programs, and for each graph that did not run on the GPU, why (for example a small graph where a GPU round trip costs more, or float64). Use it to check that a model runs where you expect after switching.
improvements(name=None, vs=None) -> list | dict | NoneEvery function whose Riptorch default differs from stock PyTorch's because PyTorch's result is wrong or degraded, each as a dict with the measurement behind it: name, area, headline, stock (what PyTorch does), riptorch (what Riptorch does), measured, and compat (how to get PyTorch's behaviour back).
improvements("index_add") returns one entry (or None when the function behaves as stock); vs="pytorch" or vs="mlx" keeps the entries measured against that library.
is_torch_alias() -> boolTrue when import torch in this process gives Riptorch (Riptorch was imported first and registered itself under that name).
program_stats() -> tupleCounts for the last program that ran (its steps) and how many graphs ran so far: a diagnostic for performance reports.
interpreter_stats() -> tuple(graphs, seconds): how many graphs the CPU reference interpreter ran in this process and the time spent there (normally 0).
torch.compile
torch.compile takes the same arguments as PyTorch’s, so existing code runs. Its behaviour is different.
compile(model=None, *, fullgraph=False, dynamic=None, backend="inductor", mode=None, options=None, disable=False)Accepts torch.compile's arguments. A function is recorded once and replayed on later calls; a module comes back wrapped and runs eagerly (its _orig_mod is the module); disable=True returns the input unchanged. Riptorch builds and caches its own programs for every graph, compiled or not, so eager code is already compiled underneath.
Different from PyTorch: records a function once and replays it; a module runs eagerly (Riptorch compiles every graph anyway).
Environment variables
Set these before import riptorch. You don’t need any of them for normal use. Riptorch’s sources read 89 RIPTORCH_* names; the 26 below are the ones meant for users. The other 63 are internal switches for Riptorch’s own tests and benchmarks and can change without notice.
Results and precision
| Variable | Values | What it does |
|---|---|---|
RIPTORCH_COMPAT | pytorch | Stock PyTorch's behaviour everywhere, the same as torch.set_compat("pytorch"). Unset (or riptorch) keeps the correct-by-default results. |
RIPTORCH_MATMUL | fp32 (default), bf16, fp16, exact; on the Apple GPU also fast, high | Floating-point matrix multiply precision, the same as torch.set_matmul(...). |
RIPTORCH_INT_MATMUL | auto (default), gpu, cpu | Where exact integer matrix multiplies run, the same as torch.set_int_matmul(...). |
RIPTORCH_FLOAT64 | auto (default), fast, gpu, cpu | Where float64 work runs on a Mac, the same as torch.set_float64(...). |
RIPTORCH_FLOAT64_MIN_WORK | a number of operations | The smallest float64 graph set_float64 sends to the GPU. |
RIPTORCH_LA_METHOD | auto (default), f64, mixed, f32 | For testing: how float32 linear algebra is computed: a measured table, in float64 rounded once, float32 LU refined in float64, or stock-style float32. Float64 inputs always use float64. |
Devices and speed
| Variable | Values | What it does |
|---|---|---|
RIPTORCH_DEVICE | unset or auto, cpu, gpu (also metal, mps), amd | Where work runs. Unset picks the GPU when there is a usable one and falls back to the CPU with one line of explanation. cpu runs everything on the CPU. gpu asks for the Apple GPU by name and raises an error if there isn't a usable one. amd uses an AMD Instinct GPU on Linux. |
RIPTORCH_HYBRID | 1 | Apple silicon: splits a large float32, bfloat16 or float16 matrix multiply between the GPU and the CPU's matrix unit at the same time, on the same memory. Never used for exact results (the two sides' bits differ), batches or a transposed first operand. |
RIPTORCH_HYBRID_SHARE | a fraction, default 0.22 | With RIPTORCH_HYBRID=1: the share of the output rows the CPU computes (the last rows) while the GPU computes the rest. |
RIPTORCH_HYBRID_MIN | multiply-adds, default 2³⁰ | With RIPTORCH_HYBRID=1: the smallest product that is split. |
RIPTORCH_NUM_THREADS | a number | CPU threads for Riptorch's CPU kernels. Default: OMP_NUM_THREADS if set, else the performance cores (Apple silicon) or the physical cores this process may use. |
RIPTORCH_CPU_CACHE_DIR | a directory | Where compiled CPU programs are cached between runs (default: the user cache directory). |
RIPTORCH_CPU_CACHE_MB | megabytes, default 512 | The size cap of that cache; the least recently used programs are removed above it. 0 keeps nothing on disk. |
RIPTORCH_CPU_LEVEL | x86-64-v2, x86-64-v3, x86-64-v4 | Linux and Windows on x86-64: which build of the CPU library to load. By default the best one this processor supports (AVX2 or AVX-512) is picked automatically. |
RIPTORCH_CPU_OFF | a comma list of sme, amx, i8mm, bf16 | For testing: CPU features to treat as absent, so an M4 or M5 runs the way an M1 would. |
Model maths (experiments)
| Variable | Values | What it does |
|---|---|---|
RIPTORCH_MATHS | rational | Order-2 model maths for supported operations, the same as torch.set_maths("rational"). |
RIPTORCH_WEIGHT | exp, taylor2, cayley, square_linear, relu_square | The softmax weighting map (set_maths(weight=...)). |
RIPTORCH_ATTENTION | as RIPTORCH_WEIGHT | The weighting map attention uses (set_maths(attention=...)). |
RIPTORCH_LOSS | cross_entropy, brier, spherical | What F.cross_entropy computes (set_maths(loss=...)). |
RIPTORCH_RECENTER | 1 | Subtract each row's mean logit before the weighting map (set_maths(recenter=True)). |
RIPTORCH_TEMPERATURE | a number, learned, learned_inv | The softmax temperature (set_maths(temperature=...)). |
RIPTORCH_CAYLEY_EPS | a number, default 1/32 | The clamp of the Cayley weighting map (set_maths(cayley_eps=...)). |
Loading, errors and profiling
| Variable | Values | What it does |
|---|---|---|
RIPTORCH_FORCE_WEIGHTS_ONLY_LOAD | 1 | torch.load always uses weights_only=True (as TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 does in PyTorch). |
RIPTORCH_LOOPS_STRICT | 1 | Raises an error, instead of one warning and a slower Python fallback, if Riptorch's compiled kernels for special functions (lgamma, the Bessel functions, cummax and others) can't load. |
RIPTORCH_PROFILE | 1 | Prints a timing line for every realised graph (build, compile and run). |
RIPTORCH_TRACE_ERRORS | 1 | Errors raised inside Riptorch's engine carry its full stack trace (for bug reports). |
Every default that differs from PyTorch
Riptorch is correct by default. Where stock PyTorch gives a wrong or degraded result, Riptorch gives the correct one, and each case below was measured. torch.improvements() returns the same 52 entries at run time, and torch.set_compat("pytorch") brings back stock behaviour where it can be reproduced.
Distributions
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.distributions.Kumaraswamy.mode | returns the mode ((a - 1) / (a b - 1))^(1 / a); PyTorch returns nan for every distribution that has one | torch.set_compat("pytorch") |
Fx
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.fx.Graph.print_tabular | prints the node table without the tabulate package; PyTorch 2.15 raises ModuleNotFoundError here | torch.set_compat("pytorch") |
Indexing
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.index_add | repeated indices summed in float64 and rounded once: [1e8, 1, -1e8] at one index gives 1.0, PyTorch's float32 sum gives 0.0 | torch.set_compat("pytorch") |
torch.index_put | accumulate=True sums repeated positions in float64 and rounds once: [1e8, 1, -1e8] at one position gives 1.0, PyTorch gives 0.0 | torch.set_compat("pytorch") |
Linalg
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.linalg.det | exact integer determinants (Bareiss); PyTorch refuses integer input, and for [[1e9, 1e9+1], [1e9+1, 1e9+2]] PyTorch float64 gives -84.7 and MLX float64 gives 0.0 where the answer is -1 | torch.set_compat("pytorch") |
torch.linalg.inv | exact inverses of integer matrices (a FractionTensor); PyTorch and MLX refuse integer input, and PyTorch's float64 inverse of the 12x12 Hilbert matrix is off by 3.4e-2 | torch.set_compat("pytorch") |
torch.linalg.solve | exact solutions for integer systems (a FractionTensor); PyTorch and MLX refuse integer input, and PyTorch's float64 solve on the 12x12 Hilbert matrix is off by 5.8e-2 | torch.set_compat("pytorch") |
torch.linalg.matrix_rank | exact rank of integer matrices; MLX has no matrix_rank; PyTorch refuses integer input, and in float64 gives rank 12 for the full-rank 16x16 integer Hilbert matrix | torch.set_compat("pytorch") |
Masked
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.masked.argmax | int64 indices, as torch.argmax returns; PyTorch's masked.argmax returns them as float32 | torch.set_compat("pytorch") |
torch.masked.argmin | int64 indices, as torch.argmin returns; PyTorch's masked.argmin returns them as float32 | torch.set_compat("pytorch") |
Matmul and convolution
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.matmul | exact integer products (int8 -> int32, int16/int32 -> int64) and int8 @ uint8; PyTorch wraps 200 of 200 entries of a 10x64 @ 64x20 int8 product (and its CPU float16 matmul is 249x slower), MLX has no integer matmul; fastest exact path at 4096 (quiet Mac, November 24, 2026): int8 x uint8 2.7 ms vs 136 ms PyTorch and 217 ms MLX, int16 10.2 vs 260 and 217; int8 @ int8 2.4 vs 3.2 ms (PyTorch MPS _int_mm, alternating runs) | torch.set_compat("pytorch") |
torch.mm | exact integer products like torch.matmul; PyTorch keeps the input dtype and wraps (200 of 200 int8 entries wrong on 10x64 @ 64x20) | torch.set_compat("pytorch") |
torch.nn.functional.conv1d | exact integer convolution (NTT + CRT) that raises instead of wrapping; PyTorch wraps 51 of 72 int64 outputs (inputs < 2^40, weights < 2^24), MLX has no integer convolution | torch.set_compat("pytorch") |
Nn
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.nn.attention.flex_attention.flex_attention | computes the backward pass, which PyTorch 2.15 refuses on both CPU and MPS (NotImplementedError whenever an input requires grad); gradients match the direct softmax formula | torch.set_compat("pytorch") |
Onnx
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.onnx.export | writes a valid ONNX file with no onnx package installed (matches the module to 6e-8 on a CNN); PyTorch 2.15 raises on both export paths here | torch.set_compat("pytorch") |
Quantization
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.quantize_per_tensor | quantized integers are the exact quotient rounded half to even; PyTorch lands one step off on 5491 of 24000 values at the .5 boundaries | torch.set_compat("pytorch") |
torch.dequantize | one rounding of (q - zero_point) * scale; PyTorch's float32 scale gives a wrong last bit on 50 of 256 integers at scale 0.1 | torch.set_compat("pytorch") |
torch.fake_quantize_per_tensor_affine | exact quotient rounding and one-rounding dequantization; PyTorch differs on 1026 of 4000 boundary-heavy values | torch.set_compat("pytorch") |
torch.ao.nn.quantized.Linear | exact integer products and bias, one rounding; PyTorch's float32 requantization multiplier turns the exact tie 6.5 into 7 | torch.set_compat("pytorch") |
Signal
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.signal.windows.bartlett | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 1.0e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.blackman | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.5e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.cosine | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.2e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.exponential | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.4e-5 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.gaussian | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 5.1e-5 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.general_cosine | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 3.0e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.general_hamming | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.2e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.hamming | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.2e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.hann | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.2e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.kaiser | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 4.2e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
torch.signal.windows.nuttall | correctly rounded window values; PyTorch's float32 arithmetic is off by up to 2.8e-7 (absolute, M up to 4096) and leaves true zeros non-zero | torch.set_compat("pytorch") |
Sparse
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.Tensor.coalesce | duplicate entries summed in float64 and rounded once: duplicates [1e8, 1, -1e8] give 1.0, PyTorch's float32 sum gives 0.0 | torch.set_compat("pytorch") |
torch.Tensor.to_dense | duplicate entries summed in float64 and rounded once: duplicates [1e8, 1, -1e8] give 1.0, PyTorch gives 0.0 | torch.set_compat("pytorch") |
torch.sparse.mm | CSR / CSC sums and BSR / BSC @ dense products work on this Mac; PyTorch 2.15 raises (its CPU kernels need MKL) | torch.set_compat("pytorch") |
torch.sparse.spsolve | solves A x = B for a sparse A on this Mac; PyTorch 2.15 raises NotImplementedError (it needs cuDSS) | torch.set_compat("pytorch") |
torch.sparse.solve | PyTorch lists torch.sparse.solve but doesn't ship it; Riptorch solves sparse systems directly, exact on integers | torch.set_compat("pytorch") (calling it raises PyTorch's AttributeError text; PyTorch fails at the attribute lookup itself) |
Special
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.special.ndtr | keeps the lower tail (erfc form, float64, rounded once): 0 ulp vs PyTorch's worst 846370998 ulp in float32; PyTorch gives ndtr(-10) = 0 even in float64; MLX has no ndtr | torch.set_compat("pytorch") |
torch.special.sinc | correct next to the integers (exact argument reduction): 0 ulp vs PyTorch's worst 859354445 ulp in float32, 30% off at sinc(1 + 2^-23); MLX has no sinc | torch.set_compat("pytorch") (PyTorch's float32 formula; within 2 float32 ulp of PyTorch, the device's own sin) |
torch.digamma | correctly rounded float32 values (computed in float64, rounded once); 1499 inputs in [-4.9, 5.7]: worst 125285 ulp (PyTorch) vs 0; MLX has no digamma | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.erfinv | correctly rounded float32 values (computed in float64, rounded once); 1999 inputs in [0.9999, 1]: every value off, worst 127 ulp vs 0; MLX's GPU erfinv is up to 3 ulp off there | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.special.ndtri | correctly rounded float32 values (computed in float64, rounded once); 1999 inputs in [6e-8, 1.2e-4]: worst 3 ulp vs 0; MLX has no ndtri | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.special.log_ndtr | correctly rounded float32 values (computed in float64, rounded once); 1500 inputs in [-40, 35]: worst 162 ulp vs 1; MLX has no log_ndtr | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.special.erfcx | correctly rounded float32 values (computed in float64, rounded once); 1500 inputs in [-5, 40]: worst 13 ulp vs 0; MLX has no erfcx | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.i0 | correctly rounded float32 values (computed in float64, rounded once); 1500 inputs in [0, 75]: worst 3 ulp vs 0; MLX has no i0 | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.special.i0e | correctly rounded float32 values (computed in float64, rounded once); 1500 inputs in [0, 105]: worst 3 ulp vs 0; MLX has no i0e | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
torch.special.i1e | correctly rounded float32 values (computed in float64, rounded once); 1500 inputs in [0, 105]: worst 8 ulp vs 0; MLX has no i1e | not reproduced: PyTorch's values come from its own float32 polynomial kernels, which Riptorch does not copy (compat keeps Riptorch's correctly rounded values) |
Torch
| Function | What Riptorch does differently | Stock behaviour |
|---|---|---|
torch.embedding_renorm_ | correctly rounded rescaled rows; PyTorch's float32 arithmetic left 21374 of 160000 values off (200 random 50x16 weights) | torch.set_compat("pytorch") |
torch.lobpcg | exact eigenpairs, identical on every call; PyTorch's random-start iteration was off by up to 3.7e-6 (relative) and varied by up to 5.8e-4 between calls on the same matrix | the same direct solver (PyTorch's random starting block can't be reproduced, so its iterates can't be matched value for value) |
torch.cos | float32 cos within 1 ulp of the correctly rounded value: worst 1.08 ulps of the exact value on [-100, 100] where PyTorch's CPU kernel has 1.57 (CPU and MPS: 2 ulps after rounding) | none: an accuracy gain, PyTorch's rounding is not reproduced |
torch.sin | float32 sin within 1 ulp on [-100, 100]: worst 0.64 ulps of the exact value where PyTorch's CPU kernel has 1.71 (CPU and MPS: 2 ulps after rounding) | none: an accuracy gain, PyTorch's rounding is not reproduced |
torch.remainder | float32 remainder is one rounding of the exact x - floor(x / y) y for every input: 0 of 20000 random pairs wrong where PyTorch MPS gets 10511 wrong (and remainder(7, -inf) is nan there) | none: PyTorch's CPU kernel already gives these values; MPS's errors are not reproduced |
torch.logsumexp | dim=[] reduces every dim, as sum(dim=[]) does; PyTorch CPU and MPS raise RuntimeError | torch.set_compat("pytorch") |
torch.sum | float64 sums compensated: the sum of 1e5 normal values is 3.39e-15 off the exact sum where PyTorch's is 5.35e-14 (1e6 values: 3.05e-14 vs 7.13e-13) | none: an accuracy gain, PyTorch's rounding is not reproduced |
More extras
Every other name Riptorch has that stock PyTorch doesn’t.
torch
torch.ComplexTensor— A complex tensor:_rvis its real view [..., 2].torch.FractionTensor— Exact results: a tensor of reduced fractions (Python ints of any size, no rounding).torch.LOSSEStorch.NestedTensor— A nested tensor:_ts(the components),_lay(strided or jagged),_ragged(the RaggedInt of a jagged tensor's ragged dim).torch.QTensor— A quantized tensor:_qrits integers (int_repr, unpacked),_qdits dtype,_qsits qscheme, and the quantization parameters (_scale,_zpper tensor;_scales,_zps,_axisper channel).torch.SparseTensor— A sparse tensor of any sparse layout (see the module docstring).torch.WEIGHT_MAPStorch.avg_pool2d— A depthwise convolution with a constant kernel: sums over each window divided by its size, or (count_include_pad=False) by the number of real (unpadded) entries.torch.maths_stats— A lazy tensor [clamped above, clamped below, entries, largest entry] over every Cayley map built since maths_stats_reset; a compiled step can return it.torch.maths_stats_reset— Forgets the Cayley clamp statistics recorded so far (call at the start of a step).torch.normalized_map— p_i = w(x_i) / sum_j w(x_j) over the last dim, nothing recentered or tempered.torch.unfold— Tensor.unfold: every window ofsizealongdimension,stepapart, as a new last dim.torch.weight_map— w(x) of a weighting map, elementwise.torch.weight_rate— r(x) = w'(x) / w(x) of a weighting map, elementwise.- 58 in-place functions at the top level, such as
torch.absolute_,torch.addbmm_,torch.addcdiv_,torch.addcmul_,torch.addmm_,torch.addr_: the same as theTensormethod of that name.
Tensor
Tensor.gelu— approximate="tanh": 0.5 x (1 + tanh(sqrt(2/pi) (x + 0.044715 x^3))).Tensor.hspmm— torch.hspmm(self, mat2): sparse self @ dense mat2 as a hybrid COO tensor.Tensor.is_distributed_— False: Riptorch has no distributed tensors.Tensor.is_quantized_— False: Riptorch has no quantized tensors.Tensor.isin— torch.isin(self, *args, **kwargs).Tensor.mps— Tensor.cpu / cuda / mps / pin_memory: the tensor itself (one unified memory and one layout).Tensor.names— Dimension names: None for every dim (no named tensors).
torch.nn
nn.Temperature— A learned temperature for one layer: a scalar parameter s and, by riptorch.set_maths(temperature=...), T = 1 + s^2 ("learned", order 2, T >= 1) or 1/T = 1 + s + s^2/2 ("learned_inv", 1/T >= 1/2).nn.clip_grad_norm_— Scales the gradients so their combined 2-norm is at most max_norm; returns the norm before scaling.nn.fan_in_values— n initial values with variance 1/(3 fan_in) (torch.nn.Linear's and Conv2d's).nn.init.trunc_normal— Fills the tensor in place with N(mean, std) draws truncated to [a, b].
torch.nn.functional
F.cross_similarity— The signed crosssign(u·v) (u·v)² / (Q(u) Q(v)):1 − spreadwith the sign ofu·v, in[−1, 1].F.customF.install_maths_routes— Puts the exponential-equivalent router in front of F.cross_entropy, F.softmax and F.scaled_dot_product_attention (called once at import, after the generated ops are installed).F.maths_custom— True when the maths configuration is neither preset (see riptorch.set_maths).F.model_cross_entropy— -mean log p_k under the model's configured map, no gradient (Riptorch extension: the side cross-entropy).F.model_probs— The model's probabilities under the configured output map.F.spread— The spread between vectors alongdim:1 − (u·v)² / (Q(u) Q(v)), whereQ(u) = u·u.
torch.optim
optim.Lion— Lion (Chen et al.
torch.linalg
linalg.FractionTensor— Exact results: a tensor of reduced fractions (Python ints of any size, no rounding).linalg.cayley— The Cayley transform Q = (I - S)^-1 (I + S) of a skew-symmetric S: an orthogonal matrix with no sin / cos and (rational S gives a rational orthogonal Q exactly; 2x2 with S = [[0, -t], [t, 0]] is the rlinalg.cayley_inverse— S = (Q - I)(Q + I)^-1: the skew-symmetric matrix whose Cayley transform is Q (Q orthogonal without eigenvalue -1).linalg.givens_triangularize— Exact triangularisation by scaled rotations (Givens with rational parameters): G A = R, R upper triangular, G's rows orthogonal with quadrances sigma (G G^T = diag(sigma)).linalg.ldl— A = L D L^T (L unit lower triangular, D the diagonal as a vector): Cholesky without its root (L_chol = L D^(1/2)).linalg.principal_spreads— The spreads (ascending; classically sin^2 of the principal angles) between the column spaces of A (m x k) and B (m x l), full column rank: 1 - the eigenvalues of (A^T A)^-1 A^T B (B^T B)^-1 B^T A (the crosses; oflinalg.qr_quadrance— Exact QR: A = Q R with Q's columns orthogonal but not normalised, R unit upper triangular, and quadrances[j] = Q(q_j) = q_j.linalg.rotation— The rational rotation by Cayley parameter t (= tan(angle / 2)) in the (i, j) plane of n dimensions: cos = (1 - t^2) / (1 + t^2), sin = 2t / (1 + t^2) placed as a Givens matrix.linalg.subspace_cross— The product of the crosses (classically cos^2 of the principal angles) between the column spaces of A and B (both m x k, full column rank): det(A^T B)^2 / (det(A^T A) det(B^T B)).
torch.fft
fft.cayley_points— the rational twiddles of maths="rational" for length n, as Pythagorean triples [n, 3] (a, b, c), the point (a / c, b / c) = w^k, w = e^(-2 pi i / n), with a^2 + b^2 = c^2 exactly.fft.ntt— the number-theoretic transform of an integer tensor along dim, mod a prime p (default 998244353 = 119 2^23 + 1): A[k] = sum_j a[j] w^(jk) mod p, w a primitive n-th root of unity mod p.fft.polymul— the full linear convolution of the last dims (polynomial product; leading dims equal or one side 1-d).