null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
6.6 kB
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { WeightArena, validateManifest, type PackageManifest } from '../../../packages/artifacts/src/index.ts';
import { ReferenceModel } from '../../../packages/kernels/src/reference/model.ts';
import { QwenTokenizer, type TokenizerJson } from '../../../packages/tokenizer/src/index.ts';
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..');
const args = new Map<string, string>();
for (let i = 2; i < process.argv.length; i += 2) {
const key = process.argv[i];
const value = process.argv[i + 1];
if (key?.startsWith('--') && value) args.set(key.slice(2), value);
}
const profile = args.get('profile') ?? 'q4_k_m';
const tokenCount = Math.max(16, Number(args.get('tokens') ?? 48));
const layers = Math.max(1, Number(args.get('layers') ?? 4));
const candidates = Math.max(2, Number(args.get('candidates') ?? 16));
const epochs = Math.max(10, Number(args.get('epochs') ?? 400));
const output = resolve(root, args.get('out') ?? 'artifacts/draft-head.json');
const artifactDir = join(root, profile === 'q8_0' ? 'artifacts/botpsy-0.8b-q8_0' : 'artifacts/botpsy-0.8b-q4_k_m');
const manifest = validateManifest(
JSON.parse(readFileSync(join(artifactDir, 'manifest.json'), 'utf8')) as PackageManifest,
);
const shards = new Map(
manifest.shards.map((shard) => [shard.name, new Uint8Array(readFileSync(join(artifactDir, shard.name)))]),
);
const model = new ReferenceModel(new WeightArena(manifest, shards), manifest.model, 2048);
const tokenizerBytes = readFileSync(join(root, 'model-src/tokenizer.json'));
const tokenizer = new QwenTokenizer(
JSON.parse(tokenizerBytes.toString('utf8')) as TokenizerJson,
createHash('sha256').update(tokenizerBytes).digest('hex'),
);
const corpus = readFileSync(join(root, 'model-src/README.md'), 'utf8');
const tokens = tokenizer.encode(corpus).slice(0, tokenCount + 1);
if (tokens.length < 8) throw new Error('corpus is too short for draft-head training');
const features: Array<{ hidden: Float64Array; label: number; logits: Float32Array }> = [];
for (let index = 0; index < tokens.length - 1; index++) {
const result = model.forwardToken(tokens[index]!, undefined, layers);
features.push({
hidden: Float64Array.from(result.normalizedHidden),
label: tokens[index + 1]!,
logits: result.logits,
});
}
const split = Math.max(1, Math.floor(features.length * 0.8));
const training = features.slice(0, split);
const testing = features.slice(split);
const frequency = new Map<number, number>();
for (const sample of training) frequency.set(sample.label, (frequency.get(sample.label) ?? 0) + 1);
const candidatesList = [...frequency.entries()]
.sort((a, b) => b[1] - a[1] || a[0] - b[0])
.slice(0, candidates)
.map(([token]) => token);
const candidateIndex = new Map(candidatesList.map((token, index) => [token, index]));
const dimension = manifest.model.text.hiddenSize;
const weights = Array.from({ length: candidatesList.length }, () => new Float64Array(dimension));
const bias = new Float64Array(candidatesList.length);
for (let epoch = 0; epoch < epochs; epoch++) {
for (const sample of training) {
const label = candidateIndex.get(sample.label);
if (label === undefined) continue;
const logits = new Float64Array(candidatesList.length);
let maximum = -Infinity;
for (let c = 0; c < candidatesList.length; c++) {
let sum = bias[c]!;
const weight = weights[c]!;
for (let d = 0; d < dimension; d++) sum += weight[d]! * sample.hidden[d]!;
logits[c] = sum;
maximum = Math.max(maximum, sum);
}
let total = 0;
for (let c = 0; c < candidatesList.length; c++) {
logits[c] = Math.exp(logits[c]! - maximum);
total += logits[c]!;
}
const learningRate = 0.05 / Math.sqrt(1 + epoch / 50);
for (let c = 0; c < candidatesList.length; c++) {
const gradient = logits[c]! / total - (c === label ? 1 : 0);
if (gradient === 0) continue;
const weight = weights[c]!;
for (let d = 0; d < dimension; d++) weight[d] = weight[d]! - learningRate * gradient * sample.hidden[d]!;
bias[c] = bias[c]! - learningRate * gradient;
}
}
}
function draftDistribution(hidden: Float64Array): { tokens: number[]; probabilities: number[] } {
const logits = weights.map((weight, c) => {
let sum = bias[c]!;
for (let d = 0; d < dimension; d++) sum += weight[d]! * hidden[d]!;
return sum;
});
const maximum = Math.max(...logits);
const probabilities = logits.map((value) => Math.exp(value - maximum));
const total = probabilities.reduce((sum, value) => sum + value, 0);
return { tokens: candidatesList, probabilities: probabilities.map((value) => value / total) };
}
function targetProbability(logits: Float32Array, token: number): number {
let maximum = -Infinity;
for (const logit of logits) maximum = Math.max(maximum, logit);
const selected = Math.exp(logits[token]! - maximum);
let total = 0;
for (const logit of logits) total += Math.exp(logit - maximum);
return selected / total;
}
let correct = 0;
let evaluated = 0;
let acceptance = 0;
for (const sample of testing) {
const distribution = draftDistribution(sample.hidden);
let best = 0;
for (let index = 1; index < distribution.probabilities.length; index++) {
if (distribution.probabilities[index]! > distribution.probabilities[best]!) best = index;
}
const proposal = distribution.tokens[best]!;
if (proposal === sample.label) correct++;
const p = targetProbability(sample.logits, proposal);
const q = distribution.probabilities[best]!;
acceptance += Math.min(1, p / q);
evaluated++;
}
const artifact = {
schemaVersion: 1,
profile,
featureTap: 'final_norm',
layers,
dimension,
candidates: candidatesList,
weights: weights.map((row) => Array.from(row, (value) => Number(value.toFixed(8)))),
bias: Array.from(bias, (value) => Number(value.toFixed(8))),
metadata: {
tokens: tokens.length,
training: training.length,
testing: testing.length,
epochs,
top1Accuracy: evaluated > 0 ? correct / evaluated : 0,
meanAcceptance: evaluated > 0 ? acceptance / evaluated : 0,
corpusSha256: createHash('sha256').update(corpus).digest('hex'),
tokenizerHash: tokenizer.tokenizerHash,
modelHash: manifest.source.ggufSha256,
},
};
writeFileSync(output, `${JSON.stringify(artifact)}\n`);
console.log(JSON.stringify({ ok: true, output, metadata: artifact.metadata }, null, 2));