File size: 14,215 Bytes
1cc8d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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<string, Float32Array> = 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<number>, 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<number>): 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<number>, 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]!;
  }
}