feat(ml): fuse two embedding models and protect the ML service with a token

This commit is contained in:
shira committed 2026-10-11 14:40:52 +03:00
1 parent bc00d6901f
commit b24e5ff906
63 files changed
+2287 -276

No files matched your search

+2 -2
View File
@@ -834,13 +834,13 @@ Store each search as a search_run with its company, original need, filters, rank
Implemented: embeddings of needs and published cards, `Sem` in Fit, a structured "why in the selection" explanation, candidate projects, and checks of their GitHub repositories. The basis is the LincodexMatch study (DEV 30 needs, TEST 70, 2594 synthetic profiles); its numbers come from synthetic data and are not product measurements.
- Model. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) at revision `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 dimensions, up to 1024 tokens a text. On TEST it is best on indirect matches (nDCG@10 indirect 0.571 against 0.409 for Qwen3-Embedding-0.6B) and meets the CPU targets with 4 threads (profile p95 352 ms, search over 100k 591 ms in the study). The recipe repeats the study: the need and each requirement are encoded with the prompt `Instruct: Given a query, retrieve relevant passages\nQuery: `, the card and its items without a prompt, mean pooling over the attention mask including the prompt tokens, L2 normalization. The remote code of the model repository is neither fetched nor executed: the same bidirectional Qwen3 is written in `ml/src/lincodex_ml/inference/giga.py`, and `make -C ml test-model` compares the vectors with the study's (difference < 1e-6).
- ML service. `POST /v1/embeddings` of the `api/ml` contract (up to 32 texts of 8000 characters, a body up to 2 MiB, an optional model id `model`, a response with id, revision, dimension, and `prompt_version`). The service loads one model now; a request for another model gets 400 with the pointer `/model`. The weights are fetched once at image build time from the lock file `ml/model/giga-embeddings-480m.lock.json` with SHA-256 verification (safetensors, configs, and the tokenizer only); the service runs offline. Readiness turns ready only after the load and a warm-up encode; before that it answers 503 `service_unavailable`. Texts are encoded one request at a time in micro-batches of a fixed size (default 1), ordered by length with the request position as the tie-breaker, so the same texts on the same image and thread count give the same vectors.
- ML service. `POST /v1/embeddings` of the `api/ml` contract (up to 32 texts of 8000 characters, a body up to 2 MiB, an optional model id `model`, a response with id, revision, dimension, and `prompt_version`). The service loads the models of the `ML_EMBEDDER` list (`giga`, `qwen3`; the first answers a request without `model`); a request for a model it did not load gets 400 with the pointer `/model`. Each model is pinned by a lock file (`ml/model/giga-embeddings-480m.lock.json`, `ml/model/qwen3-embedding-0.6b.lock.json`) with SHA-256 verification (safetensors, configs, and the tokenizer only); no remote code runs and the service works offline. The device is `ML_DEVICE` (`cpu` by default or `cuda`), the precision `ML_DTYPE` (`float32`; `float16` and `bfloat16` on CUDA only), and `ML_CUDA_MEMORY_LIMIT_MB` caps the allocator of the process on a shared GPU. A lack of device memory never stops the process: a load is retried with a growing pause (15 s, up to 5 min), a request answers 503 `service_unavailable`, and `/readyz` answers 503 for 30 seconds, after which the service serves again. Readiness turns ready only after every model is loaded and a warm-up encode has finished. Texts are encoded one request at a time in micro-batches of a fixed size (default 1), ordered by length with the request position as the tie-breaker, so the same texts on the same installation, device, precision, and thread count give the same vectors (on CUDA checked by a repeated encode). Every route except `/healthz` and `/readyz` requires `Authorization: Bearer <token>` (see [SECURITY.md](SECURITY.md#outbound-requests-and-ml)).
- Fields that rank. Only what the anonymous card of the candidate shows before cohort generalization: the roles of `self_assessment` and `categories` (`backend (middle)`), the recognized stack codes, and the published projects with the public metadata of verified repositories. Private profile text (resume, experience `summary`, employers) does not enter ranking, as before for ML ("Go sends only allowed inputs"). The study shows that private experience improves quality (proposal 3 of the report); allowing its server-side use without showing it is an open owner decision and needs an explicit privacy policy decision.
- Vectors. Table `semantic_vectors` (migration `00049`): the subject (`candidate` or `need`), the item key (`whole`, `roles`, `stack`, `project:<n>`, `required_skill:<n>`, `desired_skill:<n>`, `task:<n>`), the SHA-256 of the text with the rendering version `semantic-views-v1`, the model, revision, prompt version, dimension, and the vector as little-endian float32 (4 KiB for 1024 dimensions: exact and the same on every platform; int8 is deferred until size becomes a problem). Rows cascade with the account or the need. A candidate keeps exactly one set per model, a need the set of its latest requirements snapshot.
- Pipeline. A profile save, a publication change, a new requirements snapshot, and a finished repository check schedule a due job (`semantic.candidate`, `semantic.need`) in the same transaction; no user request waits for ML. The handler takes an advisory lock of the subject, renders the current card or snapshot, compares the digests with the stored ones (unchanged texts cost no ML call), encodes the texts, and replaces the set. The job encodes the texts with every model of the policy `members`, passing its id; the first model stores every item, the others store `whole` only. The model of the response (id, revision, prompt version) must equal the policy model, otherwise the job is retried. Up to 20 attempts with backoff outlast an ML outage; the job of an unpublished candidate removes their vectors. A C2 revocation closes the card in another usecase and schedules no job: the vectors stay until the next candidate job or a backfill, but an invisible card never enters a search. The `semantic-backfill` command schedules jobs for every candidate with a profile and every need page by page, idempotent per run label and resumable by cursor.
- Sem and Fit. The search never calls ML: it renders the need snapshot, reads the vectors with matching digests and the `whole` vectors of the visible candidates for every policy model, computes the fused score Σ w·(cos - mean)/std, and turns it into `Sem` with the isotonic calibration of the policy (P(relevant | score) on DEV, ECE 0.015-0.049 against 0.17-0.57 for the raw cosine) by integer interpolation. By default there is one model with weight 1, mean 0, and std 1, so the score is the cosine. Without vectors of the need or the candidate for any policy model, or without ML, `Sem` is the neutral 0.5 with `ml_unavailable` for that entry, as before. The candidate set, filters, visibility, quotas, and cohort rules do not change; BM25 is not mixed into the score (on TEST it cuts indirect from 0.571 to 0.250).
- Policy. `domain.DemoProductPolicyV5()` is V4 with the semantic section `matching.semantics` (`members` - one Giga model with revision, prompt version, weight 1, mean 0, and std 1; 80 calibration points `score_bp`, explanation thresholds, limit, source) and Fit weights 0.4167 / 0.0833 / 0.5. With the PRD weight 0.10 Fit reaches nDCG@10 0.649 on TEST against 0.818 for the encoder alone, with 0.5 it reaches 0.838; Cov and Dom keep the PRD ratio 5:1. V4 stays the previous version (the PRD point). Publication: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'`.
- Ensemble. The design is ready for S5-DE of the study: `Sem` = calibration(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), nDCG@10 0.842 on TEST against 0.818 for Giga alone, p95 about 0.85 s at 8 threads on 12 cores. It is not enabled now. To enable it: (1) add a second configured model `Qwen/Qwen3-Embedding-0.6B` at revision `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3` to the ML service with a lock file, its prompt, and a prompt version (the service picks the model by the `model` field; loading several models is separate work); (2) raise `ML_TORCH_THREADS` to 8 and the container limits; (3) on DEV, compute the mean and std of each model's cosine and refit the isotonic calibration and, if needed, the thresholds on the fused score (the study standardized z over the corpus of each need, the product uses global mean and std from the policy, so the numbers need a recheck); (4) publish a new policy version with two `members` (Giga first, it also explains entries; weights add up to 1) and the new calibration; (5) run `semantic-backfill` for candidates and needs as soon as the version takes effect. Jobs compute vectors for the effective policy only, so until the backfill ends, entries without vectors of the second model get the neutral `Sem`; switch at a quiet time. The Giga vectors are not recomputed (same digests), and vectors of earlier models stay, so a rollback to the previous policy version needs no recompute.
- Ensemble. S5-DE of the study is implemented: `Sem` = calibration(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), `domain.DemoProductPolicyV6()` (V5 with the section `DemoSemanticEnsembleMatchingPolicy`, the same Fit weights). The second model is `Qwen/Qwen3-Embedding-0.6B` (Apache-2.0) at revision `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3`, a stock Qwen3 without remote code: the need is encoded with the model's prompt `Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:` (joined without a separator), the card without a prompt, the tokenizer appends end-of-text, and the vector is the hidden state of the last token, L2-normalized (`prompt_version` `qwen3-card-last-v1`, `ml/src/lincodex_ml/inference/qwen3.py`, compared with the study's vectors by `make -C ml test-model`). The weights 0.4 / 0.6 are the step 5 choice of the study (5-fold CV over the DEV needs, w_giga = 0.4 in four folds of five). The mean and std were computed again on product views: the study's needs and profiles were rendered by the product view builder (`domain.NewNeedSemanticDocument` gives the study's text for all 100 needs; the card has the catalog roles with the declared grade, the card stack codes, and one published project per study experience entry) and encoded by the ML service on CUDA in float16. The mean is over all DEV pairs (Giga 0.2497, Qwen3 0.3636), the std is the pooled within-need deviation (0.0741 and 0.0731), so the fixed z reproduces the study's z over the corpus of each need: DEV nDCG@10 all / indirect 0.809 / 0.518 against 0.809 / 0.518 for the study's form and 0.738 / 0.403 for Giga alone on the same views. The calibration is the isotonic regression of P(consensus >= 2) on the fused score of the 3220 judged DEV pairs (994 positive), computed with the rounded mean and std of the policy; 56 points, 5-fold CV ECE by need 0.025. The explanation thresholds stay those of Giga (the first model, which alone provides item vectors). The provenance is in the policy `source` and in [DEPLOY.md](DEPLOY.md#semantic-matching). Without projects on the card the signal is weak (DEV nDCG@10 0.21 for the ensemble and 0.23 for Giga alone on cards with roles and stack only), so the gain of the ensemble depends on candidates publishing projects. Publication and backfill: `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'`, then `semantic-backfill` for candidates and needs. Jobs compute vectors for every model of the effective policy, so until the backfill ends, entries without Qwen3 vectors get the neutral `Sem`; switch at a quiet time. The Giga vectors are not recomputed (same digests), and V5 stays the previous version: the vectors of both models stay, so a rollback to Giga needs no recompute.
- Explanation. For a need search every confirmed requirement (required and desired skill, task) is paired with the closest card item by cosine. Thresholds from DEV: P(pair relevant | best cosine of the requirement) 0.5 and 0.7, for skills 0.3673 / 0.4607 (`medium` / `high`), for tasks 0.2997 / 0.4192. The response carries `semantic_evidence` items: the kind and text of the requirement (the organization's own need text), the item kind (`project`, `stack`, `roles`), the project title only when the candidate published the `projects` field and the title did not change since the vectors were computed, `repository_verified`, and the band; ordered `high` first, then by cosine, then by requirement order; at most 6 (policy). The stack and roles explain only while the card shows them to this organization after cohort generalization. No model text enters the explanation. Showing a project title is recorded in the candidate's access history as the `projects` field. The precision of the explanations was not checked: the study's sample of 50 pairs remained unlabeled.
#### Candidate projects and GitHub repositories