null
feat: deploy BotPsy local WebGPU static Space
1cc8d34
Raw History Blame Contribute Delete
19.9 kB
import type { VisionConfig } from '@botpsy/artifacts';
export interface RgbaImage {
width: number;
height: number;
data: Uint8ClampedArray;
}
export interface ProcessedImage {
pixelValues: Float32Array;
gridT: number;
gridH: number;
gridW: number;
resizedWidth: number;
resizedHeight: number;
}
export interface VisionWeightSource {
f32(role: string): Float32Array;
}
export interface VisionEmbeddings {
values: Float32Array;
tokens: number;
width: number;
gridT: number;
gridH: number;
gridW: number;
}
export function smartResize(
height: number,
width: number,
factor = 32,
minPixels = 65536,
maxPixels = 16777216,
): [number, number] {
if (Math.max(height, width) / Math.min(height, width) > 200) throw new Error('aspect ratio exceeds 200');
let hBar = Math.round(height / factor) * factor;
let wBar = Math.round(width / factor) * factor;
if (hBar * wBar > maxPixels) {
const beta = Math.sqrt((height * width) / maxPixels);
hBar = Math.max(factor, Math.floor(height / beta / factor) * factor);
wBar = Math.max(factor, Math.floor(width / beta / factor) * factor);
} else if (hBar * wBar < minPixels) {
const beta = Math.sqrt(minPixels / (height * width));
hBar = Math.ceil((height * beta) / factor) * factor;
wBar = Math.ceil((width * beta) / factor) * factor;
}
return [hBar, wBar];
}
function bicubicWeight(distance: number): number {
const a = -0.5;
const x = Math.abs(distance);
if (x <= 1) return (a + 2) * x ** 3 - (a + 3) * x ** 2 + 1;
if (x < 2) return a * x ** 3 - 5 * a * x ** 2 + 8 * a * x - 4 * a;
return 0;
}
function resizeBicubic(source: RgbaImage, targetWidth: number, targetHeight: number): Float32Array {
const output = new Float32Array(targetWidth * targetHeight * 3);
const scaleX = source.width / targetWidth;
const scaleY = source.height / targetHeight;
const supportX = Math.max(1, 2 * scaleX);
const supportY = Math.max(1, 2 * scaleY);
const rgb = new Float32Array(source.width * source.height * 3);
for (let i = 0; i < source.width * source.height; i++) {
rgb[i * 3] = source.data[i * 4]!;
rgb[i * 3 + 1] = source.data[i * 4 + 1]!;
rgb[i * 3 + 2] = source.data[i * 4 + 2]!;
}
for (let y = 0; y < targetHeight; y++) {
const sourceY = (y + 0.5) * scaleY - 0.5;
const yStart = Math.max(0, Math.ceil(sourceY - supportY));
const yEnd = Math.min(source.height - 1, Math.floor(sourceY + supportY));
for (let x = 0; x < targetWidth; x++) {
const sourceX = (x + 0.5) * scaleX - 0.5;
const xStart = Math.max(0, Math.ceil(sourceX - supportX));
const xEnd = Math.min(source.width - 1, Math.floor(sourceX + supportX));
for (let channel = 0; channel < 3; channel++) {
let total = 0;
let weightTotal = 0;
for (let sy = yStart; sy <= yEnd; sy++) {
const wy = bicubicWeight((sourceY - sy) / supportY);
if (wy === 0) continue;
for (let sx = xStart; sx <= xEnd; sx++) {
const wx = bicubicWeight((sourceX - sx) / supportX);
if (wx === 0) continue;
const weight = wx * wy;
total += rgb[(sy * source.width + sx) * 3 + channel]! * weight;
weightTotal += weight;
}
}
output[(y * targetWidth + x) * 3 + channel] = weightTotal === 0 ? 0 : total / weightTotal;
}
}
}
return output;
}
export function smartResizeVideo(
numFrames: number,
height: number,
width: number,
factor = 32,
temporalFactor = 2,
minPixels = 4096,
maxPixels = 25165824,
): [number, number] {
if (numFrames < temporalFactor) throw new Error(`video frames ${numFrames} must be at least ${temporalFactor}`);
if (height < factor || width < factor) {
const scale = Math.max(factor / height, factor / width);
height = Math.floor(height * scale);
width = Math.floor(width * scale);
}
if (Math.max(height, width) / Math.min(height, width) > 200) throw new Error('video aspect ratio exceeds 200');
let hBar = Math.round(height / factor) * factor;
let wBar = Math.round(width / factor) * factor;
const tBar = Math.round(numFrames / temporalFactor) * temporalFactor;
if (tBar * hBar * wBar > maxPixels) {
const beta = Math.sqrt((numFrames * height * width) / maxPixels);
hBar = Math.max(factor, Math.floor(height / beta / factor) * factor);
wBar = Math.max(factor, Math.floor(width / beta / factor) * factor);
} else if (tBar * hBar * wBar < minPixels) {
const beta = Math.sqrt(minPixels / (numFrames * height * width));
hBar = Math.ceil((height * beta) / factor) * factor;
wBar = Math.ceil((width * beta) / factor) * factor;
}
return [hBar, wBar];
}
export function preprocessVideo(
frames: RgbaImage[],
config: Pick<VisionConfig, 'patchSize' | 'spatialMergeSize' | 'temporalPatchSize'>,
bounds: { minPixels: number; maxPixels: number } = { minPixels: 4096, maxPixels: 25165824 },
): ProcessedImage {
if (frames.length === 0) throw new Error('video has no frames');
const temporal = config.temporalPatchSize;
const source = [...frames];
while (source.length % temporal !== 0) source.push(source[source.length - 1]!);
const [resizedHeight, resizedWidth] = smartResizeVideo(
source.length,
source[0]!.height,
source[0]!.width,
config.patchSize * config.spatialMergeSize,
temporal,
bounds.minPixels,
bounds.maxPixels,
);
const resized = source.map((frame) => resizeBicubic(frame, resizedWidth, resizedHeight));
const gridT = source.length / temporal;
const gridH = resizedHeight / config.patchSize;
const gridW = resizedWidth / config.patchSize;
const merge = config.spatialMergeSize;
const patchSize = config.patchSize;
const channel = 3;
const patchDim = channel * temporal * patchSize * patchSize;
const patches = gridT * gridH * gridW;
const values = new Float32Array(patches * patchDim);
let write = 0;
for (let t = 0; t < gridT; t++) {
for (let blockRow = 0; blockRow < gridH / merge; blockRow++) {
for (let blockCol = 0; blockCol < gridW / merge; blockCol++) {
for (let inRow = 0; inRow < merge; inRow++) {
for (let inCol = 0; inCol < merge; inCol++) {
const row = blockRow * merge + inRow;
const col = blockCol * merge + inCol;
for (let c = 0; c < channel; c++) {
for (let tt = 0; tt < temporal; tt++) {
const frame = resized[t * temporal + tt]!;
for (let py = 0; py < patchSize; py++) {
for (let px = 0; px < patchSize; px++) {
const y = row * patchSize + py;
const x = col * patchSize + px;
values[write++] = frame[(y * resizedWidth + x) * 3 + c]! / 127.5 - 1;
}
}
}
}
}
}
}
}
}
return { pixelValues: values, gridT, gridH, gridW, resizedWidth, resizedHeight };
}
export function preprocessImage(
image: RgbaImage,
config: Pick<VisionConfig, 'patchSize' | 'spatialMergeSize' | 'temporalPatchSize'>,
bounds: { minPixels: number; maxPixels: number } = { minPixels: 65536, maxPixels: 16777216 },
): ProcessedImage {
const factor = config.patchSize * config.spatialMergeSize;
const [resizedHeight, resizedWidth] = smartResize(image.height, image.width, factor, bounds.minPixels, bounds.maxPixels);
const resized = resizeBicubic(image, resizedWidth, resizedHeight);
const gridH = resizedHeight / config.patchSize;
const gridW = resizedWidth / config.patchSize;
const merge = config.spatialMergeSize;
const patchSize = config.patchSize;
const channel = 3;
const temporal = config.temporalPatchSize;
const patchDim = channel * temporal * patchSize * patchSize;
const patches = gridH * gridW;
const values = new Float32Array(patches * patchDim);
let write = 0;
for (let blockRow = 0; blockRow < gridH / merge; blockRow++) {
for (let blockCol = 0; blockCol < gridW / merge; blockCol++) {
for (let inRow = 0; inRow < merge; inRow++) {
for (let inCol = 0; inCol < merge; inCol++) {
const row = blockRow * merge + inRow;
const col = blockCol * merge + inCol;
for (let c = 0; c < channel; c++) {
for (let t = 0; t < temporal; t++) {
for (let py = 0; py < patchSize; py++) {
for (let px = 0; px < patchSize; px++) {
const y = row * patchSize + py;
const x = col * patchSize + px;
// Images duplicate the single frame across the temporal patch.
const pixel = resized[(y * resizedWidth + x) * 3 + c]!;
values[write++] = pixel / 127.5 - 1;
}
}
}
}
}
}
}
}
return { pixelValues: values, gridT: 1, gridH, gridW, resizedWidth, resizedHeight };
}
function layerNorm(
input: Float32Array,
offset: number,
length: number,
weight: Float32Array,
bias: Float32Array,
eps = 1e-6,
): Float32Array {
let mean = 0;
for (let i = 0; i < length; i++) mean += input[offset + i]!;
mean /= length;
let variance = 0;
for (let i = 0; i < length; i++) {
const d = input[offset + i]! - mean;
variance += d * d;
}
variance /= length;
const inv = 1 / Math.sqrt(variance + eps);
const out = new Float32Array(length);
for (let i = 0; i < length; i++) out[i] = (input[offset + i]! - mean) * inv * weight[i]! + bias[i]!;
return out;
}
function geluTanh(x: number): number {
return 0.5 * x * (1 + Math.tanh(Math.sqrt(2 / Math.PI) * (x + 0.044715 * x ** 3)));
}
function linear(input: Float32Array, weight: Float32Array, bias: Float32Array, outFeatures: number, inFeatures: number): Float32Array {
const out = new Float32Array(outFeatures);
for (let o = 0; o < outFeatures; o++) {
let sum = 0;
const base = o * inFeatures;
for (let i = 0; i < inFeatures; i++) sum += weight[base + i]! * input[i]!;
out[o] = sum + bias[o]!;
}
return out;
}
export function bilinearPositions(gridH: number, gridW: number, side: number, merge = 1): { indices: Int32Array; weights: Float32Array } {
const count = gridH * gridW;
const indices = new Int32Array(count * 4);
const weights = new Float32Array(count * 4);
const taps = (index: number, size: number): { taps: number[]; weights: number[] } => {
const src = size === 1 ? 0 : (index * (side - 1)) / (size - 1);
const floor = Math.floor(src);
const outTaps: number[] = [];
const outWeights: number[] = [];
for (const offset of [0, 1]) {
outTaps.push(Math.min(side - 1, Math.max(0, floor + offset)));
outWeights.push(Math.max(0, 1 - Math.abs(src - floor - offset)));
}
return { taps: outTaps, weights: outWeights };
};
let cursor = 0;
const blocksW = gridW / merge;
for (let token = 0; token < count; token++) {
const within = token % (gridH * gridW);
const inCol = within % merge;
const inRow = Math.floor(within / merge) % merge;
const blockCol = Math.floor(within / (merge * merge)) % blocksW;
const blockRow = Math.floor(within / (merge * merge * blocksW));
const row = blockRow * merge + inRow;
const col = blockCol * merge + inCol;
const h = taps(row, gridH);
const w = taps(col, gridW);
for (let hi = 0; hi < 2; hi++) {
for (let wi = 0; wi < 2; wi++) {
indices[cursor] = h.taps[hi]! * side + w.taps[wi]!;
weights[cursor] = h.weights[hi]! * w.weights[wi]!;
cursor++;
}
}
}
return { indices, weights };
}
function applyVisionRope(vector: Float32Array, head: number, headDim: number, posH: number, posW: number): void {
const spatial = headDim / 2;
const inv: number[] = [];
for (let i = 0; i < spatial / 2; i++) inv.push(1 / 10000 ** ((2 * i) / spatial));
const half = headDim / 2;
const base = head * headDim;
const original = vector.slice(base, base + headDim);
for (let i = 0; i < headDim; i++) {
const angleIndex = i % half;
const isHeight = angleIndex < half / 2;
const freqIndex = angleIndex % (half / 2);
const angle = (isHeight ? posH : posW) * inv[freqIndex]!;
const c = Math.cos(angle);
const s = Math.sin(angle);
const paired = i < half ? original[i + half]! : original[i - half]!;
vector[base + i] = original[i]! * c + (i < half ? -paired : paired) * s;
}
}
export function runVisionEncoder(
processed: ProcessedImage,
weights: VisionWeightSource,
config: VisionConfig,
): VisionEmbeddings {
const patchDim = 3 * config.temporalPatchSize * config.patchSize * config.patchSize;
const tokens = processed.gridT * processed.gridH * processed.gridW;
const hidden = new Float32Array(tokens * config.hiddenSize);
const patchWeight = weights.f32('visual.patch_embed.proj.weight');
const patchBias = weights.f32('visual.patch_embed.proj.bias');
for (let token = 0; token < tokens; token++) {
const input = processed.pixelValues.subarray(token * patchDim, (token + 1) * patchDim);
for (let o = 0; o < config.hiddenSize; o++) {
let sum = 0;
const base = o * patchDim;
for (let i = 0; i < patchDim; i++) sum += patchWeight[base + i]! * input[i]!;
hidden[token * config.hiddenSize + o] = sum + patchBias[o]!;
}
}
const posTable = weights.f32('visual.pos_embed.weight');
const { indices, weights: posWeights } = bilinearPositions(processed.gridH, processed.gridW, config.numGridPerSide, config.spatialMergeSize);
const spatialTokens = processed.gridH * processed.gridW;
for (let token = 0; token < tokens; token++) {
const within = token % spatialTokens;
for (let i = 0; i < config.hiddenSize; i++) {
let sum = 0;
for (let tap = 0; tap < 4; tap++) {
sum += posTable[indices[within * 4 + tap]! * config.hiddenSize + i]! * posWeights[within * 4 + tap]!;
}
hidden[token * config.hiddenSize + i] += sum;
}
}
const merge = config.spatialMergeSize;
const positionsH = new Int32Array(tokens);
const positionsW = new Int32Array(tokens);
const blocksW = processed.gridW / merge;
for (let token = 0; token < tokens; token++) {
const within = token % (processed.gridH * processed.gridW);
const inCol = within % merge;
const inRow = Math.floor(within / merge) % merge;
const blockCol = Math.floor(within / (merge * merge)) % blocksW;
const blockRow = Math.floor(within / (merge * merge * blocksW));
positionsH[token] = blockRow * merge + inRow;
positionsW[token] = blockCol * merge + inCol;
}
for (let layer = 0; layer < config.depth; layer++) {
const role = `visual.blocks.${layer}`;
const norm1w = weights.f32(`${role}.norm1.weight`);
const norm1b = weights.f32(`${role}.norm1.bias`);
const norm2w = weights.f32(`${role}.norm2.weight`);
const norm2b = weights.f32(`${role}.norm2.bias`);
const qkvW = weights.f32(`${role}.attn.qkv.weight`);
const qkvB = weights.f32(`${role}.attn.qkv.bias`);
const projW = weights.f32(`${role}.attn.proj.weight`);
const projB = weights.f32(`${role}.attn.proj.bias`);
const fc1W = weights.f32(`${role}.mlp.fc1.weight`);
const fc1B = weights.f32(`${role}.mlp.fc1.bias`);
const fc2W = weights.f32(`${role}.mlp.fc2.weight`);
const fc2B = weights.f32(`${role}.mlp.fc2.bias`);
const qkv = new Float32Array(tokens * config.hiddenSize * 3);
for (let token = 0; token < tokens; token++) {
const normed = layerNorm(hidden, token * config.hiddenSize, config.hiddenSize, norm1w, norm1b);
const projected = linear(normed, qkvW, qkvB, config.hiddenSize * 3, config.hiddenSize);
// Reshape [3, heads, headDim], then apply axial RoPE to q and k.
for (let group = 0; group < 3; group++) {
for (let headIndex = 0; headIndex < config.heads; headIndex++) {
const offset = group * config.hiddenSize + headIndex * config.headDim;
const slice = projected.slice(offset, offset + config.headDim);
if (group < 2) applyVisionRope(slice, 0, config.headDim, positionsH[token]!, positionsW[token]!);
qkv.set(slice, token * config.hiddenSize * 3 + offset);
}
}
}
const attention = new Float32Array(tokens * config.hiddenSize);
for (let headIndex = 0; headIndex < config.heads; headIndex++) {
const scores = new Float64Array(tokens);
for (let token = 0; token < tokens; token++) {
let max = Number.NEGATIVE_INFINITY;
for (let other = 0; other < tokens; other++) {
let dot = 0;
const qBase = token * config.hiddenSize * 3 + headIndex * config.headDim;
const kBase = other * config.hiddenSize * 3 + config.hiddenSize + headIndex * config.headDim;
for (let d = 0; d < config.headDim; d++) dot += qkv[qBase + d]! * qkv[kBase + d]!;
scores[other] = dot / Math.sqrt(config.headDim);
max = Math.max(max, scores[other]!);
}
let total = 0;
for (let other = 0; other < tokens; other++) {
scores[other] = Math.exp(scores[other]! - max);
total += scores[other]!;
}
for (let d = 0; d < config.headDim; d++) {
let sum = 0;
for (let other = 0; other < tokens; other++) {
const vBase = other * config.hiddenSize * 3 + config.hiddenSize * 2 + headIndex * config.headDim;
sum += (scores[other]! / total) * qkv[vBase + d]!;
}
attention[token * config.hiddenSize + headIndex * config.headDim + d] = sum;
}
}
}
const projectedOut = new Float32Array(tokens * config.hiddenSize);
for (let token = 0; token < tokens; token++) {
const input = attention.subarray(token * config.hiddenSize, (token + 1) * config.hiddenSize);
projectedOut.set(linear(input, projW, projB, config.hiddenSize, config.hiddenSize), token * config.hiddenSize);
}
for (let i = 0; i < hidden.length; i++) hidden[i] += projectedOut[i]!;
for (let token = 0; token < tokens; token++) {
const normed = layerNorm(hidden, token * config.hiddenSize, config.hiddenSize, norm2w, norm2b);
const fc1 = linear(normed, fc1W, fc1B, config.intermediateSize, config.hiddenSize);
for (let i = 0; i < fc1.length; i++) fc1[i] = geluTanh(fc1[i]!);
const fc2 = linear(fc1, fc2W, fc2B, config.hiddenSize, config.intermediateSize);
for (let i = 0; i < config.hiddenSize; i++) hidden[token * config.hiddenSize + i] += fc2[i]!;
}
}
const mergeHidden = config.hiddenSize * merge * merge;
const mergerNormW = weights.f32('visual.merger.norm.weight');
const mergerNormB = weights.f32('visual.merger.norm.bias');
const mergedTokens = tokens / (merge * merge);
const merged = new Float32Array(mergedTokens * mergeHidden);
for (let token = 0; token < tokens; token++) {
const normalized = layerNorm(hidden, token * config.hiddenSize, config.hiddenSize, mergerNormW, mergerNormB);
merged.set(normalized, token * config.hiddenSize);
}
const fc1W = weights.f32('visual.merger.fc1.weight');
const fc1B = weights.f32('visual.merger.fc1.bias');
const fc2W = weights.f32('visual.merger.fc2.weight');
const fc2B = weights.f32('visual.merger.fc2.bias');
const output = new Float32Array(mergedTokens * config.outHiddenSize);
for (let token = 0; token < mergedTokens; token++) {
const input = merged.subarray(token * mergeHidden, (token + 1) * mergeHidden);
const fc1 = linear(input, fc1W, fc1B, mergeHidden, mergeHidden);
for (let i = 0; i < fc1.length; i++) fc1[i] = geluTanh(fc1[i]!);
output.set(linear(fc1, fc2W, fc2B, config.outHiddenSize, mergeHidden), token * config.outHiddenSize);
}
return {
values: output,
tokens: mergedTokens,
width: config.outHiddenSize,
gridT: processed.gridT,
gridH: processed.gridH,
gridW: processed.gridW,
};
}