cembedding 0.9.1__tar.gz → 0.9.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {cembedding-0.9.1 → cembedding-0.9.2}/Dockerfile +1 -1
  2. {cembedding-0.9.1 → cembedding-0.9.2}/PKG-INFO +17 -15
  3. {cembedding-0.9.1 → cembedding-0.9.2}/README.md +16 -14
  4. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/__init__.py +1 -1
  5. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/download_model.py +7 -1
  6. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/server.py +46 -7
  7. cembedding-0.9.2/cloto-connector.json +148 -0
  8. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_batch_coalescing.py +164 -0
  9. cembedding-0.9.2/tests/test_download_model_default.py +40 -0
  10. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_token_info.py +2 -0
  11. cembedding-0.9.1/cloto-connector.json +0 -148
  12. {cembedding-0.9.1 → cembedding-0.9.2}/.dockerignore +0 -0
  13. {cembedding-0.9.1 → cembedding-0.9.2}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  14. {cembedding-0.9.1 → cembedding-0.9.2}/.github/ISSUE_TEMPLATE/config.yml +0 -0
  15. {cembedding-0.9.1 → cembedding-0.9.2}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  16. {cembedding-0.9.1 → cembedding-0.9.2}/.github/workflows/ci.yml +0 -0
  17. {cembedding-0.9.1 → cembedding-0.9.2}/.github/workflows/publish.yml +0 -0
  18. {cembedding-0.9.1 → cembedding-0.9.2}/.gitignore +0 -0
  19. {cembedding-0.9.1 → cembedding-0.9.2}/LICENSE +0 -0
  20. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/__main__.py +0 -0
  21. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/_vendored_mcp_common/__init__.py +0 -0
  22. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/_vendored_mcp_common/mcp_utils.py +0 -0
  23. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/_vendored_mcp_common/validation.py +0 -0
  24. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/auth.py +0 -0
  25. {cembedding-0.9.1 → cembedding-0.9.2}/cembedding/sidecar.py +0 -0
  26. {cembedding-0.9.1 → cembedding-0.9.2}/conftest.py +0 -0
  27. {cembedding-0.9.1 → cembedding-0.9.2}/docs/CONTIGUOUS_SIDECAR_DESIGN.md +0 -0
  28. {cembedding-0.9.1 → cembedding-0.9.2}/pyproject.toml +0 -0
  29. {cembedding-0.9.1 → cembedding-0.9.2}/scripts/backfill_embedding_index.py +0 -0
  30. {cembedding-0.9.1 → cembedding-0.9.2}/scripts/bench_sidecar_startup.py +0 -0
  31. {cembedding-0.9.1 → cembedding-0.9.2}/server.py +0 -0
  32. {cembedding-0.9.1 → cembedding-0.9.2}/skills/cembedding/SKILL.md +0 -0
  33. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_auth.py +0 -0
  34. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_backfill.py +0 -0
  35. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_capabilities.py +0 -0
  36. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_http_bind.py +0 -0
  37. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_model_variants.py +0 -0
  38. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_onnx_padding.py +0 -0
  39. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_ort_session_options.py +0 -0
  40. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_sidecar.py +0 -0
  41. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_vector_index.py +0 -0
  42. {cembedding-0.9.1 → cembedding-0.9.2}/tests/test_version_surface.py +0 -0
@@ -20,7 +20,7 @@
20
20
  # once, before anything depends on the service:
21
21
  #
22
22
  # docker run --rm -v cembedding-data:/data <image> \
23
- # cembedding-download-model --model jina-v5-nano
23
+ # cembedding-download-model --model bge-m3
24
24
  #
25
25
  # ONNX_MODEL_DIR below points both that command and the server at the same
26
26
  # directory, so the model a run downloads is the model the next run loads. One
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cembedding
3
- Version: 0.9.1
3
+ Version: 0.9.2
4
4
  Summary: Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed server for CPersona.
5
5
  Project-URL: Homepage, https://github.com/Cloto-dev/CEmbedding
6
6
  Project-URL: Repository, https://github.com/Cloto-dev/CEmbedding
@@ -135,15 +135,17 @@ Point any client (e.g. CPersona's `CPERSONA_EMBEDDING_URL` / generic `EMBEDDING_
135
135
  **Prerequisites:** Python 3.10+
136
136
 
137
137
  ```bash
138
- # Download a model into ./data/models (jina-v5-nano is what CPersona is tuned for)
139
- uvx --from "cembedding[onnx]" cembedding-download-model --model jina-v5-nano
138
+ # Download a model into ./data/models (bge-m3: MIT-licensed, multilingual)
139
+ uvx --from "cembedding[onnx]" cembedding-download-model --model bge-m3
140
140
 
141
141
  # Run the server (reads ./data/models from the current directory)
142
- EMBEDDING_PROVIDER=onnx_jina_v5_nano uvx --from "cembedding[onnx]" cembedding
142
+ EMBEDDING_PROVIDER=onnx_bge_m3 uvx --from "cembedding[onnx]" cembedding
143
143
  ```
144
144
 
145
145
  Or install it onto your PATH with `pip install "cembedding[onnx]"`, then run
146
- `cembedding-download-model --model jina-v5-nano` and `cembedding`.
146
+ `cembedding-download-model --model bge-m3` and `EMBEDDING_PROVIDER=onnx_bge_m3 cembedding`.
147
+ Name the provider every time: without it the server uses `api_openai`, not the model
148
+ just downloaded.
147
149
 
148
150
  From source (development):
149
151
 
@@ -153,8 +155,8 @@ cd CEmbedding
153
155
  python -m venv .venv
154
156
  source .venv/bin/activate # Windows: .venv\Scripts\activate
155
157
  pip install ".[onnx]"
156
- python -m cembedding.download_model --model jina-v5-nano
157
- EMBEDDING_PROVIDER=onnx_jina_v5_nano python -m cembedding # or: python server.py
158
+ python -m cembedding.download_model --model bge-m3
159
+ EMBEDDING_PROVIDER=onnx_bge_m3 python -m cembedding # or: python server.py
158
160
  ```
159
161
 
160
162
  You should see `HTTP embedding endpoint started on http://127.0.0.1:8401/embed`. Verify it:
@@ -176,10 +178,10 @@ docker build -t cembedding .
176
178
  # first request instead -- with the port already accepting connections it cannot
177
179
  # yet answer, and no progress visible to whoever is waiting on it.
178
180
  docker run --rm -v cembedding-data:/data cembedding \
179
- cembedding-download-model --model jina-v5-nano
181
+ cembedding-download-model --model bge-m3
180
182
 
181
183
  docker run -d --name cembedding -p 8401:8401 -v cembedding-data:/data \
182
- -e EMBEDDING_PROVIDER=onnx_jina_v5_nano \
184
+ -e EMBEDDING_PROVIDER=onnx_bge_m3 \
183
185
  -e CEMBEDDING_AUTH_TOKEN="$(openssl rand -hex 32)" \
184
186
  cembedding
185
187
  ```
@@ -205,14 +207,14 @@ Set `EMBEDDING_PROVIDER`:
205
207
 
206
208
  | Value | Model | Notes |
207
209
  |-------|-------|-------|
208
- | `onnx_jina_v5_nano` | jina-embeddings-v5-text-nano-retrieval (~212M params in the fp32 ONNX graph, 768d) | Local CPU, what CPersona is benchmarked against |
209
- | `onnx_bge_m3` | bge-m3 | Local CPU, larger / multilingual |
210
- | `onnx_miniml` | all-MiniLM-L6-v2 (22M, 384d) | Local CPU, smallest |
210
+ | `onnx_bge_m3` | bge-m3, int8 ONNX ([Xenova/bge-m3](https://huggingface.co/Xenova/bge-m3), ~550 MB, 1024d) | Local CPU, multilingual, MIT. Recommended |
211
+ | `onnx_jina_v5_nano` | jina-embeddings-v5-text-nano-retrieval (~212M params in the fp32 ONNX graph, 768d) | Local CPU. Licensed [CC BY-NC 4.0](https://huggingface.co/jinaai/jina-embeddings-v5-text-nano-retrieval): non-commercial use only |
212
+ | `onnx_miniml` | all-MiniLM-L6-v2 (22M, 384d) | Local CPU, smallest, English only, Apache 2.0 |
211
213
  | `mlx_bge_m3` | bge-m3 (MLX) | Apple Silicon only — `pip install ".[mlx]"` |
212
- | `auto_bge_m3` | bge-m3 | Auto-selects MLX on Apple Silicon, ONNX elsewhere |
214
+ | `auto_bge_m3` | bge-m3 | Auto-selects MLX on Apple Silicon, ONNX elsewhere. MLX runs fp16, so its vectors differ from `onnx_bge_m3`'s: keep one store on one of the two |
213
215
  | `api_openai` | provider's model | OpenAI-compatible API; needs `EMBEDDING_API_KEY` (+ optional `EMBEDDING_API_URL`, `EMBEDDING_MODEL`) |
214
216
 
215
- Download a local model with `cembedding-download-model --model {miniml,jina-v5-nano,bge-m3}` (or `python -m cembedding.download_model ...` from a source checkout; fetched from HuggingFace into `./data/models`, not committed to this repo).
217
+ Download a local model with `cembedding-download-model --model {bge-m3,jina-v5-nano,miniml}` (bge-m3 when `--model` is left out) (or `python -m cembedding.download_model ...` from a source checkout; fetched from HuggingFace into `./data/models`, not committed to this repo).
216
218
 
217
219
  ## Model precision
218
220
 
@@ -251,7 +253,7 @@ Vectors already indexed with one precision stay usable with another (the mixed-p
251
253
  | `ONNX_INTRA_OP_THREADS` | `0` | ONNX Runtime intra-op threads. `0` = runtime default (physical cores). Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host) |
252
254
  | `ONNX_GRAPH_OPT_LEVEL` | `all` | ONNX Runtime graph optimization: `disable` / `basic` / `extended` / `all`. Lower it only to compare against an un-fused graph |
253
255
  | `ONNX_ALLOW_SPINNING` | `0` | Whether ONNX Runtime's worker threads keep spinning on the CPU after a run, waiting for the next one. `1` restores the runtime's default. Off, the cores are free as soon as a request is answered: on a 4-core Intel host the spinning held 3 cores for about 1.4 s after each query, and a recall that embedded its query and then searched took a median of 1.58 s against 1.94 s with it. Embed calls were not slower without it (79-81 ms back to back through the server, in either setting) |
254
- | `EMBEDDING_MAX_BATCH` | `64` | Most texts one model run may carry when concurrent requests are merged into it. Local providers run one pass at a time, so requests that arrive while a pass is in flight share the next one instead of each paying for a pass (nothing waits for a batch to fill, and one request is never split). Results are bit-identical on the CPU provider; on accelerator providers the low bits (about 1e-6) can depend on the batch a text ran in, as they already did for multi-text requests. `0` disables merging |
256
+ | `EMBEDDING_MAX_BATCH` | `64` | Most texts one model run may carry when concurrent requests are merged into it. Local providers run one pass at a time, so requests that arrive while a pass is in flight share the next one instead of each paying for a pass (nothing waits for a batch to fill, and one request is never split). Results are bit-identical on the CPU provider; on accelerator providers the low bits (about 1e-6) can depend on the batch a text ran in, as they already did for multi-text requests. A graph that quantizes activations at run time (the int8 bge-m3 graph) computes one scale over the whole batch, so the server runs it one text at a time: each text gets the vector it gets alone, and on the CPU provider that is bit-identical whether or not its request was merged or sent beside other texts. Measured on the CPU provider, one text at a time took within 7% of a batch of 64 short texts and less than half the time of a batch of 16 long ones, since no text is padded to the longest. `0` disables merging |
255
257
  | `EMBEDDING_API_KEY` | — | Required for `api_openai` |
256
258
  | `EMBEDDING_API_URL` | `https://api.openai.com/v1/embeddings` | API endpoint for `api_openai` |
257
259
  | `CEMBEDDING_AUTH_TOKEN` | — | Inbound bearer token. Unset = no authentication (see below) |
@@ -90,15 +90,17 @@ Point any client (e.g. CPersona's `CPERSONA_EMBEDDING_URL` / generic `EMBEDDING_
90
90
  **Prerequisites:** Python 3.10+
91
91
 
92
92
  ```bash
93
- # Download a model into ./data/models (jina-v5-nano is what CPersona is tuned for)
94
- uvx --from "cembedding[onnx]" cembedding-download-model --model jina-v5-nano
93
+ # Download a model into ./data/models (bge-m3: MIT-licensed, multilingual)
94
+ uvx --from "cembedding[onnx]" cembedding-download-model --model bge-m3
95
95
 
96
96
  # Run the server (reads ./data/models from the current directory)
97
- EMBEDDING_PROVIDER=onnx_jina_v5_nano uvx --from "cembedding[onnx]" cembedding
97
+ EMBEDDING_PROVIDER=onnx_bge_m3 uvx --from "cembedding[onnx]" cembedding
98
98
  ```
99
99
 
100
100
  Or install it onto your PATH with `pip install "cembedding[onnx]"`, then run
101
- `cembedding-download-model --model jina-v5-nano` and `cembedding`.
101
+ `cembedding-download-model --model bge-m3` and `EMBEDDING_PROVIDER=onnx_bge_m3 cembedding`.
102
+ Name the provider every time: without it the server uses `api_openai`, not the model
103
+ just downloaded.
102
104
 
103
105
  From source (development):
104
106
 
@@ -108,8 +110,8 @@ cd CEmbedding
108
110
  python -m venv .venv
109
111
  source .venv/bin/activate # Windows: .venv\Scripts\activate
110
112
  pip install ".[onnx]"
111
- python -m cembedding.download_model --model jina-v5-nano
112
- EMBEDDING_PROVIDER=onnx_jina_v5_nano python -m cembedding # or: python server.py
113
+ python -m cembedding.download_model --model bge-m3
114
+ EMBEDDING_PROVIDER=onnx_bge_m3 python -m cembedding # or: python server.py
113
115
  ```
114
116
 
115
117
  You should see `HTTP embedding endpoint started on http://127.0.0.1:8401/embed`. Verify it:
@@ -131,10 +133,10 @@ docker build -t cembedding .
131
133
  # first request instead -- with the port already accepting connections it cannot
132
134
  # yet answer, and no progress visible to whoever is waiting on it.
133
135
  docker run --rm -v cembedding-data:/data cembedding \
134
- cembedding-download-model --model jina-v5-nano
136
+ cembedding-download-model --model bge-m3
135
137
 
136
138
  docker run -d --name cembedding -p 8401:8401 -v cembedding-data:/data \
137
- -e EMBEDDING_PROVIDER=onnx_jina_v5_nano \
139
+ -e EMBEDDING_PROVIDER=onnx_bge_m3 \
138
140
  -e CEMBEDDING_AUTH_TOKEN="$(openssl rand -hex 32)" \
139
141
  cembedding
140
142
  ```
@@ -160,14 +162,14 @@ Set `EMBEDDING_PROVIDER`:
160
162
 
161
163
  | Value | Model | Notes |
162
164
  |-------|-------|-------|
163
- | `onnx_jina_v5_nano` | jina-embeddings-v5-text-nano-retrieval (~212M params in the fp32 ONNX graph, 768d) | Local CPU, what CPersona is benchmarked against |
164
- | `onnx_bge_m3` | bge-m3 | Local CPU, larger / multilingual |
165
- | `onnx_miniml` | all-MiniLM-L6-v2 (22M, 384d) | Local CPU, smallest |
165
+ | `onnx_bge_m3` | bge-m3, int8 ONNX ([Xenova/bge-m3](https://huggingface.co/Xenova/bge-m3), ~550 MB, 1024d) | Local CPU, multilingual, MIT. Recommended |
166
+ | `onnx_jina_v5_nano` | jina-embeddings-v5-text-nano-retrieval (~212M params in the fp32 ONNX graph, 768d) | Local CPU. Licensed [CC BY-NC 4.0](https://huggingface.co/jinaai/jina-embeddings-v5-text-nano-retrieval): non-commercial use only |
167
+ | `onnx_miniml` | all-MiniLM-L6-v2 (22M, 384d) | Local CPU, smallest, English only, Apache 2.0 |
166
168
  | `mlx_bge_m3` | bge-m3 (MLX) | Apple Silicon only — `pip install ".[mlx]"` |
167
- | `auto_bge_m3` | bge-m3 | Auto-selects MLX on Apple Silicon, ONNX elsewhere |
169
+ | `auto_bge_m3` | bge-m3 | Auto-selects MLX on Apple Silicon, ONNX elsewhere. MLX runs fp16, so its vectors differ from `onnx_bge_m3`'s: keep one store on one of the two |
168
170
  | `api_openai` | provider's model | OpenAI-compatible API; needs `EMBEDDING_API_KEY` (+ optional `EMBEDDING_API_URL`, `EMBEDDING_MODEL`) |
169
171
 
170
- Download a local model with `cembedding-download-model --model {miniml,jina-v5-nano,bge-m3}` (or `python -m cembedding.download_model ...` from a source checkout; fetched from HuggingFace into `./data/models`, not committed to this repo).
172
+ Download a local model with `cembedding-download-model --model {bge-m3,jina-v5-nano,miniml}` (bge-m3 when `--model` is left out) (or `python -m cembedding.download_model ...` from a source checkout; fetched from HuggingFace into `./data/models`, not committed to this repo).
171
173
 
172
174
  ## Model precision
173
175
 
@@ -206,7 +208,7 @@ Vectors already indexed with one precision stay usable with another (the mixed-p
206
208
  | `ONNX_INTRA_OP_THREADS` | `0` | ONNX Runtime intra-op threads. `0` = runtime default (physical cores). Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host) |
207
209
  | `ONNX_GRAPH_OPT_LEVEL` | `all` | ONNX Runtime graph optimization: `disable` / `basic` / `extended` / `all`. Lower it only to compare against an un-fused graph |
208
210
  | `ONNX_ALLOW_SPINNING` | `0` | Whether ONNX Runtime's worker threads keep spinning on the CPU after a run, waiting for the next one. `1` restores the runtime's default. Off, the cores are free as soon as a request is answered: on a 4-core Intel host the spinning held 3 cores for about 1.4 s after each query, and a recall that embedded its query and then searched took a median of 1.58 s against 1.94 s with it. Embed calls were not slower without it (79-81 ms back to back through the server, in either setting) |
209
- | `EMBEDDING_MAX_BATCH` | `64` | Most texts one model run may carry when concurrent requests are merged into it. Local providers run one pass at a time, so requests that arrive while a pass is in flight share the next one instead of each paying for a pass (nothing waits for a batch to fill, and one request is never split). Results are bit-identical on the CPU provider; on accelerator providers the low bits (about 1e-6) can depend on the batch a text ran in, as they already did for multi-text requests. `0` disables merging |
211
+ | `EMBEDDING_MAX_BATCH` | `64` | Most texts one model run may carry when concurrent requests are merged into it. Local providers run one pass at a time, so requests that arrive while a pass is in flight share the next one instead of each paying for a pass (nothing waits for a batch to fill, and one request is never split). Results are bit-identical on the CPU provider; on accelerator providers the low bits (about 1e-6) can depend on the batch a text ran in, as they already did for multi-text requests. A graph that quantizes activations at run time (the int8 bge-m3 graph) computes one scale over the whole batch, so the server runs it one text at a time: each text gets the vector it gets alone, and on the CPU provider that is bit-identical whether or not its request was merged or sent beside other texts. Measured on the CPU provider, one text at a time took within 7% of a batch of 64 short texts and less than half the time of a batch of 16 long ones, since no text is padded to the longest. `0` disables merging |
210
212
  | `EMBEDDING_API_KEY` | — | Required for `api_openai` |
211
213
  | `EMBEDDING_API_URL` | `https://api.openai.com/v1/embeddings` | API endpoint for `api_openai` |
212
214
  | `CEMBEDDING_AUTH_TOKEN` | — | Inbound bearer token. Unset = no authentication (see below) |
@@ -1,3 +1,3 @@
1
1
  """CEmbedding — local-first embedding server (the reference /embed server for CPersona)."""
2
2
 
3
- __version__ = "0.9.1"
3
+ __version__ = "0.9.2"
@@ -135,7 +135,13 @@ def download_bge_m3(model_dir: str = "") -> bool:
135
135
  def main():
136
136
  """Console-script / ``python -m cembedding.download_model`` entry point."""
137
137
  parser = argparse.ArgumentParser(description="Download ONNX embedding models")
138
- parser.add_argument("--model", default="miniml", choices=["miniml", "jina-v5-nano", "bge-m3"])
138
+ parser.add_argument(
139
+ "--model",
140
+ default="bge-m3",
141
+ choices=["miniml", "jina-v5-nano", "bge-m3"],
142
+ help="model to fetch (default: bge-m3, MIT-licensed; jina-v5-nano is licensed CC BY-NC 4.0, "
143
+ "non-commercial use only)",
144
+ )
139
145
  parser.add_argument(
140
146
  "--variant",
141
147
  default="fp32",
@@ -12,6 +12,7 @@ import asyncio
12
12
  import hashlib
13
13
  import json
14
14
  import logging
15
+ import mmap
15
16
  import os
16
17
  import platform as _platform
17
18
  import sys
@@ -223,21 +224,36 @@ class _BatchRunner:
223
224
  share the next one. The batch is capped at ``max_batch`` texts, except
224
225
  that the first request of a run is always taken whole — splitting one
225
226
  caller's texts across runs would buy nothing and would break the promise
226
- that a batch is embedded together. ``max_batch=0`` means every request
227
- gets its own run.
227
+ that a batch is embedded together (``per_text`` below is the exception).
228
+ ``max_batch=0`` means every request gets its own run.
228
229
 
229
230
  ``run`` is called only from the drain loop, and at most one drain loop
230
231
  exists at a time, which is what serializes access to the session (this
231
232
  replaced a per-provider ``asyncio.Lock``).
233
+
234
+ ``per_text`` makes every run carry one text. A provider sets it when its
235
+ graph quantizes activations dynamically (see
236
+ ``_graph_quantizes_activations``): such a graph computes one quantization
237
+ scale over the whole batch, so a text's vector would depend on the texts
238
+ it happened to share a run with. One text per run makes the vector the one
239
+ the text gets alone, whether or not its request was merged, and whatever
240
+ else the caller sent with it. Requests are still queued and merged; only
241
+ the runs are split.
232
242
  """
233
243
 
234
- def __init__(self, run, max_batch: int):
244
+ def __init__(self, run, max_batch: int, *, per_text: bool = False):
235
245
  #: ``callable(list[str]) -> list[list[float]]``, run in the default executor.
236
246
  self._run = run
237
247
  self._max_batch = max_batch
248
+ self.per_text = per_text
238
249
  self._queue: deque[tuple[list[str], asyncio.Future]] = deque()
239
250
  self._drain_task: asyncio.Task | None = None
240
251
 
252
+ def _run_batch(self, texts: list[str]) -> list[list[float]]:
253
+ if not self.per_text:
254
+ return self._run(texts)
255
+ return [row for text in texts for row in self._run([text])]
256
+
241
257
  async def submit(self, texts: list[str]) -> list[list[float]]:
242
258
  """Embed ``texts``, possibly inside a run shared with other callers."""
243
259
  # A request with no texts has no work to do. Answering it here keeps
@@ -275,7 +291,7 @@ class _BatchRunner:
275
291
  if not waiters: # everything queued had been cancelled
276
292
  continue
277
293
  try:
278
- rows = await loop.run_in_executor(None, self._run, batch)
294
+ rows = await loop.run_in_executor(None, self._run_batch, batch)
279
295
  except Exception as exc:
280
296
  # The whole run failed, so every caller in it fails — but the
281
297
  # loop keeps going, or one bad request would strand every
@@ -293,6 +309,23 @@ class _BatchRunner:
293
309
  start += count
294
310
 
295
311
 
312
+ def _graph_quantizes_activations(model_path: str) -> bool:
313
+ """Whether the ONNX graph quantizes activations with a scale taken at run time.
314
+
315
+ ``DynamicQuantizeLinear`` computes one scale and zero point over its whole
316
+ input tensor, so in a batched run every sequence, padding included, sets
317
+ the quantization of every other one (the int8 bge-m3 graph has 96 such
318
+ nodes). Weight-only and fp32 graphs do not have the node.
319
+
320
+ The operator names are plain strings in the graph file itself (external
321
+ weight files hold tensors only), so a byte search answers this without
322
+ parsing the model or depending on the ``onnx`` package.
323
+ """
324
+ with open(model_path, "rb") as f:
325
+ with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m:
326
+ return m.find(b"DynamicQuantizeLinear") != -1
327
+
328
+
296
329
  # ============================================================
297
330
  # Provider Abstraction
298
331
  # ============================================================
@@ -674,6 +707,7 @@ class OnnxMiniLMProvider(EmbeddingProvider):
674
707
  providers = _select_ort_providers()
675
708
 
676
709
  self._session = _create_ort_session(model_path, providers)
710
+ self._runner.per_text = _graph_quantizes_activations(model_path)
677
711
  self._tokenizer = Tokenizer.from_file(tokenizer_path)
678
712
  # MiniLM positional embeddings cap at 512 — clamp ONNX_MAX_SEQ_LEN.
679
713
  miniml_seq_len = min(ONNX_MAX_SEQ_LEN, 512)
@@ -692,11 +726,12 @@ class OnnxMiniLMProvider(EmbeddingProvider):
692
726
  self._loaded_files = {"graph": model_path, "tokenizer": tokenizer_path}
693
727
 
694
728
  logger.info(
695
- "ONNX MiniLM provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s)",
729
+ "ONNX MiniLM provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s, one_text_per_run=%s)",
696
730
  self._model_dir,
697
731
  miniml_seq_len,
698
732
  providers,
699
733
  self._session.get_providers(),
734
+ self._runner.per_text,
700
735
  )
701
736
 
702
737
  async def embed(self, texts: list[str]) -> list[list[float]]:
@@ -950,6 +985,7 @@ class OnnxBgeM3Provider(EmbeddingProvider):
950
985
 
951
986
  providers = _select_ort_providers()
952
987
  self._session = _create_ort_session(model_path, providers)
988
+ self._runner.per_text = _graph_quantizes_activations(model_path)
953
989
  self._tokenizer = Tokenizer.from_file(tokenizer_path)
954
990
  bge_seq_len = min(ONNX_MAX_SEQ_LEN, 8192)
955
991
  # XLM-RoBERTa pad token is <pad> (id=1)
@@ -961,11 +997,12 @@ class OnnxBgeM3Provider(EmbeddingProvider):
961
997
  self._loaded_files = {"graph": model_path, "tokenizer": tokenizer_path}
962
998
 
963
999
  logger.info(
964
- "ONNX BGE-M3 provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s)",
1000
+ "ONNX BGE-M3 provider initialized (dir=%s, seq_len=%d, requested=%s, active=%s, one_text_per_run=%s)",
965
1001
  self._model_dir,
966
1002
  bge_seq_len,
967
1003
  providers,
968
1004
  self._session.get_providers(),
1005
+ self._runner.per_text,
969
1006
  )
970
1007
 
971
1008
  async def embed(self, texts: list[str]) -> list[list[float]]:
@@ -1059,6 +1096,7 @@ class OnnxJinaV5NanoProvider(EmbeddingProvider):
1059
1096
 
1060
1097
  providers = _select_ort_providers()
1061
1098
  self._session = self._create_session_with_fallback(model_path, providers)
1099
+ self._runner.per_text = _graph_quantizes_activations(model_path)
1062
1100
  self._tokenizer = Tokenizer.from_file(tokenizer_path)
1063
1101
  # jina-v5-nano supports up to 8K context via RoPE.
1064
1102
  # Pad to longest in batch (see the MiniLM provider note): fixed-length
@@ -1075,12 +1113,13 @@ class OnnxJinaV5NanoProvider(EmbeddingProvider):
1075
1113
  self._loaded_files["weights"] = external_data
1076
1114
 
1077
1115
  logger.info(
1078
- "ONNX Jina-v5-nano provider initialized (dir=%s, variant=%s, seq_len=%d, requested=%s, active=%s)",
1116
+ "ONNX Jina-v5-nano provider initialized (dir=%s, variant=%s, seq_len=%d, requested=%s, active=%s, one_text_per_run=%s)",
1079
1117
  self._model_dir,
1080
1118
  EMBEDDING_MODEL_VARIANT,
1081
1119
  ONNX_MAX_SEQ_LEN,
1082
1120
  providers,
1083
1121
  self._session.get_providers(),
1122
+ self._runner.per_text,
1084
1123
  )
1085
1124
 
1086
1125
  def _create_session_with_fallback(self, model_path: str, providers: list):
@@ -0,0 +1,148 @@
1
+ {
2
+ "spec_version": 1,
3
+ "connector_type": "mgp_server",
4
+ "id": "cembedding",
5
+ "name": "CEmbedding",
6
+ "description": "Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed and remote /search server for CPersona.",
7
+ "version": "0.9.2",
8
+ "category": "tool",
9
+ "trust_level": "core",
10
+ "magic_seal": "sha256:f75b48b630e7b1cf539577121ffddede7e35a72aadc92733d064359145ff5e64",
11
+ "install": {
12
+ "source": {
13
+ "type": "git",
14
+ "url": "https://github.com/Cloto-dev/CEmbedding",
15
+ "reference": "",
16
+ "subdir": null
17
+ },
18
+ "package_manager": "uv",
19
+ "runtime": "python",
20
+ "directory": "",
21
+ "dependencies": [],
22
+ "bin_name": null
23
+ },
24
+ "icon": "layers",
25
+ "tags": [
26
+ "embedding",
27
+ "vector",
28
+ "search",
29
+ "onnx"
30
+ ],
31
+ "host_compatibility": [
32
+ "clotocore",
33
+ "claude-code",
34
+ "claude-desktop",
35
+ "cursor",
36
+ "project-airi"
37
+ ],
38
+ "env_vars": [],
39
+ "optional_env_vars": [
40
+ {
41
+ "name": "EMBEDDING_PROVIDER",
42
+ "default": "api_openai",
43
+ "description": "Embedding provider: api_openai | onnx_miniml | onnx_jina_v5_nano | onnx_bge_m3 | mlx_bge_m3."
44
+ },
45
+ {
46
+ "name": "EMBEDDING_HTTP_PORT",
47
+ "default": "8401",
48
+ "description": "HTTP port for /embed and the vector-index endpoints."
49
+ },
50
+ {
51
+ "name": "EMBEDDING_INDEX_ENABLED",
52
+ "default": "true",
53
+ "description": "Enable the persistent vector index endpoints (/index, /search, /remove, /purge)."
54
+ },
55
+ {
56
+ "name": "EMBEDDING_INDEX_DB_PATH",
57
+ "default": "data/embedding_index.db",
58
+ "description": "SQLite file backing the vector index."
59
+ },
60
+ {
61
+ "name": "EMBEDDING_SEARCH_BACKEND",
62
+ "default": "numpy",
63
+ "description": "/search matmul backend: numpy (Accelerate BLAS) or mlx (Apple-GPU resident matrix; numpy fallback when mlx is absent). v0.6.0."
64
+ },
65
+ {
66
+ "name": "EMBEDDING_SIDECAR",
67
+ "default": "auto",
68
+ "description": "Startup source for the resident vectors: 'auto' maps them from the sidecar file, 'off' always reads them from SQLite. v0.7.0."
69
+ },
70
+ {
71
+ "name": "EMBEDDING_SIDECAR_PATH",
72
+ "default": "",
73
+ "description": "Where the sidecar file lives. Empty = alongside the index database, named after it. v0.7.0."
74
+ },
75
+ {
76
+ "name": "EMBEDDING_SIDECAR_MIN_ROWS",
77
+ "default": "10000",
78
+ "description": "Smallest corpus that gets a sidecar file; below it the in-memory index is cheap enough that a file adds nothing. v0.7.0."
79
+ },
80
+ {
81
+ "name": "EMBEDDING_SIDECAR_MAX_TAIL",
82
+ "default": "0.25",
83
+ "description": "Rebuild the sidecar when the rows written since the last build exceed this fraction of the rows in the file. v0.7.0."
84
+ },
85
+ {
86
+ "name": "ONNX_MODEL_DIR",
87
+ "default": "",
88
+ "description": "Override the model directory for ONNX providers (auto-resolved by provider when empty)."
89
+ },
90
+ {
91
+ "name": "ONNX_EP_PREFERENCE",
92
+ "default": "",
93
+ "description": "ONNX execution providers, comma-separated. Empty = auto (CoreML on macOS, DirectML on Windows, else CPU; CPU always ensured)."
94
+ },
95
+ {
96
+ "name": "ONNX_MAX_SEQ_LEN",
97
+ "default": "2048",
98
+ "description": "Max tokenization length (1-8192; MiniLM clamped to 512 internally)."
99
+ },
100
+ {
101
+ "name": "EMBEDDING_MODEL_VARIANT",
102
+ "default": "fp32",
103
+ "description": "Precision of jina-v5-nano to load: fp32 / fp16 / int8, downloaded on first use. int8 saves about 280 MB of resident memory and costs four to eight times more per query; vectors already stored were produced at fp32. v0.7.0."
104
+ },
105
+ {
106
+ "name": "ONNX_INTRA_OP_THREADS",
107
+ "default": "0",
108
+ "description": "ONNX Runtime intra-op threads. 0 = the runtime decides. Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host); over-subscribing is slower, not faster. v0.7.0."
109
+ },
110
+ {
111
+ "name": "ONNX_GRAPH_OPT_LEVEL",
112
+ "default": "all",
113
+ "description": "ONNX Runtime graph optimization level: disable / basic / extended / all. Lower it only to compare against an un-fused graph. v0.7.0."
114
+ },
115
+ {
116
+ "name": "ONNX_ALLOW_SPINNING",
117
+ "default": "0",
118
+ "description": "Whether ONNX Runtime's worker threads keep spinning on the CPU after a run, waiting for the next one. 1 restores the runtime's default. Off, the cores are free as soon as a request is answered: on a 4-core Intel host the spinning held 3 cores for about 1.4 s after each query, and a recall that embedded its query and then searched took a median of 1.58 s against 1.94 s with it. Embed calls were not slower without it (79-81 ms back to back through the server, in either setting). v0.9.1."
119
+ },
120
+ {
121
+ "name": "EMBEDDING_MAX_BATCH",
122
+ "default": "64",
123
+ "description": "Most texts one model run may carry when concurrent requests are merged into it. 0 disables merging and gives one pass per request. v0.7.0."
124
+ },
125
+ {
126
+ "name": "EMBEDDING_API_KEY",
127
+ "default": "",
128
+ "description": "Required for the api_openai provider."
129
+ },
130
+ {
131
+ "name": "EMBEDDING_API_URL",
132
+ "default": "https://api.openai.com/v1/embeddings",
133
+ "description": "API endpoint for the api_openai provider."
134
+ },
135
+ {
136
+ "name": "CEMBEDDING_AUTH_TOKEN",
137
+ "default": "",
138
+ "description": "Inbound bearer token required on every HTTP request (REST endpoints and the Streamable HTTP MCP transport). Empty = unauthenticated, which is safe only when nothing but this machine can reach the process — a tunnel or reverse proxy forwards to loopback, so a loopback bind is not evidence of that. v0.6.2."
139
+ },
140
+ {
141
+ "name": "CEMBEDDING_REQUIRE_AUTH",
142
+ "default": "false",
143
+ "description": "Refuse to start when CEMBEDDING_AUTH_TOKEN is empty, instead of starting unauthenticated with a warning. v0.6.2."
144
+ }
145
+ ],
146
+ "auto_restart": true,
147
+ "changelog": "v0.9.2: A graph that quantizes activations at run time (the int8 bge-m3 graph, with 96 DynamicQuantizeLinear nodes) took one quantization scale over the whole batch, so a text's vector changed with the texts it shared a run with: a request merged with a concurrent one, or a text sent beside others in one call, came back at a cosine of about 0.994 to the same text embedded alone. Each local ONNX provider now checks its graph for that operator when it loads; if the graph has it, requests are still queued and merged but each text runs on its own, so every text gets the vector it gets alone, bit for bit on the CPU provider. fp32 and weight-only graphs keep batched runs. On the CPU provider of a 4-core Intel N150, building the vectors of 17,684 short memory blocks took about 42% less time one text at a time than in runs of 64 (1,851 s to 1,062 s and 1,848 s to 1,071 s in two runs), since no text is padded to the longest. Vectors a caller stored from batched runs differ from the new ones at about that cosine; whether to embed them again is the caller's choice. cembedding-download-model now fetches bge-m3 when no model is named, and the README recommends it with EMBEDDING_PROVIDER=onnx_bge_m3; the server's own default provider is unchanged. 11 regression tests, one of which needs the bge-m3 model on disk.\n\nv0.9.1: ONNX Runtime's worker threads no longer keep spinning on the CPU after each run (session.intra_op.allow_spinning = 0); ONNX_ALLOW_SPINNING=1 restores the runtime's default. On a 4-core Intel host one short query had left 3 cores busy for about 1.4 s after the response, the moment a caller on the same host searches: a memory server's recall over 100,000 memories that embedded its query through this server took a median of 1.58 s without spinning against 1.94 s with it, in a registered run. Vectors are bit-identical and embed calls were not slower (79-81 ms back to back through the server in every setting tried; 8 x 512-token batches 12.3 s either way). On an Apple laptop (onnxruntime 1.27) the spinning had stopped within 20 ms. 4 regression tests (8 cases).\n\nv0.9.0: GET /capabilities says which backend produced the vectors, so a caller that stores vectors can tell whether a stored one may still be compared with a fresh one. Over /embed it cannot: the request carries texts and the server picks the model, so a client that falls back to a configured name reads two different models as one, including two precisions of one model, which return different vectors through the same tokenizer. The report names the provider, model, width, truncation window, pooling, normalization, and the digests of the graph, tokenizer and weight files the provider actually opened, and reduces them to one fingerprint to store beside a vector. When a component cannot be established, incomplete names it and the fingerprint is null, never a fingerprint over part of the identity; api_openai and mlx_bge_m3 report null because the files that would be hashed are not this process's to read. Null means unknown, not unchanged. /embed is untouched; digests are computed once per file state, off the event loop, and cached. The route sits behind the same bearer authentication as the other REST endpoints. Verified end to end on jina-v5-nano: a complete identity with a fingerprint, 401 without the token when one is configured, and a client pointed at a server without the route reads the 404 as unknown. 34 regression tests.\n\nv0.8.0: The server reports where each text's embedding window closes, so a caller storing long records can split them where the vector stops seeing them instead of guessing from a character count (for one token window that position varies by more than a factor of two). POST /embed accepts an opt-in token_info flag, and POST /count_tokens returns the same report without running the model. Each entry carries the token count, the window, whether the text was cut, and window_end_char, the character offset where the embedded prefix ends. Without the flag /embed answers exactly as before. Providers that cannot see their tokens (api_openai, mlx_bge_m3) report null, meaning unknown. The counting tokenizer is a separate instance that loads on first use (about 29 MiB resident for jina-v5-nano); counting costs 0.4 to 1.6% of an embed call and only when asked. Verified end to end on jina-v5-nano: embedding the reported prefix gives the same vector as the whole text, and cutting 8 characters earlier does not. 24 regression tests.\n\nv0.7.0: Performance and footprint, with results unchanged. Startup maps the resident vectors from a contiguous file next to the index database instead of decoding every blob out of SQLite (100k x 768: 0.23 s and 1.1 GiB peak, to 0.09 s and 402 MiB); SQLite stays the durable record and the file is a cache that can be deleted. The index keeps one matrix per namespace instead of a per-item map plus a rebuilt stack, so a write no longer costs the next search a rebuild (20k x 384: 153 ms to 17 ms over 30 write+search rounds). Concurrent /embed requests that arrive while a model pass is running share the next pass instead of each paying for one (32 clients: p50 219 ms to 90 ms, 150 to 358 req/s). fp16 and int8 weights of jina-v5-nano are selectable with EMBEDDING_MODEL_VARIANT; fp32 stays the default because int8 saves about 280 MB but costs four to eight times more per query. ONNX_INTRA_OP_THREADS and ONNX_GRAPH_OPT_LEVEL configure the runtime session, both defaulting to what it did before. The one observable difference: once the sidecar splits a namespace into two segments, the two BLAS calls can accumulate in different orders, so rows whose scores tie exactly may order differently. EMBEDDING_SIDECAR=off keeps the previous startup path, EMBEDDING_MAX_BATCH=0 the previous embed path. 116 regression tests.\n\nv0.6.2: SECURITY — both HTTP surfaces now support inbound bearer authentication, which they previously had no mechanism for at all. Set CEMBEDDING_AUTH_TOKEN and every request to the REST endpoints (/embed, /index, /search, /remove, /purge) and to the Streamable HTTP MCP transport must carry 'Authorization: Bearer <token>'; missing headers, wrong schemes and wrong tokens are all rejected with 401, compared with hmac.compare_digest. The change is additive: with no token configured the server behaves exactly as 0.6.1 and logs a warning, and CEMBEDDING_REQUIRE_AUTH=true turns that warning into a startup error for operators who want fail-closed today. A later release will make requiring a token the default. The warning deliberately states that a loopback bind is not evidence that requests are local — a tunnel or reverse proxy forwards to loopback, which is how the sibling CPersona server ran publicly reachable and unauthenticated for 13 days. 40 regression tests drive the real middleware at the ASGI and aiohttp layers.\n\nv0.6.1: ONNX providers now pad each batch to its longest sequence instead of a fixed ONNX_MAX_SEQ_LEN. Fixed-length padding made every forward pass cost the full max length (default 2048) regardless of input size: a short recall query encoded in ~617 ms; pad-to-longest brings it to ~7 ms (~90x) and batch document encode from ~0.5 to ~460 docs/s, with bit-identical embeddings (pooling honors the attention mask; parity verified to cosine 1.0). Affects all three local ONNX providers (jina-v5-nano, bge-m3, MiniLM). Adds padding-regression tests.\n\nv0.6.0: /search runs one matmul over a per-namespace resident matrix instead of a per-item Python loop, with vectorized threshold + top-K selection (~21x at 237k x 384: 131 ms -> 6 ms/query). New EMBEDDING_SEARCH_BACKEND env (numpy default, mlx = Apple-GPU resident matrix with numpy fallback). New scripts/backfill_embedding_index.py migrates existing cpersona embedding blobs into the index so a deployment can flip CPERSONA_VECTOR_SEARCH_MODE=remote without losing pre-flip semantic recall. Adds the test suite (12 tests) and CI the repo lacked since extraction.\n\nv0.5.0: PyPI packaging release — flat layout restructured into the cembedding/ package with console scripts (cembedding, cembedding-download-model); published to PyPI as 'cembedding'. Functionally identical to clotohub-servers servers/embedding 0.4.0, from which this repository was extracted on 2026-06-28.\n\nv0.4.0 and earlier: see the clotohub-servers repository history (servers/embedding)."
148
+ }
@@ -12,6 +12,7 @@ padding tests, self-skips where the model was never downloaded.
12
12
  """
13
13
 
14
14
  import asyncio
15
+ import importlib.util
15
16
  import os
16
17
  import threading
17
18
 
@@ -233,3 +234,166 @@ def test_a_negative_cap_is_rejected_at_import(monkeypatch):
233
234
  module = importlib.util.module_from_spec(spec)
234
235
  with pytest.raises(ValueError, match="EMBEDDING_MAX_BATCH"):
235
236
  spec.loader.exec_module(module)
237
+
238
+
239
+ class BatchDependentModel(FakeModel):
240
+ """A model whose rows depend on the batch, as a dynamically quantized graph's do.
241
+
242
+ Each row carries the size of the run it came from, so any text that shared
243
+ a run with another comes back different from the same text embedded alone.
244
+ """
245
+
246
+ def __call__(self, texts: list[str]) -> list[list[float]]:
247
+ rows = super().__call__(texts)
248
+ return [row + [float(len(texts))] for row in rows]
249
+
250
+
251
+ def _alone_row(text: str) -> list[float]:
252
+ return [float(len(text)), float(hash(text) % 1000), 1.0]
253
+
254
+
255
+ async def test_per_text_runs_give_every_text_its_alone_vector_when_requests_merge():
256
+ model = BatchDependentModel(block_first=True)
257
+ runner = _BatchRunner(model, max_batch=64, per_text=True)
258
+
259
+ tasks = [asyncio.create_task(runner.submit([f"text {i}"])) for i in range(16)]
260
+ await asyncio.sleep(0.05)
261
+ model.release()
262
+ results = await _within(asyncio.gather(*tasks))
263
+
264
+ assert all(len(b) == 1 for b in model.batches), model.batches
265
+ for i, result in enumerate(results):
266
+ assert result == [_alone_row(f"text {i}")], f"caller {i} got a batch-dependent row"
267
+
268
+
269
+ async def test_per_text_runs_split_a_multi_text_request():
270
+ model = BatchDependentModel()
271
+ runner = _BatchRunner(model, max_batch=64, per_text=True)
272
+ texts = ["first", "a second, longer text", "third"]
273
+
274
+ result = await _within(runner.submit(texts))
275
+
276
+ assert model.batches == [[t] for t in texts]
277
+ assert result == [_alone_row(t) for t in texts]
278
+
279
+
280
+ async def test_without_per_text_a_batch_dependent_model_leaks_the_batch():
281
+ """The control for the two tests above: the fake model really is batch-dependent."""
282
+ model = BatchDependentModel()
283
+ runner = _BatchRunner(model, max_batch=64)
284
+ texts = ["first", "second"]
285
+
286
+ result = await _within(runner.submit(texts))
287
+
288
+ assert result != [_alone_row(t) for t in texts]
289
+
290
+
291
+ def test_a_dynamically_quantized_graph_is_detected(tmp_path):
292
+ from cembedding.server import _graph_quantizes_activations
293
+
294
+ quantized = tmp_path / "quantized.onnx"
295
+ quantized.write_bytes(b"\x08\x07" + b"\x00" * 4096 + b"DynamicQuantizeLinear" + b"\x00" * 4096)
296
+ plain = tmp_path / "plain.onnx"
297
+ plain.write_bytes(b"\x08\x07" + b"\x00" * 4096 + b"MatMulInteger QuantizeLinear MatMul" + b"\x00" * 4096)
298
+
299
+ assert _graph_quantizes_activations(str(quantized)) is True
300
+ assert _graph_quantizes_activations(str(plain)) is False
301
+
302
+
303
+ @pytest.mark.parametrize(
304
+ "provider_name,graph_name",
305
+ [
306
+ ("OnnxMiniLMProvider", "model.onnx"),
307
+ ("OnnxBgeM3Provider", "model.onnx"),
308
+ ("OnnxJinaV5NanoProvider", None),
309
+ ],
310
+ )
311
+ @pytest.mark.parametrize("quantized", [True, False])
312
+ async def test_every_local_onnx_provider_runs_one_text_at_a_time_on_a_quantized_graph(
313
+ provider_name, graph_name, quantized, tmp_path, monkeypatch
314
+ ):
315
+ """The detection has to reach each provider's runner, read from the graph it loads.
316
+
317
+ The session and tokenizer are stubbed, and onnxruntime is stood in for when
318
+ it is not installed (the CI job installs only the dev extra), so only the
319
+ path from the graph file to the runner is exercised.
320
+ """
321
+ import sys
322
+ import types
323
+
324
+ import tokenizers
325
+
326
+ from cembedding import server
327
+ from cembedding.download_model import JINA_VARIANT_STEMS
328
+
329
+ graph_name = graph_name or f"{JINA_VARIANT_STEMS[server.EMBEDDING_MODEL_VARIANT]}.onnx"
330
+ op = b"DynamicQuantizeLinear" if quantized else b"MatMul"
331
+ (tmp_path / graph_name).write_bytes(b"\x00" * 64 + op + b"\x00" * 64)
332
+ (tmp_path / "tokenizer.json").write_text("{}")
333
+
334
+ class StubSession:
335
+ def get_providers(self):
336
+ return ["CPUExecutionProvider"]
337
+
338
+ def get_inputs(self):
339
+ return []
340
+
341
+ class StubTokenizer:
342
+ def __getattr__(self, name):
343
+ return lambda *a, **k: None
344
+
345
+ if "onnxruntime" not in sys.modules:
346
+ try:
347
+ import onnxruntime # noqa: F401
348
+ except ImportError:
349
+ monkeypatch.setitem(sys.modules, "onnxruntime", types.ModuleType("onnxruntime"))
350
+ monkeypatch.setattr(server, "_create_ort_session", lambda path, providers: StubSession())
351
+ monkeypatch.setattr(tokenizers.Tokenizer, "from_file", staticmethod(lambda path: StubTokenizer()))
352
+ monkeypatch.setattr(server._TokenCounter, "from_file", classmethod(lambda cls, path, window: None))
353
+
354
+ provider = getattr(server, provider_name)(str(tmp_path))
355
+ await provider.initialize()
356
+
357
+ assert provider._runner.per_text is quantized
358
+
359
+
360
+ BGE_M3_DIR = os.path.join(
361
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
362
+ "data",
363
+ "models",
364
+ "bge-m3",
365
+ )
366
+
367
+
368
+ @pytest.mark.skipif(
369
+ not os.path.exists(os.path.join(BGE_M3_DIR, "model.onnx")) or importlib.util.find_spec("onnxruntime") is None,
370
+ reason="bge-m3 model assets or onnxruntime not installed (local-only test)",
371
+ )
372
+ async def test_bge_m3_int8_vectors_do_not_depend_on_the_batch(monkeypatch):
373
+ """The int8 graph quantizes activations per run, so this is where batching used to leak.
374
+
375
+ Every text must come back bit-equal to its alone vector whether its request
376
+ was merged with others or sent beside other texts in one call.
377
+ """
378
+ monkeypatch.setenv("ONNX_EP_PREFERENCE", "CPUExecutionProvider")
379
+ from cembedding.server import OnnxBgeM3Provider
380
+
381
+ texts = [
382
+ "how large is the recall window?",
383
+ "what did we decide about the deployment schedule last week?",
384
+ "a medium document " + "with some repeated content " * 20,
385
+ "a short text",
386
+ ]
387
+
388
+ provider = OnnxBgeM3Provider(BGE_M3_DIR)
389
+ await provider.initialize()
390
+ try:
391
+ assert provider._runner.per_text is True
392
+ alone = [(await _within(provider.embed([t]), 60))[0] for t in texts]
393
+ together = await _within(provider.embed(texts), 60)
394
+ coalesced = await _within(asyncio.gather(*(asyncio.create_task(provider.embed([t])) for t in texts)), 120)
395
+ finally:
396
+ await provider.shutdown()
397
+
398
+ np.testing.assert_array_equal(np.array(alone), np.array(together))
399
+ np.testing.assert_array_equal(np.array(alone), np.array([rows[0] for rows in coalesced]))
@@ -0,0 +1,40 @@
1
+ """`cembedding-download-model` with no --model fetches bge-m3.
2
+
3
+ bge-m3 is the recommended model (MIT-licensed); the default used to be MiniLM. The
4
+ download functions are replaced, so no test touches the network or the disk.
5
+ """
6
+
7
+ import sys
8
+
9
+ import pytest
10
+
11
+ from cembedding import download_model
12
+
13
+
14
+ @pytest.fixture
15
+ def fetched(monkeypatch):
16
+ calls = []
17
+ monkeypatch.setattr(download_model, "download", lambda: calls.append("miniml") or True)
18
+ monkeypatch.setattr(
19
+ download_model, "download_jina_v5_nano", lambda variant="fp32": calls.append("jina-v5-nano") or True
20
+ )
21
+ monkeypatch.setattr(download_model, "download_bge_m3", lambda model_dir="": calls.append("bge-m3") or True)
22
+ return calls
23
+
24
+
25
+ def _run(monkeypatch, *args):
26
+ monkeypatch.setattr(sys, "argv", ["cembedding-download-model", *args])
27
+ with pytest.raises(SystemExit) as exit_info:
28
+ download_model.main()
29
+ return exit_info.value.code
30
+
31
+
32
+ def test_no_model_fetches_bge_m3(monkeypatch, fetched):
33
+ assert _run(monkeypatch) == 0
34
+ assert fetched == ["bge-m3"]
35
+
36
+
37
+ @pytest.mark.parametrize("name", ["miniml", "jina-v5-nano", "bge-m3"])
38
+ def test_a_named_model_is_still_the_one_fetched(monkeypatch, fetched, name):
39
+ assert _run(monkeypatch, "--model", name) == 0
40
+ assert fetched == [name]
@@ -250,6 +250,8 @@ async def test_each_local_provider_counts_against_the_window_it_truncates_to(
250
250
  session = type("Session", (), {"get_providers": lambda self: ["CPUExecutionProvider"]})()
251
251
  monkeypatch.setattr(server, "_create_ort_session", lambda *a, **k: session)
252
252
  monkeypatch.setattr(server.os.path, "exists", lambda _p: True)
253
+ # No graph file exists here, so the graph is not read for its quantization.
254
+ monkeypatch.setattr(server, "_graph_quantizes_activations", lambda _p: False)
253
255
  monkeypatch.setattr(Tokenizer, "from_file", staticmethod(lambda _p: _toy_tokenizer()))
254
256
  provider = cls(str(tmp_path))
255
257
  await provider.initialize()
@@ -1,148 +0,0 @@
1
- {
2
- "spec_version": 1,
3
- "connector_type": "mgp_server",
4
- "id": "cembedding",
5
- "name": "CEmbedding",
6
- "description": "Local-first embedding server: vector generation + index/search over HTTP (ONNX on-device or API providers). The reference /embed and remote /search server for CPersona.",
7
- "version": "0.9.1",
8
- "category": "tool",
9
- "trust_level": "core",
10
- "magic_seal": "sha256:f75b48b630e7b1cf539577121ffddede7e35a72aadc92733d064359145ff5e64",
11
- "install": {
12
- "source": {
13
- "type": "git",
14
- "url": "https://github.com/Cloto-dev/CEmbedding",
15
- "reference": "",
16
- "subdir": null
17
- },
18
- "package_manager": "uv",
19
- "runtime": "python",
20
- "directory": "",
21
- "dependencies": [],
22
- "bin_name": null
23
- },
24
- "icon": "layers",
25
- "tags": [
26
- "embedding",
27
- "vector",
28
- "search",
29
- "onnx"
30
- ],
31
- "host_compatibility": [
32
- "clotocore",
33
- "claude-code",
34
- "claude-desktop",
35
- "cursor",
36
- "project-airi"
37
- ],
38
- "env_vars": [],
39
- "optional_env_vars": [
40
- {
41
- "name": "EMBEDDING_PROVIDER",
42
- "default": "api_openai",
43
- "description": "Embedding provider: api_openai | onnx_miniml | onnx_jina_v5_nano | onnx_bge_m3 | mlx_bge_m3."
44
- },
45
- {
46
- "name": "EMBEDDING_HTTP_PORT",
47
- "default": "8401",
48
- "description": "HTTP port for /embed and the vector-index endpoints."
49
- },
50
- {
51
- "name": "EMBEDDING_INDEX_ENABLED",
52
- "default": "true",
53
- "description": "Enable the persistent vector index endpoints (/index, /search, /remove, /purge)."
54
- },
55
- {
56
- "name": "EMBEDDING_INDEX_DB_PATH",
57
- "default": "data/embedding_index.db",
58
- "description": "SQLite file backing the vector index."
59
- },
60
- {
61
- "name": "EMBEDDING_SEARCH_BACKEND",
62
- "default": "numpy",
63
- "description": "/search matmul backend: numpy (Accelerate BLAS) or mlx (Apple-GPU resident matrix; numpy fallback when mlx is absent). v0.6.0."
64
- },
65
- {
66
- "name": "EMBEDDING_SIDECAR",
67
- "default": "auto",
68
- "description": "Startup source for the resident vectors: 'auto' maps them from the sidecar file, 'off' always reads them from SQLite. v0.7.0."
69
- },
70
- {
71
- "name": "EMBEDDING_SIDECAR_PATH",
72
- "default": "",
73
- "description": "Where the sidecar file lives. Empty = alongside the index database, named after it. v0.7.0."
74
- },
75
- {
76
- "name": "EMBEDDING_SIDECAR_MIN_ROWS",
77
- "default": "10000",
78
- "description": "Smallest corpus that gets a sidecar file; below it the in-memory index is cheap enough that a file adds nothing. v0.7.0."
79
- },
80
- {
81
- "name": "EMBEDDING_SIDECAR_MAX_TAIL",
82
- "default": "0.25",
83
- "description": "Rebuild the sidecar when the rows written since the last build exceed this fraction of the rows in the file. v0.7.0."
84
- },
85
- {
86
- "name": "ONNX_MODEL_DIR",
87
- "default": "",
88
- "description": "Override the model directory for ONNX providers (auto-resolved by provider when empty)."
89
- },
90
- {
91
- "name": "ONNX_EP_PREFERENCE",
92
- "default": "",
93
- "description": "ONNX execution providers, comma-separated. Empty = auto (CoreML on macOS, DirectML on Windows, else CPU; CPU always ensured)."
94
- },
95
- {
96
- "name": "ONNX_MAX_SEQ_LEN",
97
- "default": "2048",
98
- "description": "Max tokenization length (1-8192; MiniLM clamped to 512 internally)."
99
- },
100
- {
101
- "name": "EMBEDDING_MODEL_VARIANT",
102
- "default": "fp32",
103
- "description": "Precision of jina-v5-nano to load: fp32 / fp16 / int8, downloaded on first use. int8 saves about 280 MB of resident memory and costs four to eight times more per query; vectors already stored were produced at fp32. v0.7.0."
104
- },
105
- {
106
- "name": "ONNX_INTRA_OP_THREADS",
107
- "default": "0",
108
- "description": "ONNX Runtime intra-op threads. 0 = the runtime decides. Set it when the process runs under a CPU quota the runtime cannot see (container limit, shared host); over-subscribing is slower, not faster. v0.7.0."
109
- },
110
- {
111
- "name": "ONNX_GRAPH_OPT_LEVEL",
112
- "default": "all",
113
- "description": "ONNX Runtime graph optimization level: disable / basic / extended / all. Lower it only to compare against an un-fused graph. v0.7.0."
114
- },
115
- {
116
- "name": "ONNX_ALLOW_SPINNING",
117
- "default": "0",
118
- "description": "Whether ONNX Runtime's worker threads keep spinning on the CPU after a run, waiting for the next one. 1 restores the runtime's default. Off, the cores are free as soon as a request is answered: on a 4-core Intel host the spinning held 3 cores for about 1.4 s after each query, and a recall that embedded its query and then searched took a median of 1.58 s against 1.94 s with it. Embed calls were not slower without it (79-81 ms back to back through the server, in either setting). v0.9.1."
119
- },
120
- {
121
- "name": "EMBEDDING_MAX_BATCH",
122
- "default": "64",
123
- "description": "Most texts one model run may carry when concurrent requests are merged into it. 0 disables merging and gives one pass per request. v0.7.0."
124
- },
125
- {
126
- "name": "EMBEDDING_API_KEY",
127
- "default": "",
128
- "description": "Required for the api_openai provider."
129
- },
130
- {
131
- "name": "EMBEDDING_API_URL",
132
- "default": "https://api.openai.com/v1/embeddings",
133
- "description": "API endpoint for the api_openai provider."
134
- },
135
- {
136
- "name": "CEMBEDDING_AUTH_TOKEN",
137
- "default": "",
138
- "description": "Inbound bearer token required on every HTTP request (REST endpoints and the Streamable HTTP MCP transport). Empty = unauthenticated, which is safe only when nothing but this machine can reach the process — a tunnel or reverse proxy forwards to loopback, so a loopback bind is not evidence of that. v0.6.2."
139
- },
140
- {
141
- "name": "CEMBEDDING_REQUIRE_AUTH",
142
- "default": "false",
143
- "description": "Refuse to start when CEMBEDDING_AUTH_TOKEN is empty, instead of starting unauthenticated with a warning. v0.6.2."
144
- }
145
- ],
146
- "auto_restart": true,
147
- "changelog": "v0.9.1: ONNX Runtime's worker threads no longer keep spinning on the CPU after each run (session.intra_op.allow_spinning = 0); ONNX_ALLOW_SPINNING=1 restores the runtime's default. On a 4-core Intel host one short query had left 3 cores busy for about 1.4 s after the response, the moment a caller on the same host searches: a memory server's recall over 100,000 memories that embedded its query through this server took a median of 1.58 s without spinning against 1.94 s with it, in a registered run. Vectors are bit-identical and embed calls were not slower (79-81 ms back to back through the server in every setting tried; 8 x 512-token batches 12.3 s either way). On an Apple laptop (onnxruntime 1.27) the spinning had stopped within 20 ms. 4 regression tests (8 cases).\n\nv0.9.0: GET /capabilities says which backend produced the vectors, so a caller that stores vectors can tell whether a stored one may still be compared with a fresh one. Over /embed it cannot: the request carries texts and the server picks the model, so a client that falls back to a configured name reads two different models as one, including two precisions of one model, which return different vectors through the same tokenizer. The report names the provider, model, width, truncation window, pooling, normalization, and the digests of the graph, tokenizer and weight files the provider actually opened, and reduces them to one fingerprint to store beside a vector. When a component cannot be established, incomplete names it and the fingerprint is null, never a fingerprint over part of the identity; api_openai and mlx_bge_m3 report null because the files that would be hashed are not this process's to read. Null means unknown, not unchanged. /embed is untouched; digests are computed once per file state, off the event loop, and cached. The route sits behind the same bearer authentication as the other REST endpoints. Verified end to end on jina-v5-nano: a complete identity with a fingerprint, 401 without the token when one is configured, and a client pointed at a server without the route reads the 404 as unknown. 34 regression tests.\n\nv0.8.0: The server reports where each text's embedding window closes, so a caller storing long records can split them where the vector stops seeing them instead of guessing from a character count (for one token window that position varies by more than a factor of two). POST /embed accepts an opt-in token_info flag, and POST /count_tokens returns the same report without running the model. Each entry carries the token count, the window, whether the text was cut, and window_end_char, the character offset where the embedded prefix ends. Without the flag /embed answers exactly as before. Providers that cannot see their tokens (api_openai, mlx_bge_m3) report null, meaning unknown. The counting tokenizer is a separate instance that loads on first use (about 29 MiB resident for jina-v5-nano); counting costs 0.4 to 1.6% of an embed call and only when asked. Verified end to end on jina-v5-nano: embedding the reported prefix gives the same vector as the whole text, and cutting 8 characters earlier does not. 24 regression tests.\n\nv0.7.0: Performance and footprint, with results unchanged. Startup maps the resident vectors from a contiguous file next to the index database instead of decoding every blob out of SQLite (100k x 768: 0.23 s and 1.1 GiB peak, to 0.09 s and 402 MiB); SQLite stays the durable record and the file is a cache that can be deleted. The index keeps one matrix per namespace instead of a per-item map plus a rebuilt stack, so a write no longer costs the next search a rebuild (20k x 384: 153 ms to 17 ms over 30 write+search rounds). Concurrent /embed requests that arrive while a model pass is running share the next pass instead of each paying for one (32 clients: p50 219 ms to 90 ms, 150 to 358 req/s). fp16 and int8 weights of jina-v5-nano are selectable with EMBEDDING_MODEL_VARIANT; fp32 stays the default because int8 saves about 280 MB but costs four to eight times more per query. ONNX_INTRA_OP_THREADS and ONNX_GRAPH_OPT_LEVEL configure the runtime session, both defaulting to what it did before. The one observable difference: once the sidecar splits a namespace into two segments, the two BLAS calls can accumulate in different orders, so rows whose scores tie exactly may order differently. EMBEDDING_SIDECAR=off keeps the previous startup path, EMBEDDING_MAX_BATCH=0 the previous embed path. 116 regression tests.\n\nv0.6.2: SECURITY — both HTTP surfaces now support inbound bearer authentication, which they previously had no mechanism for at all. Set CEMBEDDING_AUTH_TOKEN and every request to the REST endpoints (/embed, /index, /search, /remove, /purge) and to the Streamable HTTP MCP transport must carry 'Authorization: Bearer <token>'; missing headers, wrong schemes and wrong tokens are all rejected with 401, compared with hmac.compare_digest. The change is additive: with no token configured the server behaves exactly as 0.6.1 and logs a warning, and CEMBEDDING_REQUIRE_AUTH=true turns that warning into a startup error for operators who want fail-closed today. A later release will make requiring a token the default. The warning deliberately states that a loopback bind is not evidence that requests are local — a tunnel or reverse proxy forwards to loopback, which is how the sibling CPersona server ran publicly reachable and unauthenticated for 13 days. 40 regression tests drive the real middleware at the ASGI and aiohttp layers.\n\nv0.6.1: ONNX providers now pad each batch to its longest sequence instead of a fixed ONNX_MAX_SEQ_LEN. Fixed-length padding made every forward pass cost the full max length (default 2048) regardless of input size: a short recall query encoded in ~617 ms; pad-to-longest brings it to ~7 ms (~90x) and batch document encode from ~0.5 to ~460 docs/s, with bit-identical embeddings (pooling honors the attention mask; parity verified to cosine 1.0). Affects all three local ONNX providers (jina-v5-nano, bge-m3, MiniLM). Adds padding-regression tests.\n\nv0.6.0: /search runs one matmul over a per-namespace resident matrix instead of a per-item Python loop, with vectorized threshold + top-K selection (~21x at 237k x 384: 131 ms -> 6 ms/query). New EMBEDDING_SEARCH_BACKEND env (numpy default, mlx = Apple-GPU resident matrix with numpy fallback). New scripts/backfill_embedding_index.py migrates existing cpersona embedding blobs into the index so a deployment can flip CPERSONA_VECTOR_SEARCH_MODE=remote without losing pre-flip semantic recall. Adds the test suite (12 tests) and CI the repo lacked since extraction.\n\nv0.5.0: PyPI packaging release — flat layout restructured into the cembedding/ package with console scripts (cembedding, cembedding-download-model); published to PyPI as 'cembedding'. Functionally identical to clotohub-servers servers/embedding 0.4.0, from which this repository was extracted on 2026-06-28.\n\nv0.4.0 and earlier: see the clotohub-servers repository history (servers/embedding)."
148
- }
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes