Spaces:
Running
Running
File size: 6,209 Bytes
a2bd61d | 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 | /* Portable int8 storage, dequantized Float64 arithmetic in a local browser. */
const PREPROCESS =
"NFC/lowercase/Python-whitespace; ^text$; codepoint3,4,5 FNV1a32; count-L2";
const WS =
/[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/gu;
const trim = (text) => text.replace(WS, " ").replace(/^ | $/g, "");
function scalar(text) {
for (const c of text) {
const p = c.codePointAt(0);
if (p >= 0xd800 && p <= 0xdfff) return false;
}
return true;
}
function keys(value, names) {
return (
value &&
typeof value === "object" &&
!Array.isArray(value) &&
Object.keys(value).length === names.length &&
names.every((k) => Object.hasOwn(value, k))
);
}
function numbers(a, n, positive = false) {
if (
!Array.isArray(a) ||
a.length !== n ||
a.some(
(x) =>
typeof x !== "number" || !Number.isFinite(x) || (positive && x <= 0),
)
)
throw Error("Invalid model numeric array.");
return a;
}
function bytes(value, n) {
if (
typeof value !== "string" ||
value.length !== 4 * Math.ceil(n / 3) ||
!/^[A-Za-z0-9+/]*={0,2}$/.test(value)
)
throw Error("Invalid encoded weights.");
let raw;
try {
raw = atob(value);
} catch {
throw Error("Invalid base64 weights.");
}
if (raw.length !== n) throw Error("Wrong weight byte count.");
const q = new Int8Array(n);
for (let i = 0; i < n; i++) {
const v = raw.charCodeAt(i);
q[i] = v > 127 ? v - 256 : v;
if (q[i] === -128) throw Error("Unsupported -128 quantized value.");
}
return q;
}
export function parseModel(raw) {
if (typeof raw !== "string" || new TextEncoder().encode(raw).length > 2097152)
throw Error("Model asset exceeds 2 MiB.");
const m = JSON.parse(raw);
if (
!keys(m, [
"schema_version",
"tool_version",
"work_identity",
"dimensions",
"preprocessing",
"input_utf16_limit",
"labels",
"temperature",
"embedding_scales",
"embedding_q_base64",
"output_scales",
"output_q_base64",
"hidden_bias",
"output_bias",
]) ||
m.schema_version !== 1 ||
m.tool_version !== "0.1.0" ||
m.work_identity !== "work:tiny-hash-intent:v1" ||
m.preprocessing !== PREPROCESS ||
m.input_utf16_limit !== 2048 ||
!keys(m.dimensions, ["features", "hidden", "classes"]) ||
m.dimensions.features !== 4096 ||
m.dimensions.hidden !== 64 ||
m.dimensions.classes !== 77
)
throw Error("Unsupported portable model schema.");
if (
!Array.isArray(m.labels) ||
m.labels.length !== 77 ||
new Set(m.labels).size !== 77 ||
m.labels.some(
(l) => typeof l !== "string" || !scalar(l) || !trim(l) || l.length > 128,
)
)
throw Error("Invalid model labels.");
if (
typeof m.temperature !== "number" ||
!Number.isFinite(m.temperature) ||
m.temperature <= 0
)
throw Error("Invalid model temperature.");
const se = numbers(m.embedding_scales, 4096, true),
sw = numbers(m.output_scales, 77, true),
qe = bytes(m.embedding_q_base64, 4096 * 64),
qw = bytes(m.output_q_base64, 64 * 77);
const E = new Float64Array(qe.length),
W = new Float64Array(qw.length);
for (let i = 0; i < E.length; i++) E[i] = qe[i] * se[Math.floor(i / 64)];
for (let i = 0; i < W.length; i++) W[i] = qw[i] * sw[i % 77];
if (!E.every(Number.isFinite) || !W.every(Number.isFinite))
throw Error("Nonfinite dequantized weights.");
return {
E,
W,
bh: Float64Array.from(numbers(m.hidden_bias, 64)),
bo: Float64Array.from(numbers(m.output_bias, 77)),
labels: m.labels.slice(),
temperature: m.temperature,
version: m.tool_version,
};
}
export function normalized(text) {
return trim(text.normalize("NFC").toLowerCase());
}
export function fnv(text) {
let h = 2166136261;
for (const b of new TextEncoder().encode(text))
h = Math.imul(h ^ b, 16777619) >>> 0;
return h;
}
export function features(text) {
if (typeof text !== "string" || !scalar(text) || !trim(text))
throw Error("Use nonblank Unicode scalar text.");
if (text.length > 2048)
throw Error(
"Input exceeds 2,048 UTF-16 units; no truncation is performed.",
);
const chars = Array.from("^" + normalized(text) + "$"),
counts = new Map();
for (const n of [3, 4, 5])
for (let i = 0; i + n <= chars.length; i++) {
const id = fnv(chars.slice(i, i + n).join("")) % 4096;
counts.set(id, (counts.get(id) || 0) + 1);
}
const ids = [...counts.keys()].sort((a, b) => a - b),
den = Math.sqrt(ids.reduce((s, id) => s + counts.get(id) ** 2, 0));
return { ids, values: ids.map((id) => (den ? counts.get(id) / den : 0)) };
}
export function predict(model, text, calibrated = true) {
const f = features(text),
h = new Float64Array(64),
logits = new Float64Array(77);
for (let k = 0; k < 64; k++) {
let v = model.bh[k];
for (let j = 0; j < f.ids.length; j++)
v += f.values[j] * model.E[f.ids[j] * 64 + k];
if (!Number.isFinite(v)) throw Error("Nonfinite hidden activation.");
h[k] = Math.tanh(v);
}
for (let c = 0; c < 77; c++) {
let v = model.bo[c];
for (let k = 0; k < 64; k++) v += h[k] * model.W[k * 77 + c];
if (!Number.isFinite(v)) throw Error("Nonfinite class score.");
logits[c] = v;
}
const T = calibrated ? model.temperature : 1;
if (!Number.isFinite(T) || T <= 0) throw Error("Invalid temperature.");
const scaled = Array.from(logits, (z) => z / T);
if (!scaled.every(Number.isFinite))
throw Error("Nonfinite scaled class score.");
const max = Math.max(...scaled),
exp = scaled.map((z) => Math.exp(z - max)),
sum = exp.reduce((a, b) => a + b, 0),
prob = exp.map((v) => v / sum);
const order = Array.from({ length: 77 }, (_, i) => i).sort(
(a, b) => logits[b] - logits[a] || a - b,
);
return {
predicted_label_id: order[0],
predicted_label: model.labels[order[0]],
temperature: T,
feature_bins_used: f.ids.length,
top3: order
.slice(0, 3)
.map((i) => ({ label_id: i, label: model.labels[i], score: prob[i] })),
logits: Array.from(logits),
probabilities: prob,
};
}
|