Spaces:
Running
Running
File size: 7,986 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 | 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<number, number>;
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<number, number>,
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<number>;
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 };
}
|