File size: 11,677 Bytes
82b533a |
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
/**
* Decoder Worker - Runs adapter + decoder in a separate thread
*/
importScripts('https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/ort.min.js');
// Configure ONNX Runtime to find WASM files from CDN
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.17.0/dist/';
// Helper to fetch model with progress reporting
async function fetchModelWithProgress(url, modelName) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch ${modelName}: ${response.status}`);
}
const contentLength = response.headers.get('Content-Length');
const total = contentLength ? parseInt(contentLength, 10) : 0;
if (!response.body || !total) {
// No streaming support or unknown size - just download
const buffer = await response.arrayBuffer();
self.postMessage({
type: 'progress',
model: modelName,
loaded: buffer.byteLength,
total: buffer.byteLength,
done: true
});
return buffer;
}
const reader = response.body.getReader();
const chunks = [];
let loaded = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks.push(value);
loaded += value.length;
self.postMessage({
type: 'progress',
model: modelName,
loaded,
total,
done: false
});
}
self.postMessage({
type: 'progress',
model: modelName,
loaded: total,
total,
done: true
});
// Combine chunks into single ArrayBuffer
const result = new Uint8Array(loaded);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result.buffer;
}
// Model config
let cfg = null;
let tailLatency = 0;
// Sessions
let adapterSession = null;
let decoderInitSession = null;
let decoderStepSession = null;
// Decoder state
let crossCache = null;
let selfCache = null;
// Tokenizer
let tokenizer = null;
// Accumulated features
let accumulatedFeatures = null;
let currentSegmentId = null;
class MoonshineTokenizer {
constructor() {
this.decoder = null;
this.vocab = null;
}
load(tokenizerJson) {
this.vocab = tokenizerJson.model.vocab;
this.decoder = Object.fromEntries(
Object.entries(this.vocab).map(([k, v]) => [v, k])
);
}
decode(tokenIds, skipSpecial = true) {
const specialTokens = new Set([0, 1, 2]);
let text = '';
for (const id of tokenIds) {
if (skipSpecial && specialTokens.has(id)) continue;
const token = this.decoder[id] || '';
text += token;
}
// Handle various space placeholder representations
text = text.replace(/\u0120/g, ' '); // Ġ (GPT-2 style)
text = text.replace(/Ġ/g, ' '); // Literal Ġ character
text = text.replace(/▁/g, ' '); // SentencePiece style (U+2581)
text = text.replace(/\u010a/g, '\n'); // Newline marker
return text.trim();
}
}
async function runAdapter(features, dims) {
const feeds = {
'encoder_output': new ort.Tensor('float32', features, dims)
};
const results = await adapterSession.run(feeds);
return results.context;
}
async function initDecoderCache(context) {
const feeds = { 'context': context };
const results = await decoderInitSession.run(feeds);
// Store cross-attention cache (even-indexed layers)
crossCache = [];
for (let i = 0; i < cfg.depth * 2; i++) {
if ((i + 1) % 2 === 0) {
crossCache.push({
k: results[`cache_${i}_k`],
v: results[`cache_${i}_v`]
});
}
}
// Initialize empty self-attention cache
selfCache = [];
for (let i = 0; i < cfg.depth; i++) {
selfCache.push({
k: new ort.Tensor('float32', new Float32Array(0), [1, cfg.nheads, 0, cfg.head_dim]),
v: new ort.Tensor('float32', new Float32Array(0), [1, cfg.nheads, 0, cfg.head_dim])
});
}
}
async function decodeStep(tokenId, position) {
const feeds = {
'token_id': new ort.Tensor('int64', BigInt64Array.from([BigInt(tokenId)]), [1, 1]),
'position': new ort.Tensor('int64', BigInt64Array.from([BigInt(position)]), [1])
};
// Add cache inputs
let selfIdx = 0;
let crossIdx = 0;
for (let i = 0; i < cfg.depth * 2; i++) {
if ((i + 1) % 2 !== 0) {
feeds[`in_cache_${i}_k`] = selfCache[selfIdx].k;
feeds[`in_cache_${i}_v`] = selfCache[selfIdx].v;
selfIdx++;
} else {
feeds[`in_cache_${i}_k`] = crossCache[crossIdx].k;
feeds[`in_cache_${i}_v`] = crossCache[crossIdx].v;
crossIdx++;
}
}
const results = await decoderStepSession.run(feeds);
// Update self-attention cache
selfIdx = 0;
for (let i = 0; i < cfg.depth * 2; i++) {
if ((i + 1) % 2 !== 0) {
selfCache[selfIdx] = {
k: results[`out_cache_${i}_k`],
v: results[`out_cache_${i}_v`]
};
selfIdx++;
}
}
return results.logits;
}
async function decodeAccumulated() {
if (!accumulatedFeatures || accumulatedFeatures.dims[1] === 0) {
return '';
}
try {
const context = await runAdapter(accumulatedFeatures.data, accumulatedFeatures.dims);
await initDecoderCache(context);
const numFrames = accumulatedFeatures.dims[1];
const maxTokens = Math.max(10, Math.floor(numFrames * 1.5));
const tokens = [1]; // BOS
for (let step = 0; step < maxTokens; step++) {
const logits = await decodeStep(tokens[tokens.length - 1], step);
let maxIdx = 0;
let maxVal = logits.data[0];
for (let i = 1; i < cfg.vocab_size; i++) {
if (logits.data[i] > maxVal) {
maxVal = logits.data[i];
maxIdx = i;
}
}
tokens.push(maxIdx);
if (maxIdx === 2) break; // EOS
}
return tokenizer.decode(tokens, true);
} catch (e) {
console.error('Decode error:', e);
return '';
}
}
self.onmessage = async function(e) {
const { type, data } = e.data;
switch (type) {
case 'init': {
try {
cfg = data.cfg;
const onnxUrl = data.onnxUrl;
const modelName = data.modelName;
const dtype = 'fp32';
tailLatency = cfg.n_future * cfg.encoder_depth;
// Load tokenizer
self.postMessage({ type: 'status', message: 'Loading tokenizer...' });
self.postMessage({ type: 'model_start', model: 'Tokenizer' });
const tokenizerResponse = await fetch(`${onnxUrl}/tokenizer.json`);
const tokenizerJson = await tokenizerResponse.json();
tokenizer = new MoonshineTokenizer();
tokenizer.load(tokenizerJson);
self.postMessage({ type: 'model_done', model: 'Tokenizer' });
// Initialize adapter
const adapterUrl = `${onnxUrl}/adapter_${modelName}_${dtype}.onnx`;
self.postMessage({ type: 'status', message: 'Loading adapter...' });
self.postMessage({ type: 'model_start', model: 'Adapter' });
const adapterBuffer = await fetchModelWithProgress(adapterUrl, 'Adapter');
adapterSession = await ort.InferenceSession.create(adapterBuffer);
self.postMessage({ type: 'model_done', model: 'Adapter' });
// Initialize decoder init
const decInitUrl = `${onnxUrl}/decoder_init_${modelName}_${dtype}.onnx`;
self.postMessage({ type: 'status', message: 'Loading decoder (init)...' });
self.postMessage({ type: 'model_start', model: 'Decoder Init' });
const decInitBuffer = await fetchModelWithProgress(decInitUrl, 'Decoder Init');
decoderInitSession = await ort.InferenceSession.create(decInitBuffer);
self.postMessage({ type: 'model_done', model: 'Decoder Init' });
// Initialize decoder step
const decStepUrl = `${onnxUrl}/decoder_step_${modelName}_${dtype}.onnx`;
self.postMessage({ type: 'status', message: 'Loading decoder (step)...' });
self.postMessage({ type: 'model_start', model: 'Decoder Step' });
const decStepBuffer = await fetchModelWithProgress(decStepUrl, 'Decoder Step');
decoderStepSession = await ort.InferenceSession.create(decStepBuffer);
self.postMessage({ type: 'model_done', model: 'Decoder Step' });
self.postMessage({ type: 'ready' });
} catch (err) {
self.postMessage({ type: 'error', message: err.message });
}
break;
}
case 'segment_start': {
accumulatedFeatures = null;
currentSegmentId = data.segmentId;
self.postMessage({ type: 'live_caption', text: '' });
break;
}
case 'segment_end': {
if (data.segmentId !== currentSegmentId) break;
const text = await decodeAccumulated();
self.postMessage({
type: 'transcript',
segmentId: data.segmentId,
text: text
});
accumulatedFeatures = null;
currentSegmentId = null;
self.postMessage({ type: 'live_caption', text: '' });
break;
}
case 'features': {
if (data.segmentId !== currentSegmentId) break;
const newFeatures = {
data: new Float32Array(data.features),
dims: data.dims
};
console.log(`Decoder received ${data.dims[1]} frames, accumulated: ${accumulatedFeatures ? accumulatedFeatures.dims[1] : 0}`);
if (accumulatedFeatures === null) {
accumulatedFeatures = newFeatures;
} else {
// Trim last tailLatency frames from accumulated
const numFrames = accumulatedFeatures.dims[1];
const keepFrames = Math.max(0, numFrames - tailLatency);
if (keepFrames > 0) {
const totalFrames = keepFrames + newFeatures.dims[1];
const combined = new Float32Array(totalFrames * cfg.dim);
// Copy kept frames
for (let f = 0; f < keepFrames; f++) {
for (let d = 0; d < cfg.dim; d++) {
combined[f * cfg.dim + d] = accumulatedFeatures.data[f * cfg.dim + d];
}
}
// Copy new frames
combined.set(newFeatures.data, keepFrames * cfg.dim);
accumulatedFeatures = {
data: combined,
dims: [1, totalFrames, cfg.dim]
};
} else {
accumulatedFeatures = newFeatures;
}
}
// Live caption
const partialText = await decodeAccumulated();
self.postMessage({ type: 'live_caption', text: partialText });
break;
}
}
};
|