Skip to content
Applied engineeringExperiments

Verace FastKernel

Header-only C++20 array, dataframe and autograd libraries with a service that compiles, fuzz-checks and benchmarks numerical kernels.

Verace Research
  1. Tile of 64: One block of the inner dimension, sized for cache
  2. OpenMP threads: Each thread owns its own output tiles
  3. Output tile: Products accumulated into the result block
  4. Vectorized column loop: Columns swept with SIMD in the innermost loop
Figure 1. Cache-blocked parallel matrix multiplication in the array library. Schematic: the array library multiplies two strided arrays tile by tile, with each OpenMP thread owning an output tile and the inner loop vectorized with SIMD.
Open the simulator on its own pageMultiplying in blocks: an interactive toy model of the principle. You can also try it below

Overview

Verace FastKernel is the lab's work on native C++20 replacements for numerical Python code. It has two parts. The first is a kernel service that maps Python numerical routines to compiled C++ kernels, checks them against the Python original and benchmarks them. The second is three header-only C++20 libraries: a NumPy-style array library, a pandas-style dataframe library and a PyTorch-style autograd library, called NumCpp, Pandas-CPP and TorchCpp in the lab's code. The array library is the lab's own code and is not the unrelated open-source library of the same name. The work asks how much speed vectorized native code gains over Python while keeping results numerically equal.

The libraries exist as a research implementation of the array and dataframe libraries, a research implementation of the autograd library, a combined set, and a copy bundled with the service. These copies share their files. Arrays are strided views over reference-counted buffers, with OpenMP threading and SIMD loops. The dataframe library stores typed columns with a null mask and parses CSV to RFC 4180. The autograd library records each operation as a backward closure and provides linear, embedding, RMSNorm, attention and pre-norm Transformer layers, losses, SGD and AdamW. The service adds a Python gateway with an API and a command line, a native compiler, a package builder, a micro-benchmarker and a dual-oracle differential fuzzer.

The service's technical reference reports speedups over Python of 1,183.3x for pairwise_cosine, 64.2x for dynamic time warping, 77.7x for Black-Scholes pricing, 51.9x for pairwise Euclidean distance and 35.4x for RMSNorm, each fuzzed on 1,000 cases. The lab's own audit found these claims overstated: synthesis is a keyword matcher over 6 hardcoded kernels, the Black-Scholes speedup measured 5-6x rather than 77.7x, and invalid keys returned a false success. For the libraries, the audit matched the matrix inverse to NumPy within a maximum error of 7.6e-15. It matched autograd gradients exactly to PyTorch and found a Transformer block finite-difference error of about 1e-9.

All three libraries are implemented, with test suites, examples and benchmarks, and the lab's audit fixed CSV, random seed and build defects in the array and dataframe code. The service runs end to end but does not synthesize kernels in general: it selects among 6 prewritten kernels, and its headline speedups did not hold under the lab's audit. Library benchmark figures, such as 54.7 GFLOPs for matrix multiplication, come from the lab's technical references and are not repeated in the audit. The attention layer is a single non-causal head, and the Transformer MLP uses plain GELU. Kernel synthesis beyond the fixed set remains open.

Status

Experiments. The libraries are implemented with tests and recorded benchmarks, and the lab's own audit verified their numerics while finding that the kernel service matches 6 hardcoded kernels and overstates its speedups.

Simulator

Two matrices are multiplied in two orders that do exactly the same work: straight through, and tile by tile. A small cache holds the lines read most recently. Count how often each order misses it.

  • A times B gives C; the coloured squares are the tiles in use
  • grey bar: cache misses in the plain order · coloured bar: in tiles
Cache misses, plain order
3,744
Cache misses, in tiles
1,872
Plain order misses
2.0 times as often
Elements read in all
41,472

Shrink the cache, then find the tile size that fits it. A tile as large as the matrix is the plain order.

This simulator is an illustration of the principle, with made-up numbers. It does not run the lab's code or show the lab's data, and nothing in it is a measurement.

Architecture

  1. NumPy-style array library

    A header-only C++20 n-dimensional array template with creation routines, vectorized elementwise math, reductions, tiled matrix multiplication, linear algebra and parallel random number generation.

  2. Pandas-style dataframe library

    A header-only C++20 Series and DataFrame implementation with nullable values, describe, sort, group-by mean and CSV reading and writing with type inference.

  3. PyTorch-style autograd library

    A header-only C++20 reverse-mode automatic differentiation framework on double tensors, with neural network modules, losses and optimizers.

  4. Neural network modules

    Linear, Embedding, RMSNorm, Sequential, MultiheadAttention and a pre-norm TransformerBlock, all built on the Module base class with parameter registration and zero_grad.

  5. Losses and optimizers

    MSE, cross-entropy with log-sum-exp and binary focal loss, plus SGD with momentum and AdamW; Adam is an alias of AdamW and so still applies weight decay.

  6. Mini-GPT example

    A token embedding, one Transformer block, RMSNorm and a bias-free output head, trained for 60 epochs with AdamW to map each odd token to the next odd token, then decoded greedily from token 1.

  7. MLP classifier example

    A 3-layer GELU network of shape 2->32->32->4, trained with AdamW at lr 0.05 and wd 0.001 for 100 epochs on a 200-point synthetic 4-quadrant set.

  8. Kernel service gateway

    A Python API and command line in front of the native compiler, receiving kernel requests and returning compiled kernels with benchmark and fuzz reports.

  9. Native compiler and package builder

    NativeCompiler builds C++20 kernels with OpenMP and AVX2 flags, and PackageBuilder wraps the result for calling from Python through ctypes.

  10. Dual-oracle differential fuzzer

    DualOracleFuzzer runs a compiled kernel and its Python reference on randomized inputs and compares outputs, designed for 1,000 cases per kernel.

  11. Micro-benchmarker

    MicroBenchmarker times the Python reference against the compiled kernel and reports mean latencies and speedup.

Implementation

Mechanisms as they are implemented in the source code, with the constants the code uses.

Closure-based reverse-mode autograd
Each operation's output stores shared pointers to its parents and a lambda that captures the parent tensors. backward() topologically sorts the graph from the root and runs the lambdas in reverse order, each adding into the parents' gradient vectors. Gradients are not cleared automatically, so zero_grad must be called between steps.
Analytic matmul gradient
For C=ABC = AB the backward pass computes dAik=∑jdCijBkjdA_{ik} = \sum_j dC_{ij} B_{kj} and dBkj=∑iAikdCijdB_{kj} = \sum_i A_{ik} dC_{ij}. Results are accumulated with +=, parallelised over two collapsed loops with SIMD reductions inside.
RMSNorm backward with cached scale
Per row, with r=1/rms(x)r = 1/\mathrm{rms}(x) cached from the forward pass, the code forms s=∑gwxs = \sum g w x and f=sr3/Df = s r^3 / D. It then sets dx=gwr−fxdx = g w r - f x and accumulates dw+=gxrdw \mathrel{+}= g x r.
Pre-norm Transformer block
RMSNorm is applied before attention and before the MLP, each followed by a residual add, in the Llama-style ordering. The MLP maps d to mlp_dim with GELU and back to d; it is plain GELU, not SwiGLU, although a code comment says SwiGLU.
Single-head attention with head-dim scaling
Attention runs on the full d_model queries, keys and values as one head but scales scores by 1/dmodel/nheads1/\sqrt{d_{model}/n_{heads}}. The head count therefore changes only the softmax temperature, and no causal mask is applied.
AdamW with folded bias correction
Defaults are lr 1e-3, β1=0.9\beta_1 = 0.9, β2=0.999\beta_2 = 0.999, eps 1e-8 and weight decay 0.01. Decay is applied to the parameter before the moment update, and bias correction is merged into one step size η′=lrbc2/bc1\eta' = \mathrm{lr}\sqrt{bc_2}/bc_1, with eps left uncorrected.
Focal loss for class imbalance
With pt=pp_t = p when the target exceeds 0.5 and 1−p1-p otherwise, and αt\alpha_t chosen the same way from α\alpha, the loss is mean(−αt(1−pt)γlog⁡pt)\mathrm{mean}(-\alpha_t (1-p_t)^{\gamma} \log p_t). Defaults are alpha 0.25 and gamma 2, and the gradient is written by hand.
Linear layer initialisation
Linear draws weights from a normal distribution with standard deviation 1/in1/\sqrt{in}, using a fixed seed of 42, and adds a broadcast bias. The technical reference describes Kaiming or Xavier initialisation, which the code does not match exactly.
Strided shared-buffer arrays
An array is a view with shape, C-order strides and an offset over a reference-counted std::vector. The linear index is offset+∑iidxi stridei\mathrm{offset} + \sum_i \mathrm{idx}_i \, \mathrm{stride}_i, so reshape shares data without copying while transpose copies.
Cache-blocked parallel GEMM
C=ABC = AB is computed in tiles with BLOCK_SIZE=64. Threads own output tiles, loop over blocks of the inner dimension and accumulate cij+=aikbkjc_{ij} \mathrel{+}= a_{ik} b_{kj} with the j loop vectorized through omp simd.
Gauss-Jordan elimination with partial pivoting
For each column the row with the largest absolute entry is swapped up, then the pivot row is normalised and other rows are eliminated. inv eliminates all other rows of the augmented matrix with the identity, det eliminates below the pivot and multiplies pivots, and the singularity tolerance is 1e-12.
Modified Gram-Schmidt QR
For each column, Rjj=∥vj∥R_{jj} = \lVert v_j \rVert and qj=vj/Rjjq_j = v_j / R_{jj}, set to zero when the norm is below 1e-12. For later columns k>jk > j, Rjk=qj⋅vkR_{jk} = q_j \cdot v_k and vk←vk−Rjkqjv_k \leftarrow v_k - R_{jk} q_j, updating residual vectors immediately for stability.
Per-thread random streams
Each OpenMP thread holds its own mt19937_64 generator, whose seed is offset by the thread index multiplied by 10007, so parallel fills do not race on shared state. Results reproduce only for a fixed thread count and schedule.
RFC 4180 CSV state machine
A single-pass parser alternates between quoted and unquoted states: a doubled quote becomes one quote, delimiters and newlines count only outside quotes, and CRLF is collapsed. read_csv infers each column as integer, then float, then string, and to_csv wraps fields in quotes and doubles embedded quotes.
Typed columnar dataframe storage
A table is a name-ordered list of columns held in an unordered_map. Each Column keeps one homogeneous vector for its type tag plus a null mask, and cells surface as std::variant<double,int64_t,string,bool>.
Optional-based missing values
Series<T> stores std::optional<T>, so missing values are std::nullopt rather than NaN sentinels and any type is nullable. Reductions skip nulls, statistics use the sample variance, and dropna and fillna rebuild the data and index together.

Results

From the lab's own experiments and records. They have not been independently replicated.

  1. Kernel synthesis is keyword matching over fixed kernels

    The lab's own audit found that the service's synthesis step matches keywords against 6 hardcoded kernels rather than generating new code, and that invalid keys returned a false success.

  2. Black-Scholes speedup overstated

    The technical reference reports a 77.7x speedup for the Black-Scholes kernel; the lab's audit measured 5-6x.

  3. Reported kernel speedups in the technical reference

    The service's technical reference lists 1,183.3x for pairwise cosine (693.06 ms against 0.41 ms), 64.2x for dynamic time warping, 51.9x for pairwise Euclidean distance and 35.4x for RMSNorm, with focal loss showing no gain. Given the audit's correction, these figures are the reference's claims and not confirmed results.

  4. Matrix inverse matches NumPy

    The lab's audit cross-checked the array library's inverse against NumPy and found a maximum error of 7.6e-15.

  5. Array and dataframe defects fixed in audit

    The same audit fixed RFC 4180 CSV handling, made the random generator use a fixed seed and corrected build errors.

  6. Autograd gradients match PyTorch

    In the lab's audit the autograd library's gradients matched PyTorch exactly, and the Transformer block's finite-difference gradient error was about 1e-9.

  7. Autograd benchmark latencies

    The autograd technical reference records 2.06 ms for a matrix multiply forward and backward pass at batch 64 and dimension 256 (485.1 passes per second), and 1.96 ms for a Transformer block pass at sequence 32, width 64 and 4 heads (508.2 passes per second).

  8. Small training runs complete

    The technical reference reports the MLP classifier example reaching 100% accuracy in 216.4 ms over 100 epochs, about 2.2 ms per epoch, and the Mini-GPT example training in 116.2 ms, about 1.9 ms per epoch.

  9. Matrix multiplication throughput claimed

    The array library's technical reference claims 54.7 GFLOPs for its matrix multiplication; the audit records do not repeat this figure.

Concepts

Header-only library
A C++ library delivered entirely as header files, so it is used by including headers and needs no separate build or linking step.
Reverse-mode automatic differentiation
A method that computes gradients of a scalar output with respect to all inputs by recording operations in a forward pass and applying the chain rule backward through them.
SIMD and OpenMP
SIMD instructions apply one operation to several numbers at once, and OpenMP splits loops across processor threads; the libraries use both for elementwise math, reductions and matrix products.
Cache blocking
Splitting a matrix product into small tiles that fit in processor cache, so data is reused before being evicted; the array library uses 64 by 64 tiles.
Strided view
An array described by a shape, strides and an offset into a shared buffer, which lets reshapes reuse memory instead of copying it.
RMSNorm
A normalisation that divides each row by its root mean square and multiplies by a learned weight, without subtracting the mean.
Pre-norm Transformer
A Transformer layer that normalises inputs before the attention and MLP sublayers rather than after, with a residual connection around each.
AdamW
An adaptive optimizer that keeps running averages of gradients and squared gradients and applies weight decay directly to parameters instead of through the gradient.
Focal loss
A binary classification loss that multiplies cross-entropy by (1−pt)γ(1-p_t)^{\gamma} so that confidently correct examples contribute less, which helps with class imbalance.
Partial pivoting
Choosing the row with the largest absolute entry as the pivot during elimination, which limits growth of rounding error.
RFC 4180
The common specification of CSV files, covering quoted fields, embedded delimiters and newlines and doubled quote characters.
Differential fuzzing
Testing a program by feeding the same random inputs to it and to a reference implementation and comparing outputs; the service compares each compiled kernel against its Python original.
Finite-difference gradient check
Verifying analytic gradients by perturbing inputs slightly and comparing the change in output with the computed gradient; the lab's audit used it on the Transformer block.
Kernel synthesis claim
The service's technical reference presents it as producing optimised C++ kernels from Python code; the lab's audit found it selects one of 6 prewritten kernels by keyword.

About this page

Written from the lab's own documents and source code. Figures and results are the lab's measurements as it recorded them at the time, and have not been independently replicated.

Published under the PolyForm Noncommercial License 1.0.0: free for noncommercial use.