botpsy-0.8b-web / packages /kernels /src /reference /reference.test.ts
null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
10.9 kB
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);
}
});
});