File size: 10,915 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
import { describe, expect, it } from 'vitest';
import { FixtureRng } from './types.ts';
import {
  gdnChunked,
  gdnDeferred,
  gdnNormalizeSequence,
  gdnSequential,
  gdnTree,
  gdnTreeSolve,
  type GdnSequence,
  type GdnTree,
} from './gdn.ts';
import { probabilityOf, type SparseDistribution } from './speculative.ts';
import {
  BOTPSY_APPLICATION_PROFILE,
  createPenaltyHistory,
  Philox4x32,
  pushPenaltyToken,
  selectCandidates,
} from './sampler.ts';
import { attentionDecode, attentionDecodeOnline } from './attention.ts';
import { QuantizedKvCache, dequantizeInt4, orthogonalMatrix, quantizeInt4, rotateGdnQK, rotateInitialState } from './transforms.ts';

function randomSequence(
  rng: FixtureRng,
  tokens: number,
  heads: number,
  keyDim: number,
  valueDim: number,
): GdnSequence {
  const q = new Float64Array(tokens * heads * keyDim);
  const k = new Float64Array(tokens * heads * keyDim);
  const v = new Float64Array(tokens * heads * valueDim);
  const g = new Float64Array(tokens * heads);
  const beta = new Float64Array(tokens * heads);
  for (let i = 0; i < q.length; i++) q[i] = rng.normal();
  for (let i = 0; i < k.length; i++) k[i] = rng.normal();
  for (let i = 0; i < v.length; i++) v[i] = rng.normal();
  for (let i = 0; i < g.length; i++) {
    g[i] = -Math.abs(rng.normal()) * 0.4;
    beta[i] = 1 / (1 + Math.exp(-rng.normal()));
  }
  return gdnNormalizeSequence({ q, k, v, g, beta, tokens, heads, keyDim, valueDim });
}

function initialState(rng: FixtureRng, heads: number, keyDim: number, valueDim: number): Float64Array {
  const state = new Float64Array(heads * keyDim * valueDim);
  for (let i = 0; i < state.length; i++) state[i] = rng.normal() * 0.1;
  return state;
}

function maxAbsDiff(a: Float64Array, b: Float64Array): number {
  let max = 0;
  for (let i = 0; i < a.length; i++) max = Math.max(max, Math.abs(a[i]! - b[i]!));
  return max;
}

describe('Gated DeltaNet reference algebra', () => {
  it('sequential, chunked, and deferred paths agree', () => {
    const rng = new FixtureRng(26418);
    let maxOutput = 0;
    let maxState = 0;
    for (let trial = 0; trial < 60; trial++) {
      const tokens = 1 + (trial % 17);
      const heads = 1 + (trial % 4);
      const keyDim = [3, 7, 16][trial % 3]!;
      const valueDim = [2, 5, 11][trial % 3]!;
      const seq = randomSequence(rng, tokens, heads, keyDim, valueDim);
      const initial = initialState(rng, heads, keyDim, valueDim);
      const sequential = gdnSequential(seq, initial);
      for (const chunkSize of [1, 2, 4, 8, 16, 64]) {
        const chunked = gdnChunked(seq, initial, chunkSize);
        maxOutput = Math.max(maxOutput, maxAbsDiff(sequential.output, chunked.output));
        maxState = Math.max(maxState, maxAbsDiff(sequential.state, chunked.state));
      }
      const deferred = gdnDeferred(seq, initial);
      maxOutput = Math.max(maxOutput, maxAbsDiff(sequential.output, deferred.output));
      maxState = Math.max(maxState, maxAbsDiff(sequential.state, deferred.state));
    }
    expect(maxOutput).toBeLessThan(1e-10);
    expect(maxState).toBeLessThan(1e-10);
  });

  it('ancestor-indexed tree solve matches explicit recurrence', () => {
    const rng = new FixtureRng(26419);
    let maxOutput = 0;
    let maxState = 0;
    for (let trial = 0; trial < 60; trial++) {
      const tokens = 1 + (trial % 17);
      const heads = 1 + (trial % 4);
      const keyDim = [3, 7, 16][trial % 3]!;
      const valueDim = [2, 5, 11][trial % 3]!;
      const seq = randomSequence(rng, tokens, heads, keyDim, valueDim);
      const parent = new Int32Array(tokens);
      for (let i = 0; i < tokens; i++) parent[i] = i === 0 ? -1 : Math.floor(rng.next() * i);
      const tree: GdnTree = { ...seq, parent };
      const initial = initialState(rng, heads, keyDim, valueDim);
      const explicit = gdnTree(tree, initial);
      const solved = gdnTreeSolve(tree, initial);
      maxOutput = Math.max(maxOutput, maxAbsDiff(explicit.output, solved.output));
      maxState = Math.max(maxState, maxAbsDiff(explicit.nodeStates, solved.nodeStates));
    }
    expect(maxOutput).toBeLessThan(1e-10);
    expect(maxState).toBeLessThan(1e-10);
  });
});

describe('sampler algebra', () => {
  it('matches the published Philox4x32-10 vector', () => {
    const out = Philox4x32.random(new Uint32Array(4), new Uint32Array(2));
    expect([...out].map((x) => x.toString(16).padStart(8, '0'))).toEqual([
      '6627e8d5',
      'e169c58d',
      'bc57ac4c',
      '9b00dbd8',
    ]);
  });

  it('preserves the target distribution under sampled rejection', () => {
    const rng = new FixtureRng(26418);
    let maxError = 0;
    for (let trial = 0; trial < 1000; trial++) {
      const pTokens = Array.from({ length: 29 }, (_, i) => i * 3 + 1);
      const pWeights = pTokens.map(() => rng.next() + 1e-6);
      const pTotal = pWeights.reduce((a, b) => a + b, 0);
      const pProb = pWeights.map((w) => w / pTotal);
      const p: SparseDistribution = {
        tokens: Uint32Array.from(pTokens),
        probabilities: Float64Array.from(pProb),
      };
      const qTokens = pTokens.filter(() => rng.next() < 0.55);
      if (qTokens.length === 0) qTokens.push(pTokens[Math.floor(rng.next() * pTokens.length)]!);
      const qWeights = qTokens.map(() => rng.next() + 1e-6);
      const qTotal = qWeights.reduce((a, b) => a + b, 0);
      const q: SparseDistribution = {
        tokens: Uint32Array.from(qTokens),
        probabilities: Float64Array.from(qWeights.map((w) => w / qTotal)),
      };
      let acceptedMass = 0;
      let residualTotal = 0;
      const residual: number[] = [];
      for (let i = 0; i < p.tokens.length; i++) {
        const token = p.tokens[i]!;
        const pt = p.probabilities[i]!;
        const qt = probabilityOf(q, token);
        acceptedMass += Math.min(pt, qt);
        const mass = Math.max(pt - qt, 0);
        residual.push(mass);
        residualTotal += mass;
      }
      for (let i = 0; i < p.tokens.length; i++) {
        const reconstructed = Math.min(p.probabilities[i]!, probabilityOf(q, p.tokens[i]!)) + (residualTotal > 0 ? (1 - acceptedMass) * (residual[i]! / residualTotal) : 0);
        maxError = Math.max(maxError, Math.abs(reconstructed - p.probabilities[i]!));
      }
      let normalized = 0;
      for (let i = 0; i < p.tokens.length; i++) normalized += Math.min(p.probabilities[i]!, probabilityOf(q, p.tokens[i]!)) + residual[i]!;
      expect(normalized).toBeCloseTo(1, 12);
    }
    expect(maxError).toBeLessThan(1e-12);
  });

  it('applies subtractive presence penalty and respects window eviction', () => {
    const history = createPenaltyHistory(3);
    for (const token of [5, 5, 6]) pushPenaltyToken(history, token);
    expect(history.counts.get(5)).toBe(2);
    pushPenaltyToken(history, 7);
    expect(history.counts.get(5)).toBe(1);
    pushPenaltyToken(history, 8);
    expect(history.counts.get(5) ?? 0).toBe(0);
    pushPenaltyToken(history, 9);
    expect(history.counts.get(5) ?? 0).toBe(0);
  });

  it('selects exact top-k with deterministic ties', () => {
    const logits = new Float64Array([1, 4, 4, 2, 3]);
    const candidates = selectCandidates(logits, {
      profile: { ...BOTPSY_APPLICATION_PROFILE, topK: 3, topP: 1, minP: 0, temperature: 1 },
    });
    expect(candidates.map((c) => c.token)).toEqual([1, 2, 4]);
    expect(candidates[0]!.probability + candidates[1]!.probability + candidates[2]!.probability).toBeCloseTo(1, 12);
  });

  it('rejects an all-masked distribution', () => {
    expect(() =>
      selectCandidates(new Float64Array([Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY]), {
        profile: BOTPSY_APPLICATION_PROFILE,
      }),
    ).toThrow(/empty legal distribution/);
  });
});

describe('attention reference', () => {
  it('online softmax matches two-pass attention within FP64 tolerance', () => {
    const rng = new FixtureRng(7);
    const tokens = 37;
    const queryHeads = 8;
    const kvHeads = 2;
    const headDim = 16;
    const query = new Float64Array(queryHeads * headDim);
    const keyCache = new Float64Array(tokens * kvHeads * headDim);
    const valueCache = new Float64Array(tokens * kvHeads * headDim);
    for (let i = 0; i < query.length; i++) query[i] = rng.normal();
    for (let i = 0; i < keyCache.length; i++) keyCache[i] = rng.normal();
    for (let i = 0; i < valueCache.length; i++) valueCache[i] = rng.normal();
    const input = {
      query,
      key: new Float64Array(kvHeads * headDim),
      value: new Float64Array(kvHeads * headDim),
      keyCache,
      valueCache,
      tokens,
      kvHeads,
      headDim,
      queryHeads,
      groupSize: queryHeads / kvHeads,
    };
    const twoPass = attentionDecode(input, new Float64Array(queryHeads * headDim).fill(100));
    const online = attentionDecodeOnline(input);
    expect(maxAbsDiff(twoPass, online)).toBeLessThan(1e-12);
  });
});

describe('quantization and rotation research transforms', () => {
  it('preserves GDN outputs under orthogonal q/k and state rotation', () => {
    const seq = randomSequence(new FixtureRng(991), 5, 2, 7, 3);
    const initial = initialState(new FixtureRng(992), 2, 7, 3);
    const matrix = orthogonalMatrix(7, 123);
    const reference = gdnSequential(seq, initial);
    const transformed = gdnSequential(rotateGdnQK(seq, matrix), rotateInitialState(initial, 2, 7, 3, matrix));
    expect(maxAbsDiff(reference.output, transformed.output)).toBeLessThan(1e-9);
    const expectedState = rotateInitialState(reference.state, 2, 7, 3, matrix);
    expect(maxAbsDiff(expectedState, transformed.state)).toBeLessThan(1e-9);
  });

  it('keeps a recent FP32 tail and int4 quantized completed KV tokens', () => {
    const cache = new QuantizedKvCache(2, 128, 4, 64);
    const keys: Float64Array[] = [];
    for (let token = 0; token < 7; token++) {
      const key = Float64Array.from({ length: 256 }, (_, index) => Math.sin((token + 1) * (index + 1) * 0.01));
      keys.push(key);
      cache.append(key, key);
    }
    expect(cache.length).toBe(7);
    const decoded = cache.keys();
    expect(decoded).toHaveLength(7);
    for (let index = 3; index < 7; index++) expect(Array.from(decoded[index]!)).toEqual(Array.from(keys[index]!));
    for (let index = 0; index < 3; index++) {
      for (let i = 0; i < 256; i++) expect(Number.isFinite(decoded[index]![i]!)).toBe(true);
    }
  });

  it('bounds int4 group quantization error', () => {
    const values = Float64Array.from({ length: 1024 }, (_, index) => Math.sin(index * 0.07) * 2.5 + Math.cos(index * 0.013));
    const groups = quantizeInt4(values, 64);
    const restored = dequantizeInt4(groups);
    let maximum = 0;
    for (const group of groups) maximum = Math.max(maximum, group.scale / 2);
    for (let index = 0; index < values.length; index++) {
      expect(Math.abs(values[index]! - restored[index]!)).toBeLessThanOrEqual(maximum + 1e-9);
    }
  });
});