v0.2 step 9 — embeddings (#42)
POST /v1/embeddings with mlx-swift-lm's MLXEmbedders: string or list input, float or base64 encoding, dimensions (truncate and renormalise), batches of 32 with an attention mask, 400s for inputs longer than the model accepts. Engines are created per model kind, so a repository can be loaded as a chat and as an embedding model; a model of the wrong kind on an endpoint is a 400. Cosine similarities match sentence-transformers within 1e-3 for all-MiniLM-L6-v2 and bge-small-en-v1.5. Getting there needed one fix: sentence-transformers' CLS pooling is the first token's hidden state, while MLXEmbedders' .cls takes BERT's pooler output. Tests: Linux 144, Mac 167. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e171b51 parent: 53d6eb7 modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +9 -2 | @@ -10,16 +10,20 @@ made by Claude on a plain "go": mention them to the user if reasoning comes up. | ||
| 10 | 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; |
| 11 | 11 | now verified on the Mac). |
| 12 | 12 | Update after #41: constrained decoding, response_format, tools done (Linux 136, Mac 156). |
| 13 | +Update after #42: embeddings done (Linux 144, Mac 167). The user received a testing checklist for | |
| 14 | +#38–#42 (in the chat, not in the repo): their results may reopen items. | |
| 13 | 15 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 14 | 16 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 15 | 17 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 16 | 18 | closed. Nothing pushed. |
| 17 | 19 | |
| 18 | 20 | ## Next steps |
| 19 | -1. #42 embeddings (in progress in this session), then give the user the testing checklist they | |
| 20 | - asked for (end of the #38–#42 request). | |
| 21 | +1. Wait for the user's results on the #38–#42 checklist (openai `.parse` with a 4B model, a second | |
| 22 | + tool-call family, LangChain embeddings, Release-build speed of constrained decoding). | |
| 21 | 23 | 2. Then #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; agent docs still in docs/). |
| 22 | 24 | 3. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. |
| 25 | +4. /v1/models lists cached repositories as kind "chat" even when they are embedding models (the | |
| 26 | + cache does not say); declared models carry their real kind. | |
| 23 | 27 | |
| 24 | 28 | ## Watch out for |
| 25 | 29 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -57,6 +61,9 @@ closed. Nothing pushed. | ||
| 57 | 61 | end token; `GrammarProcessor` stops committing once the grammar has terminated. |
| 58 | 62 | - Debugging a constrained generation: print the raw `EngineEvent`s of a session — when the tool |
| 59 | 63 | parser swallows a truncated call, the API shows only an empty answer with finish_reason length. |
| 64 | +- Embedding reference values: `scratchpad/ref/reference.py` (sentence-transformers via | |
| 65 | + `uv run --with sentence-transformers --with torch --extra-index-url https://download.pytorch.org/whl/cpu`); | |
| 66 | + the scratchpad is not durable — the values are hard-coded in `EmbeddingSmokeTests.swift`. | |
| 60 | 67 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 61 | 68 | the requested name. |
| 62 | 69 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
| @@ -10,16 +10,20 @@ made by Claude on a plain "go": mention them to the user if reasoning comes up. | |||
| 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; | 10 | for a way to hide it (`show_reasoning` / `include_reasoning`, done) and for it to stream (it did; |
| 11 | now verified on the Mac). | 11 | now verified on the Mac). |
| 12 | Update after #41: constrained decoding, response_format, tools done (Linux 136, Mac 156). | 12 | Update after #41: constrained decoding, response_format, tools done (Linux 136, Mac 156). |
| 13 | +Update after #42: embeddings done (Linux 144, Mac 167). The user received a testing checklist for | ||
| 14 | +#38–#42 (in the chat, not in the repo): their results may reopen items. | ||
| 13 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP | 15 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 14 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket | 16 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 15 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task | 17 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 16 | closed. Nothing pushed. | 18 | closed. Nothing pushed. |
| 17 | 19 | ||
| 18 | ## Next steps | 20 | ## Next steps |
| 19 | -1. #42 embeddings (in progress in this session), then give the user the testing checklist they | 21 | +1. Wait for the user's results on the #38–#42 checklist (openai `.parse` with a 4B model, a second |
| 20 | - asked for (end of the #38–#42 request). | 22 | + tool-call family, LangChain embeddings, Release-build speed of constrained decoding). |
| 21 | 2. Then #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; agent docs still in docs/). | 23 | 2. Then #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; agent docs still in docs/). |
| 22 | 3. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | 24 | 3. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. |
| 25 | +4. /v1/models lists cached repositories as kind "chat" even when they are embedding models (the | ||
| 26 | + cache does not say); declared models carry their real kind. | ||
| 23 | 27 | ||
| 24 | ## Watch out for | 28 | ## Watch out for |
| 25 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns | 29 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -57,6 +61,9 @@ closed. Nothing pushed. | |||
| 57 | end token; `GrammarProcessor` stops committing once the grammar has terminated. | 61 | end token; `GrammarProcessor` stops committing once the grammar has terminated. |
| 58 | - Debugging a constrained generation: print the raw `EngineEvent`s of a session — when the tool | 62 | - Debugging a constrained generation: print the raw `EngineEvent`s of a session — when the tool |
| 59 | parser swallows a truncated call, the API shows only an empty answer with finish_reason length. | 63 | parser swallows a truncated call, the API shows only an empty answer with finish_reason length. |
| 64 | +- Embedding reference values: `scratchpad/ref/reference.py` (sentence-transformers via | ||
| 65 | + `uv run --with sentence-transformers --with torch --extra-index-url https://download.pytorch.org/whl/cpu`); | ||
| 66 | + the scratchpad is not durable — the values are hard-coded in `EmbeddingSmokeTests.swift`. | ||
| 60 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by | 67 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 61 | the requested name. | 68 | the requested name. |
| 62 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. | 69 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
modified
.memory/history.md +8 -0 | @@ -198,3 +198,11 @@ | ||
| 198 | 198 | 400, rejected the ticket's retry-then-500 fallback). Found and fixed: JSON answers streamed in one |
| 199 | 199 | piece because mlx-swift-lm's `.json` parser holds back a leading brace (switch to `.gptOSS` parser |
| 200 | 200 | when no tools). Linux 136, Mac 156 (8 constrained smoke tests with real Qwen3), gate PASS (run #15). |
| 201 | +- #42 embeddings: MLXEmbedder + /v1/embeddings (string/list input, float/base64, dimensions with | |
| 202 | + renormalisation, batches of 32, max-length 400, kind checks). Reference cosines computed with | |
| 203 | + sentence-transformers in the sandbox (uv, CPU torch) and hard-coded in a Mac test: MiniLM matched | |
| 204 | + at once, bge-small was 0.08 off → found MLXEmbedders' `.cls` uses BERT's pooler output; mapped to | |
| 205 | + `.first`. Not done (ticket deviations recorded): per-model dimension capability, `truncate`, | |
| 206 | + pooling/prefix config. `rzb models pull` fetched both reference models on the Mac. Linux 144, | |
| 207 | + Mac 167, gate PASS (run #16). #42 closed. End of the user's #38–#42 request; testing checklist | |
| 208 | + given in the final answer. | |
| @@ -198,3 +198,11 @@ | |||
| 198 | 400, rejected the ticket's retry-then-500 fallback). Found and fixed: JSON answers streamed in one | 198 | 400, rejected the ticket's retry-then-500 fallback). Found and fixed: JSON answers streamed in one |
| 199 | piece because mlx-swift-lm's `.json` parser holds back a leading brace (switch to `.gptOSS` parser | 199 | piece because mlx-swift-lm's `.json` parser holds back a leading brace (switch to `.gptOSS` parser |
| 200 | when no tools). Linux 136, Mac 156 (8 constrained smoke tests with real Qwen3), gate PASS (run #15). | 200 | when no tools). Linux 136, Mac 156 (8 constrained smoke tests with real Qwen3), gate PASS (run #15). |
| 201 | +- #42 embeddings: MLXEmbedder + /v1/embeddings (string/list input, float/base64, dimensions with | ||
| 202 | + renormalisation, batches of 32, max-length 400, kind checks). Reference cosines computed with | ||
| 203 | + sentence-transformers in the sandbox (uv, CPU torch) and hard-coded in a Mac test: MiniLM matched | ||
| 204 | + at once, bge-small was 0.08 off → found MLXEmbedders' `.cls` uses BERT's pooler output; mapped to | ||
| 205 | + `.first`. Not done (ticket deviations recorded): per-model dimension capability, `truncate`, | ||
| 206 | + pooling/prefix config. `rzb models pull` fetched both reference models on the Mac. Linux 144, | ||
| 207 | + Mac 167, gate PASS (run #16). #42 closed. End of the user's #38–#42 request; testing checklist | ||
| 208 | + given in the final answer. | ||
modified
.memory/summary.md +8 -3 | @@ -8,7 +8,7 @@ and reasoning, structured output, function calling, embeddings; "decision models | ||
| 8 | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | 10 | model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37, constrained |
| 11 | -decoding #38, structured output #39, function calling #40/#41 (see Architecture). Decided by the user (#31): the | |
| 11 | +decoding #38, structured output #39, function calling #40/#41, embeddings #42 (see Architecture). Decided by the user (#31): the | |
| 12 | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 14 | 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -69,7 +69,11 @@ by a `GrammarProcessor` (LogitProcessor on mlx-swift-lm's XGrammar bridge, inact | ||
| 69 | 69 | `response_format` → `.jsonSchema` (strict + unenforced keyword → 400); tools/tool_choice in |
| 70 | 70 | `Chat/ToolsAndFormats.swift`; forced tool calls via structural tags for the `<tool_call>` JSON syntax |
| 71 | 71 | only (others → 400); forced calls are single unless `parallel_tool_calls: true`. Sessions without |
| 72 | -tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Next: embeddings (#42). | |
| 72 | +tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Embeddings (#42): | |
| 73 | +`InferenceEngine.embed`, `EngineRegistry` factories take a `ModelKind` (`mlx` → `MLXEngine` or | |
| 74 | +`MLXEmbedder`), `ModelManager` slots keyed `org/name` (chat) or `org/name#embedding`, | |
| 75 | +`POST /v1/embeddings` in `EmbeddingsRoute.swift`; sentence-transformers CLS pooling mapped to | |
| 76 | +`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). Next: #43 compatibility suite. | |
| 73 | 77 | |
| 74 | 78 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 75 | 79 | |
| @@ -160,7 +164,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | ||
| 160 | 164 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 161 | 165 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 162 | 166 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 163 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #41): Linux 136, Mac 156 (incl. `ConstrainedSmokeTests`, `ChatSmokeTests`: real | |
| 167 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #42): Linux 144, Mac 167 (incl. `EmbeddingSmokeTests` against | |
| 168 | +sentence-transformers reference cosines, which need the two models pulled; `ConstrainedSmokeTests`, `ChatSmokeTests`: real | |
| 164 | 169 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 165 | 170 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 166 | 171 | |
| @@ -8,7 +8,7 @@ and reasoning, structured output, function calling, embeddings; "decision models | |||
| 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37, constrained | 10 | model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35, its streaming #36, reasoning over the API #37, constrained |
| 11 | -decoding #38, structured output #39, function calling #40/#41 (see Architecture). Decided by the user (#31): the | 11 | +decoding #38, structured output #39, function calling #40/#41, embeddings #42 (see Architecture). Decided by the user (#31): the |
| 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by | 14 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -69,7 +69,11 @@ by a `GrammarProcessor` (LogitProcessor on mlx-swift-lm's XGrammar bridge, inact | |||
| 69 | `response_format` → `.jsonSchema` (strict + unenforced keyword → 400); tools/tool_choice in | 69 | `response_format` → `.jsonSchema` (strict + unenforced keyword → 400); tools/tool_choice in |
| 70 | `Chat/ToolsAndFormats.swift`; forced tool calls via structural tags for the `<tool_call>` JSON syntax | 70 | `Chat/ToolsAndFormats.swift`; forced tool calls via structural tags for the `<tool_call>` JSON syntax |
| 71 | only (others → 400); forced calls are single unless `parallel_tool_calls: true`. Sessions without | 71 | only (others → 400); forced calls are single unless `parallel_tool_calls: true`. Sessions without |
| 72 | -tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Next: embeddings (#42). | 72 | +tools switch a `.json` model to the `.gptOSS` parser (no bare-JSON hold-back). Embeddings (#42): |
| 73 | +`InferenceEngine.embed`, `EngineRegistry` factories take a `ModelKind` (`mlx` → `MLXEngine` or | ||
| 74 | +`MLXEmbedder`), `ModelManager` slots keyed `org/name` (chat) or `org/name#embedding`, | ||
| 75 | +`POST /v1/embeddings` in `EmbeddingsRoute.swift`; sentence-transformers CLS pooling mapped to | ||
| 76 | +`.first` (MLXEmbedders' `.cls` = BERT pooler output, wrong). Next: #43 compatibility suite. | ||
| 73 | 77 | ||
| 74 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 78 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 75 | 79 | ||
| @@ -160,7 +164,8 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | |||
| 160 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). | 164 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 161 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped | 165 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 162 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). | 166 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 163 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #41): Linux 136, Mac 156 (incl. `ConstrainedSmokeTests`, `ChatSmokeTests`: real | 167 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #42): Linux 144, Mac 167 (incl. `EmbeddingSmokeTests` against |
| 168 | +sentence-transformers reference cosines, which need the two models pulled; `ConstrainedSmokeTests`, `ChatSmokeTests`: real | ||
| 164 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | 169 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 165 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 170 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 166 | 171 | ||
modified
.quality/history.jsonl +1 -0 | @@ -13,3 +13,4 @@ | ||
| 13 | 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} |
| 14 | 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} |
| 15 | 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} |
| 16 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "53d6eb7", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 208, "complex": 408, "cyclo": 487, "fields": 983, "funcs": 478, "lcom": 99, "lines": 8756, "loc": 6933}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 16, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:38:25Z"} | |
| @@ -13,3 +13,4 @@ | |||
| 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} | 13 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "7cdd37d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 171, "complex": 338, "cyclo": 401, "fields": 770, "funcs": 390, "lcom": 77, "lines": 7106, "loc": 5580}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 13, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:55:33Z"} |
| 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} | 14 | {"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 1 (max 0)", "warning-level issues: 3 (max 0)", "code smells: 2 (max 0)"], "commit": "1f0e95f", "counts": {"error": 1, "warning": 3}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 191, "complex": 406, "cyclo": 464, "fields": 891, "funcs": 440, "lcom": 84, "lines": 8086, "loc": 6388}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 14, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:25:34Z"} |
| 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} | 15 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "1f0e95f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 191, "complex": 377, "cyclo": 457, "fields": 891, "funcs": 442, "lcom": 84, "lines": 8087, "loc": 6384}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 15, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:26:02Z"} |
| 16 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "53d6eb7", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 208, "complex": 408, "cyclo": 487, "fields": 983, "funcs": 478, "lcom": 99, "lines": 8756, "loc": 6933}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 16, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T13:38:25Z"} | ||
added
.quality/report-20261125T133825Z.md +73 -0 | new file mode 100644 | ||
| @@ -0,0 +1,73 @@ | ||
| 1 | +# Quality report — 2026-11-25T13:38:25Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` | |
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | |
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | |
| 7 | +- **Run**: #16 (previous: 2026-11-25T13:26:02Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +_none_ | |
| 12 | + | |
| 13 | +### Top rules | |
| 14 | + | |
| 15 | +_none_ | |
| 16 | + | |
| 17 | +### Most affected files | |
| 18 | + | |
| 19 | +_none_ | |
| 20 | + | |
| 21 | +## Code smells (`qlty smells`) | |
| 22 | + | |
| 23 | +Total: **0** (vs previous: ±0) | |
| 24 | + | |
| 25 | +_none_ | |
| 26 | + | |
| 27 | +## Metrics (`qlty metrics`) | |
| 28 | + | |
| 29 | +| metric | total | vs previous | | |
| 30 | +|---|---|---| | |
| 31 | +| funcs | 478 | +36 | | |
| 32 | +| classes | 208 | +17 | | |
| 33 | +| fields | 983 | +92 | | |
| 34 | +| cyclo | 487 | +30 | | |
| 35 | +| complex | 408 | +31 | | |
| 36 | +| lcom | 99 | +15 | | |
| 37 | +| lines | 8756 | +669 | | |
| 38 | +| loc | 6933 | +549 | | |
| 39 | + | |
| 40 | +### Most complex files | |
| 41 | + | |
| 42 | +| file | complex | cyclo | loc | | |
| 43 | +|---|---|---|---| | |
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | |
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | |
| 46 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | |
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | |
| 51 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | |
| 52 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 53 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 55 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | |
| 56 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | |
| 57 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 58 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | |
| 59 | + | |
| 60 | +## Trend | |
| 61 | + | |
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 63 | +|---|---|---|---|---|---|---| | |
| 64 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 65 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 66 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 67 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 68 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| 69 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | |
| 70 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | |
| 71 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | |
| 72 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# Quality report — 2026-11-25T13:38:25Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` | ||
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | ||
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | ||
| 7 | +- **Run**: #16 (previous: 2026-11-25T13:26:02Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +_none_ | ||
| 12 | + | ||
| 13 | +### Top rules | ||
| 14 | + | ||
| 15 | +_none_ | ||
| 16 | + | ||
| 17 | +### Most affected files | ||
| 18 | + | ||
| 19 | +_none_ | ||
| 20 | + | ||
| 21 | +## Code smells (`qlty smells`) | ||
| 22 | + | ||
| 23 | +Total: **0** (vs previous: ±0) | ||
| 24 | + | ||
| 25 | +_none_ | ||
| 26 | + | ||
| 27 | +## Metrics (`qlty metrics`) | ||
| 28 | + | ||
| 29 | +| metric | total | vs previous | | ||
| 30 | +|---|---|---| | ||
| 31 | +| funcs | 478 | +36 | | ||
| 32 | +| classes | 208 | +17 | | ||
| 33 | +| fields | 983 | +92 | | ||
| 34 | +| cyclo | 487 | +30 | | ||
| 35 | +| complex | 408 | +31 | | ||
| 36 | +| lcom | 99 | +15 | | ||
| 37 | +| lines | 8756 | +669 | | ||
| 38 | +| loc | 6933 | +549 | | ||
| 39 | + | ||
| 40 | +### Most complex files | ||
| 41 | + | ||
| 42 | +| file | complex | cyclo | loc | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 232 | | ||
| 46 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 133 | | ||
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 50 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | ||
| 51 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | ||
| 52 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 53 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 55 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | ||
| 56 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | ||
| 57 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 58 | +| Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | ||
| 59 | + | ||
| 60 | +## Trend | ||
| 61 | + | ||
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 63 | +|---|---|---|---|---|---|---| | ||
| 64 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 65 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 66 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 67 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 68 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
| 69 | +| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS | | ||
| 70 | +| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | ||
| 71 | +| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | ||
| 72 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
modified
.quality/report-latest.md +16 -19 | @@ -1,17 +1,14 @@ | ||
| 1 | -# Quality report — 2026-11-25T13:26:02Z | |
| 1 | +# Quality report — 2026-11-25T13:38:25Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` | |
| 5 | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #15 (previous: 2026-11-25T13:25:34Z) | |
| 7 | +- **Run**: #16 (previous: 2026-11-25T13:26:02Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| 11 | -| level | count | vs previous | | |
| 12 | -|---|---|---| | |
| 13 | -| error | 0 | -1 | | |
| 14 | -| warning | 0 | -3 | | |
| 11 | +_none_ | |
| 15 | 12 | |
| 16 | 13 | ### Top rules |
| 17 | 14 | |
| @@ -23,7 +20,7 @@ _none_ | ||
| 23 | 20 | |
| 24 | 21 | ## Code smells (`qlty smells`) |
| 25 | 22 | |
| 26 | -Total: **0** (vs previous: -2) | |
| 23 | +Total: **0** (vs previous: ±0) | |
| 27 | 24 | |
| 28 | 25 | _none_ |
| 29 | 26 | |
| @@ -31,14 +28,14 @@ _none_ | ||
| 31 | 28 | |
| 32 | 29 | | metric | total | vs previous | |
| 33 | 30 | |---|---|---| |
| 34 | -| funcs | 442 | +2 | | |
| 35 | -| classes | 191 | ±0 | | |
| 36 | -| fields | 891 | ±0 | | |
| 37 | -| cyclo | 457 | -7 | | |
| 38 | -| complex | 377 | -29 | | |
| 39 | -| lcom | 84 | ±0 | | |
| 40 | -| lines | 8087 | +1 | | |
| 41 | -| loc | 6384 | -4 | | |
| 31 | +| funcs | 478 | +36 | | |
| 32 | +| classes | 208 | +17 | | |
| 33 | +| fields | 983 | +92 | | |
| 34 | +| cyclo | 487 | +30 | | |
| 35 | +| complex | 408 | +31 | | |
| 36 | +| lcom | 99 | +15 | | |
| 37 | +| lines | 8756 | +669 | | |
| 38 | +| loc | 6933 | +549 | | |
| 42 | 39 | |
| 43 | 40 | ### Most complex files |
| 44 | 41 | |
| @@ -53,18 +50,17 @@ _none_ | ||
| 53 | 50 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | |
| 54 | 51 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | |
| 55 | 52 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 53 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 56 | 54 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 57 | 55 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | |
| 58 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | |
| 56 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | | |
| 59 | 57 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 60 | 58 | | Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | |
| 61 | -| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 62 | 59 | |
| 63 | 60 | ## Trend |
| 64 | 61 | |
| 65 | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 66 | 63 | |---|---|---|---|---|---|---| |
| 67 | -| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 68 | 64 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | |
| 69 | 65 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| 70 | 66 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| @@ -74,3 +70,4 @@ _none_ | ||
| 74 | 70 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| 75 | 71 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | |
| 76 | 72 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | |
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| @@ -1,17 +1,14 @@ | |||
| 1 | -# Quality report — 2026-11-25T13:26:02Z | 1 | +# Quality report — 2026-11-25T13:38:25Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `1f0e95f` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `53d6eb7` on `feature/v0.2-openai-server` |
| 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #15 (previous: 2026-11-25T13:25:34Z) | 7 | +- **Run**: #16 (previous: 2026-11-25T13:26:02Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| 11 | -| level | count | vs previous | | 11 | +_none_ |
| 12 | -|---|---|---| | ||
| 13 | -| error | 0 | -1 | | ||
| 14 | -| warning | 0 | -3 | | ||
| 15 | 12 | ||
| 16 | ### Top rules | 13 | ### Top rules |
| 17 | 14 | ||
| @@ -23,7 +20,7 @@ _none_ | |||
| 23 | 20 | ||
| 24 | ## Code smells (`qlty smells`) | 21 | ## Code smells (`qlty smells`) |
| 25 | 22 | ||
| 26 | -Total: **0** (vs previous: -2) | 23 | +Total: **0** (vs previous: ±0) |
| 27 | 24 | ||
| 28 | _none_ | 25 | _none_ |
| 29 | 26 | ||
| @@ -31,14 +28,14 @@ _none_ | |||
| 31 | 28 | ||
| 32 | | metric | total | vs previous | | 29 | | metric | total | vs previous | |
| 33 | |---|---|---| | 30 | |---|---|---| |
| 34 | -| funcs | 442 | +2 | | 31 | +| funcs | 478 | +36 | |
| 35 | -| classes | 191 | ±0 | | 32 | +| classes | 208 | +17 | |
| 36 | -| fields | 891 | ±0 | | 33 | +| fields | 983 | +92 | |
| 37 | -| cyclo | 457 | -7 | | 34 | +| cyclo | 487 | +30 | |
| 38 | -| complex | 377 | -29 | | 35 | +| complex | 408 | +31 | |
| 39 | -| lcom | 84 | ±0 | | 36 | +| lcom | 99 | +15 | |
| 40 | -| lines | 8087 | +1 | | 37 | +| lines | 8756 | +669 | |
| 41 | -| loc | 6384 | -4 | | 38 | +| loc | 6933 | +549 | |
| 42 | 39 | ||
| 43 | ### Most complex files | 40 | ### Most complex files |
| 44 | 41 | ||
| @@ -53,18 +50,17 @@ _none_ | |||
| 53 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | | 50 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 14 | 22 | 268 | |
| 54 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | | 51 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 14 | 25 | 146 | |
| 55 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 52 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 53 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 56 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | 54 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | |
| 57 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | | 55 | | Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 11 | 12 | 137 | |
| 58 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | 56 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 256 | |
| 59 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | 57 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 60 | | Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | | 58 | | Sources/RazorbillCore/Engine/OutputConstraint.swift | 10 | 8 | 64 | |
| 61 | -| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 62 | 59 | ||
| 63 | ## Trend | 60 | ## Trend |
| 64 | 61 | ||
| 65 | | run | timestamp | error | warning | smells | complex | gate | | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 66 | |---|---|---|---|---|---|---| | 63 | |---|---|---|---|---|---|---| |
| 67 | -| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 68 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | 64 | | 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | |
| 69 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | 65 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| 70 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | 66 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| @@ -74,3 +70,4 @@ _none_ | |||
| 74 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | | 70 | | 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS | |
| 75 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | | 71 | | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL | |
| 76 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | 72 | | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | |
| 73 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
modified
.tickets/issues/0042-embeddings-post-v1-embeddings-with-mlxembedders.yaml +35 -9 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 42 |
| 3 | 3 | title: "Embeddings: POST /v1/embeddings with MLXEmbedders" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T14:00:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::embeddings" |
| @@ -37,50 +37,76 @@ body: | | ||
| 37 | 37 | tasks: |
| 38 | 38 | - id: 1 |
| 39 | 39 | title: "Embedding engine protocol in Core + FakeEmbedder for tests" |
| 40 | - state: open | |
| 40 | + state: closed | |
| 41 | 41 | priority: high |
| 42 | 42 | author: |
| 43 | 43 | name: k33g |
| 44 | 44 | email: ph.charriere@gmail.com |
| 45 | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 47 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 46 | 48 | - id: 2 |
| 47 | 49 | title: "MLX implementation with EmbedderModelContainer and pooling" |
| 48 | - state: open | |
| 50 | + state: closed | |
| 49 | 51 | priority: high |
| 50 | 52 | author: |
| 51 | 53 | name: k33g |
| 52 | 54 | email: ph.charriere@gmail.com |
| 53 | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 57 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 54 | 58 | - id: 3 |
| 55 | 59 | title: "Endpoint: input forms, encoding_format, usage" |
| 56 | - state: open | |
| 60 | + state: closed | |
| 57 | 61 | priority: high |
| 58 | 62 | author: |
| 59 | 63 | name: k33g |
| 60 | 64 | email: ph.charriere@gmail.com |
| 61 | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 67 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 62 | 68 | - id: 4 |
| 63 | 69 | title: "dimensions (Matryoshka truncation + renormalisation)" |
| 64 | - state: open | |
| 70 | + state: closed | |
| 65 | 71 | priority: medium |
| 66 | 72 | author: |
| 67 | 73 | name: k33g |
| 68 | 74 | email: ph.charriere@gmail.com |
| 69 | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 76 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 77 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 70 | 78 | - id: 5 |
| 71 | 79 | title: "Batching and max length handling" |
| 72 | - state: open | |
| 80 | + state: closed | |
| 73 | 81 | priority: medium |
| 74 | 82 | author: |
| 75 | 83 | name: k33g |
| 76 | 84 | email: ph.charriere@gmail.com |
| 77 | 85 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 87 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 78 | 88 | - id: 6 |
| 79 | 89 | title: "Reference-value test against a Python implementation" |
| 80 | - state: open | |
| 90 | + state: closed | |
| 81 | 91 | priority: high |
| 82 | 92 | author: |
| 83 | 93 | name: k33g |
| 84 | 94 | email: ph.charriere@gmail.com |
| 85 | 95 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | -comments: [] | |
| 96 | + updatedAt: 2026-11-25T14:00:00.000Z | |
| 97 | + closedAt: 2026-11-25T14:00:00.000Z | |
| 98 | +comments: | |
| 99 | + - id: 1 | |
| 100 | + author: | |
| 101 | + name: k33g | |
| 102 | + email: ph.charriere@gmail.com | |
| 103 | + createdAt: 2026-11-25T14:00:00.000Z | |
| 104 | + body: | | |
| 105 | + Done: `POST /v1/embeddings` with MLXEmbedders (`MLXEmbedder` engine; the engine registry now builds an engine per model kind, and chat and embedding loads of one repository are separate slots). | |
| 106 | + - Input: a string or a list of strings (≤ 2048, none empty); token arrays give a 400 for now. `encoding_format` float / base64 (little-endian float32). `dimensions`: first N values, L2-renormalised; larger than the model's size gives a 400. Deviation: allowed for any model (meaningful only for Matryoshka models), no per-model capability list. Response and usage in OpenAI's shape. | |
| 107 | + - Batches of 32 inputs per forward pass, right-padded with an attention mask; an input longer than `max_position_embeddings` gives a 400 naming it (no `truncate` option yet). | |
| 108 | + - Pooling from `1_Pooling/config.json`, except that sentence-transformers' CLS mode is mapped to the first token's hidden state: MLXEmbedders' `.cls` takes BERT's pooler output, which put bge-small-en-v1.5 up to 0.08 off the reference. Vectors are always normalised. Not done: pooling override and instruction prefixes in the server config (clients prepend `search_query:` etc. themselves). | |
| 109 | + - A declared chat model on /v1/embeddings, or an embedding model on /v1/chat/completions, gives a 400 `param: model`; undeclared ids take the endpoint's kind. `rzb models pull` works for embedding repos (used to fetch the two reference models). | |
| 110 | + Reference test (acceptance): cosines of 4 sentences match sentence-transformers 5 within 1e-3 for all-MiniLM-L6-v2 (mean pooling) and bge-small-en-v1.5 (CLS). The openai SDK `embeddings.create` works against the server; LangChain is on the user's checklist. | |
| 111 | + Tests: Linux 144, Mac 167; gate PASS. | |
| 112 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 42 | 2 | id: 42 |
| 3 | title: "Embeddings: POST /v1/embeddings with MLXEmbedders" | 3 | title: "Embeddings: POST /v1/embeddings with MLXEmbedders" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T14:00:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::embeddings" | 12 | - "area::embeddings" |
| @@ -37,50 +37,76 @@ body: | | |||
| 37 | tasks: | 37 | tasks: |
| 38 | - id: 1 | 38 | - id: 1 |
| 39 | title: "Embedding engine protocol in Core + FakeEmbedder for tests" | 39 | title: "Embedding engine protocol in Core + FakeEmbedder for tests" |
| 40 | - state: open | 40 | + state: closed |
| 41 | priority: high | 41 | priority: high |
| 42 | author: | 42 | author: |
| 43 | name: k33g | 43 | name: k33g |
| 44 | email: ph.charriere@gmail.com | 44 | email: ph.charriere@gmail.com |
| 45 | createdAt: 2026-11-24T21:17:08.000Z | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T14:00:00.000Z | ||
| 47 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 46 | - id: 2 | 48 | - id: 2 |
| 47 | title: "MLX implementation with EmbedderModelContainer and pooling" | 49 | title: "MLX implementation with EmbedderModelContainer and pooling" |
| 48 | - state: open | 50 | + state: closed |
| 49 | priority: high | 51 | priority: high |
| 50 | author: | 52 | author: |
| 51 | name: k33g | 53 | name: k33g |
| 52 | email: ph.charriere@gmail.com | 54 | email: ph.charriere@gmail.com |
| 53 | createdAt: 2026-11-24T21:17:08.000Z | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T14:00:00.000Z | ||
| 57 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 54 | - id: 3 | 58 | - id: 3 |
| 55 | title: "Endpoint: input forms, encoding_format, usage" | 59 | title: "Endpoint: input forms, encoding_format, usage" |
| 56 | - state: open | 60 | + state: closed |
| 57 | priority: high | 61 | priority: high |
| 58 | author: | 62 | author: |
| 59 | name: k33g | 63 | name: k33g |
| 60 | email: ph.charriere@gmail.com | 64 | email: ph.charriere@gmail.com |
| 61 | createdAt: 2026-11-24T21:17:08.000Z | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T14:00:00.000Z | ||
| 67 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 62 | - id: 4 | 68 | - id: 4 |
| 63 | title: "dimensions (Matryoshka truncation + renormalisation)" | 69 | title: "dimensions (Matryoshka truncation + renormalisation)" |
| 64 | - state: open | 70 | + state: closed |
| 65 | priority: medium | 71 | priority: medium |
| 66 | author: | 72 | author: |
| 67 | name: k33g | 73 | name: k33g |
| 68 | email: ph.charriere@gmail.com | 74 | email: ph.charriere@gmail.com |
| 69 | createdAt: 2026-11-24T21:17:08.000Z | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 76 | + updatedAt: 2026-11-25T14:00:00.000Z | ||
| 77 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 70 | - id: 5 | 78 | - id: 5 |
| 71 | title: "Batching and max length handling" | 79 | title: "Batching and max length handling" |
| 72 | - state: open | 80 | + state: closed |
| 73 | priority: medium | 81 | priority: medium |
| 74 | author: | 82 | author: |
| 75 | name: k33g | 83 | name: k33g |
| 76 | email: ph.charriere@gmail.com | 84 | email: ph.charriere@gmail.com |
| 77 | createdAt: 2026-11-24T21:17:08.000Z | 85 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | + updatedAt: 2026-11-25T14:00:00.000Z | ||
| 87 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 78 | - id: 6 | 88 | - id: 6 |
| 79 | title: "Reference-value test against a Python implementation" | 89 | title: "Reference-value test against a Python implementation" |
| 80 | - state: open | 90 | + state: closed |
| 81 | priority: high | 91 | priority: high |
| 82 | author: | 92 | author: |
| 83 | name: k33g | 93 | name: k33g |
| 84 | email: ph.charriere@gmail.com | 94 | email: ph.charriere@gmail.com |
| 85 | createdAt: 2026-11-24T21:17:08.000Z | 95 | createdAt: 2026-11-24T21:17:08.000Z |
| 86 | -comments: [] | 96 | + updatedAt: 2026-11-25T14:00:00.000Z |
| 97 | + closedAt: 2026-11-25T14:00:00.000Z | ||
| 98 | +comments: | ||
| 99 | + - id: 1 | ||
| 100 | + author: | ||
| 101 | + name: k33g | ||
| 102 | + email: ph.charriere@gmail.com | ||
| 103 | + createdAt: 2026-11-25T14:00:00.000Z | ||
| 104 | + body: | | ||
| 105 | + Done: `POST /v1/embeddings` with MLXEmbedders (`MLXEmbedder` engine; the engine registry now builds an engine per model kind, and chat and embedding loads of one repository are separate slots). | ||
| 106 | + - Input: a string or a list of strings (≤ 2048, none empty); token arrays give a 400 for now. `encoding_format` float / base64 (little-endian float32). `dimensions`: first N values, L2-renormalised; larger than the model's size gives a 400. Deviation: allowed for any model (meaningful only for Matryoshka models), no per-model capability list. Response and usage in OpenAI's shape. | ||
| 107 | + - Batches of 32 inputs per forward pass, right-padded with an attention mask; an input longer than `max_position_embeddings` gives a 400 naming it (no `truncate` option yet). | ||
| 108 | + - Pooling from `1_Pooling/config.json`, except that sentence-transformers' CLS mode is mapped to the first token's hidden state: MLXEmbedders' `.cls` takes BERT's pooler output, which put bge-small-en-v1.5 up to 0.08 off the reference. Vectors are always normalised. Not done: pooling override and instruction prefixes in the server config (clients prepend `search_query:` etc. themselves). | ||
| 109 | + - A declared chat model on /v1/embeddings, or an embedding model on /v1/chat/completions, gives a 400 `param: model`; undeclared ids take the endpoint's kind. `rzb models pull` works for embedding repos (used to fetch the two reference models). | ||
| 110 | + Reference test (acceptance): cosines of 4 sentences match sentence-transformers 5 within 1e-3 for all-MiniLM-L6-v2 (mean pooling) and bge-small-en-v1.5 (CLS). The openai SDK `embeddings.create` works against the server; LangChain is on the user's checklist. | ||
| 111 | + Tests: Linux 144, Mac 167; gate PASS. | ||
| 112 | + | ||
modified
Package.swift +2 -0 | @@ -52,6 +52,8 @@ let package = Package( | ||
| 52 | 52 | macOnly("MLXHuggingFace", "mlx-swift-lm"), |
| 53 | 53 | // Constrained decoding (XGrammar, C++): structured output and forced tool calls. |
| 54 | 54 | macOnly("MLXGuidedGeneration", "mlx-swift-lm"), |
| 55 | + // Embedding models (BERT, Qwen3-Embedding…) for /v1/embeddings. | |
| 56 | + macOnly("MLXEmbedders", "mlx-swift-lm"), | |
| 55 | 57 | macOnly("MLX", "mlx-swift"), |
| 56 | 58 | macOnly("HuggingFace", "swift-huggingface"), |
| 57 | 59 | macOnly("Tokenizers", "swift-transformers"), |
| @@ -52,6 +52,8 @@ let package = Package( | |||
| 52 | macOnly("MLXHuggingFace", "mlx-swift-lm"), | 52 | macOnly("MLXHuggingFace", "mlx-swift-lm"), |
| 53 | // Constrained decoding (XGrammar, C++): structured output and forced tool calls. | 53 | // Constrained decoding (XGrammar, C++): structured output and forced tool calls. |
| 54 | macOnly("MLXGuidedGeneration", "mlx-swift-lm"), | 54 | macOnly("MLXGuidedGeneration", "mlx-swift-lm"), |
| 55 | + // Embedding models (BERT, Qwen3-Embedding…) for /v1/embeddings. | ||
| 56 | + macOnly("MLXEmbedders", "mlx-swift-lm"), | ||
| 55 | macOnly("MLX", "mlx-swift"), | 57 | macOnly("MLX", "mlx-swift"), |
| 56 | macOnly("HuggingFace", "swift-huggingface"), | 58 | macOnly("HuggingFace", "swift-huggingface"), |
| 57 | macOnly("Tokenizers", "swift-transformers"), | 59 | macOnly("Tokenizers", "swift-transformers"), |
modified
Sources/RazorbillCLI/CLIEnvironment.swift +1 -1 | @@ -8,7 +8,7 @@ import RazorbillServer | ||
| 8 | 8 | /// |
| 9 | 9 | /// ```swift |
| 10 | 10 | /// var engines = EngineRegistry() |
| 11 | -/// engines.register("fake") { FakeEngine() } | |
| 11 | +/// engines.register("fake") { _ in FakeEngine() } | |
| 12 | 12 | /// await CLIEnvironment.$current.withValue(.standard(engines: engines)) { |
| 13 | 13 | /// await Rzb.main() |
| 14 | 14 | /// } |
| @@ -8,7 +8,7 @@ import RazorbillServer | |||
| 8 | /// | 8 | /// |
| 9 | /// ```swift | 9 | /// ```swift |
| 10 | /// var engines = EngineRegistry() | 10 | /// var engines = EngineRegistry() |
| 11 | -/// engines.register("fake") { FakeEngine() } | 11 | +/// engines.register("fake") { _ in FakeEngine() } |
| 12 | /// await CLIEnvironment.$current.withValue(.standard(engines: engines)) { | 12 | /// await CLIEnvironment.$current.withValue(.standard(engines: engines)) { |
| 13 | /// await Rzb.main() | 13 | /// await Rzb.main() |
| 14 | /// } | 14 | /// } |
added
Sources/RazorbillCore/Engine/Embeddings.swift +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// The vectors of one embeddings request, in input order, L2-normalised. | |
| 4 | +public struct Embeddings: Sendable, Equatable { | |
| 5 | + public var vectors: [[Float]] | |
| 6 | + /// Tokens read across all inputs. | |
| 7 | + public var promptTokens: Int | |
| 8 | + | |
| 9 | + public init(vectors: [[Float]], promptTokens: Int) { | |
| 10 | + self.vectors = vectors | |
| 11 | + self.promptTokens = promptTokens | |
| 12 | + } | |
| 13 | + | |
| 14 | + /// Keeps the first `dimensions` values of each vector and L2-normalises them again | |
| 15 | + /// (Matryoshka truncation: meaningful for models trained for it, such as Qwen3-Embedding or | |
| 16 | + /// nomic-embed v1.5). | |
| 17 | + public func truncated(to dimensions: Int) -> Embeddings { | |
| 18 | + Embeddings( | |
| 19 | + vectors: vectors.map { Self.normalised(Array($0.prefix(dimensions))) }, | |
| 20 | + promptTokens: promptTokens) | |
| 21 | + } | |
| 22 | + | |
| 23 | + public static func normalised(_ vector: [Float]) -> [Float] { | |
| 24 | + let norm = vector.reduce(0) { $0 + $1 * $1 }.squareRoot() | |
| 25 | + return norm > 0 ? vector.map { $0 / norm } : vector | |
| 26 | + } | |
| 27 | + | |
| 28 | + /// The vector as little-endian float32 bytes in base64 (`encoding_format: base64`). | |
| 29 | + public static func base64(_ vector: [Float]) -> String { | |
| 30 | + var data = Data(capacity: vector.count * 4) | |
| 31 | + for value in vector { | |
| 32 | + withUnsafeBytes(of: value.bitPattern.littleEndian) { data.append(contentsOf: $0) } | |
| 33 | + } | |
| 34 | + return data.base64EncodedString() | |
| 35 | + } | |
| 36 | +} | |
| 37 | + | |
| 38 | +/// The model was asked for something its kind cannot do (chat from an embedding model, or | |
| 39 | +/// embeddings from a chat model): a 400 on `model`. | |
| 40 | +public struct WrongModelKind: RequestSettingError, Equatable { | |
| 41 | + public let model: String | |
| 42 | + public let kind: ModelKind | |
| 43 | + public let wanted: ModelKind | |
| 44 | + | |
| 45 | + public init(model: String, kind: ModelKind, wanted: ModelKind) { | |
| 46 | + self.model = model | |
| 47 | + self.kind = kind | |
| 48 | + self.wanted = wanted | |
| 49 | + } | |
| 50 | + | |
| 51 | + public var parameter: String { "model" } | |
| 52 | + public var description: String { | |
| 53 | + "'\(model)' is a \(kind.rawValue) model; this endpoint needs a \(wanted.rawValue) model" | |
| 54 | + } | |
| 55 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// The vectors of one embeddings request, in input order, L2-normalised. | ||
| 4 | +public struct Embeddings: Sendable, Equatable { | ||
| 5 | + public var vectors: [[Float]] | ||
| 6 | + /// Tokens read across all inputs. | ||
| 7 | + public var promptTokens: Int | ||
| 8 | + | ||
| 9 | + public init(vectors: [[Float]], promptTokens: Int) { | ||
| 10 | + self.vectors = vectors | ||
| 11 | + self.promptTokens = promptTokens | ||
| 12 | + } | ||
| 13 | + | ||
| 14 | + /// Keeps the first `dimensions` values of each vector and L2-normalises them again | ||
| 15 | + /// (Matryoshka truncation: meaningful for models trained for it, such as Qwen3-Embedding or | ||
| 16 | + /// nomic-embed v1.5). | ||
| 17 | + public func truncated(to dimensions: Int) -> Embeddings { | ||
| 18 | + Embeddings( | ||
| 19 | + vectors: vectors.map { Self.normalised(Array($0.prefix(dimensions))) }, | ||
| 20 | + promptTokens: promptTokens) | ||
| 21 | + } | ||
| 22 | + | ||
| 23 | + public static func normalised(_ vector: [Float]) -> [Float] { | ||
| 24 | + let norm = vector.reduce(0) { $0 + $1 * $1 }.squareRoot() | ||
| 25 | + return norm > 0 ? vector.map { $0 / norm } : vector | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /// The vector as little-endian float32 bytes in base64 (`encoding_format: base64`). | ||
| 29 | + public static func base64(_ vector: [Float]) -> String { | ||
| 30 | + var data = Data(capacity: vector.count * 4) | ||
| 31 | + for value in vector { | ||
| 32 | + withUnsafeBytes(of: value.bitPattern.littleEndian) { data.append(contentsOf: $0) } | ||
| 33 | + } | ||
| 34 | + return data.base64EncodedString() | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// The model was asked for something its kind cannot do (chat from an embedding model, or | ||
| 39 | +/// embeddings from a chat model): a 400 on `model`. | ||
| 40 | +public struct WrongModelKind: RequestSettingError, Equatable { | ||
| 41 | + public let model: String | ||
| 42 | + public let kind: ModelKind | ||
| 43 | + public let wanted: ModelKind | ||
| 44 | + | ||
| 45 | + public init(model: String, kind: ModelKind, wanted: ModelKind) { | ||
| 46 | + self.model = model | ||
| 47 | + self.kind = kind | ||
| 48 | + self.wanted = wanted | ||
| 49 | + } | ||
| 50 | + | ||
| 51 | + public var parameter: String { "model" } | ||
| 52 | + public var description: String { | ||
| 53 | + "'\(model)' is a \(kind.rawValue) model; this endpoint needs a \(wanted.rawValue) model" | ||
| 54 | + } | ||
| 55 | +} | ||
modified
Sources/RazorbillCore/Engine/EngineRegistry.swift +8 -6 | @@ -4,11 +4,12 @@ | ||
| 4 | 4 | /// |
| 5 | 5 | /// ```swift |
| 6 | 6 | /// var engines = EngineRegistry() |
| 7 | -/// engines.register("fake") { FakeEngine() } | |
| 8 | -/// let engine = try engines.make("fake") | |
| 7 | +/// engines.register("fake") { _ in FakeEngine() } | |
| 8 | +/// let engine = try engines.make("fake", kind: .chat) | |
| 9 | 9 | /// ``` |
| 10 | 10 | public struct EngineRegistry: Sendable { |
| 11 | - public typealias Factory = @Sendable () -> any InferenceEngine | |
| 11 | + /// Creates an engine for a model of this kind (chat or embedding). | |
| 12 | + public typealias Factory = @Sendable (ModelKind) -> any InferenceEngine | |
| 12 | 13 | |
| 13 | 14 | /// The requested engine is not in this build. |
| 14 | 15 | public struct UnknownEngine: Error, Equatable, CustomStringConvertible { |
| @@ -41,11 +42,12 @@ public struct EngineRegistry: Sendable { | ||
| 41 | 42 | |
| 42 | 43 | public var names: [String] { factories.keys.sorted() } |
| 43 | 44 | |
| 44 | - /// Creates the engine called `name`, or the default one when `name` is `nil`. | |
| 45 | - public func make(_ name: String? = nil) throws -> any InferenceEngine { | |
| 45 | + /// Creates the engine called `name`, or the default one when `name` is `nil`, for a model of | |
| 46 | + /// this kind. | |
| 47 | + public func make(_ name: String? = nil, kind: ModelKind = .chat) throws -> any InferenceEngine { | |
| 46 | 48 | guard let wanted = name ?? defaultName, let factory = factories[wanted] else { |
| 47 | 49 | throw UnknownEngine(name: name ?? "(none)", available: names) |
| 48 | 50 | } |
| 49 | - return factory() | |
| 51 | + return factory(kind) | |
| 50 | 52 | } |
| 51 | 53 | } |
| @@ -4,11 +4,12 @@ | |||
| 4 | /// | 4 | /// |
| 5 | /// ```swift | 5 | /// ```swift |
| 6 | /// var engines = EngineRegistry() | 6 | /// var engines = EngineRegistry() |
| 7 | -/// engines.register("fake") { FakeEngine() } | 7 | +/// engines.register("fake") { _ in FakeEngine() } |
| 8 | -/// let engine = try engines.make("fake") | 8 | +/// let engine = try engines.make("fake", kind: .chat) |
| 9 | /// ``` | 9 | /// ``` |
| 10 | public struct EngineRegistry: Sendable { | 10 | public struct EngineRegistry: Sendable { |
| 11 | - public typealias Factory = @Sendable () -> any InferenceEngine | 11 | + /// Creates an engine for a model of this kind (chat or embedding). |
| 12 | + public typealias Factory = @Sendable (ModelKind) -> any InferenceEngine | ||
| 12 | 13 | ||
| 13 | /// The requested engine is not in this build. | 14 | /// The requested engine is not in this build. |
| 14 | public struct UnknownEngine: Error, Equatable, CustomStringConvertible { | 15 | public struct UnknownEngine: Error, Equatable, CustomStringConvertible { |
| @@ -41,11 +42,12 @@ public struct EngineRegistry: Sendable { | |||
| 41 | 42 | ||
| 42 | public var names: [String] { factories.keys.sorted() } | 43 | public var names: [String] { factories.keys.sorted() } |
| 43 | 44 | ||
| 44 | - /// Creates the engine called `name`, or the default one when `name` is `nil`. | 45 | + /// Creates the engine called `name`, or the default one when `name` is `nil`, for a model of |
| 45 | - public func make(_ name: String? = nil) throws -> any InferenceEngine { | 46 | + /// this kind. |
| 47 | + public func make(_ name: String? = nil, kind: ModelKind = .chat) throws -> any InferenceEngine { | ||
| 46 | guard let wanted = name ?? defaultName, let factory = factories[wanted] else { | 48 | guard let wanted = name ?? defaultName, let factory = factories[wanted] else { |
| 47 | throw UnknownEngine(name: name ?? "(none)", available: names) | 49 | throw UnknownEngine(name: name ?? "(none)", available: names) |
| 48 | } | 50 | } |
| 49 | - return factory() | 51 | + return factory(kind) |
| 50 | } | 52 | } |
| 51 | } | 53 | } |
modified
Sources/RazorbillCore/Engine/FakeEngine.swift +11 -0 | @@ -52,6 +52,17 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable { | ||
| 52 | 52 | lock.withLock { loaded.append(model) } |
| 53 | 53 | } |
| 54 | 54 | |
| 55 | + /// Deterministic 8-dimension vectors from the text's bytes; one token per word. | |
| 56 | + public func embed(_ texts: [String]) async throws -> Embeddings { | |
| 57 | + let vectors = texts.map { text -> [Float] in | |
| 58 | + var vector = [Float](repeating: 0, count: 8) | |
| 59 | + for (index, byte) in text.utf8.enumerated() { vector[index % 8] += Float(byte) } | |
| 60 | + return Embeddings.normalised(vector) | |
| 61 | + } | |
| 62 | + let tokens = texts.reduce(0) { $0 + $1.split(separator: " ").count } | |
| 63 | + return Embeddings(vectors: vectors, promptTokens: tokens) | |
| 64 | + } | |
| 65 | + | |
| 55 | 66 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 56 | 67 | lock.withLock { setups.append(setup) } |
| 57 | 68 | return Session(engine: self) |
| @@ -52,6 +52,17 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable { | |||
| 52 | lock.withLock { loaded.append(model) } | 52 | lock.withLock { loaded.append(model) } |
| 53 | } | 53 | } |
| 54 | 54 | ||
| 55 | + /// Deterministic 8-dimension vectors from the text's bytes; one token per word. | ||
| 56 | + public func embed(_ texts: [String]) async throws -> Embeddings { | ||
| 57 | + let vectors = texts.map { text -> [Float] in | ||
| 58 | + var vector = [Float](repeating: 0, count: 8) | ||
| 59 | + for (index, byte) in text.utf8.enumerated() { vector[index % 8] += Float(byte) } | ||
| 60 | + return Embeddings.normalised(vector) | ||
| 61 | + } | ||
| 62 | + let tokens = texts.reduce(0) { $0 + $1.split(separator: " ").count } | ||
| 63 | + return Embeddings(vectors: vectors, promptTokens: tokens) | ||
| 64 | + } | ||
| 65 | + | ||
| 55 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 66 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 56 | lock.withLock { setups.append(setup) } | 67 | lock.withLock { setups.append(setup) } |
| 57 | return Session(engine: self) | 68 | return Session(engine: self) |
modified
Sources/RazorbillCore/Engine/InferenceEngine.swift +8 -0 | @@ -65,11 +65,19 @@ public protocol InferenceEngine: Sendable { | ||
| 65 | 65 | |
| 66 | 66 | /// Frees the loaded model. The server calls it before dropping the engine. |
| 67 | 67 | func unload() async |
| 68 | + | |
| 69 | + /// Embeds `texts` with a loaded embedding model, one vector per text. | |
| 70 | + func embed(_ texts: [String]) async throws -> Embeddings | |
| 68 | 71 | } |
| 69 | 72 | |
| 70 | 73 | extension InferenceEngine { |
| 71 | 74 | /// Engines that hold nothing worth freeing early do nothing. |
| 72 | 75 | public func unload() async {} |
| 76 | + | |
| 77 | + /// Chat engines cannot embed. | |
| 78 | + public func embed(_ texts: [String]) async throws -> Embeddings { | |
| 79 | + throw WrongModelKind(model: name, kind: .chat, wanted: .embedding) | |
| 80 | + } | |
| 73 | 81 | } |
| 74 | 82 | |
| 75 | 83 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each |
| @@ -65,11 +65,19 @@ public protocol InferenceEngine: Sendable { | |||
| 65 | 65 | ||
| 66 | /// Frees the loaded model. The server calls it before dropping the engine. | 66 | /// Frees the loaded model. The server calls it before dropping the engine. |
| 67 | func unload() async | 67 | func unload() async |
| 68 | + | ||
| 69 | + /// Embeds `texts` with a loaded embedding model, one vector per text. | ||
| 70 | + func embed(_ texts: [String]) async throws -> Embeddings | ||
| 68 | } | 71 | } |
| 69 | 72 | ||
| 70 | extension InferenceEngine { | 73 | extension InferenceEngine { |
| 71 | /// Engines that hold nothing worth freeing early do nothing. | 74 | /// Engines that hold nothing worth freeing early do nothing. |
| 72 | public func unload() async {} | 75 | public func unload() async {} |
| 76 | + | ||
| 77 | + /// Chat engines cannot embed. | ||
| 78 | + public func embed(_ texts: [String]) async throws -> Embeddings { | ||
| 79 | + throw WrongModelKind(model: name, kind: .chat, wanted: .embedding) | ||
| 80 | + } | ||
| 73 | } | 81 | } |
| 74 | 82 | ||
| 75 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each | 83 | /// One conversation with a loaded model. It keeps the history (and the model's cache), so each |
modified
Sources/RazorbillCore/Models/ModelCatalog.swift +17 -2 | @@ -13,6 +13,16 @@ public struct ResolvedModel: Sendable, Equatable { | ||
| 13 | 13 | /// `locked` blocks, server-wide first, then the model's. |
| 14 | 14 | public var locked: [GenerationOverrides] |
| 15 | 15 | |
| 16 | + /// The model manager's slot for this model: chat and embedding loads of one repository | |
| 17 | + /// are distinct models. | |
| 18 | + public var slotKey: String { | |
| 19 | + Self.slotKey(source: source, kind: kind) | |
| 20 | + } | |
| 21 | + | |
| 22 | + public static func slotKey(source: ModelReference, kind: ModelKind) -> String { | |
| 23 | + kind == .chat ? source.description : "\(source.description)#\(kind.rawValue)" | |
| 24 | + } | |
| 25 | + | |
| 16 | 26 | /// The settings of a request that sent `client`. |
| 17 | 27 | public func generation(client: GenerationOverrides = .init()) -> GenerationSettings { |
| 18 | 28 | GenerationOverrides.resolve(defaults: defaults, client: client, locked: locked) |
| @@ -57,8 +67,13 @@ public struct ModelCatalog: Sendable { | ||
| 57 | 67 | self.store = store |
| 58 | 68 | } |
| 59 | 69 | |
| 60 | - public func resolve(_ name: String) throws -> ResolvedModel { | |
| 70 | + /// `kind`: what the endpoint needs. A declared model of another kind is refused; an | |
| 71 | + /// undeclared Hugging Face id is taken to be of this kind. | |
| 72 | + public func resolve(_ name: String, kind: ModelKind = .chat) throws -> ResolvedModel { | |
| 61 | 73 | if let entry = config.models.first(where: { $0.id == name }) { |
| 74 | + guard entry.kind == kind else { | |
| 75 | + throw WrongModelKind(model: name, kind: entry.kind, wanted: kind) | |
| 76 | + } | |
| 62 | 77 | return ResolvedModel( |
| 63 | 78 | name: name, source: entry.source, kind: entry.kind, isDeclared: true, |
| 64 | 79 | defaults: [config.defaults, entry.defaults], locked: [config.locked, entry.locked]) |
| @@ -70,7 +85,7 @@ public struct ModelCatalog: Sendable { | ||
| 70 | 85 | throw ModelResolutionError.notMLX(id) |
| 71 | 86 | } |
| 72 | 87 | return ResolvedModel( |
| 73 | - name: name, source: reference, kind: .chat, isDeclared: false, | |
| 88 | + name: name, source: reference, kind: kind, isDeclared: false, | |
| 74 | 89 | defaults: [config.defaults], locked: [config.locked]) |
| 75 | 90 | } |
| 76 | 91 | |
| @@ -13,6 +13,16 @@ public struct ResolvedModel: Sendable, Equatable { | |||
| 13 | /// `locked` blocks, server-wide first, then the model's. | 13 | /// `locked` blocks, server-wide first, then the model's. |
| 14 | public var locked: [GenerationOverrides] | 14 | public var locked: [GenerationOverrides] |
| 15 | 15 | ||
| 16 | + /// The model manager's slot for this model: chat and embedding loads of one repository | ||
| 17 | + /// are distinct models. | ||
| 18 | + public var slotKey: String { | ||
| 19 | + Self.slotKey(source: source, kind: kind) | ||
| 20 | + } | ||
| 21 | + | ||
| 22 | + public static func slotKey(source: ModelReference, kind: ModelKind) -> String { | ||
| 23 | + kind == .chat ? source.description : "\(source.description)#\(kind.rawValue)" | ||
| 24 | + } | ||
| 25 | + | ||
| 16 | /// The settings of a request that sent `client`. | 26 | /// The settings of a request that sent `client`. |
| 17 | public func generation(client: GenerationOverrides = .init()) -> GenerationSettings { | 27 | public func generation(client: GenerationOverrides = .init()) -> GenerationSettings { |
| 18 | GenerationOverrides.resolve(defaults: defaults, client: client, locked: locked) | 28 | GenerationOverrides.resolve(defaults: defaults, client: client, locked: locked) |
| @@ -57,8 +67,13 @@ public struct ModelCatalog: Sendable { | |||
| 57 | self.store = store | 67 | self.store = store |
| 58 | } | 68 | } |
| 59 | 69 | ||
| 60 | - public func resolve(_ name: String) throws -> ResolvedModel { | 70 | + /// `kind`: what the endpoint needs. A declared model of another kind is refused; an |
| 71 | + /// undeclared Hugging Face id is taken to be of this kind. | ||
| 72 | + public func resolve(_ name: String, kind: ModelKind = .chat) throws -> ResolvedModel { | ||
| 61 | if let entry = config.models.first(where: { $0.id == name }) { | 73 | if let entry = config.models.first(where: { $0.id == name }) { |
| 74 | + guard entry.kind == kind else { | ||
| 75 | + throw WrongModelKind(model: name, kind: entry.kind, wanted: kind) | ||
| 76 | + } | ||
| 62 | return ResolvedModel( | 77 | return ResolvedModel( |
| 63 | name: name, source: entry.source, kind: entry.kind, isDeclared: true, | 78 | name: name, source: entry.source, kind: entry.kind, isDeclared: true, |
| 64 | defaults: [config.defaults, entry.defaults], locked: [config.locked, entry.locked]) | 79 | defaults: [config.defaults, entry.defaults], locked: [config.locked, entry.locked]) |
| @@ -70,7 +85,7 @@ public struct ModelCatalog: Sendable { | |||
| 70 | throw ModelResolutionError.notMLX(id) | 85 | throw ModelResolutionError.notMLX(id) |
| 71 | } | 86 | } |
| 72 | return ResolvedModel( | 87 | return ResolvedModel( |
| 73 | - name: name, source: reference, kind: .chat, isDeclared: false, | 88 | + name: name, source: reference, kind: kind, isDeclared: false, |
| 74 | defaults: [config.defaults], locked: [config.locked]) | 89 | defaults: [config.defaults], locked: [config.locked]) |
| 75 | } | 90 | } |
| 76 | 91 | ||
added
Sources/RazorbillMLX/MLXEmbedder.swift +145 -0 | new file mode 100644 | ||
| @@ -0,0 +1,145 @@ | ||
| 1 | +#if canImport(MLXEmbedders) | |
| 2 | +import Foundation | |
| 3 | +import HuggingFace | |
| 4 | +import MLX | |
| 5 | +import MLXEmbedders | |
| 6 | +import MLXHuggingFace | |
| 7 | +import MLXLMCommon | |
| 8 | +import RazorbillCore | |
| 9 | +import Tokenizers | |
| 10 | + | |
| 11 | +/// Runs MLX embedding models (BERT, NomicBERT, Qwen3-Embedding, EmbeddingGemma, LFM2…) with | |
| 12 | +/// mlx-swift-lm's MLXEmbedders (ticket #42). | |
| 13 | +/// | |
| 14 | +/// Pooling comes from the model (sentence-transformers' `1_Pooling/config.json`, else the model's | |
| 15 | +/// own strategy); vectors are L2-normalised, like OpenAI's. | |
| 16 | +/// | |
| 17 | +/// ```swift | |
| 18 | +/// let embedder = MLXEmbedder() | |
| 19 | +/// try await embedder.load(.huggingFace(id: "sentence-transformers/all-MiniLM-L6-v2", revision: "main"), | |
| 20 | +/// offline: false) { _ in } | |
| 21 | +/// let result = try await embedder.embed(["Hello", "Bonjour"]) | |
| 22 | +/// ``` | |
| 23 | +public final class MLXEmbedder: InferenceEngine, @unchecked Sendable { | |
| 24 | + public let name = "mlx" | |
| 25 | + private let store: ModelStore | |
| 26 | + private let lock = NSLock() | |
| 27 | + private var container: EmbedderModelContainer? | |
| 28 | + /// Longest input the model takes (`max_position_embeddings`), when its config says. | |
| 29 | + private var maxTokens: Int? | |
| 30 | + /// Inputs per forward pass. | |
| 31 | + static let batchSize = 32 | |
| 32 | + | |
| 33 | + public init(store: ModelStore = ModelStore()) { | |
| 34 | + self.store = store | |
| 35 | + } | |
| 36 | + | |
| 37 | + /// Embedding models answer `/v1/embeddings` only. | |
| 38 | + public struct NotAChatModel: RequestSettingError { | |
| 39 | + public var parameter: String { "model" } | |
| 40 | + public var description: String { "this is an embedding model; use /v1/embeddings" } | |
| 41 | + } | |
| 42 | + | |
| 43 | + /// An input longer than the model accepts. | |
| 44 | + public struct InputTooLong: RequestSettingError { | |
| 45 | + public let index: Int | |
| 46 | + public let tokens: Int | |
| 47 | + public let limit: Int | |
| 48 | + public var parameter: String { "input" } | |
| 49 | + public var description: String { | |
| 50 | + "input[\(index)] has \(tokens) tokens; this model accepts at most \(limit)" | |
| 51 | + } | |
| 52 | + } | |
| 53 | + | |
| 54 | + public func load( | |
| 55 | + _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void | |
| 56 | + ) async throws { | |
| 57 | + let tokenizerLoader = #huggingFaceTokenizerLoader() | |
| 58 | + let loaded: EmbedderModelContainer | |
| 59 | + switch model { | |
| 60 | + case .local(let path): | |
| 61 | + loaded = try await EmbedderModelFactory.shared.loadContainer( | |
| 62 | + from: path, using: tokenizerLoader) | |
| 63 | + case .huggingFace(let id, let revision): | |
| 64 | + let cached = store.isAvailableLocally(model) | |
| 65 | + let downloader = HubDownloader(client: HubClient(), localOnly: offline || cached) | |
| 66 | + loaded = try await EmbedderModelFactory.shared.loadContainer( | |
| 67 | + from: downloader, using: tokenizerLoader, | |
| 68 | + configuration: ModelConfiguration(id: id, revision: revision), | |
| 69 | + progressHandler: { fraction in | |
| 70 | + if !cached { progress(fraction.fractionCompleted) } | |
| 71 | + }) | |
| 72 | + } | |
| 73 | + let limit = Self.maxTokens(in: try await loaded.modelDirectory) | |
| 74 | + lock.withLock { | |
| 75 | + container = loaded | |
| 76 | + maxTokens = limit | |
| 77 | + } | |
| 78 | + } | |
| 79 | + | |
| 80 | + public func download( | |
| 81 | + _ model: ModelReference, progress: @escaping @Sendable (Double) -> Void | |
| 82 | + ) async throws { | |
| 83 | + try await MLXEngine(store: store).download(model, progress: progress) | |
| 84 | + } | |
| 85 | + | |
| 86 | + public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | |
| 87 | + throw NotAChatModel() | |
| 88 | + } | |
| 89 | + | |
| 90 | + public func unload() async { | |
| 91 | + lock.withLock { container = nil } | |
| 92 | + } | |
| 93 | + | |
| 94 | + public func embed(_ texts: [String]) async throws -> Embeddings { | |
| 95 | + guard let (container, limit) = lock.withLock({ container.map { ($0, maxTokens) } }) else { | |
| 96 | + throw MLXEngine.NotLoaded() | |
| 97 | + } | |
| 98 | + return try await container.perform { context in | |
| 99 | + let tokens = texts.map { context.tokenizer.encode(text: $0, addSpecialTokens: true) } | |
| 100 | + if let limit, let index = tokens.firstIndex(where: { $0.count > limit }) { | |
| 101 | + throw InputTooLong(index: index, tokens: tokens[index].count, limit: limit) | |
| 102 | + } | |
| 103 | + var vectors: [[Float]] = [] | |
| 104 | + for start in stride(from: 0, to: tokens.count, by: Self.batchSize) { | |
| 105 | + let batch = Array(tokens[start ..< min(start + Self.batchSize, tokens.count)]) | |
| 106 | + vectors += Self.embedBatch(batch, context: context) | |
| 107 | + } | |
| 108 | + return Embeddings(vectors: vectors, promptTokens: tokens.reduce(0) { $0 + $1.count }) | |
| 109 | + } | |
| 110 | + } | |
| 111 | + | |
| 112 | + /// One forward pass: inputs right-padded to the longest, with an attention mask. | |
| 113 | + static func embedBatch(_ batch: [[Int]], context: EmbedderModelContext) -> [[Float]] { | |
| 114 | + let length = batch.map(\.count).max() ?? 1 | |
| 115 | + let ids = batch.flatMap { $0 + Array(repeating: 0, count: length - $0.count) } | |
| 116 | + let flags = batch.flatMap { row in (0 ..< length).map { $0 < row.count } } | |
| 117 | + let inputs = MLXArray(ids.map(Int32.init)).reshaped([batch.count, length]) | |
| 118 | + let mask = MLXArray(flags).reshaped([batch.count, length]) | |
| 119 | + let output = context.model( | |
| 120 | + inputs, positionIds: nil, tokenTypeIds: MLXArray.zeros(like: inputs), | |
| 121 | + attentionMask: mask) | |
| 122 | + let pooled = sentenceTransformersPooling(context.pooling)( | |
| 123 | + output, mask: mask, normalize: true) | |
| 124 | + pooled.eval() | |
| 125 | + return (0 ..< batch.count).map { pooled[$0].asArray(Float.self) } | |
| 126 | + } | |
| 127 | + | |
| 128 | + /// sentence-transformers' `pooling_mode_cls_token` means the first token's hidden state, but | |
| 129 | + /// MLXEmbedders maps it to `.cls`, which takes BERT's pooler output (dense + tanh) when the | |
| 130 | + /// model has one: cosines then differ by up to 0.08 from sentence-transformers (seen with | |
| 131 | + /// bge-small-en-v1.5). Use `.first` instead. | |
| 132 | + static func sentenceTransformersPooling(_ pooling: Pooling) -> Pooling { | |
| 133 | + guard pooling.strategy == .cls else { return pooling } | |
| 134 | + return Pooling(strategy: .first, dimension: pooling.dimension) | |
| 135 | + } | |
| 136 | + | |
| 137 | + /// `max_position_embeddings` from the model's `config.json`. | |
| 138 | + static func maxTokens(in directory: URL) -> Int? { | |
| 139 | + guard let data = try? Data(contentsOf: directory.appendingPathComponent("config.json")), | |
| 140 | + let config = try? JSONSerialization.jsonObject(with: data) as? [String: Any] | |
| 141 | + else { return nil } | |
| 142 | + return config["max_position_embeddings"] as? Int | |
| 143 | + } | |
| 144 | +} | |
| 145 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,145 @@ | |||
| 1 | +#if canImport(MLXEmbedders) | ||
| 2 | +import Foundation | ||
| 3 | +import HuggingFace | ||
| 4 | +import MLX | ||
| 5 | +import MLXEmbedders | ||
| 6 | +import MLXHuggingFace | ||
| 7 | +import MLXLMCommon | ||
| 8 | +import RazorbillCore | ||
| 9 | +import Tokenizers | ||
| 10 | + | ||
| 11 | +/// Runs MLX embedding models (BERT, NomicBERT, Qwen3-Embedding, EmbeddingGemma, LFM2…) with | ||
| 12 | +/// mlx-swift-lm's MLXEmbedders (ticket #42). | ||
| 13 | +/// | ||
| 14 | +/// Pooling comes from the model (sentence-transformers' `1_Pooling/config.json`, else the model's | ||
| 15 | +/// own strategy); vectors are L2-normalised, like OpenAI's. | ||
| 16 | +/// | ||
| 17 | +/// ```swift | ||
| 18 | +/// let embedder = MLXEmbedder() | ||
| 19 | +/// try await embedder.load(.huggingFace(id: "sentence-transformers/all-MiniLM-L6-v2", revision: "main"), | ||
| 20 | +/// offline: false) { _ in } | ||
| 21 | +/// let result = try await embedder.embed(["Hello", "Bonjour"]) | ||
| 22 | +/// ``` | ||
| 23 | +public final class MLXEmbedder: InferenceEngine, @unchecked Sendable { | ||
| 24 | + public let name = "mlx" | ||
| 25 | + private let store: ModelStore | ||
| 26 | + private let lock = NSLock() | ||
| 27 | + private var container: EmbedderModelContainer? | ||
| 28 | + /// Longest input the model takes (`max_position_embeddings`), when its config says. | ||
| 29 | + private var maxTokens: Int? | ||
| 30 | + /// Inputs per forward pass. | ||
| 31 | + static let batchSize = 32 | ||
| 32 | + | ||
| 33 | + public init(store: ModelStore = ModelStore()) { | ||
| 34 | + self.store = store | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + /// Embedding models answer `/v1/embeddings` only. | ||
| 38 | + public struct NotAChatModel: RequestSettingError { | ||
| 39 | + public var parameter: String { "model" } | ||
| 40 | + public var description: String { "this is an embedding model; use /v1/embeddings" } | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + /// An input longer than the model accepts. | ||
| 44 | + public struct InputTooLong: RequestSettingError { | ||
| 45 | + public let index: Int | ||
| 46 | + public let tokens: Int | ||
| 47 | + public let limit: Int | ||
| 48 | + public var parameter: String { "input" } | ||
| 49 | + public var description: String { | ||
| 50 | + "input[\(index)] has \(tokens) tokens; this model accepts at most \(limit)" | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + public func load( | ||
| 55 | + _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void | ||
| 56 | + ) async throws { | ||
| 57 | + let tokenizerLoader = #huggingFaceTokenizerLoader() | ||
| 58 | + let loaded: EmbedderModelContainer | ||
| 59 | + switch model { | ||
| 60 | + case .local(let path): | ||
| 61 | + loaded = try await EmbedderModelFactory.shared.loadContainer( | ||
| 62 | + from: path, using: tokenizerLoader) | ||
| 63 | + case .huggingFace(let id, let revision): | ||
| 64 | + let cached = store.isAvailableLocally(model) | ||
| 65 | + let downloader = HubDownloader(client: HubClient(), localOnly: offline || cached) | ||
| 66 | + loaded = try await EmbedderModelFactory.shared.loadContainer( | ||
| 67 | + from: downloader, using: tokenizerLoader, | ||
| 68 | + configuration: ModelConfiguration(id: id, revision: revision), | ||
| 69 | + progressHandler: { fraction in | ||
| 70 | + if !cached { progress(fraction.fractionCompleted) } | ||
| 71 | + }) | ||
| 72 | + } | ||
| 73 | + let limit = Self.maxTokens(in: try await loaded.modelDirectory) | ||
| 74 | + lock.withLock { | ||
| 75 | + container = loaded | ||
| 76 | + maxTokens = limit | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + public func download( | ||
| 81 | + _ model: ModelReference, progress: @escaping @Sendable (Double) -> Void | ||
| 82 | + ) async throws { | ||
| 83 | + try await MLXEngine(store: store).download(model, progress: progress) | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | ||
| 87 | + throw NotAChatModel() | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + public func unload() async { | ||
| 91 | + lock.withLock { container = nil } | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + public func embed(_ texts: [String]) async throws -> Embeddings { | ||
| 95 | + guard let (container, limit) = lock.withLock({ container.map { ($0, maxTokens) } }) else { | ||
| 96 | + throw MLXEngine.NotLoaded() | ||
| 97 | + } | ||
| 98 | + return try await container.perform { context in | ||
| 99 | + let tokens = texts.map { context.tokenizer.encode(text: $0, addSpecialTokens: true) } | ||
| 100 | + if let limit, let index = tokens.firstIndex(where: { $0.count > limit }) { | ||
| 101 | + throw InputTooLong(index: index, tokens: tokens[index].count, limit: limit) | ||
| 102 | + } | ||
| 103 | + var vectors: [[Float]] = [] | ||
| 104 | + for start in stride(from: 0, to: tokens.count, by: Self.batchSize) { | ||
| 105 | + let batch = Array(tokens[start ..< min(start + Self.batchSize, tokens.count)]) | ||
| 106 | + vectors += Self.embedBatch(batch, context: context) | ||
| 107 | + } | ||
| 108 | + return Embeddings(vectors: vectors, promptTokens: tokens.reduce(0) { $0 + $1.count }) | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + | ||
| 112 | + /// One forward pass: inputs right-padded to the longest, with an attention mask. | ||
| 113 | + static func embedBatch(_ batch: [[Int]], context: EmbedderModelContext) -> [[Float]] { | ||
| 114 | + let length = batch.map(\.count).max() ?? 1 | ||
| 115 | + let ids = batch.flatMap { $0 + Array(repeating: 0, count: length - $0.count) } | ||
| 116 | + let flags = batch.flatMap { row in (0 ..< length).map { $0 < row.count } } | ||
| 117 | + let inputs = MLXArray(ids.map(Int32.init)).reshaped([batch.count, length]) | ||
| 118 | + let mask = MLXArray(flags).reshaped([batch.count, length]) | ||
| 119 | + let output = context.model( | ||
| 120 | + inputs, positionIds: nil, tokenTypeIds: MLXArray.zeros(like: inputs), | ||
| 121 | + attentionMask: mask) | ||
| 122 | + let pooled = sentenceTransformersPooling(context.pooling)( | ||
| 123 | + output, mask: mask, normalize: true) | ||
| 124 | + pooled.eval() | ||
| 125 | + return (0 ..< batch.count).map { pooled[$0].asArray(Float.self) } | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + /// sentence-transformers' `pooling_mode_cls_token` means the first token's hidden state, but | ||
| 129 | + /// MLXEmbedders maps it to `.cls`, which takes BERT's pooler output (dense + tanh) when the | ||
| 130 | + /// model has one: cosines then differ by up to 0.08 from sentence-transformers (seen with | ||
| 131 | + /// bge-small-en-v1.5). Use `.first` instead. | ||
| 132 | + static func sentenceTransformersPooling(_ pooling: Pooling) -> Pooling { | ||
| 133 | + guard pooling.strategy == .cls else { return pooling } | ||
| 134 | + return Pooling(strategy: .first, dimension: pooling.dimension) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// `max_position_embeddings` from the model's `config.json`. | ||
| 138 | + static func maxTokens(in directory: URL) -> Int? { | ||
| 139 | + guard let data = try? Data(contentsOf: directory.appendingPathComponent("config.json")), | ||
| 140 | + let config = try? JSONSerialization.jsonObject(with: data) as? [String: Any] | ||
| 141 | + else { return nil } | ||
| 142 | + return config["max_position_embeddings"] as? Int | ||
| 143 | + } | ||
| 144 | +} | ||
| 145 | +#endif | ||
modified
Sources/RazorbillMLX/MLXSupport.swift +6 -1 | @@ -18,7 +18,12 @@ public enum MLXSupport { | ||
| 18 | 18 | /// Adds the `mlx` engine when this build has it. |
| 19 | 19 | public static func register(into engines: inout EngineRegistry) { |
| 20 | 20 | #if canImport(MLXLLM) |
| 21 | - engines.register("mlx") { MLXEngine() } | |
| 21 | + engines.register("mlx") { kind in | |
| 22 | + switch kind { | |
| 23 | + case .chat: MLXEngine() | |
| 24 | + case .embedding: MLXEmbedder() | |
| 25 | + } | |
| 26 | + } | |
| 22 | 27 | #endif |
| 23 | 28 | } |
| 24 | 29 | } |
| @@ -18,7 +18,12 @@ public enum MLXSupport { | |||
| 18 | /// Adds the `mlx` engine when this build has it. | 18 | /// Adds the `mlx` engine when this build has it. |
| 19 | public static func register(into engines: inout EngineRegistry) { | 19 | public static func register(into engines: inout EngineRegistry) { |
| 20 | #if canImport(MLXLLM) | 20 | #if canImport(MLXLLM) |
| 21 | - engines.register("mlx") { MLXEngine() } | 21 | + engines.register("mlx") { kind in |
| 22 | + switch kind { | ||
| 23 | + case .chat: MLXEngine() | ||
| 24 | + case .embedding: MLXEmbedder() | ||
| 25 | + } | ||
| 26 | + } | ||
| 22 | #endif | 27 | #endif |
| 23 | } | 28 | } |
| 24 | } | 29 | } |
added
Sources/RazorbillServer/EmbeddingsRoute.swift +171 -0 | new file mode 100644 | ||
| @@ -0,0 +1,171 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import RazorbillCore | |
| 4 | + | |
| 5 | +/// The body of `POST /v1/embeddings`. | |
| 6 | +struct EmbeddingsRequest: Decodable, Sendable { | |
| 7 | + let model: String | |
| 8 | + let input: EmbeddingInput | |
| 9 | + var encodingFormat: String? | |
| 10 | + var dimensions: Int? | |
| 11 | + | |
| 12 | + enum CodingKeys: String, CodingKey { | |
| 13 | + case model, input, dimensions | |
| 14 | + case encodingFormat = "encoding_format" | |
| 15 | + } | |
| 16 | + | |
| 17 | + /// Most inputs per request, as OpenAI. | |
| 18 | + static let maxInputs = 2048 | |
| 19 | + | |
| 20 | + /// The texts to embed, checked: none empty, at most ``maxInputs``. | |
| 21 | + func texts() throws -> [String] { | |
| 22 | + let texts: [String] | |
| 23 | + switch input { | |
| 24 | + case .text(let text): texts = [text] | |
| 25 | + case .texts(let list): texts = list | |
| 26 | + case .tokens: | |
| 27 | + throw invalid("input", "token arrays are not supported yet; send text") | |
| 28 | + } | |
| 29 | + guard !texts.isEmpty else { throw invalid("input", "must hold at least one text") } | |
| 30 | + guard texts.count <= Self.maxInputs else { | |
| 31 | + throw invalid("input", "can hold at most \(Self.maxInputs) texts") | |
| 32 | + } | |
| 33 | + if let empty = texts.firstIndex(where: \.isEmpty) { | |
| 34 | + throw invalid("input", "input[\(empty)] is empty") | |
| 35 | + } | |
| 36 | + return texts | |
| 37 | + } | |
| 38 | + | |
| 39 | + func checkOptions() throws { | |
| 40 | + guard ["float", "base64"].contains(encodingFormat ?? "float") else { | |
| 41 | + throw invalid("encoding_format", "must be float or base64") | |
| 42 | + } | |
| 43 | + if let dimensions, dimensions < 1 { | |
| 44 | + throw invalid("dimensions", "must be 1 or more") | |
| 45 | + } | |
| 46 | + } | |
| 47 | + | |
| 48 | + private func invalid(_ param: String, _ message: String) -> OpenAIError { | |
| 49 | + OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | |
| 50 | + } | |
| 51 | +} | |
| 52 | + | |
| 53 | +/// `input`: a string, a list of strings, or (refused for now) token arrays. | |
| 54 | +enum EmbeddingInput: Decodable, Sendable { | |
| 55 | + case text(String) | |
| 56 | + case texts([String]) | |
| 57 | + case tokens | |
| 58 | + | |
| 59 | + init(from decoder: any Decoder) throws { | |
| 60 | + let container = try decoder.singleValueContainer() | |
| 61 | + if let text = try? container.decode(String.self) { | |
| 62 | + self = .text(text) | |
| 63 | + } else if let texts = try? container.decode([String].self) { | |
| 64 | + self = .texts(texts) | |
| 65 | + } else if Self.isTokenArray(container) { | |
| 66 | + self = .tokens | |
| 67 | + } else { | |
| 68 | + throw DecodingError.typeMismatch( | |
| 69 | + String.self, | |
| 70 | + .init( | |
| 71 | + codingPath: decoder.codingPath, | |
| 72 | + debugDescription: "a string or a list of strings")) | |
| 73 | + } | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +extension EmbeddingInput { | |
| 78 | + /// `[1, 2, 3]` or `[[1, 2], [3]]`. | |
| 79 | + static func isTokenArray(_ container: any SingleValueDecodingContainer) -> Bool { | |
| 80 | + (try? container.decode([Int].self)) != nil || (try? container.decode([[Int]].self)) != nil | |
| 81 | + } | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// `{"object": "list", "data": [...], "model": …, "usage": …}`. | |
| 85 | +struct EmbeddingsResponse: Encodable, Sendable { | |
| 86 | + var object = "list" | |
| 87 | + let data: [EmbeddingItem] | |
| 88 | + let model: String | |
| 89 | + let usage: EmbeddingUsage | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// One vector, as floats or base64 (little-endian float32). | |
| 93 | +struct EmbeddingItem: Encodable, Sendable { | |
| 94 | + var object = "embedding" | |
| 95 | + let index: Int | |
| 96 | + let embedding: EmbeddingValue | |
| 97 | +} | |
| 98 | + | |
| 99 | +enum EmbeddingValue: Encodable, Sendable { | |
| 100 | + case floats([Float]) | |
| 101 | + case base64(String) | |
| 102 | + | |
| 103 | + func encode(to encoder: any Encoder) throws { | |
| 104 | + var container = encoder.singleValueContainer() | |
| 105 | + switch self { | |
| 106 | + case .floats(let values): try container.encode(values) | |
| 107 | + case .base64(let text): try container.encode(text) | |
| 108 | + } | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +struct EmbeddingUsage: Encodable, Sendable { | |
| 113 | + let promptTokens: Int | |
| 114 | + var totalTokens: Int { promptTokens } | |
| 115 | + | |
| 116 | + enum CodingKeys: String, CodingKey { | |
| 117 | + case promptTokens = "prompt_tokens" | |
| 118 | + case totalTokens = "total_tokens" | |
| 119 | + } | |
| 120 | + | |
| 121 | + func encode(to encoder: any Encoder) throws { | |
| 122 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 123 | + try container.encode(promptTokens, forKey: .promptTokens) | |
| 124 | + try container.encode(totalTokens, forKey: .totalTokens) | |
| 125 | + } | |
| 126 | +} | |
| 127 | + | |
| 128 | +/// `POST /v1/embeddings` (ticket #42). The model is held while its batch runs, like a chat answer. | |
| 129 | +struct EmbeddingsRoute { | |
| 130 | + let models: ModelManager | |
| 131 | + | |
| 132 | + func add(to router: Router<ServerContext>) { | |
| 133 | + router.post("/v1/embeddings") { request, context in | |
| 134 | + let body = try await request.decode(as: EmbeddingsRequest.self, context: context) | |
| 135 | + let texts = try body.texts() | |
| 136 | + try body.checkOptions() | |
| 137 | + let embeddings = try await models.withModel(body.model, kind: .embedding) { lease in | |
| 138 | + try await lease.engine.embed(texts) | |
| 139 | + } | |
| 140 | + context.usage.record( | |
| 141 | + model: body.model, promptTokens: embeddings.promptTokens, completionTokens: 0) | |
| 142 | + return try jsonResponse(try Self.response(embeddings, for: body)) | |
| 143 | + } | |
| 144 | + } | |
| 145 | + | |
| 146 | + /// Applies `dimensions` and `encoding_format`. | |
| 147 | + static func response( | |
| 148 | + _ embeddings: Embeddings, for request: EmbeddingsRequest | |
| 149 | + ) throws -> EmbeddingsResponse { | |
| 150 | + var result = embeddings | |
| 151 | + if let dimensions = request.dimensions { | |
| 152 | + let native = embeddings.vectors.first?.count ?? 0 | |
| 153 | + guard dimensions <= native else { | |
| 154 | + throw OpenAIError( | |
| 155 | + .badRequest, | |
| 156 | + message: "dimensions \(dimensions) is larger than this model's \(native).", | |
| 157 | + param: "dimensions") | |
| 158 | + } | |
| 159 | + result = embeddings.truncated(to: dimensions) | |
| 160 | + } | |
| 161 | + let base64 = request.encodingFormat == "base64" | |
| 162 | + let items = result.vectors.enumerated().map { index, vector in | |
| 163 | + EmbeddingItem( | |
| 164 | + index: index, | |
| 165 | + embedding: base64 ? .base64(Embeddings.base64(vector)) : .floats(vector)) | |
| 166 | + } | |
| 167 | + return EmbeddingsResponse( | |
| 168 | + data: items, model: request.model, | |
| 169 | + usage: EmbeddingUsage(promptTokens: embeddings.promptTokens)) | |
| 170 | + } | |
| 171 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,171 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import RazorbillCore | ||
| 4 | + | ||
| 5 | +/// The body of `POST /v1/embeddings`. | ||
| 6 | +struct EmbeddingsRequest: Decodable, Sendable { | ||
| 7 | + let model: String | ||
| 8 | + let input: EmbeddingInput | ||
| 9 | + var encodingFormat: String? | ||
| 10 | + var dimensions: Int? | ||
| 11 | + | ||
| 12 | + enum CodingKeys: String, CodingKey { | ||
| 13 | + case model, input, dimensions | ||
| 14 | + case encodingFormat = "encoding_format" | ||
| 15 | + } | ||
| 16 | + | ||
| 17 | + /// Most inputs per request, as OpenAI. | ||
| 18 | + static let maxInputs = 2048 | ||
| 19 | + | ||
| 20 | + /// The texts to embed, checked: none empty, at most ``maxInputs``. | ||
| 21 | + func texts() throws -> [String] { | ||
| 22 | + let texts: [String] | ||
| 23 | + switch input { | ||
| 24 | + case .text(let text): texts = [text] | ||
| 25 | + case .texts(let list): texts = list | ||
| 26 | + case .tokens: | ||
| 27 | + throw invalid("input", "token arrays are not supported yet; send text") | ||
| 28 | + } | ||
| 29 | + guard !texts.isEmpty else { throw invalid("input", "must hold at least one text") } | ||
| 30 | + guard texts.count <= Self.maxInputs else { | ||
| 31 | + throw invalid("input", "can hold at most \(Self.maxInputs) texts") | ||
| 32 | + } | ||
| 33 | + if let empty = texts.firstIndex(where: \.isEmpty) { | ||
| 34 | + throw invalid("input", "input[\(empty)] is empty") | ||
| 35 | + } | ||
| 36 | + return texts | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + func checkOptions() throws { | ||
| 40 | + guard ["float", "base64"].contains(encodingFormat ?? "float") else { | ||
| 41 | + throw invalid("encoding_format", "must be float or base64") | ||
| 42 | + } | ||
| 43 | + if let dimensions, dimensions < 1 { | ||
| 44 | + throw invalid("dimensions", "must be 1 or more") | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + private func invalid(_ param: String, _ message: String) -> OpenAIError { | ||
| 49 | + OpenAIError(.badRequest, message: "\(param) \(message).", param: param) | ||
| 50 | + } | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// `input`: a string, a list of strings, or (refused for now) token arrays. | ||
| 54 | +enum EmbeddingInput: Decodable, Sendable { | ||
| 55 | + case text(String) | ||
| 56 | + case texts([String]) | ||
| 57 | + case tokens | ||
| 58 | + | ||
| 59 | + init(from decoder: any Decoder) throws { | ||
| 60 | + let container = try decoder.singleValueContainer() | ||
| 61 | + if let text = try? container.decode(String.self) { | ||
| 62 | + self = .text(text) | ||
| 63 | + } else if let texts = try? container.decode([String].self) { | ||
| 64 | + self = .texts(texts) | ||
| 65 | + } else if Self.isTokenArray(container) { | ||
| 66 | + self = .tokens | ||
| 67 | + } else { | ||
| 68 | + throw DecodingError.typeMismatch( | ||
| 69 | + String.self, | ||
| 70 | + .init( | ||
| 71 | + codingPath: decoder.codingPath, | ||
| 72 | + debugDescription: "a string or a list of strings")) | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +extension EmbeddingInput { | ||
| 78 | + /// `[1, 2, 3]` or `[[1, 2], [3]]`. | ||
| 79 | + static func isTokenArray(_ container: any SingleValueDecodingContainer) -> Bool { | ||
| 80 | + (try? container.decode([Int].self)) != nil || (try? container.decode([[Int]].self)) != nil | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// `{"object": "list", "data": [...], "model": …, "usage": …}`. | ||
| 85 | +struct EmbeddingsResponse: Encodable, Sendable { | ||
| 86 | + var object = "list" | ||
| 87 | + let data: [EmbeddingItem] | ||
| 88 | + let model: String | ||
| 89 | + let usage: EmbeddingUsage | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// One vector, as floats or base64 (little-endian float32). | ||
| 93 | +struct EmbeddingItem: Encodable, Sendable { | ||
| 94 | + var object = "embedding" | ||
| 95 | + let index: Int | ||
| 96 | + let embedding: EmbeddingValue | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +enum EmbeddingValue: Encodable, Sendable { | ||
| 100 | + case floats([Float]) | ||
| 101 | + case base64(String) | ||
| 102 | + | ||
| 103 | + func encode(to encoder: any Encoder) throws { | ||
| 104 | + var container = encoder.singleValueContainer() | ||
| 105 | + switch self { | ||
| 106 | + case .floats(let values): try container.encode(values) | ||
| 107 | + case .base64(let text): try container.encode(text) | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +struct EmbeddingUsage: Encodable, Sendable { | ||
| 113 | + let promptTokens: Int | ||
| 114 | + var totalTokens: Int { promptTokens } | ||
| 115 | + | ||
| 116 | + enum CodingKeys: String, CodingKey { | ||
| 117 | + case promptTokens = "prompt_tokens" | ||
| 118 | + case totalTokens = "total_tokens" | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + func encode(to encoder: any Encoder) throws { | ||
| 122 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 123 | + try container.encode(promptTokens, forKey: .promptTokens) | ||
| 124 | + try container.encode(totalTokens, forKey: .totalTokens) | ||
| 125 | + } | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +/// `POST /v1/embeddings` (ticket #42). The model is held while its batch runs, like a chat answer. | ||
| 129 | +struct EmbeddingsRoute { | ||
| 130 | + let models: ModelManager | ||
| 131 | + | ||
| 132 | + func add(to router: Router<ServerContext>) { | ||
| 133 | + router.post("/v1/embeddings") { request, context in | ||
| 134 | + let body = try await request.decode(as: EmbeddingsRequest.self, context: context) | ||
| 135 | + let texts = try body.texts() | ||
| 136 | + try body.checkOptions() | ||
| 137 | + let embeddings = try await models.withModel(body.model, kind: .embedding) { lease in | ||
| 138 | + try await lease.engine.embed(texts) | ||
| 139 | + } | ||
| 140 | + context.usage.record( | ||
| 141 | + model: body.model, promptTokens: embeddings.promptTokens, completionTokens: 0) | ||
| 142 | + return try jsonResponse(try Self.response(embeddings, for: body)) | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// Applies `dimensions` and `encoding_format`. | ||
| 147 | + static func response( | ||
| 148 | + _ embeddings: Embeddings, for request: EmbeddingsRequest | ||
| 149 | + ) throws -> EmbeddingsResponse { | ||
| 150 | + var result = embeddings | ||
| 151 | + if let dimensions = request.dimensions { | ||
| 152 | + let native = embeddings.vectors.first?.count ?? 0 | ||
| 153 | + guard dimensions <= native else { | ||
| 154 | + throw OpenAIError( | ||
| 155 | + .badRequest, | ||
| 156 | + message: "dimensions \(dimensions) is larger than this model's \(native).", | ||
| 157 | + param: "dimensions") | ||
| 158 | + } | ||
| 159 | + result = embeddings.truncated(to: dimensions) | ||
| 160 | + } | ||
| 161 | + let base64 = request.encodingFormat == "base64" | ||
| 162 | + let items = result.vectors.enumerated().map { index, vector in | ||
| 163 | + EmbeddingItem( | ||
| 164 | + index: index, | ||
| 165 | + embedding: base64 ? .base64(Embeddings.base64(vector)) : .floats(vector)) | ||
| 166 | + } | ||
| 167 | + return EmbeddingsResponse( | ||
| 168 | + data: items, model: request.model, | ||
| 169 | + usage: EmbeddingUsage(promptTokens: embeddings.promptTokens)) | ||
| 170 | + } | ||
| 171 | +} | ||
modified
Sources/RazorbillServer/ModelManager.swift +12 -11 | @@ -60,7 +60,8 @@ public struct ModelLease: Sendable { | ||
| 60 | 60 | /// let session = try await lease.engine.makeSession(setup) |
| 61 | 61 | /// ``` |
| 62 | 62 | public actor ModelManager { |
| 63 | - public typealias EngineFactory = @Sendable () throws -> any InferenceEngine | |
| 63 | + /// Creates an engine for a model of this kind. | |
| 64 | + public typealias EngineFactory = @Sendable (ModelKind) throws -> any InferenceEngine | |
| 64 | 65 | |
| 65 | 66 | public nonisolated let catalog: ModelCatalog |
| 66 | 67 | let limits: ServerLimits |
| @@ -104,9 +105,9 @@ public actor ModelManager { | ||
| 104 | 105 | |
| 105 | 106 | /// Waits for the model's turn, loads it if needed and hands it over. Cancelling the calling |
| 106 | 107 | /// task while it waits removes it from the queue. |
| 107 | - public func acquire(_ name: String) async throws -> ModelLease { | |
| 108 | - let model = try catalog.resolve(name) | |
| 109 | - let key = model.source.description | |
| 108 | + public func acquire(_ name: String, kind: ModelKind = .chat) async throws -> ModelLease { | |
| 109 | + let model = try catalog.resolve(name, kind: kind) | |
| 110 | + let key = model.slotKey | |
| 110 | 111 | try await takeTurn(key: key, model: model) |
| 111 | 112 | do { |
| 112 | 113 | let engine = try await loadedEngine(key: key) |
| @@ -119,9 +120,9 @@ public actor ModelManager { | ||
| 119 | 120 | |
| 120 | 121 | /// Runs `body` with the model, releasing it afterwards. |
| 121 | 122 | public func withModel<T: Sendable>( |
| 122 | - _ name: String, _ body: @Sendable (ModelLease) async throws -> T | |
| 123 | + _ name: String, kind: ModelKind = .chat, _ body: @Sendable (ModelLease) async throws -> T | |
| 123 | 124 | ) async throws -> T { |
| 124 | - let lease = try await acquire(name) | |
| 125 | + let lease = try await acquire(name, kind: kind) | |
| 125 | 126 | do { |
| 126 | 127 | let result = try await body(lease) |
| 127 | 128 | await lease.release() |
| @@ -192,7 +193,7 @@ public actor ModelManager { | ||
| 192 | 193 | try await makeRoom(for: key, model: model.name, size: size) |
| 193 | 194 | let engine: any InferenceEngine |
| 194 | 195 | do { |
| 195 | - engine = try makeEngine() | |
| 196 | + engine = try makeEngine(model.kind) | |
| 196 | 197 | let start = ContinuousClock.now |
| 197 | 198 | try await engine.load(model.source, offline: false) { _ in } |
| 198 | 199 | logger.info("loaded \(model.source) in \(ContinuousClock.now - start)") |
| @@ -253,7 +254,7 @@ public actor ModelManager { | ||
| 253 | 254 | public func preload() async { |
| 254 | 255 | for entry in catalog.config.models where entry.preload { |
| 255 | 256 | do { |
| 256 | - let lease = try await acquire(entry.id) | |
| 257 | + let lease = try await acquire(entry.id, kind: entry.kind) | |
| 257 | 258 | await lease.release() |
| 258 | 259 | } catch { |
| 259 | 260 | logger.error("cannot preload \(entry.id): \(error)") |
| @@ -281,17 +282,17 @@ public actor ModelManager { | ||
| 281 | 282 | |
| 282 | 283 | /// Requests waiting for `name` (tests and diagnostics). |
| 283 | 284 | func queueLength(_ name: String) throws -> Int { |
| 284 | - let key = try catalog.resolve(name).source.description | |
| 285 | + let key = try catalog.resolve(name).slotKey | |
| 285 | 286 | return slots[key]?.waiters.count ?? 0 |
| 286 | 287 | } |
| 287 | 288 | |
| 288 | 289 | /// A request holds `name` right now (tests and diagnostics). |
| 289 | 290 | func isBusy(_ name: String) throws -> Bool { |
| 290 | - let key = try catalog.resolve(name).source.description | |
| 291 | + let key = try catalog.resolve(name).slotKey | |
| 291 | 292 | return slots[key]?.busy ?? false |
| 292 | 293 | } |
| 293 | 294 | |
| 294 | - /// Sources of the models currently loaded, as `ModelReference.description`. | |
| 295 | + /// Slot keys of the models currently loaded (``ResolvedModel/slotKey``). | |
| 295 | 296 | public func loadedSources() -> Set<String> { |
| 296 | 297 | Set(slots.filter { $0.value.engine != nil }.keys) |
| 297 | 298 | } |
| @@ -60,7 +60,8 @@ public struct ModelLease: Sendable { | |||
| 60 | /// let session = try await lease.engine.makeSession(setup) | 60 | /// let session = try await lease.engine.makeSession(setup) |
| 61 | /// ``` | 61 | /// ``` |
| 62 | public actor ModelManager { | 62 | public actor ModelManager { |
| 63 | - public typealias EngineFactory = @Sendable () throws -> any InferenceEngine | 63 | + /// Creates an engine for a model of this kind. |
| 64 | + public typealias EngineFactory = @Sendable (ModelKind) throws -> any InferenceEngine | ||
| 64 | 65 | ||
| 65 | public nonisolated let catalog: ModelCatalog | 66 | public nonisolated let catalog: ModelCatalog |
| 66 | let limits: ServerLimits | 67 | let limits: ServerLimits |
| @@ -104,9 +105,9 @@ public actor ModelManager { | |||
| 104 | 105 | ||
| 105 | /// Waits for the model's turn, loads it if needed and hands it over. Cancelling the calling | 106 | /// Waits for the model's turn, loads it if needed and hands it over. Cancelling the calling |
| 106 | /// task while it waits removes it from the queue. | 107 | /// task while it waits removes it from the queue. |
| 107 | - public func acquire(_ name: String) async throws -> ModelLease { | 108 | + public func acquire(_ name: String, kind: ModelKind = .chat) async throws -> ModelLease { |
| 108 | - let model = try catalog.resolve(name) | 109 | + let model = try catalog.resolve(name, kind: kind) |
| 109 | - let key = model.source.description | 110 | + let key = model.slotKey |
| 110 | try await takeTurn(key: key, model: model) | 111 | try await takeTurn(key: key, model: model) |
| 111 | do { | 112 | do { |
| 112 | let engine = try await loadedEngine(key: key) | 113 | let engine = try await loadedEngine(key: key) |
| @@ -119,9 +120,9 @@ public actor ModelManager { | |||
| 119 | 120 | ||
| 120 | /// Runs `body` with the model, releasing it afterwards. | 121 | /// Runs `body` with the model, releasing it afterwards. |
| 121 | public func withModel<T: Sendable>( | 122 | public func withModel<T: Sendable>( |
| 122 | - _ name: String, _ body: @Sendable (ModelLease) async throws -> T | 123 | + _ name: String, kind: ModelKind = .chat, _ body: @Sendable (ModelLease) async throws -> T |
| 123 | ) async throws -> T { | 124 | ) async throws -> T { |
| 124 | - let lease = try await acquire(name) | 125 | + let lease = try await acquire(name, kind: kind) |
| 125 | do { | 126 | do { |
| 126 | let result = try await body(lease) | 127 | let result = try await body(lease) |
| 127 | await lease.release() | 128 | await lease.release() |
| @@ -192,7 +193,7 @@ public actor ModelManager { | |||
| 192 | try await makeRoom(for: key, model: model.name, size: size) | 193 | try await makeRoom(for: key, model: model.name, size: size) |
| 193 | let engine: any InferenceEngine | 194 | let engine: any InferenceEngine |
| 194 | do { | 195 | do { |
| 195 | - engine = try makeEngine() | 196 | + engine = try makeEngine(model.kind) |
| 196 | let start = ContinuousClock.now | 197 | let start = ContinuousClock.now |
| 197 | try await engine.load(model.source, offline: false) { _ in } | 198 | try await engine.load(model.source, offline: false) { _ in } |
| 198 | logger.info("loaded \(model.source) in \(ContinuousClock.now - start)") | 199 | logger.info("loaded \(model.source) in \(ContinuousClock.now - start)") |
| @@ -253,7 +254,7 @@ public actor ModelManager { | |||
| 253 | public func preload() async { | 254 | public func preload() async { |
| 254 | for entry in catalog.config.models where entry.preload { | 255 | for entry in catalog.config.models where entry.preload { |
| 255 | do { | 256 | do { |
| 256 | - let lease = try await acquire(entry.id) | 257 | + let lease = try await acquire(entry.id, kind: entry.kind) |
| 257 | await lease.release() | 258 | await lease.release() |
| 258 | } catch { | 259 | } catch { |
| 259 | logger.error("cannot preload \(entry.id): \(error)") | 260 | logger.error("cannot preload \(entry.id): \(error)") |
| @@ -281,17 +282,17 @@ public actor ModelManager { | |||
| 281 | 282 | ||
| 282 | /// Requests waiting for `name` (tests and diagnostics). | 283 | /// Requests waiting for `name` (tests and diagnostics). |
| 283 | func queueLength(_ name: String) throws -> Int { | 284 | func queueLength(_ name: String) throws -> Int { |
| 284 | - let key = try catalog.resolve(name).source.description | 285 | + let key = try catalog.resolve(name).slotKey |
| 285 | return slots[key]?.waiters.count ?? 0 | 286 | return slots[key]?.waiters.count ?? 0 |
| 286 | } | 287 | } |
| 287 | 288 | ||
| 288 | /// A request holds `name` right now (tests and diagnostics). | 289 | /// A request holds `name` right now (tests and diagnostics). |
| 289 | func isBusy(_ name: String) throws -> Bool { | 290 | func isBusy(_ name: String) throws -> Bool { |
| 290 | - let key = try catalog.resolve(name).source.description | 291 | + let key = try catalog.resolve(name).slotKey |
| 291 | return slots[key]?.busy ?? false | 292 | return slots[key]?.busy ?? false |
| 292 | } | 293 | } |
| 293 | 294 | ||
| 294 | - /// Sources of the models currently loaded, as `ModelReference.description`. | 295 | + /// Slot keys of the models currently loaded (``ResolvedModel/slotKey``). |
| 295 | public func loadedSources() -> Set<String> { | 296 | public func loadedSources() -> Set<String> { |
| 296 | Set(slots.filter { $0.value.engine != nil }.keys) | 297 | Set(slots.filter { $0.value.engine != nil }.keys) |
| 297 | } | 298 | } |
modified
Sources/RazorbillServer/ModelRoutes.swift +19 -6 | @@ -50,23 +50,36 @@ struct ModelRoutes { | ||
| 50 | 50 | let config = models.catalog.config |
| 51 | 51 | var result = config.models.map { entry in |
| 52 | 52 | ModelObject( |
| 53 | - id: entry.id, created: created, loaded: loaded.contains(entry.source.description), | |
| 53 | + id: entry.id, created: created, | |
| 54 | + loaded: loaded.contains( | |
| 55 | + ResolvedModel.slotKey(source: entry.source, kind: entry.kind)), | |
| 54 | 56 | kind: entry.kind.rawValue) |
| 55 | 57 | } |
| 56 | 58 | var listed = Set(result.map(\.id)) |
| 57 | 59 | let cached = ((try? models.catalog.store.list()) ?? []).filter(\.isLoadable).map(\.id) |
| 58 | 60 | // Loaded undeclared models pinned to a revision (`org/name@rev`) are not in the cache |
| 59 | 61 | // list; loaded declared models are already listed under their declared id. |
| 60 | - let declaredSources = Set(config.models.map(\.source.description)) | |
| 61 | - let loadedUndeclared = loaded.subtracting(declaredSources).sorted() | |
| 62 | - for id in cached + loadedUndeclared where listed.insert(id).inserted { | |
| 63 | - result.append( | |
| 64 | - ModelObject(id: id, created: created, loaded: loaded.contains(id), kind: "chat")) | |
| 62 | + let declared = Set( | |
| 63 | + config.models.map { ResolvedModel.slotKey(source: $0.source, kind: $0.kind) }) | |
| 64 | + let loadedUndeclared = loaded.subtracting(declared).sorted() | |
| 65 | + for key in cached + loadedUndeclared { | |
| 66 | + let (id, kind) = Self.split(key) | |
| 67 | + guard listed.insert(id).inserted else { continue } | |
| 68 | + let isLoaded = loaded.contains(id) || loaded.contains("\(id)#embedding") | |
| 69 | + result.append(ModelObject(id: id, created: created, loaded: isLoaded, kind: kind)) | |
| 65 | 70 | } |
| 66 | 71 | return result |
| 67 | 72 | } |
| 68 | 73 | } |
| 69 | 74 | |
| 75 | +extension ModelRoutes { | |
| 76 | + /// `org/name#embedding` → (`org/name`, `embedding`); a plain id is a chat model. | |
| 77 | + static func split(_ key: String) -> (id: String, kind: String) { | |
| 78 | + guard let hash = key.lastIndex(of: "#") else { return (key, "chat") } | |
| 79 | + return (String(key[..<hash]), String(key[key.index(after: hash)...])) | |
| 80 | + } | |
| 81 | +} | |
| 82 | + | |
| 70 | 83 | /// A JSON response encoded like every other razorbill answer (sorted keys). |
| 71 | 84 | func jsonResponse(_ value: some Encodable, status: HTTPResponse.Status = .ok) throws -> Response { |
| 72 | 85 | var headers = HTTPFields() |
| @@ -50,23 +50,36 @@ struct ModelRoutes { | |||
| 50 | let config = models.catalog.config | 50 | let config = models.catalog.config |
| 51 | var result = config.models.map { entry in | 51 | var result = config.models.map { entry in |
| 52 | ModelObject( | 52 | ModelObject( |
| 53 | - id: entry.id, created: created, loaded: loaded.contains(entry.source.description), | 53 | + id: entry.id, created: created, |
| 54 | + loaded: loaded.contains( | ||
| 55 | + ResolvedModel.slotKey(source: entry.source, kind: entry.kind)), | ||
| 54 | kind: entry.kind.rawValue) | 56 | kind: entry.kind.rawValue) |
| 55 | } | 57 | } |
| 56 | var listed = Set(result.map(\.id)) | 58 | var listed = Set(result.map(\.id)) |
| 57 | let cached = ((try? models.catalog.store.list()) ?? []).filter(\.isLoadable).map(\.id) | 59 | let cached = ((try? models.catalog.store.list()) ?? []).filter(\.isLoadable).map(\.id) |
| 58 | // Loaded undeclared models pinned to a revision (`org/name@rev`) are not in the cache | 60 | // Loaded undeclared models pinned to a revision (`org/name@rev`) are not in the cache |
| 59 | // list; loaded declared models are already listed under their declared id. | 61 | // list; loaded declared models are already listed under their declared id. |
| 60 | - let declaredSources = Set(config.models.map(\.source.description)) | 62 | + let declared = Set( |
| 61 | - let loadedUndeclared = loaded.subtracting(declaredSources).sorted() | 63 | + config.models.map { ResolvedModel.slotKey(source: $0.source, kind: $0.kind) }) |
| 62 | - for id in cached + loadedUndeclared where listed.insert(id).inserted { | 64 | + let loadedUndeclared = loaded.subtracting(declared).sorted() |
| 63 | - result.append( | 65 | + for key in cached + loadedUndeclared { |
| 64 | - ModelObject(id: id, created: created, loaded: loaded.contains(id), kind: "chat")) | 66 | + let (id, kind) = Self.split(key) |
| 67 | + guard listed.insert(id).inserted else { continue } | ||
| 68 | + let isLoaded = loaded.contains(id) || loaded.contains("\(id)#embedding") | ||
| 69 | + result.append(ModelObject(id: id, created: created, loaded: isLoaded, kind: kind)) | ||
| 65 | } | 70 | } |
| 66 | return result | 71 | return result |
| 67 | } | 72 | } |
| 68 | } | 73 | } |
| 69 | 74 | ||
| 75 | +extension ModelRoutes { | ||
| 76 | + /// `org/name#embedding` → (`org/name`, `embedding`); a plain id is a chat model. | ||
| 77 | + static func split(_ key: String) -> (id: String, kind: String) { | ||
| 78 | + guard let hash = key.lastIndex(of: "#") else { return (key, "chat") } | ||
| 79 | + return (String(key[..<hash]), String(key[key.index(after: hash)...])) | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 70 | /// A JSON response encoded like every other razorbill answer (sorted keys). | 83 | /// A JSON response encoded like every other razorbill answer (sorted keys). |
| 71 | func jsonResponse(_ value: some Encodable, status: HTTPResponse.Status = .ok) throws -> Response { | 84 | func jsonResponse(_ value: some Encodable, status: HTTPResponse.Status = .ok) throws -> Response { |
| 72 | var headers = HTTPFields() | 85 | var headers = HTTPFields() |
modified
Sources/RazorbillServer/RazorbillServer.swift +2 -1 | @@ -42,6 +42,7 @@ public enum RazorbillServer { | ||
| 42 | 42 | addHealthRoute(to: router) |
| 43 | 43 | ModelRoutes(models: models).add(to: router) |
| 44 | 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | + EmbeddingsRoute(models: models).add(to: router) | |
| 45 | 46 | return router |
| 46 | 47 | } |
| 47 | 48 | |
| @@ -52,7 +53,7 @@ public enum RazorbillServer { | ||
| 52 | 53 | ModelManager( |
| 53 | 54 | catalog: ModelCatalog(config: settings.config, store: store), |
| 54 | 55 | limits: settings.config.limits, logger: logger |
| 55 | - ) { try engines.make() } | |
| 56 | + ) { kind in try engines.make(kind: kind) } | |
| 56 | 57 | } |
| 57 | 58 | |
| 58 | 59 | /// The application, not started. `models` is preloaded, swept for idle models and unloaded |
| @@ -42,6 +42,7 @@ public enum RazorbillServer { | |||
| 42 | addHealthRoute(to: router) | 42 | addHealthRoute(to: router) |
| 43 | ModelRoutes(models: models).add(to: router) | 43 | ModelRoutes(models: models).add(to: router) |
| 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | 44 | ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 45 | + EmbeddingsRoute(models: models).add(to: router) | ||
| 45 | return router | 46 | return router |
| 46 | } | 47 | } |
| 47 | 48 | ||
| @@ -52,7 +53,7 @@ public enum RazorbillServer { | |||
| 52 | ModelManager( | 53 | ModelManager( |
| 53 | catalog: ModelCatalog(config: settings.config, store: store), | 54 | catalog: ModelCatalog(config: settings.config, store: store), |
| 54 | limits: settings.config.limits, logger: logger | 55 | limits: settings.config.limits, logger: logger |
| 55 | - ) { try engines.make() } | 56 | + ) { kind in try engines.make(kind: kind) } |
| 56 | } | 57 | } |
| 57 | 58 | ||
| 58 | /// The application, not started. `models` is preloaded, swept for idle models and unloaded | 59 | /// The application, not started. `models` is preloaded, swept for idle models and unloaded |
modified
Sources/rzb/main.swift +1 -1 | @@ -6,7 +6,7 @@ import RazorbillMLX | ||
| 6 | 6 | // fake engine, which answers "echo: …" and lets rzb run where MLX is missing. |
| 7 | 7 | var engines = EngineRegistry() |
| 8 | 8 | MLXSupport.register(into: &engines) |
| 9 | -engines.register("fake") { FakeEngine() } | |
| 9 | +engines.register("fake") { _ in FakeEngine() } | |
| 10 | 10 | |
| 11 | 11 | await CLIEnvironment.$current.withValue(.standard(engines: engines)) { |
| 12 | 12 | await Rzb.main() |
| @@ -6,7 +6,7 @@ import RazorbillMLX | |||
| 6 | // fake engine, which answers "echo: …" and lets rzb run where MLX is missing. | 6 | // fake engine, which answers "echo: …" and lets rzb run where MLX is missing. |
| 7 | var engines = EngineRegistry() | 7 | var engines = EngineRegistry() |
| 8 | MLXSupport.register(into: &engines) | 8 | MLXSupport.register(into: &engines) |
| 9 | -engines.register("fake") { FakeEngine() } | 9 | +engines.register("fake") { _ in FakeEngine() } |
| 10 | 10 | ||
| 11 | await CLIEnvironment.$current.withValue(.standard(engines: engines)) { | 11 | await CLIEnvironment.$current.withValue(.standard(engines: engines)) { |
| 12 | await Rzb.main() | 12 | await Rzb.main() |
modified
Tests/RazorbillCLITests/Harness.swift +1 -1 | @@ -63,7 +63,7 @@ struct World { | ||
| 63 | 63 | var environment: CLIEnvironment { |
| 64 | 64 | let engine = self.engine |
| 65 | 65 | var engines = EngineRegistry() |
| 66 | - engines.register("fake") { engine } | |
| 66 | + engines.register("fake") { _ in engine } | |
| 67 | 67 | let servers = self.servers |
| 68 | 68 | return CLIEnvironment( |
| 69 | 69 | engines: engines, console: console, |
| @@ -63,7 +63,7 @@ struct World { | |||
| 63 | var environment: CLIEnvironment { | 63 | var environment: CLIEnvironment { |
| 64 | let engine = self.engine | 64 | let engine = self.engine |
| 65 | var engines = EngineRegistry() | 65 | var engines = EngineRegistry() |
| 66 | - engines.register("fake") { engine } | 66 | + engines.register("fake") { _ in engine } |
| 67 | let servers = self.servers | 67 | let servers = self.servers |
| 68 | return CLIEnvironment( | 68 | return CLIEnvironment( |
| 69 | engines: engines, console: console, | 69 | engines: engines, console: console, |
modified
Tests/RazorbillCoreTests/EngineAndQuantityTests.swift +3 -3 | @@ -29,8 +29,8 @@ import Testing | ||
| 29 | 29 | @Suite struct EngineRegistryChoosesEngines { |
| 30 | 30 | @Test func firstRegisteredEngineIsTheDefault() throws { |
| 31 | 31 | var engines = EngineRegistry() |
| 32 | - engines.register("fake") { FakeEngine() } | |
| 33 | - engines.register("other") { FakeEngine() } | |
| 32 | + engines.register("fake") { _ in FakeEngine() } | |
| 33 | + engines.register("other") { _ in FakeEngine() } | |
| 34 | 34 | |
| 35 | 35 | #expect(engines.defaultName == "fake") |
| 36 | 36 | #expect(try engines.make().name == "fake") |
| @@ -39,7 +39,7 @@ import Testing | ||
| 39 | 39 | |
| 40 | 40 | @Test func unknownEngineListsTheAvailableOnes() { |
| 41 | 41 | var engines = EngineRegistry() |
| 42 | - engines.register("fake") { FakeEngine() } | |
| 42 | + engines.register("fake") { _ in FakeEngine() } | |
| 43 | 43 | #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { |
| 44 | 44 | try engines.make("mlx") |
| 45 | 45 | } |
| @@ -29,8 +29,8 @@ import Testing | |||
| 29 | @Suite struct EngineRegistryChoosesEngines { | 29 | @Suite struct EngineRegistryChoosesEngines { |
| 30 | @Test func firstRegisteredEngineIsTheDefault() throws { | 30 | @Test func firstRegisteredEngineIsTheDefault() throws { |
| 31 | var engines = EngineRegistry() | 31 | var engines = EngineRegistry() |
| 32 | - engines.register("fake") { FakeEngine() } | 32 | + engines.register("fake") { _ in FakeEngine() } |
| 33 | - engines.register("other") { FakeEngine() } | 33 | + engines.register("other") { _ in FakeEngine() } |
| 34 | 34 | ||
| 35 | #expect(engines.defaultName == "fake") | 35 | #expect(engines.defaultName == "fake") |
| 36 | #expect(try engines.make().name == "fake") | 36 | #expect(try engines.make().name == "fake") |
| @@ -39,7 +39,7 @@ import Testing | |||
| 39 | 39 | ||
| 40 | @Test func unknownEngineListsTheAvailableOnes() { | 40 | @Test func unknownEngineListsTheAvailableOnes() { |
| 41 | var engines = EngineRegistry() | 41 | var engines = EngineRegistry() |
| 42 | - engines.register("fake") { FakeEngine() } | 42 | + engines.register("fake") { _ in FakeEngine() } |
| 43 | #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { | 43 | #expect(throws: EngineRegistry.UnknownEngine(name: "mlx", available: ["fake"])) { |
| 44 | try engines.make("mlx") | 44 | try engines.make("mlx") |
| 45 | } | 45 | } |
modified
Tests/RazorbillMLXTests/ChatSmokeTests.swift +1 -1 | @@ -18,7 +18,7 @@ struct ChatSmokeTests { | ||
| 18 | 18 | |
| 19 | 19 | let models = ModelManager( |
| 20 | 20 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() |
| 21 | - ) { MLXEngine() } | |
| 21 | + ) { _ in MLXEngine() } | |
| 22 | 22 | |
| 23 | 23 | func route() -> ChatCompletionRoute { |
| 24 | 24 | ChatCompletionRoute(models: models) |
| @@ -18,7 +18,7 @@ struct ChatSmokeTests { | |||
| 18 | 18 | ||
| 19 | let models = ModelManager( | 19 | let models = ModelManager( |
| 20 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | 20 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() |
| 21 | - ) { MLXEngine() } | 21 | + ) { _ in MLXEngine() } |
| 22 | 22 | ||
| 23 | func route() -> ChatCompletionRoute { | 23 | func route() -> ChatCompletionRoute { |
| 24 | ChatCompletionRoute(models: models) | 24 | ChatCompletionRoute(models: models) |
modified
Tests/RazorbillMLXTests/ConstrainedSmokeTests.swift +1 -1 | @@ -12,7 +12,7 @@ import Testing | ||
| 12 | 12 | struct ConstrainedSmokeTests { |
| 13 | 13 | let models = ModelManager( |
| 14 | 14 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() |
| 15 | - ) { MLXEngine() } | |
| 15 | + ) { _ in MLXEngine() } | |
| 16 | 16 | |
| 17 | 17 | struct Person: Decodable { |
| 18 | 18 | let name: String |
| @@ -12,7 +12,7 @@ import Testing | |||
| 12 | struct ConstrainedSmokeTests { | 12 | struct ConstrainedSmokeTests { |
| 13 | let models = ModelManager( | 13 | let models = ModelManager( |
| 14 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | 14 | catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() |
| 15 | - ) { MLXEngine() } | 15 | + ) { _ in MLXEngine() } |
| 16 | 16 | ||
| 17 | struct Person: Decodable { | 17 | struct Person: Decodable { |
| 18 | let name: String | 18 | let name: String |
added
Tests/RazorbillMLXTests/EmbeddingSmokeTests.swift +104 -0 | new file mode 100644 | ||
| @@ -0,0 +1,104 @@ | ||
| 1 | +#if canImport(MLXEmbedders) | |
| 2 | +import Foundation | |
| 3 | +import RazorbillCore | |
| 4 | +import Testing | |
| 5 | + | |
| 6 | +@testable import RazorbillMLX | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// Reference values computed with sentence-transformers 5 (CPU, normalize_embeddings=True) for | |
| 10 | +/// four sentences; the MLX embedder must agree within 1e-3 (ticket #42). | |
| 11 | +struct EmbeddingReference: Sendable { | |
| 12 | + let model: String | |
| 13 | + let dimension: Int | |
| 14 | + /// Cosine similarity of sentence pairs, keyed "i-j". | |
| 15 | + let cosines: [String: Double] | |
| 16 | + | |
| 17 | + static let sentences = [ | |
| 18 | + "The cat sits on the mat.", | |
| 19 | + "A feline is resting on a rug.", | |
| 20 | + "Stock markets fell sharply today.", | |
| 21 | + "Il pleut beaucoup à Lyon en novembre.", | |
| 22 | + ] | |
| 23 | + | |
| 24 | + static let all = [ | |
| 25 | + EmbeddingReference( | |
| 26 | + model: "sentence-transformers/all-MiniLM-L6-v2", dimension: 384, | |
| 27 | + cosines: [ | |
| 28 | + "0-1": 0.57349, "0-2": 0.046225, "0-3": -0.051274, "1-2": 0.056358, | |
| 29 | + "1-3": -0.040675, "2-3": -0.03981, | |
| 30 | + ]), | |
| 31 | + EmbeddingReference( | |
| 32 | + model: "BAAI/bge-small-en-v1.5", dimension: 384, | |
| 33 | + cosines: [ | |
| 34 | + "0-1": 0.754619, "0-2": 0.324302, "0-3": 0.328419, "1-2": 0.313784, | |
| 35 | + "1-3": 0.439483, "2-3": 0.401721, | |
| 36 | + ]), | |
| 37 | + ] | |
| 38 | + | |
| 39 | + var isCached: Bool { | |
| 40 | + ModelStore().isAvailableLocally(.huggingFace(id: model, revision: "main")) | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +@Suite(.serialized) | |
| 45 | +struct EmbeddingSmokeTests { | |
| 46 | + @Test(arguments: EmbeddingReference.all) | |
| 47 | + func cosinesMatchSentenceTransformers(_ reference: EmbeddingReference) async throws { | |
| 48 | + try #require(reference.isCached, "run: rzb models pull \(reference.model)") | |
| 49 | + let embedder = MLXEmbedder() | |
| 50 | + try await embedder.load( | |
| 51 | + .huggingFace(id: reference.model, revision: "main"), offline: true | |
| 52 | + ) { _ in } | |
| 53 | + let result = try await embedder.embed(EmbeddingReference.sentences) | |
| 54 | + #expect( | |
| 55 | + result.vectors.count == 4 | |
| 56 | + && result.vectors.allSatisfy { $0.count == reference.dimension }) | |
| 57 | + for (pair, expected) in reference.cosines { | |
| 58 | + let indices = pair.split(separator: "-").compactMap { Int($0) } | |
| 59 | + let left = result.vectors[indices[0]] | |
| 60 | + let right = result.vectors[indices[1]] | |
| 61 | + let cosine = zip(left, right).reduce(Double(0)) { $0 + Double($1.0 * $1.1) } | |
| 62 | + #expect( | |
| 63 | + abs(cosine - expected) < 1e-3, | |
| 64 | + "\(reference.model) \(pair): \(cosine) vs \(expected)") | |
| 65 | + } | |
| 66 | + #expect(result.promptTokens > 20) | |
| 67 | + } | |
| 68 | + | |
| 69 | + @Test func tooLongInputIsA400Error() async throws { | |
| 70 | + let reference = EmbeddingReference.all[0] | |
| 71 | + try #require(reference.isCached) | |
| 72 | + let embedder = MLXEmbedder() | |
| 73 | + let model = ModelReference.huggingFace(id: reference.model, revision: "main") | |
| 74 | + try await embedder.load(model, offline: true) { _ in } | |
| 75 | + let long = String(repeating: "word ", count: 2000) | |
| 76 | + await #expect(throws: MLXEmbedder.InputTooLong.self) { | |
| 77 | + try await embedder.embed(["short", long]) | |
| 78 | + } | |
| 79 | + } | |
| 80 | + | |
| 81 | + @Test func serverEndpointWithARealModel() async throws { | |
| 82 | + let reference = EmbeddingReference.all[1] | |
| 83 | + try #require(reference.isCached) | |
| 84 | + let models = ModelManager( | |
| 85 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), | |
| 86 | + limits: ServerLimits() | |
| 87 | + ) { kind -> any InferenceEngine in | |
| 88 | + kind == .embedding ? MLXEmbedder() : MLXEngine() | |
| 89 | + } | |
| 90 | + let request = try JSONDecoder().decode( | |
| 91 | + EmbeddingsRequest.self, | |
| 92 | + from: Data(#"{"model":"\#(reference.model)","input":["a","b"],"dimensions":64}"#.utf8)) | |
| 93 | + let embeddings = try await models.withModel(reference.model, kind: .embedding) { lease in | |
| 94 | + try await lease.engine.embed(try request.texts()) | |
| 95 | + } | |
| 96 | + let response = try EmbeddingsRoute.response(embeddings, for: request) | |
| 97 | + guard case .floats(let vector) = response.data[0].embedding else { | |
| 98 | + Issue.record("not floats") | |
| 99 | + return | |
| 100 | + } | |
| 101 | + #expect(vector.count == 64) | |
| 102 | + } | |
| 103 | +} | |
| 104 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,104 @@ | |||
| 1 | +#if canImport(MLXEmbedders) | ||
| 2 | +import Foundation | ||
| 3 | +import RazorbillCore | ||
| 4 | +import Testing | ||
| 5 | + | ||
| 6 | +@testable import RazorbillMLX | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// Reference values computed with sentence-transformers 5 (CPU, normalize_embeddings=True) for | ||
| 10 | +/// four sentences; the MLX embedder must agree within 1e-3 (ticket #42). | ||
| 11 | +struct EmbeddingReference: Sendable { | ||
| 12 | + let model: String | ||
| 13 | + let dimension: Int | ||
| 14 | + /// Cosine similarity of sentence pairs, keyed "i-j". | ||
| 15 | + let cosines: [String: Double] | ||
| 16 | + | ||
| 17 | + static let sentences = [ | ||
| 18 | + "The cat sits on the mat.", | ||
| 19 | + "A feline is resting on a rug.", | ||
| 20 | + "Stock markets fell sharply today.", | ||
| 21 | + "Il pleut beaucoup à Lyon en novembre.", | ||
| 22 | + ] | ||
| 23 | + | ||
| 24 | + static let all = [ | ||
| 25 | + EmbeddingReference( | ||
| 26 | + model: "sentence-transformers/all-MiniLM-L6-v2", dimension: 384, | ||
| 27 | + cosines: [ | ||
| 28 | + "0-1": 0.57349, "0-2": 0.046225, "0-3": -0.051274, "1-2": 0.056358, | ||
| 29 | + "1-3": -0.040675, "2-3": -0.03981, | ||
| 30 | + ]), | ||
| 31 | + EmbeddingReference( | ||
| 32 | + model: "BAAI/bge-small-en-v1.5", dimension: 384, | ||
| 33 | + cosines: [ | ||
| 34 | + "0-1": 0.754619, "0-2": 0.324302, "0-3": 0.328419, "1-2": 0.313784, | ||
| 35 | + "1-3": 0.439483, "2-3": 0.401721, | ||
| 36 | + ]), | ||
| 37 | + ] | ||
| 38 | + | ||
| 39 | + var isCached: Bool { | ||
| 40 | + ModelStore().isAvailableLocally(.huggingFace(id: model, revision: "main")) | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +@Suite(.serialized) | ||
| 45 | +struct EmbeddingSmokeTests { | ||
| 46 | + @Test(arguments: EmbeddingReference.all) | ||
| 47 | + func cosinesMatchSentenceTransformers(_ reference: EmbeddingReference) async throws { | ||
| 48 | + try #require(reference.isCached, "run: rzb models pull \(reference.model)") | ||
| 49 | + let embedder = MLXEmbedder() | ||
| 50 | + try await embedder.load( | ||
| 51 | + .huggingFace(id: reference.model, revision: "main"), offline: true | ||
| 52 | + ) { _ in } | ||
| 53 | + let result = try await embedder.embed(EmbeddingReference.sentences) | ||
| 54 | + #expect( | ||
| 55 | + result.vectors.count == 4 | ||
| 56 | + && result.vectors.allSatisfy { $0.count == reference.dimension }) | ||
| 57 | + for (pair, expected) in reference.cosines { | ||
| 58 | + let indices = pair.split(separator: "-").compactMap { Int($0) } | ||
| 59 | + let left = result.vectors[indices[0]] | ||
| 60 | + let right = result.vectors[indices[1]] | ||
| 61 | + let cosine = zip(left, right).reduce(Double(0)) { $0 + Double($1.0 * $1.1) } | ||
| 62 | + #expect( | ||
| 63 | + abs(cosine - expected) < 1e-3, | ||
| 64 | + "\(reference.model) \(pair): \(cosine) vs \(expected)") | ||
| 65 | + } | ||
| 66 | + #expect(result.promptTokens > 20) | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + @Test func tooLongInputIsA400Error() async throws { | ||
| 70 | + let reference = EmbeddingReference.all[0] | ||
| 71 | + try #require(reference.isCached) | ||
| 72 | + let embedder = MLXEmbedder() | ||
| 73 | + let model = ModelReference.huggingFace(id: reference.model, revision: "main") | ||
| 74 | + try await embedder.load(model, offline: true) { _ in } | ||
| 75 | + let long = String(repeating: "word ", count: 2000) | ||
| 76 | + await #expect(throws: MLXEmbedder.InputTooLong.self) { | ||
| 77 | + try await embedder.embed(["short", long]) | ||
| 78 | + } | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + @Test func serverEndpointWithARealModel() async throws { | ||
| 82 | + let reference = EmbeddingReference.all[1] | ||
| 83 | + try #require(reference.isCached) | ||
| 84 | + let models = ModelManager( | ||
| 85 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), | ||
| 86 | + limits: ServerLimits() | ||
| 87 | + ) { kind -> any InferenceEngine in | ||
| 88 | + kind == .embedding ? MLXEmbedder() : MLXEngine() | ||
| 89 | + } | ||
| 90 | + let request = try JSONDecoder().decode( | ||
| 91 | + EmbeddingsRequest.self, | ||
| 92 | + from: Data(#"{"model":"\#(reference.model)","input":["a","b"],"dimensions":64}"#.utf8)) | ||
| 93 | + let embeddings = try await models.withModel(reference.model, kind: .embedding) { lease in | ||
| 94 | + try await lease.engine.embed(try request.texts()) | ||
| 95 | + } | ||
| 96 | + let response = try EmbeddingsRoute.response(embeddings, for: request) | ||
| 97 | + guard case .floats(let vector) = response.data[0].embedding else { | ||
| 98 | + Issue.record("not floats") | ||
| 99 | + return | ||
| 100 | + } | ||
| 101 | + #expect(vector.count == 64) | ||
| 102 | + } | ||
| 103 | +} | ||
| 104 | +#endif | ||
added
Tests/RazorbillServerTests/EmbeddingsTests.swift +132 -0 | new file mode 100644 | ||
| @@ -0,0 +1,132 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import RazorbillCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// POSTs `json` to `/v1/embeddings`. | |
| 10 | +func postEmbeddings(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | |
| 11 | + try await client.execute( | |
| 12 | + uri: "/v1/embeddings", method: .post, headers: [.contentType: "application/json"], | |
| 13 | + body: ByteBuffer(string: json)) | |
| 14 | +} | |
| 15 | + | |
| 16 | +@Suite struct EmbeddingsTests { | |
| 17 | + @Test func answersInOpenAIShape() async throws { | |
| 18 | + let engines = TestEngines() | |
| 19 | + try await withLiveServer(engines: engines) { client in | |
| 20 | + let response = try await postEmbeddings( | |
| 21 | + client, #"{"model":"org/embed","input":["one two","three"]}"#) | |
| 22 | + #expect(response.status == .ok) | |
| 23 | + let body = try json(response) | |
| 24 | + #expect(body["object"] as? String == "list" && body["model"] as? String == "org/embed") | |
| 25 | + let data = try #require(body["data"] as? [[String: Any]]) | |
| 26 | + #expect(data.map { $0["index"] as? Int } == [0, 1]) | |
| 27 | + #expect(data.allSatisfy { $0["object"] as? String == "embedding" }) | |
| 28 | + let vector = try #require(data[0]["embedding"] as? [Double]) | |
| 29 | + #expect(vector.count == 8) | |
| 30 | + #expect(abs(vector.reduce(0) { $0 + $1 * $1 } - 1) < 1e-5) // normalised | |
| 31 | + #expect((body["usage"] as? [String: Int]) == ["prompt_tokens": 3, "total_tokens": 3]) | |
| 32 | + } | |
| 33 | + #expect(engines.events.first == "load org/embed" && engines.loads == 1) | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Test func singleStringInput() async throws { | |
| 37 | + try await withLiveServer { client in | |
| 38 | + let body = try json( | |
| 39 | + try await postEmbeddings(client, #"{"model":"org/e","input":"hello"}"#)) | |
| 40 | + #expect((body["data"] as? [Any])?.count == 1) | |
| 41 | + } | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Test func dimensionsTruncateAndRenormalise() async throws { | |
| 45 | + try await withLiveServer { client in | |
| 46 | + let body = try json( | |
| 47 | + try await postEmbeddings( | |
| 48 | + client, #"{"model":"org/e","input":"hello","dimensions":3}"#)) | |
| 49 | + let vector = try #require( | |
| 50 | + ((body["data"] as? [[String: Any]])?.first)?["embedding"] as? [Double]) | |
| 51 | + #expect(vector.count == 3) | |
| 52 | + #expect(abs(vector.reduce(0) { $0 + $1 * $1 } - 1) < 1e-5) | |
| 53 | + } | |
| 54 | + } | |
| 55 | + | |
| 56 | + @Test func base64IsLittleEndianFloat32() async throws { | |
| 57 | + let engines = TestEngines() | |
| 58 | + try await withLiveServer(engines: engines) { client in | |
| 59 | + let body = try json( | |
| 60 | + try await postEmbeddings( | |
| 61 | + client, #"{"model":"org/e","input":"hello","encoding_format":"base64"}"#)) | |
| 62 | + let text = try #require( | |
| 63 | + ((body["data"] as? [[String: Any]])?.first)?["embedding"] as? String) | |
| 64 | + let data = try #require(Data(base64Encoded: text)) | |
| 65 | + #expect(data.count == 8 * 4) | |
| 66 | + let floats = data.withUnsafeBytes { raw in | |
| 67 | + (0 ..< 8).map { | |
| 68 | + Float( | |
| 69 | + bitPattern: UInt32( | |
| 70 | + littleEndian: raw.load(fromByteOffset: $0 * 4, as: UInt32.self))) | |
| 71 | + } | |
| 72 | + } | |
| 73 | + let expected = try await engines.fake.embed(["hello"]).vectors[0] | |
| 74 | + #expect(floats == expected) | |
| 75 | + } | |
| 76 | + } | |
| 77 | + | |
| 78 | + static let invalid: [(json: String, param: String)] = [ | |
| 79 | + (#"{"model":"org/e","input":[]}"#, "input"), | |
| 80 | + (#"{"model":"org/e","input":["a",""]}"#, "input"), | |
| 81 | + (#"{"model":"org/e","input":[1,2,3]}"#, "input"), | |
| 82 | + (#"{"model":"org/e","input":"a","encoding_format":"int8"}"#, "encoding_format"), | |
| 83 | + (#"{"model":"org/e","input":"a","dimensions":0}"#, "dimensions"), | |
| 84 | + (#"{"model":"org/e","input":"a","dimensions":9}"#, "dimensions"), | |
| 85 | + ] | |
| 86 | + | |
| 87 | + @Test(arguments: invalid) | |
| 88 | + func invalidRequestsAre400s(json body: String, param: String) async throws { | |
| 89 | + try await withLiveServer { client in | |
| 90 | + let response = try await postEmbeddings(client, body) | |
| 91 | + #expect(response.status == .badRequest) | |
| 92 | + let error = try ErrorBody(response).error | |
| 93 | + #expect(error.param == param) | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 97 | + @Test func modelKindsAreNotMixed() async throws { | |
| 98 | + var settings = testSettings | |
| 99 | + settings.config = ServerConfig(models: [ | |
| 100 | + ModelEntry(id: "chat", source: .huggingFace(id: "org/c", revision: "main")), | |
| 101 | + ModelEntry( | |
| 102 | + id: "embed", source: .huggingFace(id: "org/e", revision: "main"), kind: .embedding), | |
| 103 | + ]) | |
| 104 | + try await withLiveServer(settings) { client in | |
| 105 | + let wrong = try await postEmbeddings(client, #"{"model":"chat","input":"x"}"#) | |
| 106 | + #expect(wrong.status == .badRequest) | |
| 107 | + let error = try ErrorBody(wrong).error | |
| 108 | + #expect(error.param == "model" && error.message.contains("is a chat model")) | |
| 109 | + } | |
| 110 | + try await withLiveServer(settings) { client in | |
| 111 | + let response = try await post(client, simpleRequest("embed")) | |
| 112 | + #expect(response.status == .badRequest) | |
| 113 | + } | |
| 114 | + } | |
| 115 | + | |
| 116 | + @Test func chatAndEmbeddingLoadsOfOneRepositoryAreDistinct() async throws { | |
| 117 | + let engines = TestEngines() | |
| 118 | + var settings = testSettings | |
| 119 | + settings.config.limits.maxLoadedModels = 2 | |
| 120 | + let models = testModels(settings, engines: engines) | |
| 121 | + try await models.withModel("org/m") { _ in } | |
| 122 | + try await models.withModel("org/m", kind: .embedding) { _ in } | |
| 123 | + #expect(await models.loadedSources() == ["org/m", "org/m#embedding"]) | |
| 124 | + #expect(engines.loads == 2) | |
| 125 | + } | |
| 126 | + | |
| 127 | + @Test func truncationAndBase64Helpers() { | |
| 128 | + let embeddings = Embeddings(vectors: [[3, 4, 12]], promptTokens: 1) | |
| 129 | + #expect(embeddings.truncated(to: 2).vectors == [[0.6, 0.8]]) | |
| 130 | + #expect(Embeddings.base64([1]) == "AACAPw==") // 1.0f little-endian: 00 00 80 3F | |
| 131 | + } | |
| 132 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,132 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import RazorbillCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// POSTs `json` to `/v1/embeddings`. | ||
| 10 | +func postEmbeddings(_ client: any TestClientProtocol, _ json: String) async throws -> TestResponse { | ||
| 11 | + try await client.execute( | ||
| 12 | + uri: "/v1/embeddings", method: .post, headers: [.contentType: "application/json"], | ||
| 13 | + body: ByteBuffer(string: json)) | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +@Suite struct EmbeddingsTests { | ||
| 17 | + @Test func answersInOpenAIShape() async throws { | ||
| 18 | + let engines = TestEngines() | ||
| 19 | + try await withLiveServer(engines: engines) { client in | ||
| 20 | + let response = try await postEmbeddings( | ||
| 21 | + client, #"{"model":"org/embed","input":["one two","three"]}"#) | ||
| 22 | + #expect(response.status == .ok) | ||
| 23 | + let body = try json(response) | ||
| 24 | + #expect(body["object"] as? String == "list" && body["model"] as? String == "org/embed") | ||
| 25 | + let data = try #require(body["data"] as? [[String: Any]]) | ||
| 26 | + #expect(data.map { $0["index"] as? Int } == [0, 1]) | ||
| 27 | + #expect(data.allSatisfy { $0["object"] as? String == "embedding" }) | ||
| 28 | + let vector = try #require(data[0]["embedding"] as? [Double]) | ||
| 29 | + #expect(vector.count == 8) | ||
| 30 | + #expect(abs(vector.reduce(0) { $0 + $1 * $1 } - 1) < 1e-5) // normalised | ||
| 31 | + #expect((body["usage"] as? [String: Int]) == ["prompt_tokens": 3, "total_tokens": 3]) | ||
| 32 | + } | ||
| 33 | + #expect(engines.events.first == "load org/embed" && engines.loads == 1) | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + @Test func singleStringInput() async throws { | ||
| 37 | + try await withLiveServer { client in | ||
| 38 | + let body = try json( | ||
| 39 | + try await postEmbeddings(client, #"{"model":"org/e","input":"hello"}"#)) | ||
| 40 | + #expect((body["data"] as? [Any])?.count == 1) | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + @Test func dimensionsTruncateAndRenormalise() async throws { | ||
| 45 | + try await withLiveServer { client in | ||
| 46 | + let body = try json( | ||
| 47 | + try await postEmbeddings( | ||
| 48 | + client, #"{"model":"org/e","input":"hello","dimensions":3}"#)) | ||
| 49 | + let vector = try #require( | ||
| 50 | + ((body["data"] as? [[String: Any]])?.first)?["embedding"] as? [Double]) | ||
| 51 | + #expect(vector.count == 3) | ||
| 52 | + #expect(abs(vector.reduce(0) { $0 + $1 * $1 } - 1) < 1e-5) | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + @Test func base64IsLittleEndianFloat32() async throws { | ||
| 57 | + let engines = TestEngines() | ||
| 58 | + try await withLiveServer(engines: engines) { client in | ||
| 59 | + let body = try json( | ||
| 60 | + try await postEmbeddings( | ||
| 61 | + client, #"{"model":"org/e","input":"hello","encoding_format":"base64"}"#)) | ||
| 62 | + let text = try #require( | ||
| 63 | + ((body["data"] as? [[String: Any]])?.first)?["embedding"] as? String) | ||
| 64 | + let data = try #require(Data(base64Encoded: text)) | ||
| 65 | + #expect(data.count == 8 * 4) | ||
| 66 | + let floats = data.withUnsafeBytes { raw in | ||
| 67 | + (0 ..< 8).map { | ||
| 68 | + Float( | ||
| 69 | + bitPattern: UInt32( | ||
| 70 | + littleEndian: raw.load(fromByteOffset: $0 * 4, as: UInt32.self))) | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + let expected = try await engines.fake.embed(["hello"]).vectors[0] | ||
| 74 | + #expect(floats == expected) | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + static let invalid: [(json: String, param: String)] = [ | ||
| 79 | + (#"{"model":"org/e","input":[]}"#, "input"), | ||
| 80 | + (#"{"model":"org/e","input":["a",""]}"#, "input"), | ||
| 81 | + (#"{"model":"org/e","input":[1,2,3]}"#, "input"), | ||
| 82 | + (#"{"model":"org/e","input":"a","encoding_format":"int8"}"#, "encoding_format"), | ||
| 83 | + (#"{"model":"org/e","input":"a","dimensions":0}"#, "dimensions"), | ||
| 84 | + (#"{"model":"org/e","input":"a","dimensions":9}"#, "dimensions"), | ||
| 85 | + ] | ||
| 86 | + | ||
| 87 | + @Test(arguments: invalid) | ||
| 88 | + func invalidRequestsAre400s(json body: String, param: String) async throws { | ||
| 89 | + try await withLiveServer { client in | ||
| 90 | + let response = try await postEmbeddings(client, body) | ||
| 91 | + #expect(response.status == .badRequest) | ||
| 92 | + let error = try ErrorBody(response).error | ||
| 93 | + #expect(error.param == param) | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + @Test func modelKindsAreNotMixed() async throws { | ||
| 98 | + var settings = testSettings | ||
| 99 | + settings.config = ServerConfig(models: [ | ||
| 100 | + ModelEntry(id: "chat", source: .huggingFace(id: "org/c", revision: "main")), | ||
| 101 | + ModelEntry( | ||
| 102 | + id: "embed", source: .huggingFace(id: "org/e", revision: "main"), kind: .embedding), | ||
| 103 | + ]) | ||
| 104 | + try await withLiveServer(settings) { client in | ||
| 105 | + let wrong = try await postEmbeddings(client, #"{"model":"chat","input":"x"}"#) | ||
| 106 | + #expect(wrong.status == .badRequest) | ||
| 107 | + let error = try ErrorBody(wrong).error | ||
| 108 | + #expect(error.param == "model" && error.message.contains("is a chat model")) | ||
| 109 | + } | ||
| 110 | + try await withLiveServer(settings) { client in | ||
| 111 | + let response = try await post(client, simpleRequest("embed")) | ||
| 112 | + #expect(response.status == .badRequest) | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + @Test func chatAndEmbeddingLoadsOfOneRepositoryAreDistinct() async throws { | ||
| 117 | + let engines = TestEngines() | ||
| 118 | + var settings = testSettings | ||
| 119 | + settings.config.limits.maxLoadedModels = 2 | ||
| 120 | + let models = testModels(settings, engines: engines) | ||
| 121 | + try await models.withModel("org/m") { _ in } | ||
| 122 | + try await models.withModel("org/m", kind: .embedding) { _ in } | ||
| 123 | + #expect(await models.loadedSources() == ["org/m", "org/m#embedding"]) | ||
| 124 | + #expect(engines.loads == 2) | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + @Test func truncationAndBase64Helpers() { | ||
| 128 | + let embeddings = Embeddings(vectors: [[3, 4, 12]], promptTokens: 1) | ||
| 129 | + #expect(embeddings.truncated(to: 2).vectors == [[0.6, 0.8]]) | ||
| 130 | + #expect(Embeddings.base64([1]) == "AACAPw==") // 1.0f little-endian: 00 00 80 3F | ||
| 131 | + } | ||
| 132 | +} | ||
modified
Tests/RazorbillServerTests/ModelManagerTests.swift +5 -1 | @@ -44,7 +44,7 @@ final class TestEngines: @unchecked Sendable { | ||
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 46 | var make: ModelManager.EngineFactory { |
| 47 | - { [self] in Engine(owner: self) } | |
| 47 | + { [self] _ in Engine(owner: self) } | |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | final class Engine: InferenceEngine, @unchecked Sendable { |
| @@ -78,6 +78,10 @@ final class TestEngines: @unchecked Sendable { | ||
| 78 | 78 | func unload() async { |
| 79 | 79 | owner.record("unload \(lock.withLock { model })") |
| 80 | 80 | } |
| 81 | + | |
| 82 | + func embed(_ texts: [String]) async throws -> Embeddings { | |
| 83 | + try await owner.fake.embed(texts) | |
| 84 | + } | |
| 81 | 85 | } |
| 82 | 86 | } |
| 83 | 87 | |
| @@ -44,7 +44,7 @@ final class TestEngines: @unchecked Sendable { | |||
| 44 | } | 44 | } |
| 45 | 45 | ||
| 46 | var make: ModelManager.EngineFactory { | 46 | var make: ModelManager.EngineFactory { |
| 47 | - { [self] in Engine(owner: self) } | 47 | + { [self] _ in Engine(owner: self) } |
| 48 | } | 48 | } |
| 49 | 49 | ||
| 50 | final class Engine: InferenceEngine, @unchecked Sendable { | 50 | final class Engine: InferenceEngine, @unchecked Sendable { |
| @@ -78,6 +78,10 @@ final class TestEngines: @unchecked Sendable { | |||
| 78 | func unload() async { | 78 | func unload() async { |
| 79 | owner.record("unload \(lock.withLock { model })") | 79 | owner.record("unload \(lock.withLock { model })") |
| 80 | } | 80 | } |
| 81 | + | ||
| 82 | + func embed(_ texts: [String]) async throws -> Embeddings { | ||
| 83 | + try await owner.fake.embed(texts) | ||
| 84 | + } | ||
| 81 | } | 85 | } |
| 82 | } | 86 | } |
| 83 | 87 | ||
modified
examples/server.yaml +3 -0 | @@ -29,6 +29,9 @@ models: | ||
| 29 | 29 | preload: false |
| 30 | 30 | defaults: { thinking: true, thinking_budget: 512 } |
| 31 | 31 | locked: { max_tokens: 4096 } |
| 32 | + # - id: embed # for /v1/embeddings | |
| 33 | + # source: BAAI/bge-small-en-v1.5 | |
| 34 | + # kind: embedding | |
| 32 | 35 | # - id: local |
| 33 | 36 | # path: ~/models/my-mlx-model # a model already on disk |
| 34 | 37 | |
| @@ -29,6 +29,9 @@ models: | |||
| 29 | preload: false | 29 | preload: false |
| 30 | defaults: { thinking: true, thinking_budget: 512 } | 30 | defaults: { thinking: true, thinking_budget: 512 } |
| 31 | locked: { max_tokens: 4096 } | 31 | locked: { max_tokens: 4096 } |
| 32 | + # - id: embed # for /v1/embeddings | ||
| 33 | + # source: BAAI/bge-small-en-v1.5 | ||
| 34 | + # kind: embedding | ||
| 32 | # - id: local | 35 | # - id: local |
| 33 | # path: ~/models/my-mlx-model # a model already on disk | 36 | # path: ~/models/my-mlx-model # a model already on disk |
| 34 | 37 | ||