ostra / frontend /src /workers /embeddingWorker.ts
sumandas's picture
Initial release: Ostra
46d70d9
Raw History Blame Contribute Delete
11 kB
/**
* Dedicated Web Worker for client-side dense embedding inference via Transformers.js.
*
* 3-Tier Compute Cascade:
* 1. Consumer WebGPU (Apple Metal on macOS, Vulkan on Linux, D3D12 on Windows)
* 2. Consumer Browser CPU (ONNX Runtime WebAssembly SIMD, single-threaded for iframe compatibility)
* 3. Signals `fallback_server` so the UI transparently falls back to the HF Space server
*
* Runs completely off the main thread so the browser UI stays 60fps and never freezes.
*/
import { env, pipeline } from "@huggingface/transformers";
env.allowLocalModels = false;
env.useBrowserCache = true;
// Single-threaded SIMD WASM works inside HF Spaces HTTPS iframes without COOP/COEP headers
if (env.backends?.onnx?.wasm) {
env.backends.onnx.wasm.numThreads = 1;
}
export interface EmbedWorkerRequest {
type: "embed";
onnxModelId: string;
pooling: "cls" | "mean";
texts: string[];
docPrefix: string;
maxSeqLen: number;
preferredTier: "auto" | "webgpu" | "wasm";
powerPreference?: "high-performance" | "low-power";
gpuLabel: string;
}
type FeatureExtractor = Awaited<ReturnType<typeof pipeline<"feature-extraction">>>;
const workerSelf = self as unknown as {
postMessage: (message: unknown, transfer?: Transferable[]) => void;
addEventListener: typeof self.addEventListener;
};
let cachedKey = "";
let cachedExtractor: FeatureExtractor | null = null;
let cachedBackend: "webgpu" | "wasm" = "wasm";
let cachedDeviceLabel = "Browser CPU (WASM)";
async function hasWebGPUInWorker(
powerPreference?: "high-performance" | "low-power"
): Promise<boolean> {
try {
const gpu = (
self as unknown as {
navigator?: {
gpu?: { requestAdapter: (opts?: Record<string, unknown>) => Promise<unknown> };
};
}
).navigator?.gpu;
if (!gpu) return false;
if (powerPreference) {
const prefAdapter = await gpu.requestAdapter({ powerPreference });
if (prefAdapter) return true;
}
const defaultAdapter = await gpu.requestAdapter();
return Boolean(defaultAdapter);
} catch {
return false;
}
}
async function loadExtractor(
onnxModelId: string,
preferredTier: "auto" | "webgpu" | "wasm",
gpuLabel: string,
powerPreference?: "high-performance" | "low-power"
): Promise<{
extractor: FeatureExtractor;
backend: "webgpu" | "wasm";
deviceLabel: string;
}> {
const canTryWebGPU =
(preferredTier === "auto" || preferredTier === "webgpu") &&
(await hasWebGPUInWorker(powerPreference));
const attempts: Array<{
device: "webgpu" | "wasm";
label: string;
}> = [];
if (canTryWebGPU) {
attempts.push({ device: "webgpu", label: gpuLabel || "Browser WebGPU" });
}
if (preferredTier === "auto" || preferredTier === "wasm") {
attempts.push({ device: "wasm", label: "Browser CPU (WASM)" });
}
if (attempts.length === 0) {
throw new Error("Requested browser compute tier is unavailable in this browser.");
}
let lastErr: unknown = null;
for (const attempt of attempts) {
const key = `${onnxModelId}::${attempt.device}`;
if (cachedExtractor && cachedKey === key) {
return {
extractor: cachedExtractor,
backend: cachedBackend,
deviceLabel: cachedDeviceLabel,
};
}
self.postMessage({
type: "progress",
stage: "model_load",
message: `Loading ${onnxModelId} on ${attempt.label}…`,
percent: 12,
device: attempt.label,
backend: attempt.device,
});
try {
// Prefer fp32 for exact cosine similarity parity with backend PyTorch query encoding;
// fall back to default ONNX dtype if repo only provides quantized weights.
const progressCallback = (info: Record<string, unknown>) => {
if (info?.status === "progress" && typeof info.progress === "number") {
const pct = 12 + Math.min(info.progress, 100) * 0.1;
self.postMessage({
type: "progress",
stage: "model_load",
message: `Downloading ONNX weights for ${onnxModelId} (${Math.round(info.progress)}%)…`,
percent: Math.round(pct * 10) / 10,
device: attempt.label,
backend: attempt.device,
});
}
};
let loaded: FeatureExtractor;
try {
loaded = await pipeline("feature-extraction", onnxModelId, {
device: attempt.device,
dtype: "fp32",
progress_callback: progressCallback,
});
} catch {
loaded = await pipeline("feature-extraction", onnxModelId, {
device: attempt.device,
progress_callback: progressCallback,
});
}
cachedExtractor = loaded;
cachedKey = key;
cachedBackend = attempt.device;
cachedDeviceLabel = attempt.label;
return {
extractor: loaded,
backend: attempt.device,
deviceLabel: attempt.label,
};
} catch (err) {
lastErr = err;
if (attempt.device === "webgpu" && attempts.length > 1) {
self.postMessage({
type: "progress",
stage: "model_load",
message: `WebGPU unavailable for ${onnxModelId}; falling back to Browser CPU (WASM)…`,
percent: 14,
device: "Browser CPU (WASM)",
backend: "wasm",
});
}
}
}
throw lastErr instanceof Error
? lastErr
: new Error(String(lastErr || "Failed to load ONNX model in browser"));
}
self.addEventListener("message", async (event: MessageEvent<EmbedWorkerRequest>) => {
const req = event.data;
if (!req || req.type !== "embed") return;
try {
const { extractor, backend, deviceLabel } = await loadExtractor(
req.onnxModelId,
req.preferredTier,
req.gpuLabel,
req.powerPreference
);
const n = req.texts.length;
const prefix = req.docPrefix || "";
const prefixedTexts = prefix ? req.texts.map((t) => `${prefix}${t}`) : req.texts;
// Step 1: Compute token telemetry directly using the loaded HF tokenizer
self.postMessage({
type: "progress",
stage: "tokenize",
message: `Auditing tokenization & truncation on ${n.toLocaleString()} docs (${deviceLabel})…`,
percent: 22,
device: deviceLabel,
backend,
});
const tokenizer = extractor.tokenizer;
const rawMaxLen = Number(
(tokenizer as unknown as { model_max_length?: number })?.model_max_length
);
const maxSeqLen =
req.maxSeqLen > 0
? req.maxSeqLen
: Number.isFinite(rawMaxLen) && rawMaxLen > 0 && rawMaxLen <= 32768
? rawMaxLen
: 512;
const tokenCounts: number[] = new Array(n);
const isTruncated: boolean[] = new Array(n);
const truncationRatio: number[] = new Array(n);
const truncatedCharOffsets: (number | null)[] = new Array(n);
const subwordFertility: number[] = new Array(n);
let truncatedCount = 0;
for (let i = 0; i < n; i++) {
const text = req.texts[i];
const fullText = prefixedTexts[i];
const words = text.trim() ? text.trim().split(/\s+/).length : 1;
let tokLen = Math.max(1, Math.round(words * 1.3) + 2);
try {
const encoded = tokenizer.encode(fullText, { add_special_tokens: true });
tokLen = encoded.length;
} catch {
// Fallback word-based estimate
}
tokenCounts[i] = tokLen;
const contentToks = Math.max(tokLen - 2, 1);
subwordFertility[i] = Math.round((contentToks / Math.max(words, 1)) * 100) / 100;
if (tokLen > maxSeqLen) {
truncatedCount += 1;
isTruncated[i] = true;
truncationRatio[i] = Math.round(((tokLen - maxSeqLen) / tokLen) * 10000) / 10000;
truncatedCharOffsets[i] = Math.max(
0,
Math.min(text.length, Math.floor(text.length * (maxSeqLen / tokLen)))
);
} else {
isTruncated[i] = false;
truncationRatio[i] = 0;
truncatedCharOffsets[i] = null;
}
}
// Step 2: Embed in small non-blocking batches with live progress
const batchSize = backend === "webgpu" ? 16 : 8;
const t0 = performance.now();
let dim = 0;
let outputBuffer: Float32Array | null = null;
self.postMessage({
type: "progress",
stage: "embed",
message: `Embedding ${n.toLocaleString()} docs on ${deviceLabel}…`,
percent: 25,
done: 0,
total: n,
truncated_count: truncatedCount,
device: deviceLabel,
backend,
});
for (let start = 0; start < n; start += batchSize) {
const end = Math.min(start + batchSize, n);
const batch = prefixedTexts.slice(start, end);
const tensor = await extractor(batch, {
pooling: req.pooling,
normalize: true,
});
const dims = tensor.dims as number[];
const batchRows = dims.length === 2 ? dims[0] : 1;
const batchDim = dims.length === 2 ? dims[1] : dims[dims.length - 1];
const data = tensor.data as Float32Array;
if (!outputBuffer) {
dim = batchDim;
outputBuffer = new Float32Array(n * dim);
}
// Copy & ensure unit L2 norm
for (let r = 0; r < batchRows; r++) {
const srcOff = r * dim;
const dstOff = (start + r) * dim;
let sq = 0;
for (let c = 0; c < dim; c++) {
const v = data[srcOff + c];
sq += v * v;
}
const inv = sq > 1e-12 ? 1 / Math.sqrt(sq) : 1;
for (let c = 0; c < dim; c++) {
outputBuffer[dstOff + c] = data[srcOff + c] * inv;
}
}
const elapsed = Math.max((performance.now() - t0) / 1000, 0.001);
const rate = end / elapsed;
const pct = 25 + 46 * (end / Math.max(n, 1));
self.postMessage({
type: "progress",
stage: "embed",
message: `Embedded ${end.toLocaleString()}/${n.toLocaleString()} docs on ${deviceLabel} (${Math.round(rate)} docs/s)`,
percent: Math.round(pct * 10) / 10,
done: end,
total: n,
docs_per_sec: Math.round(rate * 10) / 10,
truncated_count: truncatedCount,
device: deviceLabel,
backend,
});
}
const embedSeconds = Math.max((performance.now() - t0) / 1000, 0.01);
const docsPerSec = n / embedSeconds;
const finalVecs = outputBuffer ?? new Float32Array(0);
workerSelf.postMessage(
{
type: "complete",
embeddings: finalVecs,
dim,
backendUsed: backend,
deviceLabel,
embedSeconds,
docsPerSec,
telemetry: {
token_counts: tokenCounts,
is_truncated: isTruncated,
truncation_ratio: truncationRatio,
truncated_char_offsets: truncatedCharOffsets,
subword_fertility: subwordFertility,
max_seq_len: maxSeqLen,
},
},
[finalVecs.buffer]
);
} catch (err) {
self.postMessage({
type: "fallback_server",
reason: err instanceof Error ? err.message : String(err),
});
}
});