feat(ml): fuse two embedding models and protect the ML service with a token
This commit is contained in:
1 parent
bc00d6901f
commit
b24e5ff906
63 files changed
+2287
-276
No files matched your search
+39
-8
@@ -89,7 +89,7 @@ The eight-minute step-by-step guide with links to the screens and the logins is
|
||||
### 5. FSP, ML, and data
|
||||
|
||||
- FSP: there is no integration in any mode. This build has no off or mock switch, no fixture provider, and no call to an external API. The profile is filled in manually, linking an FSP ID is optional and not available yet, and the path to a category goes through the questionnaire and the test. The project has no official access to FSP data and does not promise it; an FSP link through a fixture provider is planned (see [ARCHITECTURE.md](ARCHITECTURE.md#identity-fsp-and-privacy)).
|
||||
- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML project with the Giga-Embeddings-instruct-480M model on CPU, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No GPU or external inference keys are needed or read.
|
||||
- ML: by default the core and demo stands do not start ML and do not call it; search uses the neutral semantic similarity 0.5 with the `ml_unavailable` flag. Semantic matching is enabled separately: the ML service with the Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models (the ML Compose project on CPU or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), the shared token `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, the semantic policy, and a backfill (see [Semantic matching](#semantic-matching)). No external inference keys are needed or read.
|
||||
- Data: the demo stand holds synthetic data only. Addresses on the reserved domain `@demo.lincodex.test` never receive mail, names are marked as synthetic, categories have the source `synthetic_demo` and are uncalibrated, and the item families are synthetic and had no subject review. Do not register real people on this stand. Synthetic categories are enabled (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) only by the demo overlay and by the overlay of the isolated registration browser suite (see [TESTING.md](TESTING.md#minimal-path-from-registration-to-disclosed-contacts)); `.env.example` sets `false`.
|
||||
|
||||
### 6. Checks
|
||||
@@ -493,6 +493,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
||||
- The new version takes effect at once for new searches and changes no stored result. It is also a new version of the whole product policy, so a category opening pinned to the earlier version has to be opened again (and attested again on a demonstration stand, see above) before new assessment attempts are created. Publish it before the candidates start attempts, or repeat the opening and the attestation afterwards.
|
||||
- The demo values (the coefficients of the PRD, the limit of 10 entries per group, and the small specialization-to-technology taxonomy) are in [architecture](ARCHITECTURE.md#product-policy-versions); they are not calibrated. The isolated browser fixture publishes the same section itself.
|
||||
- `policy-publish semantic` publishes the next version with the matching section replaced by the semantic one (`DemoSemanticMatchingPolicy`: Fit weights 0.4167 / 0.0833 / 0.5, the model, the calibration, and the explanation thresholds; see [Semantic matching](#semantic-matching)); when the latest version already has a semantic section, nothing changes. The version with the PRD point stays the previous one.
|
||||
- `policy-publish semantic-ensemble` publishes the next version with the semantic section replaced by the Giga + Qwen3-Embedding ensemble (`DemoSemanticEnsembleMatchingPolicy`: two models, their weights, mean, and std, and the calibration of the fused score; the Fit weights and explanation thresholds stay the same); when the semantic section of the latest version already names both models, nothing changes. The version with Giga alone stays the previous one. The ML service must serve both models, and a backfill follows the publication (see [Semantic matching](#semantic-matching)).
|
||||
|
||||
## Isolated demo stand
|
||||
|
||||
@@ -529,17 +530,25 @@ What the seed creates (all names carry a synthetic marker; addresses are on `@de
|
||||
|
||||
ML uses a separate Compose file and project; it needs no Redis or SeaweedFS. It joins the external network of the core project (`APP_NETWORK`) with the alias `ml`, so the backend reaches `http://ml:8000` without a published port; start the core project first. The host port binds only to 127.0.0.1:8000 by default for diagnostics; change ML_BIND_ADDRESS only after preparing a private address and firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
||||
|
||||
The image is based on `python:3.14-slim` (PyTorch publishes glibc wheels only, so Alpine cannot be used; the minor version is fixed for `requires-python` and the lock). Dependencies, including the CPU build of PyTorch from the `download.pytorch.org/whl/cpu` index, are installed with uv only in the build stage; the runtime has no pip. A separate stage fetches the Giga-Embeddings-instruct-480M files at the pinned revision from `ml/model/giga-embeddings-480m.lock.json` and checks the size and SHA-256 of every file (about 0.98 GB of safetensors weights); at startup the service checks the SHA-256 again (`ML_VERIFY_WEIGHTS=true`, a few seconds) and runs with `HF_HUB_OFFLINE=1`. The expected image size is about 2.5 GB (Python and PyTorch CPU about 1.4 GB, the model about 1 GB); the image was not built on this machine because of free disk space.
|
||||
The image is based on `python:3.14-slim` (PyTorch publishes glibc wheels only, so Alpine cannot be used; the minor version is fixed for `requires-python` and the lock). Dependencies, including the CPU build of PyTorch from the `download.pytorch.org/whl/cpu` index, are installed with uv only in the build stage; the runtime has no pip. A separate stage fetches the files of both models at the pinned revisions from `ml/model/giga-embeddings-480m.lock.json` and `ml/model/qwen3-embedding-0.6b.lock.json` into `/opt/lincodex/models/giga-480m` and `/opt/lincodex/models/qwen3-0.6b` and checks the size and SHA-256 of every file (about 0.98 and 1.19 GB of safetensors weights); at startup the service checks the SHA-256 again (`ML_VERIFY_WEIGHTS=true`, a few seconds) and runs with `HF_HUB_OFFLINE=1`. The container listens on 0.0.0.0:8000 through `python -m lincodex_ml.serve`, so the service does not start without `ML_SERVICE_TOKEN`. The expected image size is about 3.7 GB (Python and PyTorch CPU about 1.4 GB, the models about 2.2 GB); the image was not built on this machine because of free disk space.
|
||||
|
||||
| Variable | Default | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `ML_EMBEDDER` | `giga` in the image and Compose, `none` outside the image | `giga` - the model of the image, `fake` - a deterministic hash encoder for stands without the model (its model id does not match the policy, so its vectors are never used), `none` - the service stays not ready |
|
||||
| `ML_EMBEDDER` | `giga,qwen3` in the image and Compose, `none` outside the image | a comma list of models (`giga`, `qwen3`), the first answers a request without `model`; `fake` - a deterministic hash encoder for stands without the models (its model id does not match the policy, so its vectors are never used), `none` - the service stays not ready |
|
||||
| `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` | empty | the bearer token shared with the backend (at least 32 printable characters, a secret); without it the service answers loopback callers only and refuses to start on a non-loopback address |
|
||||
| `ML_LISTEN_HOST`, `ML_LISTEN_PORT` | 127.0.0.1, 8000 (0.0.0.0, 8000 in the image) | address and port of `python -m lincodex_ml.serve` |
|
||||
| `ML_GIGA_MODEL_DIR`, `ML_QWEN3_MODEL_DIR` | the image directories | the model files; a Hugging Face snapshot directory works too |
|
||||
| `ML_GIGA_MODEL_LOCK`, `ML_QWEN3_MODEL_LOCK` | `model.lock.json` in the model directory | the lock file the files are checked against |
|
||||
| `ML_DEVICE` | `cpu` | `cpu`, `cuda`, or `cuda:<index>` |
|
||||
| `ML_DTYPE` | `float32` | `float16` and `bfloat16` on CUDA only |
|
||||
| `ML_CUDA_MEMORY_LIMIT_MB` | 0 (no limit) | CUDA allocator limit of the process; the CUDA context adds about 130 MiB |
|
||||
| `ML_EXIT_ON_LOAD_FAILURE` | false | end the process after a load failure other than a lack of device memory, so a supervisor restarts it |
|
||||
| `ML_TORCH_THREADS` | 4 | torch threads; with 4 the study meets the CPU targets |
|
||||
| `ML_MICRO_BATCH` | 1 | micro-batch size; 1 gives every text the same vector whatever the request holds |
|
||||
| `ML_MAX_TOKENS` | 1024 | tokens a text, as in the study |
|
||||
| `ML_VERIFY_WEIGHTS` | true | check the SHA-256 of the weights at startup |
|
||||
|
||||
Container limits: 4 CPUs and 5 GiB (the float32 model takes about 3.6 GiB resident). Readiness turns 200 only after the load and the warm-up.
|
||||
Container limits: 4 CPUs and 8 GiB (on CPU in float32 Giga takes about 3.6 GiB resident and Qwen3-Embedding about 2.5 GiB more). Readiness turns 200 only after both models are loaded and warmed up. A lack of device memory never stops the process: a load is retried, a request answers 503, and `/readyz` answers 503 for 30 seconds.
|
||||
|
||||
make -C deploy ml-config
|
||||
make -C deploy ml-build
|
||||
@@ -547,14 +556,29 @@ Container limits: 4 CPUs and 5 GiB (the float32 model takes about 3.6 GiB reside
|
||||
make -C deploy ml-logs
|
||||
make -C deploy ml-down
|
||||
|
||||
For development without Docker: `make -C ml model-fetch` fetches and checks the same files into `ML_MODEL_DIR` (default `~/.cache/lincodex-ml/giga-480m`), and `make -C ml test-model` checks that the vectors match the study. Measured on an Apple M5 (CPU, 4 threads, over HTTP, 20 requests): a need view of 887 characters p50 296 ms / p95 707 ms, a profile of 500 characters 207 / 237 ms, a short requirement 74 / 166 ms, a card job batch of 13 texts 2.2 / 5.4 s. This is one laptop with other load, not a stand measurement.
|
||||
For development without Docker: `make -C ml model-fetch` fetches and checks the same files into `ML_GIGA_MODEL_DIR` and `ML_QWEN3_MODEL_DIR` (defaults `~/.cache/lincodex-ml/giga-480m` and `~/.cache/lincodex-ml/qwen3-0.6b`), and `make -C ml test-model` compares the vectors of both models with the study (`ML_TEST_DEVICE=cuda` on a GPU). Giga measured on an Apple M5 (CPU, 4 threads, over HTTP, 20 requests): a need view of 887 characters p50 296 ms / p95 707 ms, a profile of 500 characters 207 / 237 ms, a short requirement 74 / 166 ms, a card job batch of 13 texts 2.2 / 5.4 s. This is one laptop with other load, not a stand measurement.
|
||||
|
||||
## ML service on a GPU host
|
||||
|
||||
On a separate GPU host the service runs without Docker: as the systemd user unit `lincodex-ml.service` of the service user (template [deploy/ml-gpu/lincodex-ml.service](../../deploy/ml-gpu/lincodex-ml.service), lingering enabled for the user) with a virtualenv and models from local files. Both models in float16 take 2.2-2.4 GiB of VRAM, so the service fits next to another user of the same card.
|
||||
|
||||
1. Code: the `ml/` directory of the release (`git archive`) in `~/lincodex-ml/app/ml`.
|
||||
2. Virtualenv: the pinned uv 0.12.22 creates `~/lincodex-ml/venv`. `make -C ml cuda-requirements` writes the versions pinned in `uv.lock` with the CUDA build of torch (`torch==2.11.0+cu128`) to `ml/dist/requirements-cuda.txt`; install the torch line from the `https://download.pytorch.org/whl/cu128` index first, then the other lines from PyPI (`uv pip install --python ~/lincodex-ml/venv/bin/python ...`). A shared uv cache with `UV_LINK_MODE=hardlink` takes no space for wheels it already holds, but the cache is keyed by the index address: another spelling of the address downloads torch and the CUDA libraries again (about 6 GB). Exception: where disk is short, the virtualenv uses the system CPython 3.12 with the same package versions (the cp314 CUDA wheel of torch does not fit), and the package is not installed: the unit sets `PYTHONPATH` to `src`. The service unit tests pass on 3.12, but 3.14 stays the main version, so 3.13+ syntax in `ml/src` would break such a host.
|
||||
3. Models: Hugging Face snapshot directories at the pinned revisions (`HF_HOME` read-only) or `make -C ml model-fetch`; at startup the files are checked against the lock files of the release.
|
||||
4. Settings: copy [deploy/ml-gpu/ml.env.example](../../deploy/ml-gpu/ml.env.example) to `~/.config/lincodex-ml/ml.env` (directory 700, file 600). Generate the token on the host with a CSPRNG (`python3 -c 'import secrets; print(secrets.token_hex(32))'`); it lives only in this file and in the backend environment. The address is a private address of the host, never 0.0.0.0.
|
||||
5. Start: put the unit template in `~/.config/systemd/user/lincodex-ml.service`, then `systemctl --user daemon-reload` and `systemctl --user enable --now lincodex-ml.service`. Restart after a code or settings update with `systemctl --user restart lincodex-ml.service`, check it with `systemctl --user status lincodex-ml.service`, follow the log with `journalctl --user -u lincodex-ml.service -f`. The unit sets `Restart=on-failure`, `MemoryHigh=5G`, `MemoryMax=6G`, `CPUQuota=400%`, 4 torch and OMP threads, and `ML_EXIT_ON_LOAD_FAILURE=true`: a lack of device memory never stops the process, while other load failures (for example a driver that is not ready at host startup) end it and systemd restarts it after 15 seconds.
|
||||
6. Network: the unit changes no firewall or system setting. Restrict the port to the app host address at the host or network level; the traffic crosses the LAN without TLS, so the token and the texts are visible on that segment.
|
||||
|
||||
Precision and VRAM (RTX 5060 Ti 16 GB, measured 2026-10-11, a process budget of about 2.5 GB): in float32 Giga alone takes 1984 MiB after the load and up to 2750 MiB under a request of 1024-token texts, Qwen3 2404 and 3038 MiB, together about 4.3 GiB after the load, so float32 does not fit. In float16 both models in one process take 2252 MiB after the load and 2404 MiB under the worst request (32 texts of 1024 tokens), with the allocator capped by `ML_CUDA_MEMORY_LIMIT_MB=2300`. Quality of float16 against float32 on the study's DEV data (product views): vector cosine at least 0.99986 (Giga) and 0.99999 (Qwen3), nDCG@10 changed by -0.0004 and +0.0008, for the ensemble by +0.0002 (threshold 0.005), the ensemble top-10 is the same set for 30 of 30 DEV needs and in the same order for 28, and a repeated encode at micro-batch 1 gives the same bits. `bfloat16` was rejected: the top-10 matches for 27 of 30, the order for 14. Hence `ML_DTYPE=float16`; the mean, std, and calibration of the ensemble were computed on float16 vectors.
|
||||
|
||||
Latency over the LAN from the app host (40 requests, one text, micro-batch 1, CUDA float16): a need view - Giga p50 11.4 / p95 13.0 ms, Qwen3 12.5 / 14.5 ms; a profile - 11.2 / 12.9 and 12.1 / 13.8 ms; a card job batch of 13 texts - 132 / 135 and 143 / 160 ms. The process keeps about 2.6 GiB resident (peak 2.9 GiB). This is one host measured while the other model on the card was not loaded, not a load test.
|
||||
|
||||
## Semantic matching
|
||||
|
||||
The search never calls ML: it reads the vectors that background jobs computed (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)). To enable it on a stand:
|
||||
|
||||
1. `make -C deploy up`, then `make -C deploy ml-up`, and wait for `/readyz` 200.
|
||||
2. Set `SEMANTIC_MATCHING_ENABLED=true` (and `ML_SERVICE_URL` if it differs) in the stand `.env` and restart the backend (`make -C deploy up`).
|
||||
1. `make -C deploy up`, then `make -C deploy ml-up` (or the [ML service on a GPU host](#ml-service-on-a-gpu-host)), and wait for `/readyz` 200.
|
||||
2. Set `SEMANTIC_MATCHING_ENABLED=true`, `ML_SERVICE_TOKEN` (the token of the ML service), and `ML_SERVICE_URL` if it differs (`http://<address>:<port>` for a GPU host) in the stand `.env` and restart the backend (`make -C deploy up`).
|
||||
3. Publish the semantic policy section: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (with the stand `DATABASE_URL`). Like the `matching` section, a new policy version requires opening and attesting the category again on the demo stand.
|
||||
4. Compute vectors for existing data: `make -C backend semantic-backfill ARGS='all --run <label>'`. The command needs only `DATABASE_URL`; it schedules jobs page by page and prints the cursor to resume with (`--after`). Repeating the same label schedules nothing twice; a new label recomputes, and unchanged texts cost no ML call. The backend worker runs the jobs.
|
||||
|
||||
@@ -562,6 +586,7 @@ The search never calls ML: it reads the vectors that background jobs computed (s
|
||||
| --- | --- | --- |
|
||||
| `SEMANTIC_MATCHING_ENABLED` | false | schedule and run vector jobs |
|
||||
| `ML_SERVICE_URL` | `http://ml:8000` in Compose | ML origin without a path or credentials |
|
||||
| `ML_SERVICE_TOKEN` | empty | bearer token of the ML service, 32-512 printable characters without spaces; required while `SEMANTIC_MATCHING_ENABLED=true`; a secret that never reaches a log |
|
||||
| `ML_REQUEST_TIMEOUT` | 30s | timeout of one ML request |
|
||||
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | after that many consecutive failures the client does not call ML for that long |
|
||||
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | run the checks of project repositories on `api.github.com` |
|
||||
@@ -571,7 +596,13 @@ The search never calls ML: it reads the vectors that background jobs computed (s
|
||||
|
||||
Without ML, or while it is unavailable, the search works as before: the neutral `Sem` 0.5 with the `ml_unavailable` flag; jobs retry up to 20 times and then wait for an operator (a new backfill). The isolated browser stand (e2e) does not start ML and uses policy V4; the demo stand also runs without ML by default, and enabling it takes the same steps with the project `lincodex-demo`. Metrics: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` in the backend, `lincodex_ml_embedding_request_seconds` and `lincodex_ml_embedding_texts_total` in ML.
|
||||
|
||||
The model ensemble (Giga + Qwen3-Embedding-0.6B) is not enabled; the steps to enable it - a second model in the ML service, 8 threads, a calibration of the fused score, a new policy with two `members`, and a backfill - are in [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations). The search never reads vectors of a model that the policy no longer names; they stay for a rollback to the previous policy version.
|
||||
The Giga + Qwen3-Embedding-0.6B ensemble (see [ARCHITECTURE.md](ARCHITECTURE.md#semantic-layer-and-explanations)) is enabled after the steps above, once the ML service serves both models (`ML_EMBEDDER=giga,qwen3`):
|
||||
|
||||
1. `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'` - a new policy version with two models; the version with Giga alone stays the previous one.
|
||||
2. Right after it, `make -C backend semantic-backfill ARGS='candidates --run <label>'` and `make -C backend semantic-backfill ARGS='needs --run <label>'` (or `all`). Jobs compute the vectors of every model of the effective policy: the Giga vectors do not change and cost no ML call, and Qwen3 encodes only the `whole` view of each card and need. Until the backfill ends, entries without Qwen3 vectors get the neutral `Sem` with `ml_unavailable`, so switch at a quiet time.
|
||||
3. Check: `SELECT model_id, count(*) FROM semantic_vectors WHERE item_key = 'whole' GROUP BY model_id` - the Qwen3 count catches up with the Giga count.
|
||||
|
||||
Provenance of the policy values: the DEV judgments of the LincodexMatch study (30 needs, 3220 judged pairs), the study's profiles and needs rendered by the product view builder, ML service vectors on CUDA in float16, and the weights of step 5 of the study; the encoding and fitting scripts and their outputs are kept next to the research run on the GPU host (`lincodex-ml/eval/`). The search never reads vectors of a model that the policy no longer names; they stay for a rollback to the previous policy version.
|
||||
|
||||
## Separate monitoring Compose project
|
||||
|
||||
|
||||
Reference in new issue
Block a user