|
| 1 | +import { |
| 2 | + DeterministicDummyEmbeddingBackend, |
| 3 | + type DeterministicDummyEmbeddingBackendOptions, |
| 4 | +} from "./DeterministicDummyEmbeddingBackend"; |
| 5 | +import type { EmbeddingBackend } from "./EmbeddingBackend"; |
| 6 | + |
| 7 | +export type EmbeddingProviderKind = |
| 8 | + | "webnn" |
| 9 | + | "webgpu" |
| 10 | + | "webgl" |
| 11 | + | "wasm" |
| 12 | + | "dummy" |
| 13 | + | (string & {}); |
| 14 | + |
| 15 | +export interface EmbeddingProviderCandidate { |
| 16 | + kind: EmbeddingProviderKind; |
| 17 | + isSupported: () => boolean | Promise<boolean>; |
| 18 | + createBackend: () => EmbeddingBackend | Promise<EmbeddingBackend>; |
| 19 | +} |
| 20 | + |
| 21 | +export interface EmbeddingProviderBenchmarkPolicy { |
| 22 | + enabled: boolean; |
| 23 | + warmupRuns: number; |
| 24 | + timedRuns: number; |
| 25 | + sampleTexts: string[]; |
| 26 | +} |
| 27 | + |
| 28 | +export interface EmbeddingProviderMeasurement { |
| 29 | + kind: EmbeddingProviderKind; |
| 30 | + meanMs: number; |
| 31 | +} |
| 32 | + |
| 33 | +export type EmbeddingProviderResolveReason = |
| 34 | + | "forced" |
| 35 | + | "benchmark" |
| 36 | + | "capability-order"; |
| 37 | + |
| 38 | +export interface ResolvedEmbeddingBackend { |
| 39 | + backend: EmbeddingBackend; |
| 40 | + selectedKind: EmbeddingProviderKind; |
| 41 | + reason: EmbeddingProviderResolveReason; |
| 42 | + supportedKinds: EmbeddingProviderKind[]; |
| 43 | + measurements: EmbeddingProviderMeasurement[]; |
| 44 | +} |
| 45 | + |
| 46 | +export const DEFAULT_PROVIDER_ORDER: ReadonlyArray<EmbeddingProviderKind> = |
| 47 | + Object.freeze([ |
| 48 | + "webnn", |
| 49 | + "webgpu", |
| 50 | + "webgl", |
| 51 | + "wasm", |
| 52 | + "dummy", |
| 53 | + ]); |
| 54 | + |
| 55 | +export const DEFAULT_PROVIDER_BENCHMARK_POLICY: EmbeddingProviderBenchmarkPolicy = |
| 56 | + Object.freeze({ |
| 57 | + enabled: true, |
| 58 | + warmupRuns: 1, |
| 59 | + timedRuns: 3, |
| 60 | + sampleTexts: [ |
| 61 | + "cortex benchmark probe", |
| 62 | + "routing and coherence warmup", |
| 63 | + "deterministic provider timing", |
| 64 | + ], |
| 65 | + }); |
| 66 | + |
| 67 | +export type BenchmarkBackendFn = ( |
| 68 | + backend: EmbeddingBackend, |
| 69 | + policy: EmbeddingProviderBenchmarkPolicy, |
| 70 | +) => Promise<number>; |
| 71 | + |
| 72 | +export interface ResolveEmbeddingBackendOptions { |
| 73 | + candidates: EmbeddingProviderCandidate[]; |
| 74 | + preferredOrder?: ReadonlyArray<EmbeddingProviderKind>; |
| 75 | + forceKind?: EmbeddingProviderKind; |
| 76 | + benchmark?: Partial<EmbeddingProviderBenchmarkPolicy>; |
| 77 | + benchmarkBackend?: BenchmarkBackendFn; |
| 78 | +} |
| 79 | + |
| 80 | +function assertPositiveInteger(name: string, value: number): void { |
| 81 | + if (!Number.isInteger(value) || value <= 0) { |
| 82 | + throw new Error(`${name} must be a positive integer`); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +function validateBenchmarkPolicy( |
| 87 | + policy: EmbeddingProviderBenchmarkPolicy, |
| 88 | +): EmbeddingProviderBenchmarkPolicy { |
| 89 | + assertPositiveInteger("warmupRuns", policy.warmupRuns); |
| 90 | + assertPositiveInteger("timedRuns", policy.timedRuns); |
| 91 | + |
| 92 | + if (policy.sampleTexts.length === 0) { |
| 93 | + throw new Error("sampleTexts must not be empty"); |
| 94 | + } |
| 95 | + |
| 96 | + return policy; |
| 97 | +} |
| 98 | + |
| 99 | +function nowMs(): number { |
| 100 | + const perfNow = globalThis.performance?.now?.bind(globalThis.performance); |
| 101 | + if (perfNow) { |
| 102 | + return perfNow(); |
| 103 | + } |
| 104 | + return Date.now(); |
| 105 | +} |
| 106 | + |
| 107 | +async function defaultBenchmarkBackend( |
| 108 | + backend: EmbeddingBackend, |
| 109 | + policy: EmbeddingProviderBenchmarkPolicy, |
| 110 | +): Promise<number> { |
| 111 | + for (let i = 0; i < policy.warmupRuns; i++) { |
| 112 | + await backend.embed(policy.sampleTexts); |
| 113 | + } |
| 114 | + |
| 115 | + let totalMs = 0; |
| 116 | + for (let i = 0; i < policy.timedRuns; i++) { |
| 117 | + const start = nowMs(); |
| 118 | + await backend.embed(policy.sampleTexts); |
| 119 | + totalMs += nowMs() - start; |
| 120 | + } |
| 121 | + |
| 122 | + return totalMs / policy.timedRuns; |
| 123 | +} |
| 124 | + |
| 125 | +function orderCandidates( |
| 126 | + candidates: EmbeddingProviderCandidate[], |
| 127 | + preferredOrder: ReadonlyArray<EmbeddingProviderKind>, |
| 128 | +): EmbeddingProviderCandidate[] { |
| 129 | + const orderIndex = new Map<EmbeddingProviderKind, number>(); |
| 130 | + for (let i = 0; i < preferredOrder.length; i++) { |
| 131 | + orderIndex.set(preferredOrder[i], i); |
| 132 | + } |
| 133 | + |
| 134 | + return [...candidates].sort((a, b) => { |
| 135 | + const aIndex = orderIndex.get(a.kind) ?? Number.MAX_SAFE_INTEGER; |
| 136 | + const bIndex = orderIndex.get(b.kind) ?? Number.MAX_SAFE_INTEGER; |
| 137 | + return aIndex - bIndex; |
| 138 | + }); |
| 139 | +} |
| 140 | + |
| 141 | +export async function resolveEmbeddingBackend( |
| 142 | + options: ResolveEmbeddingBackendOptions, |
| 143 | +): Promise<ResolvedEmbeddingBackend> { |
| 144 | + const preferredOrder = options.preferredOrder ?? DEFAULT_PROVIDER_ORDER; |
| 145 | + const benchmarkPolicy = validateBenchmarkPolicy({ |
| 146 | + ...DEFAULT_PROVIDER_BENCHMARK_POLICY, |
| 147 | + ...options.benchmark, |
| 148 | + }); |
| 149 | + |
| 150 | + const capabilityChecks = await Promise.all( |
| 151 | + options.candidates.map(async (candidate) => ({ |
| 152 | + candidate, |
| 153 | + supported: await candidate.isSupported(), |
| 154 | + })), |
| 155 | + ); |
| 156 | + |
| 157 | + if (options.forceKind !== undefined) { |
| 158 | + const forcedEntry = capabilityChecks.find( |
| 159 | + (entry) => entry.candidate.kind === options.forceKind, |
| 160 | + ); |
| 161 | + |
| 162 | + if (!forcedEntry || !forcedEntry.supported) { |
| 163 | + throw new Error(`Forced provider ${options.forceKind} is not supported`); |
| 164 | + } |
| 165 | + |
| 166 | + return { |
| 167 | + backend: await forcedEntry.candidate.createBackend(), |
| 168 | + selectedKind: forcedEntry.candidate.kind, |
| 169 | + reason: "forced", |
| 170 | + supportedKinds: orderCandidates( |
| 171 | + capabilityChecks |
| 172 | + .filter((entry) => entry.supported) |
| 173 | + .map((entry) => entry.candidate), |
| 174 | + preferredOrder, |
| 175 | + ).map((candidate) => candidate.kind), |
| 176 | + measurements: [], |
| 177 | + }; |
| 178 | + } |
| 179 | + |
| 180 | + const supportedCandidates = orderCandidates( |
| 181 | + capabilityChecks |
| 182 | + .filter((entry) => entry.supported) |
| 183 | + .map((entry) => entry.candidate), |
| 184 | + preferredOrder, |
| 185 | + ); |
| 186 | + |
| 187 | + if (supportedCandidates.length === 0) { |
| 188 | + throw new Error("No supported embedding providers are available"); |
| 189 | + } |
| 190 | + |
| 191 | + const supportedKinds = supportedCandidates.map((candidate) => candidate.kind); |
| 192 | + |
| 193 | + const benchmarkBackend = options.benchmarkBackend ?? defaultBenchmarkBackend; |
| 194 | + if (benchmarkPolicy.enabled) { |
| 195 | + const measurements: { |
| 196 | + candidate: EmbeddingProviderCandidate; |
| 197 | + backend: EmbeddingBackend; |
| 198 | + meanMs: number; |
| 199 | + }[] = []; |
| 200 | + |
| 201 | + for (const candidate of supportedCandidates) { |
| 202 | + const backend = await candidate.createBackend(); |
| 203 | + const meanMs = await benchmarkBackend(backend, benchmarkPolicy); |
| 204 | + measurements.push({ candidate, backend, meanMs }); |
| 205 | + } |
| 206 | + |
| 207 | + let winner = measurements[0]; |
| 208 | + for (let i = 1; i < measurements.length; i++) { |
| 209 | + if (measurements[i].meanMs < winner.meanMs) { |
| 210 | + winner = measurements[i]; |
| 211 | + } |
| 212 | + } |
| 213 | + |
| 214 | + return { |
| 215 | + backend: winner.backend, |
| 216 | + selectedKind: winner.candidate.kind, |
| 217 | + reason: "benchmark", |
| 218 | + supportedKinds, |
| 219 | + measurements: measurements.map((m) => ({ |
| 220 | + kind: m.candidate.kind, |
| 221 | + meanMs: m.meanMs, |
| 222 | + })), |
| 223 | + }; |
| 224 | + } |
| 225 | + |
| 226 | + const selectedCandidate = supportedCandidates[0]; |
| 227 | + return { |
| 228 | + backend: await selectedCandidate.createBackend(), |
| 229 | + selectedKind: selectedCandidate.kind, |
| 230 | + reason: "capability-order", |
| 231 | + supportedKinds, |
| 232 | + measurements: [], |
| 233 | + }; |
| 234 | +} |
| 235 | + |
| 236 | +export function createDummyProviderCandidate( |
| 237 | + options: DeterministicDummyEmbeddingBackendOptions = {}, |
| 238 | +): EmbeddingProviderCandidate { |
| 239 | + return { |
| 240 | + kind: "dummy", |
| 241 | + isSupported: () => globalThis.crypto?.subtle !== undefined, |
| 242 | + createBackend: () => new DeterministicDummyEmbeddingBackend(options), |
| 243 | + }; |
| 244 | +} |
0 commit comments