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
@@ -1,6 +1,6 @@
|
|||||||
# ML service standard
|
# ML service standard
|
||||||
|
|
||||||
The ML service is a separate Python HTTP service. It serves health and readiness routes and one model-backed endpoint, `POST /v1/embeddings`, with a pinned embedding model baked into its image. Ordinary tests use the deterministic fake encoder; the real model runs only in the marked slow test.
|
The ML service is a separate Python HTTP service. It serves health and readiness routes and one model-backed endpoint, `POST /v1/embeddings`, with pinned embedding models whose files are verified against the lock files in ml/model/ (baked into the image, or local files on a GPU host). Every route except health and readiness requires the shared bearer token. Ordinary tests use the deterministic fake encoder; the real models run only in the marked slow tests.
|
||||||
|
|
||||||
Keep the service contract in api/ml/. The Go client uses backend/codegen/ogen-ml.yml and is consumed under backend/internal/adapter/secondary/ml/api/. Python model generation belongs to ml/codegen/pyproject.toml: datamodel-code-generator produces Pydantic v2 models from api/ml/openapi.bundle.yml in ml/src/lincodex_ml/api/models.py. Keep generator dependencies in ml/pyproject.toml and uv.lock; the codegen pyproject contains tool settings only. Health/readiness handlers import generated models instead of maintaining duplicate transport schemas.
|
Keep the service contract in api/ml/. The Go client uses backend/codegen/ogen-ml.yml and is consumed under backend/internal/adapter/secondary/ml/api/. Python model generation belongs to ml/codegen/pyproject.toml: datamodel-code-generator produces Pydantic v2 models from api/ml/openapi.bundle.yml in ml/src/lincodex_ml/api/models.py. Keep generator dependencies in ml/pyproject.toml and uv.lock; the codegen pyproject contains tool settings only. Health/readiness handlers import generated models instead of maintaining duplicate transport schemas.
|
||||||
|
|
||||||
|
|||||||
@@ -142,5 +142,9 @@ GRAFANA_ADMIN_PASSWORD=replace-this-grafana-password
|
|||||||
ML_BIND_ADDRESS=127.0.0.1
|
ML_BIND_ADDRESS=127.0.0.1
|
||||||
ML_HTTP_PORT=8000
|
ML_HTTP_PORT=8000
|
||||||
ML_METRICS_TARGET=
|
ML_METRICS_TARGET=
|
||||||
|
# Shared bearer token of the ML service and the backend (a secret of at least
|
||||||
|
# 32 characters, for example openssl rand -hex 32); required by the ML
|
||||||
|
# container and by the backend while SEMANTIC_MATCHING_ENABLED is true.
|
||||||
|
ML_SERVICE_TOKEN=
|
||||||
# For rootless Docker, use the Unix socket from `docker context inspect`.
|
# For rootless Docker, use the Unix socket from `docker context inspect`.
|
||||||
DOCKER_SOCKET_PATH=/var/run/docker.sock
|
DOCKER_SOCKET_PATH=/var/run/docker.sock
|
||||||
@@ -16,7 +16,7 @@ EmbeddingText:
|
|||||||
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
|
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
|
||||||
EmbeddingRequest:
|
EmbeddingRequest:
|
||||||
type: object
|
type: object
|
||||||
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same image and thread count give the same vectors.'
|
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same installation, device, precision, and thread count give the same vectors.'
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required:
|
required:
|
||||||
- kind
|
- kind
|
||||||
@@ -27,7 +27,7 @@ EmbeddingRequest:
|
|||||||
minLength: 1
|
minLength: 1
|
||||||
maxLength: 200
|
maxLength: 200
|
||||||
pattern: ^[A-Za-z0-9._/-]+$
|
pattern: ^[A-Za-z0-9._/-]+$
|
||||||
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
|
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
|
||||||
kind:
|
kind:
|
||||||
$ref: '#/EmbeddingInputKind'
|
$ref: '#/EmbeddingInputKind'
|
||||||
texts:
|
texts:
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ schemas:
|
|||||||
deterministic way: texts are ordered by length with the request position
|
deterministic way: texts are ordered by length with the request position
|
||||||
as the tie-breaker, encoded in micro-batches of the configured size, and
|
as the tie-breaker, encoded in micro-batches of the configured size, and
|
||||||
returned in request order. The same texts in the same request on the same
|
returned in request order. The same texts in the same request on the same
|
||||||
image and thread count give the same vectors.
|
installation, device, precision, and thread count give the same vectors.
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required:
|
required:
|
||||||
- kind
|
- kind
|
||||||
@@ -38,10 +38,10 @@ schemas:
|
|||||||
pattern: "^[A-Za-z0-9._/-]+$"
|
pattern: "^[A-Za-z0-9._/-]+$"
|
||||||
description: >-
|
description: >-
|
||||||
Identifier of the model to use, as `EmbeddingModel.id` reports it.
|
Identifier of the model to use, as `EmbeddingModel.id` reports it.
|
||||||
Absent means the default model of the service. A service may load
|
Absent means the default model of the service, the first one it is
|
||||||
several models, for example the members of an ensemble; a model it
|
configured with. A service may load several models, for example the
|
||||||
does not serve answers 400 validation_failed with the pointer
|
members of an ensemble; a model it does not serve answers 400
|
||||||
`/model`.
|
validation_failed with the pointer `/model`.
|
||||||
kind:
|
kind:
|
||||||
$ref: "#/schemas/EmbeddingInputKind"
|
$ref: "#/schemas/EmbeddingInputKind"
|
||||||
texts:
|
texts:
|
||||||
|
|||||||
@@ -2,8 +2,21 @@ openapi: 3.2.0
|
|||||||
info:
|
info:
|
||||||
title: Lincodex ML Operational API
|
title: Lincodex ML Operational API
|
||||||
version: 0.1.0
|
version: 0.1.0
|
||||||
|
description: |-
|
||||||
|
Internal API of the ML service. Only the Go backend calls it; it is never
|
||||||
|
exposed to browsers or to the public network.
|
||||||
|
|
||||||
|
Authentication: every operation except the health routes requires
|
||||||
|
`Authorization: Bearer <token>` when the service has a token, and the
|
||||||
|
service refuses to listen on a non-loopback address without one. The
|
||||||
|
token is a shared random secret of at least 32 printable characters from
|
||||||
|
the deployment secret store, never from this repository. A missing or
|
||||||
|
wrong token answers 401 `unauthenticated`. A service without a token
|
||||||
|
answers only callers on its own loopback interface.
|
||||||
servers:
|
servers:
|
||||||
- url: /
|
- url: /
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
paths:
|
paths:
|
||||||
/healthz:
|
/healthz:
|
||||||
get:
|
get:
|
||||||
@@ -46,12 +59,11 @@ paths:
|
|||||||
/v1/embeddings:
|
/v1/embeddings:
|
||||||
post:
|
post:
|
||||||
operationId: CreateMLEmbeddings
|
operationId: CreateMLEmbeddings
|
||||||
summary: Encode texts into normalized vectors with the pinned embedding model.
|
summary: Encode texts into normalized vectors with a pinned embedding model.
|
||||||
description: |-
|
description: |-
|
||||||
Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on the private network. The request carries only text that the caller is allowed to process, and the service never logs it.
|
Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. The request carries only text that the caller is allowed to process, and the service never logs it.
|
||||||
|
|
||||||
The service answers 503 service_unavailable until the model is loaded from the image and a warm-up encode has finished; `/readyz` reports the same state. A request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
|
The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, a request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
|
||||||
security: []
|
|
||||||
tags:
|
tags:
|
||||||
- inference
|
- inference
|
||||||
requestBody:
|
requestBody:
|
||||||
@@ -69,6 +81,8 @@ paths:
|
|||||||
$ref: '#/components/schemas/EmbeddingResponse'
|
$ref: '#/components/schemas/EmbeddingResponse'
|
||||||
'400':
|
'400':
|
||||||
$ref: '#/components/responses/Problem'
|
$ref: '#/components/responses/Problem'
|
||||||
|
'401':
|
||||||
|
$ref: '#/components/responses/Problem'
|
||||||
'413':
|
'413':
|
||||||
$ref: '#/components/responses/Problem'
|
$ref: '#/components/responses/Problem'
|
||||||
'503':
|
'503':
|
||||||
@@ -76,6 +90,11 @@ paths:
|
|||||||
default:
|
default:
|
||||||
$ref: '#/components/responses/Problem'
|
$ref: '#/components/responses/Problem'
|
||||||
components:
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
bearerAuth:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
description: 'Shared random service token sent as `Authorization: Bearer <token>`. The service compares it in constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user tokens.'
|
||||||
responses:
|
responses:
|
||||||
Problem:
|
Problem:
|
||||||
description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode.
|
description: Any error response. The body is a Problem whose `status` equals the HTTP status and whose `code` is one of ProblemCode.
|
||||||
@@ -275,7 +294,7 @@ components:
|
|||||||
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
|
description: One plain text to encode. It is untrusted data and never an instruction. The service truncates it deterministically to the token limit of the model (`EmbeddingModel.max_tokens`); characters beyond 8000 are rejected instead.
|
||||||
EmbeddingRequest:
|
EmbeddingRequest:
|
||||||
type: object
|
type: object
|
||||||
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same image and thread count give the same vectors.'
|
description: 'Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are ordered by length with the request position as the tie-breaker, encoded in micro-batches of the configured size, and returned in request order. The same texts in the same request on the same installation, device, precision, and thread count give the same vectors.'
|
||||||
additionalProperties: false
|
additionalProperties: false
|
||||||
required:
|
required:
|
||||||
- kind
|
- kind
|
||||||
@@ -286,7 +305,7 @@ components:
|
|||||||
minLength: 1
|
minLength: 1
|
||||||
maxLength: 200
|
maxLength: 200
|
||||||
pattern: ^[A-Za-z0-9._/-]+$
|
pattern: ^[A-Za-z0-9._/-]+$
|
||||||
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
|
description: Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.
|
||||||
kind:
|
kind:
|
||||||
$ref: '#/components/schemas/EmbeddingInputKind'
|
$ref: '#/components/schemas/EmbeddingInputKind'
|
||||||
texts:
|
texts:
|
||||||
|
|||||||
@@ -2,8 +2,21 @@ openapi: 3.2.0
|
|||||||
info:
|
info:
|
||||||
title: Lincodex ML Operational API
|
title: Lincodex ML Operational API
|
||||||
version: 0.1.0
|
version: 0.1.0
|
||||||
|
description: |-
|
||||||
|
Internal API of the ML service. Only the Go backend calls it; it is never
|
||||||
|
exposed to browsers or to the public network.
|
||||||
|
|
||||||
|
Authentication: every operation except the health routes requires
|
||||||
|
`Authorization: Bearer <token>` when the service has a token, and the
|
||||||
|
service refuses to listen on a non-loopback address without one. The
|
||||||
|
token is a shared random secret of at least 32 printable characters from
|
||||||
|
the deployment secret store, never from this repository. A missing or
|
||||||
|
wrong token answers 401 `unauthenticated`. A service without a token
|
||||||
|
answers only callers on its own loopback interface.
|
||||||
servers:
|
servers:
|
||||||
- url: /
|
- url: /
|
||||||
|
security:
|
||||||
|
- bearerAuth: []
|
||||||
paths:
|
paths:
|
||||||
/healthz:
|
/healthz:
|
||||||
$ref: ./routes/healthz.yml
|
$ref: ./routes/healthz.yml
|
||||||
@@ -12,6 +25,14 @@ paths:
|
|||||||
/v1/embeddings:
|
/v1/embeddings:
|
||||||
$ref: ./routes/embeddings.yml
|
$ref: ./routes/embeddings.yml
|
||||||
components:
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
bearerAuth:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
description: >-
|
||||||
|
Shared random service token sent as `Authorization: Bearer <token>`.
|
||||||
|
The service compares it in constant time and never logs it. Rotation
|
||||||
|
replaces the secret on both sides; there are no per-user tokens.
|
||||||
responses:
|
responses:
|
||||||
Problem:
|
Problem:
|
||||||
$ref: ./components/responses.yml#/Problem
|
$ref: ./components/responses.yml#/Problem
|
||||||
@@ -1,11 +1,10 @@
|
|||||||
post:
|
post:
|
||||||
operationId: CreateMLEmbeddings
|
operationId: CreateMLEmbeddings
|
||||||
summary: Encode texts into normalized vectors with the pinned embedding model.
|
summary: Encode texts into normalized vectors with a pinned embedding model.
|
||||||
description: |-
|
description: |-
|
||||||
Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on the private network. The request carries only text that the caller is allowed to process, and the service never logs it.
|
Internal operation for the Go backend; it is not reachable from browsers and needs the service bearer token. The request carries only text that the caller is allowed to process, and the service never logs it.
|
||||||
|
|
||||||
The service answers 503 service_unavailable until the model is loaded from the image and a warm-up encode has finished; `/readyz` reports the same state. A request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
|
The service may load several pinned models, for example the members of an ensemble; `model` selects one, and the response names the model, revision, dimension, and prompt version that produced the vectors. The service answers 503 service_unavailable until every configured model is loaded and a warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports the same state. A request without a valid token answers 401, a request above the body limit answers 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or names a model that the service does not serve, answers 400.
|
||||||
security: []
|
|
||||||
tags:
|
tags:
|
||||||
- inference
|
- inference
|
||||||
requestBody:
|
requestBody:
|
||||||
@@ -23,6 +22,8 @@ post:
|
|||||||
$ref: ../components/schemas.yml#/EmbeddingResponse
|
$ref: ../components/schemas.yml#/EmbeddingResponse
|
||||||
"400":
|
"400":
|
||||||
$ref: ../components/responses.yml#/Problem
|
$ref: ../components/responses.yml#/Problem
|
||||||
|
"401":
|
||||||
|
$ref: ../components/responses.yml#/Problem
|
||||||
"413":
|
"413":
|
||||||
$ref: ../components/responses.yml#/Problem
|
$ref: ../components/responses.yml#/Problem
|
||||||
"503":
|
"503":
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/re
|
|||||||
|
|
||||||
## Match search
|
## Match search
|
||||||
|
|
||||||
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
|
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, the Giga + Qwen3-Embedding ensemble with `ARGS='semantic-ensemble --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
|
||||||
|
|
||||||
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
|
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -142,7 +142,7 @@
|
|||||||
|
|
||||||
## Подбор
|
## Подбор
|
||||||
|
|
||||||
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
|
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, ансамбль Giga + Qwen3-Embedding - `ARGS='semantic-ensemble --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
|
||||||
|
|
||||||
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
|
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package config
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -25,6 +27,10 @@ const (
|
|||||||
defaultGitHubChecksEnabled = false
|
defaultGitHubChecksEnabled = false
|
||||||
defaultGitHubTimeout = 10 * time.Second
|
defaultGitHubTimeout = 10 * time.Second
|
||||||
maxGitHubTimeout = time.Minute
|
maxGitHubTimeout = time.Minute
|
||||||
|
// minMLServiceTokenLength matches the ML service: 32 printable characters
|
||||||
|
// of a CSPRNG token are far beyond an online guess.
|
||||||
|
minMLServiceTokenLength = 32
|
||||||
|
maxMLServiceTokenLength = 512
|
||||||
// defaultRepositoryCheckInterval is the shortest time between two check
|
// defaultRepositoryCheckInterval is the shortest time between two check
|
||||||
// requests of one candidate through the refresh operation.
|
// requests of one candidate through the refresh operation.
|
||||||
defaultRepositoryCheckInterval = 10 * time.Minute
|
defaultRepositoryCheckInterval = 10 * time.Minute
|
||||||
@@ -32,14 +38,20 @@ const (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// SemanticSettings configure semantic matching and repository checks.
|
// SemanticSettings configure semantic matching and repository checks.
|
||||||
|
//
|
||||||
|
// String, GoString, Format, and LogValue redact everything, because the ML
|
||||||
|
// service token and the GitHub token are secrets of the deployment.
|
||||||
type SemanticSettings struct {
|
type SemanticSettings struct {
|
||||||
// SemanticMatchingEnabled schedules vector jobs on changes and runs them
|
// SemanticMatchingEnabled schedules vector jobs on changes and runs them
|
||||||
// against MLServiceURL. The search reads stored vectors either way.
|
// against MLServiceURL. The search reads stored vectors either way.
|
||||||
SemanticMatchingEnabled bool
|
SemanticMatchingEnabled bool
|
||||||
MLServiceURL string
|
MLServiceURL string
|
||||||
MLRequestTimeout time.Duration
|
// MLServiceToken is the shared bearer token of the ML service. It is
|
||||||
MLCircuitFailures int
|
// required while semantic matching is enabled and is a secret: never log it.
|
||||||
MLCircuitOpen time.Duration
|
MLServiceToken string
|
||||||
|
MLRequestTimeout time.Duration
|
||||||
|
MLCircuitFailures int
|
||||||
|
MLCircuitOpen time.Duration
|
||||||
// GitHubChecksEnabled schedules and runs repository checks against the
|
// GitHubChecksEnabled schedules and runs repository checks against the
|
||||||
// public GitHub API.
|
// public GitHub API.
|
||||||
GitHubChecksEnabled bool
|
GitHubChecksEnabled bool
|
||||||
@@ -50,12 +62,28 @@ type SemanticSettings struct {
|
|||||||
RepositoryCheckInterval time.Duration
|
RepositoryCheckInterval time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const redactedSemanticSettings = "[semantic settings redacted]"
|
||||||
|
|
||||||
|
func (settings SemanticSettings) String() string { return redactedSemanticSettings }
|
||||||
|
|
||||||
|
func (settings SemanticSettings) GoString() string { return redactedSemanticSettings }
|
||||||
|
|
||||||
|
// Format redacts every verb; without it %+v would print the tokens.
|
||||||
|
func (settings SemanticSettings) Format(state fmt.State, _ rune) {
|
||||||
|
_, _ = state.Write([]byte(redactedSemanticSettings))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (settings SemanticSettings) LogValue() slog.Value {
|
||||||
|
return slog.StringValue(redactedSemanticSettings)
|
||||||
|
}
|
||||||
|
|
||||||
// LoadSemanticSettings reads the semantic settings; the operator commands
|
// LoadSemanticSettings reads the semantic settings; the operator commands
|
||||||
// that need only them use it directly.
|
// that need only them use it directly.
|
||||||
func LoadSemanticSettings(lookup LookupEnv) (SemanticSettings, error) {
|
func LoadSemanticSettings(lookup LookupEnv) (SemanticSettings, error) {
|
||||||
settings := SemanticSettings{
|
settings := SemanticSettings{
|
||||||
MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")),
|
MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")),
|
||||||
GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")),
|
MLServiceToken: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_TOKEN", "")),
|
||||||
|
GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")),
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
if settings.SemanticMatchingEnabled, err = boolOrDefault(lookup, "SEMANTIC_MATCHING_ENABLED", defaultSemanticMatchingEnabled); err != nil {
|
if settings.SemanticMatchingEnabled, err = boolOrDefault(lookup, "SEMANTIC_MATCHING_ENABLED", defaultSemanticMatchingEnabled); err != nil {
|
||||||
@@ -96,6 +124,12 @@ func (settings SemanticSettings) validateMLService() error {
|
|||||||
if settings.SemanticMatchingEnabled && settings.MLServiceURL == "" {
|
if settings.SemanticMatchingEnabled && settings.MLServiceURL == "" {
|
||||||
return errors.New(location + " - ML_SERVICE_URL is required when SEMANTIC_MATCHING_ENABLED is true")
|
return errors.New(location + " - ML_SERVICE_URL is required when SEMANTIC_MATCHING_ENABLED is true")
|
||||||
}
|
}
|
||||||
|
if settings.SemanticMatchingEnabled && settings.MLServiceToken == "" {
|
||||||
|
return errors.New(location + " - ML_SERVICE_TOKEN is required when SEMANTIC_MATCHING_ENABLED is true")
|
||||||
|
}
|
||||||
|
if err := validateMLServiceToken(settings.MLServiceToken); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if settings.MLServiceURL != "" {
|
if settings.MLServiceURL != "" {
|
||||||
parsed, err := url.Parse(settings.MLServiceURL)
|
parsed, err := url.Parse(settings.MLServiceURL)
|
||||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" ||
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" ||
|
||||||
@@ -106,6 +140,24 @@ func (settings SemanticSettings) validateMLService() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// validateMLServiceToken checks an optional token; the messages never quote
|
||||||
|
// the value.
|
||||||
|
func validateMLServiceToken(token string) error {
|
||||||
|
const location = "SemanticSettings.Validate"
|
||||||
|
if token == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(token) < minMLServiceTokenLength || len(token) > maxMLServiceTokenLength {
|
||||||
|
return errors.New(location + " - ML_SERVICE_TOKEN must have between 32 and 512 characters")
|
||||||
|
}
|
||||||
|
for _, character := range token {
|
||||||
|
if character < 0x21 || character > 0x7e {
|
||||||
|
return errors.New(location + " - ML_SERVICE_TOKEN must be printable ASCII without white space")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (settings SemanticSettings) validateLimits() error {
|
func (settings SemanticSettings) validateLimits() error {
|
||||||
const location = "SemanticSettings.Validate"
|
const location = "SemanticSettings.Validate"
|
||||||
switch {
|
switch {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -19,14 +20,24 @@ func TestSemanticSettingsDefaultOffAndValidateTheMLOrigin(t *testing.T) {
|
|||||||
settings.MLRequestTimeout != 30*time.Second || settings.RepositoryCheckInterval != 10*time.Minute {
|
settings.MLRequestTimeout != 30*time.Second || settings.RepositoryCheckInterval != 10*time.Minute {
|
||||||
t.Fatalf("defaults = %+v, %v", settings, err)
|
t.Fatalf("defaults = %+v, %v", settings, err)
|
||||||
}
|
}
|
||||||
|
const mlToken = "ml-service-token-0123456789abcdefghij"
|
||||||
enabled, err := LoadSemanticSettings(lookupOf(map[string]string{
|
enabled, err := LoadSemanticSettings(lookupOf(map[string]string{
|
||||||
"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000", "GITHUB_TOKEN": "token-value",
|
"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://192.168.10.25:8790", "ML_SERVICE_TOKEN": mlToken,
|
||||||
|
"GITHUB_TOKEN": "token-value",
|
||||||
}))
|
}))
|
||||||
if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" {
|
if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" || enabled.MLServiceToken != mlToken {
|
||||||
t.Fatalf("enabled = %+v, %v", enabled, err)
|
t.Fatalf("enabled = %v, %v", enabled.SemanticMatchingEnabled, err)
|
||||||
|
}
|
||||||
|
for _, rendered := range []string{fmt.Sprintf("%v %+v %#v %s", enabled, enabled, enabled, enabled), enabled.LogValue().String()} {
|
||||||
|
if strings.Contains(rendered, mlToken) || strings.Contains(rendered, "token-value") {
|
||||||
|
t.Fatalf("formatted settings quote a token: %s", rendered)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for name, values := range map[string]map[string]string{
|
for name, values := range map[string]map[string]string{
|
||||||
"missing URL": {"SEMANTIC_MATCHING_ENABLED": "true"},
|
"missing URL": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_TOKEN": "ml-service-token-0123456789abcdefghij"},
|
||||||
|
"missing token": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000"},
|
||||||
|
"short token": {"ML_SERVICE_TOKEN": "secret-but-short"},
|
||||||
|
"spaced token": {"ML_SERVICE_TOKEN": "secret 0123456789abcdefghijklmnopqrstuvwxyz"},
|
||||||
"credentials": {"ML_SERVICE_URL": "http://user:secret@ml:8000"},
|
"credentials": {"ML_SERVICE_URL": "http://user:secret@ml:8000"},
|
||||||
"path": {"ML_SERVICE_URL": "http://ml:8000/v1"},
|
"path": {"ML_SERVICE_URL": "http://ml:8000/v1"},
|
||||||
"scheme": {"ML_SERVICE_URL": "file:///tmp/ml"},
|
"scheme": {"ML_SERVICE_URL": "file:///tmp/ml"},
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import (
|
|||||||
"lincodex/backend/internal/domain"
|
"lincodex/backend/internal/domain"
|
||||||
"lincodex/backend/internal/port/inbound"
|
"lincodex/backend/internal/port/inbound"
|
||||||
"lincodex/backend/internal/port/outbound"
|
"lincodex/backend/internal/port/outbound"
|
||||||
|
"lincodex/backend/internal/usecase/policy"
|
||||||
"lincodex/backend/internal/usecase/semantic"
|
"lincodex/backend/internal/usecase/semantic"
|
||||||
"lincodex/backend/internal/worker/jobrunner"
|
"lincodex/backend/internal/worker/jobrunner"
|
||||||
"lincodex/backend/internal/worker/retry"
|
"lincodex/backend/internal/worker/retry"
|
||||||
@@ -36,16 +37,32 @@ const (
|
|||||||
// never reach an organization.
|
// never reach an organization.
|
||||||
semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger"
|
semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger"
|
||||||
semanticRepositoryOwner = "Private-Owner-Marker"
|
semanticRepositoryOwner = "Private-Owner-Marker"
|
||||||
|
// semanticMLToken is the bearer token the fake ML service expects.
|
||||||
|
semanticMLToken = "integration-ml-service-token-0123456789"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fakeMLService answers the ML embedding contract with a bag-of-topics
|
// fakeMLService answers the ML embedding contract with a bag-of-topics
|
||||||
// encoder: each topic word lights one dimension, so texts about the same
|
// encoder: each topic word lights one dimension, so texts about the same
|
||||||
// topic are close and others are not. It reports the policy model, so the
|
// topic are close and others are not. Like the real service it requires the
|
||||||
// vectors pass the model check, and counts the texts it encoded.
|
// bearer token and serves the two ensemble models, reports the requested
|
||||||
|
// model, so the vectors pass the model check, and counts the texts it
|
||||||
|
// encoded per model.
|
||||||
type fakeMLService struct {
|
type fakeMLService struct {
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
texts int
|
texts int
|
||||||
down bool
|
byModel map[string]int
|
||||||
|
down bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var fakeMLModels = map[string]map[string]any{
|
||||||
|
domain.GigaEmbeddingsModelID: {
|
||||||
|
"id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision,
|
||||||
|
"prompt_version": domain.GigaEmbeddingsPromptVersion,
|
||||||
|
},
|
||||||
|
domain.Qwen3EmbeddingModelID: {
|
||||||
|
"id": domain.Qwen3EmbeddingModelID, "revision": domain.Qwen3EmbeddingModelRevision,
|
||||||
|
"prompt_version": domain.Qwen3EmbeddingPromptVersion,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
var fakeTopics = [][]string{
|
var fakeTopics = [][]string{
|
||||||
@@ -80,6 +97,12 @@ func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *htt
|
|||||||
service.mutex.Lock()
|
service.mutex.Lock()
|
||||||
down := service.down
|
down := service.down
|
||||||
service.mutex.Unlock()
|
service.mutex.Unlock()
|
||||||
|
if request.Header.Get("Authorization") != "Bearer "+semanticMLToken {
|
||||||
|
writer.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
writer.WriteHeader(http.StatusUnauthorized)
|
||||||
|
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:unauthenticated","title":"Authentication required","status":401,"code":"unauthenticated"}`))
|
||||||
|
return
|
||||||
|
}
|
||||||
if down {
|
if down {
|
||||||
writer.Header().Set("Content-Type", "application/problem+json")
|
writer.Header().Set("Content-Type", "application/problem+json")
|
||||||
writer.WriteHeader(http.StatusServiceUnavailable)
|
writer.WriteHeader(http.StatusServiceUnavailable)
|
||||||
@@ -91,28 +114,36 @@ func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *htt
|
|||||||
Kind string `json:"kind"`
|
Kind string `json:"kind"`
|
||||||
Texts []string `json:"texts"`
|
Texts []string `json:"texts"`
|
||||||
}
|
}
|
||||||
// The service serves one model; a request for another one is refused
|
// A model the service does not serve is refused as the real service
|
||||||
// as the real service refuses it.
|
// refuses it.
|
||||||
if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil ||
|
if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil ||
|
||||||
body.Model != domain.GigaEmbeddingsModelID {
|
fakeMLModels[body.Model] == nil {
|
||||||
writer.WriteHeader(http.StatusBadRequest)
|
writer.WriteHeader(http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
service.mutex.Lock()
|
service.mutex.Lock()
|
||||||
service.texts += len(body.Texts)
|
service.texts += len(body.Texts)
|
||||||
|
if service.byModel == nil {
|
||||||
|
service.byModel = map[string]int{}
|
||||||
|
}
|
||||||
|
service.byModel[body.Model] += len(body.Texts)
|
||||||
service.mutex.Unlock()
|
service.mutex.Unlock()
|
||||||
vectors := make([][]float32, 0, len(body.Texts))
|
vectors := make([][]float32, 0, len(body.Texts))
|
||||||
for _, text := range body.Texts {
|
for _, text := range body.Texts {
|
||||||
vectors = append(vectors, fakeTopicVector(text))
|
vectors = append(vectors, fakeTopicVector(text))
|
||||||
}
|
}
|
||||||
writer.Header().Set("Content-Type", "application/json")
|
writer.Header().Set("Content-Type", "application/json")
|
||||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
model := map[string]any{"dimension": len(fakeTopics) + 1, "max_tokens": 1024}
|
||||||
"model": map[string]any{
|
for key, value := range fakeMLModels[body.Model] {
|
||||||
"id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision,
|
model[key] = value
|
||||||
"dimension": len(fakeTopics) + 1, "max_tokens": 1024, "prompt_version": domain.GigaEmbeddingsPromptVersion,
|
}
|
||||||
},
|
_ = json.NewEncoder(writer).Encode(map[string]any{"model": model, "kind": body.Kind, "vectors": vectors})
|
||||||
"kind": body.Kind, "vectors": vectors,
|
}
|
||||||
})
|
|
||||||
|
func (service *fakeMLService) encodedTextsOf(model string) int {
|
||||||
|
service.mutex.Lock()
|
||||||
|
defer service.mutex.Unlock()
|
||||||
|
return service.byModel[model]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service *fakeMLService) encodedTexts() int {
|
func (service *fakeMLService) encodedTexts() int {
|
||||||
@@ -191,7 +222,7 @@ func TestSemanticMatchingOverHTTP(t *testing.T) {
|
|||||||
mlServer := httptest.NewServer(ml)
|
mlServer := httptest.NewServer(ml)
|
||||||
defer mlServer.Close()
|
defer mlServer.Close()
|
||||||
embedder, err := mladapter.NewEmbedder(mladapter.Settings{
|
embedder, err := mladapter.NewEmbedder(mladapter.Settings{
|
||||||
BaseURL: mlServer.URL, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second,
|
BaseURL: mlServer.URL, Token: semanticMLToken, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second,
|
||||||
}, time.Now)
|
}, time.Now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewEmbedder() error = %v", err)
|
t.Fatalf("NewEmbedder() error = %v", err)
|
||||||
@@ -475,4 +506,61 @@ func TestSemanticMatchingOverHTTP(t *testing.T) {
|
|||||||
t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body)
|
t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
t.Run("the ensemble policy and a backfill add the Qwen3 views and the search fuses both models", func(t *testing.T) {
|
||||||
|
// The payments candidate publishes the project again, so one card is
|
||||||
|
// close to the need under both models. The publication job falls due
|
||||||
|
// on the stand clock, ahead of the worker, so a backfill under the
|
||||||
|
// single-model policy brings the Giga vectors up to date first.
|
||||||
|
publishFields(paymentsCandidate, 2, `["projects","self_assessment","stack"]`)
|
||||||
|
backfill, err := semantic.NewBackfill(transactor, time.Now)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewBackfill() error = %v", err)
|
||||||
|
}
|
||||||
|
if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-republish", uuid.Nil, nil); err != nil {
|
||||||
|
t.Fatalf("Backfill.Run(republish) error = %v", err)
|
||||||
|
}
|
||||||
|
drain()
|
||||||
|
gigaBefore := ml.encodedTextsOf(domain.GigaEmbeddingsModelID)
|
||||||
|
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
||||||
|
published, err := publisher.EnsureDemoSemanticEnsembleSection(ctx, "operator:integration")
|
||||||
|
if err != nil || !published.Created {
|
||||||
|
t.Fatalf("EnsureDemoSemanticEnsembleSection() = %+v, %v", published, err)
|
||||||
|
}
|
||||||
|
// Until the need has a Qwen3 view, Sem is unknown for every entry.
|
||||||
|
before, _ := search()
|
||||||
|
for _, entry := range before.Groups.Unconfirmed {
|
||||||
|
if !slices.Contains(entry.flags(), "semantics:ml_unavailable") {
|
||||||
|
t.Fatalf("flags = %v before the backfill, want the ML flag", entry.flags())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, scope := range []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds} {
|
||||||
|
if err := backfill.Run(ctx, scope, "it-ensemble", uuid.Nil, nil); err != nil {
|
||||||
|
t.Fatalf("Backfill.Run(%s) error = %v", scope, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
drain()
|
||||||
|
if after := ml.encodedTextsOf(domain.GigaEmbeddingsModelID); after != gigaBefore {
|
||||||
|
t.Fatalf("the backfill encoded %d Giga texts, want none: the Giga views did not change", after-gigaBefore)
|
||||||
|
}
|
||||||
|
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key = 'whole'`, domain.Qwen3EmbeddingModelID); got != 6+1 {
|
||||||
|
t.Fatalf("Qwen3 whole views = %d, want one per published candidate and the need", got)
|
||||||
|
}
|
||||||
|
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key <> 'whole'`, domain.Qwen3EmbeddingModelID); got != 0 {
|
||||||
|
t.Fatalf("Qwen3 item vectors = %d, want none: only Giga explains entries", got)
|
||||||
|
}
|
||||||
|
// Every candidate now has both whole views, so every entry has a
|
||||||
|
// known Sem, and the fused score puts the related card first.
|
||||||
|
result, _ := search()
|
||||||
|
entries := result.Groups.Unconfirmed
|
||||||
|
for _, entry := range entries {
|
||||||
|
if slices.Contains(entry.flags(), "semantics:ml_unavailable") {
|
||||||
|
t.Fatalf("flags = %v after the backfill, want a known Sem", entry.flags())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if entries[0].CandidateHandle != paymentsHandle || entries[0].component("fit") <= entries[len(entries)-1].component("fit") {
|
||||||
|
t.Fatalf("first entry %s with fit %v, last fit %v: the fused Sem did not put the related card first",
|
||||||
|
entries[0].CandidateHandle, entries[0].component("fit"), entries[len(entries)-1].component("fit"))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// Package policypublish implements the local operator command that adds the
|
// Package policypublish implements the local operator command that adds the
|
||||||
// demo matching section, or the semantic matching section, to the product
|
// demo matching section, the semantic matching section, or the two-model
|
||||||
// policy. Until an administrative policy
|
// semantic ensemble section to the product policy. Until an administrative policy
|
||||||
// editor exists, this is how a stand gets the coefficients that the match
|
// editor exists, this is how a stand gets the coefficients that the match
|
||||||
// search needs: startup seeds only the first demo version.
|
// search needs: startup seeds only the first demo version.
|
||||||
package policypublish
|
package policypublish
|
||||||
@@ -21,7 +21,7 @@ import (
|
|||||||
"lincodex/backend/internal/usecase/policy"
|
"lincodex/backend/internal/usecase/policy"
|
||||||
)
|
)
|
||||||
|
|
||||||
const usage = "usage: policy-publish matching|semantic --actor operator:<handle>"
|
const usage = "usage: policy-publish matching|semantic|semantic-ensemble --actor operator:<handle>"
|
||||||
|
|
||||||
// Track names which section a command publishes.
|
// Track names which section a command publishes.
|
||||||
type Track string
|
type Track string
|
||||||
@@ -32,6 +32,10 @@ const (
|
|||||||
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
|
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
|
||||||
// encoder identity, the calibration, and the explanation thresholds).
|
// encoder identity, the calibration, and the explanation thresholds).
|
||||||
TrackSemantic Track = "semantic"
|
TrackSemantic Track = "semantic"
|
||||||
|
// TrackSemanticEnsemble replaces the semantic section with the two-model
|
||||||
|
// ensemble (Giga and Qwen3-Embedding) and its calibration; the earlier
|
||||||
|
// single-model version stays as the previous version.
|
||||||
|
TrackSemanticEnsemble Track = "semantic-ensemble"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Command is a parsed, validated request.
|
// Command is a parsed, validated request.
|
||||||
@@ -44,11 +48,12 @@ type Command struct {
|
|||||||
type Extender interface {
|
type Extender interface {
|
||||||
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||||
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||||
|
EnsureDemoSemanticEnsembleSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse validates every argument before Run reads configuration or connects.
|
// Parse validates every argument before Run reads configuration or connects.
|
||||||
func Parse(args []string) (Command, error) {
|
func Parse(args []string) (Command, error) {
|
||||||
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic)) {
|
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic) && args[0] != string(TrackSemanticEnsemble)) {
|
||||||
return Command{}, errors.New(usage)
|
return Command{}, errors.New(usage)
|
||||||
}
|
}
|
||||||
track := Track(args[0])
|
track := Track(args[0])
|
||||||
@@ -98,10 +103,16 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
|
|||||||
}
|
}
|
||||||
publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section",
|
publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section",
|
||||||
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n"
|
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n"
|
||||||
if command.Track == TrackSemantic {
|
switch command.Track {
|
||||||
|
case TrackSemantic:
|
||||||
publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section",
|
publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section",
|
||||||
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+
|
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+
|
||||||
"and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n"
|
"and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n"
|
||||||
|
case TrackSemanticEnsemble:
|
||||||
|
publish, section, note = extender.EnsureDemoSemanticEnsembleSection, "the semantic ensemble section (Giga + Qwen3-Embedding)",
|
||||||
|
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; the ML service must serve both models,\n"+
|
||||||
|
"and Sem stays neutral for subjects without Qwen3 vectors until the semantic-backfill command has run\n"
|
||||||
|
case TrackMatching:
|
||||||
}
|
}
|
||||||
result, err := publish(ctx, command.Author)
|
result, err := publish(ctx, command.Author)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ type extenderFake struct {
|
|||||||
err error
|
err error
|
||||||
author domain.PolicyAuthor
|
author domain.PolicyAuthor
|
||||||
semantic bool
|
semantic bool
|
||||||
|
ensemble bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||||
@@ -30,6 +31,12 @@ func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Contex
|
|||||||
return extender.result, extender.err
|
return extender.result, extender.err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (extender *extenderFake) EnsureDemoSemanticEnsembleSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||||
|
extender.author = author
|
||||||
|
extender.ensemble = true
|
||||||
|
return extender.result, extender.err
|
||||||
|
}
|
||||||
|
|
||||||
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
|
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
|
||||||
command, err := Parse([]string{"matching", "--actor", "operator:night"})
|
command, err := Parse([]string{"matching", "--actor", "operator:night"})
|
||||||
if err != nil || command.Author != "operator:night" || command.Track != TrackMatching {
|
if err != nil || command.Author != "operator:night" || command.Track != TrackMatching {
|
||||||
@@ -39,6 +46,10 @@ func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
|
|||||||
if err != nil || semantic.Track != TrackSemantic {
|
if err != nil || semantic.Track != TrackSemantic {
|
||||||
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
|
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
|
||||||
}
|
}
|
||||||
|
ensemble, err := Parse([]string{"semantic-ensemble", "--actor", "operator:night"})
|
||||||
|
if err != nil || ensemble.Track != TrackSemanticEnsemble {
|
||||||
|
t.Fatalf("Parse(semantic-ensemble) = %+v, %v", ensemble, err)
|
||||||
|
}
|
||||||
for _, args := range [][]string{
|
for _, args := range [][]string{
|
||||||
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
|
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
|
||||||
{"matching", "--actor", "operator:night", "extra"},
|
{"matching", "--actor", "operator:night", "extra"},
|
||||||
@@ -84,3 +95,14 @@ func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) {
|
|||||||
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
|
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestExecuteSemanticEnsembleTrackPublishesTheEnsembleSection(t *testing.T) {
|
||||||
|
var output bytes.Buffer
|
||||||
|
extender := &extenderFake{}
|
||||||
|
if err := Execute(context.Background(), Command{Track: TrackSemanticEnsemble, Author: "operator:night"}, extender, &output); err != nil {
|
||||||
|
t.Fatalf("Execute() error = %v", err)
|
||||||
|
}
|
||||||
|
if !extender.ensemble || extender.semantic || !strings.Contains(output.String(), "semantic ensemble section") {
|
||||||
|
t.Fatalf("output = %q, ensemble called %v", output.String(), extender.ensemble)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
|
|
||||||
"github.com/go-faster/errors"
|
"github.com/go-faster/errors"
|
||||||
ht "github.com/ogen-go/ogen/http"
|
ht "github.com/ogen-go/ogen/http"
|
||||||
|
"github.com/ogen-go/ogen/ogenerrors"
|
||||||
"github.com/ogen-go/ogen/otelogen"
|
"github.com/ogen-go/ogen/otelogen"
|
||||||
"github.com/ogen-go/ogen/uri"
|
"github.com/ogen-go/ogen/uri"
|
||||||
"go.opentelemetry.io/otel/attribute"
|
"go.opentelemetry.io/otel/attribute"
|
||||||
@@ -29,13 +30,16 @@ func trimTrailingSlashes(u *url.URL) {
|
|||||||
type Invoker interface {
|
type Invoker interface {
|
||||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||||
//
|
//
|
||||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
// bearer token. The request carries only text that the caller is allowed to process, and the service
|
||||||
// service never logs it.
|
// never logs it.
|
||||||
//
|
//
|
||||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||||
|
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||||
|
// the same state. A request without a valid token answers 401, a request above the body limit answers
|
||||||
|
// 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||||
// names a model that the service does not serve, answers 400.
|
// names a model that the service does not serve, answers 400.
|
||||||
//
|
//
|
||||||
// POST /v1/embeddings
|
// POST /v1/embeddings
|
||||||
@@ -57,11 +61,12 @@ type Invoker interface {
|
|||||||
// Client implements OAS client.
|
// Client implements OAS client.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
serverURL *url.URL
|
serverURL *url.URL
|
||||||
|
sec SecuritySource
|
||||||
baseClient
|
baseClient
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient initializes new Client defined by OAS.
|
// NewClient initializes new Client defined by OAS.
|
||||||
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) {
|
||||||
u, err := url.Parse(serverURL)
|
u, err := url.Parse(serverURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -74,6 +79,7 @@ func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
|||||||
}
|
}
|
||||||
return &Client{
|
return &Client{
|
||||||
serverURL: u,
|
serverURL: u,
|
||||||
|
sec: sec,
|
||||||
baseClient: c,
|
baseClient: c,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -95,13 +101,16 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
|
|||||||
|
|
||||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||||
//
|
//
|
||||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
// bearer token. The request carries only text that the caller is allowed to process, and the service
|
||||||
// service never logs it.
|
// never logs it.
|
||||||
//
|
//
|
||||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||||
|
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||||
|
// the same state. A request without a valid token answers 401, a request above the body limit answers
|
||||||
|
// 413, and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||||
// names a model that the service does not serve, answers 400.
|
// names a model that the service does not serve, answers 400.
|
||||||
//
|
//
|
||||||
// POST /v1/embeddings
|
// POST /v1/embeddings
|
||||||
@@ -160,6 +169,39 @@ func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingR
|
|||||||
return res, errors.Wrap(err, "encode request")
|
return res, errors.Wrap(err, "encode request")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
type bitset = [1]uint8
|
||||||
|
var satisfied bitset
|
||||||
|
{
|
||||||
|
stage = "Security:BearerAuth"
|
||||||
|
switch err := c.securityBearerAuth(ctx, CreateMLEmbeddingsOperation, r); {
|
||||||
|
case err == nil: // if NO error
|
||||||
|
satisfied[0] |= 1 << 0
|
||||||
|
case errors.Is(err, ogenerrors.ErrSkipClientSecurity):
|
||||||
|
// Skip this security.
|
||||||
|
default:
|
||||||
|
return res, errors.Wrap(err, "security \"BearerAuth\"")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ok := func() bool {
|
||||||
|
nextRequirement:
|
||||||
|
for _, requirement := range []bitset{
|
||||||
|
{0b00000001},
|
||||||
|
} {
|
||||||
|
for i, mask := range requirement {
|
||||||
|
if satisfied[i]&mask != mask {
|
||||||
|
continue nextRequirement
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}(); !ok {
|
||||||
|
return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
stage = "SendRequest"
|
stage = "SendRequest"
|
||||||
resp, err := c.cfg.Client.Do(r)
|
resp, err := c.cfg.Client.Do(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -106,6 +106,53 @@ func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddin
|
|||||||
default:
|
default:
|
||||||
return res, validate.InvalidContentType(ct)
|
return res, validate.InvalidContentType(ct)
|
||||||
}
|
}
|
||||||
|
case 401:
|
||||||
|
// Code 401.
|
||||||
|
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||||
|
if err != nil {
|
||||||
|
return res, errors.Wrap(err, "parse media type")
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case ct == "application/problem+json":
|
||||||
|
buf, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
d := jx.DecodeBytes(buf)
|
||||||
|
|
||||||
|
var response Problem
|
||||||
|
if err := func() error {
|
||||||
|
if err := response.Decode(d); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := d.Skip(); err != io.EOF {
|
||||||
|
return errors.New("unexpected trailing data")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
err = &ogenerrors.DecodeBodyError{
|
||||||
|
ContentType: ct,
|
||||||
|
Body: buf,
|
||||||
|
Err: err,
|
||||||
|
}
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
// Validate response.
|
||||||
|
if err := func() error {
|
||||||
|
if err := response.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}(); err != nil {
|
||||||
|
return res, errors.Wrap(err, "validate")
|
||||||
|
}
|
||||||
|
return &CreateMLEmbeddingsUnauthorized{
|
||||||
|
StatusCode: resp.StatusCode,
|
||||||
|
Response: response,
|
||||||
|
}, nil
|
||||||
|
default:
|
||||||
|
return res, validate.InvalidContentType(ct)
|
||||||
|
}
|
||||||
case 413:
|
case 413:
|
||||||
// Code 413.
|
// Code 413.
|
||||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||||
|
|||||||
@@ -12,6 +12,31 @@ func (s *ProblemStatusCode) Error() string {
|
|||||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type BearerAuth struct {
|
||||||
|
Token string
|
||||||
|
Roles []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetToken returns the value of Token.
|
||||||
|
func (s *BearerAuth) GetToken() string {
|
||||||
|
return s.Token
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRoles returns the value of Roles.
|
||||||
|
func (s *BearerAuth) GetRoles() []string {
|
||||||
|
return s.Roles
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetToken sets the value of Token.
|
||||||
|
func (s *BearerAuth) SetToken(val string) {
|
||||||
|
s.Token = val
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetRoles sets the value of Roles.
|
||||||
|
func (s *BearerAuth) SetRoles(val []string) {
|
||||||
|
s.Roles = val
|
||||||
|
}
|
||||||
|
|
||||||
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
||||||
|
|
||||||
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
||||||
@@ -24,6 +49,10 @@ type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
|
|||||||
|
|
||||||
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
||||||
|
|
||||||
|
type CreateMLEmbeddingsUnauthorized ProblemStatusCode
|
||||||
|
|
||||||
|
func (*CreateMLEmbeddingsUnauthorized) createMLEmbeddingsRes() {}
|
||||||
|
|
||||||
// Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so
|
// Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so
|
||||||
// callers never send model instructions.
|
// callers never send model instructions.
|
||||||
//
|
//
|
||||||
@@ -143,13 +172,14 @@ func (s *EmbeddingModel) SetPromptVersion(val string) {
|
|||||||
|
|
||||||
// Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are
|
// Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are
|
||||||
// ordered by length with the request position as the tie-breaker, encoded in micro-batches of the
|
// ordered by length with the request position as the tie-breaker, encoded in micro-batches of the
|
||||||
// configured size, and returned in request order. The same texts in the same request on the same image
|
// configured size, and returned in request order. The same texts in the same request on the same
|
||||||
// and thread count give the same vectors.
|
// installation, device, precision, and thread count give the same vectors.
|
||||||
// Ref: #/components/schemas/EmbeddingRequest
|
// Ref: #/components/schemas/EmbeddingRequest
|
||||||
type EmbeddingRequest struct {
|
type EmbeddingRequest struct {
|
||||||
// Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of
|
// Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of
|
||||||
// the service. A service may load several models, for example the members of an ensemble; a model it
|
// the service, the first one it is configured with. A service may load several models, for example the
|
||||||
// does not serve answers 400 validation_failed with the pointer `/model`.
|
// members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer
|
||||||
|
// `/model`.
|
||||||
Model OptString `json:"model"`
|
Model OptString `json:"model"`
|
||||||
Kind EmbeddingInputKind `json:"kind"`
|
Kind EmbeddingInputKind `json:"kind"`
|
||||||
Texts []EmbeddingText `json:"texts"`
|
Texts []EmbeddingText `json:"texts"`
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// Code generated by ogen, DO NOT EDIT.
|
||||||
|
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/go-faster/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SecuritySource is provider of security values (tokens, passwords, etc.).
|
||||||
|
type SecuritySource interface {
|
||||||
|
// BearerAuth provides bearerAuth security value.
|
||||||
|
// Shared random service token sent as `Authorization: Bearer <token>`. The service compares it in
|
||||||
|
// constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user
|
||||||
|
// tokens.
|
||||||
|
BearerAuth(ctx context.Context, operationName OperationName) (BearerAuth, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||||
|
var operationRolesBearerAuth = map[string][]string{
|
||||||
|
CreateMLEmbeddingsOperation: []string{},
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||||
|
//
|
||||||
|
// This is useful for authorization scenarios where you need to know which roles
|
||||||
|
// are required for an operation.
|
||||||
|
//
|
||||||
|
// Example:
|
||||||
|
//
|
||||||
|
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
|
||||||
|
//
|
||||||
|
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||||
|
func GetRolesForBearerAuth(operation string) []string {
|
||||||
|
roles, ok := operationRolesBearerAuth[operation]
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Return a copy to prevent external modification
|
||||||
|
result := make([]string, len(roles))
|
||||||
|
copy(result, roles)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error {
|
||||||
|
t, err := s.sec.BearerAuth(ctx, operationName)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "security source \"BearerAuth\"")
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+t.Token)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -33,6 +33,14 @@ func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *CreateMLEmbeddingsUnauthorized) Validate() error {
|
||||||
|
alias := (*ProblemStatusCode)(s)
|
||||||
|
if err := alias.Validate(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s EmbeddingInputKind) Validate() error {
|
func (s EmbeddingInputKind) Validate() error {
|
||||||
switch s {
|
switch s {
|
||||||
case "query":
|
case "query":
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ const (
|
|||||||
type Settings struct {
|
type Settings struct {
|
||||||
// BaseURL is the ML service origin, for example http://ml:8000.
|
// BaseURL is the ML service origin, for example http://ml:8000.
|
||||||
BaseURL string
|
BaseURL string
|
||||||
|
// Token is the shared bearer token of the ML service. It is a secret:
|
||||||
|
// it travels only in the Authorization header and is never logged.
|
||||||
|
Token string
|
||||||
// Timeout bounds one HTTP request.
|
// Timeout bounds one HTTP request.
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
||||||
@@ -57,13 +60,16 @@ func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
|
|||||||
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
|
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
|
||||||
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
|
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
|
||||||
}
|
}
|
||||||
|
if settings.Token == "" {
|
||||||
|
return nil, errors.New(location + " - the ML service token must be set")
|
||||||
|
}
|
||||||
httpClient := &http.Client{
|
httpClient := &http.Client{
|
||||||
Timeout: settings.Timeout,
|
Timeout: settings.Timeout,
|
||||||
Transport: limitedTransport{next: http.DefaultTransport},
|
Transport: limitedTransport{next: http.DefaultTransport},
|
||||||
// The service is a fixed internal origin; a redirect is never expected.
|
// The service is a fixed internal origin; a redirect is never expected.
|
||||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||||
}
|
}
|
||||||
client, err := api.NewClient(parsed.String(), api.WithClient(httpClient))
|
client, err := api.NewClient(parsed.String(), staticToken{token: settings.Token}, api.WithClient(httpClient))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
||||||
}
|
}
|
||||||
@@ -130,6 +136,12 @@ func (embedder *Embedder) embedBatch(
|
|||||||
case *api.CreateMLEmbeddingsServiceUnavailable:
|
case *api.CreateMLEmbeddingsServiceUnavailable:
|
||||||
embedder.breaker.failure()
|
embedder.breaker.failure()
|
||||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
||||||
|
case *api.CreateMLEmbeddingsUnauthorized:
|
||||||
|
// A wrong or missing token is a deployment mistake. The job retries
|
||||||
|
// with backoff, so the vectors follow once the operator fixes the
|
||||||
|
// token; the open circuit keeps the retries cheap meanwhile.
|
||||||
|
embedder.breaker.failure()
|
||||||
|
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the service token: %w", outbound.ErrEmbedderUnavailable)
|
||||||
default:
|
default:
|
||||||
// 400 or 413: the request breaks the contract or names a model the
|
// 400 or 413: the request breaks the contract or names a model the
|
||||||
// service does not serve, and a repeat cannot fix it.
|
// service does not serve, and a repeat cannot fix it.
|
||||||
@@ -167,6 +179,15 @@ func cutRunes(text string, limit int) string {
|
|||||||
return string(runes[:limit])
|
return string(runes[:limit])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// staticToken supplies the configured bearer token to the generated client.
|
||||||
|
type staticToken struct {
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (source staticToken) BearerAuth(context.Context, api.OperationName) (api.BearerAuth, error) {
|
||||||
|
return api.BearerAuth{Token: source.token}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// limitedTransport caps the bytes read from a response body.
|
// limitedTransport caps the bytes read from a response body.
|
||||||
type limitedTransport struct {
|
type limitedTransport struct {
|
||||||
next http.RoundTripper
|
next http.RoundTripper
|
||||||
|
|||||||
@@ -14,12 +14,17 @@ import (
|
|||||||
"lincodex/backend/internal/port/outbound"
|
"lincodex/backend/internal/port/outbound"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// testToken is a syntactically valid service token of the tests.
|
||||||
|
const testToken = "test-ml-service-token-0123456789abcdef"
|
||||||
|
|
||||||
type fakeService struct {
|
type fakeService struct {
|
||||||
mutex sync.Mutex
|
mutex sync.Mutex
|
||||||
requests int
|
requests int
|
||||||
batches []int
|
batches []int
|
||||||
models []string
|
models []string
|
||||||
respond func(writer http.ResponseWriter, kind string, texts []string)
|
// authorizations records the Authorization header of every request.
|
||||||
|
authorizations []string
|
||||||
|
respond func(writer http.ResponseWriter, kind string, texts []string)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||||
@@ -33,6 +38,7 @@ func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.
|
|||||||
service.requests++
|
service.requests++
|
||||||
service.batches = append(service.batches, len(body.Texts))
|
service.batches = append(service.batches, len(body.Texts))
|
||||||
service.models = append(service.models, body.Model)
|
service.models = append(service.models, body.Model)
|
||||||
|
service.authorizations = append(service.authorizations, request.Header.Get("Authorization"))
|
||||||
service.mutex.Unlock()
|
service.mutex.Unlock()
|
||||||
service.respond(writer, body.Kind, body.Texts)
|
service.respond(writer, body.Kind, body.Texts)
|
||||||
}
|
}
|
||||||
@@ -53,7 +59,7 @@ func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time)
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
server := httptest.NewServer(service)
|
server := httptest.NewServer(service)
|
||||||
t.Cleanup(server.Close)
|
t.Cleanup(server.Close)
|
||||||
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
|
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Token: testToken, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("NewEmbedder() error = %v", err)
|
t.Fatalf("NewEmbedder() error = %v", err)
|
||||||
}
|
}
|
||||||
@@ -77,6 +83,25 @@ func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) {
|
|||||||
if strings.Join(service.models, ",") != "example/model,example/model" {
|
if strings.Join(service.models, ",") != "example/model,example/model" {
|
||||||
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
|
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
|
||||||
}
|
}
|
||||||
|
for _, header := range service.authorizations {
|
||||||
|
if header != "Bearer "+testToken {
|
||||||
|
t.Fatalf("Authorization = %q, want the bearer token on every request", header)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmbedTreatsARefusedTokenAsUnavailableWithoutQuotingIt(t *testing.T) {
|
||||||
|
service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||||
|
writer.Header().Set("Content-Type", "application/problem+json")
|
||||||
|
writer.Header().Set("WWW-Authenticate", "Bearer")
|
||||||
|
writer.WriteHeader(http.StatusUnauthorized)
|
||||||
|
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:unauthenticated","title":"x","status":401,"code":"unauthenticated"}`))
|
||||||
|
}}
|
||||||
|
embedder := newTestEmbedder(t, service, time.Now)
|
||||||
|
_, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"})
|
||||||
|
if !errors.Is(err, outbound.ErrEmbedderUnavailable) || strings.Contains(err.Error(), testToken) {
|
||||||
|
t.Fatalf("error = %v, want ErrEmbedderUnavailable without the token", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
|
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
|
||||||
@@ -138,8 +163,11 @@ func TestEmbedNeverQuotesTextsInErrors(t *testing.T) {
|
|||||||
|
|
||||||
func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) {
|
func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) {
|
||||||
for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} {
|
for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} {
|
||||||
if _, err := NewEmbedder(Settings{BaseURL: raw, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
if _, err := NewEmbedder(Settings{BaseURL: raw, Token: testToken, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||||
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
|
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if _, err := NewEmbedder(Settings{BaseURL: "http://ml:8000", Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||||
|
t.Error("NewEmbedder() accepted a client without the service token")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ func semanticJobHandlers(settings config.Config, logger *slog.Logger) ([]inbound
|
|||||||
trigger := newSemanticTrigger(settings)
|
trigger := newSemanticTrigger(settings)
|
||||||
if settings.Semantic.SemanticMatchingEnabled {
|
if settings.Semantic.SemanticMatchingEnabled {
|
||||||
embedder, err := ml.NewEmbedder(ml.Settings{
|
embedder, err := ml.NewEmbedder(ml.Settings{
|
||||||
BaseURL: settings.Semantic.MLServiceURL, Timeout: settings.Semantic.MLRequestTimeout,
|
BaseURL: settings.Semantic.MLServiceURL, Token: settings.Semantic.MLServiceToken, Timeout: settings.Semantic.MLRequestTimeout,
|
||||||
FailureThreshold: settings.Semantic.MLCircuitFailures, OpenDuration: settings.Semantic.MLCircuitOpen,
|
FailureThreshold: settings.Semantic.MLCircuitFailures, OpenDuration: settings.Semantic.MLCircuitOpen,
|
||||||
}, time.Now)
|
}, time.Now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -117,3 +117,15 @@ func DemoProductPolicyV5() ProductPolicy {
|
|||||||
policy.Matching = &matching
|
policy.Matching = &matching
|
||||||
return policy
|
return policy
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DemoProductPolicyV6 returns DemoProductPolicyV5 with the two-model
|
||||||
|
// semantic section (DemoSemanticEnsembleMatchingPolicy): Sem fuses Giga and
|
||||||
|
// Qwen3-Embedding. V5 stays the previous version with Giga alone. It is
|
||||||
|
// published explicitly with the policy-publish command; startup seeding
|
||||||
|
// publishes V1 only.
|
||||||
|
func DemoProductPolicyV6() ProductPolicy {
|
||||||
|
policy := DemoProductPolicyV5()
|
||||||
|
matching := DemoSemanticEnsembleMatchingPolicy()
|
||||||
|
policy.Matching = &matching
|
||||||
|
return policy
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
// Qwen3-Embedding-0.6B at the pinned revision with the service prompt recipe
|
||||||
|
// (the model's own query prompt, last-token pooling); the ML service reports
|
||||||
|
// the same identity.
|
||||||
|
const (
|
||||||
|
Qwen3EmbeddingModelID = "Qwen/Qwen3-Embedding-0.6B"
|
||||||
|
Qwen3EmbeddingModelRevision = "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3"
|
||||||
|
Qwen3EmbeddingPromptVersion = "qwen3-card-last-v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DemoMatchingSemanticsEnsemblePolicy returns the semantic section of the
|
||||||
|
// two-model ensemble S5-DE of the LincodexMatch research: Sem is the
|
||||||
|
// calibrated fused score 0.4 * z(Giga) + 0.6 * z(Qwen3-Embedding) of the
|
||||||
|
// cosines of the need view and the card view.
|
||||||
|
//
|
||||||
|
// - Weights: the research step 5 choice, made by 5-fold CV over the DEV
|
||||||
|
// needs on the research views (w_giga = 0.4 in four folds of five).
|
||||||
|
// - Mean and standard deviation: the research profiles and needs rendered
|
||||||
|
// with the product view builder (needs exactly as the research; a card
|
||||||
|
// with the catalog roles and declared grades, the card stack codes, and
|
||||||
|
// one published project per research experience entry), encoded by the
|
||||||
|
// ML service in float16 on CUDA. The mean is over all DEV need-profile
|
||||||
|
// pairs; the deviation is the pooled within-need deviation, so the fixed
|
||||||
|
// z-score reproduces the per-need z-score of the research (DEV nDCG@10
|
||||||
|
// 0.809 / indirect 0.518 against 0.809 / 0.518; Giga alone 0.738 / 0.403).
|
||||||
|
// - Calibration: the isotonic fit of P(consensus >= 2) on the fused score
|
||||||
|
// of the 3220 judged DEV pairs (994 positive), computed with the rounded
|
||||||
|
// mean and deviation below; 5-fold grouped CV ECE 0.025.
|
||||||
|
//
|
||||||
|
// The explanation thresholds stay those of Giga, the first member, which
|
||||||
|
// alone provides the item vectors. The values are a calibrated starting
|
||||||
|
// point, not a product measurement: real cards carry fewer projects than the
|
||||||
|
// research profiles carry experience entries.
|
||||||
|
func DemoMatchingSemanticsEnsemblePolicy() MatchingSemanticsPolicy {
|
||||||
|
policy := DemoMatchingSemanticsPolicy()
|
||||||
|
policy.Members = []MatchingSemanticMember{
|
||||||
|
{
|
||||||
|
Model: SemanticModel{
|
||||||
|
ID: GigaEmbeddingsModelID, Revision: GigaEmbeddingsModelRevision, PromptVersion: GigaEmbeddingsPromptVersion,
|
||||||
|
},
|
||||||
|
Weight: 4000, Mean: 2497, StandardDeviation: 741,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Model: SemanticModel{
|
||||||
|
ID: Qwen3EmbeddingModelID, Revision: Qwen3EmbeddingModelRevision, PromptVersion: Qwen3EmbeddingPromptVersion,
|
||||||
|
},
|
||||||
|
Weight: 6000, Mean: 3636, StandardDeviation: 731,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
policy.Calibration = demoEnsembleCalibration()
|
||||||
|
policy.Source = "LincodexMatch DEV split 2026-10-11, product card views, giga+qwen3 float16; weights 0.4/0.6 S5-DE (reports/step5), mean/std and isotonic fit on 3220 judged pairs"
|
||||||
|
return policy
|
||||||
|
}
|
||||||
|
|
||||||
|
// DemoSemanticEnsembleMatchingPolicy returns DemoSemanticMatchingPolicy with
|
||||||
|
// the ensemble semantic section; the Fit weights stay those of the single
|
||||||
|
// model section.
|
||||||
|
func DemoSemanticEnsembleMatchingPolicy() MatchingPolicy {
|
||||||
|
policy := DemoSemanticMatchingPolicy()
|
||||||
|
semantics := DemoMatchingSemanticsEnsemblePolicy()
|
||||||
|
policy.Semantics = &semantics
|
||||||
|
return policy
|
||||||
|
}
|
||||||
|
|
||||||
|
// demoEnsembleCalibration is the isotonic fit of the fused score in basis
|
||||||
|
// points (a fused score of 1.0 is 10000).
|
||||||
|
func demoEnsembleCalibration() []MatchingCalibrationPoint {
|
||||||
|
return []MatchingCalibrationPoint{
|
||||||
|
{-22961, 0}, {610, 0}, {619, 101}, {3279, 101}, {3279, 263}, {5629, 263}, {5682, 267}, {7140, 267},
|
||||||
|
{7155, 559}, {9628, 559}, {9636, 985}, {12855, 985}, {12869, 1379}, {14934, 1379}, {14954, 1690}, {16934, 1690},
|
||||||
|
{16971, 1940}, {17749, 1940}, {17751, 2283}, {18641, 2283}, {18642, 2632}, {18955, 2632}, {18960, 2667}, {19764, 2667},
|
||||||
|
{19767, 3105}, {21601, 3105}, {21614, 3436}, {23072, 3436}, {23075, 4062}, {23840, 4062}, {23843, 4286}, {23906, 4286},
|
||||||
|
{23933, 4444}, {24162, 4444}, {24179, 5059}, {27070, 5059}, {27076, 5766}, {28697, 5766}, {28701, 6706}, {29902, 6706},
|
||||||
|
{29916, 7059}, {30450, 7059}, {30460, 7500}, {33107, 7500}, {33109, 7692}, {33320, 7692}, {33354, 8182}, {33738, 8182},
|
||||||
|
{33753, 8391}, {35898, 8391}, {35939, 9244}, {40768, 9244}, {40885, 9792}, {44357, 9792}, {44390, 10000}, {52584, 10000},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import (
|
||||||
|
"math"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEnsembleSemanticsPolicyIsValidAndKeepsTheGigaExplanation(t *testing.T) {
|
||||||
|
ensemble := DemoMatchingSemanticsEnsemblePolicy()
|
||||||
|
if err := ensemble.Validate(); err != nil {
|
||||||
|
t.Fatalf("ensemble Validate() = %v", err)
|
||||||
|
}
|
||||||
|
single := DemoMatchingSemanticsPolicy()
|
||||||
|
if ensemble.ExplanationModel() != single.ExplanationModel() || ensemble.ExplanationModel().ID != GigaEmbeddingsModelID {
|
||||||
|
t.Fatalf("explanation model = %+v, want Giga", ensemble.ExplanationModel())
|
||||||
|
}
|
||||||
|
if ensemble.SkillMedium != single.SkillMedium || ensemble.SkillHigh != single.SkillHigh ||
|
||||||
|
ensemble.TaskMedium != single.TaskMedium || ensemble.TaskHigh != single.TaskHigh {
|
||||||
|
t.Fatal("the explanation thresholds must stay those of Giga")
|
||||||
|
}
|
||||||
|
if ensemble.Members[1].Model != (SemanticModel{ID: Qwen3EmbeddingModelID, Revision: Qwen3EmbeddingModelRevision, PromptVersion: Qwen3EmbeddingPromptVersion}) {
|
||||||
|
t.Fatalf("second member = %+v, want the pinned Qwen3-Embedding", ensemble.Members[1].Model)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnsembleSemanticsMapsTheFusedScoreMonotonically(t *testing.T) {
|
||||||
|
ensemble := DemoMatchingSemanticsEnsemblePolicy()
|
||||||
|
// At the member means every standardized cosine, and so the fused score, is 0.
|
||||||
|
score, ok := ensemble.FusedScore([]float64{0.2497, 0.3636})
|
||||||
|
if !ok || math.Abs(score) > 1e-12 {
|
||||||
|
t.Fatalf("score at the means = %v, %v, want 0", score, ok)
|
||||||
|
}
|
||||||
|
if low, high := ensemble.Probability(-1), ensemble.Probability(10); low != 0 || high != 1_000_000 {
|
||||||
|
t.Fatalf("clipped ends = %d and %d, want 0 and 1", low, high)
|
||||||
|
}
|
||||||
|
previous := int64(-1)
|
||||||
|
for giga := 0.0; giga <= 0.8; giga += 0.02 {
|
||||||
|
score, ok := ensemble.FusedScore([]float64{giga, giga + 0.1})
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("the fused score needs both members")
|
||||||
|
}
|
||||||
|
value := ensemble.Probability(score)
|
||||||
|
if value < previous {
|
||||||
|
t.Fatalf("Sem decreased at cosine %v: %d after %d", giga, value, previous)
|
||||||
|
}
|
||||||
|
previous = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProductPolicyV6CarriesTheEnsembleAndRoundTrips(t *testing.T) {
|
||||||
|
v6 := DemoProductPolicyV6()
|
||||||
|
if err := v6.Validate(); err != nil {
|
||||||
|
t.Fatalf("V6 Validate() = %v", err)
|
||||||
|
}
|
||||||
|
v5 := DemoProductPolicyV5()
|
||||||
|
if v6.Matching.FitSemanticsWeight != v5.Matching.FitSemanticsWeight || len(v5.Matching.Semantics.Members) != 1 {
|
||||||
|
t.Fatal("V6 must keep the Fit weights of V5, and V5 must stay the single-model version")
|
||||||
|
}
|
||||||
|
encoded, _, err := encodeProductPolicy(v6)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("encodeProductPolicy(V6) error = %v", err)
|
||||||
|
}
|
||||||
|
decoded, err := decodeProductPolicy(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decodeProductPolicy(V6) error = %v", err)
|
||||||
|
}
|
||||||
|
if !slices.Equal(decoded.Matching.Semantics.Members, v6.Matching.Semantics.Members) ||
|
||||||
|
!slices.Equal(decoded.Matching.Semantics.Calibration, v6.Matching.Semantics.Calibration) {
|
||||||
|
t.Fatal("the ensemble section did not survive the document round trip")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,34 @@ func (publisher *Publisher) EnsureDemoSemanticMatchingSection(ctx context.Contex
|
|||||||
domain.DemoSemanticMatchingPolicy)
|
domain.DemoSemanticMatchingPolicy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EnsureDemoSemanticEnsembleSection makes the latest demonstration version
|
||||||
|
// carry the two-model semantic section
|
||||||
|
// (domain.DemoSemanticEnsembleMatchingPolicy). A version whose semantic
|
||||||
|
// section already names exactly the ensemble models, in order, is left
|
||||||
|
// alone. Otherwise it publishes the next version, a copy of the latest one
|
||||||
|
// whose matching section is replaced, so the single-model section stays as
|
||||||
|
// the previous version and a rollback needs no recomputed vectors.
|
||||||
|
func (publisher *Publisher) EnsureDemoSemanticEnsembleSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||||
|
ensemble := domain.DemoMatchingSemanticsEnsemblePolicy()
|
||||||
|
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoSemanticEnsembleSection",
|
||||||
|
func(current *domain.MatchingPolicy) bool {
|
||||||
|
return current != nil && current.Semantics != nil && sameMemberModels(current.Semantics.Members, ensemble.Members)
|
||||||
|
},
|
||||||
|
domain.DemoSemanticEnsembleMatchingPolicy)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameMemberModels(left, right []domain.MatchingSemanticMember) bool {
|
||||||
|
if len(left) != len(right) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for index := range left {
|
||||||
|
if left[index].Model != right[index].Model {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
func (publisher *Publisher) ensureMatching(
|
func (publisher *Publisher) ensureMatching(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
author domain.PolicyAuthor,
|
author domain.PolicyAuthor,
|
||||||
|
|||||||
@@ -81,3 +81,34 @@ func TestEnsureDemoMatchingSectionDoesNotRetryAfterAConcurrentPublication(t *tes
|
|||||||
t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions))
|
t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEnsureDemoSemanticEnsembleSectionKeepsTheSingleModelVersionBeforeIt(t *testing.T) {
|
||||||
|
store := &memoryPolicies{}
|
||||||
|
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV5())
|
||||||
|
publisher := NewPublisher(store, testClock)
|
||||||
|
|
||||||
|
result, err := publisher.EnsureDemoSemanticEnsembleSection(context.Background(), "operator:night")
|
||||||
|
if err != nil || !result.Created || result.Version.Version() != 2 {
|
||||||
|
t.Fatalf("EnsureDemoSemanticEnsembleSection() = %+v, %v, want version 2 created", result, err)
|
||||||
|
}
|
||||||
|
semantics := result.Version.Policy().Matching.Semantics
|
||||||
|
if semantics == nil || len(semantics.Members) != 2 ||
|
||||||
|
semantics.Members[0].Model.ID != domain.GigaEmbeddingsModelID || semantics.Members[1].Model.ID != domain.Qwen3EmbeddingModelID {
|
||||||
|
t.Fatalf("semantic members = %+v, want Giga first and Qwen3 second", semantics)
|
||||||
|
}
|
||||||
|
if previous := store.versions[0].Policy().Matching.Semantics; len(previous.Members) != 1 {
|
||||||
|
t.Fatalf("previous version members = %d, want the single-model version kept", len(previous.Members))
|
||||||
|
}
|
||||||
|
if result.Version.Policy().Assessment.Signals == nil || result.Version.Policy().Support == nil {
|
||||||
|
t.Fatal("the ensemble version dropped an earlier section")
|
||||||
|
}
|
||||||
|
|
||||||
|
again, err := publisher.EnsureDemoSemanticEnsembleSection(context.Background(), "operator:night")
|
||||||
|
if err != nil || again.Created || len(store.versions) != 2 {
|
||||||
|
t.Fatalf("second call = %+v, %v with %d versions, want no new version", again, err, len(store.versions))
|
||||||
|
}
|
||||||
|
single, err := publisher.EnsureDemoSemanticMatchingSection(context.Background(), "operator:night")
|
||||||
|
if err != nil || single.Created {
|
||||||
|
t.Fatalf("the single-model command after the ensemble = %+v, %v, want it to leave the ensemble alone", single, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,12 +4,17 @@ services:
|
|||||||
context: ../..
|
context: ../..
|
||||||
dockerfile: ml/Dockerfile
|
dockerfile: ml/Dockerfile
|
||||||
environment:
|
environment:
|
||||||
# giga loads the pinned model baked into the image; fake is the hash
|
# A comma list of the pinned models baked into the image (giga, qwen3),
|
||||||
# encoder for stands without the model; none keeps the service not ready.
|
# the first one is the default; fake is the hash encoder for stands
|
||||||
ML_EMBEDDER: ${ML_EMBEDDER:-giga}
|
# without the models; none keeps the service not ready. The ensemble
|
||||||
|
# policy needs giga,qwen3.
|
||||||
|
ML_EMBEDDER: ${ML_EMBEDDER:-giga,qwen3}
|
||||||
ML_TORCH_THREADS: ${ML_TORCH_THREADS:-4}
|
ML_TORCH_THREADS: ${ML_TORCH_THREADS:-4}
|
||||||
ML_MICRO_BATCH: ${ML_MICRO_BATCH:-1}
|
ML_MICRO_BATCH: ${ML_MICRO_BATCH:-1}
|
||||||
ML_VERIFY_WEIGHTS: ${ML_VERIFY_WEIGHTS:-true}
|
ML_VERIFY_WEIGHTS: ${ML_VERIFY_WEIGHTS:-true}
|
||||||
|
# The container listens on all its interfaces, so the service refuses
|
||||||
|
# to start without the shared bearer token that the backend sends.
|
||||||
|
ML_SERVICE_TOKEN: ${ML_SERVICE_TOKEN:-}
|
||||||
# Loopback only: the backend reaches the service over the app network by
|
# Loopback only: the backend reaches the service over the app network by
|
||||||
# the alias below, never through a published port.
|
# the alias below, never through a published port.
|
||||||
ports:
|
ports:
|
||||||
@@ -35,13 +40,14 @@ services:
|
|||||||
options:
|
options:
|
||||||
max-size: 10m
|
max-size: 10m
|
||||||
max-file: "3"
|
max-file: "3"
|
||||||
# The float32 model takes about 3.6 GiB resident with four torch threads
|
# The float32 Giga model takes about 3.6 GiB resident with four torch
|
||||||
# (research CPU benchmark); the limits leave headroom for a request batch.
|
# threads (research CPU benchmark) and Qwen3-Embedding about 2.5 GiB more;
|
||||||
|
# the limits leave headroom for a request batch.
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
cpus: "4.0"
|
cpus: "4.0"
|
||||||
memory: 5G
|
memory: 8G
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
# The core project network; start the core project first (make -C deploy up).
|
# The core project network; start the core project first (make -C deploy up).
|
||||||
|
|||||||
@@ -247,6 +247,9 @@ services:
|
|||||||
# the separate ML project, which joins this network as "ml".
|
# the separate ML project, which joins this network as "ml".
|
||||||
SEMANTIC_MATCHING_ENABLED: ${SEMANTIC_MATCHING_ENABLED:-false}
|
SEMANTIC_MATCHING_ENABLED: ${SEMANTIC_MATCHING_ENABLED:-false}
|
||||||
ML_SERVICE_URL: ${ML_SERVICE_URL:-http://ml:8000}
|
ML_SERVICE_URL: ${ML_SERVICE_URL:-http://ml:8000}
|
||||||
|
# Shared bearer token of the ML service (a secret, at least 32
|
||||||
|
# characters); required while SEMANTIC_MATCHING_ENABLED is true.
|
||||||
|
ML_SERVICE_TOKEN: ${ML_SERVICE_TOKEN:-}
|
||||||
ML_REQUEST_TIMEOUT: ${ML_REQUEST_TIMEOUT:-30s}
|
ML_REQUEST_TIMEOUT: ${ML_REQUEST_TIMEOUT:-30s}
|
||||||
ML_CIRCUIT_FAILURES: ${ML_CIRCUIT_FAILURES:-3}
|
ML_CIRCUIT_FAILURES: ${ML_CIRCUIT_FAILURES:-3}
|
||||||
ML_CIRCUIT_OPEN: ${ML_CIRCUIT_OPEN:-30s}
|
ML_CIRCUIT_OPEN: ${ML_CIRCUIT_OPEN:-30s}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# systemd user unit of the ML service on a GPU host without Docker. Install it
|
||||||
|
# as ~/.config/systemd/user/lincodex-ml.service of the service user (with
|
||||||
|
# lingering enabled) and keep the settings and the token in the environment
|
||||||
|
# file, mode 600; see docs/en/DEPLOY.md#ml-service-on-a-gpu-host.
|
||||||
|
#
|
||||||
|
# %h is the home directory of the user: the layout below is
|
||||||
|
# %h/lincodex-ml/app/ml the ml/ directory of the release
|
||||||
|
# %h/lincodex-ml/venv the virtualenv (make -C ml cuda-requirements)
|
||||||
|
[Unit]
|
||||||
|
Description=Lincodex ML embedding service
|
||||||
|
StartLimitIntervalSec=600
|
||||||
|
StartLimitBurst=10
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=exec
|
||||||
|
WorkingDirectory=%h/lincodex-ml/app/ml
|
||||||
|
EnvironmentFile=%h/.config/lincodex-ml/ml.env
|
||||||
|
Environment=PYTHONPATH=%h/lincodex-ml/app/ml/src
|
||||||
|
Environment=PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||||
|
# The models are read from local files only; nothing is downloaded.
|
||||||
|
Environment=HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1 HF_HUB_DISABLE_PROGRESS_BARS=1
|
||||||
|
# Thread pools of the CPU work around the GPU (tokenizer, pooling).
|
||||||
|
Environment=OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 TOKENIZERS_PARALLELISM=false
|
||||||
|
# A permanent load failure ends the process, so systemd restarts it later.
|
||||||
|
Environment=ML_EXIT_ON_LOAD_FAILURE=true
|
||||||
|
ExecStart=%h/lincodex-ml/venv/bin/python -m lincodex_ml.serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=15
|
||||||
|
TimeoutStopSec=30
|
||||||
|
# The process with both models on CUDA keeps about 2.6 GiB resident (peak
|
||||||
|
# 2.9 GiB); the limits keep a fault from starving the other host services.
|
||||||
|
MemoryHigh=5G
|
||||||
|
MemoryMax=6G
|
||||||
|
CPUQuota=400%
|
||||||
|
TasksMax=512
|
||||||
|
LimitNOFILE=4096
|
||||||
|
Nice=5
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
UMask=0077
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Settings of the ML service on a GPU host; copy to
|
||||||
|
# ~/.config/lincodex-ml/ml.env (mode 600) and replace the placeholders. The
|
||||||
|
# token is a secret: generate it on the host, for example
|
||||||
|
# python3 -c 'import secrets; print(secrets.token_hex(32))'
|
||||||
|
# and give the same value to the backend as ML_SERVICE_TOKEN.
|
||||||
|
ML_EMBEDDER=giga,qwen3
|
||||||
|
ML_DEVICE=cuda
|
||||||
|
# float16 fits both models in about 2.4 GiB of VRAM; see the precision note in
|
||||||
|
# docs/en/DEPLOY.md#ml-service-on-a-gpu-host before changing it.
|
||||||
|
ML_DTYPE=float16
|
||||||
|
# Allocator cap of the process; the CUDA context adds about 130 MiB.
|
||||||
|
ML_CUDA_MEMORY_LIMIT_MB=2300
|
||||||
|
ML_TORCH_THREADS=4
|
||||||
|
ML_MICRO_BATCH=1
|
||||||
|
ML_VERIFY_WEIGHTS=true
|
||||||
|
# A private address of the host, never 0.0.0.0.
|
||||||
|
ML_LISTEN_HOST=<private-ip>
|
||||||
|
ML_LISTEN_PORT=<port>
|
||||||
|
# Directories with the pinned files (a Hugging Face snapshot directory works)
|
||||||
|
# and the lock files of the release that pin them.
|
||||||
|
ML_GIGA_MODEL_DIR=<directory of ai-sage/Giga-Embeddings-instruct-480M-0826 at the pinned revision>
|
||||||
|
ML_GIGA_MODEL_LOCK=<release>/ml/model/giga-embeddings-480m.lock.json
|
||||||
|
ML_QWEN3_MODEL_DIR=<directory of Qwen/Qwen3-Embedding-0.6B at the pinned revision>
|
||||||
|
ML_QWEN3_MODEL_LOCK=<release>/ml/model/qwen3-embedding-0.6b.lock.json
|
||||||
|
ML_SERVICE_TOKEN=<generated on the host>
|
||||||
@@ -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.
|
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).
|
- 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.
|
- 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.
|
- 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.
|
- 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).
|
- 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>'`.
|
- 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.
|
- 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
|
#### Candidate projects and GitHub repositories
|
||||||
|
|||||||
+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
|
### 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)).
|
- 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`.
|
- 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
|
### 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 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.
|
- 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` 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
|
## 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.
|
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 |
|
| 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_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_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_MAX_TOKENS` | 1024 | tokens a text, as in the study |
|
||||||
| `ML_VERIFY_WEIGHTS` | true | check the SHA-256 of the weights at startup |
|
| `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-config
|
||||||
make -C deploy ml-build
|
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-logs
|
||||||
make -C deploy ml-down
|
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
|
## 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:
|
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.
|
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` (and `ML_SERVICE_URL` if it differs) in the stand `.env` and restart the backend (`make -C deploy up`).
|
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.
|
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.
|
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 |
|
| `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_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_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 |
|
| `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` |
|
| `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.
|
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
|
## Separate monitoring Compose project
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@ For any further exception, scope it to the specific finding and affected input,
|
|||||||
- GitHub. Project repository checks call only `https://api.github.com`: the profile accepts an address only as `https://github.com/<owner>/<repo>`, the owner and name are checked against the GitHub patterns and escaped into the path, the base origin is fixed in code (tests replace it only inside the package), no proxy from the environment is used, TLS 1.2+, connect and response timeouts, a redirect is followed only to the same origin (at most three), responses are capped at 1 MiB and the README at 64 KiB. User input therefore cannot point the server at another host (SSRF). The checks are off by default (`GITHUB_REPOSITORY_CHECKS_ENABLED`), a repeated check is limited per candidate (`REPOSITORY_CHECK_INTERVAL`), and the GitHub limit is respected from its headers.
|
- GitHub. Project repository checks call only `https://api.github.com`: the profile accepts an address only as `https://github.com/<owner>/<repo>`, the owner and name are checked against the GitHub patterns and escaped into the path, the base origin is fixed in code (tests replace it only inside the package), no proxy from the environment is used, TLS 1.2+, connect and response timeouts, a redirect is followed only to the same origin (at most three), responses are capped at 1 MiB and the README at 64 KiB. User input therefore cannot point the server at another host (SSRF). The checks are off by default (`GITHUB_REPOSITORY_CHECKS_ENABLED`), a repeated check is limited per candidate (`REPOSITORY_CHECK_INTERVAL`), and the GitHub limit is respected from its headers.
|
||||||
- Token. `GITHUB_TOKEN` is optional, needs read access to public data only, and is sent only to `api.github.com`; it never reaches logs, errors, jobs, or the database. The check log carries the job id, attempt, state, and error class, never the repository; the job key and payload carry only a digest of the repository.
|
- Token. `GITHUB_TOKEN` is optional, needs read access to public data only, and is sent only to `api.github.com`; it never reaches logs, errors, jobs, or the database. The check log carries the job id, attempt, state, and error class, never the repository; the job key and payload carry only a digest of the repository.
|
||||||
- GitHub data. The description, topics, languages, and README text are untrusted data: the README becomes plain text, is stored only for a public repository, is used only for ranking, and is never shown, let alone as HTML. The repository address and owner never reach an organization, neither in the card, nor in the explanation, nor after C4.
|
- GitHub data. The description, topics, languages, and README text are untrusted data: the README becomes plain text, is stored only for a public repository, is used only for ranking, and is never shown, let alone as HTML. The repository address and owner never reach an organization, neither in the card, nor in the explanation, nor after C4.
|
||||||
- ML. Only the backend reaches the service, over the Compose network (`http://ml:8000`); the host port is loopback. The service has no credentials, so the network is its boundary. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights come from the image by SHA-256, the remote code of the model is never executed, no pickle is loaded, and the service runs offline.
|
- ML. Every route of the service except `/healthz` and `/readyz` requires `Authorization: Bearer <token>`: a shared random token of at least 32 printable characters (`ML_SERVICE_TOKEN` in the backend, `ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE` in the service) is compared in constant time and never reaches a log, a response, or an error message; a missing or wrong token answers 401 `unauthenticated`, and the request is refused before its body is read. Without a token the service answers loopback callers only, and the entry point `python -m lincodex_ml.serve` refuses to listen on a non-loopback address; the backend does not enable semantic matching without a token. In Compose the backend reaches the service over the network (`http://ml:8000`) and the host port is loopback; on a GPU host it listens on a private LAN address without TLS, so restrict the port to the app host address with host or network rules. `/metrics` requires the token too. The backend sends ML only the texts of the published card and of the organization's need, with no contact and no private profile. The weights are pinned by lock files with SHA-256, no remote model code is executed, no pickle is loaded, and the service runs offline.
|
||||||
|
|
||||||
## CI and limits
|
## CI and limits
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -645,9 +645,11 @@ What the tests do not prove: isolation in the production VM until the suite has
|
|||||||
## Semantic matching tests
|
## Semantic matching tests
|
||||||
|
|
||||||
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
|
- ML service (`make -C ml test`, no model, no network): `tests/test_embeddings.py` checks the `POST /v1/embeddings` contract on the deterministic hash encoder: response order, normalization, equal vectors for two equal requests, micro-batches by length, 503 `service_unavailable` before readiness and ready only after the warm-up, 400 for too many texts, a length, and unknown fields, 413 for a body over the limit (with Content-Length and streamed), and no request text in the logs; `tests/test_model_files.py` checks the lock file (only safetensors and configs, a full revision, no code or pickle) and the size and SHA-256 verification.
|
||||||
- The real model: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M vectors on CPU with the study's vectors for four texts (difference below 1e-4, measured below 1e-6) and a repeated encode (the same vector). This checks that the recipe is reproduced, not model quality.
|
- Ensemble and ML token (`make -C ml test`): `tests/test_ensemble_and_auth.py` checks the choice of one of several loaded models by `model` and 400 for another one, readiness only after every model, a refusal of two encoders with one id, 503 and a readiness cool-down after a lack of device memory with recovery, a retried load on a lack of memory and the exit through `ML_EXIT_ON_LOAD_FAILURE` on another failure, 401 without a token, with a wrong token, with the Basic scheme, and on `/metrics`, open `/healthz` and `/readyz`, loopback only without a token, a refusal before the body is read, no token in logs or settings errors, and the entry point refusing a non-loopback address without a token. Checked by hand on CUDA: a load without enough memory is retried while the process stays alive and not ready; a request over the allocator limit answers 503, `/readyz` answers 503 for 30 seconds, and then the service answers 200 again.
|
||||||
|
- The real models: `make -C ml model-fetch` and `make -C ml test-model` (marker `slow`, skipped by the ordinary checks) compare the Giga-480M and Qwen3-Embedding-0.6B vectors with the study's vectors for four texts (difference below 1e-4) and a repeated encode (the same vector); `ML_TEST_DEVICE=cuda` runs them on the GPU in float32. On 2026-10-11 both models passed on CPU and on CUDA on the GPU host. This checks that the recipe is reproduced, not model quality; the float16 against float32 comparison and the fit of the ensemble policy are a separate evaluation on the study's DEV data (see [DEPLOY.md](DEPLOY.md#ml-service-on-a-gpu-host)).
|
||||||
- Backend unit: need and card views (`domain/semantic_test.go`: the exact study text, confirmed values only, metadata only for a verified repository), the float32 codec and cosine, the calibration (interpolation, steps, a monotone demo table), the thresholds, validation and the round trip of the V5 policy document; projects and GitHub addresses (`domain/candidate_project_test.go`: accepted and rejected addresses, normalization, limits, a repeated repository, no address in the card); explanation selection (`usecase/matching/semantic_test.go`: order, limit, a stale title, a hidden stack or hidden projects explain nothing, the `projects` field record); Fit with a known and the neutral Sem; the ML client (batches of 32, response checks, the circuit breaker, no text in errors); GitHub (`adapter/secondary/github`: httptest, public repositories only, the token only when set, ETag and 304, 403/429 limits with the wait, server errors, a refused redirect to another origin, size caps, README text without markup or HTML); jobs and the trigger (keys and payloads without the repository address, disabled features schedule nothing).
|
- Backend unit: need and card views (`domain/semantic_test.go`: the exact study text, confirmed values only, metadata only for a verified repository), the float32 codec and cosine, the calibration (interpolation, steps, a monotone demo table), the thresholds, validation and the round trip of the V5 policy document; projects and GitHub addresses (`domain/candidate_project_test.go`: accepted and rejected addresses, normalization, limits, a repeated repository, no address in the card); explanation selection (`usecase/matching/semantic_test.go`: order, limit, a stale title, a hidden stack or hidden projects explain nothing, the `projects` field record); Fit with a known and the neutral Sem; the ML client (batches of 32, response checks, the circuit breaker, no text in errors); GitHub (`adapter/secondary/github`: httptest, public repositories only, the token only when set, ETag and 304, 403/429 limits with the wait, server errors, a refused redirect to another origin, size caps, README text without markup or HTML); jobs and the trigger (keys and payloads without the repository address, disabled features schedule nothing).
|
||||||
- Integration (Testcontainers): `TestSemanticMatchingOverHTTP` runs over HTTP, PostgreSQL, and the real job worker with a fake ML service (httptest on the contract) and a fake GitHub: a profile save schedules jobs without the address in their keys, the repository check and the card vectors, the neutral Sem and flag before the need vectors, then the candidate with the close project first, the explanation names the project and `repository_verified`, and neither the response nor the card carries the repository address or owner; equal responses of two searches; the access history with the `projects` field; a repeated backfill with the same label schedules nothing twice and calls ML for no unchanged text; unpublishing `projects` removes the project vectors and the title from the explanation; an unavailable ML keeps the job in retry while the search answers; the refresh limit (429, then 202).
|
- Integration (Testcontainers): `TestSemanticMatchingOverHTTP` runs over HTTP, PostgreSQL, and the real job worker with a fake ML service (httptest on the contract) and a fake GitHub: a profile save schedules jobs without the address in their keys, the repository check and the card vectors, the neutral Sem and flag before the need vectors, then the candidate with the close project first, the explanation names the project and `repository_verified`, and neither the response nor the card carries the repository address or owner; equal responses of two searches; the access history with the `projects` field; a repeated backfill with the same label schedules nothing twice and calls ML for no unchanged text; unpublishing `projects` removes the project vectors and the title from the explanation; an unavailable ML keeps the job in retry while the search answers; the refresh limit (429, then 202).
|
||||||
|
- Ensemble and token in the backend: unit tests `domain/policy_matching_ensemble_test.go` (the ensemble policy validates, Giga explains with its thresholds, the fused score is 0 at the means, the calibration is monotone and clipped, the V6 document round trip), `usecase/policy` (the ensemble published on top of V5, a repeat publishes nothing, the single-model command leaves the ensemble alone), `cli/policypublish` (the `semantic-ensemble` track), `adapter/secondary/ml` (the bearer token on every request, 401 as unavailability without the token text, no client without a token), `config` (the token is required while matching is enabled, short and spaced tokens are refused, formatted settings hide the tokens). In `TestSemanticMatchingOverHTTP` the fake ML requires the token and serves both models; after the ensemble publication and before the backfill every entry has the neutral `Sem`, and the backfill adds Qwen3 `whole` vectors for the six cards and the need without re-encoding Giga and without Qwen3 item vectors, after which every entry has a known `Sem`.
|
||||||
- Not checked: ranking quality and explanation precision on real data, latency on the production server, the ML image build on this machine, and a stand with the model. Tests never call the real GitHub.
|
- Not checked: ranking quality and explanation precision on real data, latency on the production server, the ML image build on this machine, and a stand with the model. Tests never call the real GitHub.
|
||||||
|
|
||||||
## Future software validation
|
## Future software validation
|
||||||
|
|||||||
@@ -834,13 +834,13 @@ Checker задается для группы: `exact`, `tokens`, `numbers` (чи
|
|||||||
Реализовано: эмбеддинги потребностей и опубликованных карточек, `Sem` в Fit, структурированное объяснение "почему в подборке", проекты кандидата и проверка их репозиториев GitHub. Основание - исследование LincodexMatch (DEV 30 потребностей, TEST 70, 2594 синтетических профиля); его цифры получены на синтетике и не являются продуктовым замером.
|
Реализовано: эмбеддинги потребностей и опубликованных карточек, `Sem` в Fit, структурированное объяснение "почему в подборке", проекты кандидата и проверка их репозиториев GitHub. Основание - исследование LincodexMatch (DEV 30 потребностей, TEST 70, 2594 синтетических профиля); его цифры получены на синтетике и не являются продуктовым замером.
|
||||||
|
|
||||||
- Модель. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) на ревизии `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 измерения, до 1024 токенов на текст. На TEST она лучшая на косвенных совпадениях (nDCG@10 indirect 0.571 против 0.409 у Qwen3-Embedding-0.6B) и выполняет цели CPU при 4 потоках (p95 профиля 352 мс, поиск по 100k 591 мс в исследовании). Рецепт повторяет исследование: потребность и каждое требование кодируются с промптом `Instruct: Given a query, retrieve relevant passages\nQuery: `, карточка и ее элементы без промпта, среднее по маске внимания вместе с токенами промпта, L2-нормализация. Удаленный код репозитория модели не скачивается и не исполняется: тот же двунаправленный Qwen3 реализован в `ml/src/lincodex_ml/inference/giga.py`, а тест `make -C ml test-model` сверяет векторы с векторами исследования (разница < 1e-6).
|
- Модель. `ai-sage/Giga-Embeddings-instruct-480M-0826` (MIT) на ревизии `1763d603adac8057bd6482a708001b0ed2e0a903`, float32, 1024 измерения, до 1024 токенов на текст. На TEST она лучшая на косвенных совпадениях (nDCG@10 indirect 0.571 против 0.409 у Qwen3-Embedding-0.6B) и выполняет цели CPU при 4 потоках (p95 профиля 352 мс, поиск по 100k 591 мс в исследовании). Рецепт повторяет исследование: потребность и каждое требование кодируются с промптом `Instruct: Given a query, retrieve relevant passages\nQuery: `, карточка и ее элементы без промпта, среднее по маске внимания вместе с токенами промпта, L2-нормализация. Удаленный код репозитория модели не скачивается и не исполняется: тот же двунаправленный Qwen3 реализован в `ml/src/lincodex_ml/inference/giga.py`, а тест `make -C ml test-model` сверяет векторы с векторами исследования (разница < 1e-6).
|
||||||
- ML-сервис. `POST /v1/embeddings` контракта `api/ml` (до 32 текстов по 8000 символов, тело до 2 MiB, необязательный id модели `model`, ответ с id, ревизией, размерностью и `prompt_version`). Сервис сейчас загружает одну модель; запрос другой модели получает 400 с указателем `/model`. Веса скачиваются один раз при сборке образа по lock-файлу `ml/model/giga-embeddings-480m.lock.json` с проверкой SHA-256 (только safetensors, конфиги и токенизатор), сервис работает офлайн. Readiness становится ready только после загрузки и прогревочного кодирования; до этого 503 `service_unavailable`. Тексты кодируются по одному запросу за раз, в микропакетах фиксированного размера (по умолчанию 1), отсортированных по длине с позицией запроса как тай-брейком, поэтому одни и те же тексты на одном образе и числе потоков дают одни и те же векторы.
|
- ML-сервис. `POST /v1/embeddings` контракта `api/ml` (до 32 текстов по 8000 символов, тело до 2 MiB, необязательный id модели `model`, ответ с id, ревизией, размерностью и `prompt_version`). Сервис загружает модели из списка `ML_EMBEDDER` (`giga`, `qwen3`; первая отвечает на запрос без `model`), запрос модели, которую он не загрузил, получает 400 с указателем `/model`. Каждая модель закреплена lock-файлом (`ml/model/giga-embeddings-480m.lock.json`, `ml/model/qwen3-embedding-0.6b.lock.json`) с проверкой SHA-256 (только safetensors, конфиги и токенизатор), удаленный код не исполняется, сервис работает офлайн. Устройство - `ML_DEVICE` (`cpu` по умолчанию или `cuda`), точность - `ML_DTYPE` (`float32`; `float16` и `bfloat16` только на CUDA), `ML_CUDA_MEMORY_LIMIT_MB` ограничивает аллокатор процесса на общей видеокарте. Нехватка видеопамяти процесс не роняет: загрузка повторяется с растущей паузой (15 с, до 5 мин), запрос получает 503 `service_unavailable`, а `/readyz` 30 секунд отвечает 503, после чего сервис снова обслуживает запросы. Readiness становится ready только после загрузки и прогревочного кодирования всех моделей. Тексты кодируются по одному запросу за раз, в микропакетах фиксированного размера (по умолчанию 1), отсортированных по длине с позицией запроса как тай-брейком, поэтому одни и те же тексты на одной установке, устройстве, точности и числе потоков дают одни и те же векторы (на CUDA проверено повторным кодированием). Все маршруты, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>` (см. [SECURITY.md](SECURITY.md#исходящие-запросы-и-ml)).
|
||||||
- Какие поля ранжируют. Только то, что показывает анонимная карточка этого кандидата до когортного обобщения: роли из `self_assessment` и `categories` (`backend (middle)`), распознанные коды стека и опубликованные проекты с публичными метаданными проверенных репозиториев. Приватный текст профиля (резюме, `summary` опыта, работодатели) в ранжирование не попадает, как и раньше в ML (принцип "Go передает только разрешенные данные"). Исследование показывает, что приватный опыт улучшает качество (предложение 3 отчета); разрешение использовать его на сервере без показа - открытый вопрос владельца, и оно потребует явного решения в политике приватности.
|
- Какие поля ранжируют. Только то, что показывает анонимная карточка этого кандидата до когортного обобщения: роли из `self_assessment` и `categories` (`backend (middle)`), распознанные коды стека и опубликованные проекты с публичными метаданными проверенных репозиториев. Приватный текст профиля (резюме, `summary` опыта, работодатели) в ранжирование не попадает, как и раньше в ML (принцип "Go передает только разрешенные данные"). Исследование показывает, что приватный опыт улучшает качество (предложение 3 отчета); разрешение использовать его на сервере без показа - открытый вопрос владельца, и оно потребует явного решения в политике приватности.
|
||||||
- Векторы. Таблица `semantic_vectors` (миграция `00049`): субъект (`candidate` или `need`), ключ элемента (`whole`, `roles`, `stack`, `project:<n>`, `required_skill:<n>`, `desired_skill:<n>`, `task:<n>`), SHA-256 текста с версией рендеринга `semantic-views-v1`, модель, ревизия, версия промпта, размерность и вектор как little-endian float32 (4 KiB на 1024 измерения: точно, одинаково на всех платформах; int8 отложен, пока объем не станет проблемой). Каскадное удаление вместе с аккаунтом или потребностью. У кандидата хранится ровно один набор на модель, у потребности - набор последнего снимка требований.
|
- Векторы. Таблица `semantic_vectors` (миграция `00049`): субъект (`candidate` или `need`), ключ элемента (`whole`, `roles`, `stack`, `project:<n>`, `required_skill:<n>`, `desired_skill:<n>`, `task:<n>`), SHA-256 текста с версией рендеринга `semantic-views-v1`, модель, ревизия, версия промпта, размерность и вектор как little-endian float32 (4 KiB на 1024 измерения: точно, одинаково на всех платформах; int8 отложен, пока объем не станет проблемой). Каскадное удаление вместе с аккаунтом или потребностью. У кандидата хранится ровно один набор на модель, у потребности - набор последнего снимка требований.
|
||||||
- Конвейер. Сохранение профиля, изменение публикации, новый снимок требований и завершенная проверка репозитория ставят задание по сроку (`semantic.candidate`, `semantic.need`) в той же транзакции; запрос пользователя ML не ждет. Обработчик берет advisory-блокировку субъекта, рендерит текущую карточку или текущий снимок, сравнивает дайджесты с сохраненными (без изменений - без вызова ML), кодирует тексты и заменяет набор. Задание кодирует тексты каждой модели из `members` политики, передавая ее id; первая модель хранит все элементы, остальные только `whole`. Модель ответа (id, ревизия, версия промпта) должна совпадать с моделью политики, иначе задание повторяется. До 20 попыток с backoff переживают недоступность ML; задание кандидата без публикации удаляет его векторы. Отзыв C2 закрывает карточку в другом usecase и задание не ставит: векторы остаются до следующего задания кандидата или backfill, но невидимая карточка в поиск не попадает. Команда `semantic-backfill` ставит задания для всех кандидатов с профилем и всех потребностей постранично, идемпотентно по метке запуска и с курсором для продолжения.
|
- Конвейер. Сохранение профиля, изменение публикации, новый снимок требований и завершенная проверка репозитория ставят задание по сроку (`semantic.candidate`, `semantic.need`) в той же транзакции; запрос пользователя ML не ждет. Обработчик берет advisory-блокировку субъекта, рендерит текущую карточку или текущий снимок, сравнивает дайджесты с сохраненными (без изменений - без вызова ML), кодирует тексты и заменяет набор. Задание кодирует тексты каждой модели из `members` политики, передавая ее id; первая модель хранит все элементы, остальные только `whole`. Модель ответа (id, ревизия, версия промпта) должна совпадать с моделью политики, иначе задание повторяется. До 20 попыток с backoff переживают недоступность ML; задание кандидата без публикации удаляет его векторы. Отзыв C2 закрывает карточку в другом usecase и задание не ставит: векторы остаются до следующего задания кандидата или backfill, но невидимая карточка в поиск не попадает. Команда `semantic-backfill` ставит задания для всех кандидатов с профилем и всех потребностей постранично, идемпотентно по метке запуска и с курсором для продолжения.
|
||||||
- Sem и Fit. Поиск никогда не вызывает ML: он рендерит снимок потребности, читает векторы с совпадающими дайджестами и векторы `whole` видимых кандидатов по каждой модели политики, считает слитый балл Σ w·(cos - mean)/std и переводит его в `Sem` изотонической калибровкой из политики (P(релевантно | балл) на DEV, ECE 0.015-0.049 против 0.17-0.57 у сырого косинуса), целочисленной интерполяцией. По умолчанию модель одна с весом 1, mean 0 и std 1, поэтому балл равен косинусу. Нет векторов потребности или кандидата хотя бы для одной модели политики или ML - `Sem` нейтральное 0.5 и флаг `ml_unavailable` для этой записи, как раньше. Множество кандидатов, фильтры, видимость, квоты и когортные правила не меняются; BM25 в оценку не смешивается (на TEST он режет indirect с 0.571 до 0.250).
|
- Sem и Fit. Поиск никогда не вызывает ML: он рендерит снимок потребности, читает векторы с совпадающими дайджестами и векторы `whole` видимых кандидатов по каждой модели политики, считает слитый балл Σ w·(cos - mean)/std и переводит его в `Sem` изотонической калибровкой из политики (P(релевантно | балл) на DEV, ECE 0.015-0.049 против 0.17-0.57 у сырого косинуса), целочисленной интерполяцией. По умолчанию модель одна с весом 1, mean 0 и std 1, поэтому балл равен косинусу. Нет векторов потребности или кандидата хотя бы для одной модели политики или ML - `Sem` нейтральное 0.5 и флаг `ml_unavailable` для этой записи, как раньше. Множество кандидатов, фильтры, видимость, квоты и когортные правила не меняются; BM25 в оценку не смешивается (на TEST он режет indirect с 0.571 до 0.250).
|
||||||
- Политика. `domain.DemoProductPolicyV5()` - V4 с семантическим разделом `matching.semantics` (`members` - одна модель Giga с ревизией, версией промпта, весом 1, mean 0 и std 1; 80 точек калибровки `score_bp`, пороги объяснений, лимит, источник) и весами Fit 0.4167 / 0.0833 / 0.5. При весе PRD 0.10 Fit дает на TEST nDCG@10 0.649 против 0.818 у самого эмбеддера, при 0.5 - 0.838; Cov и Dom сохраняют соотношение PRD 5:1. V4 остается предыдущей версией (точка PRD). Публикация: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'`.
|
- Политика. `domain.DemoProductPolicyV5()` - V4 с семантическим разделом `matching.semantics` (`members` - одна модель Giga с ревизией, версией промпта, весом 1, mean 0 и std 1; 80 точек калибровки `score_bp`, пороги объяснений, лимит, источник) и весами Fit 0.4167 / 0.0833 / 0.5. При весе PRD 0.10 Fit дает на TEST nDCG@10 0.649 против 0.818 у самого эмбеддера, при 0.5 - 0.838; Cov и Dom сохраняют соотношение PRD 5:1. V4 остается предыдущей версией (точка PRD). Публикация: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'`.
|
||||||
- Ансамбль. Схема готова к S5-DE из исследования: `Sem` = калибровка(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), на TEST nDCG@10 0.842 против 0.818 у одной Giga, при 8 потоках p95 около 0.85 с на 12 ядрах. Сейчас не включено. Порядок включения: (1) добавить в ML-сервис вторую настроенную модель `Qwen/Qwen3-Embedding-0.6B` на ревизии `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3` с lock-файлом, своим промптом и версией промпта (сервис выбирает модель по полю `model`; загрузка нескольких моделей - отдельная доработка); (2) поднять `ML_TORCH_THREADS` до 8 и лимиты контейнера; (3) на DEV посчитать mean и std косинуса каждой модели и заново подобрать изотоническую калибровку и, при необходимости, пороги на слитом балле (исследование нормировало z по корпусу каждой потребности, продукт использует глобальные mean и std из политики, поэтому цифры нужно перепроверить); (4) опубликовать новую версию политики с двумя `members` (Giga первой, она же объясняет записи; сумма весов 1) и новой калибровкой; (5) сразу после вступления версии в силу запустить `semantic-backfill` для кандидатов и потребностей. Задания считают векторы только для действующей политики, поэтому до конца backfill записи без векторов второй модели получают нейтральное `Sem`; переход лучше проводить в тихое время. Векторы Giga при этом не пересчитываются (дайджесты те же), а векторы прежних моделей остаются и позволяют откатиться на прошлую версию политики без пересчета.
|
- Ансамбль. Реализован S5-DE из исследования: `Sem` = калибровка(0.4·z(Giga) + 0.6·z(Qwen3-Embedding-0.6B)), `domain.DemoProductPolicyV6()` (V5 с разделом `DemoSemanticEnsembleMatchingPolicy`, веса Fit те же). Вторая модель - `Qwen/Qwen3-Embedding-0.6B` (Apache-2.0) на ревизии `97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3`, обычный Qwen3 без удаленного кода: потребность кодируется с промптом модели `Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:` (склейка без разделителя), карточка без промпта, токенизатор добавляет end-of-text, вектор - скрытое состояние последнего токена с L2-нормализацией (`prompt_version` `qwen3-card-last-v1`, `ml/src/lincodex_ml/inference/qwen3.py`, сверка с векторами исследования - `make -C ml test-model`). Веса 0.4 / 0.6 - выбор шага 5 исследования (5-кратная CV по потребностям DEV, w_giga = 0.4 в четырех фолдах из пяти). Mean и std посчитаны заново на продуктовых представлениях: потребности и профили исследования отрендерены продуктовым построителем (`domain.NewNeedSemanticDocument` дает тот же текст, что исследование, для всех 100 потребностей; карточка - роли каталога с заявленным грейдом, коды стека карточки и по одному опубликованному проекту на каждый опыт исследования) и закодированы ML-сервисом на CUDA в float16. Mean - по всем парам DEV (Giga 0.2497, Qwen3 0.3636), std - средняя внутри потребности (0.0741 и 0.0731), поэтому фиксированный z воспроизводит z по корпусу каждой потребности из исследования: DEV nDCG@10 all / indirect 0.809 / 0.518 против 0.809 / 0.518 у исследовательской формы и 0.738 / 0.403 у одной Giga на тех же представлениях. Калибровка - изотоническая регрессия P(consensus >= 2) на слитом балле 3220 размеченных пар DEV (994 положительных), посчитанном с округленными mean и std политики; 56 точек, ECE 5-кратной CV по потребностям 0.025. Пороги объяснений остаются порогами Giga (первая модель, она же дает векторы элементов). Источник и скрипты расчета записаны в `source` политики и в [DEPLOY.md](DEPLOY.md#семантический-подбор). Без проектов в карточке сигнал слабый (DEV nDCG@10 0.21 у ансамбля и 0.23 у одной Giga на картах только с ролями и стеком), поэтому выигрыш ансамбля зависит от того, публикуют ли кандидаты проекты. Публикация и backfill: `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'`, затем `semantic-backfill` для кандидатов и потребностей. Задания считают векторы для каждой модели действующей политики, поэтому до конца backfill записи без векторов Qwen3 получают нейтральное `Sem`; переход лучше проводить в тихое время. Векторы Giga не пересчитываются (дайджесты те же), а V5 остается предыдущей версией: векторы обеих моделей остаются, и откат на Giga не требует пересчета.
|
||||||
- Объяснение. Для поиска по потребности каждое подтвержденное требование (обязательный и желательный навык, задача) сопоставляется с ближайшим элементом карточки по косинусу. Пороги из DEV: P(пара релевантна | лучший косинус требования) 0.5 и 0.7, для навыков 0.3673 / 0.4607 (`medium` / `high`), для задач 0.2997 / 0.4192. В ответ попадают `semantic_evidence` записи: вид и текст требования (текст самой потребности организации), вид элемента (`project`, `stack`, `roles`), название проекта, только если кандидат опубликовал поле `projects` и название не изменилось с момента расчета, признак `repository_verified` и полоса; порядок `high`, затем косинус, затем порядок требований; не больше 6 (политика). Стек и роли объясняют только пока карточка показывает их этой организации после когортного обобщения. Текст модели в объяснение не входит. Показ названия проекта записывается в историю доступа кандидата полем `projects`. Точность объяснений не проверялась: выборка исследования на 50 пар осталась без разметки.
|
- Объяснение. Для поиска по потребности каждое подтвержденное требование (обязательный и желательный навык, задача) сопоставляется с ближайшим элементом карточки по косинусу. Пороги из DEV: P(пара релевантна | лучший косинус требования) 0.5 и 0.7, для навыков 0.3673 / 0.4607 (`medium` / `high`), для задач 0.2997 / 0.4192. В ответ попадают `semantic_evidence` записи: вид и текст требования (текст самой потребности организации), вид элемента (`project`, `stack`, `roles`), название проекта, только если кандидат опубликовал поле `projects` и название не изменилось с момента расчета, признак `repository_verified` и полоса; порядок `high`, затем косинус, затем порядок требований; не больше 6 (политика). Стек и роли объясняют только пока карточка показывает их этой организации после когортного обобщения. Текст модели в объяснение не входит. Показ названия проекта записывается в историю доступа кандидата полем `projects`. Точность объяснений не проверялась: выборка исследования на 50 пар осталась без разметки.
|
||||||
|
|
||||||
#### Проекты кандидата и репозитории GitHub
|
#### Проекты кандидата и репозитории GitHub
|
||||||
|
|||||||
+39
-8
@@ -89,7 +89,7 @@ Docker Engine с Compose plugin, GNU make, python3 (цели `deploy` запус
|
|||||||
### 5. ФСП, ML и данные
|
### 5. ФСП, ML и данные
|
||||||
|
|
||||||
- ФСП: интеграции нет ни в каком режиме. В этой сборке нет переключателя off или mock, fixture-провайдера и обращений к внешнему API. Профиль заполняется вручную, привязка ФСП ID необязательна и пока недоступна, а путь до категории проходит через анкету и тест. Проект не имеет официального доступа к данным ФСП и не обещает его; связь с ФСП через fixture-провайдер запланирована (см. [ARCHITECTURE.md](ARCHITECTURE.md#идентификация-фсп-и-приватность)).
|
- ФСП: интеграции нет ни в каком режиме. В этой сборке нет переключателя off или mock, fixture-провайдера и обращений к внешнему API. Профиль заполняется вручную, привязка ФСП ID необязательна и пока недоступна, а путь до категории проходит через анкету и тест. Проект не имеет официального доступа к данным ФСП и не обещает его; связь с ФСП через fixture-провайдер запланирована (см. [ARCHITECTURE.md](ARCHITECTURE.md#идентификация-фсп-и-приватность)).
|
||||||
- ML: основной и демонстрационный стенды по умолчанию не запускают ML и не обращаются к нему; поиск подставляет нейтральную смысловую близость 0.5 с флагом `ml_unavailable`. Семантический подбор включается отдельно: ML-проект с моделью Giga-Embeddings-instruct-480M на CPU, `SEMANTIC_MATCHING_ENABLED`, семантическая политика и backfill (см. [Семантический подбор](#семантический-подбор)). GPU и ключи внешнего inference не нужны и не читаются.
|
- ML: основной и демонстрационный стенды по умолчанию не запускают ML и не обращаются к нему; поиск подставляет нейтральную смысловую близость 0.5 с флагом `ml_unavailable`. Семантический подбор включается отдельно: ML-сервис с моделями Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B (ML Compose на CPU или [ML-сервис на GPU-хосте](#ml-сервис-на-gpu-хосте)), общий токен `ML_SERVICE_TOKEN`, `SEMANTIC_MATCHING_ENABLED`, семантическая политика и backfill (см. [Семантический подбор](#семантический-подбор)). Ключи внешнего inference не нужны и не читаются.
|
||||||
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`.
|
- Данные: демонстрационный стенд содержит только синтетические данные. Адреса на зарезервированном домене `@demo.lincodex.test` никогда не получают почту, названия помечены как синтетические, категории имеют источник `synthetic_demo` и не откалиброваны, а семейства заданий синтетические и не прошли предметную проверку. Не регистрируйте на этом стенде реальных людей. Синтетические категории (`ASSESSMENT_DEMO_CATEGORIES_ENABLED=true`) включают только демонстрационный overlay и overlay изолированного браузерного набора регистрации (см. [TESTING.md](TESTING.md#минимальный-путь-от-регистрации-до-раскрытых-контактов)); в `.env.example` значение `false`.
|
||||||
|
|
||||||
### 6. Проверки
|
### 6. Проверки
|
||||||
@@ -495,6 +495,7 @@ make -C backend policy-publish ARGS='matching --actor operator:<handle>'
|
|||||||
- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после.
|
- Новая версия действует для новых поисков сразу и не меняет сохраненных результатов. Это также новая версия всей политики product, поэтому открытие категории, привязанное к прежней версии, нужно открыть заново (и аттестовать заново на демонстрационном стенде, см. выше), прежде чем создавать новые попытки оценки. Публикуйте ее до начала попыток кандидатов либо повторите открытие и аттестацию после.
|
||||||
- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам.
|
- Демонстрационные значения (коэффициенты PRD, предел 10 записей на группу и небольшая таксономия «специализация - технология») описаны в [архитектуре](ARCHITECTURE.md#версии-продуктовой-политики); они не калиброваны. Изолированный браузерный стенд публикует тот же раздел сам.
|
||||||
- `policy-publish semantic` публикует следующую версию, в которой раздел подбора заменен семантическим (`DemoSemanticMatchingPolicy`: веса Fit 0.4167 / 0.0833 / 0.5, модель, калибровка и пороги объяснений, см. [Семантический подбор](#семантический-подбор)); если у последней версии семантический раздел уже есть, ничего не меняется. Версия с точкой PRD остается предыдущей.
|
- `policy-publish semantic` публикует следующую версию, в которой раздел подбора заменен семантическим (`DemoSemanticMatchingPolicy`: веса Fit 0.4167 / 0.0833 / 0.5, модель, калибровка и пороги объяснений, см. [Семантический подбор](#семантический-подбор)); если у последней версии семантический раздел уже есть, ничего не меняется. Версия с точкой PRD остается предыдущей.
|
||||||
|
- `policy-publish semantic-ensemble` публикует следующую версию, в которой семантический раздел заменен ансамблем Giga + Qwen3-Embedding (`DemoSemanticEnsembleMatchingPolicy`: две модели, их веса, mean и std, калибровка слитого балла; веса Fit и пороги объяснений те же); если семантический раздел последней версии уже называет обе модели, ничего не меняется. Версия с одной Giga остается предыдущей. ML-сервис должен обслуживать обе модели, а после публикации нужен backfill (см. [Семантический подбор](#семантический-подбор)).
|
||||||
|
|
||||||
## Изолированный демонстрационный стенд
|
## Изолированный демонстрационный стенд
|
||||||
|
|
||||||
@@ -531,17 +532,25 @@ make -C deploy demo-down DEMO_MODE=isolated
|
|||||||
|
|
||||||
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему не требуются. Он входит во внешнюю сеть core-проекта (`APP_NETWORK`) с псевдонимом `ml`, поэтому backend обращается к `http://ml:8000` без опубликованного порта; поднимайте core-проект первым. Порт на хосте по умолчанию слушает только 127.0.0.1:8000 для диагностики; ML_BIND_ADDRESS меняйте только при подготовленном приватном адресе и firewall. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему не требуются. Он входит во внешнюю сеть core-проекта (`APP_NETWORK`) с псевдонимом `ml`, поэтому backend обращается к `http://ml:8000` без опубликованного порта; поднимайте core-проект первым. Порт на хосте по умолчанию слушает только 127.0.0.1:8000 для диагностики; ML_BIND_ADDRESS меняйте только при подготовленном приватном адресе и firewall. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
||||||
|
|
||||||
Образ основан на `python:3.14-slim` (PyTorch публикует только glibc-колеса, поэтому Alpine не подходит; минорная версия закреплена под `requires-python` и lock). Зависимости, включая CPU-сборку PyTorch с индекса `download.pytorch.org/whl/cpu`, ставятся через uv только на этапе сборки; runtime не содержит pip. Отдельная стадия скачивает файлы модели Giga-Embeddings-instruct-480M на закрепленной ревизии по `ml/model/giga-embeddings-480m.lock.json` и проверяет размер и SHA-256 каждого файла (около 0.98 GB весов safetensors); при старте сервис повторно сверяет SHA-256 (`ML_VERIFY_WEIGHTS=true`, несколько секунд) и работает с `HF_HUB_OFFLINE=1`. Ожидаемый размер образа около 2.5 GB (Python и PyTorch CPU около 1.4 GB, модель около 1 GB); на этой машине образ не собирался из-за свободного места на диске.
|
Образ основан на `python:3.14-slim` (PyTorch публикует только glibc-колеса, поэтому Alpine не подходит; минорная версия закреплена под `requires-python` и lock). Зависимости, включая CPU-сборку PyTorch с индекса `download.pytorch.org/whl/cpu`, ставятся через uv только на этапе сборки; runtime не содержит pip. Отдельная стадия скачивает файлы обеих моделей на закрепленных ревизиях по `ml/model/giga-embeddings-480m.lock.json` и `ml/model/qwen3-embedding-0.6b.lock.json` в `/opt/lincodex/models/giga-480m` и `/opt/lincodex/models/qwen3-0.6b` и проверяет размер и SHA-256 каждого файла (около 0.98 и 1.19 GB весов safetensors); при старте сервис повторно сверяет SHA-256 (`ML_VERIFY_WEIGHTS=true`, несколько секунд) и работает с `HF_HUB_OFFLINE=1`. Контейнер слушает 0.0.0.0:8000 через `python -m lincodex_ml.serve`, поэтому без `ML_SERVICE_TOKEN` сервис не стартует. Ожидаемый размер образа около 3.7 GB (Python и PyTorch CPU около 1.4 GB, модели около 2.2 GB); на этой машине образ не собирался из-за свободного места на диске.
|
||||||
|
|
||||||
| Переменная | По умолчанию | Назначение |
|
| Переменная | По умолчанию | Назначение |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `ML_EMBEDDER` | `giga` в образе и Compose, `none` вне образа | `giga` - модель из образа, `fake` - детерминированный хеш-кодировщик для стендов без модели (его model id не совпадает с политикой, векторы не используются), `none` - сервис не готов |
|
| `ML_EMBEDDER` | `giga,qwen3` в образе и Compose, `none` вне образа | список моделей через запятую (`giga`, `qwen3`), первая отвечает на запрос без `model`; `fake` - детерминированный хеш-кодировщик для стендов без моделей (его model id не совпадает с политикой, векторы не используются), `none` - сервис не готов |
|
||||||
|
| `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` | пусто | общий bearer-токен с backend (не короче 32 печатных символов, секрет); без него сервис отвечает только клиентам с loopback и не стартует на не-loopback адресе |
|
||||||
|
| `ML_LISTEN_HOST`, `ML_LISTEN_PORT` | 127.0.0.1, 8000 (в образе 0.0.0.0, 8000) | адрес и порт `python -m lincodex_ml.serve` |
|
||||||
|
| `ML_GIGA_MODEL_DIR`, `ML_QWEN3_MODEL_DIR` | каталоги образа | файлы моделей; каталог снимка Hugging Face тоже подходит |
|
||||||
|
| `ML_GIGA_MODEL_LOCK`, `ML_QWEN3_MODEL_LOCK` | `model.lock.json` в каталоге модели | lock-файл, по которому сверяются файлы |
|
||||||
|
| `ML_DEVICE` | `cpu` | `cpu`, `cuda` или `cuda:<номер>` |
|
||||||
|
| `ML_DTYPE` | `float32` | `float16` и `bfloat16` только на CUDA |
|
||||||
|
| `ML_CUDA_MEMORY_LIMIT_MB` | 0 (без предела) | предел аллокатора CUDA процесса; контекст CUDA добавляет около 130 MiB |
|
||||||
|
| `ML_EXIT_ON_LOAD_FAILURE` | false | завершить процесс после ошибки загрузки, кроме нехватки видеопамяти, чтобы supervisor его перезапустил |
|
||||||
| `ML_TORCH_THREADS` | 4 | потоки torch; при 4 потоках исследование выполняет цели CPU |
|
| `ML_TORCH_THREADS` | 4 | потоки torch; при 4 потоках исследование выполняет цели CPU |
|
||||||
| `ML_MICRO_BATCH` | 1 | размер микропакета; 1 дает каждому тексту одинаковый вектор при любом составе запроса |
|
| `ML_MICRO_BATCH` | 1 | размер микропакета; 1 дает каждому тексту одинаковый вектор при любом составе запроса |
|
||||||
| `ML_MAX_TOKENS` | 1024 | токенов на текст, как в исследовании |
|
| `ML_MAX_TOKENS` | 1024 | токенов на текст, как в исследовании |
|
||||||
| `ML_VERIFY_WEIGHTS` | true | сверять SHA-256 весов при старте |
|
| `ML_VERIFY_WEIGHTS` | true | сверять SHA-256 весов при старте |
|
||||||
|
|
||||||
Лимиты контейнера: 4 CPU и 5 GiB (float32-модель занимает около 3.6 GiB резидентной памяти). Readiness становится 200 только после загрузки и прогрева.
|
Лимиты контейнера: 4 CPU и 8 GiB (на CPU в float32 Giga занимает около 3.6 GiB резидентной памяти, Qwen3-Embedding еще около 2.5 GiB). Readiness становится 200 только после загрузки и прогрева обеих моделей. Нехватка памяти устройства процесс не роняет: загрузка повторяется, запрос получает 503, `/readyz` 30 секунд отвечает 503.
|
||||||
|
|
||||||
make -C deploy ml-config
|
make -C deploy ml-config
|
||||||
make -C deploy ml-build
|
make -C deploy ml-build
|
||||||
@@ -549,14 +558,29 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
|||||||
make -C deploy ml-logs
|
make -C deploy ml-logs
|
||||||
make -C deploy ml-down
|
make -C deploy ml-down
|
||||||
|
|
||||||
Для разработки без Docker: `make -C ml model-fetch` скачивает и проверяет те же файлы в `ML_MODEL_DIR` (по умолчанию `~/.cache/lincodex-ml/giga-480m`), `make -C ml test-model` проверяет совпадение векторов с исследованием. Замер на Apple M5 (CPU, 4 потока, HTTP, 20 запросов): представление потребности 887 символов p50 296 мс / p95 707 мс, профиль 500 символов 207 / 237 мс, короткое требование 74 / 166 мс, пакет задания карточки из 13 текстов 2.2 / 5.4 с. Это один ноутбук с другими нагрузками, а не замер стенда.
|
Для разработки без Docker: `make -C ml model-fetch` скачивает и проверяет те же файлы в `ML_GIGA_MODEL_DIR` и `ML_QWEN3_MODEL_DIR` (по умолчанию `~/.cache/lincodex-ml/giga-480m` и `~/.cache/lincodex-ml/qwen3-0.6b`), `make -C ml test-model` сверяет векторы обеих моделей с исследованием (`ML_TEST_DEVICE=cuda` - на GPU). Замер Giga на Apple M5 (CPU, 4 потока, HTTP, 20 запросов): представление потребности 887 символов p50 296 мс / p95 707 мс, профиль 500 символов 207 / 237 мс, короткое требование 74 / 166 мс, пакет задания карточки из 13 текстов 2.2 / 5.4 с. Это один ноутбук с другими нагрузками, а не замер стенда.
|
||||||
|
|
||||||
|
## ML-сервис на GPU-хосте
|
||||||
|
|
||||||
|
На отдельном GPU-хосте сервис работает без Docker: под пользователем сервиса как systemd user-юнит `lincodex-ml.service` (шаблон [deploy/ml-gpu/lincodex-ml.service](../../deploy/ml-gpu/lincodex-ml.service), для пользователя включен linger) с virtualenv и моделями из локальных файлов. Обе модели в float16 занимают 2.2-2.4 GiB видеопамяти, поэтому сервис помещается рядом с другим потребителем той же карты.
|
||||||
|
|
||||||
|
1. Код: каталог `ml/` выпуска (`git archive`) в `~/lincodex-ml/app/ml`.
|
||||||
|
2. Virtualenv: закрепленный uv 0.12.22 создает `~/lincodex-ml/venv`. `make -C ml cuda-requirements` пишет в `ml/dist/requirements-cuda.txt` закрепленные в `uv.lock` версии с CUDA-сборкой torch (`torch==2.11.0+cu128`); сначала поставьте строку torch с индекса `https://download.pytorch.org/whl/cu128`, затем остальные строки с PyPI (`uv pip install --python ~/lincodex-ml/venv/bin/python ...`). Общий кэш uv с `UV_LINK_MODE=hardlink` не занимает места под уже скачанные колеса, но кэш делится по адресу индекса: другое написание адреса скачивает torch и библиотеки CUDA заново (около 6 GB). Исключение: при нехватке диска virtualenv использует системный CPython 3.12 с теми же версиями пакетов (колесо torch для cp314 с CUDA не помещается), а пакет не устанавливается: юнит задает `PYTHONPATH` на `src`. Модульные тесты сервиса проходят на 3.12, но 3.14 остается основной версией, поэтому синтаксис 3.13+ в `ml/src` сломает этот хост.
|
||||||
|
3. Модели: каталоги снимков Hugging Face на закрепленных ревизиях (`HF_HOME` только для чтения) или `make -C ml model-fetch`; при старте файлы сверяются с lock-файлами выпуска.
|
||||||
|
4. Настройки: [deploy/ml-gpu/ml.env.example](../../deploy/ml-gpu/ml.env.example) копируется в `~/.config/lincodex-ml/ml.env` (каталог 700, файл 600). Токен генерируется на хосте CSPRNG (`python3 -c 'import secrets; print(secrets.token_hex(32))'`) и хранится только в этом файле и в окружении backend. Адрес - приватный адрес хоста, не 0.0.0.0.
|
||||||
|
5. Запуск: шаблон юнита в `~/.config/systemd/user/lincodex-ml.service`, затем `systemctl --user daemon-reload` и `systemctl --user enable --now lincodex-ml.service`. Перезапуск после обновления кода или настроек - `systemctl --user restart lincodex-ml.service`, состояние - `systemctl --user status lincodex-ml.service`, журнал - `journalctl --user -u lincodex-ml.service -f`. Юнит задает `Restart=on-failure`, `MemoryHigh=5G`, `MemoryMax=6G`, `CPUQuota=400%`, 4 потока torch и OMP и `ML_EXIT_ON_LOAD_FAILURE=true`: нехватка видеопамяти не роняет процесс, а другие ошибки загрузки (например, недоступный драйвер при старте хоста) завершают его, и systemd перезапускает его через 15 секунд.
|
||||||
|
6. Сеть: firewall и системные настройки юнит не меняет. Ограничьте порт адресом хоста приложения на уровне хоста или сети; трафик идет по LAN без TLS, поэтому токен и тексты видны в этом сегменте.
|
||||||
|
|
||||||
|
Точность и видеопамять (RTX 5060 Ti 16 GB, замер 2026-10-11, бюджет процесса около 2.5 GB): в float32 одна Giga занимает 1984 MiB после загрузки и до 2750 MiB под запросом из текстов по 1024 токена, Qwen3 - 2404 и 3038 MiB, вместе около 4.3 GiB после загрузки, поэтому float32 не помещается. В float16 обе модели в одном процессе занимают 2252 MiB после загрузки и 2404 MiB под худшим запросом (32 текста по 1024 токена), аллокатор ограничен `ML_CUDA_MEMORY_LIMIT_MB=2300`. Качество float16 против float32 на DEV исследования (продуктовые представления): косинус векторов не ниже 0.99986 (Giga) и 0.99999 (Qwen3), nDCG@10 изменился на -0.0004 и +0.0008, у ансамбля на +0.0002 (порог 0.005), top-10 ансамбля совпадает как множество для 30 из 30 потребностей DEV и по порядку для 28, повторное кодирование при микропакете 1 дает те же биты. `bfloat16` отклонен: top-10 совпадает для 27 из 30, порядок для 14. Поэтому `ML_DTYPE=float16`; mean, std и калибровка ансамбля посчитаны на векторах float16.
|
||||||
|
|
||||||
|
Задержка через LAN с хоста приложения (40 запросов, один текст, микропакет 1, CUDA float16): представление потребности - Giga p50 11.4 / p95 13.0 мс, Qwen3 12.5 / 14.5 мс; профиль - 11.2 / 12.9 и 12.1 / 13.8 мс; пакет задания карточки из 13 текстов - 132 / 135 и 143 / 160 мс. Резидентная память процесса около 2.6 GiB (пик 2.9 GiB). Это замер одного хоста, когда другая модель на карте не была загружена, а не нагрузочный тест.
|
||||||
|
|
||||||
## Семантический подбор
|
## Семантический подбор
|
||||||
|
|
||||||
Поиск не вызывает ML: он читает векторы, которые фоновые задания посчитали заранее (см. [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения)). Включение на стенде:
|
Поиск не вызывает ML: он читает векторы, которые фоновые задания посчитали заранее (см. [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения)). Включение на стенде:
|
||||||
|
|
||||||
1. `make -C deploy up`, затем `make -C deploy ml-up` и дождаться `/readyz` 200.
|
1. `make -C deploy up`, затем `make -C deploy ml-up` (или [ML-сервис на GPU-хосте](#ml-сервис-на-gpu-хосте)) и дождаться `/readyz` 200.
|
||||||
2. В `.env` стенда задать `SEMANTIC_MATCHING_ENABLED=true` (и при отличии `ML_SERVICE_URL`), перезапустить backend (`make -C deploy up`).
|
2. В `.env` стенда задать `SEMANTIC_MATCHING_ENABLED=true`, `ML_SERVICE_TOKEN` (тот же токен, что у ML-сервиса) и при отличии `ML_SERVICE_URL` (для GPU-хоста - `http://<адрес>:<порт>`), перезапустить backend (`make -C deploy up`).
|
||||||
3. Опубликовать семантический раздел политики: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (с `DATABASE_URL` стенда). Новая версия политики, как и раздел `matching`, требует заново открыть и аттестовать категорию на демонстрационном стенде.
|
3. Опубликовать семантический раздел политики: `make -C backend policy-publish ARGS='semantic --actor operator:<handle>'` (с `DATABASE_URL` стенда). Новая версия политики, как и раздел `matching`, требует заново открыть и аттестовать категорию на демонстрационном стенде.
|
||||||
4. Посчитать векторы существующих данных: `make -C backend semantic-backfill ARGS='all --run <метка>'`. Команде нужен только `DATABASE_URL`; она ставит задания постранично и печатает курсор, с которого продолжить (`--after`). Повтор с той же меткой ничего не ставит повторно; новая метка пересчитывает, а неизменившиеся тексты ML не вызывают. Задания выполняет worker backend.
|
4. Посчитать векторы существующих данных: `make -C backend semantic-backfill ARGS='all --run <метка>'`. Команде нужен только `DATABASE_URL`; она ставит задания постранично и печатает курсор, с которого продолжить (`--after`). Повтор с той же меткой ничего не ставит повторно; новая метка пересчитывает, а неизменившиеся тексты ML не вызывают. Задания выполняет worker backend.
|
||||||
|
|
||||||
@@ -564,6 +588,7 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `SEMANTIC_MATCHING_ENABLED` | false | ставить и выполнять задания векторов |
|
| `SEMANTIC_MATCHING_ENABLED` | false | ставить и выполнять задания векторов |
|
||||||
| `ML_SERVICE_URL` | `http://ml:8000` в Compose | origin ML без пути и учетных данных |
|
| `ML_SERVICE_URL` | `http://ml:8000` в Compose | origin ML без пути и учетных данных |
|
||||||
|
| `ML_SERVICE_TOKEN` | пусто | bearer-токен ML-сервиса, 32-512 печатных символов без пробелов; обязателен при `SEMANTIC_MATCHING_ENABLED=true`; секрет, в логи не попадает |
|
||||||
| `ML_REQUEST_TIMEOUT` | 30s | таймаут одного запроса к ML |
|
| `ML_REQUEST_TIMEOUT` | 30s | таймаут одного запроса к ML |
|
||||||
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | после стольких подряд неудач клиент не вызывает ML указанное время |
|
| `ML_CIRCUIT_FAILURES`, `ML_CIRCUIT_OPEN` | 3, 30s | после стольких подряд неудач клиент не вызывает ML указанное время |
|
||||||
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | выполнять проверки репозиториев проектов на `api.github.com` |
|
| `GITHUB_REPOSITORY_CHECKS_ENABLED` | false | выполнять проверки репозиториев проектов на `api.github.com` |
|
||||||
@@ -573,7 +598,13 @@ ML имеет отдельный Compose-файл и проект; Redis и Seaw
|
|||||||
|
|
||||||
Без ML или при его недоступности поиск работает как раньше: нейтральное `Sem` 0.5 и флаг `ml_unavailable`; задания повторяются до 20 раз и потом ждут оператора (повторный backfill). Изолированный браузерный стенд (e2e) ML не запускает и использует политику V4; демонстрационный стенд по умолчанию тоже работает без ML, включение на нем - те же шаги, что выше, с проектом `lincodex-demo`. Метрики: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` в backend, `lincodex_ml_embedding_request_seconds` и `lincodex_ml_embedding_texts_total` в ML.
|
Без ML или при его недоступности поиск работает как раньше: нейтральное `Sem` 0.5 и флаг `ml_unavailable`; задания повторяются до 20 раз и потом ждут оператора (повторный backfill). Изолированный браузерный стенд (e2e) ML не запускает и использует политику V4; демонстрационный стенд по умолчанию тоже работает без ML, включение на нем - те же шаги, что выше, с проектом `lincodex-demo`. Метрики: `lincodex_scheduled_jobs_total{kind="semantic.candidate"|"semantic.need"|"profile.repository_check"}` в backend, `lincodex_ml_embedding_request_seconds` и `lincodex_ml_embedding_texts_total` в ML.
|
||||||
|
|
||||||
Ансамбль моделей (Giga + Qwen3-Embedding-0.6B) не включен; порядок включения - вторая модель в ML-сервисе, 8 потоков, калибровка слитого балла, новая политика с двумя `members` и backfill - описан в [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения). Векторы модели, которую политика больше не называет, поиск не читает; они остаются для отката на прошлую версию политики.
|
Ансамбль Giga + Qwen3-Embedding-0.6B (см. [ARCHITECTURE.md](ARCHITECTURE.md#семантический-слой-и-объяснения)) включается после шагов выше, когда ML-сервис обслуживает обе модели (`ML_EMBEDDER=giga,qwen3`):
|
||||||
|
|
||||||
|
1. `make -C backend policy-publish ARGS='semantic-ensemble --actor operator:<handle>'` - новая версия политики с двумя моделями; версия с одной Giga остается предыдущей.
|
||||||
|
2. Сразу после этого `make -C backend semantic-backfill ARGS='candidates --run <метка>'` и `make -C backend semantic-backfill ARGS='needs --run <метка>'` (или `all`). Задания считают векторы каждой модели действующей политики: векторы Giga не меняются и ML не вызывают, для Qwen3 кодируется только `whole` каждой карточки и потребности. До конца backfill записи без векторов Qwen3 получают нейтральное `Sem` с `ml_unavailable`, поэтому переход лучше проводить в тихое время.
|
||||||
|
3. Проверка: `SELECT model_id, count(*) FROM semantic_vectors WHERE item_key = 'whole' GROUP BY model_id` - число векторов Qwen3 догоняет число векторов Giga.
|
||||||
|
|
||||||
|
Происхождение значений политики: DEV-разметка исследования LincodexMatch (30 потребностей, 3220 размеченных пар), профили и потребности исследования, отрендеренные продуктовым построителем представлений, векторы ML-сервиса на CUDA в float16, веса из шага 5 исследования; скрипты кодирования и расчета и их выводы хранятся рядом с исследовательским прогоном на GPU-хосте (`lincodex-ml/eval/`). Векторы модели, которую политика больше не называет, поиск не читает; они остаются для отката на прошлую версию политики.
|
||||||
|
|
||||||
## Отдельный monitoring Compose
|
## Отдельный monitoring Compose
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -47,7 +47,7 @@ Gitleaks требует полный Git checkout. Отсутствие репо
|
|||||||
- GitHub. Проверка репозиториев проектов обращается только к `https://api.github.com`: адрес в профиле принимается только в форме `https://github.com/<owner>/<repo>`, владелец и имя проверяются по шаблонам GitHub и экранируются в путь, базовый origin зашит в коде (тесты подменяют его только внутри пакета), прокси из окружения не используется, TLS 1.2+, таймауты соединения и ответа, редирект допускается только на тот же origin (не больше трех), ответы ограничены 1 MiB, README - 64 KiB. Поэтому пользовательский ввод не может направить сервер на другой хост (SSRF). Проверки выключены по умолчанию (`GITHUB_REPOSITORY_CHECKS_ENABLED`), повторная проверка ограничена на кандидата (`REPOSITORY_CHECK_INTERVAL`), лимит GitHub соблюдается по заголовкам.
|
- GitHub. Проверка репозиториев проектов обращается только к `https://api.github.com`: адрес в профиле принимается только в форме `https://github.com/<owner>/<repo>`, владелец и имя проверяются по шаблонам GitHub и экранируются в путь, базовый origin зашит в коде (тесты подменяют его только внутри пакета), прокси из окружения не используется, TLS 1.2+, таймауты соединения и ответа, редирект допускается только на тот же origin (не больше трех), ответы ограничены 1 MiB, README - 64 KiB. Поэтому пользовательский ввод не может направить сервер на другой хост (SSRF). Проверки выключены по умолчанию (`GITHUB_REPOSITORY_CHECKS_ENABLED`), повторная проверка ограничена на кандидата (`REPOSITORY_CHECK_INTERVAL`), лимит GitHub соблюдается по заголовкам.
|
||||||
- Токен. `GITHUB_TOKEN` необязателен, нужен только для чтения публичных данных и отправляется только на `api.github.com`; он не попадает в логи, ошибки, задания и базу. Журнал проверки содержит id задания, попытку, состояние и класс ошибки, но не репозиторий; ключ и payload задания несут только дайджест репозитория.
|
- Токен. `GITHUB_TOKEN` необязателен, нужен только для чтения публичных данных и отправляется только на `api.github.com`; он не попадает в логи, ошибки, задания и базу. Журнал проверки содержит id задания, попытку, состояние и класс ошибки, но не репозиторий; ключ и payload задания несут только дайджест репозитория.
|
||||||
- Данные GitHub. Описание, темы, языки и текст README - недоверенные данные: README превращается в простой текст, хранится только для публичного репозитория, используется только для ранжирования и никогда не выводится, тем более как HTML. Адрес и владелец репозитория не попадают организации ни в карточке, ни в объяснении, ни после C4.
|
- Данные GitHub. Описание, темы, языки и текст README - недоверенные данные: README превращается в простой текст, хранится только для публичного репозитория, используется только для ранжирования и никогда не выводится, тем более как HTML. Адрес и владелец репозитория не попадают организации ни в карточке, ни в объяснении, ни после C4.
|
||||||
- ML. Сервис доступен backend только по сети Compose (`http://ml:8000`), порт на хосте - loopback; учетных данных у него нет, поэтому сеть - его граница. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся из образа по SHA-256, удаленный код модели не исполняется, pickle не загружается, сервис работает офлайн.
|
- ML. Все маршруты сервиса, кроме `/healthz` и `/readyz`, требуют `Authorization: Bearer <token>`: общий случайный токен не короче 32 печатных символов (`ML_SERVICE_TOKEN` у backend, `ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE` у сервиса) сравнивается за постоянное время и не попадает в логи, ответы и сообщения об ошибках; неверный или отсутствующий токен получает 401 `unauthenticated`, а запрос отклоняется до чтения тела. Без токена сервис отвечает только клиентам с loopback, а точка входа `python -m lincodex_ml.serve` отказывается слушать не-loopback адрес; backend без токена не включает семантический подбор. В Compose сервис доступен backend по сети `http://ml:8000`, порт на хосте - loopback; на GPU-хосте он слушает приватный адрес LAN без TLS, поэтому ограничьте порт адресом хоста приложения средствами хоста или сети. `/metrics` тоже требует токен. Backend передает в ML только тексты опубликованной карточки и потребности организации, без контактов и приватного профиля. Веса берутся по lock-файлам с SHA-256, удаленный код моделей не исполняется, pickle не загружается, сервис работает офлайн.
|
||||||
|
|
||||||
## CI и границы проверок
|
## CI и границы проверок
|
||||||
|
|
||||||
|
|||||||
+3
-1
@@ -645,9 +645,11 @@ Vitest работает в Node без DOM, поэтому ограничени
|
|||||||
## Тесты семантического подбора
|
## Тесты семантического подбора
|
||||||
|
|
||||||
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.
|
- ML-сервис (`make -C ml test`, без модели и сети): `tests/test_embeddings.py` проверяет контракт `POST /v1/embeddings` на детерминированном хеш-кодировщике: порядок ответа, нормировку, одинаковые векторы двух одинаковых запросов, микропакеты по длине, 503 `service_unavailable` до готовности и ready только после прогрева, 400 на лишние тексты, длину и неизвестные поля, 413 на тело больше лимита (с Content-Length и потоком), отсутствие текстов запроса в логах; `tests/test_model_files.py` проверяет lock-файл (только safetensors и конфиги, полная ревизия, без кода и pickle) и сверку размера и SHA-256.
|
||||||
- Реальная модель: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M на CPU с векторами исследования для четырех текстов (разница меньше 1e-4, измерено меньше 1e-6) и повторное кодирование (тот же вектор). Это проверка воспроизводимости рецепта, а не оценка качества.
|
- Ансамбль и токен ML (`make -C ml test`): `tests/test_ensemble_and_auth.py` проверяет выбор одной из нескольких загруженных моделей полем `model` и 400 для чужой, готовность только после всех моделей, отказ от двух кодировщиков с одним id, 503 и остывание readiness после нехватки видеопамяти с восстановлением, повтор загрузки при нехватке памяти и выход по `ML_EXIT_ON_LOAD_FAILURE` при другой ошибке, 401 без токена, с неверным токеном, со схемой Basic и на `/metrics`, открытые `/healthz` и `/readyz`, только loopback без токена, отказ до чтения тела, отсутствие токена в логах и ошибках настроек, отказ точки входа слушать не-loopback адрес без токена. На CUDA вручную проверено: загрузка при нехватке памяти повторяется, процесс жив и не готов; запрос сверх предела аллокатора получает 503, `/readyz` 30 секунд отвечает 503, затем сервис снова отвечает 200.
|
||||||
|
- Реальные модели: `make -C ml model-fetch` и `make -C ml test-model` (маркер `slow`, обычные проверки его пропускают) сверяют векторы Giga-480M и Qwen3-Embedding-0.6B с векторами исследования для четырех текстов (разница меньше 1e-4) и повторное кодирование (тот же вектор); `ML_TEST_DEVICE=cuda` запускает их на GPU в float32. 2026-10-11 обе модели прошли и на CPU, и на CUDA на GPU-хосте. Это проверка воспроизводимости рецепта, а не оценка качества; сравнение точности float16 с float32 и расчет политики ансамбля - отдельная оценка на DEV исследования (см. [DEPLOY.md](DEPLOY.md#ml-сервис-на-gpu-хосте)).
|
||||||
- Backend unit: представления потребности и карточки (`domain/semantic_test.go`: точный текст исследования, только подтвержденные значения, метаданные только у проверенного репозитория), кодек float32 и косинус, калибровка (интерполяция, ступени, монотонность демонстрационной таблицы), пороги, проверка и круговой проход документа политики V5; проекты и адрес GitHub (`domain/candidate_project_test.go`: допустимые и отклоненные адреса, нормализация, лимиты, повтор репозитория, отсутствие адреса в карточке); выбор объяснения (`usecase/matching/semantic_test.go`: порядок, лимит, устаревшее название, скрытые стек и проекты не объясняют, запись поля `projects`); Fit с известным и нейтральным Sem; клиент ML (пакеты по 32, проверка ответа, circuit breaker, отсутствие текста в ошибках); GitHub (`adapter/secondary/github`: httptest, только публичный репозиторий, токен только когда задан, ETag и 304, лимиты 403/429 с ожиданием, ошибки сервера, отказ от редиректа на другой origin, ограничения размера, текст README без разметки и HTML); задания и триггер (ключи и payload без адреса репозитория, отключенные функции ничего не ставят).
|
- Backend unit: представления потребности и карточки (`domain/semantic_test.go`: точный текст исследования, только подтвержденные значения, метаданные только у проверенного репозитория), кодек float32 и косинус, калибровка (интерполяция, ступени, монотонность демонстрационной таблицы), пороги, проверка и круговой проход документа политики V5; проекты и адрес GitHub (`domain/candidate_project_test.go`: допустимые и отклоненные адреса, нормализация, лимиты, повтор репозитория, отсутствие адреса в карточке); выбор объяснения (`usecase/matching/semantic_test.go`: порядок, лимит, устаревшее название, скрытые стек и проекты не объясняют, запись поля `projects`); Fit с известным и нейтральным Sem; клиент ML (пакеты по 32, проверка ответа, circuit breaker, отсутствие текста в ошибках); GitHub (`adapter/secondary/github`: httptest, только публичный репозиторий, токен только когда задан, ETag и 304, лимиты 403/429 с ожиданием, ошибки сервера, отказ от редиректа на другой origin, ограничения размера, текст README без разметки и HTML); задания и триггер (ключи и payload без адреса репозитория, отключенные функции ничего не ставят).
|
||||||
- Интеграция (Testcontainers): `TestSemanticMatchingOverHTTP` проходит через HTTP, PostgreSQL и настоящий worker заданий с фиктивным ML-сервисом (httptest по контракту) и фиктивным GitHub: сохранение профиля ставит задания без адреса в ключах, проверка репозитория и векторы карточек, нейтральный Sem и флаг до векторов потребности, затем первым идет кандидат с близким проектом, объяснение называет проект и `repository_verified`, а в ответе и карточке нет адреса и владельца репозитория; одинаковые ответы двух поисков; история доступа с полем `projects`; повторный backfill с той же меткой ничего не ставит дважды и не вызывает ML для неизменных текстов; снятие поля `projects` удаляет векторы проектов и название из объяснения; недоступный ML оставляет задание в повторе, а поиск отвечает; лимит повторной проверки (429, затем 202).
|
- Интеграция (Testcontainers): `TestSemanticMatchingOverHTTP` проходит через HTTP, PostgreSQL и настоящий worker заданий с фиктивным ML-сервисом (httptest по контракту) и фиктивным GitHub: сохранение профиля ставит задания без адреса в ключах, проверка репозитория и векторы карточек, нейтральный Sem и флаг до векторов потребности, затем первым идет кандидат с близким проектом, объяснение называет проект и `repository_verified`, а в ответе и карточке нет адреса и владельца репозитория; одинаковые ответы двух поисков; история доступа с полем `projects`; повторный backfill с той же меткой ничего не ставит дважды и не вызывает ML для неизменных текстов; снятие поля `projects` удаляет векторы проектов и название из объяснения; недоступный ML оставляет задание в повторе, а поиск отвечает; лимит повторной проверки (429, затем 202).
|
||||||
|
- Ансамбль и токен в backend: unit-тесты `domain/policy_matching_ensemble_test.go` (политика ансамбля проходит проверку, объясняет Giga с ее порогами, слитый балл в среднем равен 0, калибровка монотонна и обрезана, круговой проход документа V6), `usecase/policy` (публикация ансамбля поверх V5, повтор ничего не публикует, одиночная команда не трогает ансамбль), `cli/policypublish` (трек `semantic-ensemble`), `adapter/secondary/ml` (bearer-токен в каждом запросе, 401 как недоступность без текста токена, клиент без токена не создается), `config` (токен обязателен при включенном подборе, короткий и с пробелами отклоняются, форматирование настроек токены скрывает). В `TestSemanticMatchingOverHTTP` фиктивный ML требует токен и обслуживает обе модели; после публикации ансамбля и до backfill у всех записей нейтральное `Sem`, backfill добавляет векторы `whole` Qwen3 для шести карточек и потребности без повторного кодирования Giga и без векторов элементов Qwen3, после чего у всех записей `Sem` известен.
|
||||||
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
|
- Не проверено: качество ранжирования и точность объяснений на реальных данных, задержка на рабочем сервере, сборка образа ML на этой машине и запуск стенда с моделью. Внешний GitHub в тестах не вызывается.
|
||||||
|
|
||||||
## Будущая программная валидация
|
## Будущая программная валидация
|
||||||
|
|||||||
+13
-8
@@ -24,24 +24,28 @@ COPY ml/.python-version ml/pyproject.toml ml/uv.lock ./ml/
|
|||||||
COPY ml/src ./ml/src
|
COPY ml/src ./ml/src
|
||||||
RUN uv sync --project ml --python /usr/local/bin/python --locked --no-dev --no-editable
|
RUN uv sync --project ml --python /usr/local/bin/python --locked --no-dev --no-editable
|
||||||
|
|
||||||
# The model files are fetched once, at build time, from the pinned revision
|
# The model files are fetched once, at build time, from the pinned revisions
|
||||||
# and verified against the SHA-256 of the lock file. Only safetensors weights,
|
# and verified against the SHA-256 of the lock file. Only safetensors weights,
|
||||||
# configs, and the tokenizer are fetched: no remote code, no pickle weights.
|
# configs, and the tokenizer are fetched: no remote code, no pickle weights.
|
||||||
FROM base AS model
|
FROM base AS model
|
||||||
|
|
||||||
COPY ml/src/lincodex_ml/model_files.py /tmp/model_files.py
|
COPY ml/src/lincodex_ml/model_files.py /tmp/model_files.py
|
||||||
COPY ml/model/giga-embeddings-480m.lock.json /tmp/model.lock.json
|
COPY ml/model/giga-embeddings-480m.lock.json ml/model/qwen3-embedding-0.6b.lock.json /tmp/locks/
|
||||||
RUN python /tmp/model_files.py fetch --lock /tmp/model.lock.json --out /opt/lincodex/model \
|
RUN python /tmp/model_files.py fetch --lock /tmp/locks/giga-embeddings-480m.lock.json --out /opt/lincodex/models/giga-480m \
|
||||||
&& rm /tmp/model_files.py /tmp/model.lock.json
|
&& python /tmp/model_files.py fetch --lock /tmp/locks/qwen3-embedding-0.6b.lock.json --out /opt/lincodex/models/qwen3-0.6b \
|
||||||
|
&& rm -r /tmp/model_files.py /tmp/locks
|
||||||
|
|
||||||
FROM base
|
FROM base
|
||||||
|
|
||||||
ENV PATH="/opt/venv/bin:${PATH}" \
|
ENV PATH="/opt/venv/bin:${PATH}" \
|
||||||
PYTHONDONTWRITEBYTECODE=1 \
|
PYTHONDONTWRITEBYTECODE=1 \
|
||||||
PYTHONUNBUFFERED=1 \
|
PYTHONUNBUFFERED=1 \
|
||||||
ML_EMBEDDER=giga \
|
ML_EMBEDDER=giga,qwen3 \
|
||||||
ML_MODEL_DIR=/opt/lincodex/model \
|
ML_GIGA_MODEL_DIR=/opt/lincodex/models/giga-480m \
|
||||||
|
ML_QWEN3_MODEL_DIR=/opt/lincodex/models/qwen3-0.6b \
|
||||||
ML_TORCH_THREADS=4 \
|
ML_TORCH_THREADS=4 \
|
||||||
|
ML_LISTEN_HOST=0.0.0.0 \
|
||||||
|
ML_LISTEN_PORT=8000 \
|
||||||
HF_HUB_OFFLINE=1 \
|
HF_HUB_OFFLINE=1 \
|
||||||
TRANSFORMERS_OFFLINE=1 \
|
TRANSFORMERS_OFFLINE=1 \
|
||||||
HF_HUB_DISABLE_TELEMETRY=1
|
HF_HUB_DISABLE_TELEMETRY=1
|
||||||
@@ -55,7 +59,7 @@ RUN python -m pip uninstall --yes pip \
|
|||||||
|
|
||||||
COPY --from=build --chown=lincodex:lincodex /opt/venv /opt/venv
|
COPY --from=build --chown=lincodex:lincodex /opt/venv /opt/venv
|
||||||
# Read-only for the service user: root owns the weights.
|
# Read-only for the service user: root owns the weights.
|
||||||
COPY --from=model /opt/lincodex/model /opt/lincodex/model
|
COPY --from=model /opt/lincodex/models /opt/lincodex/models
|
||||||
|
|
||||||
USER 10001:10001
|
USER 10001:10001
|
||||||
EXPOSE 8000
|
EXPOSE 8000
|
||||||
@@ -63,4 +67,5 @@ EXPOSE 8000
|
|||||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||||
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
|
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2)"]
|
||||||
|
|
||||||
CMD ["uvicorn", "lincodex_ml.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
# The entry point refuses to listen on 0.0.0.0 without ML_SERVICE_TOKEN.
|
||||||
|
CMD ["python", "-m", "lincodex_ml.serve"]
|
||||||
+24
-10
@@ -1,10 +1,15 @@
|
|||||||
.DEFAULT_GOAL := help
|
.DEFAULT_GOAL := help
|
||||||
UV ?= uv
|
UV ?= uv
|
||||||
API_PREPARED ?= 0
|
API_PREPARED ?= 0
|
||||||
# Local directory of the pinned model weights for test-model and run.
|
# Local directories of the pinned model weights for test-model and run.
|
||||||
ML_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/giga-480m
|
ML_GIGA_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/giga-480m
|
||||||
MODEL_LOCK := model/giga-embeddings-480m.lock.json
|
ML_QWEN3_MODEL_DIR ?= $(HOME)/.cache/lincodex-ml/qwen3-0.6b
|
||||||
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract test-model model-fetch check verify
|
GIGA_LOCK := model/giga-embeddings-480m.lock.json
|
||||||
|
QWEN3_LOCK := model/qwen3-embedding-0.6b.lock.json
|
||||||
|
# Where cuda-requirements writes the runtime requirements of a CUDA host.
|
||||||
|
CUDA_REQUIREMENTS ?= dist/requirements-cuda.txt
|
||||||
|
CUDA_TORCH_LOCAL ?= cu128
|
||||||
|
.PHONY: help install generate check-generated check-pydantic-compat build run fmt fmt-check lint lint-fix typecheck test test-contract test-model model-fetch cuda-requirements check verify
|
||||||
|
|
||||||
help: ## Show available ML service commands.
|
help: ## Show available ML service commands.
|
||||||
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "%-14s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
|
||||||
@@ -28,8 +33,8 @@ check-pydantic-compat: ## Generate Pydantic models from the OpenAPI 3.2 compatib
|
|||||||
build: ## Build the service wheel.
|
build: ## Build the service wheel.
|
||||||
$(UV) build
|
$(UV) build
|
||||||
|
|
||||||
run: ## Run the operational API on port 8000.
|
run: ## Run the operational API on 127.0.0.1:8000 (ML_LISTEN_HOST and ML_LISTEN_PORT change it).
|
||||||
$(UV) run uvicorn lincodex_ml.main:app --host 0.0.0.0 --port 8000
|
$(UV) run python -m lincodex_ml.serve
|
||||||
|
|
||||||
fmt: ## Format Python source.
|
fmt: ## Format Python source.
|
||||||
$(UV) run ruff format src tests scripts
|
$(UV) run ruff format src tests scripts
|
||||||
@@ -52,11 +57,20 @@ test: ## Run service tests.
|
|||||||
test-contract: ## Check implementation against the shared OpenAPI contract.
|
test-contract: ## Check implementation against the shared OpenAPI contract.
|
||||||
$(UV) run pytest tests/test_contract.py
|
$(UV) run pytest tests/test_contract.py
|
||||||
|
|
||||||
model-fetch: ## Download the pinned model files into ML_MODEL_DIR and verify their SHA-256 (about 1 GB).
|
model-fetch: ## Download the pinned files of both models into ML_GIGA_MODEL_DIR and ML_QWEN3_MODEL_DIR and verify their SHA-256 (about 2.2 GB).
|
||||||
$(UV) run python -m lincodex_ml.model_files fetch --lock $(MODEL_LOCK) --out "$(ML_MODEL_DIR)"
|
$(UV) run python -m lincodex_ml.model_files fetch --lock $(GIGA_LOCK) --out "$(ML_GIGA_MODEL_DIR)"
|
||||||
|
$(UV) run python -m lincodex_ml.model_files fetch --lock $(QWEN3_LOCK) --out "$(ML_QWEN3_MODEL_DIR)"
|
||||||
|
|
||||||
test-model: ## Run the slow parity test of the real model against the research vectors (needs model-fetch).
|
test-model: ## Run the slow parity tests of both real models against the research vectors (needs model-fetch; ML_TEST_DEVICE=cuda on a GPU).
|
||||||
ML_MODEL_DIR="$(ML_MODEL_DIR)" $(UV) run pytest -m slow -p no:cacheprovider tests/test_giga_model.py
|
ML_GIGA_MODEL_DIR="$(ML_GIGA_MODEL_DIR)" ML_QWEN3_MODEL_DIR="$(ML_QWEN3_MODEL_DIR)" $(UV) run pytest -m slow -p no:cacheprovider tests/test_giga_model.py tests/test_qwen3_model.py
|
||||||
|
|
||||||
|
cuda-requirements: ## Write the locked runtime requirements with the CUDA build of the locked torch version to CUDA_REQUIREMENTS (for a GPU host).
|
||||||
|
@mkdir -p "$(dir $(CUDA_REQUIREMENTS))"
|
||||||
|
@version=$$($(UV) export --frozen --no-dev --no-hashes --no-emit-project --format requirements.txt | sed -n 's/^torch==\([0-9.]*\).*/\1/p' | head -n 1) && \
|
||||||
|
test -n "$$version" && \
|
||||||
|
$(UV) export --frozen --no-dev --no-hashes --no-emit-project --format requirements.txt | grep -v '^torch==' > "$(CUDA_REQUIREMENTS)" && \
|
||||||
|
printf 'torch==%s+%s\n' "$$version" "$(CUDA_TORCH_LOCAL)" >> "$(CUDA_REQUIREMENTS)" && \
|
||||||
|
printf 'wrote %s (torch %s+%s)\n' "$(CUDA_REQUIREMENTS)" "$$version" "$(CUDA_TORCH_LOCAL)"
|
||||||
|
|
||||||
check: ## Run formatting, lint, type, tests, and package build.
|
check: ## Run formatting, lint, type, tests, and package build.
|
||||||
$(MAKE) fmt-check lint typecheck test build
|
$(MAKE) fmt-check lint typecheck test build
|
||||||
|
|||||||
+4
-4
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
[Русский](README.md) | English
|
[Русский](README.md) | English
|
||||||
|
|
||||||
A separate Python service using FastAPI. It serves `POST /v1/embeddings` with the pinned Giga-Embeddings-instruct-480M model on CPU for semantic matching (the optional `model` field names the model; a request for a model the service has not loaded gets 400), plus `/healthz`, `/readyz`, and metrics. `/readyz` returns 503 until the model is loaded and warmed up, and always without a model (`ML_EMBEDDER=none`, the default outside the image). The model files are fetched at image build time by `model/giga-embeddings-480m.lock.json` and verified by SHA-256; see [deployment](../docs/en/DEPLOY.md#separate-ml-compose-project).
|
A separate Python service using FastAPI. It serves `POST /v1/embeddings` with the pinned Giga-Embeddings-instruct-480M and Qwen3-Embedding-0.6B models for semantic matching (the `ML_EMBEDDER` list; the optional `model` field selects the model, and a request for a model the service has not loaded gets 400), plus `/healthz`, `/readyz`, and metrics. It runs on CPU or CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); a lack of device memory gives 503, not a crash. Every route except `/healthz` and `/readyz` requires a bearer token (`ML_SERVICE_TOKEN` or `ML_SERVICE_TOKEN_FILE`); without a token the service answers loopback callers only, and `python -m lincodex_ml.serve` does not listen on a non-loopback address. `/readyz` returns 503 until the models are loaded and warmed up, and always without a model (`ML_EMBEDDER=none`, the default outside the image). The model files are pinned by the lock files `model/*.lock.json` and verified by SHA-256; see [deployment](../docs/en/DEPLOY.md#separate-ml-compose-project) and [the GPU host](../docs/en/DEPLOY.md#ml-service-on-a-gpu-host).
|
||||||
|
|
||||||
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
|
- `src/lincodex_ml/` contains the application, HTTP routes, and infrastructure code.
|
||||||
- `codegen/` configures Pydantic model generation from `api/ml/`.
|
- `codegen/` configures Pydantic model generation from `api/ml/`.
|
||||||
- `tests/` checks service health, the embedding contract with a fake encoder, the model lock, and (marked `slow`, `make -C ml test-model`) the real model against the study vectors.
|
- `tests/` checks service health, the embedding contract with a fake encoder, several models, the token, a lack of device memory, the model locks, and (marked `slow`, `make -C ml test-model`) the real models against the study vectors.
|
||||||
- `model/` pins the model revision and the SHA-256 of its files.
|
- `model/` pins the model revisions and the SHA-256 of their files.
|
||||||
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
|
- `scripts/` checks Pydantic models generated from the OpenAPI 3.2 fixture.
|
||||||
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
|
- `pyproject.toml` and `uv.lock` define dependencies and Python tool settings.
|
||||||
|
|
||||||
From the repository root, `make -C ml check` runs checks and `make -C ml run` starts the service locally. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
|
From the repository root, `make -C ml check` runs checks, `make -C ml run` starts the service locally on 127.0.0.1:8000, and `make -C ml cuda-requirements` writes the dependency list of a GPU host. To use its separate Compose project, run `make -C deploy ml-up` after preparing `.env`.
|
||||||
|
|
||||||
See [development](../docs/en/DEVELOPMENT.md) and [deployment](../docs/en/DEPLOY.md).
|
See [development](../docs/en/DEVELOPMENT.md) and [deployment](../docs/en/DEPLOY.md).
|
||||||
+4
-4
@@ -2,15 +2,15 @@
|
|||||||
|
|
||||||
Русский | [English](README.en.md)
|
Русский | [English](README.en.md)
|
||||||
|
|
||||||
Отдельный Python-сервис на FastAPI. Он отдает `POST /v1/embeddings` с закрепленной моделью Giga-Embeddings-instruct-480M на CPU для семантического подбора (необязательное поле `model` называет модель; запрос модели, которую сервис не загрузил, получает 400), а также `/healthz`, `/readyz` и метрики. `/readyz` отвечает 503, пока модель не загружена и не прогрета, и всегда без модели (`ML_EMBEDDER=none`, значение по умолчанию вне образа). Файлы модели скачиваются при сборке образа по `model/giga-embeddings-480m.lock.json` и проверяются по SHA-256; см. [развертывание](../docs/ru/DEPLOY.md#отдельный-ml-compose).
|
Отдельный Python-сервис на FastAPI. Он отдает `POST /v1/embeddings` с закрепленными моделями Giga-Embeddings-instruct-480M и Qwen3-Embedding-0.6B для семантического подбора (список `ML_EMBEDDER`, необязательное поле `model` выбирает модель; запрос модели, которую сервис не загрузил, получает 400), а также `/healthz`, `/readyz` и метрики. Работает на CPU или CUDA (`ML_DEVICE`, `ML_DTYPE`, `ML_CUDA_MEMORY_LIMIT_MB`); нехватка видеопамяти дает 503, а не падение процесса. Все маршруты, кроме `/healthz` и `/readyz`, требуют bearer-токен (`ML_SERVICE_TOKEN` или `ML_SERVICE_TOKEN_FILE`); без токена сервис отвечает только loopback-клиентам, а `python -m lincodex_ml.serve` не слушает не-loopback адрес. `/readyz` отвечает 503, пока модели не загружены и не прогреты, и всегда без моделей (`ML_EMBEDDER=none`, значение по умолчанию вне образа). Файлы моделей закреплены lock-файлами `model/*.lock.json` и проверяются по SHA-256; см. [развертывание](../docs/ru/DEPLOY.md#отдельный-ml-compose) и [GPU-хост](../docs/ru/DEPLOY.md#ml-сервис-на-gpu-хосте).
|
||||||
|
|
||||||
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
|
- `src/lincodex_ml/` - приложение, HTTP-маршруты и инфраструктурный код.
|
||||||
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
|
- `codegen/` - настройки генерации моделей Pydantic из `api/ml/`.
|
||||||
- `tests/` - проверки состояния сервиса, контракта эмбеддингов на фиктивном кодировщике, lock-файла модели и (маркер `slow`, `make -C ml test-model`) реальной модели против векторов исследования.
|
- `tests/` - проверки состояния сервиса, контракта эмбеддингов на фиктивном кодировщике, нескольких моделей, токена, нехватки видеопамяти, lock-файлов и (маркер `slow`, `make -C ml test-model`) реальных моделей против векторов исследования.
|
||||||
- `model/` - закрепленная ревизия модели и SHA-256 ее файлов.
|
- `model/` - закрепленные ревизии моделей и SHA-256 их файлов.
|
||||||
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
|
- `scripts/` - проверка Pydantic-моделей, сгенерированных из фикстуры OpenAPI 3.2.
|
||||||
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
|
- `pyproject.toml` и `uv.lock` - зависимости и настройки Python-инструментов.
|
||||||
|
|
||||||
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
|
Из корня: `make -C ml check` запускает проверки, `make -C ml run` - сервис локально на 127.0.0.1:8000, `make -C ml cuda-requirements` - список зависимостей для GPU-хоста. Для запуска через отдельный Compose используйте `make -C deploy ml-up` после подготовки `.env`.
|
||||||
|
|
||||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md) и [развертывание](../docs/ru/DEPLOY.md).
|
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md) и [развертывание](../docs/ru/DEPLOY.md).
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
{
|
||||||
|
"id": "Qwen/Qwen3-Embedding-0.6B",
|
||||||
|
"revision": "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3",
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"source": "https://huggingface.co",
|
||||||
|
"note": "Only these files are fetched. The checkpoint is a stock Qwen3 model that lincodex_ml.inference.qwen3 loads with the pinned transformers release; the repository has no remote code and no pickle (.bin) weight file. The sentence-transformers files pin the query prompt and the last-token pooling that the service reproduces.",
|
||||||
|
"files": {
|
||||||
|
"1_Pooling/config.json": {
|
||||||
|
"size": 313,
|
||||||
|
"sha256": "37bf193fa101f19101bfad9c31d3eb0f786e247b7b1e5cb7f007d730eed1ddbd"
|
||||||
|
},
|
||||||
|
"config.json": {
|
||||||
|
"size": 727,
|
||||||
|
"sha256": "b5bf1f51fc45be473a54718cef92448d90a1be001bf9b9a44b8c7f10a19feaa9"
|
||||||
|
},
|
||||||
|
"config_sentence_transformers.json": {
|
||||||
|
"size": 215,
|
||||||
|
"sha256": "10667c72ddb772627bf1780cb7f86af8e2ae0032b8c243c731172064105c6961"
|
||||||
|
},
|
||||||
|
"model.safetensors": {
|
||||||
|
"size": 1191586416,
|
||||||
|
"sha256": "0437e45c94563b09e13cb7a64478fc406947a93cb34a7e05870fc8dcd48e23fd"
|
||||||
|
},
|
||||||
|
"modules.json": {
|
||||||
|
"size": 349,
|
||||||
|
"sha256": "84e40c8e006c9b1d6c122e02cba9b02458120b5fb0c87b746c41e0207cf642cf"
|
||||||
|
},
|
||||||
|
"tokenizer.json": {
|
||||||
|
"size": 11423705,
|
||||||
|
"sha256": "def76fb086971c7867b829c23a26261e38d9d74e02139253b38aeb9df8b4b50a"
|
||||||
|
},
|
||||||
|
"tokenizer_config.json": {
|
||||||
|
"size": 9706,
|
||||||
|
"sha256": "253153d0738ceb4c668d2eff957714dd2bea0b56de772a9fdccd96cbf517e6a0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Bearer token check of every route except the health probes.
|
||||||
|
|
||||||
|
The service is internal: only the Go backend calls it. With a configured
|
||||||
|
token every request outside /healthz and /readyz must carry
|
||||||
|
`Authorization: Bearer <token>`; the comparison takes constant time and the
|
||||||
|
token never reaches a log or a response. Without a token the service answers
|
||||||
|
only peers on the loopback interface, so a service that is reachable from the
|
||||||
|
network can never run open by accident (the serve entry point also refuses to
|
||||||
|
listen on a non-loopback address without a token).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from fastapi import status
|
||||||
|
from starlette.requests import Request
|
||||||
|
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||||
|
|
||||||
|
from lincodex_ml.api.problems import problem_for_status
|
||||||
|
from lincodex_ml.config import ServiceToken, is_loopback_host
|
||||||
|
|
||||||
|
# Probes stay open: they carry no data and the orchestrator calls them
|
||||||
|
# without credentials.
|
||||||
|
PUBLIC_PATHS: Final = frozenset({"/healthz", "/readyz"})
|
||||||
|
_SCHEME: Final = "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
class BearerAuthMiddleware:
|
||||||
|
def __init__(self, app: ASGIApp, token: ServiceToken | None) -> None:
|
||||||
|
self._app = app
|
||||||
|
self._expected = token.reveal().encode() if token is not None else None
|
||||||
|
|
||||||
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||||
|
if scope["type"] != "http" or scope.get("path") in PUBLIC_PATHS:
|
||||||
|
await self._app(scope, receive, send)
|
||||||
|
return
|
||||||
|
if self._allowed(scope):
|
||||||
|
await self._app(scope, receive, send)
|
||||||
|
return
|
||||||
|
request = Request(scope)
|
||||||
|
response = problem_for_status(
|
||||||
|
request, status.HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": "Bearer"}
|
||||||
|
)
|
||||||
|
await response(scope, receive, send)
|
||||||
|
|
||||||
|
def _allowed(self, scope: Scope) -> bool:
|
||||||
|
if self._expected is None:
|
||||||
|
client = scope.get("client")
|
||||||
|
return client is not None and is_loopback_host(str(client[0]))
|
||||||
|
presented = b""
|
||||||
|
for name, value in scope.get("headers", []):
|
||||||
|
if name == b"authorization":
|
||||||
|
scheme, _, credentials = value.partition(b" ")
|
||||||
|
if scheme.decode("latin-1").lower() == _SCHEME:
|
||||||
|
presented = credentials.strip()
|
||||||
|
break
|
||||||
|
# compare_digest takes the same time whatever prefix matches; an
|
||||||
|
# empty or missing token is compared too, so its absence is not
|
||||||
|
# faster to detect than a wrong value.
|
||||||
|
return hmac.compare_digest(presented, self._expected) and presented != b""
|
||||||
@@ -17,7 +17,12 @@ from lincodex_ml.api.models import (
|
|||||||
)
|
)
|
||||||
from lincodex_ml.api.problems import ServiceUnavailableError
|
from lincodex_ml.api.problems import ServiceUnavailableError
|
||||||
from lincodex_ml.inference.embedder import InputKind
|
from lincodex_ml.inference.embedder import InputKind
|
||||||
from lincodex_ml.inference.runtime import EmbeddingRuntime, NotReadyError
|
from lincodex_ml.inference.runtime import (
|
||||||
|
CapacityError,
|
||||||
|
EmbeddingRuntime,
|
||||||
|
NotReadyError,
|
||||||
|
UnknownModelError,
|
||||||
|
)
|
||||||
|
|
||||||
router = APIRouter(tags=["inference"])
|
router = APIRouter(tags=["inference"])
|
||||||
|
|
||||||
@@ -32,7 +37,7 @@ def get_runtime(request: Request) -> EmbeddingRuntime:
|
|||||||
operation_id="CreateMLEmbeddings",
|
operation_id="CreateMLEmbeddings",
|
||||||
response_model=EmbeddingResponse,
|
response_model=EmbeddingResponse,
|
||||||
status_code=status.HTTP_200_OK,
|
status_code=status.HTTP_200_OK,
|
||||||
summary="Encode texts into normalized vectors with the pinned embedding model.",
|
summary="Encode texts into normalized vectors with a pinned embedding model.",
|
||||||
)
|
)
|
||||||
async def create_embeddings(
|
async def create_embeddings(
|
||||||
payload: EmbeddingRequest,
|
payload: EmbeddingRequest,
|
||||||
@@ -41,14 +46,12 @@ async def create_embeddings(
|
|||||||
kind = InputKind(payload.kind.root)
|
kind = InputKind(payload.kind.root)
|
||||||
texts = [text.root for text in payload.texts]
|
texts = [text.root for text in payload.texts]
|
||||||
try:
|
try:
|
||||||
# The service loads one model today; the field keeps the contract ready
|
info, vectors = await run_in_threadpool(runtime.encode, kind, texts, payload.model)
|
||||||
# for several (an ensemble), and a model it does not serve is refused.
|
except UnknownModelError as error:
|
||||||
if payload.model is not None and payload.model != runtime.info().model_id:
|
raise RequestValidationError(
|
||||||
raise RequestValidationError(
|
[{"loc": ("body", "model"), "type": "value_error", "msg": "model not served"}]
|
||||||
[{"loc": ("body", "model"), "type": "value_error", "msg": "model not served"}]
|
) from error
|
||||||
)
|
except (NotReadyError, CapacityError) as error:
|
||||||
info, vectors = await run_in_threadpool(runtime.encode, kind, texts)
|
|
||||||
except NotReadyError as error:
|
|
||||||
raise ServiceUnavailableError from error
|
raise ServiceUnavailableError from error
|
||||||
return EmbeddingResponse(
|
return EmbeddingResponse(
|
||||||
model=EmbeddingModel(
|
model=EmbeddingModel(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from fastapi import APIRouter, Request, Response, status
|
from fastapi import APIRouter, Request, Response, status
|
||||||
|
|
||||||
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
|
from lincodex_ml.api.models import MLHealthResponse, MLReadinessResponse
|
||||||
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
|
from lincodex_ml.inference.runtime import EmbeddingRuntime
|
||||||
|
|
||||||
router = APIRouter(tags=["health"])
|
router = APIRouter(tags=["health"])
|
||||||
|
|
||||||
@@ -30,10 +30,11 @@ async def get_healthz() -> MLHealthResponse:
|
|||||||
summary="Check whether an inference runtime is available.",
|
summary="Check whether an inference runtime is available.",
|
||||||
)
|
)
|
||||||
async def get_readyz(request: Request, response: Response) -> MLReadinessResponse:
|
async def get_readyz(request: Request, response: Response) -> MLReadinessResponse:
|
||||||
# Ready only after the model is loaded and a warm-up encode finished;
|
# Ready only after every model is loaded and a warm-up encode finished;
|
||||||
# a disabled or failed runtime stays not ready.
|
# a disabled or failed runtime stays not ready, and so does one that ran
|
||||||
|
# out of device memory during the last cool-down.
|
||||||
runtime: EmbeddingRuntime = request.app.state.embedding_runtime
|
runtime: EmbeddingRuntime = request.app.state.embedding_runtime
|
||||||
if runtime.state is RuntimeState.READY:
|
if runtime.ready():
|
||||||
return MLReadinessResponse(status="ready")
|
return MLReadinessResponse(status="ready")
|
||||||
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
|
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
|
||||||
return MLReadinessResponse(status="not_ready")
|
return MLReadinessResponse(status="not_ready")
|
||||||
@@ -198,7 +198,7 @@ class EmbeddingRequest(BaseModel):
|
|||||||
model: Annotated[
|
model: Annotated[
|
||||||
str | None,
|
str | None,
|
||||||
Field(
|
Field(
|
||||||
description="Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.",
|
description="Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of the service, the first one it is configured with. A service may load several models, for example the members of an ensemble; a model it does not serve answers 400 validation_failed with the pointer `/model`.",
|
||||||
max_length=200,
|
max_length=200,
|
||||||
min_length=1,
|
min_length=1,
|
||||||
pattern="^[A-Za-z0-9._/-]+$",
|
pattern="^[A-Za-z0-9._/-]+$",
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ _STATUS_DEFINITIONS: Final[Mapping[int, _Definition]] = {
|
|||||||
ProblemCode("service_unavailable"),
|
ProblemCode("service_unavailable"),
|
||||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||||
"Service unavailable",
|
"Service unavailable",
|
||||||
"The model is not ready yet. Retry later.",
|
"The model is not ready or has no free capacity now. Retry later.",
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
# Seconds a client waits before it asks a service that is still loading.
|
# Seconds a client waits before it asks a service that is still loading.
|
||||||
@@ -185,6 +185,13 @@ class BodyLimitMiddleware:
|
|||||||
await self._app(scope, limited_receive, send)
|
await self._app(scope, limited_receive, send)
|
||||||
|
|
||||||
|
|
||||||
|
def problem_for_status(
|
||||||
|
request: Request, status_code: int, headers: Mapping[str, str] | None = None
|
||||||
|
) -> JSONResponse:
|
||||||
|
"""The problem response of an HTTP status, for middleware outside the routes."""
|
||||||
|
return _problem_response(request, _definition_for_status(status_code), headers=headers)
|
||||||
|
|
||||||
|
|
||||||
def _too_large(request: Request) -> JSONResponse:
|
def _too_large(request: Request) -> JSONResponse:
|
||||||
return _problem_response(request, _STATUS_DEFINITIONS[status.HTTP_413_CONTENT_TOO_LARGE])
|
return _problem_response(request, _STATUS_DEFINITIONS[status.HTTP_413_CONTENT_TOO_LARGE])
|
||||||
|
|
||||||
|
|||||||
+187
-18
@@ -2,14 +2,17 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
from collections.abc import Mapping
|
from collections.abc import Mapping
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass, field
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Final
|
from typing import Final
|
||||||
|
|
||||||
DEFAULT_MODEL_DIR: Final = Path("/opt/lincodex/model")
|
from lincodex_ml.model_files import LOCK_FILE_NAME
|
||||||
|
|
||||||
# Four intra-op threads meet the latency targets of the research CPU benchmark
|
# Four intra-op threads meet the latency targets of the research CPU benchmark
|
||||||
# (profile p95 352 ms, search over 100k vectors p95 591 ms) for Giga-480M.
|
# (profile p95 352 ms, search over 100k vectors p95 591 ms) for Giga-480M.
|
||||||
DEFAULT_TORCH_THREADS: Final = 4
|
DEFAULT_TORCH_THREADS: Final = 4
|
||||||
@@ -18,39 +21,115 @@ DEFAULT_TORCH_THREADS: Final = 4
|
|||||||
DEFAULT_MICRO_BATCH: Final = 1
|
DEFAULT_MICRO_BATCH: Final = 1
|
||||||
DEFAULT_MAX_TOKENS: Final = 1024
|
DEFAULT_MAX_TOKENS: Final = 1024
|
||||||
DEFAULT_MAX_BODY_BYTES: Final = 2 * 1024 * 1024
|
DEFAULT_MAX_BODY_BYTES: Final = 2 * 1024 * 1024
|
||||||
|
DEFAULT_LISTEN_HOST: Final = "127.0.0.1"
|
||||||
|
DEFAULT_LISTEN_PORT: Final = 8000
|
||||||
|
# The minimum length of the service token: 32 random characters carry far
|
||||||
|
# more entropy than an online guess can reach.
|
||||||
|
MIN_TOKEN_LENGTH: Final = 32
|
||||||
|
_MAX_TOKEN_LENGTH: Final = 512
|
||||||
_MAX_TORCH_THREADS: Final = 64
|
_MAX_TORCH_THREADS: Final = 64
|
||||||
_MAX_MICRO_BATCH: Final = 32
|
_MAX_MICRO_BATCH: Final = 32
|
||||||
_MAX_TOKENS_LIMIT: Final = 8192
|
_MAX_TOKENS_LIMIT: Final = 8192
|
||||||
|
_MAX_CUDA_MEMORY_MB: Final = 1024 * 1024
|
||||||
|
_TOKEN_PATTERN: Final = re.compile(r"^[\x21-\x7e]+$")
|
||||||
|
_DEVICE_PATTERN: Final = re.compile(r"^(cpu|cuda|cuda:[0-9]{1,2})$")
|
||||||
|
|
||||||
|
|
||||||
class EmbedderKind(StrEnum):
|
class EmbedderKind(StrEnum):
|
||||||
"""Which encoder the service loads."""
|
"""An encoder the service can load."""
|
||||||
|
|
||||||
# The pinned Giga-Embeddings model from the image.
|
# Giga-Embeddings-instruct-480M at the pinned revision.
|
||||||
GIGA = "giga"
|
GIGA = "giga"
|
||||||
|
# Qwen3-Embedding-0.6B at the pinned revision.
|
||||||
|
QWEN3 = "qwen3"
|
||||||
# A deterministic hash encoder for tests and stands without the model. It
|
# A deterministic hash encoder for tests and stands without the model. It
|
||||||
# is never a model result and reports its own model id.
|
# is never a model result and reports its own model id.
|
||||||
FAKE = "fake"
|
FAKE = "fake"
|
||||||
# No encoder: the service stays not ready and refuses inference.
|
|
||||||
NONE = "none"
|
|
||||||
|
# Where the image keeps the weights of each model; a host without the image
|
||||||
|
# points the per-model directory variables elsewhere.
|
||||||
|
DEFAULT_MODEL_DIRS: Final[Mapping[EmbedderKind, Path]] = {
|
||||||
|
EmbedderKind.GIGA: Path("/opt/lincodex/models/giga-480m"),
|
||||||
|
EmbedderKind.QWEN3: Path("/opt/lincodex/models/qwen3-0.6b"),
|
||||||
|
}
|
||||||
|
_MODEL_ENV_PREFIX: Final[Mapping[EmbedderKind, str]] = {
|
||||||
|
EmbedderKind.GIGA: "ML_GIGA",
|
||||||
|
EmbedderKind.QWEN3: "ML_QWEN3",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class DType(StrEnum):
|
||||||
|
"""Precision of the weights and activations of a real model."""
|
||||||
|
|
||||||
|
FLOAT32 = "float32"
|
||||||
|
FLOAT16 = "float16"
|
||||||
|
BFLOAT16 = "bfloat16"
|
||||||
|
|
||||||
|
|
||||||
class SettingsError(ValueError):
|
class SettingsError(ValueError):
|
||||||
"""An environment value is invalid."""
|
"""An environment value is invalid."""
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceToken:
|
||||||
|
"""The shared bearer token. Its value never appears in a repr or a log."""
|
||||||
|
|
||||||
|
__slots__ = ("_value",)
|
||||||
|
|
||||||
|
def __init__(self, value: str) -> None:
|
||||||
|
self._value = value
|
||||||
|
|
||||||
|
def reveal(self) -> str:
|
||||||
|
return self._value
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return "ServiceToken([redacted])"
|
||||||
|
|
||||||
|
__str__ = __repr__
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class ModelLocation:
|
||||||
|
"""The weight directory of one model and the lock file that pins it."""
|
||||||
|
|
||||||
|
directory: Path
|
||||||
|
lock: Path
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class Settings:
|
class Settings:
|
||||||
embedder: EmbedderKind
|
# Encoders in load order; the first one serves requests without a model
|
||||||
model_dir: Path
|
# id. Empty means no encoder: the service stays not ready.
|
||||||
|
embedders: tuple[EmbedderKind, ...]
|
||||||
|
model_locations: Mapping[EmbedderKind, ModelLocation]
|
||||||
torch_threads: int
|
torch_threads: int
|
||||||
micro_batch: int
|
micro_batch: int
|
||||||
max_tokens: int
|
max_tokens: int
|
||||||
verify_weights: bool
|
verify_weights: bool
|
||||||
max_body_bytes: int
|
max_body_bytes: int
|
||||||
|
device: str = "cpu"
|
||||||
|
dtype: DType = DType.FLOAT32
|
||||||
|
# The CUDA allocator limit of the process in MiB; 0 means no limit.
|
||||||
|
cuda_memory_limit_mb: int = 0
|
||||||
|
token: ServiceToken | None = field(default=None, repr=False)
|
||||||
|
listen_host: str = DEFAULT_LISTEN_HOST
|
||||||
|
listen_port: int = DEFAULT_LISTEN_PORT
|
||||||
|
# Exit the process when a model fails to load for any reason other than
|
||||||
|
# a lack of device memory, so a supervisor such as systemd restarts it.
|
||||||
|
exit_on_load_failure: bool = False
|
||||||
|
|
||||||
|
def location(self, kind: EmbedderKind) -> ModelLocation:
|
||||||
|
return self.model_locations.get(kind) or _default_location(kind)
|
||||||
|
|
||||||
|
|
||||||
def _integer(environ: Mapping[str, str], name: str, default: int, maximum: int) -> int:
|
def _default_location(kind: EmbedderKind) -> ModelLocation:
|
||||||
|
directory = DEFAULT_MODEL_DIRS.get(kind, Path("/nonexistent"))
|
||||||
|
return ModelLocation(directory=directory, lock=directory / LOCK_FILE_NAME)
|
||||||
|
|
||||||
|
|
||||||
|
def _integer(
|
||||||
|
environ: Mapping[str, str], name: str, default: int, maximum: int, minimum: int = 1
|
||||||
|
) -> int:
|
||||||
raw = environ.get(name, "").strip()
|
raw = environ.get(name, "").strip()
|
||||||
if raw == "":
|
if raw == "":
|
||||||
return default
|
return default
|
||||||
@@ -58,8 +137,8 @@ def _integer(environ: Mapping[str, str], name: str, default: int, maximum: int)
|
|||||||
value = int(raw)
|
value = int(raw)
|
||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
raise SettingsError(f"{name} must be an integer") from error
|
raise SettingsError(f"{name} must be an integer") from error
|
||||||
if value < 1 or value > maximum:
|
if value < minimum or value > maximum:
|
||||||
raise SettingsError(f"{name} must be between 1 and {maximum}")
|
raise SettingsError(f"{name} must be between {minimum} and {maximum}")
|
||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
@@ -74,16 +153,99 @@ def _boolean(environ: Mapping[str, str], name: str, default: bool) -> bool:
|
|||||||
raise SettingsError(f"{name} must be true or false")
|
raise SettingsError(f"{name} must be true or false")
|
||||||
|
|
||||||
|
|
||||||
|
def _embedders(environ: Mapping[str, str]) -> tuple[EmbedderKind, ...]:
|
||||||
|
raw = environ.get("ML_EMBEDDER", "").strip()
|
||||||
|
if raw in {"", "none"}:
|
||||||
|
return ()
|
||||||
|
kinds: list[EmbedderKind] = []
|
||||||
|
for part in raw.split(","):
|
||||||
|
try:
|
||||||
|
kind = EmbedderKind(part.strip())
|
||||||
|
except ValueError as error:
|
||||||
|
raise SettingsError(
|
||||||
|
"ML_EMBEDDER must be none, fake, or a comma list of giga and qwen3"
|
||||||
|
) from error
|
||||||
|
if kind in kinds:
|
||||||
|
raise SettingsError("ML_EMBEDDER names a model twice")
|
||||||
|
kinds.append(kind)
|
||||||
|
if EmbedderKind.FAKE in kinds and len(kinds) > 1:
|
||||||
|
raise SettingsError("ML_EMBEDDER fake cannot be combined with a real model")
|
||||||
|
return tuple(kinds)
|
||||||
|
|
||||||
|
|
||||||
|
def _locations(environ: Mapping[str, str]) -> dict[EmbedderKind, ModelLocation]:
|
||||||
|
locations: dict[EmbedderKind, ModelLocation] = {}
|
||||||
|
for kind, prefix in _MODEL_ENV_PREFIX.items():
|
||||||
|
raw_dir = environ.get(f"{prefix}_MODEL_DIR", "").strip()
|
||||||
|
directory = Path(raw_dir) if raw_dir else DEFAULT_MODEL_DIRS[kind]
|
||||||
|
raw_lock = environ.get(f"{prefix}_MODEL_LOCK", "").strip()
|
||||||
|
locations[kind] = ModelLocation(
|
||||||
|
directory=directory, lock=Path(raw_lock) if raw_lock else directory / LOCK_FILE_NAME
|
||||||
|
)
|
||||||
|
return locations
|
||||||
|
|
||||||
|
|
||||||
|
def _device(environ: Mapping[str, str]) -> str:
|
||||||
|
raw = environ.get("ML_DEVICE", "").strip().lower() or "cpu"
|
||||||
|
if not _DEVICE_PATTERN.fullmatch(raw):
|
||||||
|
raise SettingsError("ML_DEVICE must be cpu, cuda, or cuda:<index>")
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def _dtype(environ: Mapping[str, str], device: str) -> DType:
|
||||||
|
raw = environ.get("ML_DTYPE", "").strip().lower() or DType.FLOAT32.value
|
||||||
|
try:
|
||||||
|
dtype = DType(raw)
|
||||||
|
except ValueError as error:
|
||||||
|
raise SettingsError("ML_DTYPE must be float32, float16, or bfloat16") from error
|
||||||
|
# Half precision on CPU is slower than float32 and was never validated.
|
||||||
|
if dtype is not DType.FLOAT32 and device == "cpu":
|
||||||
|
raise SettingsError("ML_DTYPE other than float32 needs ML_DEVICE=cuda")
|
||||||
|
return dtype
|
||||||
|
|
||||||
|
|
||||||
|
def _token(environ: Mapping[str, str]) -> ServiceToken | None:
|
||||||
|
inline = environ.get("ML_SERVICE_TOKEN", "")
|
||||||
|
path = environ.get("ML_SERVICE_TOKEN_FILE", "").strip()
|
||||||
|
if inline and path:
|
||||||
|
raise SettingsError("set ML_SERVICE_TOKEN or ML_SERVICE_TOKEN_FILE, not both")
|
||||||
|
if path:
|
||||||
|
try:
|
||||||
|
inline = Path(path).read_text(encoding="utf-8")
|
||||||
|
except (OSError, UnicodeDecodeError) as error:
|
||||||
|
raise SettingsError("ML_SERVICE_TOKEN_FILE cannot be read") from error
|
||||||
|
value = inline.strip()
|
||||||
|
if value == "":
|
||||||
|
return None
|
||||||
|
# The messages never quote the value.
|
||||||
|
if not _TOKEN_PATTERN.fullmatch(value) or len(value) > _MAX_TOKEN_LENGTH:
|
||||||
|
raise SettingsError("the service token must be printable ASCII without white space")
|
||||||
|
if len(value) < MIN_TOKEN_LENGTH:
|
||||||
|
raise SettingsError(f"the service token must have at least {MIN_TOKEN_LENGTH} characters")
|
||||||
|
return ServiceToken(value)
|
||||||
|
|
||||||
|
|
||||||
|
def is_loopback_host(host: str) -> bool:
|
||||||
|
"""Whether a listen or peer address can only be reached from this host."""
|
||||||
|
if host == "localhost":
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
return ipaddress.ip_address(host.strip("[]")).is_loopback
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def load_settings(environ: Mapping[str, str] | None = None) -> Settings:
|
def load_settings(environ: Mapping[str, str] | None = None) -> Settings:
|
||||||
source = os.environ if environ is None else environ
|
source = os.environ if environ is None else environ
|
||||||
raw_kind = source.get("ML_EMBEDDER", "").strip() or EmbedderKind.NONE.value
|
device = _device(source)
|
||||||
try:
|
cuda_memory_limit_mb = _integer(
|
||||||
kind = EmbedderKind(raw_kind)
|
source, "ML_CUDA_MEMORY_LIMIT_MB", 0, _MAX_CUDA_MEMORY_MB, minimum=0
|
||||||
except ValueError as error:
|
)
|
||||||
raise SettingsError("ML_EMBEDDER must be giga, fake, or none") from error
|
if cuda_memory_limit_mb and device == "cpu":
|
||||||
|
raise SettingsError("ML_CUDA_MEMORY_LIMIT_MB needs ML_DEVICE=cuda")
|
||||||
return Settings(
|
return Settings(
|
||||||
embedder=kind,
|
embedders=_embedders(source),
|
||||||
model_dir=Path(source.get("ML_MODEL_DIR", "").strip() or DEFAULT_MODEL_DIR),
|
model_locations=_locations(source),
|
||||||
torch_threads=_integer(
|
torch_threads=_integer(
|
||||||
source, "ML_TORCH_THREADS", DEFAULT_TORCH_THREADS, _MAX_TORCH_THREADS
|
source, "ML_TORCH_THREADS", DEFAULT_TORCH_THREADS, _MAX_TORCH_THREADS
|
||||||
),
|
),
|
||||||
@@ -93,4 +255,11 @@ def load_settings(environ: Mapping[str, str] | None = None) -> Settings:
|
|||||||
max_body_bytes=_integer(
|
max_body_bytes=_integer(
|
||||||
source, "ML_MAX_BODY_BYTES", DEFAULT_MAX_BODY_BYTES, 16 * DEFAULT_MAX_BODY_BYTES
|
source, "ML_MAX_BODY_BYTES", DEFAULT_MAX_BODY_BYTES, 16 * DEFAULT_MAX_BODY_BYTES
|
||||||
),
|
),
|
||||||
|
device=device,
|
||||||
|
dtype=_dtype(source, device),
|
||||||
|
cuda_memory_limit_mb=cuda_memory_limit_mb,
|
||||||
|
token=_token(source),
|
||||||
|
listen_host=source.get("ML_LISTEN_HOST", "").strip() or DEFAULT_LISTEN_HOST,
|
||||||
|
listen_port=_integer(source, "ML_LISTEN_PORT", DEFAULT_LISTEN_PORT, 65535),
|
||||||
|
exit_on_load_failure=_boolean(source, "ML_EXIT_ON_LOAD_FAILURE", False),
|
||||||
)
|
)
|
||||||
@@ -34,6 +34,14 @@ class Embedder(Protocol):
|
|||||||
"""Encode one micro-batch; the result follows the order of texts."""
|
"""Encode one micro-batch; the result follows the order of texts."""
|
||||||
...
|
...
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
"""Clean up after a failed encode.
|
||||||
|
|
||||||
|
Returns True when the failure was a lack of device memory: the encoder
|
||||||
|
released its cached memory, and the same request may pass later.
|
||||||
|
"""
|
||||||
|
...
|
||||||
|
|
||||||
|
|
||||||
def micro_batches(texts: Sequence[str], size: int) -> list[list[int]]:
|
def micro_batches(texts: Sequence[str], size: int) -> list[list[int]]:
|
||||||
"""Split request positions into micro-batches of similar length.
|
"""Split request positions into micro-batches of similar length.
|
||||||
|
|||||||
@@ -21,9 +21,14 @@ FAKE_DIMENSION: Final = 32
|
|||||||
|
|
||||||
|
|
||||||
class FakeEmbedder:
|
class FakeEmbedder:
|
||||||
def __init__(self, dimension: int = FAKE_DIMENSION, max_tokens: int = 1024) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
dimension: int = FAKE_DIMENSION,
|
||||||
|
max_tokens: int = 1024,
|
||||||
|
model_id: str = FAKE_MODEL_ID,
|
||||||
|
) -> None:
|
||||||
self._info = ModelInfo(
|
self._info = ModelInfo(
|
||||||
model_id=FAKE_MODEL_ID,
|
model_id=model_id,
|
||||||
revision=FAKE_REVISION,
|
revision=FAKE_REVISION,
|
||||||
dimension=dimension,
|
dimension=dimension,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
@@ -37,11 +42,18 @@ class FakeEmbedder:
|
|||||||
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
|
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
|
||||||
return [self._vector(kind, text) for text in texts]
|
return [self._vector(kind, text) for text in texts]
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
def _vector(self, kind: InputKind, text: str) -> list[float]:
|
def _vector(self, kind: InputKind, text: str) -> list[float]:
|
||||||
values: list[float] = []
|
values: list[float] = []
|
||||||
counter = 0
|
counter = 0
|
||||||
while len(values) < self._info.dimension:
|
while len(values) < self._info.dimension:
|
||||||
block = hashlib.sha256(f"{kind.value}\x00{counter}\x00{text}".encode()).digest()
|
seed = f"{self._info.model_id}\x00{kind.value}\x00{counter}\x00{text}"
|
||||||
|
if self._info.model_id == FAKE_MODEL_ID:
|
||||||
|
# The original seed, so vectors stored by earlier stands stay valid.
|
||||||
|
seed = f"{kind.value}\x00{counter}\x00{text}"
|
||||||
|
block = hashlib.sha256(seed.encode()).digest()
|
||||||
for (raw,) in struct.iter_unpack(">i", block):
|
for (raw,) in struct.iter_unpack(">i", block):
|
||||||
values.append(raw / 2**31)
|
values.append(raw / 2**31)
|
||||||
counter += 1
|
counter += 1
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
"""Giga-Embeddings-instruct-480M on CPU, reproducing the research recipe.
|
"""Giga-Embeddings-instruct-480M, reproducing the research recipe.
|
||||||
|
|
||||||
The model is a Qwen3 decoder turned into a bidirectional encoder. Its Hugging
|
The model is a Qwen3 decoder turned into a bidirectional encoder. Its Hugging
|
||||||
Face repository ships that wrapper as remote code; the service does not
|
Face repository ships that wrapper as remote code; the service does not
|
||||||
@@ -11,7 +11,8 @@ The encoding recipe matches the research run (sentence-transformers 5.7.0,
|
|||||||
float32): the query side gets the model's retrieval prompt, the document side
|
float32): the query side gets the model's retrieval prompt, the document side
|
||||||
gets none; the prompt and the text are joined and stripped; tokens are
|
gets none; the prompt and the text are joined and stripped; tokens are
|
||||||
truncated to max_tokens; the last hidden states are mean-pooled over the
|
truncated to max_tokens; the last hidden states are mean-pooled over the
|
||||||
attention mask including the prompt tokens and L2-normalized.
|
attention mask including the prompt tokens and L2-normalized. Pooling and
|
||||||
|
normalization run in float32 whatever the precision of the weights.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -26,10 +27,11 @@ from transformers import PreTrainedTokenizerFast
|
|||||||
from transformers.masking_utils import create_bidirectional_mask
|
from transformers.masking_utils import create_bidirectional_mask
|
||||||
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
from transformers.models.qwen3.configuration_qwen3 import Qwen3Config
|
||||||
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
|
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
|
||||||
from transformers.utils import logging as transformers_logging
|
|
||||||
|
|
||||||
|
from lincodex_ml.config import DType
|
||||||
from lincodex_ml.inference.embedder import InputKind, ModelInfo
|
from lincodex_ml.inference.embedder import InputKind, ModelInfo
|
||||||
from lincodex_ml.model_files import LOCK_FILE_NAME, load_lock, verify_directory
|
from lincodex_ml.inference.torch_support import is_out_of_memory, release_cached_memory, torch_dtype
|
||||||
|
from lincodex_ml.model_files import load_lock, verify_directory
|
||||||
|
|
||||||
# The "query" prompt of config_sentence_transformers.json at the pinned
|
# The "query" prompt of config_sentence_transformers.json at the pinned
|
||||||
# revision. Startup checks that the file still says the same.
|
# revision. Startup checks that the file still says the same.
|
||||||
@@ -79,25 +81,34 @@ class Qwen3BidirectionalModel(Qwen3Model): # type: ignore[no-untyped-call]
|
|||||||
|
|
||||||
|
|
||||||
class GigaEmbedder:
|
class GigaEmbedder:
|
||||||
"""Loads the verified files of one directory and encodes on CPU."""
|
"""Loads the verified files of one directory and encodes on one device."""
|
||||||
|
|
||||||
def __init__(self, model_dir: Path, max_tokens: int, verify_weights: bool) -> None:
|
def __init__(
|
||||||
lock = load_lock(model_dir / LOCK_FILE_NAME)
|
self,
|
||||||
|
model_dir: Path,
|
||||||
|
lock_path: Path,
|
||||||
|
max_tokens: int,
|
||||||
|
verify_weights: bool,
|
||||||
|
device: torch.device | None = None,
|
||||||
|
dtype: DType = DType.FLOAT32,
|
||||||
|
) -> None:
|
||||||
|
lock = load_lock(lock_path)
|
||||||
if verify_weights:
|
if verify_weights:
|
||||||
verify_directory(lock, model_dir)
|
verify_directory(lock, model_dir)
|
||||||
_check_query_prompt(model_dir)
|
_check_query_prompt(model_dir)
|
||||||
|
self._device = device if device is not None else torch.device("cpu")
|
||||||
self._tokenizer = PreTrainedTokenizerFast.from_pretrained(
|
self._tokenizer = PreTrainedTokenizerFast.from_pretrained(
|
||||||
str(model_dir), local_files_only=True
|
str(model_dir), local_files_only=True
|
||||||
)
|
)
|
||||||
model = Qwen3BidirectionalModel.from_pretrained(
|
model = Qwen3BidirectionalModel.from_pretrained(
|
||||||
str(model_dir),
|
str(model_dir),
|
||||||
dtype=torch.float32,
|
dtype=torch_dtype(dtype),
|
||||||
attn_implementation="sdpa",
|
attn_implementation="sdpa",
|
||||||
local_files_only=True,
|
local_files_only=True,
|
||||||
use_safetensors=True,
|
use_safetensors=True,
|
||||||
)
|
)
|
||||||
model.eval() # type: ignore[no-untyped-call]
|
model.eval() # type: ignore[no-untyped-call]
|
||||||
self._model = model
|
self._model = model.to(self._device) # type: ignore[arg-type]
|
||||||
self._max_tokens = max_tokens
|
self._max_tokens = max_tokens
|
||||||
self._info = ModelInfo(
|
self._info = ModelInfo(
|
||||||
model_id=lock.model_id,
|
model_id=lock.model_id,
|
||||||
@@ -122,15 +133,20 @@ class GigaEmbedder:
|
|||||||
max_length=self._max_tokens,
|
max_length=self._max_tokens,
|
||||||
return_tensors="pt",
|
return_tensors="pt",
|
||||||
)
|
)
|
||||||
attention_mask: torch.Tensor = encoded["attention_mask"]
|
attention_mask: torch.Tensor = encoded["attention_mask"].to(self._device)
|
||||||
hidden = self._model.encode_hidden(encoded["input_ids"], attention_mask)
|
input_ids: torch.Tensor = encoded["input_ids"].to(self._device)
|
||||||
weights = attention_mask.unsqueeze(-1).to(hidden.dtype)
|
hidden = self._model.encode_hidden(input_ids, attention_mask).to(torch.float32)
|
||||||
|
weights = attention_mask.unsqueeze(-1).to(torch.float32)
|
||||||
summed = (hidden * weights).sum(dim=1)
|
summed = (hidden * weights).sum(dim=1)
|
||||||
counts = weights.sum(dim=1).clamp(min=1e-9)
|
counts = weights.sum(dim=1).clamp(min=1e-9)
|
||||||
pooled = torch.nn.functional.normalize(summed / counts, p=2, dim=1)
|
pooled = torch.nn.functional.normalize(summed / counts, p=2, dim=1)
|
||||||
vectors: list[list[float]] = pooled.to(torch.float32).tolist()
|
vectors: list[list[float]] = pooled.cpu().tolist()
|
||||||
return vectors
|
return vectors
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
release_cached_memory(self._device)
|
||||||
|
return is_out_of_memory(error)
|
||||||
|
|
||||||
|
|
||||||
def _check_query_prompt(model_dir: Path) -> None:
|
def _check_query_prompt(model_dir: Path) -> None:
|
||||||
document = json.loads(
|
document = json.loads(
|
||||||
@@ -139,11 +155,3 @@ def _check_query_prompt(model_dir: Path) -> None:
|
|||||||
prompts = document.get("prompts", {})
|
prompts = document.get("prompts", {})
|
||||||
if prompts.get("query") != QUERY_PROMPT or prompts.get("document", "") != DOCUMENT_PROMPT:
|
if prompts.get("query") != QUERY_PROMPT or prompts.get("document", "") != DOCUMENT_PROMPT:
|
||||||
raise RuntimeError("the model prompts differ from the reviewed recipe")
|
raise RuntimeError("the model prompts differ from the reviewed recipe")
|
||||||
|
|
||||||
|
|
||||||
def configure_torch(threads: int) -> None:
|
|
||||||
"""Fix the thread pools so results and latency do not depend on the host."""
|
|
||||||
torch.set_num_threads(threads)
|
|
||||||
torch.set_num_interop_threads(1)
|
|
||||||
# The loader's progress bar would print raw text into the JSON log.
|
|
||||||
transformers_logging.disable_progress_bar() # type: ignore[no-untyped-call]
|
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
"""Qwen3-Embedding-0.6B, reproducing the research recipe.
|
||||||
|
|
||||||
|
The checkpoint is a stock Qwen3 decoder (causal attention) published with a
|
||||||
|
sentence-transformers configuration, so it loads into the Qwen3Model class of
|
||||||
|
the pinned transformers release without any code from the model repository.
|
||||||
|
|
||||||
|
The encoding recipe matches the research run (sentence-transformers 5.7.0,
|
||||||
|
float32) and the model card: the query side gets the model's own "query"
|
||||||
|
prompt, the document side gets none; the prompt and the text are joined
|
||||||
|
without a separator and stripped; the tokenizer appends the end-of-text token
|
||||||
|
and truncates to max_tokens before it; the hidden state of the last
|
||||||
|
non-padding token is the vector (last-token pooling, prompt included), which
|
||||||
|
is L2-normalized. Pooling and normalization run in float32 whatever the
|
||||||
|
precision of the weights.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Final
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from transformers import PreTrainedTokenizerFast
|
||||||
|
from transformers.models.qwen3.modeling_qwen3 import Qwen3Model
|
||||||
|
|
||||||
|
from lincodex_ml.config import DType
|
||||||
|
from lincodex_ml.inference.embedder import InputKind, ModelInfo
|
||||||
|
from lincodex_ml.inference.torch_support import is_out_of_memory, release_cached_memory, torch_dtype
|
||||||
|
from lincodex_ml.model_files import load_lock, verify_directory
|
||||||
|
|
||||||
|
# The "query" prompt of config_sentence_transformers.json at the pinned
|
||||||
|
# revision; startup checks that the file still says the same.
|
||||||
|
QUERY_PROMPT: Final = (
|
||||||
|
"Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:"
|
||||||
|
)
|
||||||
|
DOCUMENT_PROMPT: Final = ""
|
||||||
|
# Changes whenever the prompt or the pooling recipe changes; callers store it
|
||||||
|
# with each vector.
|
||||||
|
PROMPT_VERSION: Final = "qwen3-card-last-v1"
|
||||||
|
# The sentence-transformers pooling configuration the recipe relies on.
|
||||||
|
_POOLING: Final = {
|
||||||
|
"pooling_mode_cls_token": False,
|
||||||
|
"pooling_mode_mean_tokens": False,
|
||||||
|
"pooling_mode_max_tokens": False,
|
||||||
|
"pooling_mode_mean_sqrt_len_tokens": False,
|
||||||
|
"pooling_mode_weightedmean_tokens": False,
|
||||||
|
"pooling_mode_lasttoken": True,
|
||||||
|
"include_prompt": True,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Qwen3Embedder:
|
||||||
|
"""Loads the verified files of one directory and encodes on one device."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
model_dir: Path,
|
||||||
|
lock_path: Path,
|
||||||
|
max_tokens: int,
|
||||||
|
verify_weights: bool,
|
||||||
|
device: torch.device | None = None,
|
||||||
|
dtype: DType = DType.FLOAT32,
|
||||||
|
) -> None:
|
||||||
|
lock = load_lock(lock_path)
|
||||||
|
if verify_weights:
|
||||||
|
verify_directory(lock, model_dir)
|
||||||
|
_check_recipe(model_dir)
|
||||||
|
self._device = device if device is not None else torch.device("cpu")
|
||||||
|
tokenizer = PreTrainedTokenizerFast.from_pretrained(str(model_dir), local_files_only=True)
|
||||||
|
# Right padding: the last real token of a row is at its mask length - 1.
|
||||||
|
tokenizer.padding_side = "right"
|
||||||
|
self._tokenizer = tokenizer
|
||||||
|
model = Qwen3Model.from_pretrained(
|
||||||
|
str(model_dir),
|
||||||
|
dtype=torch_dtype(dtype),
|
||||||
|
attn_implementation="sdpa",
|
||||||
|
local_files_only=True,
|
||||||
|
use_safetensors=True,
|
||||||
|
)
|
||||||
|
model.eval() # type: ignore[no-untyped-call]
|
||||||
|
self._model = model.to(self._device) # type: ignore[arg-type]
|
||||||
|
self._max_tokens = max_tokens
|
||||||
|
self._info = ModelInfo(
|
||||||
|
model_id=lock.model_id,
|
||||||
|
revision=lock.revision,
|
||||||
|
dimension=int(model.config.hidden_size),
|
||||||
|
max_tokens=max_tokens,
|
||||||
|
prompt_version=PROMPT_VERSION,
|
||||||
|
)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def info(self) -> ModelInfo:
|
||||||
|
return self._info
|
||||||
|
|
||||||
|
@torch.inference_mode()
|
||||||
|
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
|
||||||
|
prompt = QUERY_PROMPT if kind is InputKind.QUERY else DOCUMENT_PROMPT
|
||||||
|
prepared = [(prompt + text).strip() for text in texts]
|
||||||
|
encoded: Any = self._tokenizer(
|
||||||
|
prepared,
|
||||||
|
padding=True,
|
||||||
|
truncation="longest_first",
|
||||||
|
max_length=self._max_tokens,
|
||||||
|
return_tensors="pt",
|
||||||
|
)
|
||||||
|
attention_mask: torch.Tensor = encoded["attention_mask"].to(self._device)
|
||||||
|
input_ids: torch.Tensor = encoded["input_ids"].to(self._device)
|
||||||
|
output: Any = self._model(input_ids=input_ids, attention_mask=attention_mask)
|
||||||
|
hidden: torch.Tensor = output.last_hidden_state
|
||||||
|
last = attention_mask.sum(dim=1) - 1
|
||||||
|
rows = torch.arange(hidden.shape[0], device=hidden.device)
|
||||||
|
pooled = hidden[rows, last].to(torch.float32)
|
||||||
|
normalized = torch.nn.functional.normalize(pooled, p=2, dim=1)
|
||||||
|
vectors: list[list[float]] = normalized.cpu().tolist()
|
||||||
|
return vectors
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
release_cached_memory(self._device)
|
||||||
|
return is_out_of_memory(error)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_recipe(model_dir: Path) -> None:
|
||||||
|
"""Refuse a model directory whose prompts or pooling differ from the recipe."""
|
||||||
|
document = json.loads(
|
||||||
|
(model_dir / "config_sentence_transformers.json").read_text(encoding="utf-8")
|
||||||
|
)
|
||||||
|
prompts = document.get("prompts", {})
|
||||||
|
if prompts.get("query") != QUERY_PROMPT or prompts.get("document", "") != DOCUMENT_PROMPT:
|
||||||
|
raise RuntimeError("the model prompts differ from the reviewed recipe")
|
||||||
|
pooling = json.loads((model_dir / "1_Pooling" / "config.json").read_text(encoding="utf-8"))
|
||||||
|
if any(pooling.get(name) != value for name, value in _POOLING.items()):
|
||||||
|
raise RuntimeError("the model pooling differs from the reviewed recipe")
|
||||||
|
modules = json.loads((model_dir / "modules.json").read_text(encoding="utf-8"))
|
||||||
|
types = [module.get("type") for module in modules]
|
||||||
|
if types[-1:] != ["sentence_transformers.models.Normalize"]:
|
||||||
|
raise RuntimeError("the model does not end with the normalization the recipe expects")
|
||||||
@@ -1,22 +1,29 @@
|
|||||||
"""Loading state and serialized execution of the encoder.
|
"""Loading state and serialized execution of the encoders.
|
||||||
|
|
||||||
The encoder loads in a background thread after startup, so the process
|
The encoders load in a background thread after startup, so the process
|
||||||
answers /healthz at once. Readiness turns ready only after a warm-up encode
|
answers /healthz at once. Readiness turns ready only after every configured
|
||||||
of both input kinds has finished. Encoding runs one request at a time: the
|
encoder has loaded and finished a warm-up encode of both input kinds.
|
||||||
model already uses every configured CPU thread, and parallel requests would
|
Encoding runs one request at a time: a model already uses every configured
|
||||||
only compete for them.
|
CPU thread or the whole GPU, and parallel requests would only compete.
|
||||||
|
|
||||||
|
On a GPU that another service shares, an allocation can fail while that
|
||||||
|
service holds the memory. Such a failure never stops the process: a failed
|
||||||
|
load is retried with a growing pause, and a failed request answers 503 and
|
||||||
|
keeps the service not ready for a short cool-down, after which it serves again.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import gc
|
||||||
import logging
|
import logging
|
||||||
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from collections.abc import Callable, Sequence
|
from collections.abc import Callable, Sequence
|
||||||
from enum import StrEnum
|
from enum import StrEnum
|
||||||
from typing import Final
|
from typing import Final
|
||||||
|
|
||||||
from prometheus_client import Counter, Histogram
|
from prometheus_client import Counter, Gauge, Histogram
|
||||||
|
|
||||||
from lincodex_ml.config import EmbedderKind, Settings
|
from lincodex_ml.config import EmbedderKind, Settings
|
||||||
from lincodex_ml.inference.embedder import Embedder, InputKind, ModelInfo, encode_ordered
|
from lincodex_ml.inference.embedder import Embedder, InputKind, ModelInfo, encode_ordered
|
||||||
@@ -30,18 +37,29 @@ _WARMUP_TEXTS: Final = (
|
|||||||
"Разработка сервиса уведомлений с повторной доставкой и дедупликацией.", # noqa: RUF001
|
"Разработка сервиса уведомлений с повторной доставкой и дедупликацией.", # noqa: RUF001
|
||||||
)
|
)
|
||||||
_WARMUP_ROUNDS: Final = 3
|
_WARMUP_ROUNDS: Final = 3
|
||||||
|
# How long readiness stays not ready after a request ran out of device memory.
|
||||||
|
OOM_COOL_DOWN_SECONDS: Final = 30.0
|
||||||
|
# Pauses between load attempts that ran out of device memory.
|
||||||
|
_LOAD_RETRY_FIRST_SECONDS: Final = 15.0
|
||||||
|
_LOAD_RETRY_MAX_SECONDS: Final = 300.0
|
||||||
|
|
||||||
ENCODE_SECONDS: Final = Histogram(
|
ENCODE_SECONDS: Final = Histogram(
|
||||||
"lincodex_ml_embedding_request_seconds",
|
"lincodex_ml_embedding_request_seconds",
|
||||||
"Time to encode one embedding request, by input kind.",
|
"Time to encode one embedding request, by input kind.",
|
||||||
["kind"],
|
["kind"],
|
||||||
buckets=(0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0),
|
buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0),
|
||||||
)
|
)
|
||||||
ENCODED_TEXTS: Final = Counter(
|
ENCODED_TEXTS: Final = Counter(
|
||||||
"lincodex_ml_embedding_texts_total",
|
"lincodex_ml_embedding_texts_total",
|
||||||
"Texts encoded, by input kind.",
|
"Texts encoded, by input kind.",
|
||||||
["kind"],
|
["kind"],
|
||||||
)
|
)
|
||||||
|
OUT_OF_MEMORY: Final = Counter(
|
||||||
|
"lincodex_ml_out_of_memory_total",
|
||||||
|
"Loads and requests that failed for lack of device memory.",
|
||||||
|
["stage"],
|
||||||
|
)
|
||||||
|
READY: Final = Gauge("lincodex_ml_ready", "1 while every configured encoder is ready.")
|
||||||
|
|
||||||
|
|
||||||
class RuntimeState(StrEnum):
|
class RuntimeState(StrEnum):
|
||||||
@@ -52,15 +70,43 @@ class RuntimeState(StrEnum):
|
|||||||
|
|
||||||
|
|
||||||
class NotReadyError(Exception):
|
class NotReadyError(Exception):
|
||||||
"""The encoder is not loaded and warmed up."""
|
"""The encoders are not loaded and warmed up."""
|
||||||
|
|
||||||
|
|
||||||
|
class CapacityError(Exception):
|
||||||
|
"""The device ran out of memory; the same request may pass later."""
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownModelError(Exception):
|
||||||
|
"""The request names a model that the service does not serve."""
|
||||||
|
|
||||||
|
|
||||||
|
EmbedderFactory = Callable[[], Embedder]
|
||||||
|
|
||||||
|
|
||||||
class EmbeddingRuntime:
|
class EmbeddingRuntime:
|
||||||
def __init__(self, settings: Settings, factory: Callable[[], Embedder] | None) -> None:
|
def __init__(
|
||||||
|
self,
|
||||||
|
settings: Settings,
|
||||||
|
factories: EmbedderFactory | Sequence[EmbedderFactory] | None,
|
||||||
|
clock: Callable[[], float] = time.monotonic,
|
||||||
|
sleep: Callable[[float], None] = time.sleep,
|
||||||
|
on_failure: Callable[[], None] | None = None,
|
||||||
|
) -> None:
|
||||||
self._settings = settings
|
self._settings = settings
|
||||||
self._factory = factory
|
if factories is None:
|
||||||
self._state = RuntimeState.DISABLED if factory is None else RuntimeState.LOADING
|
self._factories: tuple[EmbedderFactory, ...] = ()
|
||||||
self._embedder: Embedder | None = None
|
elif callable(factories):
|
||||||
|
self._factories = (factories,)
|
||||||
|
else:
|
||||||
|
self._factories = tuple(factories)
|
||||||
|
self._clock = clock
|
||||||
|
self._sleep = sleep
|
||||||
|
self._on_failure = on_failure
|
||||||
|
self._state = RuntimeState.LOADING if self._factories else RuntimeState.DISABLED
|
||||||
|
self._embedders: dict[str, Embedder] = {}
|
||||||
|
self._default: str | None = None
|
||||||
|
self._cool_down_until = 0.0
|
||||||
self._state_lock = threading.Lock()
|
self._state_lock = threading.Lock()
|
||||||
self._encode_lock = threading.Lock()
|
self._encode_lock = threading.Lock()
|
||||||
self._thread: threading.Thread | None = None
|
self._thread: threading.Thread | None = None
|
||||||
@@ -70,9 +116,14 @@ class EmbeddingRuntime:
|
|||||||
with self._state_lock:
|
with self._state_lock:
|
||||||
return self._state
|
return self._state
|
||||||
|
|
||||||
|
def ready(self) -> bool:
|
||||||
|
"""Ready and not cooling down after an out-of-memory request."""
|
||||||
|
with self._state_lock:
|
||||||
|
return self._state is RuntimeState.READY and self._clock() >= self._cool_down_until
|
||||||
|
|
||||||
def start(self) -> None:
|
def start(self) -> None:
|
||||||
"""Load and warm up the encoder in the background."""
|
"""Load and warm up the encoders in the background."""
|
||||||
if self._factory is None or self._thread is not None:
|
if not self._factories or self._thread is not None:
|
||||||
return
|
return
|
||||||
self._thread = threading.Thread(target=self._load, name="embedder-load", daemon=True)
|
self._thread = threading.Thread(target=self._load, name="embedder-load", daemon=True)
|
||||||
self._thread.start()
|
self._thread.start()
|
||||||
@@ -83,69 +134,176 @@ class EmbeddingRuntime:
|
|||||||
return self.state
|
return self.state
|
||||||
|
|
||||||
def _load(self) -> None:
|
def _load(self) -> None:
|
||||||
factory = self._factory
|
started = self._clock()
|
||||||
if factory is None:
|
pause = _LOAD_RETRY_FIRST_SECONDS
|
||||||
return
|
while True:
|
||||||
started = time.monotonic()
|
try:
|
||||||
try:
|
embedders = self._load_all()
|
||||||
embedder = factory()
|
break
|
||||||
for _ in range(_WARMUP_ROUNDS):
|
except Exception as error:
|
||||||
for kind in InputKind:
|
out_of_memory = _released_after(error, None)
|
||||||
encode_ordered(embedder, kind, _WARMUP_TEXTS, self._settings.micro_batch)
|
if not out_of_memory:
|
||||||
except Exception as error:
|
# The message can quote file paths or text; the type is
|
||||||
# The message can quote file paths or text; the type is enough to act on.
|
# enough to act on.
|
||||||
logger.error("embedding model failed to load: %s", type(error).__name__)
|
logger.error("embedding model failed to load: %s", type(error).__name__)
|
||||||
with self._state_lock:
|
if not out_of_memory:
|
||||||
self._state = RuntimeState.FAILED
|
with self._state_lock:
|
||||||
return
|
self._state = RuntimeState.FAILED
|
||||||
|
if self._on_failure is not None:
|
||||||
|
self._on_failure()
|
||||||
|
return
|
||||||
|
# The failed attempt is unreachable now; collect it so that its
|
||||||
|
# device memory returns before the next attempt.
|
||||||
|
gc.collect()
|
||||||
|
_release_device_cache()
|
||||||
|
OUT_OF_MEMORY.labels(stage="load").inc()
|
||||||
|
logger.warning(
|
||||||
|
"embedding model load ran out of device memory; retrying",
|
||||||
|
extra={"retry_seconds": pause},
|
||||||
|
)
|
||||||
|
self._sleep(pause)
|
||||||
|
pause = min(pause * 2, _LOAD_RETRY_MAX_SECONDS)
|
||||||
with self._state_lock:
|
with self._state_lock:
|
||||||
self._embedder = embedder
|
self._embedders = {embedder.info.model_id: embedder for embedder in embedders}
|
||||||
|
self._default = embedders[0].info.model_id
|
||||||
self._state = RuntimeState.READY
|
self._state = RuntimeState.READY
|
||||||
|
READY.set(1)
|
||||||
logger.info(
|
logger.info(
|
||||||
"embedding model is ready",
|
"embedding models are ready",
|
||||||
extra={"seconds": round(time.monotonic() - started, 1)},
|
extra={
|
||||||
|
"seconds": round(self._clock() - started, 1),
|
||||||
|
"models": [embedder.info.model_id for embedder in embedders],
|
||||||
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
def info(self) -> ModelInfo:
|
def _load_all(self) -> list[Embedder]:
|
||||||
with self._state_lock:
|
embedders: list[Embedder] = []
|
||||||
if self._embedder is None:
|
try:
|
||||||
raise NotReadyError
|
for factory in self._factories:
|
||||||
return self._embedder.info
|
embedder = factory()
|
||||||
|
embedders.append(embedder)
|
||||||
|
for _ in range(_WARMUP_ROUNDS):
|
||||||
|
for kind in InputKind:
|
||||||
|
encode_ordered(embedder, kind, _WARMUP_TEXTS, self._settings.micro_batch)
|
||||||
|
if len({embedder.info.model_id for embedder in embedders}) != len(embedders):
|
||||||
|
raise RuntimeError("two encoders report the same model id")
|
||||||
|
except BaseException as error:
|
||||||
|
# Free what the attempt loaded before a retry.
|
||||||
|
for embedder in embedders:
|
||||||
|
embedder.recover(error)
|
||||||
|
embedders.clear()
|
||||||
|
raise
|
||||||
|
return embedders
|
||||||
|
|
||||||
def encode(self, kind: InputKind, texts: Sequence[str]) -> tuple[ModelInfo, list[list[float]]]:
|
def models(self) -> list[ModelInfo]:
|
||||||
|
"""The served models, the default first."""
|
||||||
with self._state_lock:
|
with self._state_lock:
|
||||||
embedder = self._embedder
|
if self._default is None:
|
||||||
|
raise NotReadyError
|
||||||
|
default = self._embedders[self._default]
|
||||||
|
return [default.info] + [
|
||||||
|
embedder.info for embedder in self._embedders.values() if embedder is not default
|
||||||
|
]
|
||||||
|
|
||||||
|
def info(self) -> ModelInfo:
|
||||||
|
"""The default model."""
|
||||||
|
return self.models()[0]
|
||||||
|
|
||||||
|
def _select(self, model_id: str | None) -> Embedder:
|
||||||
|
with self._state_lock:
|
||||||
|
if self._default is None:
|
||||||
|
raise NotReadyError
|
||||||
|
embedder = self._embedders.get(self._default if model_id is None else model_id)
|
||||||
if embedder is None:
|
if embedder is None:
|
||||||
raise NotReadyError
|
raise UnknownModelError
|
||||||
|
return embedder
|
||||||
|
|
||||||
|
def encode(
|
||||||
|
self, kind: InputKind, texts: Sequence[str], model_id: str | None = None
|
||||||
|
) -> tuple[ModelInfo, list[list[float]]]:
|
||||||
|
embedder = self._select(model_id)
|
||||||
with self._encode_lock, ENCODE_SECONDS.labels(kind=kind.value).time():
|
with self._encode_lock, ENCODE_SECONDS.labels(kind=kind.value).time():
|
||||||
vectors = encode_ordered(embedder, kind, texts, self._settings.micro_batch)
|
try:
|
||||||
|
vectors = encode_ordered(embedder, kind, texts, self._settings.micro_batch)
|
||||||
|
except Exception as error:
|
||||||
|
if not _released_after(error, embedder):
|
||||||
|
raise
|
||||||
|
OUT_OF_MEMORY.labels(stage="request").inc()
|
||||||
|
with self._state_lock:
|
||||||
|
self._cool_down_until = self._clock() + OOM_COOL_DOWN_SECONDS
|
||||||
|
logger.warning("an embedding request ran out of device memory")
|
||||||
|
raise CapacityError from None
|
||||||
ENCODED_TEXTS.labels(kind=kind.value).inc(len(texts))
|
ENCODED_TEXTS.labels(kind=kind.value).inc(len(texts))
|
||||||
return embedder.info, vectors
|
return embedder.info, vectors
|
||||||
|
|
||||||
|
|
||||||
def embedder_factory(settings: Settings) -> Callable[[], Embedder] | None:
|
def _released_after(error: BaseException, embedder: Embedder | None) -> bool:
|
||||||
"""Return how to build the configured encoder, or None when disabled."""
|
"""Whether an error is a lack of device memory, after releasing the cache."""
|
||||||
match settings.embedder:
|
if embedder is not None:
|
||||||
case EmbedderKind.NONE:
|
return embedder.recover(error)
|
||||||
return None
|
# A load failure has no encoder yet. Only a loaded torch can raise an
|
||||||
case EmbedderKind.FAKE:
|
# out-of-memory error, so a service without one never imports it here.
|
||||||
|
if "torch" not in sys.modules:
|
||||||
|
return False
|
||||||
|
from lincodex_ml.inference.torch_support import is_out_of_memory
|
||||||
|
|
||||||
def build_fake() -> Embedder:
|
return is_out_of_memory(error)
|
||||||
from lincodex_ml.inference.fake import FakeEmbedder
|
|
||||||
|
|
||||||
return FakeEmbedder(max_tokens=settings.max_tokens)
|
|
||||||
|
|
||||||
return build_fake
|
def _release_device_cache() -> None:
|
||||||
case EmbedderKind.GIGA:
|
if "torch" not in sys.modules:
|
||||||
|
return
|
||||||
|
from lincodex_ml.inference.torch_support import release_all_cached_memory
|
||||||
|
|
||||||
def build_giga() -> Embedder:
|
release_all_cached_memory()
|
||||||
# Imported here: torch and transformers load in seconds and
|
|
||||||
# only a service that runs the model needs them.
|
|
||||||
from lincodex_ml.inference.giga import GigaEmbedder, configure_torch
|
|
||||||
|
|
||||||
configure_torch(settings.torch_threads)
|
|
||||||
return GigaEmbedder(
|
|
||||||
settings.model_dir, settings.max_tokens, settings.verify_weights
|
|
||||||
)
|
|
||||||
|
|
||||||
return build_giga
|
def embedder_factories(settings: Settings) -> list[EmbedderFactory]:
|
||||||
|
"""Return how to build every configured encoder, in configuration order."""
|
||||||
|
factories: list[EmbedderFactory] = []
|
||||||
|
for kind in settings.embedders:
|
||||||
|
factories.append(_factory(settings, kind))
|
||||||
|
return factories
|
||||||
|
|
||||||
|
|
||||||
|
def _factory(settings: Settings, kind: EmbedderKind) -> EmbedderFactory:
|
||||||
|
if kind is EmbedderKind.FAKE:
|
||||||
|
|
||||||
|
def build_fake() -> Embedder:
|
||||||
|
from lincodex_ml.inference.fake import FakeEmbedder
|
||||||
|
|
||||||
|
return FakeEmbedder(max_tokens=settings.max_tokens)
|
||||||
|
|
||||||
|
return build_fake
|
||||||
|
|
||||||
|
def build_model() -> Embedder:
|
||||||
|
# Imported here: torch and transformers load in seconds and only a
|
||||||
|
# service that runs a real model needs them.
|
||||||
|
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
|
||||||
|
|
||||||
|
configure_torch(settings.torch_threads)
|
||||||
|
device = prepare_device(settings.device, settings.cuda_memory_limit_mb)
|
||||||
|
location = settings.location(kind)
|
||||||
|
if kind is EmbedderKind.GIGA:
|
||||||
|
from lincodex_ml.inference.giga import GigaEmbedder
|
||||||
|
|
||||||
|
return GigaEmbedder(
|
||||||
|
location.directory,
|
||||||
|
location.lock,
|
||||||
|
settings.max_tokens,
|
||||||
|
settings.verify_weights,
|
||||||
|
device,
|
||||||
|
settings.dtype,
|
||||||
|
)
|
||||||
|
from lincodex_ml.inference.qwen3 import Qwen3Embedder
|
||||||
|
|
||||||
|
return Qwen3Embedder(
|
||||||
|
location.directory,
|
||||||
|
location.lock,
|
||||||
|
settings.max_tokens,
|
||||||
|
settings.verify_weights,
|
||||||
|
device,
|
||||||
|
settings.dtype,
|
||||||
|
)
|
||||||
|
|
||||||
|
return build_model
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""Device, precision, and memory handling shared by the real encoders.
|
||||||
|
|
||||||
|
Only modules that run a real model import this file, because importing torch
|
||||||
|
takes seconds and a fake or disabled service never needs it.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
import torch
|
||||||
|
from transformers.utils import logging as transformers_logging
|
||||||
|
|
||||||
|
from lincodex_ml.config import DType
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_DTYPES: Final = {
|
||||||
|
DType.FLOAT32: torch.float32,
|
||||||
|
DType.FLOAT16: torch.float16,
|
||||||
|
DType.BFLOAT16: torch.bfloat16,
|
||||||
|
}
|
||||||
|
_MIB: Final = 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
def torch_dtype(dtype: DType) -> torch.dtype:
|
||||||
|
return _DTYPES[dtype]
|
||||||
|
|
||||||
|
|
||||||
|
def configure_torch(threads: int) -> None:
|
||||||
|
"""Fix the thread pools so results and latency do not depend on the host."""
|
||||||
|
torch.set_num_threads(threads)
|
||||||
|
# The inter-op pool can be sized only once per process, before it starts;
|
||||||
|
# the second model of a service finds it configured already.
|
||||||
|
if torch.get_num_interop_threads() != 1:
|
||||||
|
torch.set_num_interop_threads(1)
|
||||||
|
# The loader's progress bar would print raw text into the JSON log.
|
||||||
|
transformers_logging.disable_progress_bar() # type: ignore[no-untyped-call]
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_device(device: str, memory_limit_mb: int) -> torch.device:
|
||||||
|
"""Resolve the device and cap the CUDA allocator of this process.
|
||||||
|
|
||||||
|
The limit makes the allocator raise an out-of-memory error instead of
|
||||||
|
taking memory that another process on a shared GPU needs; the CUDA
|
||||||
|
context itself (a few hundred MiB) is outside the allocator and the cap.
|
||||||
|
Deterministic kernels are requested so that the same text gives the same
|
||||||
|
vector on every call.
|
||||||
|
"""
|
||||||
|
resolved = torch.device(device)
|
||||||
|
if resolved.type != "cuda":
|
||||||
|
return resolved
|
||||||
|
if not torch.cuda.is_available():
|
||||||
|
raise RuntimeError("ML_DEVICE names CUDA, but no CUDA device is available")
|
||||||
|
index = resolved.index if resolved.index is not None else torch.cuda.current_device()
|
||||||
|
resolved = torch.device("cuda", index)
|
||||||
|
torch.backends.cudnn.benchmark = False
|
||||||
|
torch.backends.cuda.matmul.allow_tf32 = False
|
||||||
|
torch.backends.cudnn.allow_tf32 = False
|
||||||
|
if memory_limit_mb > 0:
|
||||||
|
total = torch.cuda.get_device_properties(index).total_memory
|
||||||
|
fraction = min(1.0, memory_limit_mb * _MIB / total)
|
||||||
|
torch.cuda.set_per_process_memory_fraction(fraction, index)
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def is_out_of_memory(error: BaseException) -> bool:
|
||||||
|
"""Whether an error is a device allocation failure that may pass later."""
|
||||||
|
return isinstance(error, torch.OutOfMemoryError)
|
||||||
|
|
||||||
|
|
||||||
|
def release_cached_memory(device: torch.device) -> None:
|
||||||
|
"""Return the cached blocks of the allocator after a failed allocation."""
|
||||||
|
if device.type == "cuda":
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def release_all_cached_memory() -> None:
|
||||||
|
"""Return the cached blocks of every device, for example after a failed load."""
|
||||||
|
if torch.cuda.is_available() and torch.cuda.is_initialized(): # type: ignore[no-untyped-call]
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
|
||||||
|
|
||||||
|
def peak_memory_mb(device: torch.device) -> int:
|
||||||
|
"""The allocator peak of the process on the device in MiB, 0 on CPU."""
|
||||||
|
if device.type != "cuda":
|
||||||
|
return 0
|
||||||
|
return int(torch.cuda.max_memory_allocated(device) // _MIB)
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
from collections.abc import AsyncIterator
|
from collections.abc import AsyncIterator
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
@@ -5,14 +6,15 @@ from contextlib import asynccontextmanager
|
|||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from prometheus_client import REGISTRY, make_asgi_app
|
from prometheus_client import REGISTRY, make_asgi_app
|
||||||
|
|
||||||
|
from lincodex_ml.api.auth import BearerAuthMiddleware
|
||||||
from lincodex_ml.api.embeddings import router as embeddings_router
|
from lincodex_ml.api.embeddings import router as embeddings_router
|
||||||
from lincodex_ml.api.health import router as health_router
|
from lincodex_ml.api.health import router as health_router
|
||||||
from lincodex_ml.api.problems import BodyLimitMiddleware, install_problem_handlers
|
from lincodex_ml.api.problems import BodyLimitMiddleware, install_problem_handlers
|
||||||
from lincodex_ml.config import Settings, load_settings
|
from lincodex_ml.config import Settings, load_settings
|
||||||
from lincodex_ml.inference.runtime import EmbeddingRuntime, embedder_factory
|
from lincodex_ml.inference.runtime import EmbeddingRuntime, embedder_factories
|
||||||
from lincodex_ml.infra.logging import configure_logging
|
from lincodex_ml.infra.logging import configure_logging
|
||||||
|
|
||||||
# The model is read from the image only; the Hugging Face libraries must never
|
# The models are read from local files only; the Hugging Face libraries must never
|
||||||
# reach the network or print progress bars into the JSON log.
|
# reach the network or print progress bars into the JSON log.
|
||||||
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
||||||
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
||||||
@@ -20,13 +22,29 @@ os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
|
|||||||
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
|
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
|
||||||
|
|
||||||
|
|
||||||
|
def _exit_after_load_failure() -> None:
|
||||||
|
"""End the process so that its supervisor restarts it.
|
||||||
|
|
||||||
|
Called from the load thread after the failure was logged; no request is
|
||||||
|
in progress then, because every request answered 503 while loading.
|
||||||
|
"""
|
||||||
|
logging.getLogger(__name__).error("exiting after the model load failure")
|
||||||
|
os._exit(3)
|
||||||
|
|
||||||
|
|
||||||
def create_app(
|
def create_app(
|
||||||
settings: Settings | None = None, runtime: EmbeddingRuntime | None = None
|
settings: Settings | None = None, runtime: EmbeddingRuntime | None = None
|
||||||
) -> FastAPI:
|
) -> FastAPI:
|
||||||
configure_logging()
|
configure_logging()
|
||||||
effective = load_settings() if settings is None else settings
|
effective = load_settings() if settings is None else settings
|
||||||
embedding_runtime = (
|
embedding_runtime = (
|
||||||
EmbeddingRuntime(effective, embedder_factory(effective)) if runtime is None else runtime
|
EmbeddingRuntime(
|
||||||
|
effective,
|
||||||
|
embedder_factories(effective),
|
||||||
|
on_failure=_exit_after_load_failure if effective.exit_on_load_failure else None,
|
||||||
|
)
|
||||||
|
if runtime is None
|
||||||
|
else runtime
|
||||||
)
|
)
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -39,6 +57,9 @@ def create_app(
|
|||||||
application.state.embedding_runtime = embedding_runtime
|
application.state.embedding_runtime = embedding_runtime
|
||||||
install_problem_handlers(application)
|
install_problem_handlers(application)
|
||||||
application.add_middleware(BodyLimitMiddleware, max_body_bytes=effective.max_body_bytes)
|
application.add_middleware(BodyLimitMiddleware, max_body_bytes=effective.max_body_bytes)
|
||||||
|
# Added last, so it runs first: an unauthenticated request is refused
|
||||||
|
# before its body is read.
|
||||||
|
application.add_middleware(BearerAuthMiddleware, token=effective.token)
|
||||||
application.include_router(health_router)
|
application.include_router(health_router)
|
||||||
application.include_router(embeddings_router)
|
application.include_router(embeddings_router)
|
||||||
application.mount("/metrics", make_asgi_app(registry=REGISTRY))
|
application.mount("/metrics", make_asgi_app(registry=REGISTRY))
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Entry point of the service: `python -m lincodex_ml.serve`.
|
||||||
|
|
||||||
|
It reads the listen address from ML_LISTEN_HOST and ML_LISTEN_PORT and
|
||||||
|
refuses to listen on a non-loopback address without a service token, so the
|
||||||
|
embeddings route is never open to a network. Run the service through this
|
||||||
|
module, not through the uvicorn command line, which cannot apply that check.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
from lincodex_ml.config import SettingsError, is_loopback_host, load_settings
|
||||||
|
from lincodex_ml.infra.logging import configure_logging
|
||||||
|
|
||||||
|
logger = logging.getLogger("lincodex_ml.serve")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
configure_logging()
|
||||||
|
try:
|
||||||
|
settings = load_settings()
|
||||||
|
except SettingsError as error:
|
||||||
|
# Setting messages name the variable and never quote a secret.
|
||||||
|
logger.error("invalid settings: %s", error)
|
||||||
|
return 2
|
||||||
|
if settings.token is None and not is_loopback_host(settings.listen_host):
|
||||||
|
logger.error(
|
||||||
|
"refusing to listen on a non-loopback address without a service token; "
|
||||||
|
"set ML_SERVICE_TOKEN_FILE or ML_SERVICE_TOKEN"
|
||||||
|
)
|
||||||
|
return 2
|
||||||
|
from lincodex_ml.main import create_app
|
||||||
|
|
||||||
|
uvicorn.run(
|
||||||
|
create_app(settings),
|
||||||
|
host=settings.listen_host,
|
||||||
|
port=settings.listen_port,
|
||||||
|
workers=1,
|
||||||
|
log_config=None,
|
||||||
|
server_header=False,
|
||||||
|
proxy_headers=False,
|
||||||
|
)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"source": "research run qwen3-emb-0.6b, float32, sentence-transformers 5.7.0 on CUDA (reports/step3 caches); synthetic texts written for the study", "model": "Qwen/Qwen3-Embedding-0.6B", "revision": "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3", "cases": [{"kind": "query", "text": "Title: Junior backend-разработчик в команду товарного каталога\nGrade: junior\nDomain: e-commerce, товарный каталог\nRequired skills: Python; REST API; SQL\nDesired skills: FastAPI или Django; pydantic\nTasks:\n- разрабатывать эндпоинты создания и редактирования карточек товаров\n- валидировать входящие данные от контент-менеджеров и внешних систем\n- делать постраничную выдачу и регулярные выгрузки для других систем\nDescription: Вакансия: Junior backend-разработчик. Мы развиваем внутренний сервис товарного каталога, через который контент-менеджеры заводят карточки, а остальные системы забирают данные. Нужно писать эндпоинты для создания и редактирования карточек, аккуратно проверять входные данные, делать постраничную выдачу и регулярные выгрузки в другие системы. Ожидаем уверенный Python, понимание REST и SQL. Будет плюсом опыт с FastAPI или Django и pydantic. Наставничество есть.", "vector": [0.0602012, 0.0124066, -0.00837608, -0.115849, 0.0229714, -0.0449449, 0.0400122, 0.0186199, -0.00262195, 0.027917, 0.0115094, 0.000379152, 0.0552954, -0.00858507, -0.0528446, 0.0245004, -0.0605631, 0.0374188, -0.00460552, 0.0603005, -0.00414506, 0.0224963, 0.00617129, 0.0920065, -0.0528705, 0.00388604, -0.00378349, 0.0508754, 0.0240473, -0.0719818, 0.0396926, -0.0525244, -0.0855952, -0.0116856, -0.0157775, -0.0102084, -0.00526572, -0.00796006, -0.0160493, -0.0297368, 0.00406728, 0.0168165, 0.0646498, 0.00876707, 0.0549871, 0.0423338, -0.0239126, 0.000764695, -0.00399904, 0.017483, -0.0283778, 0.0267792, 0.00549343, -0.0443869, 0.00771952, 0.0909804, 0.0371597, 0.01389, -0.00961419, -0.0128616, -0.025547, -0.00974861, -0.0433427, -0.00446814, -0.0170152, -0.027677, 0.0247146, 0.0634491, -0.0116979, -0.0214617, 0.015703, -0.0443664, -0.0266521, 0.0655657, -0.00101198, -0.0222626, -0.0410097, 0.0145328, -0.00270477, 0.0360168, -0.0389881, 0.00160317, -0.00716379, 0.0389457, 0.0131134, 0.0305296, -0.0542479, 0.0148947, 0.073781, 0.0135235, -0.0465107, 0.000482755, -0.0262602, 0.0843561, 0.0721028, -0.00949527, -0.000411064, -0.0189709, 0.0149664, -0.00340449, -0.0288007, 0.00626825, 0.00581747, -0.0265795, -0.0226354, 0.0365, -0.0728306, -9.14146e-05, -0.000612176, -0.00620869, -0.0203464, -0.00915578, 0.0238467, 0.0323428, -0.0091572, 0.00530451, -0.0114913, -0.0185306, 0.0243089, 0.00311003, 0.00358606, -0.0205419, 0.0333829, -0.00381886, -0.00959042, 0.023225, -0.0110733, -0.0030246, 0.0144974, -0.0231456, -0.0169505, -0.0123519, 0.00108274, -0.00476542, 0.00202406, 0.00983555, 0.0353283, 0.00340459, 0.0238342, 0.0210707, -0.0302298, -0.000957774, -0.0357876, 8.6956e-05, -0.00317794, 0.0275074, 2.96926e-05, -0.00522985, -0.0203424, -0.034108, 0.0282373, 0.0232936, 0.00558298, -0.017145, -0.0224415, 0.0390445, 0.0176887, -0.0204843, -0.00637747, 0.00863677, -0.0067378, -0.0241422, 0.0108148, -0.0254529, -0.0103555, 0.00521044, 0.0171894, -0.0309625, -0.0220943, -0.026691, -0.01241, 0.0150758, 0.00336508, -0.00769786, -0.00773804, 0.019265, -0.0438933, -0.0260157, 0.0359295, -0.0273923, -0.0321467, -0.0569879, -0.00392302, -0.0256407, 0.00749932, 0.0250187, 0.00792559, -0.00756945, -0.00372752, -0.000173198, -0.0145194, 0.010585, -0.0436066, -0.0223215, 0.00134221, -0.0077836, 0.0259203, -0.0117231, -0.0303712, 0.00692453, -0.00119344, -0.068066, 0.0261531, -0.00601992, -0.00955028, 0.0315477, 0.0212862, -0.00440249, -0.0365007, -0.0470244, -0.032537, 0.000758911, 0.00886744, 0.0143412, 0.0291826, 0.0253873, 0.0306272, 0.0160996, 0.0125119, 0.0111439, 0.0196644, 0.00969219, -0.0375632, 0.0237727, -0.0197809, -0.00282755, -0.0189743, 0.0262661, 0.030764, 0.00804198, -0.0476831, -0.00346554, -0.00169148, 0.0549661, 0.0173557, -0.0132749, -0.0122172, 0.00490362, 0.0077466, 0.0259259, 0.0423622, 0.02566, -0.0186705, 0.0112911, -0.0338476, 0.0140017, -0.0238772, 0.0217582, -0.013552, 0.00732205, 0.0236143, 0.00532941, -0.0210365, 0.0894465, 0.0385867, -0.0634436, 0.0226703, -0.00490849, -0.000202779, 0.000529942, 0.0851105, -0.00573467, 0.0111772, 0.0346563, 0.0201242, 0.00518378, -0.00829974, 0.0529882, -0.0122595, -0.0267392, -0.0358635, 0.0131867, -0.0123355, 0.00716906, -0.0230974Line truncated
|
||||||
@@ -2,6 +2,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import replace
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -9,7 +10,7 @@ import pytest
|
|||||||
import yaml
|
import yaml
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
|
||||||
from lincodex_ml.config import EmbedderKind, Settings, load_settings
|
from lincodex_ml.config import Settings, load_settings
|
||||||
from lincodex_ml.inference.embedder import InputKind, ModelInfo, micro_batches
|
from lincodex_ml.inference.embedder import InputKind, ModelInfo, micro_batches
|
||||||
from lincodex_ml.inference.fake import FakeEmbedder
|
from lincodex_ml.inference.fake import FakeEmbedder
|
||||||
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
|
from lincodex_ml.inference.runtime import EmbeddingRuntime, RuntimeState
|
||||||
@@ -25,18 +26,7 @@ def anyio_backend() -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _settings(**overrides: object) -> Settings:
|
def _settings(**overrides: object) -> Settings:
|
||||||
base = load_settings({"ML_EMBEDDER": "fake"})
|
return replace(load_settings({"ML_EMBEDDER": "fake"}), **overrides) # type: ignore[arg-type]
|
||||||
values = {
|
|
||||||
"embedder": base.embedder,
|
|
||||||
"model_dir": base.model_dir,
|
|
||||||
"torch_threads": base.torch_threads,
|
|
||||||
"micro_batch": base.micro_batch,
|
|
||||||
"max_tokens": base.max_tokens,
|
|
||||||
"verify_weights": base.verify_weights,
|
|
||||||
"max_body_bytes": base.max_body_bytes,
|
|
||||||
}
|
|
||||||
values.update(overrides)
|
|
||||||
return Settings(**values) # type: ignore[arg-type]
|
|
||||||
|
|
||||||
|
|
||||||
class RecordingEmbedder:
|
class RecordingEmbedder:
|
||||||
@@ -54,6 +44,9 @@ class RecordingEmbedder:
|
|||||||
self.batches.append(list(texts))
|
self.batches.append(list(texts))
|
||||||
return self.inner.encode_batch(kind, texts)
|
return self.inner.encode_batch(kind, texts)
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _ready_app(settings: Settings, embedder: object | None = None) -> FastAPI:
|
def _ready_app(settings: Settings, embedder: object | None = None) -> FastAPI:
|
||||||
built = embedder if embedder is not None else FakeEmbedder()
|
built = embedder if embedder is not None else FakeEmbedder()
|
||||||
@@ -117,7 +110,7 @@ async def test_micro_batch_size_bounds_every_forward_pass() -> None:
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_service_answers_503_until_the_model_is_ready() -> None:
|
async def test_service_answers_503_until_the_model_is_ready() -> None:
|
||||||
application = create_app(_settings(embedder=EmbedderKind.NONE))
|
application = create_app(_settings(embedders=()))
|
||||||
async with httpx.AsyncClient(
|
async with httpx.AsyncClient(
|
||||||
transport=httpx.ASGITransport(app=application), base_url="http://test"
|
transport=httpx.ASGITransport(app=application), base_url="http://test"
|
||||||
) as client:
|
) as client:
|
||||||
@@ -210,7 +203,7 @@ async def test_request_texts_never_reach_the_log(caplog: pytest.LogCaptureFixtur
|
|||||||
def test_embedding_operation_matches_the_shared_contract() -> None:
|
def test_embedding_operation_matches_the_shared_contract() -> None:
|
||||||
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
|
contract = yaml.safe_load(CONTRACT_PATH.read_text(encoding="utf-8"))
|
||||||
operation = contract["paths"]["/v1/embeddings"]["post"]
|
operation = contract["paths"]["/v1/embeddings"]["post"]
|
||||||
implementation = create_app(_settings(embedder=EmbedderKind.NONE)).openapi()
|
implementation = create_app(_settings(embedders=())).openapi()
|
||||||
actual = implementation["paths"]["/v1/embeddings"]["post"]
|
actual = implementation["paths"]["/v1/embeddings"]["post"]
|
||||||
assert actual["operationId"] == operation["operationId"]
|
assert actual["operationId"] == operation["operationId"]
|
||||||
assert set(operation["responses"]) >= {"200", "400", "413", "503"}
|
assert set(operation["responses"]) >= {"200", "400", "413", "503"}
|
||||||
@@ -228,7 +221,7 @@ def test_settings_reject_invalid_values() -> None:
|
|||||||
with pytest.raises(SettingsError):
|
with pytest.raises(SettingsError):
|
||||||
load_settings(environ)
|
load_settings(environ)
|
||||||
settings = load_settings({})
|
settings = load_settings({})
|
||||||
assert settings.embedder is EmbedderKind.NONE
|
assert settings.embedders == ()
|
||||||
assert (settings.torch_threads, settings.micro_batch, settings.max_tokens) == (4, 1, 1024)
|
assert (settings.torch_threads, settings.micro_batch, settings.max_tokens) == (4, 1, 1024)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,352 @@
|
|||||||
|
"""Several models in one service, device memory failures, and the bearer token."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import replace
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from fastapi import FastAPI
|
||||||
|
|
||||||
|
from lincodex_ml import serve
|
||||||
|
from lincodex_ml.config import (
|
||||||
|
DType,
|
||||||
|
EmbedderKind,
|
||||||
|
ServiceToken,
|
||||||
|
Settings,
|
||||||
|
SettingsError,
|
||||||
|
is_loopback_host,
|
||||||
|
load_settings,
|
||||||
|
)
|
||||||
|
from lincodex_ml.inference import runtime as runtime_module
|
||||||
|
from lincodex_ml.inference.embedder import InputKind, ModelInfo
|
||||||
|
from lincodex_ml.inference.fake import FakeEmbedder
|
||||||
|
from lincodex_ml.inference.runtime import (
|
||||||
|
OOM_COOL_DOWN_SECONDS,
|
||||||
|
EmbeddingRuntime,
|
||||||
|
RuntimeState,
|
||||||
|
)
|
||||||
|
from lincodex_ml.main import create_app
|
||||||
|
|
||||||
|
TOKEN = "t0k3n-" + "x" * 40
|
||||||
|
OTHER_MODEL = "lincodex/fake-second-embedder"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def anyio_backend() -> str:
|
||||||
|
return "asyncio"
|
||||||
|
|
||||||
|
|
||||||
|
def _settings(**overrides: object) -> Settings:
|
||||||
|
return replace(load_settings({"ML_EMBEDDER": "fake"}), **overrides) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
class Clock:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.now = 1000.0
|
||||||
|
|
||||||
|
def __call__(self) -> float:
|
||||||
|
return self.now
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceFull(Exception):
|
||||||
|
"""Stands for a CUDA out-of-memory error."""
|
||||||
|
|
||||||
|
|
||||||
|
class FlakyEmbedder:
|
||||||
|
"""Runs out of device memory while `full` is set."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.inner = FakeEmbedder(model_id=OTHER_MODEL)
|
||||||
|
self.full = False
|
||||||
|
self.released = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def info(self) -> ModelInfo:
|
||||||
|
return self.inner.info
|
||||||
|
|
||||||
|
def encode_batch(self, kind: InputKind, texts: Sequence[str]) -> list[list[float]]:
|
||||||
|
if self.full:
|
||||||
|
raise DeviceFull
|
||||||
|
return self.inner.encode_batch(kind, texts)
|
||||||
|
|
||||||
|
def recover(self, error: BaseException) -> bool:
|
||||||
|
self.released += 1
|
||||||
|
return isinstance(error, DeviceFull)
|
||||||
|
|
||||||
|
|
||||||
|
def _ready(settings: Settings, *embedders: object, clock: Clock | None = None) -> FastAPI:
|
||||||
|
runtime = EmbeddingRuntime(
|
||||||
|
settings,
|
||||||
|
[lambda embedder=embedder: embedder for embedder in embedders], # type: ignore[misc]
|
||||||
|
clock=clock or Clock(),
|
||||||
|
)
|
||||||
|
runtime.start()
|
||||||
|
assert runtime.wait(10) is RuntimeState.READY
|
||||||
|
return create_app(settings, runtime)
|
||||||
|
|
||||||
|
|
||||||
|
async def _call(
|
||||||
|
application: FastAPI,
|
||||||
|
method: str,
|
||||||
|
path: str,
|
||||||
|
client: tuple[str, int] = ("127.0.0.1", 50000),
|
||||||
|
**kwargs: object,
|
||||||
|
) -> httpx.Response:
|
||||||
|
transport = httpx.ASGITransport(app=application, client=client)
|
||||||
|
async with httpx.AsyncClient(transport=transport, base_url="http://test") as http:
|
||||||
|
return await http.request(method, path, **kwargs) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- settings
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_accept_an_ordered_model_list_and_cuda_options(tmp_path: Path) -> None:
|
||||||
|
token_file = tmp_path / "token"
|
||||||
|
token_file.write_text(TOKEN + "\n", encoding="utf-8")
|
||||||
|
settings = load_settings(
|
||||||
|
{
|
||||||
|
"ML_EMBEDDER": "giga, qwen3",
|
||||||
|
"ML_DEVICE": "cuda",
|
||||||
|
"ML_DTYPE": "float16",
|
||||||
|
"ML_CUDA_MEMORY_LIMIT_MB": "2300",
|
||||||
|
"ML_SERVICE_TOKEN_FILE": str(token_file),
|
||||||
|
"ML_GIGA_MODEL_DIR": "/models/giga",
|
||||||
|
"ML_QWEN3_MODEL_DIR": "/models/qwen3",
|
||||||
|
"ML_QWEN3_MODEL_LOCK": "/locks/qwen3.lock.json",
|
||||||
|
"ML_LISTEN_HOST": "192.168.10.25",
|
||||||
|
"ML_LISTEN_PORT": "8790",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
assert settings.embedders == (EmbedderKind.GIGA, EmbedderKind.QWEN3)
|
||||||
|
assert (settings.device, settings.dtype, settings.cuda_memory_limit_mb) == (
|
||||||
|
"cuda",
|
||||||
|
DType.FLOAT16,
|
||||||
|
2300,
|
||||||
|
)
|
||||||
|
assert settings.token is not None and settings.token.reveal() == TOKEN
|
||||||
|
assert settings.location(EmbedderKind.GIGA).lock == Path("/models/giga/model.lock.json")
|
||||||
|
assert settings.location(EmbedderKind.QWEN3).lock == Path("/locks/qwen3.lock.json")
|
||||||
|
assert (settings.listen_host, settings.listen_port) == ("192.168.10.25", 8790)
|
||||||
|
assert TOKEN not in repr(settings) and TOKEN not in str(settings.token)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"environ",
|
||||||
|
[
|
||||||
|
{"ML_EMBEDDER": "giga,giga"},
|
||||||
|
{"ML_EMBEDDER": "fake,giga"},
|
||||||
|
{"ML_EMBEDDER": "giga,gpt"},
|
||||||
|
{"ML_DEVICE": "tpu"},
|
||||||
|
{"ML_DTYPE": "float16"},
|
||||||
|
{"ML_DEVICE": "cuda", "ML_DTYPE": "int8"},
|
||||||
|
{"ML_CUDA_MEMORY_LIMIT_MB": "2000"},
|
||||||
|
{"ML_SERVICE_TOKEN": "short"},
|
||||||
|
{"ML_SERVICE_TOKEN": "x" * 20 + " " + "y" * 20},
|
||||||
|
{"ML_SERVICE_TOKEN": TOKEN, "ML_SERVICE_TOKEN_FILE": "/run/token"},
|
||||||
|
{"ML_SERVICE_TOKEN_FILE": "/nonexistent/token"},
|
||||||
|
{"ML_LISTEN_PORT": "70000"},
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_settings_reject_invalid_combinations(environ: dict[str, str]) -> None:
|
||||||
|
with pytest.raises(SettingsError) as raised:
|
||||||
|
load_settings(environ)
|
||||||
|
assert TOKEN not in str(raised.value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_loopback_detection() -> None:
|
||||||
|
assert all(is_loopback_host(host) for host in ("127.0.0.1", "::1", "[::1]", "localhost"))
|
||||||
|
assert not any(is_loopback_host(host) for host in ("0.0.0.0", "192.168.10.25", "ml", "::"))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- several models
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_the_model_field_selects_one_of_the_loaded_models() -> None:
|
||||||
|
application = _ready(_settings(), FakeEmbedder(), FakeEmbedder(model_id=OTHER_MODEL))
|
||||||
|
body = {"kind": "query", "texts": ["Kafka consumer idempotency"]}
|
||||||
|
|
||||||
|
default = await _call(application, "POST", "/v1/embeddings", json=body)
|
||||||
|
second = await _call(application, "POST", "/v1/embeddings", json={**body, "model": OTHER_MODEL})
|
||||||
|
unknown = await _call(application, "POST", "/v1/embeddings", json={**body, "model": "x/y"})
|
||||||
|
|
||||||
|
assert default.status_code == 200 and second.status_code == 200
|
||||||
|
assert default.json()["model"]["id"] == "lincodex/fake-hash-embedder"
|
||||||
|
assert second.json()["model"]["id"] == OTHER_MODEL
|
||||||
|
assert default.json()["vectors"] != second.json()["vectors"]
|
||||||
|
assert unknown.status_code == 400
|
||||||
|
assert unknown.json()["errors"][0]["pointer"] == "/model"
|
||||||
|
|
||||||
|
|
||||||
|
def test_readiness_needs_every_model_and_a_broken_one_fails_the_service() -> None:
|
||||||
|
def broken() -> FakeEmbedder:
|
||||||
|
raise OSError("weights are missing")
|
||||||
|
|
||||||
|
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, broken])
|
||||||
|
runtime.start()
|
||||||
|
assert runtime.wait(10) is RuntimeState.FAILED
|
||||||
|
assert not runtime.ready()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_permanent_load_failure_calls_the_exit_hook_and_memory_does_not() -> None:
|
||||||
|
calls: list[str] = []
|
||||||
|
|
||||||
|
def broken() -> FakeEmbedder:
|
||||||
|
raise OSError("weights are missing")
|
||||||
|
|
||||||
|
runtime = EmbeddingRuntime(_settings(), [broken], on_failure=lambda: calls.append("exit"))
|
||||||
|
runtime.start()
|
||||||
|
assert runtime.wait(10) is RuntimeState.FAILED
|
||||||
|
assert calls == ["exit"]
|
||||||
|
assert load_settings({"ML_EXIT_ON_LOAD_FAILURE": "true"}).exit_on_load_failure
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_encoders_with_one_model_id_are_refused() -> None:
|
||||||
|
runtime = EmbeddingRuntime(_settings(), [FakeEmbedder, FakeEmbedder])
|
||||||
|
runtime.start()
|
||||||
|
assert runtime.wait(10) is RuntimeState.FAILED
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- device memory
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_out_of_memory_answers_503_and_cools_readiness_down_without_crashing() -> None:
|
||||||
|
clock = Clock()
|
||||||
|
flaky = FlakyEmbedder()
|
||||||
|
application = _ready(_settings(), flaky, clock=clock)
|
||||||
|
body = {"kind": "document", "texts": ["Stack: go, kafka"]}
|
||||||
|
|
||||||
|
flaky.full = True
|
||||||
|
failed = await _call(application, "POST", "/v1/embeddings", json=body)
|
||||||
|
readiness = await _call(application, "GET", "/readyz")
|
||||||
|
assert failed.status_code == 503
|
||||||
|
assert failed.json()["code"] == "service_unavailable"
|
||||||
|
assert failed.headers["retry-after"] == "5"
|
||||||
|
assert readiness.status_code == 503
|
||||||
|
assert flaky.released >= 1
|
||||||
|
|
||||||
|
flaky.full = False
|
||||||
|
clock.now += OOM_COOL_DOWN_SECONDS + 1
|
||||||
|
recovered = await _call(application, "POST", "/v1/embeddings", json=body)
|
||||||
|
assert recovered.status_code == 200
|
||||||
|
assert (await _call(application, "GET", "/readyz")).status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_load_that_runs_out_of_memory_is_retried(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
attempts: list[int] = []
|
||||||
|
pauses: list[float] = []
|
||||||
|
|
||||||
|
def factory() -> FakeEmbedder:
|
||||||
|
attempts.append(1)
|
||||||
|
if len(attempts) < 3:
|
||||||
|
raise DeviceFull
|
||||||
|
return FakeEmbedder()
|
||||||
|
|
||||||
|
monkeypatch.setattr(
|
||||||
|
runtime_module, "_released_after", lambda error, _: isinstance(error, DeviceFull)
|
||||||
|
)
|
||||||
|
runtime = EmbeddingRuntime(_settings(), [factory], sleep=pauses.append)
|
||||||
|
runtime.start()
|
||||||
|
assert runtime.wait(10) is RuntimeState.READY
|
||||||
|
assert len(attempts) == 3
|
||||||
|
assert pauses == [15.0, 30.0]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- bearer token
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_a_configured_token_guards_every_route_but_the_probes(
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
application = _ready(_settings(token=ServiceToken(TOKEN)), FakeEmbedder())
|
||||||
|
body = {"kind": "query", "texts": ["Go"]}
|
||||||
|
remote = ("192.168.10.30", 41000)
|
||||||
|
|
||||||
|
with caplog.at_level(logging.DEBUG):
|
||||||
|
missing = await _call(application, "POST", "/v1/embeddings", remote, json=body)
|
||||||
|
wrong = await _call(
|
||||||
|
application,
|
||||||
|
"POST",
|
||||||
|
"/v1/embeddings",
|
||||||
|
remote,
|
||||||
|
json=body,
|
||||||
|
headers={"Authorization": "Bearer " + TOKEN[:-1] + "y"},
|
||||||
|
)
|
||||||
|
basic = await _call(
|
||||||
|
application,
|
||||||
|
"POST",
|
||||||
|
"/v1/embeddings",
|
||||||
|
remote,
|
||||||
|
json=body,
|
||||||
|
headers={"Authorization": "Basic " + TOKEN},
|
||||||
|
)
|
||||||
|
metrics = await _call(application, "GET", "/metrics/", remote)
|
||||||
|
accepted = await _call(
|
||||||
|
application,
|
||||||
|
"POST",
|
||||||
|
"/v1/embeddings",
|
||||||
|
remote,
|
||||||
|
json=body,
|
||||||
|
headers={"Authorization": "bearer " + TOKEN},
|
||||||
|
)
|
||||||
|
health = await _call(application, "GET", "/healthz", remote)
|
||||||
|
ready = await _call(application, "GET", "/readyz", remote)
|
||||||
|
|
||||||
|
for refused in (missing, wrong, basic, metrics):
|
||||||
|
assert refused.status_code == 401
|
||||||
|
assert refused.headers["www-authenticate"] == "Bearer"
|
||||||
|
assert refused.json()["code"] == "unauthenticated"
|
||||||
|
assert TOKEN not in refused.text
|
||||||
|
assert accepted.status_code == 200
|
||||||
|
assert health.status_code == 200 and ready.status_code == 200
|
||||||
|
assert TOKEN not in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_without_a_token_only_loopback_callers_are_served() -> None:
|
||||||
|
application = _ready(_settings(), FakeEmbedder())
|
||||||
|
body = {"kind": "query", "texts": ["Go"]}
|
||||||
|
|
||||||
|
local = await _call(application, "POST", "/v1/embeddings", json=body)
|
||||||
|
remote = await _call(application, "POST", "/v1/embeddings", ("10.0.0.7", 5000), json=body)
|
||||||
|
|
||||||
|
assert local.status_code == 200
|
||||||
|
assert remote.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_an_unauthenticated_body_is_never_read() -> None:
|
||||||
|
application = _ready(_settings(token=ServiceToken(TOKEN), max_body_bytes=1024), FakeEmbedder())
|
||||||
|
response = await _call(
|
||||||
|
application,
|
||||||
|
"POST",
|
||||||
|
"/v1/embeddings",
|
||||||
|
("10.0.0.7", 5000),
|
||||||
|
json={"kind": "query", "texts": ["x" * 4000]},
|
||||||
|
)
|
||||||
|
assert response.status_code == 401
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- entry point
|
||||||
|
|
||||||
|
|
||||||
|
def test_serve_refuses_a_network_address_without_a_token(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
|
started: list[object] = []
|
||||||
|
monkeypatch.setattr(serve.uvicorn, "run", lambda *args, **kwargs: started.append(kwargs))
|
||||||
|
for name in ("ML_SERVICE_TOKEN", "ML_SERVICE_TOKEN_FILE", "ML_EMBEDDER"):
|
||||||
|
monkeypatch.delenv(name, raising=False)
|
||||||
|
monkeypatch.setenv("ML_LISTEN_HOST", "0.0.0.0")
|
||||||
|
assert serve.main() == 2
|
||||||
|
assert started == []
|
||||||
|
|
||||||
|
monkeypatch.setenv("ML_SERVICE_TOKEN", TOKEN)
|
||||||
|
assert serve.main() == 0
|
||||||
|
assert started and started[0]["host"] == "0.0.0.0" # type: ignore[index]
|
||||||
|
|
||||||
|
monkeypatch.delenv("ML_SERVICE_TOKEN")
|
||||||
|
monkeypatch.setenv("ML_LISTEN_HOST", "127.0.0.1")
|
||||||
|
assert serve.main() == 0
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
"""Parity of the real model with the research vectors.
|
"""Parity of the real Giga model with the research vectors.
|
||||||
|
|
||||||
Marked slow: it needs the pinned weights in ML_MODEL_DIR (fetch them with
|
Marked slow: it needs the pinned weights in ML_GIGA_MODEL_DIR (fetch them with
|
||||||
`make -C ml model-fetch`) and runs only with `make -C ml test-model`.
|
`make -C ml model-fetch`) and runs only with `make -C ml test-model`. The
|
||||||
|
files are verified against the checked-in lock file. ML_TEST_DEVICE=cuda runs
|
||||||
|
it on the GPU in float32.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@@ -13,8 +15,10 @@ import pytest
|
|||||||
|
|
||||||
from lincodex_ml.inference.embedder import InputKind
|
from lincodex_ml.inference.embedder import InputKind
|
||||||
|
|
||||||
GOLDEN = Path(__file__).resolve().parent / "data" / "giga_golden.json"
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
# CPU float32 against the research CUDA float32 run; measured differences are
|
GOLDEN = ROOT / "tests" / "data" / "giga_golden.json"
|
||||||
|
LOCK = ROOT / "model" / "giga-embeddings-480m.lock.json"
|
||||||
|
# float32 against the research CUDA float32 run; measured differences are
|
||||||
# below 1e-6 per component.
|
# below 1e-6 per component.
|
||||||
MAX_COMPONENT_DIFFERENCE = 1e-4
|
MAX_COMPONENT_DIFFERENCE = 1e-4
|
||||||
|
|
||||||
@@ -23,17 +27,19 @@ pytestmark = pytest.mark.slow
|
|||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def model_dir() -> Path:
|
def model_dir() -> Path:
|
||||||
raw = os.environ.get("ML_MODEL_DIR", "")
|
raw = os.environ.get("ML_GIGA_MODEL_DIR", "")
|
||||||
if not raw:
|
if not raw:
|
||||||
pytest.skip("ML_MODEL_DIR is not set")
|
pytest.skip("ML_GIGA_MODEL_DIR is not set")
|
||||||
return Path(raw)
|
return Path(raw)
|
||||||
|
|
||||||
|
|
||||||
def test_real_model_reproduces_the_research_vectors_deterministically(model_dir: Path) -> None:
|
def test_real_model_reproduces_the_research_vectors_deterministically(model_dir: Path) -> None:
|
||||||
from lincodex_ml.inference.giga import GigaEmbedder, configure_torch
|
from lincodex_ml.inference.giga import GigaEmbedder
|
||||||
|
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
|
||||||
|
|
||||||
configure_torch(4)
|
configure_torch(4)
|
||||||
embedder = GigaEmbedder(model_dir, max_tokens=1024, verify_weights=True)
|
device = prepare_device(os.environ.get("ML_TEST_DEVICE", "cpu"), 0)
|
||||||
|
embedder = GigaEmbedder(model_dir, LOCK, max_tokens=1024, verify_weights=True, device=device)
|
||||||
golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
|
golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
|
||||||
assert embedder.info.model_id == golden["model"]
|
assert embedder.info.model_id == golden["model"]
|
||||||
assert embedder.info.revision == golden["revision"]
|
assert embedder.info.revision == golden["revision"]
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Parity of the real Qwen3-Embedding model with the research vectors.
|
||||||
|
|
||||||
|
Marked slow: it needs the pinned weights in ML_QWEN3_MODEL_DIR (fetch them with
|
||||||
|
`make -C ml model-fetch`) and runs only with `make -C ml test-model`. The
|
||||||
|
files are verified against the checked-in lock file. ML_TEST_DEVICE=cuda runs
|
||||||
|
it on the GPU in float32.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from lincodex_ml.inference.embedder import InputKind
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
GOLDEN = ROOT / "tests" / "data" / "qwen3_golden.json"
|
||||||
|
LOCK = ROOT / "model" / "qwen3-embedding-0.6b.lock.json"
|
||||||
|
# float32 against the research CUDA float32 run; measured differences are
|
||||||
|
# below 1e-6 per component.
|
||||||
|
MAX_COMPONENT_DIFFERENCE = 1e-4
|
||||||
|
|
||||||
|
pytestmark = pytest.mark.slow
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module")
|
||||||
|
def model_dir() -> Path:
|
||||||
|
raw = os.environ.get("ML_QWEN3_MODEL_DIR", "")
|
||||||
|
if not raw:
|
||||||
|
pytest.skip("ML_QWEN3_MODEL_DIR is not set")
|
||||||
|
return Path(raw)
|
||||||
|
|
||||||
|
|
||||||
|
def test_real_model_reproduces_the_research_vectors_deterministically(model_dir: Path) -> None:
|
||||||
|
from lincodex_ml.inference.qwen3 import Qwen3Embedder
|
||||||
|
from lincodex_ml.inference.torch_support import configure_torch, prepare_device
|
||||||
|
|
||||||
|
configure_torch(4)
|
||||||
|
device = prepare_device(os.environ.get("ML_TEST_DEVICE", "cpu"), 0)
|
||||||
|
embedder = Qwen3Embedder(model_dir, LOCK, max_tokens=1024, verify_weights=True, device=device)
|
||||||
|
golden = json.loads(GOLDEN.read_text(encoding="utf-8"))
|
||||||
|
assert embedder.info.model_id == golden["model"]
|
||||||
|
assert embedder.info.revision == golden["revision"]
|
||||||
|
assert embedder.info.dimension == 1024
|
||||||
|
for case in golden["cases"]:
|
||||||
|
kind = InputKind(case["kind"])
|
||||||
|
first = embedder.encode_batch(kind, [case["text"]])[0]
|
||||||
|
second = embedder.encode_batch(kind, [case["text"]])[0]
|
||||||
|
assert first == second
|
||||||
|
assert math.isclose(math.sqrt(sum(value * value for value in first)), 1.0, abs_tol=1e-5)
|
||||||
|
difference = max(abs(a - b) for a, b in zip(first, case["vector"], strict=True))
|
||||||
|
assert difference < MAX_COMPONENT_DIFFERENCE
|
||||||
Reference in new issue
Block a user