import type { ModelConfig, WeightArena } from '@botpsy/artifacts'; import { l2Norm, rmsNorm, rmsNormDirect, sigmoid, silu, softmaxInPlace, softplus } from './ops.ts'; import { ropeCosSin, ropeInverseFrequencies } from './attention.ts'; export interface ReferenceLayerState { kind: 'linear_attention' | 'full_attention'; /** [heads, valueDim, keyDim] runtime layout for GDN. */ recurrent: Float32Array | null; /** [channels * 3], oldest first. */ convHistory: Float32Array | null; /** [context, kvHeads, headDim] */ keyCache: Float32Array | null; valueCache: Float32Array | null; } export interface ReferenceState { processed: number; layers: ReferenceLayerState[]; /** Position triples for processed tokens; text uses identical values. */ positions: Array<[number, number, number]>; delta: number; } export interface ReferenceForwardResult { logits: Float32Array; hidden: Float32Array; normalizedHidden: Float64Array; } export class ReferenceModel { readonly weights: WeightArena; readonly config: ModelConfig; readonly contextLength: number; state: ReferenceState; lastTrace: Map = new Map(); private readonly ropeInv: Float64Array; private readonly headDim: number; private readonly hiddenSize: number; private readonly kvHeads: number; private readonly qHeads: number; private readonly groupSize: number; private readonly linearHeads: number; private readonly linearKeyDim: number; private readonly linearValueDim: number; private readonly convChannels: number; constructor(weights: WeightArena, config: ModelConfig, contextLength = 8192) { this.weights = weights; this.config = config; this.contextLength = contextLength; this.headDim = config.text.headDim; this.hiddenSize = config.text.hiddenSize; this.qHeads = config.text.numAttentionHeads; this.kvHeads = config.text.numKeyValueHeads; this.groupSize = this.qHeads / this.kvHeads; this.linearHeads = config.text.linearValueHeads; this.linearKeyDim = config.text.linearKeyHeadDim; this.linearValueDim = config.text.linearValueHeadDim; this.convChannels = this.linearHeads * this.linearValueDim * 3; this.ropeInv = ropeInverseFrequencies(this.headDim, config.text.ropeTheta, config.text.partialRotaryFactor); this.state = this.emptyState(); } emptyState(): ReferenceState { return { processed: 0, delta: 0, positions: [], layers: this.config.text.layerTypes.map((kind) => ({ kind, recurrent: kind === 'linear_attention' ? new Float32Array(this.linearHeads * this.linearValueDim * this.linearKeyDim) : null, convHistory: kind === 'linear_attention' ? new Float32Array(this.convChannels * 3) : null, keyCache: kind === 'full_attention' ? new Float32Array(this.contextLength * this.kvHeads * this.headDim) : null, valueCache: kind === 'full_attention' ? new Float32Array(this.contextLength * this.kvHeads * this.headDim) : null, })), }; } reset(): void { this.state = this.emptyState(); } cloneState(): ReferenceState { return { processed: this.state.processed, delta: this.state.delta, positions: this.state.positions.map((p) => [...p] as [number, number, number]), layers: this.state.layers.map((layer) => ({ kind: layer.kind, recurrent: layer.recurrent ? new Float32Array(layer.recurrent) : null, convHistory: layer.convHistory ? new Float32Array(layer.convHistory) : null, keyCache: layer.keyCache ? new Float32Array(layer.keyCache) : null, valueCache: layer.valueCache ? new Float32Array(layer.valueCache) : null, })), }; } restoreState(state: ReferenceState): void { this.state = state; } /** Text-only position is the processed length plus the multimodal delta. */ nextPosition(): [number, number, number] { const p = this.state.processed + this.state.delta; return [p, p, p]; } forwardToken(tokenId: number, positions?: [number, number, number], layerLimit = this.config.text.layers): ReferenceForwardResult { const embedding = this.weights.rowF32('embed_tokens', tokenId); return this.forwardEmbedding(embedding, positions, layerLimit); } /** Multimodal path: inject an already projected image embedding instead of a token row. */ forwardEmbedding(embedding: ArrayLike, positions?: [number, number, number], layerLimit = this.config.text.layers): ReferenceForwardResult { if (this.state.processed >= this.contextLength) throw new Error('reference context exhausted'); if (embedding.length !== this.hiddenSize) throw new Error('embedding width mismatch'); const position = positions ?? this.nextPosition(); this.lastTrace.clear(); const x = new Float32Array(this.hiddenSize); x.set(embedding); let hidden = x; for (let layer = 0; layer < layerLimit; layer++) { const prefix = `blk.${layer}`; const inputNorm = this.weights.f32(`${prefix}.input_norm`); const normed = rmsNorm(hidden, inputNorm, this.config.text.rmsNormEps, false); this.lastTrace.set('normed', Float32Array.from(normed)); let mixer: Float32Array; if (this.config.text.layerTypes[layer] === 'linear_attention') { mixer = this.gdnLayer(layer, normed); } else { mixer = this.attentionLayer(layer, normed, position); } const residual1 = new Float32Array(this.hiddenSize); for (let i = 0; i < this.hiddenSize; i++) residual1[i] = hidden[i]! + mixer[i]!; const postNorm = this.weights.f32(`${prefix}.post_attn_norm`); const normed2 = rmsNorm(residual1, postNorm, this.config.text.rmsNormEps, false); const gate = this.weights.matVec(`${prefix}.mlp.gate`, normed2); const up = this.weights.matVec(`${prefix}.mlp.up`, normed2); const act = new Float32Array(gate.length); for (let i = 0; i < act.length; i++) act[i] = silu(gate[i]!) * up[i]!; this.lastTrace.set('mlpAct', act); const down = this.weights.matVec(`${prefix}.mlp.down`, act); hidden = new Float32Array(this.hiddenSize); for (let i = 0; i < this.hiddenSize; i++) hidden[i] = residual1[i]! + down[i]!; } const finalNorm = this.weights.f32('final_norm'); const normalizedHidden = rmsNorm(hidden, finalNorm, this.config.text.rmsNormEps, false); const logits = this.weights.matVec('embed_tokens', normalizedHidden); this.state.positions.push(position); this.state.processed++; return { logits, hidden, normalizedHidden }; } private gdnLayer(layer: number, normed: ArrayLike): Float32Array { const prefix = `blk.${layer}.gdn`; const state = this.state.layers[layer]!; const qkv = this.weights.matVec(`${prefix}.in_qkv`, normed); this.lastTrace.set('qkv', qkv); const z = this.weights.matVec(`${prefix}.in_z`, normed); this.lastTrace.set('z', z); const a = this.weights.matVec(`${prefix}.in_a`, normed); this.lastTrace.set('a', a); const b = this.weights.matVec(`${prefix}.in_b`, normed); this.lastTrace.set('b', b); const convWeight = this.weights.f32(`${prefix}.conv`); const history = state.convHistory!; const convolved = new Float32Array(this.convChannels); for (let channel = 0; channel < this.convChannels; channel++) { const base = channel * 4; const w0 = convWeight[base]!; const w1 = convWeight[base + 1]!; const w2 = convWeight[base + 2]!; const w3 = convWeight[base + 3]!; const h0 = history[channel * 3]!; const h1 = history[channel * 3 + 1]!; const h2 = history[channel * 3 + 2]!; const current = qkv[channel]!; convolved[channel] = silu(w0 * h0 + w1 * h1 + w2 * h2 + w3 * current); history[channel * 3] = h1; history[channel * 3 + 1] = h2; history[channel * 3 + 2] = current; } this.lastTrace.set('convOut', Float32Array.from(convolved)); const q = convolved.subarray(0, this.linearHeads * this.linearKeyDim); const k = convolved.subarray(this.linearHeads * this.linearKeyDim, 2 * this.linearHeads * this.linearKeyDim); const v = convolved.subarray(2 * this.linearHeads * this.linearKeyDim); const aLog = this.weights.f32(`${prefix}.a_log`); const dtBias = this.weights.f32(`${prefix}.dt_bias`); const normWeight = this.weights.f32(`${prefix}.norm`); const recurrent = state.recurrent!; const y = new Float32Array(this.linearHeads * this.linearValueDim); for (let head = 0; head < this.linearHeads; head++) { const qBase = head * this.linearKeyDim; const qn = l2Norm(q.subarray(qBase, qBase + this.linearKeyDim), 1e-6); const kn = l2Norm(k.subarray(qBase, qBase + this.linearKeyDim), 1e-6); const scale = 1 / Math.sqrt(this.linearKeyDim); const alpha = Math.exp(aLog[head]! * softplus(a[head]! + dtBias[head]!)); const beta = sigmoid(b[head]!); const stateBase = head * this.linearValueDim * this.linearKeyDim; for (let i = 0; i < this.linearValueDim * this.linearKeyDim; i++) recurrent[stateBase + i]! *= alpha; const mem = new Float32Array(this.linearValueDim); for (let vv = 0; vv < this.linearValueDim; vv++) { let sum = 0; const rowBase = stateBase + vv * this.linearKeyDim; for (let kk = 0; kk < this.linearKeyDim; kk++) sum += recurrent[rowBase + kk]! * kn[kk]!; mem[vv] = beta * (v[head * this.linearValueDim + vv]! - sum); } for (let vv = 0; vv < this.linearValueDim; vv++) { const rowBase = stateBase + vv * this.linearKeyDim; for (let kk = 0; kk < this.linearKeyDim; kk++) { recurrent[rowBase + kk] = recurrent[rowBase + kk]! + kn[kk]! * mem[vv]!; } let out = 0; for (let kk = 0; kk < this.linearKeyDim; kk++) out += recurrent[rowBase + kk]! * qn[kk]! * scale; y[head * this.linearValueDim + vv] = out; } const normalized = rmsNormDirect( y.subarray(head * this.linearValueDim, (head + 1) * this.linearValueDim), normWeight, this.config.text.rmsNormEps, ); for (let vv = 0; vv < this.linearValueDim; vv++) { y[head * this.linearValueDim + vv] = normalized[vv]! * silu(z[head * this.linearValueDim + vv]!); } } this.lastTrace.set('gdnY', Float32Array.from(y)); const gdnOut = this.weights.matVec(`${prefix}.out_proj`, y); this.lastTrace.set('mixer', gdnOut); return gdnOut; } private attentionLayer(layer: number, normed: ArrayLike, position: [number, number, number]): Float32Array { const prefix = `blk.${layer}.attn`; const state = this.state.layers[layer]!; const qProjection = this.weights.matVec(`${prefix}.q`, normed); this.lastTrace.set('qProj', qProjection); const kProjection = this.weights.matVec(`${prefix}.k`, normed); this.lastTrace.set('kProj', kProjection); const vProjection = this.weights.matVec(`${prefix}.v`, normed); this.lastTrace.set('vProj', vProjection); const qNorm = this.weights.f32(`${prefix}.q_norm`); const kNorm = this.weights.f32(`${prefix}.k_norm`); const { cos, sin } = ropeCosSin(position, this.ropeInv); const query = new Float32Array(this.qHeads * this.headDim); this.lastTrace.set('attnQ', query); // replaced below with a copy after projection const gate = new Float32Array(this.qHeads * this.headDim); for (let head = 0; head < this.qHeads; head++) { const base = head * this.headDim * 2; const qHead = qProjection.subarray(base, base + this.headDim); const normalized = rmsNorm(qHead, qNorm, this.config.text.rmsNormEps, false); applyRope(normalized, cos, sin); query.set(normalized, head * this.headDim); gate.set(qProjection.subarray(base + this.headDim, base + this.headDim * 2), head * this.headDim); } const key = new Float32Array(this.kvHeads * this.headDim); const value = new Float32Array(this.kvHeads * this.headDim); for (let head = 0; head < this.kvHeads; head++) { const base = head * this.headDim; const kHead = rmsNorm(kProjection.subarray(base, base + this.headDim), kNorm, this.config.text.rmsNormEps, false); applyRope(kHead, cos, sin); key.set(kHead, base); value.set(vProjection.subarray(base, base + this.headDim), base); } const positionIndex = this.state.processed; const kvBase = positionIndex * this.kvHeads * this.headDim; state.keyCache!.set(key, kvBase); state.valueCache!.set(value, kvBase); const positions = positionIndex + 1; this.lastTrace.set('attnQ', Float32Array.from(query)); this.lastTrace.set('attnGate', Float32Array.from(gate)); const output = new Float32Array(this.qHeads * this.headDim); const scores = new Float64Array(positions); for (let head = 0; head < this.qHeads; head++) { const kvHead = Math.floor(head / this.groupSize); for (let t = 0; t < positions; t++) { let sum = 0; const cacheBase = (t * this.kvHeads + kvHead) * this.headDim; for (let d = 0; d < this.headDim; d++) sum += query[head * this.headDim + d]! * state.keyCache![cacheBase + d]!; scores[t] = sum / Math.sqrt(this.headDim); } softmaxInPlace(scores); for (let d = 0; d < this.headDim; d++) { let sum = 0; for (let t = 0; t < positions; t++) { sum += scores[t]! * state.valueCache![(t * this.kvHeads + kvHead) * this.headDim + d]!; } output[head * this.headDim + d] = sum * sigmoid(gate[head * this.headDim + d]!); } } this.lastTrace.set('attnOut', output); const attnProj = this.weights.matVec(`${prefix}.o`, output); this.lastTrace.set('mixer', attnProj); return attnProj; } } function applyRope(vector: Float32Array | Float64Array, cos: Float64Array, sin: Float64Array): void { const half = 32; for (let i = 0; i < 64; i++) { const original = vector[i]!; const paired = i < half ? vector[i + half]! : vector[i - half]!; vector[i] = original * cos[i]! + (i < half ? -paired : paired) * sin[i]!; } }