// The mood reader: a small text classifier that the owner of this app trains // and publishes on Hugging Face (see learn/01-mood-reader), run here in the // browser. This file is the whole "inference engine": it reads the three // standard files of a BERT-style model // // config.json the shape of the network and the names of its labels // tokenizer.json how text is cut into word pieces, and their numbers // model.safetensors the learned numbers ("weights") // // and turns a sentence into a score per mood. No library is involved: every // step of the network is spelled out below. No browser APIs are needed for // the maths, so the unit tests run it in Node against PyTorch's own results. export class MoodReaderError extends Error { constructor(message) { super(message); this.name = 'MoodReaderError'; } } // ---------- model.safetensors ---------- function halfToFloat(u) { const sign = u & 0x8000 ? -1 : 1; const exp = (u >> 10) & 0x1f; const frac = u & 0x3ff; if (exp === 0) return sign * 2 ** -14 * (frac / 1024); if (exp === 31) return frac ? NaN : sign * Infinity; return sign * 2 ** (exp - 15) * (1 + frac / 1024); } /** * Reads a .safetensors file: 8 bytes giving the length of a JSON header, the * header (name, type, shape and position of every tensor), then the numbers. * @returns {{ tensors: Map, params: number }} */ export function parseSafetensors(buffer) { if (!(buffer instanceof ArrayBuffer) || buffer.byteLength < 16) throw new MoodReaderError('The weights file is empty or incomplete.'); const view = new DataView(buffer); const headerLength = Number(view.getBigUint64(0, true)); if (!(headerLength > 0) || 8 + headerLength > buffer.byteLength) throw new MoodReaderError('The weights file is not a safetensors file.'); let header; try { header = JSON.parse(new TextDecoder().decode(new Uint8Array(buffer, 8, headerLength))); } catch { throw new MoodReaderError('The weights file is not a safetensors file.'); } const base = 8 + headerLength; const tensors = new Map(); let params = 0; for (const [name, t] of Object.entries(header)) { if (name === '__metadata__') continue; const [from, to] = t.data_offsets; const count = t.shape.reduce((a, b) => a * b, 1); if (base + to > buffer.byteLength) throw new MoodReaderError('The weights file is cut short. Download it again.'); let data; if (t.dtype === 'F32') { data = new Float32Array(buffer.slice(base + from, base + to)); } else if (t.dtype === 'F16') { const half = new Uint16Array(buffer.slice(base + from, base + to)); data = new Float32Array(count); for (let i = 0; i < count; i += 1) data[i] = halfToFloat(half[i]); } else { continue; // counters and other bookkeeping that the maths does not use } if (data.length !== count) throw new MoodReaderError(`The weights file is damaged (${name}).`); tensors.set(name, { shape: t.shape, data }); params += count; } return { tensors, params }; } // ---------- tokenizer.json ---------- const CJK = /[一-鿿㐀-䶿豈-﫿\u{20000}-\u{2A6DF}\u{2A700}-\u{2B73F}\u{2B740}-\u{2B81F}\u{2B820}-\u{2CEAF}\u{2F800}-\u{2FA1F}]/gu; const PUNCTUATION = /[!-/:-@[-`{-~]|\p{P}/u; /** * Text to token numbers, the way BERT's tokenizer does it: tidy the text, * lower-case it and drop accents, split it at spaces and punctuation, then cut * each word into the longest pieces found in the vocabulary ("##" marks a * piece that continues a word). */ export function makeTokenizer(json) { const model = json?.model; if (model?.type !== 'WordPiece' || !model.vocab) throw new MoodReaderError('This tokenizer is not the WordPiece kind that BERT models use.'); const vocab = new Map(Object.entries(model.vocab)); const norm = json.normalizer || {}; const lower = norm.lowercase !== false; const stripAccents = norm.strip_accents ?? lower; const spaceCjk = norm.handle_chinese_chars !== false; const prefix = model.continuing_subword_prefix ?? '##'; const maxChars = model.max_input_chars_per_word ?? 100; const id = (token) => { if (!vocab.has(token)) throw new MoodReaderError(`The tokenizer has no ${token} token.`); return vocab.get(token); }; const unk = id(model.unk_token || '[UNK]'); const cls = id('[CLS]'); const sep = id('[SEP]'); // Special tokens written out in the text itself ("[SEP]") are taken as they are, as the original does. const special = (json.added_tokens || []).filter((t) => t.special && vocab.has(t.content)).map((t) => t.content).sort((a, b) => b.length - a.length); const specialSplit = special.length ? new RegExp(`(${special.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})`) : null; function normalize(text) { let s = String(text ?? ''); s = s.replace(/[\t\n\r]/g, ' ').replace(/[�\p{Cc}\p{Cf}\p{Co}]/gu, '').replace(/\p{White_Space}/gu, ' '); if (spaceCjk) s = s.replace(CJK, ' $& '); if (stripAccents) s = s.normalize('NFD').replace(/\p{Mn}/gu, ''); if (lower) s = s.toLowerCase(); return s; } function pieces(word, out) { const chars = Array.from(word); if (chars.length > maxChars) { out.push(unk); return; } const found = []; let start = 0; while (start < chars.length) { let end = chars.length; let hit = null; while (start < end) { const piece = (start > 0 ? prefix : '') + chars.slice(start, end).join(''); if (vocab.has(piece)) { hit = vocab.get(piece); break; } end -= 1; } if (hit === null) { out.push(unk); // one unknown piece makes the whole word unknown return; } found.push(hit); start = end; } out.push(...found); } return { size: vocab.size, /** @returns {number[]} token numbers, starting with [CLS] and ending with [SEP] */ encode(text, maxLength = 128) { const ids = []; for (const part of specialSplit ? String(text ?? '').split(specialSplit) : [text]) { if (special.includes(part)) { ids.push(vocab.get(part)); continue; } for (const chunk of normalize(part).split(' ')) { if (!chunk) continue; let word = ''; for (const ch of chunk) { if (PUNCTUATION.test(ch)) { if (word) pieces(word, ids); word = ''; pieces(ch, ids); } else { word += ch; } } if (word) pieces(word, ids); } } return [cls, ...ids.slice(0, Math.max(0, maxLength - 2)), sep]; }, }; } // ---------- the network ---------- /** y = x·Wᵀ + b for `rows` rows. W is stored row by row: one row of `inDim` numbers per output. */ function linear(x, rows, inDim, w, b, outDim) { const y = new Float32Array(rows * outDim); for (let r = 0; r < rows; r += 1) { const xo = r * inDim; const yo = r * outDim; for (let o = 0; o < outDim; o += 1) { const wo = o * inDim; // Four running sums instead of one: the same result, and the processor can work on them side by side. let s0 = 0; let s1 = 0; let s2 = 0; let s3 = 0; let i = 0; for (; i + 3 < inDim; i += 4) { s0 += w[wo + i] * x[xo + i]; s1 += w[wo + i + 1] * x[xo + i + 1]; s2 += w[wo + i + 2] * x[xo + i + 2]; s3 += w[wo + i + 3] * x[xo + i + 3]; } for (; i < inDim; i += 1) s0 += w[wo + i] * x[xo + i]; y[yo + o] = b[o] + s0 + s1 + s2 + s3; } } return y; } /** Rescales each row to mean 0 and spread 1, then applies the learned scale and shift. In place. */ function layerNorm(x, rows, dim, gamma, beta, eps) { for (let r = 0; r < rows; r += 1) { const o = r * dim; let mean = 0; for (let i = 0; i < dim; i += 1) mean += x[o + i]; mean /= dim; let variance = 0; for (let i = 0; i < dim; i += 1) variance += (x[o + i] - mean) ** 2; const scale = 1 / Math.sqrt(variance / dim + eps); for (let i = 0; i < dim; i += 1) x[o + i] = (x[o + i] - mean) * scale * gamma[i] + beta[i]; } return x; } /** The error function (Abramowitz and Stegun 7.1.26, accurate to about 1e-7). */ function erf(x) { const sign = x < 0 ? -1 : 1; const a = Math.abs(x); const t = 1 / (1 + 0.3275911 * a); const poly = ((((1.061405429 * t - 1.453152027) * t + 1.421413741) * t - 0.284496736) * t + 0.254829592) * t; return sign * (1 - poly * Math.exp(-a * a)); } const ACTIVATIONS = { gelu: (v) => 0.5 * v * (1 + erf(v / Math.SQRT2)), gelu_new: (v) => 0.5 * v * (1 + Math.tanh(Math.sqrt(2 / Math.PI) * (v + 0.044715 * v ** 3))), relu: (v) => Math.max(0, v), }; function softmax(values) { let max = -Infinity; for (const v of values) if (v > max) max = v; let sum = 0; const out = Array.from(values, (v) => { const e = Math.exp(v - max); sum += e; return e; }); return out.map((e) => e / sum); } /** * Builds a reader from the three files of a model. * @param config parsed config.json * @param tokenizer parsed tokenizer.json * @param weights ArrayBuffer of model.safetensors */ export function createMoodReader({ config, tokenizer, weights }) { if (config?.model_type !== 'bert') throw new MoodReaderError(`This app's mood reader runs BERT-style models; this one says it is "${config?.model_type || 'unknown'}".`); const act = ACTIVATIONS[config.hidden_act || 'gelu']; if (!act) throw new MoodReaderError(`This model uses the "${config.hidden_act}" activation, which the reader does not know.`); const H = config.hidden_size; const heads = config.num_attention_heads; const layers = config.num_hidden_layers; const inner = config.intermediate_size; const eps = config.layer_norm_eps ?? 1e-12; // Long texts are cut off: the first 64 tokens say enough about a mood, and reading time grows fast with length. const maxTokens = Math.min(64, config.max_position_embeddings || 512); if (!(H > 0) || !(heads > 0) || H % heads || !(layers > 0)) throw new MoodReaderError('The model’s config.json is missing its sizes.'); const labels = Object.entries(config.id2label || {}).sort((a, b) => Number(a[0]) - Number(b[0])).map(([, name]) => String(name)); if (labels.length < 2) throw new MoodReaderError('The model’s config.json does not name its labels (id2label).'); const { tensors, params } = parseSafetensors(weights); const get = (name, size) => { const t = tensors.get(name); if (!t) throw new MoodReaderError(`The weights file has no "${name}". Is this a BERT model for text classification?`); if (size && t.data.length !== size) throw new MoodReaderError(`"${name}" has ${t.data.length} numbers where config.json promises ${size}.`); return t.data; }; const tok = makeTokenizer(tokenizer); const W = { word: get('bert.embeddings.word_embeddings.weight'), position: get('bert.embeddings.position_embeddings.weight'), type: get('bert.embeddings.token_type_embeddings.weight'), normG: get('bert.embeddings.LayerNorm.weight', H), normB: get('bert.embeddings.LayerNorm.bias', H), layers: Array.from({ length: layers }, (_, i) => { const p = `bert.encoder.layer.${i}.`; return { qW: get(`${p}attention.self.query.weight`, H * H), qB: get(`${p}attention.self.query.bias`, H), kW: get(`${p}attention.self.key.weight`, H * H), kB: get(`${p}attention.self.key.bias`, H), vW: get(`${p}attention.self.value.weight`, H * H), vB: get(`${p}attention.self.value.bias`, H), oW: get(`${p}attention.output.dense.weight`, H * H), oB: get(`${p}attention.output.dense.bias`, H), n1G: get(`${p}attention.output.LayerNorm.weight`, H), n1B: get(`${p}attention.output.LayerNorm.bias`, H), iW: get(`${p}intermediate.dense.weight`, inner * H), iB: get(`${p}intermediate.dense.bias`, inner), fW: get(`${p}output.dense.weight`, H * inner), fB: get(`${p}output.dense.bias`, H), n2G: get(`${p}output.LayerNorm.weight`, H), n2B: get(`${p}output.LayerNorm.bias`, H), }; }), poolW: get('bert.pooler.dense.weight', H * H), poolB: get('bert.pooler.dense.bias', H), outW: get('classifier.weight', labels.length * H), outB: get('classifier.bias', labels.length), }; if (W.word.length / H < tok.size) throw new MoodReaderError('The tokenizer knows more word pieces than the model has rows for. The two files do not belong together.'); /** Token numbers in, one raw score ("logit") per label out. */ function logits(ids) { const n = ids.length; // 1. Each token becomes a row of H numbers: its own meaning plus its position in the sentence. let x = new Float32Array(n * H); for (let t = 0; t < n; t += 1) { const w = ids[t] * H; const p = t * H; for (let i = 0; i < H; i += 1) x[p + i] = W.word[w + i] + W.position[p + i] + W.type[i]; } layerNorm(x, n, H, W.normG, W.normB, eps); const d = H / heads; const scale = 1 / Math.sqrt(d); const weightsRow = new Float32Array(n); for (const L of W.layers) { // Only the first token is read at the very end, so the last layer need not update the others. const rows = L === W.layers[W.layers.length - 1] ? 1 : n; // 2. Attention: every token looks at every other token and takes in a weighted mix of them. const q = linear(x, rows, H, L.qW, L.qB, H); const k = linear(x, n, H, L.kW, L.kB, H); const v = linear(x, n, H, L.vW, L.vB, H); const mixed = new Float32Array(rows * H); for (let h = 0; h < heads; h += 1) { const off = h * d; for (let i = 0; i < rows; i += 1) { let max = -Infinity; for (let j = 0; j < n; j += 1) { let dot = 0; for (let c = 0; c < d; c += 1) dot += q[i * H + off + c] * k[j * H + off + c]; weightsRow[j] = dot * scale; if (weightsRow[j] > max) max = weightsRow[j]; } let sum = 0; for (let j = 0; j < n; j += 1) { weightsRow[j] = Math.exp(weightsRow[j] - max); sum += weightsRow[j]; } for (let j = 0; j < n; j += 1) { const wgt = weightsRow[j] / sum; for (let c = 0; c < d; c += 1) mixed[i * H + off + c] += wgt * v[j * H + off + c]; } } } const attended = linear(mixed, rows, H, L.oW, L.oB, H); for (let i = 0; i < attended.length; i += 1) attended[i] += x[i]; x = layerNorm(attended, rows, H, L.n1G, L.n1B, eps); // 3. A small two-step network works on each token by itself. const wide = linear(x, rows, H, L.iW, L.iB, inner); for (let i = 0; i < wide.length; i += 1) wide[i] = act(wide[i]); const narrow = linear(wide, rows, inner, L.fW, L.fB, H); for (let i = 0; i < narrow.length; i += 1) narrow[i] += x[i]; x = layerNorm(narrow, rows, H, L.n2G, L.n2B, eps); } // 4. The first token ([CLS]) now stands for the whole sentence: one last layer turns it into scores. const pooled = linear(x.subarray(0, H), 1, H, W.poolW, W.poolB, H); for (let i = 0; i < H; i += 1) pooled[i] = Math.tanh(pooled[i]); return linear(pooled, 1, H, W.outW, W.outB, labels.length); } return { labels, layers, hidden: H, params, tokenize: (text) => tok.encode(text, maxTokens), logits, /** * Reads a sentence. * @returns {{ label: string, score: number, ranked: { label: string, score: number }[], tokens: number }} */ read(text) { const ids = tok.encode(text, maxTokens); const probs = softmax(logits(ids)); const ranked = labels.map((label, i) => ({ label, score: probs[i] })).sort((a, b) => b.score - a.score); return { label: ranked[0].label, score: ranked[0].score, ranked, tokens: ids.length }; }, }; } // ---------- fetching a model from Hugging Face ---------- export const HUB = 'https://huggingface.co'; /** "name/model", as shown at the top of a model page. A pasted link to the page works too. */ export function repoId(input) { const s = String(input ?? '').trim().replace(/^https?:\/\/huggingface\.co\//i, '').replace(/\/(tree|blob|resolve)\/.*$/, '').replace(/\/+$/, ''); return /^[A-Za-z0-9][\w.-]{0,95}\/[A-Za-z0-9][\w.-]{0,95}$/.test(s) && !s.includes('..') ? s : null; } export const modelFile = (repo, file) => `${HUB}/${repo}/resolve/main/${file}`; /** * Downloads the three files of a public model. * @param opts.onProgress (fraction 0..1) while the weights arrive * @returns {Promise<{ config: object, tokenizer: object, weights: ArrayBuffer }>} */ export async function downloadMoodReader(repo, { fetch: fetchImpl = (...a) => globalThis.fetch(...a), onProgress = () => {} } = {}) { const grab = async (file) => { let res; try { res = await fetchImpl(modelFile(repo, file)); } catch { throw new MoodReaderError('Could not reach Hugging Face. Are you online?'); } if (res.status === 404) throw new MoodReaderError(`Hugging Face has no ${file} at “${repo}”. Check the name, and that the model has been uploaded.`); if (res.status === 401 || res.status === 403) throw new MoodReaderError(`“${repo}” is private or gated. Make the model public in its settings on Hugging Face.`); if (!res.ok) throw new MoodReaderError(`Hugging Face answered with an error (${res.status}) for ${file}.`); return res; }; const json = async (file) => { try { return await (await grab(file)).json(); } catch (err) { if (err instanceof MoodReaderError) throw err; throw new MoodReaderError(`${file} could not be read.`); } }; const config = await json('config.json'); const tokenizer = await json('tokenizer.json'); const res = await grab('model.safetensors'); const total = Number(res.headers?.get?.('content-length')) || 0; if (!res.body?.getReader || !total) { const weights = await res.arrayBuffer(); onProgress(1); return { config, tokenizer, weights }; } const reader = res.body.getReader(); const bytes = new Uint8Array(total); let got = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; if (got + value.length > total) throw new MoodReaderError('The weights file is larger than Hugging Face announced. Try again.'); bytes.set(value, got); got += value.length; onProgress(got / total); } if (got !== total) throw new MoodReaderError('The download stopped early. Try again.'); return { config, tokenizer, weights: bytes.buffer }; }