Spaces:
Running
Running
File size: 7,142 Bytes
9b81ca9 | 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 | // Shenava Rizeh v1.5 RNN-T engine, runtime-agnostic (onnxruntime-web in the browser, onnxruntime-node for evaluation).
// - streaming pass: cache-aware chunked encoder (45 fbank frames in, hop 32 = 320 ms, 8 encoder frames out) + greedy RNN-T
// - correction pass: full-context encoder over the utterance + beam search with in-beam word-level n-gram LM fusion
import { normTokens } from './lm.js';
const D = 512, V = 2080;
// Persian output only: shared ids 0..31 + Persian block 1056..2079 (English block 32..1055 is masked)
export const ALLOWED = Int32Array.from([...Array(32).keys(), ...Array.from({ length: 1024 }, (_, i) => 1056 + i)]);
const LN10 = Math.LN10;
export class Engine {
constructor(ort, sessions, pieces, streamCfg) {
this.ort = ort; Object.assign(this, sessions); // streamEnc, offEnc, dec, joi
this.pieces = pieces; this.cfg = streamCfg;
this.T = +streamCfg.meta.T; this.hop = +streamCfg.meta.decode_chunk_len;
this.wordStart = pieces.map(p => p.startsWith('▁'));
}
i64(arr, dims) { return new this.ort.Tensor('int64', BigInt64Array.from(arr, BigInt), dims); }
f32(arr, dims) { return new this.ort.Tensor('float32', arr, dims); }
async decode(ctxs) { // ctxs: array of [a,b] -> Float32Array(N*512)
const flat = []; for (const c of ctxs) flat.push(c[0], c[1]);
const o = await this.dec.run({ y: this.i64(flat, [ctxs.length, 2]) });
return o.decoder_out.data;
}
async join(enc, decOut, n) { const o = await this.joi.run({ encoder_out: this.f32(enc, [n, D]), decoder_out: this.f32(decOut, [n, D]) }); return o.logit.data; }
text(toks) { return toks.map(k => this.pieces[k]).join('').replace(/▁/g, ' ').replace(/\s+/g, ' ').trim(); }
// ---------------- streaming ----------------
async newStream() {
const st = { states: {}, ctx: [0, 0], toks: [], frames: [], dout: null, chunk: 0 };
for (const [name, dt, dims] of this.cfg.inputs.slice(1)) {
const n = dims.reduce((a, b) => a * b, 1);
st.states[name] = dt === 'int64' ? new this.ort.Tensor('int64', new BigInt64Array(n), dims) : this.f32(new Float32Array(n), dims);
}
st.dout = await this.decode([st.ctx]);
return st;
}
/** feed one chunk (Float32Array(45*80)); greedy-decodes its 8 encoder frames. returns number of new tokens */
async streamChunk(st, x) {
const feeds = { x: this.f32(x, [1, this.T, 80]), ...st.states };
const o = await this.streamEnc.run(feeds);
for (const name of this.cfg.outputs.slice(1)) st.states[name.slice(4)] = o[name];
const eo = o.encoder_out.data, nf = eo.length / D;
let added = 0;
for (let t = 0; t < nf; t++) {
const frame = st.chunk * nf + t, e = eo.subarray(t * D, (t + 1) * D);
for (let s = 0; s < 2; s++) {
const lg = await this.join(e, st.dout, 1);
let best = 0, bv = lg[0];
for (let j = 1; j < ALLOWED.length; j++) { const k = ALLOWED[j]; if (lg[k] > bv) { bv = lg[k]; best = k; } }
if (best === 0) break;
st.toks.push(best); st.frames.push(frame); added++;
st.ctx = [st.ctx[1], best]; st.dout = await this.decode([st.ctx]);
}
}
st.chunk++;
return added;
}
// ---------------- correction pass ----------------
async encodeFull(feats, T) {
const o = await this.offEnc.run({ x: this.f32(feats, [1, T, 80]), x_lens: this.i64([T], [1]) });
const n = Number(o.encoder_out_lens.data[0]);
return { enc: o.encoder_out.data.subarray(0, n * D), n };
}
lmWord(lm, st, word, alpha, beta) {
let s = 0;
for (const w of normTokens(word)) { const [lp, nx] = lm.score(st, lm.id(w)); s += alpha * lp * LN10 + beta; st = nx; }
return [s, st];
}
/** modified beam search (<=1 symbol per frame) with in-beam LM shallow fusion on completed words */
async beam(enc, n, { beam = 4, lm = null, alpha = 0.2, beta = 1.5 } = {}) {
const P = this.pieces, WS = this.wordStart, A = ALLOWED.length;
let hyps = [{ toks: [], key: '', ctx: [0, 0], logp: 0, fz: 0, part: '', lms: lm ? lm.begin() : null, dout: null }];
hyps[0].dout = await this.decode([hyps[0].ctx]);
const lp = new Float32Array(A);
for (let t = 0; t < n; t++) {
const N = hyps.length, e = new Float32Array(N * D), d = new Float32Array(N * D);
for (let i = 0; i < N; i++) { e.set(enc.subarray(t * D, (t + 1) * D), i * D); d.set(hyps[i].dout, i * D); }
const lg = await this.join(e, d, N);
const cands = [];
for (let i = 0; i < N; i++) {
const h = hyps[i], base = i * V;
let mx = -Infinity; for (let j = 0; j < A; j++) { const v = lg[base + ALLOWED[j]]; lp[j] = v; if (v > mx) mx = v; }
let se = 0; for (let j = 0; j < A; j++) se += Math.exp(lp[j] - mx);
const lse = mx + Math.log(se);
cands.push({ i, k: 0, logp: h.logp + lp[0] - lse, fz: h.fz });
// top beam non-blank tokens of this hyp
const top = [];
for (let j = 1; j < A; j++) {
const v = lp[j];
if (top.length < beam) { top.push(j); top.sort((a, b) => lp[b] - lp[a]); }
else if (v > lp[top[beam - 1]]) { top[beam - 1] = j; top.sort((a, b) => lp[b] - lp[a]); }
}
let wd = null;
for (const j of top) {
const k = ALLOWED[j]; let fz = h.fz;
if (lm && WS[k] && h.part) { if (!wd) wd = this.lmWord(lm, h.lms, h.part, alpha, beta); fz += wd[0]; }
cands.push({ i, k, logp: h.logp + lp[j] - lse, fz, wd: WS[k] && h.part ? wd : null });
}
}
cands.sort((a, b) => (b.logp + b.fz) - (a.logp + a.fz));
const next = new Map();
for (const c of cands) {
const h = hyps[c.i];
const key = c.k ? h.key + ',' + c.k : h.key;
const ex = next.get(key);
if (ex) { const m = Math.max(ex.logp, c.logp); ex.logp = m + Math.log(Math.exp(ex.logp - m) + Math.exp(c.logp - m)); continue; }
if (next.size >= beam) continue;
if (!c.k) next.set(key, { ...h, logp: c.logp });
else {
const piece = P[c.k];
const nh = { toks: [...h.toks, c.k], key, ctx: [h.ctx[1], c.k], logp: c.logp, fz: c.fz, dout: null,
part: WS[c.k] ? piece.slice(1) : h.part + piece, lms: h.lms };
if (lm && WS[c.k] && h.part) nh.lms = c.wd ? c.wd[1] : this.lmWord(lm, h.lms, h.part, alpha, beta)[1];
next.set(key, nh);
}
}
hyps = [...next.values()];
const need = hyps.filter(h => !h.dout);
if (need.length) { const out = await this.decode(need.map(h => h.ctx)); need.forEach((h, i) => { h.dout = out.slice(i * D, (i + 1) * D); }); }
}
let best = null, bs = -Infinity;
for (const h of hyps) {
let s = h.logp + h.fz;
if (lm) { let st = h.lms; if (h.part) { const w = this.lmWord(lm, st, h.part, alpha, beta); s += w[0]; st = w[1]; } s += alpha * lm.end(st) * LN10; }
if (s > bs) { bs = s; best = h; }
}
return { toks: best.toks, text: this.text(best.toks) };
}
}
export function parseTokens(txt) {
const p = [];
for (const line of txt.split('\n')) { if (!line) continue; const i = line.lastIndexOf(' '); p[+line.slice(i + 1)] = line.slice(0, i); }
return p;
}
|