Every mainstream neural network speaks the same native dialect: ordinary one-dimensional real numbers. Give a standard multilayer perceptron a 3D force vector, a spinning molecule, a robotic arm pose, or a four-number stock candle (Open, High, Low, Close), and the very first thing it does is flatten those structured objects into a pile of independent floats. It has no built-in idea that (x, y, z) belong to the same 3D arrow, or that rotating a water molecule in space leaves its energy unchanged while rotating the force pulling on its oxygen atom by the exact same angle. To learn even basic 3D geometry, a standard network has to see the same object tilted in hundreds of directions and memorize each orientation separately.

What if you changed the number system itself?

Instead of real numbers (ℝ), Quaternion Neural Networks (QNNs) compute in Hamilton's four-dimensional quaternion algebra (ℍ), where every weight, bias, and neuron activation is a four-component bundle (r, i, j, k) multiplied using the rules of 3D rotations. In Glades Machine Learning, QNNs are a first-class C++98 network family (TYPE_QNN) implemented alongside standard real dense networks (TYPE_DFF) with identical optimizers, binary checkpoints, and controlled unit-test benchmarks.

Here is the short version of what happens when we run them head-to-head:

  • 4× fewer weights per real width: One 4-float quaternion weight generates a structured 4×4 real matrix block through Hamilton multiplication—sharing 4 parameters across 16 real connections.
  • Exact 3D rotational symmetry (SO(3)): With Glades' bilinear equivariant layer (LAYER_SO3_EQUIVARIANT) and radial polarTanh activation, rotational symmetry holds to floating-point precision (~10⁻⁷–10⁻⁶) before training, after training, and after reloading from disk.
  • 50× to 176× lower error on 3D geometry and physics: On 3D vector rotation, an equivariant QNN trained on just 32 examples reaches 0.0114 RMSE (0.54°)—beating a real MLP trained on 512 examples (0.5672) by 50×. On unseen 3D orientations of water molecules, quantum orbitals, and planetary orbits, error drops by 28× to 109×, and mirror-image molecular chirality hits 100.00% out-of-distribution accuracy in under three epochs.
  • Honest limits where real MLPs still win: On unrelated low-data tabular columns with weak regularization (like Iris), standard TYPE_DFF wins; and because TYPE_QNN currently runs on CPU and spends 4× more FLOPs per stored parameter, wide GPU-bound dense workloads still belong on TYPE_DFF.

This article explains both sides—starting with a plain-English intuition for what a quaternion actually is, walking straight into the exact algebra, C++98 implementation, and gradient derivations inside Glades ML, and finishing with the complete controlled benchmark evidence.

What is a quaternion, really?

Think of number systems as tools for describing motion:

  1. A real number (ℝ) is a slider along a line. Multiply by 2 and you stretch; multiply by -1 and you flip direction.
  2. A complex number (ℂ) adds a second axis (a + b·I) so it acts like a 2D turntable: multiplying two complex numbers scales and rotates in a flat plane.
  3. A quaternion (ℍ), discovered by William Rowan Hamilton in 1843, adds two more imaginary axes (q = r + i·I + j·J + k·K) so it can describe 3D orientation and rotation smoothly, with no gimbal lock and no trigonometric edge cases.

The cleanest mental picture is to split a quaternion into two pieces: a scalar part r (an ordinary number that never changes when you rotate your camera) and a 3D vector part v = (i, j, k) (an arrow pointing somewhere in 3D space).

text
q = (r, v) = r + i·I + j·J + k·K      where  I² = J² = K² = IJK = -1

Hamilton product of w = (w_r, w_v) and a = (a_r, a_v):
  w ⊗ a = ( w_r·a_r - w_v · a_v ,   w_r·a_v + a_r·w_v + w_v × a_v )
            \_____ scalar _____/     \________ 3D vector ________/

Look closely at that single line of algebra. Built directly into quaternion multiplication are the two workhorses of 3D physics: the dot product (w_v · a_v, which measures how aligned two 3D arrows are and drops into the scalar slot) and the cross product (w_v × a_v, which produces a third perpendicular arrow pointing by the right-hand rule). Because the cross product flips sign when you swap its arguments (a × b = -(b × a)), quaternion multiplication is non-commutative: w ⊗ a ≠ a ⊗ w.

Rotating 3D space by conjugation

To rotate any 3D arrow v = (0, x, y, z) by an angle θ around a unit axis û, you build the unit quaternion u = (cos(θ/2), û·sin(θ/2)) and sandwich v between u and its conjugate u* = (u.r, -u.i, -u.j, -u.k):

text
v′ = u ⊗ v ⊗ u*

This sandwich operation—called conjugation—does three remarkable things at once:

  • It leaves the scalar slot r completely untouched (SO(3) invariance).
  • It rotates the 3D vector (i, j, k) cleanly around û by θ (SO(3) equivariance).
  • Most importantly for neural networks, conjugation is an algebraic automorphism of ℍ:
text
u ⊗ (a ⊗ b) ⊗ u*  =  (u ⊗ a ⊗ u*) ⊗ (u ⊗ b ⊗ u*)

In plain English: if you rotate both inputs a and b first and then multiply them, you get the exact same result as multiplying them first and rotating the answer afterward. Ordinary real matrix multiplication does not have this property unless you constrain its weights.

How one 16-byte struct replaces 16 real weights

In Glades ML (Backend/Machine Learning/GMath/quaternion.h), a quaternion is a flat 16-byte C++98 POD struct holding four contiguous IEEE-754 floats: { r, i, j, k }. When you write the Hamilton product w ⊗ a in ordinary 4D real vector notation, the single 4-float weight w = (w_r, w_i, w_j, w_k) expands into a structured 4×4 matrix block:

text
[ out.r ]   [  w_r  -w_i  -w_j  -w_k ] [ a.r ]
[ out.i ] = [  w_i   w_r  -w_k   w_j ] [ a.i ]
[ out.j ]   [  w_j   w_k   w_r  -w_i ] [ a.j ]
[ out.k ]   [  w_k  -w_j   w_i   w_r ] [ a.k ]

A standard real layer mapping 4 floats to 4 floats needs 4 × 4 = 16 independent weight parameters. A quaternion connection mapping one quaternion to one quaternion produces all 4 outputs using only 4 weight parameters—a 4× weight reduction per real channel width—while forcing the four lanes to interact through the exact geometry of 3D space.

Diagram showing the 16-byte layout of a Glades Quaternion struct with scalar r and 3D vector components i, j, k, a 3D sphere illustrating rotation by conjugation v' = u tensor v tensor u*, and the 4x4 real-equivalent Hamilton matrix block demonstrating 4-to-1 parameter sharing
Inside one Glades Quaternion: 16 contiguous bytes, 3D rotation by conjugation, and the 4×4 structured Hamilton weight block that shares 4 floats across 16 real connections.

Inside a Glades QNN: two layer architectures and two activations

Here is a subtle catch that trips up many first-time implementations of quaternion neural networks.

Suppose you build a standard quaternion dense layer (LAYER_STANDARD in Glades ML):

text
z_m = b_m + Σ_n (W_{m,n} ⊗ a_n)

This layer gives you 4× weight sharing and rich cross-channel mixing—which turns out to be great for coupled 4-tuples like OHLC financial bars or compact parity circuits. However, it is not 3D rotation-equivariant. Why? Because W_{m,n} is a fixed learned quaternion sitting in the network's weights. When you rotate the input a_n → u ⊗ a_n ⊗ u*, the fixed weight W_{m,n} does not rotate with it, so W_{m,n} ⊗ (u ⊗ a_n ⊗ u*) ≠ u ⊗ (W_{m,n} ⊗ a_n) ⊗ u* unless W_{m,n} has zero vector part.

If a layer multiplies inputs only by scalars, it preserves rotations—but it can never form dot products or cross products between two 3D vectors, so it can't compute angles, forces, or handedness. How do you get both rich geometric interactions and exact 3D rotational symmetry?

LAYER_SO3_EQUIVARIANT: bilinear Hamilton coupling

Glades ML solves this in Backend/Machine Learning/Networks/sgd_qnn.cpp with a second layer mode, LAYER_SO3_EQUIVARIANT, that exploits the conjugation automorphism directly.

Instead of multiplying inputs by fixed directional weights, each output neuron m builds two equivariant linear combinations—a left branch L_m and a right branch R_m—using strictly scalar real weights (w_r, w_i, w_j, w_k) applied independently to the scalar and vector parts of each incoming quaternion a_n = (a_r, a_v). Then it multiplies L_m and R_m with each other using the Hamilton product:

text
L_m = ( b_m.r + Σ_n w_{r,m,n} · a_{n,r} ,   Σ_n w_{i,m,n} · a_{n,v} )
R_m = ( b_m.i + Σ_n w_{j,m,n} · a_{n,r} ,   Σ_n w_{k,m,n} · a_{n,v} )
z_m = ( b_m.j , 0, 0, 0 )  +  L_m ⊗ R_m

Check what happens when you rotate every input quaternion by any u ∈ SO(3):

  1. Scalar weights commute with u, and the biases b_m.r, b_m.i, b_m.j live strictly in the invariant scalar slot (the fourth bias slot b_m.k is deliberately unused, leaving 3 active bias scalars per output node).
  2. Therefore, L_m → u ⊗ L_m ⊗ u* and R_m → u ⊗ R_m ⊗ u*.
  3. By the automorphism rule, L_m ⊗ R_m → (u ⊗ L_m ⊗ u*) ⊗ (u ⊗ R_m ⊗ u*) = u ⊗ (L_m ⊗ R_m) ⊗ u*.
  4. Meanwhile, expanding L_m ⊗ R_m inside a single layer produces every fundamental 3D geometric building block:
    • Dot products -L_v · R_v (angles and squared distances) in the scalar channel z_m.r.
    • Scaled linear combinations L_r R_v + R_r L_v in the vector channel z_m.v.
    • Cross products L_v × R_v (perpendicular axes, torques, angular momentum) in the vector channel z_m.v.
    • Stack just two layers and you get signed scalar triple products b₁ · (b₂ × b₃)—the exact pseudoscalar invariant that distinguishes a left-handed molecule from its right-handed mirror image!

There is one subtle initialization trap in a bilinear product L ⊗ R: if both L and R start near zero, their product L ⊗ R has nearly zero gradient with respect to inputs and weights (a saddle point at the origin). Glades ML avoids this cleanly in network.cpp by initializing the three active biases to initBias = (0.5, 0.5, -0.25, 0.0):

text
(0.5 + L′) ⊗ (0.5 + R′) - 0.25  =  0.5·L′ + 0.5·R′ + L′ ⊗ R′

The 0.5 × 0.5 = 0.25 constant cancels out -0.25 exactly, so initial activations stay zero-mean while the linear 0.5·L′ + 0.5·R′ terms guarantee healthy, non-vanishing gradients from step zero.

ACT_SPLIT vs. ACT_POLAR_TANH: choosing whether to keep or break symmetry

A neural network also needs a nonlinear activation function between layers, and the activation has to respect the same symmetry contract:

  • ACT_SPLIT applies an ordinary 1D nonlinearity (tanh, ReLU, sigmoid, etc.) to each of the four coordinates separately: (f(r), f(i), f(j), f(k)). Because tanh squashes along the x, y, z coordinate axes, it breaks 3D rotational symmetry—but it excels on axis-aligned problems like binary parity and tabular bars.
  • ACT_POLAR_TANH preserves exact SO(3) (and in fact full 4D O(4)) equivariance by scaling only the 4D Euclidean length r = ‖z‖ while leaving direction completely untouched:
text
Φ(z) = ( tanh(‖z‖) / ‖z‖ ) · z

Near z = 0, dividing tanh(r) by r would risk 0 / 0 numerical instability. For r² < 10⁻⁶, Glades ML switches seamlessly to the 4th-order Taylor polynomial s(r) = 1 - r²/3 + (2/15)·r⁴, keeping Φ(z) infinitely smooth (C^∞) and singularity-free across all of ℍ.

Boundary codecs: packing real data into ℍ and reading answers back

Real datasets arrive as flat arrays of floats, so QuaternionInput.h and QuaternionConfig expose explicit boundary codecs at both ends of the network:

Boundary Mode Mapping Best used for
Input packing PACK_GROUPS_OF_4 Packs consecutive 4-float groups into (r, i, j, k) (Q_in = ceil(D_real / 4), zero-padded) 3D vectors (0, x, y, z), quaternions (r, i, j, k), OHLC 4-tuples, compact tabular
Input packing ONE_QUAT_PER_FEATURE Places each real feature in its own scalar slot (x_f, 0, 0, 0) (Q_in = D_real) General tabular benchmarks (e.g. 13-feature Wine) where columns shouldn't be grouped arbitrarily
Output readout READOUT_REAL_PART Reads only the scalar channel out_m.r (D_out = Q_out) Exact SO(3)-invariant scalars: potential energy, chirality logits, orbital hopping integrals
Output readout READOUT_SPLIT_COMPONENTS Reads all 4 components (r, i, j, k) (D_out = 4 · Q_out) Joint scalar + 3D equivariant vector outputs, e.g. (Energy, F_x, F_y, F_z) or rotated vectors
Architecture diagram comparing LAYER_STANDARD (left Hamilton multiplication W tensor a) against LAYER_SO3_EQUIVARIANT (scalar-weighted L and R branches coupled through bilinear Hamilton product L tensor R with init bias 0.5, 0.5, -0.25), alongside a visual comparison of ACT_SPLIT axis-warping versus ACT_POLAR_TANH radial-only equivariant squashing
The two Glades QNN layer modes and two activations: LAYER_STANDARD for 4× weight sharing vs. LAYER_SO3_EQUIVARIANT + ACT_POLAR_TANH for exact 3D rotational symmetry.

Training in ℍ: backpropagation, initialization, and checkpoints

Because quaternion multiplication is non-commutative, you cannot blindly copy scalar backpropagation formulas—swapping the order of two factors flips the sign of the cross product and sends the optimizer downhill in the wrong direction.

The clean way to derive exact quaternion gradients without guessing is through the standard real Euclidean inner product ⟨p, q⟩ = p.r·q.r + p.i·q.i + p.j·q.j + p.k·q.k. Under this inner product, moving a factor across the comma turns it into its conjugate, while preserving left-versus-right side:

text
For z = W ⊗ a  and upstream gradient  δ = ∂L/∂z:

  Weight gradient:  ⟨W ⊗ a, δ⟩ = ⟨W, δ ⊗ a*⟩   →   ∂L/∂W = δ ⊗ a*    (mulConjRight)
  Input gradient:   ⟨W ⊗ a, δ⟩ = ⟨a, W* ⊗ δ⟩   →   ∂L/∂a = W* ⊗ δ    (mulConjLeft)

Notice the intuition: to isolate W from W ⊗ a, you "undo" a from the right using a*; to isolate a, you undo W from the left using W*. In LAYER_SO3_EQUIVARIANT, the exact same two helpers differentiate z_m = (b_m.j, 0, 0, 0) + L_m ⊗ R_m cleanly in two lines: ∂L/∂L_m = δ_m ⊗ R_m* and ∂L/∂R_m = L_m* ⊗ δ_m, which then project back onto the four scalar weight channels (w_r, w_i, w_j, w_k) via ordinary dot products.

For ACT_POLAR_TANH, differentiating Φ(z) = s(r) · z (where r = ‖z‖ and s(r) = tanh(r)/r) yields the exact analytical vector-Jacobian product:

text
∂L/∂z = s(r)·g  +  (s′(r) / r) · ⟨g, z⟩ · z
  where  s′(r) / r = (r·sech²(r) - tanh(r)) / r³
  and for r² < 10⁻⁶:  s′(r) / r ≈ -2/3 + (8/15)·r²

Here is the core C++98 arithmetic and analytical VJP directly from Backend/Machine Learning/GMath/quaternion.h:

cpp
struct Quaternion
{
    float r;
    float i;
    float j;
    float k;

    // Non-commutative Hamilton product: a (x) b.
    static Quaternion mul(const Quaternion& a, const Quaternion& b)
    {
        return Quaternion(
            (a.r * b.r) - (a.i * b.i) - (a.j * b.j) - (a.k * b.k),
            (a.r * b.i) + (a.i * b.r) + (a.j * b.k) - (a.k * b.j),
            (a.r * b.j) - (a.i * b.k) + (a.j * b.r) + (a.k * b.i),
            (a.r * b.k) + (a.i * b.j) - (a.j * b.i) + (a.k * b.r));
    }

    // Right-conjugated Hamilton product: a (x) b*  (weight adjoint: delta (x) a*).
    static Quaternion mulConjRight(const Quaternion& a, const Quaternion& b)
    {
        return Quaternion(
            (a.r * b.r) + (a.i * b.i) + (a.j * b.j) + (a.k * b.k),
            -(a.r * b.i) + (a.i * b.r) - (a.j * b.k) + (a.k * b.j),
            -(a.r * b.j) + (a.i * b.k) + (a.j * b.r) - (a.k * b.i),
            -(a.r * b.k) - (a.i * b.j) + (a.j * b.i) + (a.k * b.r));
    }

    // Left-conjugated Hamilton product: a* (x) b  (input adjoint: W* (x) delta).
    static Quaternion mulConjLeft(const Quaternion& a, const Quaternion& b)
    {
        return Quaternion(
            (a.r * b.r) + (a.i * b.i) + (a.j * b.j) + (a.k * b.k),
            (a.r * b.i) - (a.i * b.r) - (a.j * b.k) + (a.k * b.j),
            (a.r * b.j) + (a.i * b.k) - (a.j * b.r) - (a.k * b.i),
            (a.r * b.k) - (a.i * b.j) + (a.j * b.i) - (a.k * b.r));
    }

    // Exact analytical vector-Jacobian product for polarTanh.
    static Quaternion polarTanhBackward(const Quaternion& z, const Quaternion& gradA)
    {
        const float r2 = z.normSq();
        float s = 1.0f;
        float spOverR = -2.0f / 3.0f;
        if (r2 < 1e-6f)
        {
            s = 1.0f - (r2 / 3.0f) + ((2.0f / 15.0f) * r2 * r2);
            spOverR = -(2.0f / 3.0f) + ((8.0f / 15.0f) * r2);
        }
        else
        {
            const float r = sqrtf(r2);
            const float t = tanhf(r);
            const float sech2 = 1.0f - (t * t);
            s = t / r;
            spOverR = ((r * sech2) - t) / (r2 * r);
        }
        const float gz = dot(gradA, z);
        const float coeffZ = spOverR * gz;
        return Quaternion(
            (s * gradA.r) + (coeffZ * z.r),
            (s * gradA.i) + (coeffZ * z.i),
            (s * gradA.j) + (coeffZ * z.j),
            (s * gradA.k) + (coeffZ * z.k));
    }
};

In unit-tests/Backend/Machine Learning/qnn-test.cpp, Glades ML verifies both the algebra identities (u ⊗ (a ⊗ b) ⊗ u* == (u ⊗ a ⊗ u*) ⊗ (u ⊗ b ⊗ u*)) and polarTanhBackward directly against central finite differences across both the general regime and the r² < 10⁻⁶ Taylor branch, alongside full end-to-end SO(3) equivariance checks (< 1e-5 max error).

4D isotropic initialization, optimizers, and bit-exact checkpoints

Standard Xavier/Glorot and He initialization assume independent scalar weights. Because each quaternion weight has four components contributing to the squared norm (E[‖w‖²] = 4·L²/3 for components drawn uniformly from [-L, L]), Glades ML initializes quaternion weights isotropically in 4D (network.cpp):

  • Quaternion Glorot: L = √(3 / (2 · (Q_in + Q_out)))
  • Quaternion He: L = √(3 / (2 · Q_in))

Training in sgd_qnn.cpp supports both SGD_MOMENTUM and decoupled ADAMW, inverted per-quaternion dropout (dropping an entire 4-component quaternion as a single unit to keep channels coherent), and global gradient-norm clipping.

When a trained QNN is saved, network.cpp writes a versioned binary weights.bin (GLADES_TENSOR_WEIGHTS_BIN) containing the full QuaternionConfig (layer mode, activation mode, packing mode, readout mode, dimensions) followed by contiguous FP32 (r, i, j, k) weight and bias tensors. Unit tests verify bit-exact round-trip reload (max_pred_diff == 0.0f) and preserved SO(3) equivariance before training, after training, and after deserialization.

Benchmark 1: 3D rotations from 32 examples and unseen frames

How much does baking 3D geometry into the algebra actually matter? Glades ML's benchmark harness (docs/qnn-vs-dff.md and scripts/benchqnnvsdff/) compares every QNN variant against two carefully matched real TYPE_DFF baselines across 5 random seeds:

  • DFF [param=] — matched to the QNN's parameter count (fair storage budget).
  • DFF [width=] — matched to the QNN's real channel width (4 × Q, roughly 3–4× more parameters, fair representational width).

Tier 1A: Learning 3D vector rotation from 32 to 512 samples

The task is simple to state and brutally hard for a naive MLP: given a 3D vector v and a unit rotation quaternion u, predict the rotated vector v′ = u ⊗ v ⊗ u* (N_test = 256, 400 epochs, 5-seed mean). The QNN uses architecture 2 → 8 → 1 (123 active parameters in equivariant mode, 132 in standard mode); DFF [width=] uses 8 → 32 → 4 (420 params) and DFF [param=] uses 8 → 10 → 4 (134 params).

Model Params Optimizer N = 32 RMSE N = 64 RMSE N = 128 RMSE N = 256 RMSE N = 512 RMSE N = 512 Angle / R²
QNN-SO3-Equiv 123 SGD+M 0.0114 0.0081 0.0054 0.0038 0.0034 0.21° / 1.0000
QNN-SO3-Equiv 123 AdamW 0.0105 0.0110 0.0073 0.0110 0.0096 0.66° / 0.9997
QNN-Std Polar 132 AdamW 0.4927 0.3401 0.2833 0.2950 0.2992 20.6° / 0.7285
QNN-Std Split 132 AdamW 0.7948 0.6475 0.4839 0.4900 0.5482 41.9° / 0.0908
DFF [width=] 420 SGD+M 0.7611 0.6709 0.5358 0.6007 0.5782 44.3° / -0.011
DFF [param=] 134 SGD+M 0.9174 0.8210 0.6265 0.6076 0.5672 43.2° / 0.027

The gap is not incremental—it is more than two orders of magnitude. At just 32 training examples, QNN-SO3-Equiv (SGD+M) reaches 0.0114 RMSE (0.54°, R² = 0.9996), beating DFF [param=] trained on 512 examples (0.5672) by 50×—more than a 16× data-efficiency advantage. At N = 512, QNN-SO3-Equiv hits 0.0034 RMSE (0.21°, R² = 1.0000), 167× lower error than the parameter-matched DFF.

Notice also the clear stepping-stone ablation in the middle of the table: QNN-Std Split (0.5482) behaves nearly identically to DFF (0.5672), QNN-Std Polar (0.2992) cuts error roughly in half by preserving radial geometry, and QNN-SO3-Equiv (0.0034) collapses the remaining error by nearly another 100× by making every layer algebraically equivariant.

Log-scale learning curve chart of Tier 1 SO(3) 3D rotation Test RMSE across training set sizes 32, 64, 128, 256, and 512, showing QNN-SO3-Equiv (SGD+M and AdamW) more than two orders of magnitude below QNN-Std Polar, QNN-Std Split, DFF width-matched, and DFF param-matched, reaching 167x lower RMSE at N=512 and 50x lower error at N=32 than DFF at N=512
Tier 1 SO(3) 3D rotation learning curves (log₁₀ scale): exact rotational equivariance separates QNN-SO3-Equiv by more than two orders of magnitude across every dataset size.

Tier 1B: Flipping the world upside down (out-of-distribution generalization)

In-distribution accuracy can hide memorization. The tougher test is out-of-distribution (OOD) generalization (N_train = 128, N_test = 256): train only on one slice of 3D space, then evaluate on orientations the network has never seen.

  • 3D Rotation OOD: Train only on vectors in the upper hemisphere with small rotations; test on vectors pointing downward (v_z < -0.25) rotated by large angles (θ ∈ [π/2, π]).
  • Quaternion Composition OOD (q₁ ⊗ q₂): Train in one global reference frame; test in the opposite reference frame (93 active parameters for QNN-SO3-Equiv).
OOD Task Model Active Params Test RMSE Angle Error Test R² Equivariance Error
3D Rotation OOD QNN-SO3-Equiv (AdamW) 123 0.0929 6.16° 0.9747 ~10⁻⁷
3D Rotation OOD DFF [width=] 420 0.9578 91.9° -1.561 0.32–4.68
3D Rotation OOD DFF [param=] 134 1.0928 96.4° -2.350 0.32–4.68
Quat Composition OOD QNN-SO3-Equiv (SGD+M) 93 0.0045 0.74° 0.9999 4.48×10⁻⁷–7.90×10⁻⁷
Quat Composition OOD DFF [param=] 134 0.7941 138.0° -2.044 0.32–4.68

When the reference frame flips, both DFF baselines collapse into negative R² (-1.56 to -2.35, with angular errors past 90°—worse than predicting zero). On quaternion composition OOD, QNN-SO3-Equiv suffers zero OOD degradation, achieving 0.0045 RMSE (0.74°, R² = 0.9999)—176× lower error than the parameter-matched DFF—with measured equivariance error at the single-precision floating-point noise floor (4.48×10⁻⁷ to 7.90×10⁻⁷).

Benchmark 2: molecules, mirror-image chemistry, orbitals, and planets

Rotating a standalone vector is a clean textbook check. Do these same gains hold up on multi-body physics problems where a network must output both rotation-invariant scalars (like energy) and rotation-equivariant 3D vectors (like forces) at the same time?

Glades ML ships four Tier 2 physics datasets inside Backend/Machine Learning/DataObjects/QuaternionInput.cpp, each evaluated across 5 seeds under strict out-of-distribution orientation splits (recorded in unit-tests/data/qnn_tier2_benchmark.json):

  1. Water molecule (H₂O) potential energy + force (mol_pes_ood): Given the two O–H bond vectors of a deformed water molecule, simultaneously predict its potential energy E (invariant scalar in slot r) and the restoring force vector F on the oxygen atom (equivariant 3D arrow in (i, j, k)). Train only on small tilts [0°, 30°]; test on heavily rotated molecules [60°, 180°].
  2. Kepler two-body orbital mechanics (orbital_kepler_ood): Given a planet's 3D position r and velocity v, jointly predict its specific orbital energy (invariant scalar) and its 3D Laplace–Runge–Lenz (LRL) eccentricity vector pointing toward closest approach (equivariant vector). Train only on near-equatorial orbits (inclination ∈ [0°, 25°]); test on steeply inclined, polar, and retrograde orbits ([65°, 180°]).
  3. Slater–Koster p-p quantum orbital hopping (orbital_slater_ood): Given two atomic p-orbital orientation vectors and the interatomic bond vector, predict the scalar quantum hopping integral using READOUT_REAL_PART (exact SO(3) scalar invariance). Train on bonds pointing upward (z > 0.65); test in the opposite hemisphere (z < -0.35).
  4. Molecular chirality (mol_chiral_ood): Classify a 3-bond tetrahedral center as Planar, R (right-handed), or S (left-handed). Like a left glove and a right glove, R and S enantiomers have identical bond lengths and bond angles—the only thing separating them is the sign of the 3D scalar triple product b₁ · (b₂ × b₃). Train at tilts [0°, 35°]; test at [60°, 180°].

Full Tier 2 OOD results (5-seed means)

Tier 2 OOD Physics Task Best QNN-SO3-Equiv QNN-Std Polar DFF [param=] DFF [width=] OOD Gain vs. DFF
H₂O PES + Force ([0°,30°] → [60°,180°]) 0.0232 RMSE (E=0.0163, 1.95°, R²=0.9984, Equiv=1.92×10⁻⁶) 1.0232 1.6208 (339p) 1.7495 (1,180p) 69.9× – 75.4× lower RMSE
Kepler Energy + LRL (i∈[0°,25°] → [65°,180°]) 0.0065 RMSE (E=0.0079, 1.31°, R²=0.9985, Equiv=5.97×10⁻⁷) 0.4501 0.6681 (339p) 0.7098 (1,180p) 102.8× – 109.2× lower RMSE
Slater–Koster p-p (z>0.65 → z<-0.35) 0.0276 RMSE (MAE=0.0196, R²=0.9944, Invar=5.72×10⁻⁷) 0.5867 0.9160 (381p) 0.7655 (1,217p) 27.7× – 33.2× lower RMSE
Molecular Chirality ([0°,35°] → [60°,180°]) 100.00% acc (CE=0.0000, Invar=6.60×10⁻⁷, <3 epochs) 51.08% (Std Split: 53.58%) 47.83% (247p) 46.92% (1,027p) 100% vs. 47–48% (chance 33.3%)

The chirality result is the clearest demonstration of why the algebra matters. Standard DFF and non-equivariant QNN-Std hover between 46.9% and 53.6% when the molecule rotates into unseen orientations—barely better than flipping a three-sided coin (33.3%). Because two stacked LAYER_SO3_EQUIVARIANT layers naturally compose a cross product b₂ × b₃ followed by a dot product with b₁ into the invariant scalar channel, QNN-SO3-Equiv (225 active parameters) hits 100.00% OOD test accuracy with 0.0000 cross-entropy in fewer than 3 epochs under both AdamW and SGD+Momentum.

Four-panel benchmark chart comparing QNN-SO3-Equiv, QNN-Std, DFF param-matched, and DFF width-matched on Tier 2 out-of-distribution physics tasks: H2O Energy and Force (75.4x lower RMSE), Kepler Orbit Energy and LRL (109x lower RMSE), Slater-Koster p-p hopping (33.2x lower RMSE), and Molecular Chirality accuracy (100.0 percent OOD in under 3 epochs versus 46.9 to 53.6 percent), plus a 2-hidden-layer footprint summary strip
Tier 2 physics OOD benchmark (5-seed means): QNN-SO3-Equiv generalizes across unseen 3D orientations with 28× to 109× lower error and 100.0% chirality accuracy, using 3.6× fewer parameters than width-matched DFF.

Footprint and CPU speed on 2-hidden-layer physics networks

Because each quaternion connection packs four real channels into one 4-float weight, an equivariant QNN does not just win on accuracy—it is smaller and faster on CPU than a width-matched real MLP. On the 2-hidden-layer mol_pes_ood benchmark (2 → 8 → 6 → 1 quaternion vs. 8 → 32 → 24 → 4 real):

Metric (mol_pes_ood, CPU) QNN-SO3-Equiv (2→8→6→1) DFF [width=] (8→32→24→4) Comparison
Active / stored parameters 325 / 340 1,180 / 1,180 3.6× fewer active params
Serialized weights.bin 1,508 B 4,844 B 3.2× smaller checkpoint
Peak heap memory 16.3 KiB 35.1 KiB 2.2× smaller heap
Training wall time 271.5 ms 389.8 ms ~30% faster training
Single-sample inference 1.72 µs/sample 3.14 µs/sample 1.8× faster inference

Beyond 3D geometry: where QNNs win, tie, and where real MLPs still win

A good architectural deep dive shouldn't cherry-pick only the tasks where its idea shines. Glades ML's benchmark suite also tests TYPE_QNN on four non-geometric problems—binary logic parity, financial OHLC time series, and two classic UCI tabular datasets—precisely to map where quaternion structure helps and where it gets in the way.

1. Binary XOR and 4-bit odd parity (where ACT_SPLIT shines and ACT_POLAR_TANH fails)

  • XOR (20 seeds): A minimal QNN 1 → 1 → 1 (13 parameters) solves XOR 20/20 times (BCE 0.00075), compared to 9/20 for a minimal real DFF 2 → 2 → 1.
  • 4-bit odd parity (20 seeds): A minimal QNN 1 → 3 → 1 with LAYER_STANDARD and ACT_SPLIT (37 parameters) solves 4-bit parity 20/20 times (BCE 0.00058), beating a parameter-matched DFF 4 → 6 → 1 (15/20).
  • Critical activation lesson: Switching that exact same 4-bit parity network from ACT_SPLIT to ACT_POLAR_TANH drops its solve rate from 20/20 to 0/20. Parity is inherently an axis-aligned corner-separation problem, and radial-only squashing refuses to crease along individual coordinate axes.

2. Dow Jones OHLC market bars (coupled 4-tuples)

Financial candlestick bars (Open, High, Low, Close) are not 3D rotations, but they are tightly coupled four-number tuples where every component lives on the same price scale and obeys joint ordering constraints (Low ≤ Open, Close ≤ High). Packing each bar into one quaternion (PACK_GROUPS_OF_4):

  • QNN 1 → 4 → 1 (LAYER_STANDARD, ACT_SPLIT, AdamW, 49 parameters) reaches $2.08 ± $0.07 RMSE (R² = 0.9962)—matching a 2×-larger DFF 4 → 16 → 1 (97 parameters, $2.08) and beating a parameter-matched DFF 4 → 8 → 1 (49 parameters) by 1.76× to 1.91×.
  • Under aggressive SGD+Momentum (lr = 0.05), the QNN stays stable at $2.16 RMSE, whereas the real DFF destabilizes to $8.39 ± $12.42.

3. Wine and Iris tabular classification (where real DFF holds its ground)

  • Wine (13 features, 25 runs): Using ONE_QUAT_PER_FEATURE with weight decay wd2 = 1e-2, TYPE_QNN matches 97.78% test accuracy while achieving the lowest test cross-entropy (0.0565 vs. 0.0586–0.0668 for DFF). Using PACK_GROUPS_OF_4 delivers 97.67% accuracy with 53% fewer parameters (195 vs. 411).
  • Iris low-data (iris40, 60 train / 90 test) with weak L2 (1e-4): Here TYPE_DFF wins clearly (96.40–96.98% accuracy, CE 0.088–0.138) over unregularized TYPE_QNN (95.29–96.13%, CE 0.170–0.194). When features are four small botanical measurements with no rotational or 4-tuple symmetry and regularization is light, the Hamilton coupling introduces extra inductive bias that simply isn't needed.

Honest engineering boundaries in Glades ML today

Before reaching for a QNN, weigh three concrete engineering realities:

  1. CPU-only execution today: TYPE_QNN currently runs on CPU in Glades ML, while TYPE_DFF has native CUDA and BLAS acceleration. For wide networks or large mini-batches on a GPU, TYPE_DFF has far higher raw throughput.
  2. 4× FLOPs per stored parameter: One Hamilton product executes 16 multiplies and 12 adds using 4 floats (4 multiplies per parameter vs. 1 in real matmul). A QNN is faster wall-clock only when its parameter savings let you shrink layer width (as in the 325 vs. 1,180 Tier 2 physics comparison) or when its sample efficiency cuts required data and epochs.
  3. Symmetry must match the task: Exact SO(3) equivariance is a superpower for 3D geometry and physics, and a handicap for axis-aligned logic or unrelated tabular columns. Pick the layer mode and activation deliberately.
Decision map routing problems to three Glades ML architectures: QNN SO(3)-Equivariant with LAYER_SO3_EQUIVARIANT and ACT_POLAR_TANH for 3D geometry and physics, QNN Standard with LAYER_STANDARD and ACT_SPLIT for coupled 4-tuples and parity, and Standard Real DFF for general tabular data and GPU scale, with a bottom engineering boundary callout noting CPU-only QNN execution and 4x FLOPs per stored parameter
Glades ML architecture decision guide: match the algebra to the structure of your data, and keep CPU-only execution and FLOPs-per-parameter trade-offs in view.

Trying it yourself in Glades ML

Configuring an SO(3)-equivariant QNN in Glades ML takes one TrainingConfig::qnn block on a standard NNetwork constructed with TYPE_QNN. Here is the exact C++98 setup from unit-tests/Backend/Machine Learning/qnn-test.cpp for the Tier 2 H₂O potential energy + force OOD benchmark:

cpp
glades::QuaternionInput pesOod;
pesOod.loadMolecularPES(192u, 192u, 42u, /*oodOrientation=*/true);

std::vector<unsigned int> qH;
qH.push_back(8u);
qH.push_back(6u);
glades::NNInfo* qInfo = make_qnn_info(
    "qnn_mol_pes_ood", 16, 0.015f, 0.0f, 1e-5f,
    qH, glades::GMath::TANH, 4, glades::OutputLayerInfo::REGRESSION, glades::GMath::LINEAR);

glades::NNetwork qNet(qInfo, glades::NNetwork::TYPE_QNN);
delete qInfo;
qNet.setSeed(42u);

glades::TrainingConfig qCfg = qNet.getTrainingConfig();
qCfg.optimizer.type      = glades::OptimizerConfig::ADAMW;
qCfg.qnn.inputPacking    = glades::QuaternionConfig::PACK_GROUPS_OF_4;
qCfg.qnn.outputReadout   = glades::QuaternionConfig::READOUT_SPLIT_COMPONENTS;
qCfg.qnn.layerMode       = glades::QuaternionConfig::LAYER_SO3_EQUIVARIANT;
qCfg.qnn.activationMode  = glades::QuaternionConfig::ACT_POLAR_TANH;
qNet.setTrainingConfig(qCfg);

glades::Terminator term;
term.setEpoch(350);
qNet.setTerminator(term);
qNet.train(&pesOod);

To build the library and run the QNN unit tests (algebra identities, finite-difference VJP checks, SO(3) equivariance verification, bit-exact weights.bin round-trips, and Tier 2 docs/JSON parity checks) from a Glades ML checkout:

sh
sh .configure.sh
cmake --build build -j "$(nproc)"
cd unit-tests && sh .configure.sh
cmake --build build -j "$(nproc)"
bash test.sh qnn

For the full multi-seed Tier 1 and Tier 2 comparisons against DFF [param=] and DFF [width=], see the reproducible benchmark harness under scripts/benchqnnvsdff/ and the recorded JSON telemetry in unit-tests/data/qnn_tier2_benchmark.json.

Sources and further reading

  • Glades Machine Learning — Gattic's C++98 machine-learning library containing the full QNN implementation: Backend/Machine Learning/GMath/quaternion.h, Backend/Machine Learning/Networks/sgd_qnn.cpp, Backend/Machine Learning/Networks/training_config.h, Backend/Machine Learning/Networks/network.cpp, Backend/Machine Learning/DataObjects/QuaternionInput.{h,cpp}, unit-tests/Backend/Machine Learning/qnn-test.cpp, docs/qnn-vs-dff.md, scripts/benchqnnvsdff/README.md, and unit-tests/data/qnn_tier2_benchmark.json.
  • Deterministic Execution Contract in Play2Train — companion systems deep dive on bit-reproducible simulation, floating-point guards, and versioned binary serialization inside Gattic's C++ engine.
  • Active Ragdolls with Staged Recovery in Play2Train — companion physics deep dive on 3D joint constraints, angular drives, and automated stability gates.