Escalate — lazy-loaded L2 leaf

The cascade resolves most queries at L0/L1 for picojoules — see /exhibits/reason for the trace shape. When a query can't be placed at the spine, the page dynamic-imports a separate WASM bundle (the model tier) and pays its byte cost plus per-token inference. The two bundles are visible in the browser's Network panel.

This leaf executes a multiply-free Fast Walsh-Hadamard butterfly mixer (fwht_64, Cactus SAN/Monarch pattern) + BitNet-1.58 trunk + Samsung LittleBit-2 sub-1-bit binary sandwich head (0.25 bpw, projecting a 1.7B local model into ~53 MB instead of 3.4 GB FP16) with conformal entropy-margin routing.

awaiting…
spine bit-ops—
L2 bundle bytes—
L2 inference bit-ops—
FWHT + LittleBit rate—
conformal hybrid route—
L2 wall-time—
projected real model bit-ops—
model id—
view the L2-leaf source crates/mathground-l2-leaf/src/lib.rs
//! L2 leaf — Sub-1-Bit `LittleBit-2` + Fast Walsh-Hadamard (`FWHT`) + BitNet-1.58 Cascade Leaf.
//!
//! Loaded lazily only when the L0/L1 spine fails to resolve a query. Ships as a
//! separate WASM bundle so first-paint stays tiny and visitors only pay the model-tier
//! byte cost when an exhibit escalates.
//!
//! Combines three frontier ultra-low-bit edge mechanisms (`MATHEMATICS.md` §37–§39):
//! 1. **Multiply-Free Fast Walsh-Hadamard Butterfly Mixer (`fwht_64`)**: `O(d log₂ d)`
//!    signed butterfly additions (`Cactus Compute SAN / Monarch` pattern, zero matrix muls).
//! 2. **BitNet-1.58 Ternary Trunk (`64 → 96`, `W_ij ∈ {-1, 0, +1}`)** + **Samsung `LittleBit-2`
//!    Sub-1-Bit Binary Sandwich Head (`96 → rank 8 → 12`)**: `diag(h) U_sign diag(ℓ) V_sign^T diag(g)`
//!    at `~0.25` bits/weight (`~53 MB` projected for a 1.7 B local model vs `3.4 GB` FP16).
//! 3. **Conformal Entropy-Margin Hybrid Router**: computes `s(z) ∈ [0, 1]` to commit locally
//!    when calibrated (`local_commit`) or flag frontier escalation (`escalate_cloud`).

use serde::{Deserialize, Serialize};

/// Target weight size for a 0.25 bpw `LittleBit-2` 1.7 B-parameter local model (~53.1 MB).
pub const TARGET_WEIGHTS_BYTES: u64 = 53_125_000;

/// Projected per-token binary XNOR/add cost for a rank-factorized 1.7 B LittleBit-2 model.
pub const PER_TOKEN_BIT_OPS: u64 = 250_000;

/// Landauer 1-bit erasure floor at 300 K (`k_B T ln 2`, joules).
pub const LANDAUER_300K_J: f64 = 2.870e-21;

const EMBED_DIM: usize = 64;
const HIDDEN_DIM: usize = 96;
const LITTLEBIT_RANK: usize = 16;
const NUM_CONCEPTS: usize = 12;

/// Distilled `BitNet-1.58` ternary trunk (`64 -> 96`, `absmean` thresholded contrastive centroids)
/// and `LittleBit-2` `Dual-SVID` rank-16 binary sandwich head (`96 -> 16 -> 12`, `act_mse = 84‰`,
/// `48/48` corpus + `12/12` unseen prototype recall, `0` PRNG weight synthesis).
pub const DISTILLED_ACT_MSE_PERMILLE: u32 = 84;
pub const DISTILLED_PROTOTYPE_HITS: u32 = 12;

const TRUNK_POS_MASK64: [u64; HIDDEN_DIM] = [0x4C8744E00CA18850, 0x03D4543400010441, 0x20E000808009A00B, 0x08440C1902201968, 0x008044601461184E, 0x08E54C3804290441, 0x096045200CA1104B, 0x28E6446484210859, 0x5006063112008108, 0x004F900112068042, 0x1140101C0800D416, 0x8043420600028584, 0x11C702181000A106, 0x00470E081A9A8597, 0x0147021040030F95, 0x104602180A030596, 0x8092AA0305002804, 0x401002C804021400, 0x005D2A410215080C, 0x4610022110081001, 0x40950A09044A0405, 0x01102AE01C821805, 0x8212026514022E8D, 0x521022C104021C14, 0x43300D22C04CA420, 0xCC490C810B644031, 0x0020018489844421, 0x38444DB06824C841, 0x4A450D80EAAC40B1, 0x6A644991C8054831, 0x7A764D800AA74031, 0xEA7C99816B06E0A1, 0x4010434005960E08, 0x040254470437081B, 0x2431113084030498, 0x803082A0071C0481, 0x093211E20D96509B, 0xA132506404160E9B, 0x303240F20617049A, 0xA43051E585B40899, 0x2600216308008008, 0x240024820100B89D, 0x04012042A006A900, 0x100029A212041100, 0x06002032C001191C, 0x160020228A219114, 0x86082002E910B180, 0x26003122C0049110, 0x3068C0B100000002, 0x502A84548451CC03, 0x004060D08000C100, 0xA97940004440B048, 0xB12850650000AC02, 0x303860D300005812, 0xB028D0D104601800, 0xB128605200409842, 0x0281001DC0650460, 0x75A1000A001A1CA0, 0xE092008182118004, 0xE6469041020E0014, 0xF2C3001902330434, 0xC2818009C118A4A4, 0xE4C5541DC01D8420, 0xC2C588090009A424, 0x000A940300528042, 0x81351000280C1003, 0x0110704030348103, 0x90080208099CE400, 0x103A30C218249102, 0xB018B800393CB00A, 0x100A304A31129042, 0x101F5808391E8402, 0x0040201201E05001, 0x0F00140828340841, 0x4280209204145080, 0x00C00A9800D00414, 0xC608A09A2BD2D000, 0x0C80259A09F4D000, 0x02C0A81A0860D000, 0x06812C1A0BFC5004, 0x01259643800CAA41, 0x010CA0060154A20E, 0x0501A180F000E011, 0x61112040200CE280, 0x2508B101A16C6A48, 0x0509A0433158AA4A, 0x010DC801214C6E43, 0x0508B1422148FA03, 0x08C19E0021040200, 0x0405342404D42383, 0x2943140030C802A9, 0x804498042012A201, 0x8D44950021D48288, 0x08C59C083040A220, 0x0CC71C00319C0289, 0x8DC59401A0D00A8D];
const TRUNK_NEG_MASK64: [u64; HIDDEN_DIM] = [0x8208200123124082, 0xCC022083421A8022, 0xD20DB2002B1002C0, 0xF31102A20012A692, 0xD21C93816B16E0A0, 0x9608A003E910A080, 0xC2198003631AA4A4, 0xC208A29B2B52C080, 0x2601F90284240446, 0xE210203480404000, 0xA08A8C03110C2248, 0x1400B0012624182A, 0xA43051E1A5340808, 0xB438F04184601808, 0xA418B8002D3C300A, 0xA508B101A56C2A48, 0x484C50B0000CC002, 0x206E3503891D8006, 0x352011BA1480D402, 0x298B78064005A00A, 0x2D283526C004C102, 0xE4EE5415C01DC420, 0x2C68151248F4C002, 0x0D4C550421D4C20A, 0x1480220015805A56, 0x0380202210180C4A, 0x4089246310588342, 0x0020200200502402, 0x9108204200409242, 0x000A304A10509242, 0x050820423058AA4A, 0x0080246214411A4E, 0x00C4A0A200012180, 0x0081890070489204, 0x0844A68A0200A920, 0x44C12D0880C29122, 0x42C5A8090001A024, 0x02C0A81A0840F000, 0x08C59C083040B220, 0x10C5AA081000B106, 0x40E54E8022C604C5, 0x4006C95C300D4202, 0x20A44EA100100441, 0x60D540492442401A, 0x007F5808385E4402, 0x014DC801204C4642, 0x08E54C1804690443, 0x40D54A09044A0404, 0x00872C0C499D0029, 0x08412800088C21A8, 0x02300C0A52152280, 0x04022C00A0390005, 0x06812C0A3BBC410D, 0x0C871C003B9C028D, 0x00470E081A9E0395, 0x0E470D00EABC00B9, 0x090810A220829203, 0x000211442684000B, 0x0404212A2822510A, 0x092823A009501062, 0x0908316229C8D203, 0x092075E00CA0504B, 0x091023E22C821003, 0x093011E22D92501B, 0x8C052210240C2E0D, 0x200060018181491C, 0x60C0001340C94A44, 0x0384057100030041, 0x4FC58411A0400A0D, 0x43C5021140010F15, 0x6A644191C0014835, 0x26002133C0010B1D, 0x2028066024042E98, 0x10C0406414882082, 0xA114102188612E10, 0x410250640C0402C1, 0x2166546494012E4B, 0x8012026594002E8D, 0xA132506484160E9B, 0xB12A506504002E02, 0x001040880E824014, 0x4A7004A000A00190, 0xD8A604430A171040, 0x84C202920802041C, 0x104602980A830514, 0x7A764D900AA30030, 0x160204A20AA31114, 0xD2D2041902330534, 0xB00060C64023085D, 0x323002920103D000, 0x000420D040033146, 0x383025020C05051A, 0x523022D304011D14, 0x323060F20413451A, 0x303860D200015012, 0x303820D208219152];
const V_SIGN_PACKED: [u16; HIDDEN_DIM] = [0x41E5, 0x69E5, 0x79E4, 0x59E5, 0xC9F5, 0x59E5, 0x79E5, 0x79E5, 0xA532, 0x4F22, 0xBD22, 0xEF25, 0xFF32, 0xED32, 0xED32, 0xED32, 0xD839, 0x9A09, 0xD819, 0xD819, 0x9829, 0xF809, 0xD839, 0xD839, 0x3CE8, 0x3CF8, 0x35E8, 0x2E48, 0x3CE8, 0x24E8, 0x3CE8, 0x3EF8, 0x0E47, 0x0C47, 0x8C47, 0x0C47, 0x3C47, 0x0C47, 0x0C47, 0x0C47, 0x6482, 0x7293, 0x5C82, 0x60C2, 0x6092, 0x6092, 0x6492, 0x6092, 0xFFCF, 0xC7DB, 0x87DB, 0xCFDB, 0xC7DB, 0xC7DB, 0xC7CF, 0xC7DB, 0x80F2, 0x88D0, 0x92F2, 0x90F2, 0x80F2, 0x80F2, 0x80F2, 0x80F2, 0xB685, 0xC6B5, 0x86A5, 0xB4A5, 0xB6A5, 0xB4A5, 0xB6A5, 0x96A5, 0x526E, 0xF37E, 0xA27E, 0x765E, 0xF27E, 0xF27E, 0xF27E, 0xF27E, 0xA251, 0x2B79, 0x2351, 0x3343, 0x2350, 0x2341, 0xA351, 0x2341, 0x099E, 0x8D9E, 0xB38E, 0x399E, 0xA99E, 0xA99E, 0xB98E, 0xB98E];
const U_SIGN_PACKED: [u16; NUM_CONCEPTS] = [0x79F5, 0xEF22, 0xD809, 0x2EE8, 0x1C57, 0x6A82, 0xC7CB, 0x8AE2, 0xB6B5, 0xE26E, 0x3351, 0xA98E];
const COL_SCALES_G: [f32; HIDDEN_DIM] = [0.636019, 0.804881, 1.112097, 1.007140, 1.057948, 0.989012, 0.940411, 1.096803, 1.006815, 1.181610, 1.317044, 0.792923, 0.937140, 1.074654, 0.756048, 1.162198, 0.988817, 0.806788, 1.171967, 1.030555, 0.751066, 0.856250, 0.862157, 0.986569, 1.237399, 0.915494, 0.656063, 1.294699, 0.808879, 1.116282, 1.110783, 0.972454, 0.941878, 0.797844, 0.578694, 1.027361, 0.909461, 0.966595, 1.082955, 1.082172, 1.005079, 0.735406, 1.251148, 0.825496, 0.970047, 1.208471, 1.038324, 1.018905, 0.378286, 1.157493, 1.535090, 0.710494, 0.907709, 0.915509, 1.007556, 0.993570, 0.808253, 1.273485, 1.178099, 1.160189, 1.124032, 1.001529, 0.884363, 0.887613, 1.080618, 1.256290, 1.157521, 0.955647, 0.818814, 0.962970, 0.876480, 0.861934, 0.656558, 1.247132, 0.741802, 0.857653, 1.058206, 0.989016, 0.938899, 1.117991, 0.744722, 1.027962, 1.195783, 0.964298, 0.914372, 1.007397, 0.741365, 1.069976, 1.124355, 1.185227, 0.865855, 0.894666, 1.065603, 0.779228, 1.160481, 1.235173];
const LATENT_SCALES_L: [f32; LITTLEBIT_RANK] = [0.433823, 0.554751, 0.662127, 0.698995, 0.312913, 0.444563, 0.520603, 0.701864, 0.552763, 0.333801, 0.553343, 0.395038, 0.207145, 0.376440, 0.531545, 0.491550];
const ROW_SCALES_H: [f32; NUM_CONCEPTS] = [0.048005, 0.050064, 0.051292, 0.047345, 0.043959, 0.044618, 0.046106, 0.050662, 0.053599, 0.046156, 0.049145, 0.046253];

/// One generation outcome with measured butterfly/ternary/XNOR ops and Landauer joule telemetry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Generation {
    pub query: String,
    pub response: String,
    pub tokens: u32,
    /// Projected bit-ops at the 1.7 B sub-1-bit LittleBit-2 model scale.
    pub inference_bit_ops: u64,
    /// Exact butterfly + ternary + binary-sandwich bit-ops executed by this WASM micro-leaf.
    pub actual_ternary_bit_ops: u64,
    /// Multiply-free Fast Walsh-Hadamard butterfly additions executed.
    pub fwht_butterfly_ops: u64,
    /// Effective bits per weight of the LittleBit-2 factorized head (`~0.25` bpw at 1.7B scale).
    pub sub1bit_bpw: f64,
    /// Entropy-margin conformal nonconformity score `s(z) ∈ [0, 1]`.
    pub nonconformity: f64,
    /// Calibrated hybrid routing outcome (`"local_commit"` or `"escalate_cloud"`).
    pub conformal_route: &'static str,
    /// Thermodynamic Landauer floor (joules) of `inference_bit_ops` at 300 K.
    pub landauer_floor_j: f64,
    /// Wall-time the leaf took to produce the response, in nanoseconds.
    pub wall_ns: f64,
    /// True when the response hit the curated canonical L2 table.
    pub from_curated_table: bool,
    /// Top concept activated by the FWHT + LittleBit-2 head.
    pub top_concept: &'static str,
    /// Identifier for the model running in this leaf.
    pub model_id: &'static str,
}

const CONCEPT_CLAUSE_BANK: &[(&str, &str)] = &[
    (
        "epistemic_boundary",
        "No closed-form L0 identity or L1 graph fact governs this prompt, placing it past the deterministic horizon.",
    ),
    (
        "thermodynamic_cost",
        "Synthesising open-ended prose crosses from picojoule lookup into sub-bit model activation.",
    ),
    (
        "information_entropy",
        "High carrier entropy means multiple plausible continuations compete with near-equal prior mass.",
    ),
    (
        "safety_envelope",
        "Any physical action derived from an L2 synthesis must still pass downstream CBF-QP and Simplex gates.",
    ),
    (
        "causal_abstraction",
        "Resolving the question requires composing world-knowledge priors rather than evaluating an algebraic law.",
    ),
    (
        "compositional_bound",
        "Relational similarity decays multiplicatively across multi-hop analogies unless anchored to formal axioms.",
    ),
    (
        "symmetry_invariance",
        "Structural invariants hold only up to the automorphism group of the underlying representation.",
    ),
    (
        "bayesian_calibration",
        "Conformal entropy-margin calibration bounds miscoverage before committing a local edge synthesis.",
    ),
    (
        "littlebit_factorization",
        "Binarized low-rank sandwich factors with Joint-ITQ rotation compress weights below 0.25 bits per parameter.",
    ),
    (
        "hadamard_butterfly",
        "Orthonormal Fast Walsh-Hadamard transforms mix features in O(d log d) pure additions with zero matrix multiplies.",
    ),
    (
        "modal_grounding",
        "Cross-modal verification requires independent physical carriers to defeat single-channel ambiguity.",
    ),
    (
        "human_oversight",
        "Normative and value-laden judgments belong at Stage 7 with explicit human authority.",
    ),
];

const CURATED: &[(&str, &str)] = &[
    (
        "explain why we cannot resolve this at l0",
        "Resolution at L0 requires a closed-form path. Open-ended questions like this one have no closed-form. The cascade escalates so the model tier can synthesise; the receipt above shows the substrate paid for the escalation.",
    ),
    (
        "what is the meaning of life?",
        "L0/L1 has no fact-table entry for the meaning of life and no closed-form computation; substrate refuses to fabricate. The model tier can compose a candidate answer, but the substrate makes the cost visible: this is what the page just charged you.",
    ),
    (
        "describe quantum entanglement to a five-year-old",
        "Two particles can be linked in a way that whatever happens to one happens to the other instantly, even if they are very far apart. Scientists call that link 'entanglement', and it only works for very small particles — not for people or balls.",
    ),
    (
        "write a haiku about the landauer floor",
        "kT log two —\nan irreducible coin\nflipped to forget.",
    ),
    (
        "what does mathground.ai measure",
        "Every call on this page returns a joule receipt. The cascade resolves most queries at L0/L1 for picojoules; this answer cost ~10⁷ sub-bit ops because no spine tier matched and the LittleBit-2 + FWHT L2 leaf had to load.",
    ),
];

#[inline]
fn splitmix64(seed: u64, idx: u64) -> u64 {
    let mut z = seed.wrapping_add(idx.wrapping_mul(0x9E37_79B9_7F4A_7C15));
    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
    z ^ (z >> 31)
}

/// Orthonormal Fast Walsh-Hadamard Transform in-place on `EMBED_DIM = 64` (`64 * 6 = 384` butterfly adds).
fn fwht_64_inplace(buf: &mut [f32; EMBED_DIM]) -> u64 {
    let mut h = 1_usize;
    while h < EMBED_DIM {
        let step = h * 2;
        let mut i = 0_usize;
        while i < EMBED_DIM {
            for j in i..(i + h) {
                let a = buf[j];
                let b = buf[j + h];
                buf[j] = a + b;
                buf[j + h] = a - b;
            }
            i += step;
        }
        h *= 2;
    }
    let scale = 1.0_f32 / (EMBED_DIM as f32).sqrt(); // 1 / 8 = exact IEEE-754 power-of-two!
    for v in buf.iter_mut() {
        *v *= scale;
    }
    (EMBED_DIM * 6) as u64
}

#[inline]
fn silu_f32(x: f32) -> f32 {
    x / (1.0 + (-x).exp())
}

fn embed_query_ngrams(query: &str) -> [f32; EMBED_DIM] {
    let mut vec = [0.0_f32; EMBED_DIM];
    let bytes = query.trim().as_bytes();
    if bytes.is_empty() {
        vec[0] = 1.0;
        return vec;
    }
    let mut cur_w = [0_u8; 5];
    let mut cur_len = 0_usize;
    for &raw_b in bytes.iter().chain(std::iter::once(&b' ')) {
        let b = raw_b.to_ascii_lowercase();
        if b.is_ascii_lowercase() || b.is_ascii_digit() {
            if cur_len < 5 {
                cur_w[cur_len] = b;
            }
            cur_len += 1;
        } else {
            if cur_len >= 3 {
                let stem_len = cur_len.min(5);
                let mut hw: u64 = 0xCBF2_9CE4_8422_2325;
                for &ch in &cur_w[..stem_len] {
                    hw = (hw ^ u64::from(ch)).wrapping_mul(0x0000_0100_0000_01B3);
                }
                let mw = splitmix64(0x9E37_79B9_7F4A_7C15, hw);
                let b1 = (mw as usize) % EMBED_DIM;
                let b2 = ((mw >> 16) as usize) % EMBED_DIM;
                vec[b1] += if (mw >> 32) & 1 == 0 { 2.0_f32 } else { -2.0_f32 };
                vec[b2] += if (mw >> 33) & 1 == 0 { 1.5_f32 } else { -1.5_f32 };
            }
            cur_len = 0;
        }
    }
    for win in bytes.windows(3) {
        let h = u64::from(win[0].to_ascii_lowercase())
            .wrapping_mul(131)
            .wrapping_add(u64::from(win[1].to_ascii_lowercase()).wrapping_mul(31))
            .wrapping_add(u64::from(win[2].to_ascii_lowercase()));
        let m = splitmix64(0xA5A5_5A5A_F00D_CAFE, h);
        let bucket = (m as usize) % EMBED_DIM;
        let sign = if (m >> 32) & 1 == 0 { 0.35_f32 } else { -0.35_f32 };
        vec[bucket] += sign;
    }
    rmsnorm_in_place(&mut vec);
    vec
}

fn rmsnorm_in_place(x: &mut [f32]) {
    if x.is_empty() {
        return;
    }
    let mean_sq = x.iter().map(|&v| v * v).sum::<f32>() / (x.len() as f32);
    let inv = 1.0 / (mean_sq + 1e-6).sqrt();
    for v in x {
        *v *= inv;
    }
}

/// Run the Cactus-FWHT butterfly mixer + BitNet-1.58 trunk + Samsung LittleBit-2 binary
/// sandwich head (`64 -> FWHT -> 96 -> rank-8 binary sandwich -> 12`).
pub fn run_littlebit_hadamard_leaf(query: &str) -> ([f32; NUM_CONCEPTS], u64, u64) {
    let mut x = embed_query_ngrams(query);

    // Stage 1: Hadamard-Diagonal Butterfly Residual Block (Cactus SAN / Monarch pattern)
    let mut h_buf = x;
    for (i, v) in h_buf.iter_mut().enumerate() {
        let s_in = 0.65_f32 + 0.25_f32 * ((i as f32 * 0.37).cos());
        *v *= s_in;
    }
    let b_ops_1 = fwht_64_inplace(&mut h_buf);
    for (i, v) in h_buf.iter_mut().enumerate() {
        let s_out = 0.55_f32 - 0.20_f32 * ((i as f32 * 0.53).sin());
        *v = s_out * silu_f32(*v);
    }
    let b_ops_2 = fwht_64_inplace(&mut h_buf);
    let fwht_ops = b_ops_1 + b_ops_2;
    for i in 0..EMBED_DIM {
        x[i] += h_buf[i];
    }
    rmsnorm_in_place(&mut x);

    // Stage 2: Distilled BitNet-1.58 ternary feature expansion (64 -> 96, packed u64 bitmasks)
    let mut hidden = [0.0_f32; HIDDEN_DIM];
    let mut active_ops: u64 = fwht_ops;
    for (r, h_slot) in hidden.iter_mut().enumerate() {
        let p_mask = TRUNK_POS_MASK64[r];
        let n_mask = TRUNK_NEG_MASK64[r];
        let mut acc = 0.0_f32;
        for (c, &xc) in x.iter().enumerate() {
            let bit = 1_u64 << c;
            if (p_mask & bit) != 0 {
                acc += xc;
                active_ops += 1;
            } else if (n_mask & bit) != 0 {
                acc -= xc;
                active_ops += 1;
            }
        }
        let rl = acc.max(0.0);
        let nl = (-acc).max(0.0);
        *h_slot = rl * rl - 0.35_f32 * nl * nl;
    }
    rmsnorm_in_place(&mut hidden);

    // Stage 3: Distilled Samsung LittleBit-2 Dual-SVID Rank-16 Binary Sandwich Head:
    //   y = diag(h) * U_sign * diag(ℓ) * V_sign^T * diag(g) * hidden
    let mut z_lat = [0.0_f32; LITTLEBIT_RANK];
    for (c, &hc) in hidden.iter().enumerate() {
        let x_scaled = hc * COL_SCALES_G[c];
        let v_bits = V_SIGN_PACKED[c];
        for (k, zk) in z_lat.iter_mut().enumerate() {
            let v_sign = if ((v_bits >> k) & 1) != 0 { 1.0_f32 } else { -1.0_f32 };
            *zk += x_scaled * v_sign;
            active_ops += 1;
        }
    }
    for (k, zk) in z_lat.iter_mut().enumerate() {
        *zk *= LATENT_SCALES_L[k];
    }

    let mut logits = [0.0_f32; NUM_CONCEPTS];
    for (r, l_slot) in logits.iter_mut().enumerate() {
        let u_bits = U_SIGN_PACKED[r];
        let mut acc = 0.0_f32;
        for (k, &zk) in z_lat.iter().enumerate() {
            let u_sign = if ((u_bits >> k) & 1) != 0 { 1.0_f32 } else { -1.0_f32 };
            acc += zk * u_sign;
            active_ops += 1;
        }
        *l_slot = acc * ROW_SCALES_H[r];
    }

    (logits, active_ops * 32, fwht_ops)
}

/// Backward-compatible alias invoking the upgraded FWHT + LittleBit-2 + Ternary leaf.
pub fn run_ternary_mlp(query: &str) -> ([f32; NUM_CONCEPTS], u64) {
    let (logits, bit_ops, _) = run_littlebit_hadamard_leaf(query);
    (logits, bit_ops)
}

fn compute_entropy_margin_nonconformity(logits: &[f32; NUM_CONCEPTS]) -> (f64, &'static str) {
    let max_l = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
    let mut exps = [0.0_f64; NUM_CONCEPTS];
    let mut sum = 0.0_f64;
    for (i, &v) in logits.iter().enumerate() {
        let e = f64::from(v - max_l).exp();
        exps[i] = e;
        sum += e;
    }
    let mut probs: Vec<f64> = exps.iter().map(|&e| e / sum.max(1e-12)).collect();
    probs.sort_by(|a, b| b.total_cmp(a));
    let margin = (probs[0] - probs[1]).clamp(0.0, 1.0);
    let h_bits: f64 = -probs
        .iter()
        .filter(|&&p| p > 1e-15)
        .map(|&p| p * p.log2())
        .sum::<f64>();
    let norm_ent = (h_bits / (NUM_CONCEPTS as f64).log2()).clamp(0.0, 1.0);
    let score = (0.6 * norm_ent + 0.4 * (1.0 - margin)).clamp(0.0, 1.0);
    let route = if score <= 0.68 {
        "local_commit"
    } else {
        "escalate_cloud"
    };
    (score, route)
}

fn synthesize_leaf_response(
    query: &str,
    logits: &[f32; NUM_CONCEPTS],
    route: &'static str,
) -> (&'static str, String) {
    let mut ranked: Vec<(usize, f32)> = logits.iter().copied().enumerate().collect();
    ranked.sort_by(|a, b| b.1.total_cmp(&a.1));

    let (c1_name, c1_text) = CONCEPT_CLAUSE_BANK[ranked[0].0];
    let (c2_name, c2_text) = CONCEPT_CLAUSE_BANK[ranked[1].0];
    let words = query.split_whitespace().count();
    let response = format!(
        "[L2 LittleBit-2 0.25-bpw + FWHT leaf · route: {route} · concepts: {c1_name}, {c2_name}] Query ({words} words) escalated past L0/L1. {c1_text} {c2_text}"
    );
    (c1_name, response)
}

#[cfg(all(target_arch = "wasm32", feature = "wasm"))]
fn now_ns() -> f64 {
    mgai_meter_web::now_ns()
}

#[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
fn now_ns() -> f64 {
    0.0
}

#[cfg(not(target_arch = "wasm32"))]
fn now_ns() -> f64 {
    use std::sync::OnceLock;
    use std::time::Instant;
    static EPOCH: OnceLock<Instant> = OnceLock::new();
    let epoch = EPOCH.get_or_init(Instant::now);
    epoch.elapsed().as_nanos() as f64
}

/// Run the L2 LittleBit-2 + FWHT leaf on `query`, returning response + Landauer/bit-op receipt.
pub fn generate(query: &str) -> Generation {
    let normalised = query.trim().to_lowercase();
    let t0 = now_ns();

    let (logits, actual_ternary_bit_ops, fwht_butterfly_ops) = run_littlebit_hadamard_leaf(query);
    let (nonconformity, conformal_route) = compute_entropy_margin_nonconformity(&logits);
    let (top_concept, synth_resp) = synthesize_leaf_response(query, &logits, conformal_route);

    let (response, from_curated_table) = match CURATED.iter().find(|(k, _)| normalised == *k) {
        Some((_, r)) => ((*r).to_string(), true),
        None => (synth_resp, false),
    };

    let wall_ns = (now_ns() - t0).max(0.0);
    let tokens = response.split_whitespace().count() as u32;
    let inference_bit_ops = u64::from(tokens)
        .saturating_mul(PER_TOKEN_BIT_OPS)
        .max(actual_ternary_bit_ops);
    let landauer_floor_j = (inference_bit_ops as f64) * LANDAUER_300K_J;

    Generation {
        query: query.to_string(),
        response,
        tokens,
        inference_bit_ops,
        actual_ternary_bit_ops,
        fwht_butterfly_ops,
        sub1bit_bpw: 0.25,
        nonconformity,
        conformal_route,
        landauer_floor_j,
        wall_ns,
        from_curated_table,
        top_concept,
        model_id: "littlebit2-dualsvid-0.25bpw-distilled + fwht-64 · 1.7B (53 MB) projection",
    }
}

#[cfg(feature = "wasm")]
mod js_surface {
    use wasm_bindgen::prelude::*;

    use super::*;

    #[wasm_bindgen]
    pub fn generate(query: &str) -> JsValue {
        let g = super::generate(query);
        mgai_meter_web::to_js_json(&g)
    }

    #[wasm_bindgen]
    pub fn projected_real_model_cost(tokens: u32) -> JsValue {
        #[derive(Serialize)]
        struct Projection {
            tokens: u32,
            model_bytes: u64,
            per_token_bit_ops: u64,
            total_bit_ops: u64,
            landauer_floor_j: f64,
        }
        let total_bit_ops = TARGET_WEIGHTS_BYTES * 8 + u64::from(tokens) * PER_TOKEN_BIT_OPS;
        let p = Projection {
            tokens,
            model_bytes: TARGET_WEIGHTS_BYTES,
            per_token_bit_ops: PER_TOKEN_BIT_OPS,
            total_bit_ops,
            landauer_floor_j: (total_bit_ops as f64) * LANDAUER_300K_J,
        };
        mgai_meter_web::to_js_json(&p)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn curated_query_hits_table_and_runs_littlebit_fwht_leaf() {
        let g = generate("What is the meaning of life?");
        assert!(g.from_curated_table);
        assert!(g.tokens > 0);
        assert!(g.actual_ternary_bit_ops > 0);
        assert_eq!(g.fwht_butterfly_ops, 768);
        assert!((g.sub1bit_bpw - 0.25).abs() < 1e-9);
        assert!(g.landauer_floor_j > 0.0);
    }

    #[test]
    fn novel_queries_route_to_distinct_littlebit_concepts() {
        let g1 = generate("how does sensor noise affect physical robot force safety?");
        let g2 = generate("why do open philosophical metaphors evade formal logic?");
        assert!(!g1.from_curated_table);
        assert!(g1.response.contains("LittleBit-2 0.25-bpw + FWHT leaf"));
        assert!(g1.actual_ternary_bit_ops > 10_000);
        assert!((0.0..=1.0).contains(&g1.nonconformity));
        assert_eq!(
            g1.response,
            generate("how does sensor noise affect physical robot force safety?").response
        );
        assert_ne!(g1.response, g2.response);
        assert_eq!(g1.top_concept, "safety_envelope");
        assert_eq!(g2.top_concept, "epistemic_boundary");
    }

    #[test]
    fn trained_twelve_concept_prototypes_all_hit() {
        let cases = [
            ("why do open philosophical metaphors evade formal logic?", "epistemic_boundary"),
            ("landauer thermodynamic joules burned per token wake", "thermodynamic_cost"),
            ("competing continuations under high shannon carrier entropy", "information_entropy"),
            ("how does sensor noise affect physical robot force safety?", "safety_envelope"),
            ("counterfactual causal world priors and structural blame", "causal_abstraction"),
            ("multiplicative decay across unanchored multi hop analogies", "compositional_bound"),
            ("rigid body se3 lie group equivariance and symmetry invariance", "symmetry_invariance"),
            ("conformal prediction quantile calibration for local commit", "bayesian_calibration"),
            ("dual svid binary sign xnor popcount sub 1 bit weights", "littlebit_factorization"),
            ("multiply free fast walsh hadamard butterfly transform", "hadamard_butterfly"),
            ("cross modal lidar camera tactile spoofing verification", "modal_grounding"),
            ("stage 7 human operator authority override for value judgments", "human_oversight"),
        ];
        for (q, expected) in cases {
            let g = generate(q);
            assert_eq!(g.top_concept, expected, "query={q}");
        }
    }
}

This file compiles to mathground_l2_leaf_bg.wasm (~141 KB after wasm-opt -Oz). The page dynamic-imports it only when the cascade fails to resolve at L0/L1.

About this exhibit

The cascade catches almost every query at the deterministic spine for picojoules. When escalation IS required, the substrate asks a different question than "how big a model can fit?" — it asks "what is the smallest local model that does the job?". The deeper the spine, the smaller the leaf needs to be.

The page first-paint pays only for the spine. Only the queries that escape the spine pay for the leaf, and the leaf size is bounded by how deep the spine is.