null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
6.38 kB
import type { Candidate } from './sampler.ts';
export interface SparseDistribution {
/** Token IDs sorted ascending; probabilities sum to one over this support. */
tokens: Uint32Array;
probabilities: Float64Array;
}
export function sparseFromCandidates(candidates: Candidate[]): SparseDistribution {
const sorted = [...candidates].sort((a, b) => a.token - b.token);
return {
tokens: Uint32Array.from(sorted.map((c) => c.token)),
probabilities: Float64Array.from(sorted.map((c) => c.probability)),
};
}
export function probabilityOf(dist: SparseDistribution, token: number): number {
let low = 0;
let high = dist.tokens.length - 1;
while (low <= high) {
const mid = (low + high) >>> 1;
const value = dist.tokens[mid]!;
if (value === token) return dist.probabilities[mid]!;
if (value < token) low = mid + 1;
else high = mid - 1;
}
return 0;
}
export function sampleSparse(dist: SparseDistribution, uniform: number): number {
let cumulative = 0;
for (let i = 0; i < dist.tokens.length; i++) {
cumulative += dist.probabilities[i]!;
if (uniform < cumulative) return dist.tokens[i]!;
}
return dist.tokens[dist.tokens.length - 1]!;
}
export interface VerificationResult {
accepted: number[];
corrected: number | null;
bonus: number | null;
consumed: number;
/** Target distribution at the decision that ended the block, when available. */
targetAtDecision: SparseDistribution;
}
export interface VerifyOptions {
/** Uniform draws in [0,1). One for each acceptance and one for a correction/bonus. */
uniforms: () => number;
targetDistributions: SparseDistribution[];
}
/**
* Distribution-preserving speculative verification for sampled generation.
* `proposals[i]` is the draft's token at prefix i, with target distribution i.
*/
export function verifySampledChain(
proposals: Uint32Array,
draftDistributions: SparseDistribution[],
targetDistributions: SparseDistribution[],
options: VerifyOptions,
): VerificationResult {
if (proposals.length !== draftDistributions.length || proposals.length > targetDistributions.length) {
throw new Error('speculative chain shape mismatch');
}
const accepted: number[] = [];
for (let i = 0; i < proposals.length; i++) {
const x = proposals[i]!;
const p = targetDistributions[i]!;
const q = draftDistributions[i]!;
const px = probabilityOf(p, x);
const qx = probabilityOf(q, x);
if (!(qx > 0)) throw new Error('draft proposed a token outside its own support');
const accept = Math.min(1, px / qx);
if (options.uniforms() < accept) {
accepted.push(x);
continue;
}
const corrected = sampleResidual(p, q, options.uniforms);
return {
accepted,
corrected,
bonus: null,
consumed: accepted.length + 1,
targetAtDecision: p,
};
}
const last = targetDistributions[proposals.length]!;
const bonus = sampleSparse(last, options.uniforms());
return {
accepted,
corrected: null,
bonus,
consumed: accepted.length + 1,
targetAtDecision: last,
};
}
/** Sample from normalized positive part of p - q over the union support. */
export function sampleResidual(p: SparseDistribution, q: SparseDistribution, uniforms: () => number): number {
const tokens: number[] = [];
const masses: number[] = [];
let total = 0;
for (let i = 0; i < p.tokens.length; i++) {
const token = p.tokens[i]!;
const mass = Math.max(p.probabilities[i]! - probabilityOf(q, token), 0);
if (mass > 0) {
tokens.push(token);
masses.push(mass);
total += mass;
}
}
if (!(total > 0) || !Number.isFinite(total)) {
throw new Error('speculative residual has zero mass under the declared numerical profile');
}
let threshold = uniforms() * total;
for (let i = 0; i < tokens.length; i++) {
threshold -= masses[i]!;
if (threshold < 0) return tokens[i]!;
}
return tokens[tokens.length - 1]!;
}
export interface TreeNode {
token: number;
parent: number;
/** Draft distribution at this node's prefix. */
draft: SparseDistribution;
/** Target distribution at this node's prefix, when precomputed. */
target: SparseDistribution | null;
}
export interface TreeSampleResult {
path: number[];
correction: number | null;
consumed: number;
}
/**
* Sample a single realized proposal path through the tree. Siblings are extra
* precomputation, not a source of selection-bias correction.
*/
export function sampleTreePath(
nodes: TreeNode[],
rootTarget: SparseDistribution,
uniforms: () => number,
): TreeSampleResult {
const children = new Map<number, number[]>();
for (let i = 0; i < nodes.length; i++) {
const parent = nodes[i]!.parent;
const list = children.get(parent) ?? [];
list.push(i);
children.set(parent, list);
}
const path: number[] = [];
let current = -1;
let distribution = rootTarget;
for (;;) {
const options = children.get(current) ?? [];
if (options.length === 0) {
return { path, correction: null, consumed: path.length + 1 };
}
// The path is realized by sampling from the draft distribution at the
// current prefix. A node stores the distribution after its own token, so
// children are selected through their parent's branch probabilities.
const total = options.reduce((sum, index) => sum + probabilityOf(nodes[index]!.draft, nodes[index]!.token), 0);
if (total <= 0) {
const token = sampleSparse(distribution, uniforms());
return { path, correction: token, consumed: path.length + 1 };
}
let draw = uniforms() * total;
let chosen = options[options.length - 1]!;
for (const index of options) {
draw -= probabilityOf(nodes[index]!.draft, nodes[index]!.token);
if (draw < 0) {
chosen = index;
break;
}
}
const node = nodes[chosen]!;
const px = probabilityOf(distribution, node.token);
const qx = probabilityOf(node.draft, node.token);
if (qx <= 0) throw new Error('tree branch has zero draft probability');
if (uniforms() < Math.min(1, px / qx)) {
path.push(node.token);
current = chosen;
distribution = node.target ?? distribution;
continue;
}
return {
path,
correction: sampleResidual(distribution, node.draft, uniforms),
consumed: path.length + 1,
};
}
}