File size: 10,997 Bytes
46d70d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * 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),
    });
  }
});