File size: 13,369 Bytes
82b533a f5961bb 82b533a f5961bb 82b533a f5961bb 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 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 |
/**
* 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;
// Decoding config
const TOKENS_PER_SECOND = 6.5; // Max tokens per second of audio
const FRAME_DURATION_MS = 20; // Each encoder frame is 20ms
// Check for repetitive token patterns that indicate decoding should stop
function hasRepetition(tokens) {
const len = tokens.length;
if (len < 5) return false;
// Check if last 5 tokens are the same
const last5 = tokens.slice(-5);
if (last5.every(t => t === last5[0])) {
return true;
}
// Check for 3 repeated same pairs (e.g., [A,B,A,B,A,B])
if (len >= 6) {
const pair1 = [tokens[len - 6], tokens[len - 5]];
const pair2 = [tokens[len - 4], tokens[len - 3]];
const pair3 = [tokens[len - 2], tokens[len - 1]];
if (pair1[0] === pair2[0] && pair2[0] === pair3[0] &&
pair1[1] === pair2[1] && pair2[1] === pair3[1]) {
return true;
}
}
// Check for 2 repeated same triples (e.g., [A,B,C,A,B,C])
if (len >= 6) {
const triple1 = [tokens[len - 6], tokens[len - 5], tokens[len - 4]];
const triple2 = [tokens[len - 3], tokens[len - 2], tokens[len - 1]];
if (triple1[0] === triple2[0] &&
triple1[1] === triple2[1] &&
triple1[2] === triple2[2]) {
return true;
}
}
return false;
}
// 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];
// Calculate duration in seconds and max tokens based on that
const durationSeconds = (numFrames * FRAME_DURATION_MS) / 1000;
const maxTokens = Math.max(10, Math.floor(durationSeconds * TOKENS_PER_SECOND));
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);
// Stop on EOS
if (maxIdx === 2) break;
// Stop on repetitive patterns
if (hasRepetition(tokens)) {
console.log('Stopping decode due to repetition detected');
break;
}
}
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;
}
}
};
|