import { validateManifest, type PackageManifest, type TensorRecord, type ShardRecord, } from '@botpsy/artifacts'; import { addKernel, advanceKernel, attnAvKernel, attnQkRopeKernel, attnScoresKernel, attnKStoreKernel, attnVCopyKernel, commitKernel, convSiluKernel, embeddingKernel, embeddingPrefillKernel, embeddingKQuantKernel, gemvKQuantKernel, topkProjectionKQuantKernel, gdnGatesKernel, gdnChunkKernel, replacePendingKernel, gdnNormSiluKernel, gdnRecurrentKernel, gemvQ8Kernel, qkL2NormKernel, rmsnormKernel, visionEmbeddingKernel, samplerKernel, siluMulKernel, topkMergeKernel, topkProjectionKernel, type EmbeddingSegment, type KernelBinding, type WgslKernel, } from '@botpsy/kernels'; import type { CheckpointRef, CheckpointId, EngineEvent, EngineIdentity, GenerateRequest, PrefixState, ProfileId, } from '@botpsy/protocol'; import { asCheckpointId, asPrefixHash, asProfileId } from '@botpsy/protocol'; import { requestEngineDevice, probeCapabilities } from './device.ts'; import { VisionGpuEncoder, type VisionLoadOptions } from './vision.ts'; import { targetDistributionFromTopK, type Drafter } from './speculative.ts'; import { probabilityOf, sampleResidual } from '@botpsy/kernels'; const CONTROL_WORDS = 64; const PENALTY_WINDOW = 64; const TOP_K = 20; const RING_WORDS = 66; const USAGE_STATE = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC; const USAGE_WEIGHT = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST; const USAGE_UPLOAD = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST; const USAGE_READBACK = GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST; interface CompiledKernel { spec: WgslKernel; pipeline: GPUComputePipeline; layout: GPUBindGroupLayout; bindGroupCache: Map; } interface QuantBinding { buffer: GPUBuffer; base: number; rows: number; cols: number; rowStride: number; dtype: 'q8_0' | 'q4_k' | 'q6_k'; } export interface EngineLoadOptions { contextLength?: number; windowWidth?: number; diagnostic?: boolean; allowSoftwareAdapter?: boolean; verifyShards?: boolean; onProgress?: (event: EngineEvent) => void; /** Diagnostic-only vocabulary subset; production always uses the full tied head. */ diagnosticOutputRows?: number; diagnosticLayers?: number; diagnosticStopAfter?: 'embedding' | 'advance' | 'norm' | 'topk' | 'merge' | 'sampler' | 'commit'; manifest?: PackageManifest; shardLoader?: (shard: ShardRecord) => Promise; } export interface PrefillOptions { seed?: bigint; samplerProfile?: ProfileId; maxNewTokens?: number; positions?: Array<[number, number, number]>; images?: Array<{ embeddings: Float32Array; tokenStart: number; tokenCount: number }>; signal?: AbortSignal; onProgress?: (processed: number, total: number) => void; } export interface Readback { control: Uint32Array; ring: Uint32Array; } class Immediate { readonly buffer = new ArrayBuffer(64); readonly words = new Uint32Array(this.buffer); private readonly floats = new Float32Array(this.buffer); reset(): this { this.words.fill(0); return this; } p(index: number, value: number): this { this.words[index < 4 ? index : index + 4] = value >>> 0; return this; } f(index: number, value: number): this { this.floats[index + 4] = value; return this; } } export class BotPsyGpuEngine { readonly device: GPUDevice; readonly manifest: PackageManifest; readonly identity: EngineIdentity; readonly subgroupSize: number; readonly contextLength: number; windowWidth: number; private readonly weightBuffers: GPUBuffer[] = []; private readonly shardBytes = new Map(); private readonly auxBuffers = new Map(); private readonly buffers = new Map(); private readonly kernels = new Map(); private readonly tensorByRole = new Map(); private readonly embedSegments: EmbeddingSegment[] = []; private embedDtype: 'q8_0' | 'q4_k' | 'q6_k' = 'q8_0'; private readonly outputSegments: Array<{ binding: GPUBuffer; base: number; rows: number; rowStart: number; tileBase: number; tiles: number }> = []; private readonly readbackBuffer: GPUBuffer; private readonly immediate = new Immediate(); private totalTiles = 0; private destroyed = false; private sessionTokens: number[] = []; private processed = 0; private pendingToken: number | null = null; private emitted = 0; private active = false; private ringCount = 0; private stopReason = 0; private requestId = 0; private epoch = 0; private maxNewTokens = 0; private samplerProfileId: ProfileId = asProfileId('botpsy-app-v1'); private cancelling = false; private loadError: Error | null = null; private readonly shardLoader?: (shard: ShardRecord) => Promise; private pendingEmissions: number[] = []; private requestEmittedBase = 0; private configuredWindowWidth: number; private targetTopKValid = false; private visionRanges: Array<{ start: number; count: number; offset: number }> = []; private positionDelta = 0; private speculativeDrafter: Drafter | null = null; private speculativeAccepted = 0; private grammarEnabled = false; private readonly kvPageSize = 64; private kvMaxPages = 0; private kvFullLayers = 0; private speculativeRejected = 0; private readonly checkpoints = new Map; tokens: number[]; processed: number; pending: number | null; emitted: number; active: boolean; stopReason: number; ringCount: number; positionDelta: number; requestEmittedBase: number; pendingEmissions: number[]; identity: EngineIdentity }>(); private diagnosticOutputRows: number; private diagnosticLayers: number; private diagnosticStopAfter?: string; private constructor(device: GPUDevice, manifest: PackageManifest, subgroupSize: number, options: EngineLoadOptions) { this.device = device; this.manifest = manifest; this.subgroupSize = subgroupSize; this.contextLength = Math.min(options.contextLength ?? manifest.numericalProfile.contextDefault, manifest.model.text.maxPositions); this.windowWidth = Math.min(options.windowWidth ?? 8, 32); this.configuredWindowWidth = this.windowWidth; this.diagnosticOutputRows = options.diagnosticOutputRows ?? Number.POSITIVE_INFINITY; this.diagnosticLayers = Math.min(options.diagnosticLayers ?? manifest.model.text.layers, manifest.model.text.layers); this.diagnosticStopAfter = options.diagnosticStopAfter; this.shardLoader = options.shardLoader; for (const tensor of manifest.tensors) this.tensorByRole.set(tensor.role, tensor); this.identity = { modelHash: manifest.source.ggufSha256, tokenizerHash: manifest.source.tokenizerSha256, templateHash: manifest.source.templateSha256, numericalProfile: asProfileId(manifest.numericalProfile.id), stateSchema: manifest.stateSchema, }; this.readbackBuffer = device.createBuffer({ label: 'result-readback', size: 256 + RING_WORDS * 4, usage: USAGE_READBACK, }); device.lost.then((info) => { this.loadError = new Error(`GPU device lost: ${info.reason}: ${info.message}`); console.error('[botpsy] device lost', info.reason, info.message); }); device.addEventListener('uncapturederror', (event) => { console.error('[botpsy] WebGPU validation error', (event as GPUUncapturedErrorEvent).error.message); }); } static async create( manifestUrl: string, options: EngineLoadOptions = {}, ): Promise { const probe = await probeCapabilities(); if (probe.missing.length > 0 && !options.diagnostic) { throw new Error(`WebGPU contract not satisfied: ${probe.missing.join(', ')}`); } if (!probe.adapter) throw new Error('no WebGPU adapter'); const { device, subgroupSize } = await requestEngineDevice(probe.adapter, { diagnostic: options.diagnostic, allowSoftwareAdapter: options.allowSoftwareAdapter, }); let manifest = options.manifest; let baseUrl: URL; if (manifest) { baseUrl = new URL('.', new URL(manifestUrl, globalThis.location?.href ?? 'http://localhost/')); } else { const manifestResponse = await fetch(manifestUrl); if (!manifestResponse.ok) throw new Error(`manifest fetch failed: ${manifestResponse.status}`); manifest = validateManifest((await manifestResponse.json()) as unknown); baseUrl = new URL('.', manifestResponse.url); } if (!options.diagnostic) { const available = new Set([...probe.capabilities.features, ...probe.capabilities.wgslLanguageFeatures]); for (const feature of [...manifest.capabilities.features, ...manifest.capabilities.wgslLanguageFeatures]) { if (!available.has(feature)) throw new Error(`artifact requires unavailable feature ${feature}`); } for (const [limit, required] of Object.entries(manifest.capabilities.minLimits)) { const actual = probe.capabilities.limits[limit]; if (typeof actual !== 'number' || actual < required) { throw new Error(`artifact requires ${limit} >= ${required}, adapter reports ${actual ?? 'missing'}`); } } } const engine = new BotPsyGpuEngine(device, manifest, subgroupSize, options); await engine.initialize(baseUrl, options); return engine; } private async initialize(baseUrl: URL, options: EngineLoadOptions): Promise { await this.loadWeights(baseUrl, options); this.createAuxBuffers(); this.createStateBuffers(); this.initializeKvPageTable(); await this.compileKernels(); this.initializeControl(); if (options.onProgress) options.onProgress({ type: 'preparation', requestId: 0 as never, stage: 'ready', completed: 1, total: 1 }); } private async loadWeights(baseUrl: URL, options: EngineLoadOptions): Promise { let completed = 0; const total = this.manifest.shards.reduce((sum, shard) => sum + shard.byteLength, 0); for (let index = 0; index < this.manifest.shards.length; index++) { const shard = this.manifest.shards[index]!; let bytes: Uint8Array; if (this.shardLoader) { bytes = await this.shardLoader(shard); } else { const response = await fetch(new URL(shard.name, baseUrl)); if (!response.ok) throw new Error(`shard ${shard.name} fetch failed: ${response.status}`); bytes = new Uint8Array(await response.arrayBuffer()); } if (bytes.byteLength !== shard.byteLength) throw new Error(`shard ${shard.name} length mismatch`); if (options.verifyShards !== false) { const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as BufferSource); const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join(''); if (hex !== shard.sha256) throw new Error(`shard ${shard.name} hash mismatch`); } this.shardBytes.set(shard.name, bytes); const buffer = this.device.createBuffer({ label: shard.name, size: Math.ceil(bytes.byteLength / 4) * 4, usage: USAGE_WEIGHT, }); this.device.queue.writeBuffer(buffer, 0, bytes as unknown as GPUAllowSharedBufferSource); this.weightBuffers[index] = buffer; completed += shard.byteLength; options.onProgress?.({ type: 'preparation', requestId: 0 as never, stage: 'upload', completed, total, }); } await this.device.queue.onSubmittedWorkDone(); } private createAuxBuffers(): void { for (const tensor of this.manifest.tensors) { if (tensor.dtype !== 'f32') continue; const buffer = this.device.createBuffer({ label: `aux-${tensor.role}`, size: Math.ceil(tensor.byteLength / 4) * 4, usage: USAGE_WEIGHT, }); const data = new Uint8Array(tensor.byteLength); for (const segment of tensor.segments) { const shard = this.manifest.shards[segment.buffer]!; const bytes = this.shardBytes.get(shard.name)!; data.set(bytes.subarray(segment.offset, segment.offset + segment.length), segment.tensorOffset); } this.device.queue.writeBuffer(buffer, 0, data); this.auxBuffers.set(tensor.role, buffer); } this.shardBytes.clear(); } private createBuffer(name: string, byteLength: number, usage = USAGE_STATE): GPUBuffer { const buffer = this.device.createBuffer({ label: name, size: Math.max(4, Math.ceil(byteLength / 4) * 4), usage, }); this.buffers.set(name, buffer); return buffer; } private createF32(name: string, count: number): GPUBuffer { return this.createBuffer(name, count * 4); } private createStateBuffers(): void { const cfg = this.manifest.model.text; this.createF32('hidden', cfg.hiddenSize); this.createF32('normed', cfg.hiddenSize); this.createF32('mixer', cfg.hiddenSize); this.createF32('mlpAct', cfg.intermediateSize); this.createF32('mlpGate', cfg.intermediateSize); this.createF32('mlpUp', cfg.intermediateSize); this.createF32('qkv', cfg.linearValueHeads * cfg.linearValueHeadDim * 3); this.createF32('convOut', cfg.linearValueHeads * cfg.linearValueHeadDim * 3); this.createF32('z', cfg.linearValueHeads * cfg.linearValueHeadDim); this.createF32('a', cfg.linearValueHeads); this.createF32('b', cfg.linearValueHeads); this.createF32('alpha', cfg.linearValueHeads); this.createF32('beta', cfg.linearValueHeads); this.createF32('qk', cfg.linearKeyHeads * cfg.linearKeyHeadDim * 2); this.createF32('gdnY', cfg.linearValueHeads * cfg.linearValueHeadDim); this.createF32('gdnOut', cfg.linearValueHeads * cfg.linearValueHeadDim); this.createF32('kNorm', cfg.numKeyValueHeads * cfg.headDim); this.createF32('qProj', cfg.numAttentionHeads * cfg.headDim * 2); this.createF32('kProj', cfg.numKeyValueHeads * cfg.headDim); this.createF32('vProj', cfg.numKeyValueHeads * cfg.headDim); this.createF32('attnQ', cfg.numAttentionHeads * cfg.headDim); this.createF32('attnGate', cfg.numAttentionHeads * cfg.headDim); this.createF32('attnOut', cfg.numAttentionHeads * cfg.headDim); this.createF32('scores', 6 * cfg.numAttentionHeads * this.contextLength); const gdnLayers = cfg.layerTypes.filter((type) => type === 'linear_attention').length; this.createF32('states', gdnLayers * cfg.linearValueHeads * cfg.linearKeyHeadDim * cfg.linearValueHeadDim); this.createF32( 'convHistory', gdnLayers * cfg.linearValueHeads * cfg.linearValueHeadDim * 3 * 3, ); this.kvFullLayers = cfg.layerTypes.filter((type) => type === 'full_attention').length; this.kvMaxPages = Math.ceil(this.contextLength / this.kvPageSize); const kvPageSpan = this.kvMaxPages * this.kvPageSize; const kvBytes = this.kvFullLayers * kvPageSpan * cfg.numKeyValueHeads * cfg.headDim * 2; this.createBuffer('kCache', kvBytes); this.createBuffer('vCache', kvBytes); this.createBuffer('kvPageTable', this.kvFullLayers * this.kvMaxPages * 4); this.createBuffer('tokens', this.contextLength * 4, USAGE_UPLOAD); this.createF32('visionEmbeds', 4096 * cfg.hiddenSize); this.createBuffer('control', CONTROL_WORDS * 4); this.createBuffer('rng', 8 * 4); this.createBuffer('penaltyRing', PENALTY_WINDOW * 4); this.createBuffer('counts', cfg.vocabSize * 4); this.createBuffer('grammarMask', Math.ceil(cfg.vocabSize / 32) * 4); this.createBuffer('outRing', RING_WORDS * 4); this.createF32('mergedTokenLogits', TOP_K); this.createBuffer('mergedTokens', TOP_K * 4); const embed = this.tensorByRole.get('embed_tokens')!; const rowStride = embed.quantization!.rowStride; let rowStart = 0; let tileBase = 0; let diagnosticRemaining = this.diagnosticOutputRows; for (const segment of embed.segments) { if (diagnosticRemaining <= 0) break; const fullRows = segment.length / rowStride; const rows = Math.min(fullRows, diagnosticRemaining); diagnosticRemaining -= rows; const tiles = Math.ceil(rows / 20); this.outputSegments.push({ binding: this.weightBuffers[segment.buffer]!, base: segment.offset, rows, rowStart, tileBase, tiles, }); rowStart += fullRows; tileBase += tiles; } this.totalTiles = tileBase; this.createBuffer('candTokens', this.totalTiles * TOP_K * 4); this.createF32('candLogits', this.totalTiles * TOP_K); // Initialize grammar mask to all-legal (unconstrained generation). const mask = new Uint32Array(Math.ceil(cfg.vocabSize / 32)).fill(0xffffffff); this.device.queue.writeBuffer(this.buffers.get('grammarMask')!, 0, mask); } private async compileKernels(): Promise { const embed = this.tensorByRole.get('embed_tokens')!; if (embed.dtype !== 'q8_0' && embed.dtype !== 'q4_k' && embed.dtype !== 'q6_k') throw new Error('embedding must be quantized'); this.embedDtype = embed.dtype; const rowStride = embed.quantization!.rowStride; const cols = embed.shape[embed.shape.length - 1]!; let rowStart = 0; for (let i = 0; i < embed.segments.length; i++) { const segment = embed.segments[i]!; const rows = segment.length / rowStride; this.embedSegments.push({ binding: `w${i}`, rowStart, rows, byteOffset: segment.offset, rowStride, cols, dtype: embed.dtype, }); rowStart += rows; } const embeddingKernels = embed.dtype === 'q8_0' ? [embeddingKernel(this.embedSegments), embeddingPrefillKernel(this.embedSegments)] : [embeddingKQuantKernel(embed.dtype, false, this.embedSegments), embeddingKQuantKernel(embed.dtype, true, this.embedSegments)]; const kernels = [ ...embeddingKernels, rmsnormKernel(), visionEmbeddingKernel(), addKernel(), siluMulKernel(), gemvQ8Kernel(false, this.subgroupSize), gemvQ8Kernel(true, this.subgroupSize), gemvKQuantKernel('q4_k', this.subgroupSize), gemvKQuantKernel('q6_k', this.subgroupSize), convSiluKernel(), qkL2NormKernel(), gdnGatesKernel(), gdnRecurrentKernel(this.subgroupSize), gdnChunkKernel(this.subgroupSize), gdnNormSiluKernel(), attnQkRopeKernel(), attnKStoreKernel(), attnVCopyKernel(), attnScoresKernel(), attnAvKernel(), topkProjectionKernel(this.subgroupSize), topkProjectionKQuantKernel('q4_k'), topkProjectionKQuantKernel('q6_k'), topkMergeKernel(), samplerKernel(), commitKernel(), advanceKernel(), replacePendingKernel(), ]; for (const spec of kernels) { const entries: GPUBindGroupLayoutEntry[] = spec.bindings.map((binding, index) => ({ binding: index, visibility: GPUShaderStage.COMPUTE, buffer: { type: binding.access === 'read' ? 'read-only-storage' : 'storage' }, })); const layout = this.device.createBindGroupLayout({ entries }); const pipelineLayout = this.device.createPipelineLayout({ bindGroupLayouts: [layout], immediateSize: 64, }); const module = this.device.createShaderModule({ code: spec.code, label: spec.name }); const info = await module.getCompilationInfo(); const errors = info.messages.filter((message) => message.type === 'error'); if (errors.length > 0) { throw new Error(`WGSL compile failed for ${spec.name}: ${errors.map((e) => `${e.lineNum}:${e.linePos} ${e.message}`).join('; ')}`); } const pipeline = await this.device.createComputePipelineAsync({ layout: pipelineLayout, compute: { module, entryPoint: spec.entryPoint }, }); this.kernels.set(spec.name, { spec, pipeline, layout, bindGroupCache: new Map() }); } } private initializeKvPageTable(): void { const table = new Uint32Array(this.kvFullLayers * this.kvMaxPages); for (let layer = 0; layer < this.kvFullLayers; layer++) { for (let page = 0; page < this.kvMaxPages; page++) { table[layer * this.kvMaxPages + page] = page; } } this.device.queue.writeBuffer(this.buffers.get('kvPageTable')!, 0, table); } private initializeControl(): void { const control = new Uint32Array(CONTROL_WORDS); control[2] = 0; control[3] = 0; control[7] = 0; control[8] = 0; control[12] = 0; control[13] = 0; control[15] = 1; this.device.queue.writeBuffer(this.buffers.get('control')!, 0, control); this.device.queue.writeBuffer(this.buffers.get('rng')!, 0, new Uint32Array(8)); } private tensor(role: string): TensorRecord { const tensor = this.tensorByRole.get(role); if (!tensor) throw new Error(`missing tensor ${role}`); return tensor; } private quant(role: string): QuantBinding { const tensor = this.tensor(role); if (tensor.dtype !== 'q8_0' && tensor.dtype !== 'q4_k' && tensor.dtype !== 'q6_k') { throw new Error(`${role} is not a supported quantized tensor`); } if (tensor.segments.length !== 1) throw new Error(`${role} unexpectedly spans multiple buffers`); const segment = tensor.segments[0]!; const rows = tensor.shape[tensor.shape.length - 2] ?? 1; const cols = tensor.shape[tensor.shape.length - 1]!; return { buffer: this.weightBuffers[segment.buffer]!, base: segment.offset, rows, cols, rowStride: tensor.quantization!.rowStride, dtype: tensor.dtype, }; } private gemvKernelFor(dtype: QuantBinding['dtype']): string { return dtype === 'q8_0' ? 'gemv_q8' : dtype === 'q4_k' ? 'gemv_q4_k' : 'gemv_q6_k'; } private dispatchGemv( pass: GPUComputePassEncoder, binding: QuantBinding, input: GPUBuffer, out: GPUBuffer, ): void { this.dispatch(pass, this.gemvKernelFor(binding.dtype), { weights: binding.buffer, input, out, }, this.immediate.reset().p(0, binding.rows).p(1, binding.cols).p(2, binding.base).p(7, binding.rowStride), [Math.ceil(binding.rows / (256 / this.subgroupSize))]); } private aux(role: string): GPUBuffer { const buffer = this.auxBuffers.get(role); if (!buffer) throw new Error(`missing f32 tensor ${role}`); return buffer; } private resolveBuffers(spec: WgslKernel, overrides: Record): GPUBuffer[] { return spec.bindings.map((binding) => { const buffer = overrides[binding.name] ?? this.buffers.get(binding.name); if (!buffer) throw new Error(`kernel ${spec.name} has no buffer for ${binding.name}`); return buffer; }); } private dispatch( pass: GPUComputePassEncoder, name: string, overrides: Record, imm: Immediate, workgroups: [number, number?, number?], ): void { const kernel = this.kernels.get(name); if (!kernel) throw new Error(`unknown kernel ${name}`); const buffers = this.resolveBuffers(kernel.spec, overrides); const key = buffers.map((buffer) => this.bufferId(buffer)).join(','); let bindGroup = kernel.bindGroupCache.get(key); if (!bindGroup) { bindGroup = this.device.createBindGroup({ layout: kernel.layout, entries: buffers.map((buffer, binding) => ({ binding, resource: { buffer, size: buffer.size } })), }); kernel.bindGroupCache.set(key, bindGroup); } pass.setPipeline(kernel.pipeline); pass.setBindGroup(0, bindGroup); pass.setImmediates(0, imm.words, 0, 16); pass.dispatchWorkgroups(workgroups[0], workgroups[1] ?? 1, workgroups[2] ?? 1); } private bufferIds = new WeakMap(); private nextBufferId = 1; private bufferId(buffer: GPUBuffer): number { let id = this.bufferIds.get(buffer); if (!id) { id = this.nextBufferId++; this.bufferIds.set(buffer, id); } return id; } private encodeForward( pass: GPUComputePassEncoder, kvSlot: number, position: [number, number, number], mode: 'decode' | 'prefill', includeOutput: boolean, ): void { const cfg = this.manifest.model.text; const imm = this.immediate; if (mode === 'decode') { this.dispatch(pass, this.embedDtype === 'q8_0' ? 'embedding' : `embedding_${this.embedDtype}`, Object.fromEntries([ ...this.embedSegments.map((segment, i) => [`w${i}`, this.weightBuffers[this.tensor('embed_tokens').segments[i]!.buffer]!]), ['out', this.buffers.get('hidden')!], ]), imm.reset(), [1]); } else { const range = this.visionRanges.find((candidate) => kvSlot >= candidate.start && kvSlot < candidate.start + candidate.count); if (range) { this.dispatch(pass, 'vision_embedding', { embeddings: this.buffers.get('visionEmbeds')!, out: this.buffers.get('hidden')!, }, imm.reset().p(0, range.start).p(1, range.count).p(2, range.offset), [1]); } else { this.dispatch(pass, this.embedDtype === 'q8_0' ? 'embedding_prefill' : `embedding_prefill_${this.embedDtype}`, Object.fromEntries([ ['tokens', this.buffers.get('tokens')!], ...this.embedSegments.map((segment, i) => [`w${i}`, this.weightBuffers[this.tensor('embed_tokens').segments[i]!.buffer]!]), ['out', this.buffers.get('hidden')!], ]), imm.reset(), [1]); } } if (this.diagnosticStopAfter === 'embedding') return; let gdnIndex = 0; let fullIndex = 0; for (let layer = 0; layer < this.diagnosticLayers; layer++) { const prefix = `blk.${layer}`; if (cfg.layerTypes[layer] === 'linear_attention') { const qkv = this.quant(`${prefix}.gdn.in_qkv`); const z = this.quant(`${prefix}.gdn.in_z`); const a = this.quant(`${prefix}.gdn.in_a`); const b = this.quant(`${prefix}.gdn.in_b`); const out = this.quant(`${prefix}.gdn.out_proj`); this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux(`${prefix}.input_norm`), out: this.buffers.get('normed')!, }, imm.reset().p(0, cfg.hiddenSize).p(1, 0).f(0, cfg.rmsNormEps), [1]); this.dispatchGemv(pass, qkv, this.buffers.get('normed')!, this.buffers.get('qkv')!); this.dispatchGemv(pass, z, this.buffers.get('normed')!, this.buffers.get('z')!); this.dispatchGemv(pass, a, this.buffers.get('normed')!, this.buffers.get('a')!); this.dispatchGemv(pass, b, this.buffers.get('normed')!, this.buffers.get('b')!); this.dispatch(pass, 'conv_silu', { projected: this.buffers.get('qkv')!, weight: this.aux(`${prefix}.gdn.conv`), history: this.buffers.get('convHistory')!, out: this.buffers.get('convOut')!, }, imm.reset().p(0, cfg.linearValueHeads * cfg.linearValueHeadDim * 3).p(1, gdnIndex * cfg.linearValueHeads * cfg.linearValueHeadDim * 9), [1]); this.dispatch(pass, 'qk_l2norm', { source: this.buffers.get('convOut')!, qk: this.buffers.get('qk')!, }, imm.reset().f(0, cfg.rmsNormEps), [cfg.linearKeyHeads]); this.dispatch(pass, 'gdn_gates', { a: this.buffers.get('a')!, b: this.buffers.get('b')!, aLog: this.aux(`${prefix}.gdn.a_log`), dtBias: this.aux(`${prefix}.gdn.dt_bias`), alpha: this.buffers.get('alpha')!, beta: this.buffers.get('beta')!, }, imm.reset(), [1]); const stateBase = gdnIndex * cfg.linearValueHeads * cfg.linearKeyHeadDim * cfg.linearValueHeadDim; this.dispatch(pass, 'gdn_recurrent', { states: this.buffers.get('states')!, qk: this.buffers.get('qk')!, projected: this.buffers.get('convOut')!, alpha: this.buffers.get('alpha')!, beta: this.buffers.get('beta')!, out: this.buffers.get('gdnY')!, }, imm.reset().p(0, stateBase), [cfg.linearValueHeads * cfg.linearValueHeadDim]); this.dispatch(pass, 'gdn_norm_silu', { y: this.buffers.get('gdnY')!, z: this.buffers.get('z')!, normWeight: this.aux(`${prefix}.gdn.norm`), out: this.buffers.get('gdnOut')!, }, imm.reset().f(0, cfg.rmsNormEps), [cfg.linearValueHeads]); this.dispatchGemv(pass, out, this.buffers.get('gdnOut')!, this.buffers.get('mixer')!); gdnIndex++; } else { const q = this.quant(`${prefix}.attn.q`); const k = this.quant(`${prefix}.attn.k`); const v = this.quant(`${prefix}.attn.v`); const o = this.quant(`${prefix}.attn.o`); this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux(`${prefix}.input_norm`), out: this.buffers.get('normed')!, }, imm.reset().p(0, cfg.hiddenSize).p(1, 0).f(0, cfg.rmsNormEps), [1]); this.dispatchGemv(pass, q, this.buffers.get('normed')!, this.buffers.get('qProj')!); this.dispatchGemv(pass, k, this.buffers.get('normed')!, this.buffers.get('kProj')!); this.dispatchGemv(pass, v, this.buffers.get('normed')!, this.buffers.get('vProj')!); const kvLayerByte = fullIndex * this.kvMaxPages * this.kvPageSize * cfg.numKeyValueHeads * cfg.headDim * 2; this.dispatch(pass, 'attn_qk_rope', { qProjection: this.buffers.get('qProj')!, kProjection: this.buffers.get('kProj')!, qNormWeight: this.aux(`${prefix}.attn.q_norm`), kNormWeight: this.aux(`${prefix}.attn.k_norm`), qOut: this.buffers.get('attnQ')!, gateOut: this.buffers.get('attnGate')!, kNorm: this.buffers.get('kNorm')!, }, imm.reset().p(0, position[0]).p(1, position[1]).p(2, position[2]).p(3, kvLayerByte).p(4, kvSlot).f(0, cfg.rmsNormEps), [cfg.numAttentionHeads + cfg.numKeyValueHeads]); this.dispatch(pass, 'attn_k_store', { kNorm: this.buffers.get('kNorm')!, kCache: this.buffers.get('kCache')!, pageTable: this.buffers.get('kvPageTable')!, }, imm.reset().p(0, kvSlot).p(1, kvLayerByte).p(4, fullIndex * this.kvMaxPages).p(5, this.kvPageSize), [cfg.numKeyValueHeads]); this.dispatch(pass, 'attn_v_copy', { vProjection: this.buffers.get('vProj')!, vCache: this.buffers.get('vCache')!, pageTable: this.buffers.get('kvPageTable')!, }, imm.reset().p(0, kvSlot).p(1, kvLayerByte).p(4, fullIndex * this.kvMaxPages).p(5, this.kvPageSize), [cfg.numKeyValueHeads]); const tokens = kvSlot + 1; const scoreBase = fullIndex * cfg.numAttentionHeads * this.contextLength; this.dispatch(pass, 'attn_scores', { qOut: this.buffers.get('attnQ')!, kCache: this.buffers.get('kCache')!, scores: this.buffers.get('scores')!, pageTable: this.buffers.get('kvPageTable')!, }, imm.reset().p(0, tokens).p(1, kvLayerByte).p(2, scoreBase).p(3, this.contextLength).p(4, fullIndex * this.kvMaxPages).p(5, this.kvPageSize), [Math.ceil(tokens / 256), cfg.numAttentionHeads]); this.dispatch(pass, 'attn_av', { scores: this.buffers.get('scores')!, vCache: this.buffers.get('vCache')!, gate: this.buffers.get('attnGate')!, out: this.buffers.get('attnOut')!, pageTable: this.buffers.get('kvPageTable')!, }, imm.reset().p(0, tokens).p(1, kvLayerByte).p(2, scoreBase).p(3, this.contextLength).p(4, fullIndex * this.kvMaxPages).p(5, this.kvPageSize), [cfg.numAttentionHeads]); this.dispatchGemv(pass, o, this.buffers.get('attnOut')!, this.buffers.get('mixer')!); fullIndex++; } this.dispatch(pass, 'add', { x: this.buffers.get('hidden')!, delta: this.buffers.get('mixer')!, }, imm.reset().p(0, cfg.hiddenSize), [1]); this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux(`${prefix}.post_attn_norm`), out: this.buffers.get('normed')!, }, imm.reset().p(0, cfg.hiddenSize).p(1, 0).f(0, cfg.rmsNormEps), [1]); const gate = this.quant(`${prefix}.mlp.gate`); const up = this.quant(`${prefix}.mlp.up`); const down = this.quant(`${prefix}.mlp.down`); if (gate.dtype === 'q8_0' && up.dtype === 'q8_0') { this.dispatch(pass, 'gemv_q8_pair', { weightsA: gate.buffer, weightsB: up.buffer, input: this.buffers.get('normed')!, outA: this.buffers.get('mlpGate')!, outB: this.buffers.get('mlpUp')!, }, imm.reset().p(0, gate.rows).p(1, gate.cols).p(2, gate.base).p(3, up.base).p(4, gate.rowStride), [Math.ceil(gate.rows / (256 / this.subgroupSize))]); } else { this.dispatchGemv(pass, gate, this.buffers.get('normed')!, this.buffers.get('mlpGate')!); this.dispatchGemv(pass, up, this.buffers.get('normed')!, this.buffers.get('mlpUp')!); } this.dispatch(pass, 'silu_mul', { gate: this.buffers.get('mlpGate')!, up: this.buffers.get('mlpUp')!, out: this.buffers.get('mlpAct')!, }, imm.reset().p(0, cfg.intermediateSize), [1]); this.dispatchGemv(pass, down, this.buffers.get('mlpAct')!, this.buffers.get('mixer')!); this.dispatch(pass, 'add', { x: this.buffers.get('hidden')!, delta: this.buffers.get('mixer')!, }, imm.reset().p(0, cfg.hiddenSize), [1]); } this.dispatch(pass, 'advance', {}, imm.reset(), [1]); if (this.diagnosticStopAfter === 'advance') return; if (!includeOutput) return; this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux('final_norm'), out: this.buffers.get('normed')!, }, imm.reset().p(0, cfg.hiddenSize).p(1, 0).f(0, cfg.rmsNormEps), [1]); if (this.diagnosticStopAfter === 'norm') return; const grammarEnabled = this.grammarEnabled; const rowStride = this.tensor('embed_tokens').quantization!.rowStride; for (const segment of this.outputSegments) { this.dispatch(pass, this.embedDtype === 'q8_0' ? 'topk_projection' : `topk_projection_${this.embedDtype}`, { weights: segment.binding, input: this.buffers.get('normed')!, counts: this.buffers.get('counts')!, grammarMask: this.buffers.get('grammarMask')!, candidateTokens: this.buffers.get('candTokens')!, candidateLogits: this.buffers.get('candLogits')!, }, imm.reset() .p(0, segment.rows) .p(1, segment.rowStart) .p(2, segment.tileBase) .p(3, grammarEnabled ? 1 : 0) .p(4, cfg.vocabSize) .p(5, cfg.hiddenSize) .p(6, segment.base).p(7, rowStride) .f(0, 1.5), [segment.tiles * 1]); } if (this.diagnosticStopAfter === 'topk') return; this.dispatch(pass, 'topk_merge', { candidateTokens: this.buffers.get('candTokens')!, candidateLogits: this.buffers.get('candLogits')!, outTokens: this.buffers.get('mergedTokens')!, outLogits: this.buffers.get('mergedTokenLogits')!, }, imm.reset().p(0, this.totalTiles * TOP_K).p(1, TOP_K), [1]); if (this.diagnosticStopAfter === 'merge') return; const profile = this.manifest.samplerProfiles.find((entry) => entry.id === this.samplerProfileId) ?? this.manifest.samplerProfiles[0]!; this.dispatch(pass, 'sampler', { candidateTokens: this.buffers.get('mergedTokens')!, candidateLogits: this.buffers.get('mergedTokenLogits')!, rng: this.buffers.get('rng')!, }, imm.reset().p(0, TOP_K).p(1, profile.minCandidates).f(0, profile.topP).f(1, profile.minP).f(2, profile.temperature), [1]); if (this.diagnosticStopAfter === 'sampler') return; const eos = cfg.eosIds; this.dispatch(pass, 'commit', { ring: this.buffers.get('outRing')!, penaltyRing: this.buffers.get('penaltyRing')!, counts: this.buffers.get('counts')!, }, imm.reset().p(0, eos[0] ?? 248046).p(1, eos[1] ?? 248044).p(2, this.maxNewTokens).p(3, PENALTY_WINDOW), [1]); } async debugSequence(mode: 'embed-norm' | 'advance-norm' | 'embed-advance-norm'): Promise { const control = new Uint32Array(CONTROL_WORDS); control[2] = 1; control[3] = 0; this.device.queue.writeBuffer(this.buffers.get('control')!, 0, control); const encoder = this.device.createCommandEncoder({ label: 'debug-sequence' }); const pass = encoder.beginComputePass(); const imm = this.immediate; if (mode !== 'advance-norm') { this.dispatch(pass, this.embedDtype === 'q8_0' ? 'embedding_prefill' : `embedding_prefill_${this.embedDtype}`, Object.fromEntries([ ['tokens', this.buffers.get('tokens')!], ...this.embedSegments.map((segment, i) => [`w${i}`, this.weightBuffers[this.tensor('embed_tokens').segments[i]!.buffer]!]), ['out', this.buffers.get('hidden')!], ]), imm.reset(), [1]); } if (mode !== 'embed-norm') { this.dispatch(pass, 'advance', {}, imm.reset(), [1]); } this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux('final_norm'), out: this.buffers.get('normed')!, }, imm.reset().p(0, this.manifest.model.text.hiddenSize).p(1, 0).f(0, this.manifest.model.text.rmsNormEps), [1]); pass.end(); this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); } async debugReadF32(name: string, count: number): Promise { const source = this.buffers.get(name); if (!source) throw new Error(`missing buffer ${name}`); const byteLength = count * 4; const readback = this.device.createBuffer({ size: byteLength, usage: USAGE_READBACK }); const encoder = this.device.createCommandEncoder(); encoder.copyBufferToBuffer(source, 0, readback, 0, byteLength); this.device.queue.submit([encoder.finish()]); await readback.mapAsync(GPUMapMode.READ); const result = new Float32Array(readback.getMappedRange().slice(0)); readback.unmap(); readback.destroy(); return result; } async debugReadU32(name: string, count: number): Promise { const source = this.buffers.get(name); if (!source) throw new Error(`missing buffer ${name}`); const byteLength = count * 4; const readback = this.device.createBuffer({ size: byteLength, usage: USAGE_READBACK }); const encoder = this.device.createCommandEncoder(); encoder.copyBufferToBuffer(source, 0, readback, 0, byteLength); this.device.queue.submit([encoder.finish()]); await readback.mapAsync(GPUMapMode.READ); const result = new Uint32Array(readback.getMappedRange().slice(0)); readback.unmap(); readback.destroy(); return result; } async debugQuantGemv(role: string, input: Float32Array): Promise { const binding = this.quant(role); if (input.length !== binding.cols) throw new Error('gemv input width mismatch'); this.device.queue.writeBuffer(this.buffers.get('control')!, 8, Uint32Array.of(1)); const inputBuffer = this.device.createBuffer({ size: input.byteLength, usage: USAGE_STATE }); const outBuffer = this.device.createBuffer({ size: binding.rows * 4, usage: USAGE_STATE }); this.device.queue.writeBuffer(inputBuffer, 0, input as unknown as GPUAllowSharedBufferSource); const encoder = this.device.createCommandEncoder({ label: 'debug-gemv' }); const pass = encoder.beginComputePass(); this.dispatchGemv(pass, binding, inputBuffer, outBuffer); pass.end(); this.device.queue.submit([encoder.finish()]); const bytes = await this.readBufferBytes(outBuffer); inputBuffer.destroy(); outBuffer.destroy(); return new Float32Array(bytes.buffer as ArrayBuffer, bytes.byteOffset, bytes.byteLength / 4); } async debugGdnChunk(input: { qk: Float32Array; projected: Float32Array; alpha: Float32Array; beta: Float32Array; tokens: number; initial?: Float32Array; }): Promise<{ output: Float32Array; state: Float32Array }> { const heads = this.manifest.model.text.linearValueHeads; const valueDim = this.manifest.model.text.linearValueHeadDim; const keyDim = this.manifest.model.text.linearKeyHeadDim; if (input.qk.length !== input.tokens * heads * keyDim * 2) throw new Error('chunk qk shape mismatch'); if (input.projected.length !== input.tokens * heads * valueDim * 3) throw new Error('chunk projected shape mismatch'); if (input.alpha.length !== input.tokens * heads || input.beta.length !== input.tokens * heads) throw new Error('chunk gate shape mismatch'); const stateBytes = heads * keyDim * valueDim * 4; const make = (bytes: number): GPUBuffer => this.device.createBuffer({ size: bytes, usage: USAGE_STATE }); const qk = make(input.qk.byteLength); const projected = make(input.projected.byteLength); const alpha = make(input.alpha.byteLength); const beta = make(input.beta.byteLength); const state = make(stateBytes); const out = make(input.tokens * heads * valueDim * 4); const control = make(256); this.device.queue.writeBuffer(control, 0, new Uint32Array([0, 0, 1, 0])); this.device.queue.writeBuffer(qk, 0, input.qk as unknown as GPUAllowSharedBufferSource); this.device.queue.writeBuffer(projected, 0, input.projected as unknown as GPUAllowSharedBufferSource); this.device.queue.writeBuffer(alpha, 0, input.alpha as unknown as GPUAllowSharedBufferSource); this.device.queue.writeBuffer(beta, 0, input.beta as unknown as GPUAllowSharedBufferSource); if (input.initial) { if (input.initial.length !== stateBytes / 4) throw new Error('chunk initial state shape mismatch'); this.device.queue.writeBuffer(state, 0, input.initial as unknown as GPUAllowSharedBufferSource); } const kernel = this.kernels.get('gdn_chunk')!; const group = this.device.createBindGroup({ layout: kernel.layout, entries: [ { binding: 0, resource: { buffer: control } }, { binding: 1, resource: { buffer: state } }, { binding: 2, resource: { buffer: qk } }, { binding: 3, resource: { buffer: projected } }, { binding: 4, resource: { buffer: alpha } }, { binding: 5, resource: { buffer: beta } }, { binding: 6, resource: { buffer: out } }, ], }); const encoder = this.device.createCommandEncoder({ label: 'gdn-chunk' }); const pass = encoder.beginComputePass(); pass.setPipeline(kernel.pipeline); pass.setBindGroup(0, group); const imm = this.immediate; pass.setImmediates(0, imm.reset().p(0, 0).p(1, input.tokens).words, 0, 16); pass.dispatchWorkgroups(heads * valueDim); pass.end(); this.device.queue.submit([encoder.finish()]); const outputBytes = await this.readBufferBytes(out); const output = new Float32Array(outputBytes.buffer as ArrayBuffer, outputBytes.byteOffset, outputBytes.byteLength / 4); const stateBytesRead = await this.readBufferBytes(state); const finalState = new Float32Array(stateBytesRead.buffer as ArrayBuffer, stateBytesRead.byteOffset, stateBytesRead.byteLength / 4); for (const buffer of [qk, projected, alpha, beta, state, out, control]) buffer.destroy(); return { output, state: finalState }; } setGrammarMask(mask: Uint32Array | null): void { if (!mask) { this.grammarEnabled = false; return; } const bytes = this.buffers.get('grammarMask')!; if (mask.byteLength > bytes.size) throw new Error('grammar mask exceeds the vocabulary mask buffer'); this.device.queue.writeBuffer(bytes, 0, mask as unknown as GPUAllowSharedBufferSource); if (mask.byteLength < bytes.size) { this.device.queue.writeBuffer(bytes, mask.byteLength, new Uint8Array(bytes.size - mask.byteLength)); } this.grammarEnabled = true; } async currentTargetTopK(): Promise<{ tokens: number[]; logits: number[]; profile: { topP: number; minP: number; temperature: number; minCandidates: number } }> { await this.device.queue.onSubmittedWorkDone(); const tokens = [...(await this.debugReadU32('mergedTokens', TOP_K))]; const logits = [...(await this.debugReadF32('mergedTokenLogits', TOP_K))]; const profile = this.manifest.samplerProfiles.find((entry) => entry.id === this.samplerProfileId) ?? this.manifest.samplerProfiles[0]!; return { tokens, logits, profile: { topP: profile.topP, minP: profile.minP, temperature: profile.temperature, minCandidates: profile.minCandidates, }, }; } async debugNoop(): Promise { console.error('[botpsy] noop start'); const encoder = this.device.createCommandEncoder(); this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); console.error('[botpsy] noop done'); } async debugNorm(): Promise { const control = new Uint32Array(CONTROL_WORDS); control[2] = 1; this.device.queue.writeBuffer(this.buffers.get('control')!, 0, control); const encoder = this.device.createCommandEncoder({ label: 'debug-norm' }); this.device.pushErrorScope('validation'); const pass = encoder.beginComputePass(); this.dispatch(pass, 'rmsnorm', { x: this.buffers.get('hidden')!, weight: this.aux('final_norm'), out: this.buffers.get('normed')!, }, this.immediate.reset().p(0, this.manifest.model.text.hiddenSize).p(1, 0).f(0, this.manifest.model.text.rmsNormEps), [1]); pass.end(); this.device.queue.submit([encoder.finish()]); const validation = await this.device.popErrorScope(); if (validation) throw new Error(validation.message); await this.device.queue.onSubmittedWorkDone(); } setPositionDelta(delta: number): void { this.positionDelta = Math.trunc(delta); } async prefill(tokens: Uint32Array, options: PrefillOptions = {}): Promise { options.signal?.throwIfAborted(); if (this.destroyed) throw new Error('engine disposed'); if (this.loadError) throw this.loadError; if (this.processed + tokens.length > this.contextLength) throw new Error('context length exceeded'); const full = [...this.sessionTokens, ...tokens]; if (full.length !== this.processed + tokens.length) throw new Error('session token prefix mismatch'); const tokenData = new Uint32Array(this.contextLength); tokenData.set(full); this.device.queue.writeBuffer(this.buffers.get('tokens')!, 0, tokenData); this.sessionTokens = full; if (options.seed !== undefined) { this.writeRng(options.seed, options.samplerProfile ?? this.samplerProfileId); } if (options.images && options.images.length > 0) { const ranges: Array<{ start: number; count: number; offset: number }> = []; let offset = 0; const embeddings = new Float32Array(4096 * this.manifest.model.text.hiddenSize); for (const image of options.images) { if (image.embeddings.length !== image.tokenCount * this.manifest.model.text.hiddenSize) throw new Error('image embedding shape mismatch'); if (offset + image.tokenCount > 4096) throw new Error('image token count exceeds admitted vision capacity'); embeddings.set(image.embeddings, offset * this.manifest.model.text.hiddenSize); ranges.push({ start: image.tokenStart, count: image.tokenCount, offset }); offset += image.tokenCount; } this.device.queue.writeBuffer(this.buffers.get('visionEmbeds')!, 0, embeddings as unknown as GPUAllowSharedBufferSource); this.visionRanges = ranges; } else { this.visionRanges = []; } this.samplerProfileId = options.samplerProfile ?? this.samplerProfileId; this.maxNewTokens = options.maxNewTokens ?? 0xffffffff; this.requestEmittedBase = this.emitted; const penaltyEncoder = this.device.createCommandEncoder({ label: 'prefill-penalty-reset' }); penaltyEncoder.clearBuffer(this.buffers.get('counts')!); penaltyEncoder.clearBuffer(this.buffers.get('penaltyRing')!); this.device.queue.submit([penaltyEncoder.finish()]); const control = new Uint32Array(CONTROL_WORDS); control[2] = 1; control[3] = this.processed; control[5] = this.emitted; control[13] = this.requestEmittedBase + this.maxNewTokens; this.device.queue.writeBuffer(this.buffers.get('control')!, 0, control); const start = this.processed; const end = full.length; if (end === start) throw new Error('nothing to prefill'); // Cap submitted work so a long prompt cannot put 128 full forward passes in one GPU job. const chunkSize = 8; for (let chunkStart = start; chunkStart < end; chunkStart += chunkSize) { const chunkEnd = Math.min(end, chunkStart + chunkSize); const encoder = this.device.createCommandEncoder({ label: `prefill-${chunkStart}` }); const pass = encoder.beginComputePass(); for (let position = chunkStart; position < chunkEnd; position++) { const includeOutput = position === end - 1; const positionIds = options.positions?.[position] ?? [position, position, position]; this.encodeForward(pass, position, positionIds, 'prefill', includeOutput); } pass.end(); this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); if (this.loadError) throw this.loadError; options.signal?.throwIfAborted(); options.onProgress?.(chunkEnd, end); } const readback = await this.readback(); this.active = readback.control[2] !== 0; this.processed = readback.control[3]!; this.pendingToken = readback.control[8]!; this.emitted = readback.control[5]!; this.stopReason = readback.control[6]!; this.ringCount = readback.control[7]!; // Reset the output ring index; the emitted count remains authoritative. this.device.queue.writeBuffer(this.buffers.get('control')!, 7 * 4, Uint32Array.of(0)); this.ringCount = 0; if (this.emitted > 0) this.pendingEmissions = [readback.ring[0]!]; this.targetTopKValid = true; return { processedLength: this.processed, prefixHash: asPrefixHash(`${this.identity.modelHash}:${this.processed}`), pendingToken: this.pendingToken, samplerPhase: 'afterDraw', }; } async *generate(req: GenerateRequest): AsyncIterable { if (this.pendingToken === null) throw new Error('prefill must sample the first token before generation'); this.requestId = req.requestId; this.epoch = req.epoch; this.cancelling = false; if (this.speculativeDrafter) { await this.applySpeculation(); this.pendingEmissions = [this.pendingToken]; } for (let i = 0; i < this.pendingEmissions.length; i++) { yield { type: 'token', requestId: req.requestId, tokenId: this.pendingEmissions[i]!, index: i }; } this.pendingEmissions = []; this.maxNewTokens = req.maxNewTokens; this.samplerProfileId = req.samplerProfile; this.device.queue.writeBuffer(this.buffers.get('control')!, 13 * 4, Uint32Array.of(this.requestEmittedBase + req.maxNewTokens)); if (this.emitted >= this.requestEmittedBase + req.maxNewTokens) { yield { type: 'completion', requestId: req.requestId, reason: 'length', processed: this.processed, emitted: this.emitted }; return; } if (this.stopReason === 1) { yield { type: 'completion', requestId: req.requestId, reason: 'eos', processed: this.processed, emitted: this.emitted }; return; } if (!this.active) { const control = new Uint32Array(CONTROL_WORDS); control[2] = 1; control[3] = this.processed; control[5] = this.emitted; control[8] = this.pendingToken; control[13] = this.maxNewTokens; this.device.queue.writeBuffer(this.buffers.get('control')!, 0, control); this.active = true; } while (this.active) { if (this.cancelling) { yield { type: 'cancelled', requestId: req.requestId, boundary: this.prefixState() }; return; } const remainingTokens = this.requestEmittedBase + req.maxNewTokens - this.emitted; const remainingContext = this.contextLength - this.processed; const width = Math.min(this.windowWidth, remainingTokens, remainingContext); if (width <= 0) break; const encoder = this.device.createCommandEncoder({ label: 'decode-window' }); const pass = encoder.beginComputePass(); for (let step = 0; step < width; step++) { const position = this.processed + step; const rope = position + this.positionDelta; this.encodeForward(pass, position, [rope, rope, rope], 'decode', true); } pass.end(); this.device.queue.submit([encoder.finish()]); const readback = await this.readback(); const newTokens: number[] = []; for (let i = this.ringCount; i < readback.control[7]!; i++) newTokens.push(readback.ring[i]!); const previousEmitted = this.emitted; const processedBefore = this.processed; const pendingBefore = this.pendingToken; this.processed = readback.control[3]!; const committed = this.processed - processedBefore; if (pendingBefore !== null && committed > 0) this.sessionTokens.push(pendingBefore); for (let i = 0; i < committed - 1; i++) { const token = newTokens[i]; if (token !== undefined) this.sessionTokens.push(token); } if (this.sessionTokens.length !== this.processed) throw new Error('generated token prefix diverged from processed length'); this.pendingToken = readback.control[8]!; this.emitted = readback.control[5]!; this.stopReason = readback.control[6]!; this.active = readback.control[2] !== 0; this.ringCount = readback.control[7]!; this.device.queue.writeBuffer(this.buffers.get('control')!, 7 * 4, Uint32Array.of(0)); this.ringCount = 0; this.targetTopKValid = true; if (this.speculativeDrafter && newTokens.length > 0) { const targetPending = newTokens[newTokens.length - 1]!; this.pendingToken = targetPending; if (await this.applySpeculation()) newTokens[newTokens.length - 1] = this.pendingToken; } for (let index = 0; index < newTokens.length; index++) { yield { type: 'token', requestId: req.requestId, tokenId: newTokens[index]!, index: previousEmitted + index }; } if (!this.active || this.stopReason !== 0) { const reason = this.stopReason === 1 ? 'eos' : this.stopReason === 2 ? 'length' : this.stopReason === 5 ? 'fault' : 'window'; yield { type: 'completion', requestId: req.requestId, reason, processed: this.processed, emitted: this.emitted }; return; } if (this.cancelling) { yield { type: 'cancelled', requestId: req.requestId, boundary: this.prefixState() }; return; } } yield { type: 'completion', requestId: req.requestId, reason: 'length', processed: this.processed, emitted: this.emitted }; } private writeRng(seed: bigint, profile: ProfileId): void { const rng = new Uint32Array(8); rng[0] = 0; rng[1] = 0; rng[2] = 0; rng[3] = 0; rng[4] = Number(seed & 0xffffffffn); rng[5] = Number((seed >> 32n) & 0xffffffffn); rng[6] = Number(seed >> 64n) & 0xffffffff; rng[7] = Number(seed >> 96n) & 0xffffffff; this.device.queue.writeBuffer(this.buffers.get('rng')!, 0, rng); this.samplerProfileId = profile; } private async readBufferBytes(source: GPUBuffer): Promise { const staging = this.device.createBuffer({ size: source.size, usage: USAGE_READBACK }); const encoder = this.device.createCommandEncoder({ label: 'checkpoint-read' }); encoder.copyBufferToBuffer(source, 0, staging, 0, source.size); this.device.queue.submit([encoder.finish()]); await staging.mapAsync(GPUMapMode.READ); const bytes = new Uint8Array(staging.getMappedRange().slice(0)); staging.unmap(); staging.destroy(); return bytes; } private async readback(): Promise { const encoder = this.device.createCommandEncoder({ label: 'readback' }); encoder.copyBufferToBuffer(this.buffers.get('control')!, 0, this.readbackBuffer, 0, 256); encoder.copyBufferToBuffer(this.buffers.get('outRing')!, 0, this.readbackBuffer, 256, RING_WORDS * 4); this.device.queue.submit([encoder.finish()]); try { await this.readbackBuffer.mapAsync(GPUMapMode.READ); } catch (error) { throw this.loadError ?? error; } const mapped = new Uint32Array(this.readbackBuffer.getMappedRange().slice(0)); this.readbackBuffer.unmap(); return { control: mapped.slice(0, CONTROL_WORDS), ring: mapped.slice(CONTROL_WORDS, CONTROL_WORDS + RING_WORDS), }; } private prefixState(): PrefixState { return { processedLength: this.processed, prefixHash: asPrefixHash(`${this.identity.modelHash}:${this.processed}`), pendingToken: this.pendingToken ?? undefined, samplerPhase: 'afterDraw', }; } async createVisionEncoder(manifestUrl: string, options: VisionLoadOptions = {}): Promise { return VisionGpuEncoder.create(this.device, manifestUrl, { subgroupSize: this.subgroupSize, ...options }); } enableSpeculation(drafter: Drafter): void { this.speculativeDrafter = drafter; this.windowWidth = 1; } disableSpeculation(): void { this.speculativeDrafter = null; this.windowWidth = this.configuredWindowWidth; } get speculationStats(): { accepted: number; rejected: number } { return { accepted: this.speculativeAccepted, rejected: this.speculativeRejected }; } private async replacePendingToken(token: number): Promise { const cfg = this.manifest.model.text; const kernel = this.kernels.get('replace_pending')!; const group = this.device.createBindGroup({ layout: kernel.layout, entries: [ { binding: 0, resource: { buffer: this.buffers.get('control')! } }, { binding: 1, resource: { buffer: this.buffers.get('penaltyRing')! } }, { binding: 2, resource: { buffer: this.buffers.get('counts')! } }, ], }); const encoder = this.device.createCommandEncoder({ label: 'replace-pending' }); const pass = encoder.beginComputePass(); pass.setPipeline(kernel.pipeline); pass.setBindGroup(0, group); pass.setImmediates( 0, this.immediate.reset().p(0, token).p(1, PENALTY_WINDOW).p(2, cfg.eosIds[0] ?? 248046).p(3, cfg.eosIds[1] ?? 248044).words, 0, 16, ); pass.dispatchWorkgroups(1); pass.end(); this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); const readback = await this.readback(); this.pendingToken = token; this.emitted = readback.control[5]!; this.active = readback.control[2] !== 0; this.stopReason = readback.control[6]!; } /** Verify the pending target sample against one context-draft proposal. */ private async applySpeculation(): Promise { const drafter = this.speculativeDrafter; if (!drafter || this.pendingToken === null || !this.targetTopKValid) return false; drafter.setHistory(this.sessionTokens); const draft = drafter.propose(1); if (draft.proposals.length === 0) return false; const topk = await this.currentTargetTopK(); const target = targetDistributionFromTopK(topk, topk.profile); if (target.tokens.length === 0) return false; const proposal = draft.proposals[0]!; const draftDistribution = draft.distributions[0]!; const px = probabilityOf(target, proposal); const qx = probabilityOf(draftDistribution, proposal); if (!(qx > 0)) return false; let chosen: number; if (drafter.uniform() < Math.min(1, px / qx)) { chosen = proposal; this.speculativeAccepted++; } else { try { chosen = sampleResidual(target, draftDistribution, () => drafter.uniform()); } catch { return false; } this.speculativeRejected++; } await this.replacePendingToken(chosen); return true; } async checkpoint(): Promise { await this.device.queue.onSubmittedWorkDone(); const names = ['states', 'convHistory', 'kCache', 'vCache', 'kvPageTable', 'counts', 'penaltyRing', 'rng', 'control', 'outRing']; const snapshots = new Map(); const encoder = this.device.createCommandEncoder({ label: 'checkpoint' }); for (const name of names) { const source = this.buffers.get(name)!; const copy = this.device.createBuffer({ label: `checkpoint-${name}`, size: source.size, usage: USAGE_STATE }); encoder.copyBufferToBuffer(source, 0, copy, 0, source.size); snapshots.set(name, copy); } this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); const id = `mem-${this.processed}-${this.emitted}-${this.checkpoints.size}-${Date.now()}`; this.checkpoints.set(id, { buffers: snapshots, tokens: [...this.sessionTokens], processed: this.processed, pending: this.pendingToken, emitted: this.emitted, active: this.active, stopReason: this.stopReason, ringCount: this.ringCount, positionDelta: this.positionDelta, requestEmittedBase: this.requestEmittedBase, pendingEmissions: [...this.pendingEmissions], identity: this.identity, }); return { id: asCheckpointId(id), identity: this.identity, prefix: this.prefixState(), canResampleNext: false, }; } async exportCheckpoint(ref: CheckpointRef): Promise { const snapshot = this.checkpoints.get(String(ref.id)); if (!snapshot) throw new Error('checkpoint not found in this worker'); const buffers: Array<{ name: string; size: number; bytes: Uint8Array }> = []; for (const [name, source] of snapshot.buffers) { const bytes = await this.readBufferBytes(source); buffers.push({ name, size: source.size, bytes }); } const header = new TextEncoder().encode(JSON.stringify({ schemaVersion: 1, identity: snapshot.identity ?? this.identity, meta: { tokens: snapshot.tokens, processed: snapshot.processed, pending: snapshot.pending, emitted: snapshot.emitted, active: snapshot.active, stopReason: snapshot.stopReason, ringCount: snapshot.ringCount, positionDelta: snapshot.positionDelta, requestEmittedBase: snapshot.requestEmittedBase, pendingEmissions: snapshot.pendingEmissions, }, buffers: buffers.map(({ name, size }) => ({ name, size })), })); const padded = Math.ceil(header.byteLength / 8) * 8; const total = 8 + padded + buffers.reduce((sum, buffer) => sum + buffer.size, 0); const output = new Uint8Array(total); new DataView(output.buffer).setUint32(0, header.byteLength, true); new DataView(output.buffer).setUint32(4, buffers.length, true); output.set(header, 8); let offset = 8 + padded; for (const buffer of buffers) { output.set(buffer.bytes, offset); offset += buffer.size; } return output; } async importCheckpoint(bytes: Uint8Array): Promise { if (bytes.byteLength < 16) throw new Error('checkpoint is truncated'); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); const headerLength = view.getUint32(0, true); const padded = Math.ceil(headerLength / 8) * 8; if (8 + padded > bytes.byteLength) throw new Error('checkpoint header is truncated'); const header = JSON.parse(new TextDecoder().decode(bytes.subarray(8, 8 + headerLength))) as { schemaVersion: number; identity: EngineIdentity; meta: { tokens: number[]; processed: number; pending: number | null; emitted: number; active: boolean; stopReason: number; ringCount: number; positionDelta: number; requestEmittedBase: number; pendingEmissions: number[]; }; buffers: Array<{ name: string; size: number }>; }; if (header.schemaVersion !== 1) throw new Error('unsupported checkpoint schema'); if ( header.identity.modelHash !== this.identity.modelHash || header.identity.tokenizerHash !== this.identity.tokenizerHash || header.identity.templateHash !== this.identity.templateHash || header.identity.numericalProfile !== this.identity.numericalProfile || header.identity.stateSchema !== this.identity.stateSchema ) { throw new Error('checkpoint identity mismatch'); } const snapshots = new Map(); let offset = 8 + padded; for (const record of header.buffers) { if (offset + record.size > bytes.byteLength) throw new Error('checkpoint payload is truncated'); const target = this.buffers.get(record.name); if (!target) throw new Error(`checkpoint buffer ${record.name} is not part of this runtime`); if (target.size !== record.size) throw new Error(`checkpoint buffer ${record.name} size mismatch`); const buffer = this.device.createBuffer({ label: `checkpoint-${record.name}`, size: record.size, usage: USAGE_STATE }); this.device.queue.writeBuffer(buffer, 0, bytes.subarray(offset, offset + record.size) as unknown as GPUAllowSharedBufferSource); snapshots.set(record.name, buffer); offset += record.size; } await this.device.queue.onSubmittedWorkDone(); const id = `import-${header.meta.processed}-${header.meta.emitted}-${this.checkpoints.size}-${Date.now()}`; this.checkpoints.set(id, { buffers: snapshots, tokens: header.meta.tokens, processed: header.meta.processed, pending: header.meta.pending, emitted: header.meta.emitted, active: header.meta.active, stopReason: header.meta.stopReason, ringCount: header.meta.ringCount, positionDelta: header.meta.positionDelta, requestEmittedBase: header.meta.requestEmittedBase ?? 0, pendingEmissions: header.meta.pendingEmissions ?? [], identity: header.identity, }); this.positionDelta = header.meta.positionDelta; return { id: asCheckpointId(id), identity: this.identity, prefix: { processedLength: header.meta.processed, prefixHash: asPrefixHash(`${this.identity.modelHash}:${header.meta.processed}`), pendingToken: header.meta.pending ?? undefined, samplerPhase: 'afterDraw', }, canResampleNext: false, }; } async restore(ref: CheckpointRef): Promise { if (ref.identity.modelHash !== this.identity.modelHash) throw new Error('checkpoint model mismatch'); if (ref.identity.tokenizerHash !== this.identity.tokenizerHash) throw new Error('checkpoint tokenizer mismatch'); if (ref.identity.stateSchema !== this.identity.stateSchema) throw new Error('checkpoint schema mismatch'); const snapshot = this.checkpoints.get(String(ref.id)); if (!snapshot) throw new Error('checkpoint not found in this worker'); await this.device.queue.onSubmittedWorkDone(); const encoder = this.device.createCommandEncoder({ label: 'restore' }); for (const [name, source] of snapshot.buffers) { const target = this.buffers.get(name)!; encoder.copyBufferToBuffer(source, 0, target, 0, Math.min(source.size, target.size)); } this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); this.sessionTokens = [...snapshot.tokens]; this.processed = snapshot.processed; this.pendingToken = snapshot.pending; this.emitted = snapshot.emitted; this.active = snapshot.active; this.stopReason = snapshot.stopReason; this.ringCount = snapshot.ringCount; this.positionDelta = snapshot.positionDelta ?? 0; this.requestEmittedBase = snapshot.requestEmittedBase ?? 0; this.pendingEmissions = [...snapshot.pendingEmissions]; this.targetTopKValid = false; return this.prefixState(); } releaseCheckpoint(id: CheckpointId): void { const snapshot = this.checkpoints.get(String(id)); if (!snapshot) return; for (const buffer of snapshot.buffers.values()) buffer.destroy(); this.checkpoints.delete(String(id)); } async cancel(requestId: number): Promise { if (requestId !== this.requestId) return this.prefixState(); this.cancelling = true; return this.prefixState(); } async reset(): Promise { const encoder = this.device.createCommandEncoder({ label: 'reset' }); for (const name of ['states', 'convHistory', 'kCache', 'vCache', 'counts', 'penaltyRing', 'outRing', 'scores']) { const buffer = this.buffers.get(name)!; encoder.clearBuffer(buffer); } encoder.clearBuffer(this.buffers.get('control')!); encoder.clearBuffer(this.buffers.get('rng')!); this.device.queue.submit([encoder.finish()]); await this.device.queue.onSubmittedWorkDone(); this.initializeControl(); this.initializeKvPageTable(); this.sessionTokens = []; this.processed = 0; this.pendingToken = null; this.emitted = 0; this.active = false; this.ringCount = 0; this.stopReason = 0; this.positionDelta = 0; this.requestEmittedBase = 0; this.pendingEmissions = []; this.targetTopKValid = false; this.visionRanges = []; } async dispose(): Promise { if (this.destroyed) return; this.destroyed = true; for (const buffer of this.buffers.values()) buffer.destroy(); for (const buffer of this.auxBuffers.values()) buffer.destroy(); for (const snapshot of this.checkpoints.values()) for (const buffer of snapshot.buffers.values()) buffer.destroy(); this.checkpoints.clear(); for (const buffer of this.weightBuffers) buffer.destroy(); this.readbackBuffer.destroy(); this.device.destroy(); } get tokenIds(): readonly number[] { return this.sessionTokens; } get state(): { processed: number; pendingToken: number | null; active: boolean; emitted: number; stopReason: number } { return { processed: this.processed, pendingToken: this.pendingToken, active: this.active, emitted: this.emitted, stopReason: this.stopReason, }; } }