/** * Deterministic hashing utilities — bit-identical TypeScript port of * `spira/hashing.py`. All 64-bit arithmetic uses BigInt; 32-bit paths use * plain numbers with >>> 0 semantics. */ export const MASK32 = 0xffffffff; export const MASK64 = 0xffffffffffffffffn; const FNV_OFFSET_BASIS = 0xcbf29ce484222325n; const FNV_PRIME_64 = 0x100000001b3n; /** Lane salts (one per hippocampal context slot). */ export const LANE_SALTS: bigint[] = [ 0x9e3779b97f4a7c15n, 0xbf58476d1ce4e5b9n, 0x94d049bb133111ebn, 0x2545f4914f6ddc1dn, ]; /** FNV-1a 64-bit hash of a byte string (content address of a patch). */ export function fnv1a64(data: Uint8Array, seed = 0n): bigint { let h = (FNV_OFFSET_BASIS ^ (seed & MASK64)) & MASK64; for (let i = 0; i < data.length; i++) { h ^= BigInt(data[i]); h = (h * FNV_PRIME_64) & MASK64; } return h; } /** splitmix64 finalizer (MurmurHash3 helper). */ export function splitmix64(x: bigint): bigint { let z = (x + 0x9e3779b97f4a7c15n) & MASK64; z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK64; z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK64; return (z ^ (z >> 31n)) & MASK64; } /** 32-bit hippocampal lane key for one context slot. */ export function laneKey32(patchId: bigint, lane: number): number { return Number(splitmix64(patchId ^ LANE_SALTS[lane]) >> 32n) >>> 0; } /** * mulberry32 PRNG — produces the exact same float sequence as the Python * implementation, so weights regenerated from a seed are bit-identical. */ export class Mulberry32 { private state: number; constructor(seed: number) { this.state = seed >>> 0; } nextFloat(): number { this.state = (this.state + 0x6d2b79f5) >>> 0; let t = this.state; t = Math.imul(t ^ (t >>> 15), t | 1); t = (t ^ (t + Math.imul(t ^ (t >>> 7), t | 61))) >>> 0; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; } nextWeight(scale: number): number { return (this.nextFloat() * 2 - 1) * scale; } } /** * Map a patch id to k input-neuron indices (hashing trick, no embeddings). * Matches `spira.hashing.input_neurons` including the uint64 salt wrap. */ export function inputNeurons(patchId: bigint, dIn: number, kIn: number): number[] { const out: number[] = []; for (let j = 0; j < kIn; j++) { const salt = (0x51ed270b733d4c31n + BigInt(j) * 0x9e3779b97f4a7c15n) & MASK64; const h = splitmix64(patchId ^ salt); out.push(Number((h >> 32n) % BigInt(dIn))); } return out; }