import { softmaxInPlace } from './ops.ts'; export type SamplerStage = 'top_k' | 'top_p' | 'min_p' | 'temperature'; export interface SamplerProfile { id: string; temperature: number; topK: number; topP: number; minP: number; presencePenalty: number; penaltyWindow: number; /** Applied in this order after the presence penalty. */ order: SamplerStage[]; minCandidates: number; seed: bigint; } export const BOTPSY_APPLICATION_PROFILE: SamplerProfile = { id: 'botpsy-app-v1', temperature: 0.3, topK: 20, topP: 0.95, minP: 0.05, presencePenalty: 1.5, penaltyWindow: 64, order: ['top_k', 'top_p', 'min_p', 'temperature'], minCandidates: 1, seed: 0x9e3779b97f4a7c15n, }; export interface Candidate { token: number; logit: number; probability: number; } export interface PenaltyHistory { /** Newest last. */ tokens: number[]; counts: Map; window: number; } export function createPenaltyHistory(window: number): PenaltyHistory { return { tokens: [], counts: new Map(), window }; } export function pushPenaltyToken(history: PenaltyHistory, token: number): void { history.tokens.push(token); history.counts.set(token, (history.counts.get(token) ?? 0) + 1); while (history.tokens.length > history.window) { const evicted = history.tokens.shift()!; const count = history.counts.get(evicted)! - 1; if (count === 0) history.counts.delete(evicted); else history.counts.set(evicted, count); } } export function clonePenaltyHistory(history: PenaltyHistory): PenaltyHistory { return { tokens: [...history.tokens], counts: new Map(history.counts), window: history.window }; } /** Presence penalty is a subtractive score adjustment for every seen token. */ export function applyPresencePenalty( logits: Float64Array, counts: ReadonlyMap, penalty: number, ): void { if (penalty === 0) return; for (const token of counts.keys()) { if (token < logits.length) logits[token] = logits[token]! - penalty; } } export function maskGrammar(logits: Float64Array, mask: Uint32Array | null): void { if (mask === null) return; for (let token = 0; token < logits.length; token++) { if (((mask[token >>> 5]! >>> (token & 31)) & 1) === 0) logits[token] = Number.NEGATIVE_INFINITY; } } export interface CandidateOptions { profile: SamplerProfile; /** Optional grammar mask. */ mask?: Uint32Array | null; /** If supplied, restrict evaluation to these token IDs (grammar sparsity). */ allowedTokens?: Uint32Array | null; } function sortedDescending(candidates: Candidate[]): Candidate[] { return candidates.sort((a, b) => b.logit - a.logit || a.token - b.token); } /** Exact candidate selection. Returns at most topK processed candidates. */ export function selectCandidates(logits: Float64Array, options: CandidateOptions): Candidate[] { const { profile } = options; let tokens: Iterable; if (options.allowedTokens && options.allowedTokens.length > 0) { tokens = options.allowedTokens; } else { tokens = Array.from({ length: logits.length }, (_, i) => i); } const candidates: Candidate[] = []; for (const token of tokens) { const logit = logits[token]!; if (Number.isNaN(logit) || logit === Number.POSITIVE_INFINITY) { throw new Error(`sampler received invalid logit ${logit} at token ${token}`); } if (logit === Number.NEGATIVE_INFINITY) continue; if (options.mask && ((options.mask[token >>> 5]! >>> (token & 31)) & 1) === 0) continue; candidates.push({ token, logit, probability: 0 }); } if (candidates.length === 0) throw new Error('sampler received an empty legal distribution'); let current = sortedDescending(candidates); for (const stage of profile.order) { if (stage === 'top_k') { if (profile.topK > 0 && current.length > profile.topK) current = current.slice(0, profile.topK); } else if (stage === 'top_p') { if (profile.topP < 1) { const probabilities = softmaxInPlace(Float64Array.from(current.map((c) => c.logit))); let cumulative = 0; let keep = 0; for (let i = 0; i < current.length; i++) { cumulative += probabilities[i]!; keep = i + 1; if (cumulative >= profile.topP) break; } keep = Math.max(keep, profile.minCandidates, 1); current = current.slice(0, keep); } } else if (stage === 'min_p') { if (profile.minP > 0) { const probabilities = softmaxInPlace(Float64Array.from(current.map((c) => c.logit))); const threshold = profile.minP * Math.max(...probabilities); const kept = current.filter((_, i) => probabilities[i]! >= threshold); if (kept.length >= profile.minCandidates) current = kept; else current = current.slice(0, Math.max(profile.minCandidates, 1)); } } else if (stage === 'temperature') { if (profile.temperature <= 0) { current = [current[0]!]; } else if (profile.temperature !== 1) { for (const candidate of current) candidate.logit /= profile.temperature; } } if (current.length === 0) throw new Error('sampler stage emptied the distribution'); } const probabilities = softmaxInPlace(Float64Array.from(current.map((c) => c.logit))); current.forEach((candidate, i) => (candidate.probability = probabilities[i]!)); return current; } /** Convert a full processed logit vector into the sparse candidate list. */ export function candidateDistribution(logits: Float64Array, options: CandidateOptions): Candidate[] { return selectCandidates(logits, options); } export function sampleCandidate(candidates: Candidate[], uniform: number): Candidate { let total = 0; for (const candidate of candidates) total += candidate.probability; if (!(total > 0) || !Number.isFinite(total)) throw new Error('sampler normalization fault'); let threshold = uniform * total; for (const candidate of candidates) { threshold -= candidate.probability; if (threshold < 0) return candidate; } return candidates[candidates.length - 1]!; } export class Philox4x32 { private counter: Uint32Array; private readonly key: Uint32Array; private buffer: Uint32Array = new Uint32Array(0); private offset = 0; constructor(seed: bigint, stream = 0) { this.counter = new Uint32Array([0, 0, 0, 0]); const low = Number(seed & 0xffffffffn) >>> 0; const high = Number((seed >> 32n) & 0xffffffffn) >>> 0; this.key = new Uint32Array([low, (high ^ (stream >>> 0)) >>> 0]); } static random(counter: Uint32Array, key: Uint32Array): Uint32Array { let c0 = counter[0]!; let c1 = counter[1]!; let c2 = counter[2]!; let c3 = counter[3]!; let k0 = key[0]!; let k1 = key[1]!; for (let round = 0; round < 10; round++) { const p0 = mulhilo(0xd2511f53, c0); const p1 = mulhilo(0xcd9e8d57, c2); c0 = (p1.hi ^ c1 ^ k0) >>> 0; c1 = p1.lo; c2 = (p0.hi ^ c3 ^ k1) >>> 0; c3 = p0.lo; k0 = (k0 + 0x9e3779b9) >>> 0; k1 = (k1 + 0xbb67ae85) >>> 0; } return new Uint32Array([c0, c1, c2, c3]); } nextUint32(): number { if (this.offset >= this.buffer.length) { this.buffer = Philox4x32.random(this.counter, this.key); this.offset = 0; this.counter[0] = (this.counter[0]! + 1) >>> 0; if (this.counter[0] === 0) { this.counter[1] = (this.counter[1]! + 1) >>> 0; if (this.counter[1] === 0) { this.counter[2] = (this.counter[2]! + 1) >>> 0; if (this.counter[2] === 0) this.counter[3] = (this.counter[3]! + 1) >>> 0; } } } return this.buffer[this.offset++]!; } next(): number { return this.nextUint32() / 2 ** 32; } } function mulhilo(multiplier: number, value: number): { hi: number; lo: number } { const product = BigInt(multiplier) * BigInt(value >>> 0); return { hi: Number((product >> 32n) & 0xffffffffn) >>> 0, lo: Number(product & 0xffffffffn) >>> 0 }; }