import * as fs from "node:fs"; import * as path from "node:path"; import * as os from "node:os"; import { getSearchConfig, type SearchConfig } from "./search_config"; import { kernelDebug } from "../safety/kernel_debug"; export interface EmbeddingResult { vector: Float32Array; dim: number; } export class LocalEmbedder { private extractor: any = null; private config: SearchConfig; private isInitializing = false; private initPromise: Promise | null = null; private queryLruCache = new Map(); private static readonly MAX_QUERY_CACHE_ENTRIES = 128; constructor(config?: SearchConfig) { this.config = config || getSearchConfig(); } public updateConfig(config: SearchConfig): void { this.config = config; this.queryLruCache.clear(); } public isLoaded(): boolean { return this.extractor !== null; } /** * Check if model weights are already downloaded and cached locally on disk. */ public isCachedOnDisk(): boolean { try { const modelParts = this.config.modelId.split("/"); const candidateDirs = [ path.join( __dirname, "../../node_modules", "@huggingface", "transformers", ".cache", ...modelParts, ), path.join( __dirname, "../..", "node_modules", "@huggingface", "transformers", ".cache", ...modelParts, ), path.join( process.cwd(), "node_modules", "@huggingface", "transformers", ".cache", ...modelParts, ), path.join( os.homedir(), ".pi", "agent", "extensions", "agent-kernel", "node_modules", "@huggingface", "transformers", ".cache", ...modelParts, ), path.join( os.homedir(), ".pi", "agent", "extensions", "features", "node_modules", "@huggingface", "transformers", ".cache", ...modelParts, ), path.join( os.homedir(), ".cache", "huggingface", "hub", `models--${this.config.modelId.replace("/", "--")}`, ), path.join( os.homedir(), ".cache", "huggingface", "transformers", ...modelParts, ), path.join(os.homedir(), ".cache", ...modelParts), path.join(os.homedir(), ".pi", "cache", "models", ...modelParts), ]; for (const dir of candidateDirs) { if (!fs.existsSync(dir)) continue; for (const revisionDir of [ path.join(dir, this.config.modelRevision), path.join(dir, "snapshots", this.config.modelRevision), ]) { if (fs.existsSync(revisionDir) && fs.readdirSync(revisionDir).length > 0) { return true; } } } } catch (e) { kernelDebug(e); } return false; } /** * Lazy-initializes the Hugging Face Transformers pipeline with strict thread limits. */ public async initialize(onProgress?: (msg: string) => void): Promise { if (this.extractor) return true; if ( this.config.effectiveProfile === "off" || this.config.effectiveProfile === "lean" ) { return false; } if (this.initPromise) { await this.initPromise; return this.extractor !== null; } this.isInitializing = true; this.initPromise = (async () => { try { const cached = this.isCachedOnDisk(); if (cached) { onProgress?.("Loading embedding weights into RAM..."); } else { onProgress?.("Downloading embedding weights: 0% (~147 MB)..."); } // Enforce single-thread CPU constraints to avoid starving system processes process.env.OMP_NUM_THREADS = String(this.config.numThreads || 1); process.env.ORT_INTRA_OP_NUM_THREADS = String(this.config.numThreads || 1); process.env.ORT_INTER_OP_NUM_THREADS = String(this.config.numThreads || 1); const { env, pipeline } = await import( "@huggingface/transformers" ); if (env && env.backends && env.backends.onnx) { env.backends.onnx.numThreads = this.config.numThreads || 1; env.backends.onnx.logLevel = "warning"; } this.extractor = await pipeline("feature-extraction", this.config.modelId, { revision: this.config.modelRevision, dtype: this.config.dtype, progress_callback: (p: any) => { if (p.status === "progress" && p.total && p.loaded) { const pct = Math.round((p.loaded / p.total) * 100); onProgress?.(`Downloading embedding weights: ${pct}%`); } }, }); // Clamp the sequence length to bound ONNX activation RAM. Texts are cut to 1,800 chars first; with this // model those take ≤ 980 tokens in all but 3 of 23,000 measured chunks, so 1,024 rarely truncates. if (this.extractor?.tokenizer?.config) { this.extractor.tokenizer.config.model_max_length = 1024; } onProgress?.("Embedding model loaded."); } catch (err: any) { console.error("[Search Embedder] Error loading pipeline:", err); this.extractor = null; } finally { this.isInitializing = false; } })(); await this.initPromise; return this.extractor !== null; } /** * Embed a single text string (document or query). */ public async embed( text: string, isQuery = false, onProgress?: (msg: string) => void, ): Promise { if (isQuery) { const cached = this.queryLruCache.get(text); if (cached) { // Refresh MRU order this.queryLruCache.delete(text); this.queryLruCache.set(text, cached); return cached; } } const results = await this.embedBatch([text], isQuery, onProgress); if (results.length > 0) { if (isQuery) { if (this.queryLruCache.size >= LocalEmbedder.MAX_QUERY_CACHE_ENTRIES) { const firstKey = this.queryLruCache.keys().next().value; if (firstKey !== undefined) { this.queryLruCache.delete(firstKey); } } this.queryLruCache.set(text, results[0]); } return results[0]; } return null; } /** * Embed texts as L2-normalized CLS vectors (gte-modernbert-base: no task prefix). Callers pass one text per call: * with q8 weights, texts batched together change each other's vectors. */ public async embedBatch( texts: string[], _isQuery = false, // queries and documents are embedded alike (no task prefix) onProgress?: (msg: string) => void, ): Promise { if ( this.config.effectiveProfile === "off" || this.config.effectiveProfile === "lean" ) { return []; } if (!this.extractor) { const ok = await this.initialize(onProgress); if (!ok || !this.extractor) return []; } if (texts.length === 0) return []; try { const tensorOutput = await this.extractor(texts.map((t) => t.slice(0, 1800)), { pooling: "cls", normalize: true, }); const data: Float32Array = tensorOutput.data; const batchCount = tensorOutput.dims[0]; const actualDim = tensorOutput.dims[1]; const results: Float32Array[] = []; for (let b = 0; b < batchCount; b++) { const start = b * actualDim; const end = start + actualDim; const slice = new Float32Array(actualDim); slice.set(data.subarray(start, end)); results.push(slice); } return results; } catch (err: any) { console.error("[Search Embedder] Error during batch embedding:", err); return []; } } /** * Compute fast cosine similarity between two normalized vectors. */ public static cosineSimilarity(a: Float32Array, b: Float32Array): number { if (a.length !== b.length) return 0; let dot = 0; const len = a.length; for (let i = 0; i < len; i++) { dot += a[i] * b[i]; } return dot; } /** * Unload model from RAM and aggressively release native ONNX sessions and C++ heap buffers. */ public async dispose(): Promise { if (this.extractor) { try { if (typeof this.extractor.dispose === "function") { await this.extractor.dispose(); } if (this.extractor.model) { if (typeof this.extractor.model.dispose === "function") { await this.extractor.model.dispose(); } if (this.extractor.model.session) { if (typeof this.extractor.model.session.release === "function") { await this.extractor.model.session.release(); } if (typeof this.extractor.model.session.dispose === "function") { await this.extractor.model.session.dispose(); } } } if ( this.extractor.tokenizer && typeof this.extractor.tokenizer.dispose === "function" ) { await this.extractor.tokenizer.dispose(); } } catch (e) { kernelDebug(e); } } this.extractor = null; this.initPromise = null; this.queryLruCache.clear(); try { const globalWithGc = globalThis as typeof globalThis & { gc?: () => void }; if (typeof globalWithGc.gc === "function") { globalWithGc.gc(); } } catch (e) { kernelDebug(e); } } }