diff --git a/docs/guide/architecture.md b/docs/guide/architecture.md index 333895b..ab0b39e 100644 --- a/docs/guide/architecture.md +++ b/docs/guide/architecture.md @@ -151,7 +151,7 @@ src/ │ ├── embedding.ts # EmbeddingProvider interface │ ├── index.ts # createEmbeddingProvider() from config │ ├── dimensions.ts # vector sizes of known models -│ ├── local.ts # all-MiniLM-L6-v2 on onnxruntime-web (WebAssembly) +│ ├── local.ts # local models (all-MiniLM-L6-v2, bge) on onnxruntime-web (WebAssembly) │ ├── ollama.ts # Ollama HTTP API │ └── openai.ts # OpenAI embeddings API ├── registry/ # git pack registries: config, git, sync, search, resolve, publish, checksum diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 8930704..a812fa9 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -65,11 +65,11 @@ Earlier versions of the SDK stored data in `~/.libscope/libscope.db`. If that fi Embeddings turn text into vectors for semantic search. LibScope supports three providers: -| Provider | Default | Requires | Notes | -| -------- | ------- | ---------------------- | --------------------------------------------- | -| `local` | ✅ | Nothing | all-MiniLM-L6-v2, ~90MB download on first use | -| `ollama` | | Ollama running locally | Uses nomic-embed-text by default | -| `openai` | | API key | Uses text-embedding-3-small by default | +| Provider | Default | Requires | Notes | +| -------- | ------- | ---------------------- | ------------------------------------------------------------- | +| `local` | ✅ | Nothing | Uses all-MiniLM-L6-v2 by default, ~90MB download on first use | +| `ollama` | | Ollama running locally | Uses nomic-embed-text by default | +| `openai` | | API key | Uses text-embedding-3-small by default | The local provider works out of the box — no API keys, no external services. It runs the model in-process on the ONNX Runtime WebAssembly build (no native addon) and caches it in `~/.libscope/models`. @@ -84,7 +84,19 @@ libscope config set embedding.provider openai libscope config set openai.apiKey sk-... # or export OPENAI_API_KEY ``` -`embedding.model` and `embedding.url` apply to the selected provider. The local provider always uses all-MiniLM-L6-v2 and ignores `embedding.model`. +`embedding.model` and `embedding.url` apply to the selected provider. For the local provider, `embedding.model` selects one of these models. Any other name is an error. + +| `embedding.model` | Vector size | Max tokens | Download | +| ---------------------------- | ----------- | ---------- | -------- | +| `all-MiniLM-L6-v2` (default) | 384 | 256 | ~90MB | +| `bge-small-en-v1.5` | 384 | 512 | ~130MB | +| `bge-base-en-v1.5` | 768 | 512 | ~440MB | + +```bash +libscope config set embedding.model bge-small-en-v1.5 +``` + +Earlier versions ignored `embedding.model` (and `LIBSCOPE_EMBEDDING_MODEL`) for the local provider. A value left from another provider is now an error, and a bge name selects that model, so an existing index then needs a rebuild. To go back to the default, run `libscope config unset embedding.model`, or remove `LIBSCOPE_EMBEDDING_MODEL` or the key in the project `.libscope.json` if it is set there. LibScope records the provider, model, and vector size that built the vector index. If you change the provider, the model, or `embedding.dimensions` after you index documents, LibScope stops with an error that names the old and the new model. To rebuild the vector index with the new model, run: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 52121da..80432de 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -22,23 +22,23 @@ Every key `section.field` has the environment variable `LIBSCOPE_
_ -| Key | Type | Default | Environment variables | Secret | Description | -| ------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `embedding.provider` | `local` \| `ollama` \| `openai` | `local` | `LIBSCOPE_EMBEDDING_PROVIDER` | | Embedding provider. | -| `embedding.model` | string | ollama: nomic-embed-text; openai: text-embedding-3-small | `LIBSCOPE_EMBEDDING_MODEL` | | Embedding model. Ignored by the local provider (always sentence-transformers/all-MiniLM-L6-v2). | -| `embedding.url` | string | `http://localhost:11434` | `LIBSCOPE_EMBEDDING_URL` | | Server URL of the embedding provider. Used by the ollama provider. | -| `embedding.dimensions` | integer | size of the model | `LIBSCOPE_EMBEDDING_DIMENSIONS` | | Vector size, for models whose size is not built in. | -| `llm.provider` | `auto` \| `openai` \| `anthropic` \| `ollama` \| `passthrough` | `auto` | `LIBSCOPE_LLM_PROVIDER` | | LLM for "ask". "auto": passthrough under MCP, else openai if an OpenAI key is set, else anthropic if an Anthropic key is set, else ollama if llm.url is set or embedding.provider is ollama, else none. | -| `llm.model` | string | openai: gpt-4o-mini; anthropic: claude-3-5-haiku-20241022; ollama: llama3.2 | `LIBSCOPE_LLM_MODEL` | | LLM model. | -| `llm.url` | string | embedding.url, then `http://localhost:11434` | `LIBSCOPE_LLM_URL` | | Server URL of the LLM. Used by the ollama provider. | -| `openai.apiKey` | string | — | `LIBSCOPE_OPENAI_API_KEY`, `OPENAI_API_KEY` | yes | OpenAI API key (embeddings and LLM). | -| `anthropic.apiKey` | string | — | `LIBSCOPE_ANTHROPIC_API_KEY`, `ANTHROPIC_API_KEY` | yes | Anthropic API key (LLM). | -| `database.path` | string | `~/.libscope/workspaces//libscope.db` | `LIBSCOPE_DATABASE_PATH` | | SQLite database file. A leading ~ is expanded. Unset: the workspace database. | -| `indexing.maxDocumentSize` | integer | `104857600` | `LIBSCOPE_INDEXING_MAX_DOCUMENT_SIZE` | | Largest document to index, in bytes. | -| `indexing.allowPrivateUrls` | boolean | `false` | `LIBSCOPE_INDEXING_ALLOW_PRIVATE_URLS` | | Allow fetching URLs on private or local networks. | -| `indexing.allowSelfSignedCerts` | boolean | `false` | `LIBSCOPE_INDEXING_ALLOW_SELF_SIGNED_CERTS` | | Accept self-signed TLS certificates when fetching. | -| `logging.level` | `debug` \| `info` \| `warn` \| `error` \| `silent` | `info` | `LIBSCOPE_LOGGING_LEVEL` | | Log level. | -| `mcp.toolsets` | list of `core` \| `admin` \| `all` | `none` | `LIBSCOPE_MCP_TOOLSETS` | | Optional MCP toolsets (comma list). admin adds sync, install-pack, list-packs and reindex-documents; all enables every optional toolset. The core tools are always on. | +| Key | Type | Default | Environment variables | Secret | Description | +| ------------------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `embedding.provider` | `local` \| `ollama` \| `openai` | `local` | `LIBSCOPE_EMBEDDING_PROVIDER` | | Embedding provider. | +| `embedding.model` | string | local: all-MiniLM-L6-v2; ollama: nomic-embed-text; openai: text-embedding-3-small | `LIBSCOPE_EMBEDDING_MODEL` | | Embedding model. Models of the local provider: all-MiniLM-L6-v2, bge-small-en-v1.5, bge-base-en-v1.5. | +| `embedding.url` | string | `http://localhost:11434` | `LIBSCOPE_EMBEDDING_URL` | | Server URL of the embedding provider. Used by the ollama provider. | +| `embedding.dimensions` | integer | size of the model | `LIBSCOPE_EMBEDDING_DIMENSIONS` | | Vector size, for models whose size is not built in. | +| `llm.provider` | `auto` \| `openai` \| `anthropic` \| `ollama` \| `passthrough` | `auto` | `LIBSCOPE_LLM_PROVIDER` | | LLM for "ask". "auto": passthrough under MCP, else openai if an OpenAI key is set, else anthropic if an Anthropic key is set, else ollama if llm.url is set or embedding.provider is ollama, else none. | +| `llm.model` | string | openai: gpt-4o-mini; anthropic: claude-3-5-haiku-20241022; ollama: llama3.2 | `LIBSCOPE_LLM_MODEL` | | LLM model. | +| `llm.url` | string | embedding.url, then `http://localhost:11434` | `LIBSCOPE_LLM_URL` | | Server URL of the LLM. Used by the ollama provider. | +| `openai.apiKey` | string | — | `LIBSCOPE_OPENAI_API_KEY`, `OPENAI_API_KEY` | yes | OpenAI API key (embeddings and LLM). | +| `anthropic.apiKey` | string | — | `LIBSCOPE_ANTHROPIC_API_KEY`, `ANTHROPIC_API_KEY` | yes | Anthropic API key (LLM). | +| `database.path` | string | `~/.libscope/workspaces//libscope.db` | `LIBSCOPE_DATABASE_PATH` | | SQLite database file. A leading ~ is expanded. Unset: the workspace database. | +| `indexing.maxDocumentSize` | integer | `104857600` | `LIBSCOPE_INDEXING_MAX_DOCUMENT_SIZE` | | Largest document to index, in bytes. | +| `indexing.allowPrivateUrls` | boolean | `false` | `LIBSCOPE_INDEXING_ALLOW_PRIVATE_URLS` | | Allow fetching URLs on private or local networks. | +| `indexing.allowSelfSignedCerts` | boolean | `false` | `LIBSCOPE_INDEXING_ALLOW_SELF_SIGNED_CERTS` | | Accept self-signed TLS certificates when fetching. | +| `logging.level` | `debug` \| `info` \| `warn` \| `error` \| `silent` | `info` | `LIBSCOPE_LOGGING_LEVEL` | | Log level. | +| `mcp.toolsets` | list of `core` \| `admin` \| `all` | `none` | `LIBSCOPE_MCP_TOOLSETS` | | Optional MCP toolsets (comma list). admin adds sync, install-pack, list-packs and reindex-documents; all enables every optional toolset. The core tools are always on. | diff --git a/src/config-schema.ts b/src/config-schema.ts index 2972f9b..19ef919 100644 --- a/src/config-schema.ts +++ b/src/config-schema.ts @@ -7,6 +7,7 @@ * metadata. Secret keys are read only from env vars and ~/.libscope/secrets.json. */ import { z } from "zod"; +import { DEFAULT_LOCAL_MODEL, LOCAL_MODELS } from "./providers/local.js"; /** Metadata attached to each leaf of ConfigSchema. */ export interface ConfigKeyMeta { @@ -47,9 +48,11 @@ export const ConfigSchema = z.object({ nonEmpty() .optional() .describe( - "Embedding model. Ignored by the local provider (always sentence-transformers/all-MiniLM-L6-v2).", + `Embedding model. Models of the local provider: ${[...LOCAL_MODELS.keys()].join(", ")}.`, ), - { defaultText: "ollama: nomic-embed-text; openai: text-embedding-3-small" }, + { + defaultText: `local: ${DEFAULT_LOCAL_MODEL}; ollama: nomic-embed-text; openai: text-embedding-3-small`, + }, ), url: leaf( nonEmpty() diff --git a/src/config.ts b/src/config.ts index f3b08df..ea60447 100644 --- a/src/config.ts +++ b/src/config.ts @@ -387,11 +387,6 @@ function validateProviderConfig(config: LibScopeConfig, warnings: string[]): voi if (config.embedding.provider === "openai" && !openaiKey) { warnings.push(`embedding.provider is "openai" but no API key found. ${apiKeyHint("OPENAI")}`); } - if (config.embedding.provider === "local" && config.embedding.model) { - warnings.push( - `embedding.model "${config.embedding.model}" is ignored by the local provider (it always uses sentence-transformers/all-MiniLM-L6-v2).`, - ); - } if (config.llm?.provider === "openai" && !openaiKey) { warnings.push(`llm.provider is "openai" but no API key found. ${apiKeyHint("OPENAI")}`); } diff --git a/src/providers/index.ts b/src/providers/index.ts index b041fc7..9b1d02b 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -16,7 +16,7 @@ export function createEmbeddingProvider(config: LibScopeConfig): EmbeddingProvid const { embedding } = config; switch (embedding.provider) { case "local": - return new LocalEmbeddingProvider(); + return new LocalEmbeddingProvider(embedding.model); case "ollama": return new OllamaEmbeddingProvider( embedding.url ?? DEFAULT_OLLAMA_URL, diff --git a/src/providers/local.ts b/src/providers/local.ts index a4fe05d..9d53058 100644 --- a/src/providers/local.ts +++ b/src/providers/local.ts @@ -1,26 +1,76 @@ -import { existsSync } from "node:fs"; -import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { createWriteStream, existsSync } from "node:fs"; +import { mkdir, readFile, rename, rm } from "node:fs/promises"; import { availableParallelism, homedir } from "node:os"; import { dirname, join } from "node:path"; +import { pipeline } from "node:stream/promises"; import type { InferenceSession, Tensor } from "onnxruntime-web"; -import { EmbeddingError } from "../errors.js"; +import { ConfigError, EmbeddingError } from "../errors.js"; import type { EmbeddingProvider } from "./embedding.js"; import { getLogger } from "../logger.js"; import { forEachSequential, mapSequential } from "../utils/async.js"; import { withRetry } from "../utils/retry.js"; -/** Hugging Face repository and pinned revision of the ONNX export of all-MiniLM-L6-v2. */ -const MODEL_REPO = "Xenova/all-MiniLM-L6-v2"; -const MODEL_REVISION = "751bff37182d3f1213fa05d7196b954e230abad9"; +/** A model that the local provider can run. */ +interface LocalModel { + /** Model identifier, recorded with the vector index. */ + model: string; + /** Hugging Face repository and pinned revision of the ONNX export. */ + repo: string; + revision: string; + /** The model's max_seq_length in sentence-transformers. Longer input is truncated. */ + maxTokens: number; + /** How the token vectors become the vector of the text. */ + pooling: "mean" | "cls"; + dimensions: number; +} + +/** The supported local models, keyed by their `embedding.model` name. */ +export const LOCAL_MODELS: ReadonlyMap = new Map([ + [ + "all-MiniLM-L6-v2", + { + model: "sentence-transformers/all-MiniLM-L6-v2", + repo: "Xenova/all-MiniLM-L6-v2", + revision: "751bff37182d3f1213fa05d7196b954e230abad9", + maxTokens: 256, + pooling: "mean", + dimensions: 384, + }, + ], + [ + "bge-small-en-v1.5", + { + model: "BAAI/bge-small-en-v1.5", + repo: "Xenova/bge-small-en-v1.5", + revision: "ea104dacec62c0de699686887e3f920caeb4f3e3", + maxTokens: 512, + pooling: "cls", + dimensions: 384, + }, + ], + [ + "bge-base-en-v1.5", + { + model: "BAAI/bge-base-en-v1.5", + repo: "Xenova/bge-base-en-v1.5", + revision: "4d6cd88e18e51a5e020c2c305726d76ada9c03cf", + maxTokens: 512, + pooling: "cls", + dimensions: 768, + }, + ], +]); + +/** The key of LOCAL_MODELS used when `embedding.model` is not set. */ +export const DEFAULT_LOCAL_MODEL = "all-MiniLM-L6-v2"; + const TOKENIZER_FILE = "tokenizer.json"; const TOKENIZER_CONFIG_FILE = "tokenizer_config.json"; // Full precision: the quantized export's vectors drift from the original model's. const ONNX_FILE = "onnx/model.onnx"; const MODEL_FILES = [TOKENIZER_FILE, TOKENIZER_CONFIG_FILE, ONNX_FILE]; -/** The model's max_seq_length in sentence-transformers. Longer input is truncated. */ -export const MAX_TOKENS = 256; - /** Download events while the model files are fetched (first use only). */ export interface ModelDownloadEvent { /** "progress" while a file downloads, then "ready" once all files are cached. */ @@ -30,18 +80,23 @@ export interface ModelDownloadEvent { progress?: number | undefined; } -/** Directory where the local embedding model is cached (`~/.libscope/models`). */ +/** Directory where the local embedding models are cached (`~/.libscope/models`). */ export function getModelCacheDir(): string { return join(homedir(), ".libscope", "models"); } /** - * Truncate token ids that start with [CLS] and end with [SEP] to MAX_TOKENS, + * Truncate token ids that start with [CLS] and end with [SEP] to `maxTokens`, * keeping the final [SEP] as sentence-transformers does. */ -export function truncateTokenIds(ids: number[]): number[] { - if (ids.length <= MAX_TOKENS) return ids; - return [...ids.slice(0, MAX_TOKENS - 1), ...ids.slice(-1)]; +export function truncateTokenIds(ids: number[], maxTokens: number): number[] { + if (ids.length <= maxTokens) return ids; + return [...ids.slice(0, maxTokens - 1), ...ids.slice(-1)]; +} + +function scaleToUnitLength(vector: number[]): number[] { + const norm = Math.sqrt(vector.reduce((acc, x) => acc + x * x, 0)); + return vector.map((x) => x / norm); } /** Mean of the token vectors (shape [tokens, dimensions], row-major), scaled to unit length. */ @@ -56,40 +111,51 @@ export function meanPoolNormalized( sum[d]! += hidden[t * dimensions + d]!; } } - const norm = Math.sqrt(sum.reduce((acc, x) => acc + x * x, 0)); - return sum.map((x) => x / norm); + return scaleToUnitLength(sum); +} + +/** Vector of the first token, [CLS] (shape [tokens, dimensions], row-major), scaled to unit length. */ +export function clsPoolNormalized(hidden: Float32Array, dimensions: number): number[] { + return scaleToUnitLength(Array.from(hidden.subarray(0, dimensions))); } -/** Download one model file into the cache, through a temporary file. */ +/** Download one model file into the cache, through a temporary file of this download. */ async function downloadModelFile( + model: LocalModel, file: string, dest: string, onProgress: ((event: ModelDownloadEvent) => void) | undefined, ): Promise { - const url = `https://huggingface.co/${MODEL_REPO}/resolve/${MODEL_REVISION}/${file}`; - const { body, total } = await withRetry(async () => { - const res = await fetch(url); - if (!res.ok || !res.body) { - throw new EmbeddingError(`Download of ${url} failed: HTTP ${res.status}`); + const url = `https://huggingface.co/${model.repo}/resolve/${model.revision}/${file}`; + const partial = `${dest}.${randomUUID()}.partial`; + await mkdir(dirname(dest), { recursive: true }); + await withRetry(async () => { + try { + const res = await fetch(url); + if (!res.ok || !res.body) { + throw new EmbeddingError(`Download of ${url} failed: HTTP ${res.status}`); + } + const total = Number(res.headers.get("content-length")); + let received = 0; + await pipeline( + res.body as AsyncIterable, + async function* (parts: AsyncIterable) { + for await (const part of parts) { + received += part.length; + if (onProgress && total > 0) { + onProgress({ status: "progress", file, progress: (received / total) * 100 }); + } + yield part; + } + }, + createWriteStream(partial), + ); + await rename(partial, dest); + } catch (err) { + await rm(partial, { force: true }).catch(() => undefined); + throw err; } - return { - body: res.body as AsyncIterable, - total: Number(res.headers.get("content-length")), - }; }); - const parts: Uint8Array[] = []; - let received = 0; - for await (const part of body) { - parts.push(part); - received += part.length; - if (onProgress && total > 0) { - onProgress({ status: "progress", file, progress: (received / total) * 100 }); - } - } - await mkdir(dirname(dest), { recursive: true }); - const partial = `${dest}.partial`; - await writeFile(partial, Buffer.concat(parts)); - await rename(partial, dest); } /** @@ -112,17 +178,35 @@ interface LoadedModel { } /** - * Local embedding provider: all-MiniLM-L6-v2 run in-process on the ONNX Runtime - * WebAssembly build, with truncation and mean pooling as in sentence-transformers. - * Downloads the model on first use (~90MB). + * Local embedding provider: one of LOCAL_MODELS run in-process on the ONNX Runtime + * WebAssembly build, with truncation and pooling as in sentence-transformers. + * Downloads the model on first use. */ export class LocalEmbeddingProvider implements EmbeddingProvider { readonly name = "local"; - readonly model = "sentence-transformers/all-MiniLM-L6-v2"; - readonly dimensions = 384; + readonly model: string; + readonly dimensions: number; + private readonly localModel: LocalModel; private loading: Promise | null = null; + /** @throws ConfigError when `modelName` is not a key of LOCAL_MODELS. */ + constructor(modelName: string = DEFAULT_LOCAL_MODEL) { + const localModel = LOCAL_MODELS.get(modelName); + if (!localModel) { + throw new ConfigError( + `embedding.model "${modelName}" is not a model of the local provider. ` + + `Supported models: ${[...LOCAL_MODELS.keys()].join(", ")}. ` + + 'Run "libscope config set embedding.model " or ' + + '"libscope config unset embedding.model". ' + + "If LIBSCOPE_EMBEDDING_MODEL or a project .libscope.json sets it, change it there.", + ); + } + this.localModel = localModel; + this.model = localModel.model; + this.dimensions = localModel.dimensions; + } + /** Called while the model is downloaded (not when it is already cached), e.g. to show progress. */ onDownloadProgress: ((event: ModelDownloadEvent) => void) | undefined; @@ -137,12 +221,12 @@ export class LocalEmbeddingProvider implements EmbeddingProvider { private async loadModel(): Promise { const log = getLogger(); - log.info("Loading local embedding model (all-MiniLM-L6-v2)..."); - const modelDir = join(getModelCacheDir(), MODEL_REPO); + log.info(`Loading local embedding model (${this.model})...`); + const modelDir = join(getModelCacheDir(), this.localModel.repo); const missing = MODEL_FILES.filter((file) => !existsSync(join(modelDir, file))); // One file at a time, so that download progress reports one file at a time. await forEachSequential(missing, (file) => - downloadModelFile(file, join(modelDir, file), this.onDownloadProgress), + downloadModelFile(this.localModel, file, join(modelDir, file), this.onDownloadProgress), ); if (missing.length > 0) this.onDownloadProgress?.({ status: "ready" }); @@ -176,7 +260,7 @@ export class LocalEmbeddingProvider implements EmbeddingProvider { } const { tokenizer, session, Tensor } = await this.load(); try { - const ids = truncateTokenIds(tokenizer.encode(text).ids); + const ids = truncateTokenIds(tokenizer.encode(text).ids, this.localModel.maxTokens); const shape = [1, ids.length]; const output = await session.run({ input_ids: new Tensor("int64", BigInt64Array.from(ids, BigInt), shape), @@ -189,7 +273,12 @@ export class LocalEmbeddingProvider implements EmbeddingProvider { `Expected embedding dimension ${this.dimensions}, got ${hidden.length / ids.length}`, ); } - return meanPoolNormalized(hidden, ids.length, this.dimensions); + switch (this.localModel.pooling) { + case "mean": + return meanPoolNormalized(hidden, ids.length, this.dimensions); + case "cls": + return clsPoolNormalized(hidden, this.dimensions); + } } catch (err) { throw new EmbeddingError(`Failed to generate embedding: ${String(err)}`, err); } diff --git a/tests/unit/config.test.ts b/tests/unit/config.test.ts index 44a5624..964eb27 100644 --- a/tests/unit/config.test.ts +++ b/tests/unit/config.test.ts @@ -187,12 +187,6 @@ describe("validateConfig", () => { expect(validateConfig(config)).toHaveLength(0); }); - it("should warn when embedding.model is set for the local provider", () => { - const config = makeConfig({ embedding: { provider: "local", model: "bge-m3" } }); - const warnings = validateConfig(config); - expect(warnings.some((w) => w.includes("ignored by the local provider"))).toBe(true); - }); - it("should not warn when ollama provider has a URL", () => { const config = makeConfig({ embedding: { provider: "ollama", url: "http://localhost:11434" }, diff --git a/tests/unit/local-embedding-models.test.ts b/tests/unit/local-embedding-models.test.ts new file mode 100644 index 0000000..6aa6e75 --- /dev/null +++ b/tests/unit/local-embedding-models.test.ts @@ -0,0 +1,248 @@ +import { join } from "node:path"; +import { Writable } from "node:stream"; +import { describe, it, expect, vi, beforeAll, beforeEach } from "vitest"; + +const TOKENS = 600; +const run = vi.fn(); +const fetchMock = vi.fn(); +const existsSync = vi.fn(); +const rename = vi.fn(); +const rm = vi.fn(); +const written = new Map(); + +vi.stubGlobal("fetch", fetchMock); + +vi.mock("node:fs", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + existsSync, + createWriteStream: vi.fn((path: string) => { + const chunks: Buffer[] = []; + written.set(path, chunks); + return new Writable({ + write(chunk: Buffer, _encoding, done): void { + chunks.push(chunk); + done(); + }, + }); + }), + }; +}); + +vi.mock("node:fs/promises", async (importOriginal) => { + const original = await importOriginal(); + return { + ...original, + mkdir: vi.fn(() => Promise.resolve(undefined)), + readFile: vi.fn(() => Promise.resolve("{}")), + rename, + rm, + }; +}); + +vi.mock("../../src/utils/retry.js", async (importOriginal) => { + const original = await importOriginal(); + return { + withRetry: (fn: () => Promise): Promise => original.withRetry(fn, { baseDelayMs: 0 }), + }; +}); + +vi.mock("@huggingface/tokenizers", () => ({ + Tokenizer: class { + encode(): { ids: number[] } { + return { ids: Array.from({ length: TOKENS }, (_, i) => i) }; + } + }, +})); + +vi.mock("onnxruntime-web", () => ({ + env: { wasm: {} }, + InferenceSession: { create: vi.fn(() => Promise.resolve({ run })) }, + Tensor: class { + constructor( + readonly type: string, + readonly data: BigInt64Array, + readonly dims: number[], + ) {} + }, +})); + +const { getModelCacheDir, LOCAL_MODELS, LocalEmbeddingProvider } = + await import("../../src/providers/local.js"); +const { initLogger } = await import("../../src/logger.js"); + +/** Hidden state where the [CLS] vector is the first axis and every other token the second. */ +function hiddenState(tokens: number, dimensions: number): Float32Array { + const hidden = new Float32Array(tokens * dimensions); + hidden[0] = 1; + for (let t = 1; t < tokens; t++) { + hidden[t * dimensions + 1] = 1; + } + return hidden; +} + +function mockSession(dimensions: number): void { + run.mockImplementation((feeds: { input_ids: { dims: number[] } }) => + Promise.resolve({ + last_hidden_state: { data: hiddenState(feeds.input_ids.dims[1]!, dimensions) }, + }), + ); +} + +beforeAll(() => { + initLogger("silent"); +}); + +beforeEach(() => { + run.mockReset(); + fetchMock.mockReset(); + existsSync.mockReset(); + rename.mockReset(); + rm.mockReset(); + written.clear(); +}); + +describe.each([...LOCAL_MODELS])( + "LocalEmbeddingProvider with %s", + (name, { maxTokens, pooling, dimensions }) => { + it(`truncates to ${maxTokens} tokens and pools with ${pooling}`, async () => { + existsSync.mockReturnValue(true); + mockSession(dimensions); + + const vector = await new LocalEmbeddingProvider(name).embed("some text"); + + const feeds = run.mock.calls[0]![0] as { input_ids: { data: BigInt64Array } }; + expect(feeds.input_ids.data).toHaveLength(maxTokens); + expect(feeds.input_ids.data.at(-1)).toBe(BigInt(TOKENS - 1)); + + expect(vector).toHaveLength(dimensions); + const others = maxTokens - 1; + const expected = { + cls: [1, 0], + mean: [1 / Math.hypot(1, others), others / Math.hypot(1, others)], + }[pooling]; + expect(vector[0]).toBeCloseTo(expected[0]!, 6); + expect(vector[1]).toBeCloseTo(expected[1]!, 6); + expect(vector.slice(2).every((x) => x === 0)).toBe(true); + }); + }, +); + +describe("LocalEmbeddingProvider model download", () => { + const name = "bge-small-en-v1.5"; + const { repo, revision, dimensions } = LOCAL_MODELS.get(name)!; + const content = new Uint8Array([1, 2, 3, 4]); + const tokenizerDest = join(getModelCacheDir(), repo, "tokenizer.json"); + const onnxDest = join(getModelCacheDir(), repo, "onnx/model.onnx"); + const TEMP_SUFFIX = /^\.[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\.partial$/; + + /** The one temporary file that was opened for `dest`. */ + function tempFileOf(dest: string): string { + const temps = [...written.keys()].filter( + (path) => path.startsWith(dest) && TEMP_SUFFIX.test(path.slice(dest.length)), + ); + expect(temps).toHaveLength(1); + return temps[0]!; + } + + /** A body without content-length that sends `content`, then fails if `fail` is set. */ + function streamBody(fail: boolean): ReadableStream { + let sent = false; + return new ReadableStream({ + pull(controller): void { + if (!sent) { + sent = true; + controller.enqueue(content); + } else if (fail) { + controller.error(new Error("connection reset")); + } else { + controller.close(); + } + }, + }); + } + + function embedCollectingEvents(): { result: Promise; events: unknown[] } { + const provider = new LocalEmbeddingProvider(name); + const events: unknown[] = []; + provider.onDownloadProgress = (event): void => { + events.push(event); + }; + return { result: provider.embed("some text"), events }; + } + + beforeEach(() => { + existsSync.mockReturnValue(false); + rename.mockResolvedValue(undefined); + rm.mockResolvedValue(undefined); + mockSession(dimensions); + }); + + it("removes the temporary file and rejects when the body fails on every attempt", async () => { + fetchMock.mockImplementation(() => Promise.resolve(new Response(streamBody(true)))); + + await expect(embedCollectingEvents().result).rejects.toThrow( + "Failed to load local embedding model", + ); + + expect(fetchMock).toHaveBeenCalledTimes(4); + const removal = [tempFileOf(tokenizerDest), { force: true }]; + expect(rm.mock.calls).toEqual([removal, removal, removal, removal]); + expect(rename).not.toHaveBeenCalled(); + }); + + it("retries a download whose body fails", async () => { + fetchMock + .mockImplementationOnce(() => Promise.resolve(new Response(streamBody(true)))) + .mockImplementation(() => Promise.resolve(new Response(streamBody(false)))); + + await embedCollectingEvents().result; + + expect(fetchMock).toHaveBeenCalledTimes(4); + const temp = tempFileOf(tokenizerDest); + expect(rm.mock.calls).toEqual([[temp, { force: true }]]); + expect(Buffer.concat(written.get(temp)!)).toEqual(Buffer.from(content)); + expect(rename).toHaveBeenCalledWith(temp, tokenizerDest); + }); + + it("rejects with the download error when removing the temporary file fails", async () => { + fetchMock.mockImplementation(() => Promise.resolve(new Response(null, { status: 404 }))); + rm.mockRejectedValue(new Error("EISDIR")); + + await expect(embedCollectingEvents().result).rejects.toMatchObject({ + cause: { message: expect.stringContaining("HTTP 404") as unknown }, + }); + }); + + it("reports only ready when the response has no content-length", async () => { + fetchMock.mockImplementation(() => Promise.resolve(new Response(streamBody(false)))); + + const { result, events } = embedCollectingEvents(); + await result; + + expect(events).toEqual([{ status: "ready" }]); + }); + + it("streams the files of the pinned revision into the model's cache directory", async () => { + fetchMock.mockImplementation(() => + Promise.resolve(new Response(content, { headers: { "content-length": "4" } })), + ); + + const { result, events } = embedCollectingEvents(); + await result; + + const urls = fetchMock.mock.calls.map((call) => call[0] as string); + expect(urls).toEqual( + ["tokenizer.json", "tokenizer_config.json", "onnx/model.onnx"].map( + (file) => `https://huggingface.co/${repo}/resolve/${revision}/${file}`, + ), + ); + + const temp = tempFileOf(onnxDest); + expect(Buffer.concat(written.get(temp)!)).toEqual(Buffer.from(content)); + expect(rename).toHaveBeenCalledWith(temp, onnxDest); + expect(events).toContainEqual({ status: "progress", file: "onnx/model.onnx", progress: 100 }); + expect(events.at(-1)).toEqual({ status: "ready" }); + }); +}); diff --git a/tests/unit/local-embedding.test.ts b/tests/unit/local-embedding.test.ts index 695a8ca..1dfbc24 100644 --- a/tests/unit/local-embedding.test.ts +++ b/tests/unit/local-embedding.test.ts @@ -1,28 +1,80 @@ import { describe, it, expect, beforeAll } from "vitest"; import { + clsPoolNormalized, + LOCAL_MODELS, LocalEmbeddingProvider, - MAX_TOKENS, meanPoolNormalized, truncateTokenIds, } from "../../src/providers/local.js"; +import { createEmbeddingProvider } from "../../src/providers/index.js"; +import type { LibScopeConfig } from "../../src/config.js"; +import { ConfigError } from "../../src/errors.js"; import { initLogger } from "../../src/logger.js"; const CLS = 101; const SEP = 102; -describe("truncateTokenIds", () => { - it("keeps input of at most MAX_TOKENS ids unchanged", () => { - const ids = [CLS, ...Array.from({ length: MAX_TOKENS - 2 }, (_, i) => 1000 + i), SEP]; - expect(truncateTokenIds(ids)).toEqual(ids); +const TOKEN_LIMITS = [...new Set([...LOCAL_MODELS.values()].map((model) => model.maxTokens))]; + +describe.each(TOKEN_LIMITS)("truncateTokenIds to %i tokens", (maxTokens) => { + it("keeps input of at most maxTokens ids unchanged", () => { + const ids = [CLS, ...Array.from({ length: maxTokens - 2 }, (_, i) => 1000 + i), SEP]; + expect(truncateTokenIds(ids, maxTokens)).toEqual(ids); }); - it("cuts longer input to MAX_TOKENS ids and keeps the final [SEP]", () => { + it("cuts longer input to maxTokens ids and keeps the final [SEP]", () => { const body = Array.from({ length: 600 }, (_, i) => 1000 + i); - const truncated = truncateTokenIds([CLS, ...body, SEP]); - expect(truncated).toHaveLength(MAX_TOKENS); + const truncated = truncateTokenIds([CLS, ...body, SEP], maxTokens); + expect(truncated).toHaveLength(maxTokens); expect(truncated[0]).toBe(CLS); expect(truncated.at(-1)).toBe(SEP); - expect(truncated.slice(1, -1)).toEqual(body.slice(0, MAX_TOKENS - 2)); + expect(truncated.slice(1, -1)).toEqual(body.slice(0, maxTokens - 2)); + }); +}); + +describe("clsPoolNormalized", () => { + it("takes the first token vector and scales it to unit length", () => { + expect(clsPoolNormalized(new Float32Array([3, 4, 1, 0]), 2)).toEqual([0.6, 0.8]); + }); +}); + +describe("local model selection", () => { + function config(embedding: LibScopeConfig["embedding"]): LibScopeConfig { + return { + embedding, + database: { path: ":memory:" }, + indexing: { maxDocumentSize: 1024, allowPrivateUrls: false, allowSelfSignedCerts: false }, + logging: { level: "silent" }, + }; + } + + it("uses all-MiniLM-L6-v2 when embedding.model is not set", () => { + const provider = createEmbeddingProvider(config({ provider: "local" })); + expect(provider.model).toBe("sentence-transformers/all-MiniLM-L6-v2"); + expect(provider.dimensions).toBe(384); + }); + + it.each([ + ["all-MiniLM-L6-v2", "sentence-transformers/all-MiniLM-L6-v2", 384], + ["bge-small-en-v1.5", "BAAI/bge-small-en-v1.5", 384], + ["bge-base-en-v1.5", "BAAI/bge-base-en-v1.5", 768], + ])("selects %s from embedding.model", (name, model, dimensions) => { + const provider = createEmbeddingProvider(config({ provider: "local", model: name })); + expect(provider.model).toBe(model); + expect(provider.dimensions).toBe(dimensions); + }); + + it.each(["bge-m3", "constructor"])("rejects the unknown model %s", (name) => { + const create = (): unknown => + createEmbeddingProvider(config({ provider: "local", model: name })); + expect(create).toThrow(ConfigError); + expect(create).toThrow( + `embedding.model "${name}" is not a model of the local provider. ` + + "Supported models: all-MiniLM-L6-v2, bge-small-en-v1.5, bge-base-en-v1.5. " + + 'Run "libscope config set embedding.model " or ' + + '"libscope config unset embedding.model". ' + + "If LIBSCOPE_EMBEDDING_MODEL or a project .libscope.json sets it, change it there.", + ); }); });