Equivalence with tinymind (C++)

The acceptance test for every ported path is that it produces the same bits as the tinymind (C++) build. Not close results: identical files.

What is compared

Twelve of tinymind (C++)’s examples are ported, and every file they write must be byte-identical to the C++ example’s output:

  • XOR, in Q16.16 and Q8.8: stdout, the per-step weight trajectory (nn_fixed_xor.txt, about 20,000 lines), the learning curve and the decision surface.
  • Iris: stdout, the loss curve, the per-sample test predictions and the confusion matrix. Its input is the dataset file tinymind (C++) ships with the example, checked byte for byte against tinymind (C++)’s copy.
  • Handwritten digits (optical_digits): stdout, the loss curve, the test confusion matrix and 40 sample test images of a 64-32-10 Q16.16 network trained on the UCI optical digits data, read from copies of tinymind (C++)’s two data files and checked byte for byte against them.
  • Energy efficiency: stdout, the loss curve and the per-sample test predictions of a regression (linear output, clipped gradients) on the UCI Energy Efficiency data, again read from tinymind (C++)’s own copy of the file.
  • Maze: stdout, the path of every training and test episode of a Q-learner finding its way out of a six-room maze, and its final Q table beside the optimal one from value iteration.
  • Deep Q-network maze (dqn_maze): the same files for the same maze learned by a deep Q-network, a 6-8-6 Q16.16 network with a target network, over 10,000 episodes. Its initial weights come from the C++’s std::default_random_engine and uniform_real_distribution<double>, reproduced bit for bit, and the C++ is built with -ffp-contract=off.
  • Activity recognition (har_activity): stdout, the loss curve, the synthesized sample windows and the test confusion matrix of an LSTM network trained on 800 windows of accelerometer data. The C++ is built with -ffp-contract=off, because the windows are synthesized in double and a compiler that fuses multiply-adds would change them.
  • Air quality (air_quality): stdout, the loss curve and the one-step forecast over the 200 held-out hours of an LSTM network trained on a synthetic hourly pollutant series until no sample trains (28 epochs). Built with -ffp-contract=off, because the series is synthesized in double.
  • Gas sensor drift (gas_sensor_drift): stdout, the loss curve, the batch-1 confusion matrix, the drift curve over 10 batches and the comparison of seven ways to adapt to each drifted batch from 1 to 20 labelled samples per class (a PrototypeHead, a DenseHead, the backbone’s biases through DenseHead::backward, re-normalized inputs), each averaged over 10 draws of the samples. Built with -ffp-contract=off for the same reason.
  • Int8 XOR: stdout and the decision surface of a PyTorch-trained network running in int8. tinymind (C++)’s int8 path matches TensorFlow Lite’s reference kernels, so this also ties the Rust port to TFLite’s arithmetic on these cases.
  • Int8 GBDT: stdout, the predicted class over a 48 x 48 input grid and the compact golden report of a five-tree gradient-boosted ensemble quantized to int8.
  • Int8 KWS-shaped CNN (kws_cortex_m_int8): its stdout carries host timings, so it is compared tensor by tensor instead (below).

The four classifiers among them (iris, handwritten digits, activity recognition, gas sensor drift) pick their class with predicted_class(), as tinymind (C++)’s examples do with getPredictedClass(), so these files check it too.

Parts that no tinymind (C++) example exercises are compared through small C++ programs built on tinymind (C++)’s library (in scripts/cpp/), whose output must match the Rust port’s in the same way:

  • Networks with several hidden layers: tinymind (C++)’s NeuralNetwork with two and three hidden layers, in both formats, trained for thousands of steps, with a hash of every weight after every step; two regressions with a linear output and gradient clipping (one with an asymmetric range), sized so that clipping the weight and bias gradients changes the result; runs with tinymind (C++)’s Adam and RMSprop optimizers on one, two and three hidden layers, in both formats; and five runs with its L2WeightDecay and StepDecaySchedule policies (SGD, Adam and RMSprop; one to three hidden layers; both formats; tinymind (C++)’s default lambda and decay factor and explicit ones), printing the learning rate as it decays and what its EarlyStopping reported over the run.
  • Scheduled sampling: tinymind (C++)’s ScheduledSampling stepped through eight decay lengths with the same rand() draws, printing how often it picked the true value, its ratio, and the next random number afterwards (it must make no draw once its window is over); and a Q16.16 LSTM network trained on a periodic sequence where each input is the true value or the network’s own previous prediction, as the sampler chooses, every weight hashed after every step.
  • Floating-point networks: tinymind (C++)’s NeuralNetwork instantiated with double and float, with the floating-point activations and transfer-function bundle its float example and unit tests define (tanh, 1 / (1 + exp(-x))), trained for 2,000 to 3,000 steps in nine configurations (one to two hidden layers; tanh and ReLU; sigmoid and linear outputs; SGD and its AdamOptimizerFloat and RmsPropOptimizerFloat), and its LstmNeuralNetwork in four (SGD and Adam), every weight hashed after every step: bit-identical on a glibc host, where both take tanh and exp from glibc. The float results depend on the glibc version (its tanhf and expf became correctly rounded in 2.41), so those are compared live on each machine; the double results also have a committed golden.
  • Inference-only networks: tinymind (C++)’s networks built with IsTrainable = false, loaded with the same weights as the Rust InferencePerceptron (one hidden layer, two shapes) and InferenceNetwork (one to three hidden layers, five configurations); the trainable networks loaded with the same weights must agree too.
  • Int8 softmax: tinymind (C++)’s TFLite-exact softmax and its calibration over 504 calibrations and row lengths from 1 to 511, plus the golden rows tinymind (C++)’s tests take from the TensorFlow Lite Micro reference kernel.
  • Fine-tuning heads: tinymind (C++)’s DenseHead and PrototypeHead, every parameter and output hashed after every step: nine dense heads (Q16.16, Q8.8, double and float; softmax cross-entropy and squared error; logits far beyond the exp table; sums that wrap in Q8.8), the softmax on its own, and seven prototype heads (squared Euclidean and Manhattan; squared distances that wrap; count caps, loaded and forgotten classes, ties). No float softmax: glibc’s expf changed between versions.
  • FFT: tinymind (C++)’s QFFT1D, its real-input QRFFT1D and their twiddle-table builder, buildQFFTTwiddles, at every power-of-two length from 2 to 1024: the tables, then nine test signals (impulses, DC, tones, random samples, full-scale values that saturate) through the forward and inverse transforms, the round trip and the bin magnitudes, and the real FFT of each signal’s real part, on the built tables and on random ones.
  • Int8 KWS-shaped CNN: every tensor of tinymind (C++)’s kws_cortex_m_int8 example (the quantized input, weight tables and requantizers from its calibration, and each layer’s output) and its report of the int8 logits against the float model’s, dumped by a program that compiles the example unchanged. The calibration runs the network in float, so this also checks that the float sums match bit for bit.
  • Int8 convolution and pooling: tinymind (C++)’s QConv2D, QConv2DPerChannel, QDepthwiseConv2D, QPointwiseConv2D, QPointwiseConv2DPerChannel, QMaxPool2D, QAvgPool2D and QGlobalAvgPool2D over random tensors, in 57 configurations covering the code paths of its portable (non-SIMD) build, padding on every side and both requantizer paths.
  • Int8 addition: tinymind (C++)’s QAdd and its calibration, buildQAddParams: 48 layers calibrated from random scales, run on every pair of int8 inputs, and 80 with random integer parameters, including sums that saturate the requantizer.
  • Int8 multiplication, concatenation and padding: tinymind (C++)’s QMul with buildQMulRequantizer (32 calibrated layers on every pair of int8 inputs, 48 with random requantizers), QConcat2_2D with buildRescaler (five shapes) and QPad2D (six padding patterns).
  • Int8 recurrent cells: tinymind (C++)’s QLSTMCell (int8 and int16 cell state) and QGRUCell with buildQLSTMParams, buildQGRUParams and the bias quantizers: seven LSTM and six GRU shapes, two trials calibrated from random float models and two with random integer parameters each, the hidden and cell state hashed after every step of 32-step sequences.
  • Q-learning: tinymind (C++)’s QLearner with its Q table hashed after every update, on the maze example (in the unsigned Q16.16 the C++ example uses) and on 60 random environments in Q16.16 and Q8.8 with negative rewards, states with zero, one, two or more valid actions, learning rates and discount factors of exactly 1 and ones its setters must reject, and updates for a state other than the learner’s current one.
  • LSTM networks: tinymind (C++)’s LstmNeuralNetwork in nine configurations (Q16.16 and Q8.8; 1 to 16 cells; tanh or ReLU cell candidates; sigmoid or linear outputs; gradient clipping, including an asymmetric range; SGD and Adam; L2 weight decay with a step-decay schedule) on sequences of 1 to 12 steps with the state reset between them, some steps not trained, and the outputs and every weight hashed after every step.
  • Decision trees: tinymind (C++)’s QDecisionTree and QGBDT over 72 random ensembles with int8, uint8 and int16 thresholds, base scores, tied classes and inputs on the thresholds.
  • PyTorch importer: the same models imported with tinymind (C++)’s importer and with this repository’s, run on both runtimes: two dense networks (sigmoid, softmax) and two convolutional ones, whose comparison includes a hash of every intermediate tensor. On nine models, the two LSTM ones included, both importers also compute identical scales, zero points, weights and biases. For the two LSTM models a C++ program takes the float scales, float LSTM biases and int8 weights this importer computed, builds every integer parameter itself with tinymind (C++)’s calibration functions, and runs the models on its QLSTMCell and QDense: the parameters, a hash of the hidden and cell state after every step and the outputs match the Rust example’s byte for byte.
  • ONNX importer: five int8 models quantized by ONNX Runtime (a convolutional network in QDQ format with per-channel weights, tanh, sigmoid and a softmax; one in QOperator format with per-tensor weights; a dense network with a separate bias addition; and a residual network with max pooling, a depthwise convolution, an addition, tanh and sigmoid on feature maps, average and global average pooling, in QDQ format and in QOperator format ending in its QLinearSoftmax) are read by tinymind (C++)’s own ONNX importer, run on its int8 layers wired as each layer’s record says, and give the Rust example’s output byte for byte on 16 inputs each; the importer’s parser is checked to be tinymind (C++)’s, line for line, and the five committed modules to be what it writes.
  • TFLite translator: the MLPerf Tiny keyword-spotting model (DS-CNN) and image-classification model (ResNet-8, with residual additions), translated from their .tflite, give tinymind (C++)’s output hashes on 8 seeded inputs each (the hashes TFLite’s reference kernels also give); its softmax parameters equal tinymind (C++)’s on 504 calibrations, and its addition parameters tinymind (C++)’s buildQAddParams on 48. Its padding, multiplication and concatenation, which those models do not use, are checked on small generated models against TFLite’s own reference kernels (LiteRT): every output byte the same.
  • Tree importer: 18 scikit-learn, XGBoost and LightGBM models imported with both importers must give identical integer trees, and each output must match on its own runtime; two models for the UCI Wine data run on both runtimes with byte-identical output.

Fixed-point arithmetic makes this demanding. A multiply truncates, so (a * b) * c and a * (b * c) can differ in the last bit, and one bit early in training becomes a different weight trajectory. The port keeps the C++ operation order in every expression, and repeats details that do not affect the result’s quality but do affect its bits, such as a random draw the C++ makes for a connection it never uses.

How it is checked

  • Golden tests. cargo test --all-features runs the examples (xor in each format, iris, optical digits, energy efficiency, maze, dqn_maze, har_activity, air_quality, gas_sensor_drift, int8 xor, the GBDT, the KWS-shaped CNN and the importers’ models) and the comparisons above that have goldens, and checks their output against goldens produced by the C++ build; the importer parity checks, the TFLite translator and the live floating-point comparison run in scripts/compare-with-cpp.sh only. The goldens for everything ported come only from C++ runs, never from the Rust output, or the test would prove nothing. The anomaly-detection example has no tinymind (C++) counterpart, so tests/anomaly_golden.rs pins its own output instead: a regression check, and the hash the boards must reproduce.
  • Live comparison. scripts/compare-with-cpp.sh builds the tinymind (C++) examples from a tinymind (C++) checkout with the flags their Makefiles use, and the C++ programs in scripts/cpp/, runs both sides and compares every output file: 111 checks today, including that data/iris.data, data/optdigits.* and data/ENB2012_data.csv are still tinymind (C++)’s files. The Q8.8 xor build is tinymind (C++)’s example with its two bit-count constants set to 8; nothing else changes.
  • Pinned tinymind (C++) commit. The file TINYMIND_REF records the tinymind (C++) commit the port was last verified against. CI checks out exactly that commit.
  • Arithmetic oracle. Ported from tinymind (C++)’s own oracle: every QValue operation is checked against an exact integer reference, on edge values and a random sample for nine formats, and on every pair of operands for Q8.8, about 26 billion checks per pull request. That run keeps Rust’s integer-overflow checks on, so an overflow that happens to give the right answer still fails. A nightly job repeats the sample with a fresh seed.
  • Proofs. Kani, a model checker built on the same CBMC engine tinymind (C++) uses for its own proofs, checks properties for every possible input rather than a sample: that addition, subtraction and multiplication wrap and round exactly as specified, that division never panics, that tanh and sigmoid never index outside their tables or leave their range, that the int8 requantizer’s fast path equals gemmlowp’s two-step rounding, and that the requantizer, the int8 dense layers, convolutions, pooling, addition, multiplication, padding and concatenation, the tables, the softmax, the int8 LSTM and GRU cells, both FFTs, the decision trees, the Q-learner, the deep Q-network, the LSTM network and small Q8.8 fine-tuning heads never panic, whatever their parameters, that the heads keep every class count within its cap and the softmax’s exp in [0, 1], that the learning-rate schedule, early stopping and scheduled sampling never panic and weight decay with lambda 0 changes no weight, and that the FFT’s saturation skip on cores without a saturating instruction changes no output.
  • No reachable panics. CI links a Cortex-M firmware image that calls every public function and has no panic handler, for Cortex-M0+ and M4F at three optimisation levels; a panic path that survives optimisation fails the build.
  • On Cortex-M, emulated. CI runs the on-board checks under QEMU on a Cortex-M4 and a Cortex-M0, the instruction sets of the two boards, at three optimisation levels, and fails if any workload’s output hash differs from the one the boards must produce: int8 inference, the MLPerf models, training on the device, the FFT, the fine-tuning heads and the trees, on Arm code on every pull request, not only on the desktop. The same run takes every sweep but the fine-tuning heads’ (on Cortex-M those are checked by the heads’ workload) to Cortex-M (convolution and pooling, addition, composition, softmax, the FFT, the int8 LSTM and GRU cells, LSTM training, decision trees and Q-learning), where each report must equal tinymind (C++)’s golden byte for byte (calibration needs std, so there the calibrated layers take the C++’s parameters from the golden, and the int8 recurrent cells run their directly drawn trials), and runs the qformat oracle’s default sample there (240,277 checks of every QValue operation against exact arithmetic). Timings still come from the boards.
  • Tables. CI regenerates the activation lookup tables from tinymind (C++)’s source and fails if they differ from the committed ones.
  • CI and branch protection. Every pull request runs all of this, and a pull request cannot merge unless it passes. Each check was shown to fail on a deliberately planted defect before it was trusted.

Back to top

Dan McLeran — danmcleran@gmail.com — MIT License

This site uses Just the Docs, a documentation theme for Jekyll.