Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
release: v0.6.16
github-actions[bot]cbb3c8fbb563
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3b3252e31..e284904b8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,38 @@# Changelog+## v0.6.16++- chore(main): release 0.6.16+- fix(adapters): honor caller instruction in use_model_encode without a template+- feat(adapters): use_model_encode — delegate to checkpoint-native encode()+- Revert "feat(adapters): opt-in template_as_prompt for ST prompt-length-aware templates"+- Revert "fix(models): serve NV-Embed-v2 via its native latent-attention ST path"+- fix(models): serve NV-Embed-v2 via its native latent-attention ST path+- feat(adapters): opt-in template_as_prompt for ST prompt-length-aware templates+- chore(models): remove Qwen3-0.6B experimental custom LoRA profile+- test(keda): cover gpu-agnostic kind smoke demand+- docs(gateway): clarify legacy empty demand comments+- fix(adapters): harden splade flash gate + add flash-vs-native parity test+- fix(gateway): normalize explicit GPU demand labels+- fix(gateway): fan out gpu-agnostic demand across pool profiles for scale-from-zero+- fix(bundles): pin flash-attn-4 prerelease so sglang 0.5.10.post1 resolves+- fix(helm): wake a deterministic owner lane on gpu-agnostic demand for multi-profile bundles+- fix(colbert): GTE muvera also at simhash 6 - CMedQA/MMarco evals OOM at dim 81920+- fix(colbert): mxbai muvera at simhash 6 (FDE dim 20480) - runner dies at 81920+- fix(colbert): retune GTE/mxbai muvera for the Dense-projected representation+- fix(colbert): serve pylate Dense chains and align fallback with flash+- fix(models): restore e5 templates on multilingual-e5-large ST profile+- fix(colbert_modernbert_flash): faithful ModernBERT forward + hardened 1_Dense loading+- test: cover candle warm model residency+- fix: align candle workers with catalog lane config+- refactor(server): dedup flash mean-pooling into _flash_pack+- fix(colbert_modernbert_flash): address CodeRabbit review on #1591+- fix(colbert_modernbert_flash): only apply Dense head when out_features==token_dim+- fix(colbert_modernbert_flash): apply trained ColBERT Dense projection+- Revert "feat(models): onboard topk-io/Iso-ModernColBERT (ColBERT multivector)"+- fix(colbert_modernbert_flash): tolerate transformers>=5 tokenizer_class+- feat(models): onboard topk-io/Iso-ModernColBERT (ColBERT multivector)+## v0.6.15- chore(main): release 0.6.15diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex d22720879..e7e65c6da 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.15 # x-release-please-version-appVersion: v0.6.15 # x-release-please-version+version: 0.6.16 # x-release-please-version+appVersion: v0.6.16 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex e9d3cc797..b554d7d90 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -125,9 +125,11 @@ autoscaling:The gateway exposes `sie_gateway_pending_demand{pool="...",machine_profile="...",bundle="..."}`when requests arrive for queue lanes with no available workers. KEDA uses thisto trigger scale-up even when there are 0 workers (and thus no worker metrics).-For `X-SIE-Pool` requests that omit `X-SIE-MACHINE-PROFILE`, the gateway can-emit a lane-specific signal only when the registered pool spec contains exactly-one machine profile. Multi-profile tenant pools should send both headers.+For gpu-agnostic cold requests, including `X-SIE-Pool` requests that omit+`X-SIE-MACHINE-PROFILE`, the gateway emits concrete lane signals for every+machine profile the backing pool can provision. Multi-profile pools therefore+wake candidate lanes from zero without relying on an empty `machine_profile`+label that KEDA cannot match.### Scaling Metricsdiff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 3f11a5ec7..738e61a44 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -468,15 +468,13 @@ store enabled" and an empty result as "off".{{/*Distinct machine profiles serving a bundle within a queue pool.-Drives the KEDA pending_demand trigger's scale-from-zero matcher. When a-gpu-agnostic request (e.g. /v1/chat/completions without an X-SIE-MACHINE-PROFILE-or a model `:profile` suffix) cannot be served, the gateway records pending-demand with an EMPTY machine_profile label, because a multi-profile queue pool-gives it no single cold lane to name (proxy.rs PoolLookup.pending_demand_profile).-A per-lane scaler keyed on machine_profile="<profile>" never sees that demand, so-the lane stays at zero and the model is stuck "provisioning". A lane whose bundle-maps to exactly one machine profile in the pool is unambiguous and can safely also-count the empty-label demand.+Drives the KEDA pending_demand trigger's scale-from-zero matcher. Current+gateways fan gpu-agnostic cold demand (for example, /v1/chat/completions without+an X-SIE-MACHINE-PROFILE or a model `:profile` suffix) out to concrete machine+profiles at the source, so each per-lane scaler can see the demand it owns. Older+gateways could emit that demand under the EMPTY machine_profile label instead.+A lane whose bundle maps to exactly one machine profile in the pool is+unambiguous and can safely keep counting that legacy empty-label bucket.Args (dict): root, queuePool, bundle.Returns a comma-joined, sorted list of distinct machine profiles.diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yamlindex fa320e5eb..c5c666926 100644--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml@@ -137,9 +137,9 @@ data:serverAddress: {{ $promAddr }}metricName: sie_gateway_pending_demand_{{ $poolName }}_{{ $bundleName }}{{- if $singleProfileBundle }}- # Single-profile bundle: add gpu-agnostic demand the gateway records- # with an empty machine_profile when it cannot name a cold lane (a- # multi-profile pool; see proxy.rs PoolLookup). Each term is guarded+ # Single-profile bundle: keep counting the legacy gpu-agnostic+ # empty-profile demand bucket for older gateways. Current gateways+ # emit concrete profile demand at the source; each term is guarded# with `or vector(0)` so one absent series cannot void the sum.query: (sum(sie_gateway_pending_demand{pool="{{ $queuePool }}", machine_profile="{{ $machineProfile }}", bundle="{{ $bundle }}"}) or vector(0)) + (sum(sie_gateway_pending_demand{pool="{{ $queuePool }}", machine_profile="", bundle="{{ $bundle }}"}) or vector(0)){{- else }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex a5efd044b..5df4e7020 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -79,20 +79,6 @@ fast at render time.{{- if and (eq $engine "candle") (ne $bundle "candle") }}{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires bundle=candle so gateway routing and worker heartbeats agree" $poolName $bundleName) }}{{- end }}-{{- $poolCandle := default dict $pool.candle }}-{{- $candleModelIds := list }}-{{- if $poolCandle.modelIds }}-{{- if kindIs "slice" $poolCandle.modelIds }}-{{- $candleModelIds = $poolCandle.modelIds }}-{{- else }}-{{- $candleModelIds = list $poolCandle.modelIds }}-{{- end }}-{{- else if $poolCandle.modelId }}-{{- $candleModelIds = list $poolCandle.modelId }}-{{- end }}-{{- if and (eq $engine "candle") (eq (len $candleModelIds) 0) }}-{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires workers.pools.%s.candle.modelId or candle.modelIds" $poolName $bundleName $poolName) }}-{{- end }}---apiVersion: apps/v1kind: StatefulSet@@ -197,14 +183,6 @@ spec:valueFrom:fieldRef:fieldPath: metadata.name- - name: SIE_ENGINE- value: "candle"- - name: SIE_CANDLE_MODELS- value: {{ join "," $candleModelIds | quote }}- {{- if $poolCandle.profile }}- - name: SIE_CANDLE_PROFILE- value: {{ $poolCandle.profile | quote }}- {{- end }}- name: SIE_CANDLE_BATCH_BUDGETvalue: {{ $root.Values.workers.common.rust.candle.batchBudget | default 64 | quote }}- name: SIE_CANDLE_MAX_CONCURRENT_FORWARDSdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 64a363092..3f30d9cd9 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -687,8 +687,10 @@ workers:## Pool-level keys (shared across bundles on this hardware):# enabled: bool. Skip rendering the whole pool when false.- # engine: Optional runtime engine default for bundle lanes in this- # pool. `pytorch` (default) or `candle`.+ # engine: Optional bundle execution-engine default for lanes in+ # this pool. `pytorch` (default) or `candle`. Used by the+ # chart for image/label selection, not propagated as a+ # worker process env var.# gpu.count: int. 0 disables nvidia.com/gpu request on the pod.# gpu.product: string. nvidia.com/gpu.product node-label match.# gpuType: GPU/node label used for node selection and display.@@ -708,16 +710,6 @@ workers:# container. For `engine: candle`, this is the Rust# native worker image instead of Python.# runtimeClassName: Optional override of common.runtimeClassName.- # candle.modelId: Primary Hugging Face model id loaded by the Rust Candle- # worker. Required when `engine: candle` unless- # `candle.modelIds` is set.- # candle.modelIds: Optional list, or comma-separated string, of Hugging- # Face model ids loaded by the Rust worker. Defaults to- # `[candle.modelId]`.- # candle.profile: Optional catalog profile pinned to this Rust Candle- # adapter process. Leave empty for default-only native- # models; set to `candle` only for side-by-side profile- # variants such as `model:candle`.# candle.cudaComputeCap:# Optional per-pool Rust Candle CUDA compute capability# override. If omitted, the chart resolves it from@@ -742,10 +734,9 @@ workers:# Each queuePool/machineProfile/bundle lane renders one StatefulSet +# KEDA ScaledObject + PDB + image-prepull DaemonSet, named worker-{pool}-{bundle}.#- # NOTE: `engine: candle` serves an explicit native model allowlist via- # `candle.modelId` or `candle.modelIds`. Multiple model ids can share a- # pool when GPU memory and startup budget allow it; use additional pools- # for different GPU shapes, batch settings, or profile pinning.+ # NOTE: `engine: candle` serves applied Candle catalog models for the+ # lane's bundle/pool, just like PyTorch workers. Use `preloadModels` or pool+ # `pinnedModels` for warm model residency.pools:# L4 GPUdiff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 53a62086f..5e39dcf2c 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex 166911be6..ee18b1c0f 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex 17763f993..478f125cc 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 69b515d0e..ebb266480 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex 2806b52e8..ea3586f9a 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 26a15d835..d00ec1461 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex b2c46061a..093344d26 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 36b0563e7..038a415ae 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex 500a5921a..5833ebc1d 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.15",+ "version": "0.6.16","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex b18b28713..8e5d34e27 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.15",+ "version": "0.6.16","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex ea830fae6..2eb682c9f 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.15",+ "version": "0.6.16","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex a78ef42f8..cc6e66ec9 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.15",+ "version": "0.6.16","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 899578aa0..ac864b113 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.15"+version = "0.6.16"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex d762ac7d9..e35c8c0f0 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -3164,7 +3164,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.15"+version = "0.6.16"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex cd7fc04c5..926bdc9b7 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.15"+version = "0.6.16"edition = "2021"publish = falsediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 1cdbf247b..e907c1566 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -57,7 +57,7 @@ Rules enforced on the inference path:- The inference hot path is queue-only. There is no direct-HTTP fallback. `src/handlers/proxy.rs` is the queue-submission handler despite its name.- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.-- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries with hashes unknown to the worker-sidecar, or logical pools that do not assign that worker, are NAKed before Python IPC.+- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries with hashes unknown to the worker-sidecar, or logical pools that do not assign that worker, are NAKed before backend IPC.- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`.- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.@@ -100,7 +100,7 @@ Ordering guarantees:NATS publish behavior:- One `ConfigNotification` message is published per affected bundle to `sie.config.models.{bundle_id}`, and a byte-identical copy to `sie.config.models._all`.-- Gateway code consumes `sie.config.models._all`. Worker-sidecar containers consume their bundle-scoped subject and forward accepted deltas to Python over IPC `ApplyModelConfig`.+- Gateway code consumes `sie.config.models._all`. Worker-sidecar containers consume their bundle-scoped subject and forward accepted deltas over backend IPC `ApplyModelConfig`.- If publish fails for a subset of bundles, `NatsPublisher` continues publishing to the remaining bundles and raises `PartialPublishError` at the end with the failed bundle list. The write itself is still durable on disk. The response `warnings` field names the failed bundles; gateway convergence is repaired by the poller/export path if `_all` is missed. Worker-sidecar convergence is repaired by the worker export reconciler when `SIE_CONFIG_SERVICE_URL` is set.Idempotency:@@ -224,7 +224,7 @@ Concurrency on the gateway's `ModelRegistry`:## 6. Worker-Ack Status (`GET /v1/configs/models/{id}/status`)-Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by Python IPC `ApplyModelConfig`, or after the worker export reconciler replaces the bundle-scoped Python registry view from `sie-config`.+Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by backend IPC `ApplyModelConfig`, or after the worker export reconciler replaces the bundle-scoped backend registry/catalog view from `sie-config`.Response shape:@@ -291,7 +291,7 @@ Per-subject transport:| Worker direct-dispatch | `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}` | JetStream | Worker-specific stream used by generation and by capped logical batch pools that must target an assigned worker instead of allowing unassigned workers on the same backing queue to burn JetStream delivery attempts. || Batch direct cancel | `batch_cancel.{router_id}.{worker_id}.{request_id}` | NATS Core | Best-effort worker-scoped signal emitted only after non-streaming worker-direct fallback publishes are durably acked on the pool subject. Sidecars ACK-drop queued worker-direct encode/score/extract items for the request; pool fallback items are never cancelled by this signal. || Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client may retry (the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5` — see §2). Result payload is msgpack. |-| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. |+| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (section 4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through backend IPC. || Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. || DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. || DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, memory storage, 24 h `max_age`) captures `sie.dlq.>`. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |@@ -672,7 +672,7 @@ adapters:- sie_server_rust.adapters.candle```-`ModelRegistry` maps a requested model/profile identity to a bundle by resolving the requested profile's `adapter_path` module, matching that module against each bundle's `adapters` list, then preferring the lowest-priority bundle in the match set. The base model id means the `default` profile; non-default profiles are routable as `base-model:profile` aliases. Models that are only available through the native Candle runtime use `default` with the Candle adapter, while `:candle` is reserved for side-by-side native variants of models that also have another default path:+`ModelRegistry` maps a requested model/profile identity to a bundle by resolving the requested profile's `adapter_path` module, matching that module against each bundle's `adapters` list, then preferring the lowest-priority bundle in the match set. The base model id means the `default` profile; non-default profiles are routable as `base-model:profile` aliases. Native Candle lanes use explicit `:candle` identities for both side-by-side variants and Candle-only models unless the product intentionally introduces a separate public alias:```Model: BAAI/bge-m3@@ -804,7 +804,7 @@ POST /v1/poolsHelm publishes canonical machine profiles in `SIE_GATEWAY_CONFIGURED_GPUS`, request aliases in `SIE_GATEWAY_GPU_ALIASES`, and optional deploy-owned static queue pools in `SIE_GATEWAY_STATIC_QUEUE_POOLS`.-Each physical queue pool gets its own JetStream stream (`WORK_POOL_{queue_pool}`) with subjects `sie.work.{queue_pool}.*.*.*`. Pool and queue-pool names are validated against `[A-Za-z0-9_-]` and canonicalized to lowercase at the API, gateway request, K8s restore/watch, and Helm render boundaries, so NATS subjects and KEDA labels do not split by case. Workers are deployed with `SIE_POOL={queue_pool}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{queue_pool}.{profile}.{bundle}.*` lane. A logical API pool names the tenant/workload boundary and carries `PoolSpec.queue_pool` to select the physical queue lane; omitted `queue_pool` means `default`. Helm's baseline default puts enabled worker groups in `SIE_POOL=default`, so SDK calls can pass just the machine profile (`gpu="l4"`) for shared-cluster capacity, and API-created pools can borrow that same base capacity with `gpu="pool/l4"`. Dedicated queue deployments override Helm `queuePool` and must declare the same name under `queueRouting.staticQueuePools` before API pools can use it as a non-default `queue_pool`; callers can target the protected static pool directly or create a differently named logical pool backed by that queue, for example `{"name":"customer-acme-workload","queue_pool":"customer-acme"}` plus SDK `gpu="customer-acme-workload/l4"`. A cold `X-SIE-POOL` request without `X-SIE-MACHINE-PROFILE` can emit lane-specific `pending_demand` only when the registered pool spec contains exactly one machine profile; multi-profile pools require the caller to send the profile because the gateway must not guess which StatefulSet KEDA should scale.+Each physical queue pool gets its own JetStream stream (`WORK_POOL_{queue_pool}`) with subjects `sie.work.{queue_pool}.*.*.*`. Pool and queue-pool names are validated against `[A-Za-z0-9_-]` and canonicalized to lowercase at the API, gateway request, K8s restore/watch, and Helm render boundaries, so NATS subjects and KEDA labels do not split by case. Workers are deployed with `SIE_POOL={queue_pool}`, `SIE_MACHINE_PROFILE={profile}`, and `SIE_BUNDLE={bundle}`; they consume only from their concrete `sie.work.{queue_pool}.{profile}.{bundle}.*` lane. A logical API pool names the tenant/workload boundary and carries `PoolSpec.queue_pool` to select the physical queue lane; omitted `queue_pool` means `default`. Helm's baseline default puts enabled worker groups in `SIE_POOL=default`, so SDK calls can pass just the machine profile (`gpu="l4"`) for shared-cluster capacity, and API-created pools can borrow that same base capacity with `gpu="pool/l4"`. Dedicated queue deployments override Helm `queuePool` and must declare the same name under `queueRouting.staticQueuePools` before API pools can use it as a non-default `queue_pool`; callers can target the protected static pool directly or create a differently named logical pool backed by that queue, for example `{"name":"customer-acme-workload","queue_pool":"customer-acme"}` plus SDK `gpu="customer-acme-workload/l4"`. A cold `X-SIE-POOL` request without `X-SIE-MACHINE-PROFILE` records lane-specific `pending_demand` for every machine profile the pool can provision. Multi-profile pool demand therefore wakes all candidate lanes from zero instead of relying on an empty `machine_profile` label that no per-lane KEDA ScaledObject can observe; once a capable worker registers, exact-lane demand clears and idle candidate lanes scale back down normally.A pool spec may also carry `minimum_worker_count` (a per-pool warm floor, default `0`). It keeps the first request from hitting a cold VM: every 30 seconds the gateway re-emits `sie_gateway_pool_warm_floor{pool,machine_profile,bundle}` for each backing queue lane the pool can name (clearing lanes that disappear), and a per-lane KEDA trigger reads it with `or vector(0)` so KEDA keeps machines warm. When multiple logical pools share one backing lane, the emitted value is the maximum requested floor for that physical lane, not a sum. Active lease capacity is labeled the same way. Default `0` emits nothing and leaves scale-from-zero unchanged.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex ceeb4bffd..0b32f897e 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -3005,7 +3005,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.15"+ "version": "0.6.16"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 4e2818076..b4bf76152 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -753,7 +753,7 @@ mod route_tests {}#[tokio::test]- async fn test_list_models_advertises_profile_only_candle_models_as_variants() {+ async fn test_list_models_advertises_profile_only_candle_variants() {let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;seed_profile_only_candle_model(&state, "acme/candle-only");diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 57cf01c71..6d4cdb92e 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -265,14 +265,17 @@ struct PoolLookup {/// Caller-pinned pools still probe the registry when a GPU is/// present so demand tracking can avoid spurious scale-up signals.exact_gpu_match: bool,- /// Concrete machine-profile label that should receive pending demand+ /// Concrete machine-profile labels that should receive pending demand/// even when the caller did not send `X-SIE-MACHINE-PROFILE`.///- /// This is populated only when route resolution can name a cold lane- /// safely (for example explicit pool+GPU, or a pool spec with exactly- /// one profile). KEDA queries are exact `pool/profile/bundle` matches,- /// so recording `machine_profile=""` does not scale a specific lane.- pending_demand_profile: Option<String>,+ /// KEDA queries are exact `pool/profile/bundle` matches, so recording+ /// `machine_profile=""` cannot scale a specific lane. When the caller+ /// pins a GPU we record that one profile; when a cold gpu-agnostic+ /// request cannot name one, we fan demand across every profile the pool+ /// can provision so each candidate cold lane can scale from zero (a+ /// capable one comes up and serves; the others reap on scale-down).+ /// Empty when a healthy worker already exists or no profile is known.+ pending_demand_profiles: Vec<String>,}/// Strict allowlist for caller-supplied pool names (`[A-Za-z0-9_-]`).@@ -345,10 +348,9 @@ async fn apply_model_pool_default(/// - If the caller pinned a pool via `X-SIE-Pool` and supplied a GPU,/// route only when a healthy worker exists in that exact lane. Otherwise/// return `Provisioning` and record pending demand for the pinned lane. If-/// they pinned only a pool, prefer a healthy worker to infer the concrete-/// machine-profile token; when none exists, use the pool spec only if it-/// contains exactly one machine profile so pending demand can still target a-/// concrete KEDA lane.+/// they pinned only a pool, use the pool's provisionable profiles for+/// pending-demand fan-out, probing a concrete cold lane only when the pool+/// has exactly one profile./// - Otherwise look up a healthy default-pool worker for `(bundle, gpu)`./// The worker must also report the gateway's expected bundle config hash./// If GPU was specified and the exact tuple has no worker, return@@ -375,7 +377,7 @@ async fn resolve_effective_pool(admission_pool: normalized_pool,demand_pool: DEFAULT_POOL_NAME.to_string(),exact_gpu_match: false,- pending_demand_profile: None,+ pending_demand_profiles: Vec::new(),};};// Caller pinned a pool. With the new subject shape, a pool-only@@ -385,15 +387,21 @@ async fn resolve_effective_pool(// retryable provisioning error until a healthy worker is present so// the gateway does not publish to a stream with no active consumer.if gpu.is_empty() {- let inferred_profile = infer_single_pool_profile(pool_manager, pool_name).await;- let lookup_gpu = inferred_profile.as_deref().unwrap_or("");+ let profiles = demand_profiles_for_pool(pool_manager, pool_name).await;+ // Probe the exact cold lane when the pool has a single profile;+ // otherwise probe profile-agnostically and let demand fan out.+ let lookup_gpu = if profiles.len() == 1 {+ profiles[0].as_str()+ } else {+ ""+ };let route = registry.resolve_queue_route_in_pool(bundle, lookup_gpu, &queue_pool, bundle_config_hash).await;- let pending_demand_profile = if route.is_none() {- inferred_profile+ let pending_demand_profiles = if route.is_none() {+ profiles} else {- None+ Vec::new()};return PoolLookup {resolution: match route {@@ -403,7 +411,7 @@ async fn resolve_effective_pool(admission_pool: normalize_pool_name(pool_name),demand_pool: queue_pool,exact_gpu_match: false,- pending_demand_profile,+ pending_demand_profiles,};}@@ -419,10 +427,10 @@ async fn resolve_effective_pool(admission_pool: normalize_pool_name(pool_name),demand_pool: queue_pool,exact_gpu_match,- pending_demand_profile: if exact_gpu_match {- None+ pending_demand_profiles: if exact_gpu_match {+ Vec::new()} else {- Some(gpu.to_string())+ vec![gpu.to_lowercase()]},};}@@ -438,19 +446,19 @@ async fn resolve_effective_pool(Some(route) => PoolResolution::Route(route),None => PoolResolution::Provisioning,};- let pending_demand_profile = if !gpu.is_empty() && !exact_gpu_match {- Some(gpu.to_string())+ let pending_demand_profiles = if !gpu.is_empty() && !exact_gpu_match {+ vec![gpu.to_lowercase()]} else if matches!(resolution, PoolResolution::Provisioning) {- infer_single_pool_profile(pool_manager, DEFAULT_POOL_NAME).await+ demand_profiles_for_pool(pool_manager, DEFAULT_POOL_NAME).await} else {- None+ Vec::new()};PoolLookup {resolution,admission_pool: DEFAULT_POOL_NAME.to_string(),demand_pool: DEFAULT_POOL_NAME.to_string(),exact_gpu_match,- pending_demand_profile,+ pending_demand_profiles,}}@@ -468,12 +476,14 @@ async fn queue_pool_for_request(manager.queue_pool_for_pool(&normalized).await}-async fn infer_single_pool_profile(+async fn demand_profiles_for_pool(pool_manager: Option<&PoolManager>,pool_name: &str,-) -> Option<String> {- let manager = pool_manager?;- manager.single_machine_profile_for_pool(pool_name).await+) -> Vec<String> {+ match pool_manager {+ Some(manager) => manager.demand_profiles_for_pool(pool_name).await,+ None => Vec::new(),+ }}fn provisioning_message(gpu: &str, bundle: &str) -> String {@@ -1369,10 +1379,10 @@ async fn proxy_request(// folds the demand-tracking probe ("was there an exact// (bundle, machine_profile) match?") into the same registry load it uses to pick a// route, so we don't make two registry route-resolution calls on the- // hot path. The `pending_demand_profile` field is what drives KEDA:- // it is set when the caller expressed a GPU preference but no- // exact-tuple worker was registered, or when a cold pool-only request- // can be mapped to a single machine profile from the pool spec.+ // hot path. The `pending_demand_profiles` field is what drives KEDA:+ // it holds the caller's GPU preference when no exact-tuple worker was+ // registered, or, for a cold gpu-agnostic request, every machine profile+ // the pool can provision so each candidate lane can scale from zero.let lookup = resolve_effective_pool(&state.registry,Some(&state.pool_manager),@@ -1384,8 +1394,8 @@ async fn proxy_request(.await;let demand_pool = lookup.demand_pool.clone();let admission_pool = lookup.admission_pool.clone();- let pending_demand_profile = lookup.pending_demand_profile.clone();- if let Some(profile) = pending_demand_profile.as_deref() {+ let pending_demand_profiles = lookup.pending_demand_profiles.clone();+ for profile in &pending_demand_profiles {state.demand_tracker.record(&demand_pool, profile, &bundle);}@@ -1396,11 +1406,11 @@ async fn proxy_request(return build_pool_not_found_response_for_surface(&pool, provisioning_surface);}PoolResolution::Provisioning => {- // If route resolution named a concrete cold lane, demand was- // recorded above with that machine-profile label. Otherwise keep+ // If route resolution named concrete cold lanes, demand was+ // recorded above with those machine-profile labels. Otherwise keep// the legacy empty/unknown-profile series for observability even// though KEDA cannot scale a lane without a profile token.- if pending_demand_profile.is_none() {+ if pending_demand_profiles.is_empty() {state.demand_tracker.record(&demand_pool, &gpu, &bundle);}return build_provisioning_response_for_surface(&gpu, &bundle, provisioning_surface);@@ -5149,8 +5159,8 @@ async fn resolve_generation_route(.await;let demand_pool = lookup.demand_pool.clone();let admission_pool = lookup.admission_pool.clone();- let pending_demand_profile = lookup.pending_demand_profile.clone();- if let Some(profile) = pending_demand_profile.as_deref() {+ let pending_demand_profiles = lookup.pending_demand_profiles.clone();+ for profile in &pending_demand_profiles {state.demand_tracker.record(&demand_pool, profile, bundle);}let effective_route = match lookup.resolution {@@ -5163,7 +5173,7 @@ async fn resolve_generation_route());}PoolResolution::Provisioning => {- if pending_demand_profile.is_none() {+ if pending_demand_profiles.is_empty() {state.demand_tracker.record(&demand_pool, &gpu, bundle);}return Err(build_openai_provisioning_response(&gpu, bundle));@@ -13486,7 +13496,30 @@ mod tests {let out = resolve_effective_pool(®, None, "default", "l4", "", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));+ assert_eq!(out.pending_demand_profiles, vec!["l4".to_string()]);+ }++ #[tokio::test]+ async fn test_resolve_effective_pool_lowercases_explicit_gpu_pending_demand_profiles() {+ // KEDA ScaledObject queries use lowercased machine_profile labels. Keep+ // explicit-GPU cold demand on that same label shape even when callers or+ // profile aliases pass mixed-case values through routing.+ let reg = pool_registry();++ let default_pool = resolve_effective_pool(®, None, "sglang", "RTX6000", "", "").await;+ assert_eq!(default_pool.resolution, PoolResolution::Provisioning);+ assert_eq!(+ default_pool.pending_demand_profiles,+ vec!["rtx6000".to_string()]+ );++ let pinned_pool =+ resolve_effective_pool(®, None, "sglang", "RTX6000", "tenant-a", "").await;+ assert_eq!(pinned_pool.resolution, PoolResolution::Provisioning);+ assert_eq!(+ pinned_pool.pending_demand_profiles,+ vec!["rtx6000".to_string()]+ );}#[tokio::test]@@ -13529,7 +13562,7 @@ mod tests {let out = resolve_effective_pool(®, None, "default", "", "my-bench", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile, None);+ assert!(out.pending_demand_profiles.is_empty());}#[tokio::test]@@ -13552,7 +13585,7 @@ mod tests {);assert_eq!(out.admission_pool, "customer-acme");assert_eq!(out.demand_pool, DEFAULT_POOL_NAME);- assert_eq!(out.pending_demand_profile, None);+ assert!(out.pending_demand_profiles.is_empty());assert!(!out.exact_gpu_match);}@@ -13572,11 +13605,14 @@ mod tests {let out = resolve_effective_pool(®, Some(&pm), "default", "", "my-bench", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));+ assert_eq!(out.pending_demand_profiles, vec!["l4".to_string()]);}#[tokio::test]- async fn test_resolve_effective_pool_does_not_guess_ambiguous_pool_profile() {+ async fn test_resolve_effective_pool_fans_out_demand_across_ambiguous_pool_profiles() {+ // A pool-only cold request cannot name one profile of a multi-profile+ // pool, so demand fans out to every profile (sorted) — each candidate+ // cold lane can then scale from zero and a capable one serves the work.let reg = pool_registry();let pm = PoolManager::new(vec!["l4".into(), "a100".into()]);let mut gpus = std::collections::HashMap::new();@@ -13589,7 +13625,30 @@ mod tests {let out = resolve_effective_pool(®, Some(&pm), "default", "", "my-bench", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile, None);+ assert_eq!(+ out.pending_demand_profiles,+ vec!["a100".to_string(), "l4".to_string()]+ );+ }++ #[tokio::test]+ async fn test_resolve_effective_pool_fans_out_default_pool_demand_when_gpu_agnostic() {+ // The scale-from-zero case from issue 1681: an unpinned, gpu-agnostic+ // request for a bundle the multi-profile default pool serves. The+ // default pool is implicit, so its cold lanes are the cluster's+ // configured profiles; with no worker yet, demand fans out to each so+ // every candidate lane can scale from zero and a capable one comes up.+ let reg = pool_registry();+ let pm = PoolManager::new(vec!["RTX6000".into(), "l4".into()]);++ let out = resolve_effective_pool(®, Some(&pm), "sglang", "", "", "").await;+ assert_eq!(out.resolution, PoolResolution::Provisioning);+ assert!(!out.exact_gpu_match);+ // Sorted + lowercased to match the KEDA machine_profile labels.+ assert_eq!(+ out.pending_demand_profiles,+ vec!["l4".to_string(), "rtx6000".to_string()]+ );}#[tokio::test]@@ -13604,7 +13663,7 @@ mod tests {let out = resolve_effective_pool(®, None, "default", "l4-spot", "my-bench", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));+ assert_eq!(out.pending_demand_profiles, vec!["l4-spot".to_string()]);}#[tokio::test]@@ -13663,7 +13722,7 @@ mod tests {assert_eq!(out.resolution, PoolResolution::Provisioning);assert_eq!(out.admission_pool, "tenant-l4");assert_eq!(out.demand_pool, DEFAULT_POOL_NAME);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));+ assert_eq!(out.pending_demand_profiles, vec!["l4".to_string()]);}#[tokio::test]@@ -13724,7 +13783,7 @@ mod tests {assert_eq!(out.resolution, PoolResolution::Provisioning);assert_eq!(out.admission_pool, "tenant-a");assert_eq!(out.demand_pool, "customer-queue");- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));+ assert_eq!(out.pending_demand_profiles, vec!["l4-spot".to_string()]);assert!(!out.exact_gpu_match);}@@ -13739,7 +13798,7 @@ mod tests {let out = resolve_effective_pool(®, None, "default", "l4", "my-bench", "").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4"));+ assert_eq!(out.pending_demand_profiles, vec!["l4".to_string()]);}#[tokio::test]@@ -13767,7 +13826,7 @@ mod tests {resolve_effective_pool(®, None, "default", "l4-spot", "my-bench", "new-hash").await;assert_eq!(out.resolution, PoolResolution::Provisioning);assert!(!out.exact_gpu_match);- assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));+ assert_eq!(out.pending_demand_profiles, vec!["l4-spot".to_string()]);}// ── grammar routing: dispatch vs display model ─────────────────diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rsindex 4a723eb1f..aa96258eb 100644--- a/packages/sie_gateway/src/state/pool_manager.rs+++ b/packages/sie_gateway/src/state/pool_manager.rs@@ -692,21 +692,38 @@ impl PoolManager {)}- /// Return the pool's only configured machine profile, if the spec is- /// unambiguous across both requirements (`gpus`) and admission caps- /// (`gpu_caps`). Used by cold queue routing when a caller pins only a- /// pool: the NATS subject still needs a concrete machine-profile token so- /// KEDA can observe `pending_demand{pool,machine_profile,bundle}`.- pub async fn single_machine_profile_for_pool(&self, pool_name: &str) -> Option<String> {- let pools = self.pools.read().await;- let key = pool_key_for_name(&pools, pool_name)?;- let pool = pools.get(&key)?;- let profiles = machine_profiles_for_pool(pool);- if profiles.len() == 1 {- profiles.into_iter().next()- } else {- None+ /// Every machine profile the pool can provision, sorted for a+ /// deterministic emit order. Used to fan pending demand across all cold+ /// lanes when a gpu-agnostic request cannot name a single profile: a+ /// pool serves every bundle from every profile it declares, so any of+ /// them may end up running the work, and KEDA must be able to observe+ /// `pending_demand{pool,machine_profile,bundle}` on each. Empty when the+ /// pool is unknown.+ pub async fn demand_profiles_for_pool(&self, pool_name: &str) -> Vec<String> {+ {+ let pools = self.pools.read().await;+ if let Some(key) = pool_key_for_name(&pools, pool_name) {+ if let Some(pool) = pools.get(&key) {+ let mut profiles = machine_profiles_for_pool(pool);+ profiles.sort();+ return profiles;+ }+ }+ }+ // The default pool is implicit (never stored in `pools`): its cold+ // lanes are the cluster's configured machine profiles. Lowercased to+ // match the KEDA `machine_profile` label the chart renders.+ if normalize_pool_name(pool_name) == DEFAULT_POOL_NAME {+ let mut profiles: Vec<String> = self+ .configured_profiles+ .iter()+ .map(|p| p.to_lowercase())+ .collect();+ profiles.sort();+ profiles.dedup();+ return profiles;}+ Vec::new()}pub async fn queue_pool_for_pool(&self, pool_name: &str) -> Option<String> {@@ -1107,7 +1124,7 @@ fn known_queue_pool_from_names(static_pool_names: &HashSet<String>, name: &str)/// Deduplicated, lowercased machine-profile set for a pool, taken from the/// union of `spec.gpus` (requirements) and `spec.gpu_caps` (admission caps).-/// This is the same set `single_machine_profile_for_pool` collapses to one;+/// This is the same set `demand_profiles_for_pool` fans pending demand across;/// the warm-floor emitter keeps all of them so each lane gets its own/// `sie_gateway_pool_warm_floor` series.pub(crate) fn machine_profiles_for_pool(pool: &Pool) -> Vec<String> {diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex c5a5ab9c8..9a00e519d 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.15"+version = "0.6.16"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/bundles/sglang-embedding.yaml b/packages/sie_server/bundles/sglang-embedding.yamlindex 64cb1782c..f89244a3b 100644--- a/packages/sie_server/bundles/sglang-embedding.yaml+++ b/packages/sie_server/bundles/sglang-embedding.yaml@@ -16,3 +16,13 @@ deps:xgrammar: '==0.1.32'outlines: '==0.1.11'llguidance: '>=0.7.11,<0.8.0'+ # ``sglang==0.5.10.post1`` metadata requires ``flash-attn-4>=4.0.0b4`` —+ # a pre-release-only requirement. PyPI's ``flash-attn-4`` also publishes a+ # stable ``0.0.1`` placeholder, which disables uv's "allow pre-releases+ # when a package has nothing but pre-releases" rule, so a resolution that+ # only names ``sglang`` is unsatisfiable (nightly quality-adapter 7B lanes+ # died on this for weeks — #1684). Declaring the dep here with an explicit+ # pre-release specifier re-enables pre-releases for exactly this package.+ # Runtime-inert for us: sglang's default attention backend is flashinfer;+ # fa4 only needs to be importable to satisfy the dependency.+ flash-attn-4: '==4.0.0b19'diff --git a/packages/sie_server/bundles/sglang.yaml b/packages/sie_server/bundles/sglang.yamlindex 3053ad603..d70680fc1 100644--- a/packages/sie_server/bundles/sglang.yaml+++ b/packages/sie_server/bundles/sglang.yaml@@ -72,6 +72,16 @@ deps:llguidance:version: '>=0.7.11,<0.8.0'marker: sys_platform == 'linux'+ # ``sglang==0.5.10.post1`` metadata requires ``flash-attn-4>=4.0.0b4``, which+ # is pre-release-only — and PyPI's ``flash-attn-4`` also carries a stable+ # ``0.0.1`` placeholder that disables uv's only-pre-releases allowance, so+ # resolving sglang without an explicit fa4 specifier is unsatisfiable+ # (#1684). The explicit pre-release pin re-enables pre-releases for exactly+ # this package. Runtime-inert: sglang defaults to its flashinfer backend and+ # never selects fa4 unless asked; the package only has to be importable.+ flash-attn-4:+ version: '==4.0.0b19'+ marker: sys_platform == 'linux'# Apple Silicon (Metal) generation. SGLang is CUDA-only, so on macOS the# SGLangGenerationAdapter.create_for_device swap serves generation via Apple's# MLX (mlx_lm.server) instead — this makes the same bundle resolve correctly ondiff --git a/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yamlindex 49d1b110b..d980dfc01 100644--- a/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3-Embedding-0.6B.yaml@@ -29,15 +29,3 @@ profiles:Instruct: {instruction}Query:{text}default_instruction: Given a web search query, retrieve relevant passages that answer the query- custom:- extends: default- adapter_options:- runtime:- pooling: last- normalize: true- query_template: |-- Instruct: {instruction}- Query:{text}- default_instruction: Given a web search query, retrieve relevant passages that answer the query- lora_id: gauravprasadgp/qwen3-embedding_0.6B_lora- instruction: Retrieve relevant informationdiff --git a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml b/packages/sie_server/models/intfloat__multilingual-e5-large.yamlindex e49daabdd..be75b9ab1 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-large.yaml@@ -35,6 +35,8 @@ profiles:runtime:pooling: meannormalize: true+ query_template: 'query: {text}'+ doc_template: 'passage: {text}'candle:extends: defaultadapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapterdiff --git a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yamlindex 05b479f11..a2dd9339c 100644--- a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml+++ b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml@@ -26,6 +26,7 @@ profiles:num_simhash_projections: 6projection_dim: 8final_projection_dim: null+ center_tokens: truetoken_dim: 128normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yamlindex f3ab578ec..8d5e6612b 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml@@ -26,6 +26,7 @@ profiles:num_simhash_projections: 6projection_dim: 8final_projection_dim: null+ center_tokens: truetoken_dim: 64normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/nvidia__NV-Embed-v2.yaml b/packages/sie_server/models/nvidia__NV-Embed-v2.yamlindex 96df7ca18..1b379cf52 100644--- a/packages/sie_server/models/nvidia__NV-Embed-v2.yaml+++ b/packages/sie_server/models/nvidia__NV-Embed-v2.yaml@@ -1,5 +1,9 @@sie_id: nvidia/NV-Embed-v2-hf_id: Hyukkyu/nv-embed-v2 # works with newer transformers version+# Mirror of nvidia/NV-Embed-v2 with transformers-5.x compatibility patches in+# modeling_nvembed.py (DynamicCache API, rotary position_embeddings). Verified+# 2026-07-06: weight files sha-identical to nvidia/NV-Embed-v2, configuration+# identical, modeling diff is compat-only; latent-attention stack intact (#1692).+hf_id: Hyukkyu/nv-embed-v2inputs:text: trueimage: false@@ -24,5 +28,19 @@ profiles:trust_remote_code: trueuses_legacy_transformers_cache: trueattn_implementation: eager+ # NV-Embed-v2's defining feature is latent-attention pooling with+ # instruction-masked mean + EOS append + right padding — none of which+ # the generic tokenize/forward/pool pipeline reproduces (calling the+ # forward without pool_mask returns the UNPOOLED latent sequence, which+ # was then last-token pooled: NFCorpus -17%, #1692). Delegate to the+ # checkpoint's own encode(prompts, instruction=...) instead. The+ # checkpoint's sentence-transformers chain is NOT an option: it predates+ # ST 5.x, whose Transformer module requires last_hidden_state in the+ # forward output while NVEmbedModel returns only sentence_embeddings.+ use_model_encode: trueruntime:normalize: true+ # Official NV-Embed query recipe; documents are encoded raw (no prefix).+ # The rendered prefix is passed as the model's `instruction`, so+ # is_mask_instruction excludes it from the pooling mean.+ query_template: "Instruct: {instruction}\nQuery: {text}"diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex 275a1cc60..4936b49a2 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.15"+ "version": "0.6.16"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex e13e65ce7..4c4caf923 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.15"+version = "0.6.16"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.pyindex 6042a1669..822ca6399 100644--- a/packages/sie_server/src/sie_server/_ipc_test_harness.py+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py@@ -20,6 +20,8 @@ The process exits on SIGINT / SIGTERM. All stubbed RPCs:* ``ProcessGenerate`` — when ``--fake-generate-model`` is set, streams``in_progress`` → ``publish`` → ``ack`` events through the IPC generationprotocol without loading a real generation adapter.+* ``SetPinnedModels`` — records the requested pinned set and returns the applied+ count so the sidecar pinned reconciler can exercise the IPC method.* ``Drain`` — handled by ``IpcServer`` itself."""@@ -42,6 +44,8 @@ from sie_server.ipc_types import (ProcessExtractBatchRequest,ProcessScoreBatchRequest,ReadinessState,+ SetPinnedModelsRequest,+ SetPinnedModelsResponse,)logger = logging.getLogger(__name__)@@ -87,7 +91,7 @@ class _StubRegistry:class _StubExecutor:"""Duck-typed replacement for :class:`sie_server.queue_executor.QueueExecutor`.- We only need the four methods ``IpcServer`` actually calls. The test asserts+ We only need the methods ``IpcServer`` actually calls. The test assertson the outcome shape, not on any real inference output.The optional ``per_request_delay_ms`` knob injects an ``asyncio.sleep`` at@@ -111,6 +115,7 @@ class _StubExecutor:self._batch_budget = batch_budgetself._descriptor = descriptorself._per_request_delay_ms = per_request_delay_ms+ self._pinned_models: frozenset[str] = frozenset()self.registry = _StubRegistry(generation_model, generation_hidden_polls)async def ensure_model_ready(self, model_id: str) -> ReadinessState: # noqa: ARG002@@ -125,6 +130,10 @@ class _StubExecutor:def loaded_model_names(self) -> list[str]:return []+ async def set_pinned_models(self, req: SetPinnedModelsRequest) -> SetPinnedModelsResponse:+ self._pinned_models = frozenset(model.strip() for model in req.models if model.strip())+ return SetPinnedModelsResponse(applied=True, pinned_count=len(self._pinned_models))+async def _maybe_sleep(self) -> None:if self._per_request_delay_ms > 0:await asyncio.sleep(self._per_request_delay_ms / 1000.0)diff --git a/packages/sie_server/src/sie_server/adapters/_flash_pack.py b/packages/sie_server/src/sie_server/adapters/_flash_pack.pyindex cc01464ec..54d2d4fb2 100644--- a/packages/sie_server/src/sie_server/adapters/_flash_pack.py+++ b/packages/sie_server/src/sie_server/adapters/_flash_pack.py@@ -38,3 +38,25 @@ def build_position_ids(cu_seqlens: torch.Tensor, *, offset: int = 0) -> torch.Teseq_starts = torch.repeat_interleave(cu_seqlens[:-1], cu_seqlens[1:] - cu_seqlens[:-1])positions = positions - seq_startsreturn positions + offset if offset else positions+++def mean_pool_packed(hidden: torch.Tensor, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:+ """Mean-pool each sequence of a varlen-packed hidden-state tensor.++ ``hidden`` is the flat ``[total_tokens, dim]`` output of a flash encoder;+ ``cu_seqlens`` (shape ``[num_seqs + 1]``) marks the packed sequence+ boundaries. Returns ``[num_seqs, dim]`` — each row the mean of one+ sequence's token vectors.++ This is the exact per-sequence loop the ``*_flash`` embedding adapters+ (nomic / rope / qwen2 / xlm_roberta) each carried inline, relocated here+ unchanged so a pooling fix lands once. Behaviour is bit-identical to the+ inline loops (same slice + ``mean(dim=0)`` + ``stack``); it is intentionally+ NOT vectorized so no adapter's numerics shift.+ """+ mean_embeddings = []+ for i in range(num_seqs):+ start = cu_seqlens[i].item()+ end = cu_seqlens[i + 1].item()+ mean_embeddings.append(hidden[start:end].mean(dim=0))+ return torch.stack(mean_embeddings)diff --git a/packages/sie_server/src/sie_server/adapters/_pylate_dense.py b/packages/sie_server/src/sie_server/adapters/_pylate_dense.pynew file mode 100644index 000000000..60f72f33c--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/_pylate_dense.py@@ -0,0 +1,259 @@+"""Shared pylate Dense-chain loading for ColBERT-style adapters.++pylate ColBERT checkpoints describe their projection head in ``modules.json``:+module 0 is the sentence-transformers ``Transformer`` backbone, and every later+module is a ``pylate.models.Dense.Dense`` whose weights live in+``<path>/model.safetensors`` under the single key ``linear.weight`` (shape+``[out_features, in_features]``). pylate's ``Dense.forward`` is literally+``self.linear(x)`` — it never applies the checkpoint's ``activation_function``+— so with ``bias: false`` / ``use_residual: false`` the whole head is the+sequential matmul ``hidden @ W0.T @ W1.T ...`` on the backbone's final-normed+``last_hidden_state``. This composition is proven bit-exact against official+pylate output in ``_poc/pylate-dense-chain/FINDINGS.md``. See #1680.++Any checkpoint whose modules.json is absent, has no Dense modules (e.g.+mxbai-colbert-large-v1 ships a Transformer-only modules.json), or declares math+this loader does not reproduce (bias, residual, non-Identity activation, dim+discontinuities) yields ``None`` so callers keep their existing behavior+(legacy projection probes / backbone truncation) — degrade, don't fail.+"""++from __future__ import annotations++import itertools+import json+import logging+from collections.abc import Sequence+from pathlib import Path+from typing import Any++import torch+from huggingface_hub import hf_hub_download+from safetensors.torch import load_file++logger = logging.getLogger(__name__)+++def _repo_file(model_name_or_path: str, rel: str) -> str | None:+ """Resolve a repo-relative file locally or via the HF hub; None if absent."""+ local = Path(model_name_or_path) / rel+ if local.is_file():+ return str(local)+ try:+ return hf_hub_download(model_name_or_path, rel)+ except Exception: # noqa: BLE001 - missing file/offline -> caller decides severity+ return None+++def load_pylate_dense_chain(+ model_name_or_path: str,+ *,+ hidden_size: int,+ token_dim: int,+ device: str | torch.device | None,+ dtype: torch.dtype,+) -> list[torch.Tensor] | None:+ """Load the trained pylate Dense chain for a checkpoint.++ Args:+ model_name_or_path: HuggingFace model ID or local path.+ hidden_size: Backbone hidden size; the first weight's in_features must+ match it.+ token_dim: Served token dimension; the last weight's out_features must+ match it (a head that does not land on token_dim degrades to+ truncation, preserving the old single-head semantics).+ device: Device to move the weights to.+ dtype: Dtype to cast the weights to.++ Returns:+ The chain weights in modules.json order, or None to signal the caller+ to fall back to its existing behavior (backbone truncation / legacy+ projection probes).+ """+ modules_path = _repo_file(model_name_or_path, "modules.json")+ if modules_path is None:+ # Normal for stanford-format ColBERT repos (no modules.json shipped).+ logger.debug("No modules.json for %s; no pylate Dense chain to load", model_name_or_path)+ return None++ try:+ parsed = json.loads(Path(modules_path).read_text())+ except (OSError, ValueError) as exc:+ logger.warning("Unparseable modules.json for %s; using backbone truncation (%s)", model_name_or_path, exc)+ return None+ modules: list[dict[str, Any]] = []+ if not isinstance(parsed, list) or not parsed:+ logger.warning("Malformed modules.json for %s; using backbone truncation", model_name_or_path)+ return None+ for entry in parsed:+ if not isinstance(entry, dict):+ logger.warning("Malformed modules.json for %s; using backbone truncation", model_name_or_path)+ return None+ modules.append(entry)++ modules.sort(key=lambda m: m.get("idx", 0))+ first_type = str(modules[0].get("type", ""))+ if not first_type.endswith("Transformer"):+ logger.warning(+ "modules.json for %s does not start with a Transformer module (got %s); using backbone truncation",+ model_name_or_path,+ first_type,+ )+ return None++ dense_modules: list[dict[str, Any]] = []+ for module in modules[1:]:+ module_type = str(module.get("type", ""))+ if module_type.rsplit(".", 1)[-1] != "Dense":+ logger.warning(+ "Unsupported module type %s in modules.json for %s; using backbone truncation",+ module_type,+ model_name_or_path,+ )+ return None+ dense_modules.append(module)++ if not dense_modules:+ # A Transformer-only modules.json is a healthy checkpoint layout+ # (e.g. mxbai-colbert-large-v1); the caller's existing probes apply.+ logger.debug("No Dense modules in modules.json for %s", model_name_or_path)+ return None++ weights: list[torch.Tensor] = []+ for module in dense_modules:+ rel_dir = str(module.get("path", ""))+ config_path = _repo_file(model_name_or_path, f"{rel_dir}/config.json")+ if config_path is None:+ logger.warning("Missing %s/config.json for %s; using backbone truncation", rel_dir, model_name_or_path)+ return None+ try:+ config = json.loads(Path(config_path).read_text())+ except (OSError, ValueError) as exc:+ logger.warning(+ "Unparseable %s/config.json for %s; using backbone truncation (%s)",+ rel_dir,+ model_name_or_path,+ exc,+ )+ return None+ if config.get("bias"):+ logger.warning(+ "Dense module %s has bias=true for %s; using backbone truncation", rel_dir, model_name_or_path+ )+ return None+ # Missing key == false (GTE-ModernColBERT's config has no use_residual key).+ if config.get("use_residual"):+ logger.warning(+ "Dense module %s has use_residual=true for %s; using backbone truncation",+ rel_dir,+ model_name_or_path,+ )+ return None+ # pylate's Dense.forward never applies activation_function, but+ # sentence-transformers' Dense.forward does — a non-Identity value means+ # the checkpoint was trained with math we would not reproduce: degrade.+ activation = config.get("activation_function")+ if activation is not None and str(activation).rsplit(".", 1)[-1] != "Identity":+ logger.warning(+ "Dense module %s has non-Identity activation_function=%s for %s; using backbone truncation",+ rel_dir,+ activation,+ model_name_or_path,+ )+ return None++ weights_path = _repo_file(model_name_or_path, f"{rel_dir}/model.safetensors")+ if weights_path is None:+ logger.warning(+ "Missing %s/model.safetensors for %s; using backbone truncation. "+ "If this checkpoint ships Dense modules (e.g. partial weight cache), embeddings are degraded.",+ rel_dir,+ model_name_or_path,+ )+ return None+ try:+ state = load_file(weights_path)+ except Exception as exc: # noqa: BLE001 - corrupt/partial Dense -> degrade, don't fail the load+ logger.warning(+ "Failed to read %s/model.safetensors for %s (%s); using backbone truncation",+ rel_dir,+ model_name_or_path,+ exc,+ )+ return None+ weight = state.get("linear.weight")+ if weight is None or weight.ndim != 2:+ logger.warning(+ "Dense module %s for %s has no 2D linear.weight (keys=%s); using backbone truncation",+ rel_dir,+ model_name_or_path,+ sorted(state.keys()),+ )+ return None+ if "linear.bias" in state:+ logger.warning(+ "Dense module %s for %s ships a linear.bias tensor; using backbone truncation",+ rel_dir,+ model_name_or_path,+ )+ return None+ expected_shape = (config.get("out_features"), config.get("in_features"))+ if tuple(weight.shape) != expected_shape:+ logger.warning(+ "Dense module %s weight shape %s != config (out, in)=%s for %s; using backbone truncation",+ rel_dir,+ tuple(weight.shape),+ expected_shape,+ model_name_or_path,+ )+ return None+ weights.append(weight)++ # Shape-guard the chain ends plus adjacency: the first hop must consume the+ # backbone hidden size, every hop must consume the previous hop's output,+ # and the last hop must land exactly on token_dim (preserving the old+ # single-head semantics: a head not landing on token_dim degrades to+ # truncation, as today).+ if weights[0].shape[1] != hidden_size:+ logger.warning(+ "Dense chain in_features=%d != model hidden_size=%d for %s; using backbone truncation",+ weights[0].shape[1],+ hidden_size,+ model_name_or_path,+ )+ return None+ for prev, nxt in itertools.pairwise(weights):+ if nxt.shape[1] != prev.shape[0]:+ logger.warning(+ "Dense chain dimension discontinuity (%d -> %d) for %s; using backbone truncation",+ prev.shape[0],+ nxt.shape[1],+ model_name_or_path,+ )+ return None+ if weights[-1].shape[0] != token_dim:+ logger.warning(+ "Dense chain out_features=%d != token_dim=%d for %s; using backbone truncation",+ weights[-1].shape[0],+ token_dim,+ model_name_or_path,+ )+ return None++ logger.info(+ "Loaded pylate Dense chain for %s: %s",+ model_name_or_path,+ [tuple(w.shape) for w in weights],+ )+ return [w.to(device=device, dtype=dtype) for w in weights]+++def apply_dense_chain(hidden: torch.Tensor, chain: Sequence[torch.Tensor]) -> torch.Tensor:+ """Apply the Dense chain: ``hidden @ W0.T @ W1.T ...`` in order.++ Works for 2D packed ``[tokens, hidden]`` and 3D padded+ ``[batch, seq, hidden]`` inputs (plain matmul broadcasting).+ """+ for weight in chain:+ hidden = hidden @ weight.T+ return hiddendiff --git a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert/__init__.pyindex 953d41e5f..a1d50b6d7 100644--- a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py@@ -27,6 +27,7 @@ See: https://github.com/stanford-futuredata/ColBERTfrom __future__ import annotationsimport logging+import stringfrom typing import TYPE_CHECKING, Any, castimport torch@@ -35,6 +36,7 @@ from torch.nn import functionalfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._multivector import maxsim_scores_batched+from sie_server.adapters._pylate_dense import apply_dense_chain, load_pylate_dense_chainfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters._utils import grouped_score_pairs@@ -76,7 +78,7 @@ class ColBERTAdapter(BaseAdapter):spec = AdapterSpec(inputs=("text",),outputs=("multivector", "score"),- unload_fields=("_model", "_tokenizer", "_linear", "_actual_token_dim"),+ unload_fields=("_model", "_tokenizer", "_linear", "_actual_token_dim", "_dense_chain"),)def __init__(@@ -94,6 +96,7 @@ class ColBERTAdapter(BaseAdapter):doc_prefix: str = "",use_native_attention: bool | None = None,query_expansion: bool = True,+ doc_punctuation_skiplist: bool = True,muvera_config: dict[str, Any] | None = None,**kwargs: Any,) -> None:@@ -118,6 +121,10 @@ class ColBERTAdapter(BaseAdapter):query_expansion: Whether to pad queries with MASK tokens to query_max_length.This is a core ColBERT feature where MASK tokens become additional"virtual" query tokens. Default: True.+ doc_punctuation_skiplist: Whether to remove punctuation tokens from+ document multivectors (pylate applies a punctuation skiplist to+ document embeddings; disable to match a serving path that does+ not). Default: True.muvera_config: MUVERA configuration dict with keys like num_repetitions,num_simhash_projections, normalize. Used for FDE postprocessing.**kwargs: Additional arguments (ignored, for compatibility).@@ -135,11 +142,13 @@ class ColBERTAdapter(BaseAdapter):self._doc_prefix = doc_prefixself._use_native_attention = use_native_attentionself._query_expansion = query_expansion+ self._doc_punctuation_skiplist = doc_punctuation_skiplistself._muvera_config = muvera_configself._model: PreTrainedModel | None = Noneself._tokenizer: PreTrainedTokenizerFast | None = Noneself._linear: torch.nn.Linear | None = None+ self._dense_chain: list[torch.Tensor] | None = Noneself._device: str | None = Noneself._actual_token_dim: int | None = Noneself._is_cuda: bool = False # Set during load()@@ -214,18 +223,19 @@ class ColBERTAdapter(BaseAdapter):# ``skiplist_words = string.punctuation``). Document token embeddings# whose token ID is in this set are removed before returning# multivectors, preventing punctuation from participating in MaxSim.- import string-- skiplist_ids: set[int] = set()- for ch in string.punctuation:- ids = self._tokenizer.encode(ch, add_special_tokens=False)- skiplist_ids.update(ids)- self._doc_skiplist_ids = skiplist_ids- logger.info(- "Built document skiplist with %d token IDs from %d punctuation chars",- len(skiplist_ids),- len(string.punctuation),- )+ if self._doc_punctuation_skiplist:+ skiplist_ids: set[int] = set()+ for ch in string.punctuation:+ ids = self._tokenizer.encode(ch, add_special_tokens=False)+ skiplist_ids.update(ids)+ self._doc_skiplist_ids = skiplist_ids+ logger.info(+ "Built document skiplist with %d token IDs from %d punctuation chars",+ len(skiplist_ids),+ len(string.punctuation),+ )+ else:+ logger.info("Document punctuation skiplist disabled (doc_punctuation_skiplist=False)")# Determine whether to use native attention or manual flash attentionconfig = AutoConfig.from_pretrained(@@ -235,12 +245,18 @@ class ColBERTAdapter(BaseAdapter):self._native_mode = self._is_cuda and self._should_use_native_mode(config)if self._native_mode:- # Use model's native forward with flash_attention_2- logger.info("Using native attention mode (model has built-in flash attention)")+ # Use model's native forward with flash_attention_2, or sdpa when+ # flash-attn is unavailable (exactly the situation that selects the+ # ColBERTAdapter fallback for e.g. ModernBERT on pre-Ampere CUDA).+ # Import lazily to avoid circular deps (core.inference -> core.loader -> base)+ from sie_server.core.inference import is_flash_attention_available++ attn_impl = "flash_attention_2" if is_flash_attention_available(device) else "sdpa"+ logger.info("Using native attention mode with attn_implementation=%s", attn_impl)self._model = AutoModel.from_pretrained(self._model_name_or_path,torch_dtype=dtype,- attn_implementation="flash_attention_2",+ attn_implementation=attn_impl,trust_remote_code=True,)else:@@ -264,13 +280,31 @@ class ColBERTAdapter(BaseAdapter):self._model.to(device)self._model.eval()+ # Probe the trained pylate Dense chain first (#1680). When a checkpoint+ # ships one it IS the projection head, so the legacy probes must not+ # run; the loader returns None for a missing modules.json AND for a+ # Dense-less modules.json (e.g. mxbai-colbert-large-v1), so every+ # checkpoint without a chain falls through to the exact same probes.+ self._dense_chain = load_pylate_dense_chain(+ self._model_name_or_path,+ hidden_size=self._model.config.hidden_size,+ token_dim=self._token_dim,+ device=self._device,+ dtype=dtype,+ )# Check for linear projection layer (ColBERT-specific)# Different ColBERT implementations use different names- self._linear = self._find_projection_layer()+ self._linear = None if self._dense_chain is not None else self._find_projection_layer()# Determine actual output dimensionhidden_size = self._model.config.hidden_size- if self._linear is not None:+ if self._dense_chain is not None:+ self._actual_token_dim = self._dense_chain[-1].shape[0]+ logger.info(+ "ColBERT pylate Dense chain: %s",+ [tuple(w.shape) for w in self._dense_chain],+ )+ elif self._linear is not None:self._actual_token_dim = self._linear.out_featureslogger.info("ColBERT projection: %d -> %d",@@ -305,6 +339,12 @@ class ColBERTAdapter(BaseAdapter):if self._use_native_attention is not None:return self._use_native_attention+ # ModernBERT requires native mode (the manual flash loop is BERT-only:+ # it iterates model.encoder.layer, which ModernBERT does not have)+ if getattr(config, "model_type", None) == "modernbert":+ logger.info("Detected ModernBERT architecture, using native mode (manual flash loop is BERT-only)")+ return True+# Auto-detect based on model config# Rotary embeddings require native mode (our manual loop doesn't support them)if getattr(config, "position_embedding_type", None) == "rotary":@@ -613,8 +653,11 @@ class ColBERTAdapter(BaseAdapter):outputs = self._model(**batch)hidden = outputs.last_hidden_state # [batch, seq_len, hidden_size]- # Apply projection layer if present, or Matryoshka truncation- if self._linear is not None:+ # Apply the trained pylate Dense chain if present, else the single+ # projection layer, else Matryoshka truncation+ if self._dense_chain is not None:+ hidden = apply_dense_chain(hidden, self._dense_chain)+ elif self._linear is not None:hidden = self._linear(hidden)elif self._actual_token_dim is not None and self._actual_token_dim < hidden.shape[-1]:hidden = hidden[:, :, : self._actual_token_dim]@@ -633,14 +676,16 @@ class ColBERTAdapter(BaseAdapter):input_ids = batch["input_ids"]for i in range(len(texts)):- if is_query:- # Queries: keep ALL tokens (matches PyLate: "we do not- # want to prune expansion tokens in queries even if we+ if is_query and use_expansion:+ # Expanded queries: keep ALL tokens (matches PyLate: "we do+ # not want to prune expansion tokens in queries even if we# do not attend to them in attention layers")seq_hidden = hidden[i]seq_ids = input_ids[i]else:- # Documents: use attention_mask to drop real PAD tokens+ # Documents and non-expanded queries: use attention_mask to+ # drop real PAD tokens (without expansion, PAD rows carry+ # no semantics and must not leak into the multivectors)mask = attention_mask[i].bool()seq_hidden = hidden[i][mask]seq_ids = input_ids[i][mask]@@ -740,8 +785,11 @@ class ColBERTAdapter(BaseAdapter):# Run transformer layers with flash attentionhidden = self._run_transformer_flash(hidden, cu_seqlens, max_seqlen, total_tokens)- # Apply projection layer if present- if self._linear is not None:+ # Apply the trained pylate Dense chain if present, else the single+ # projection layer+ if self._dense_chain is not None:+ hidden = apply_dense_chain(hidden, self._dense_chain)+ elif self._linear is not None:hidden = self._linear(hidden)# L2 normalizediff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.pyindex 1b159f295..1de2a045d 100644--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py@@ -1,6 +1,7 @@from __future__ import annotationsimport logging+from pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVarimport torch@@ -9,6 +10,7 @@ from torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapterfrom sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._multivector import maxsim_scores_batched+from sie_server.adapters._pylate_dense import apply_dense_chain, load_pylate_dense_chainfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters._utils import apply_rotary_pos_emb, grouped_score_pairs, validate_output_types@@ -17,8 +19,6 @@ from sie_server.core.inference_output import EncodeOutput, ScoreOutputfrom sie_server.types.inputs import Itemif TYPE_CHECKING:- from pathlib import Path-import numpy as npfrom transformers import PreTrainedTokenizerFast@@ -34,19 +34,33 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):"""ColBERT adapter for ModernBERT with RoPE and Flash Attention 2 varlen.This adapter eliminates padding waste by packing sequences and using- flash_attn_varlen_func. Supports ModernBERT architecture with Rotary- Position Embeddings and Matryoshka dimension truncation.+ flash_attn_varlen_func. Mirrors the ModernBERT forward faithfully:+ local/global attention alternation (per-layer sliding window + rope theta),+ final_norm, and the trained pylate Dense chain when the checkpoint ships+ one (falling back to Matryoshka truncation otherwise). See #1680.Works with ModernBERT-based ColBERT models (GTE-ModernColBERT, Reason-ModernColBERT,mxbai-edge-colbert)."""fallback_adapter_path: ClassVar[str | None] = "colbert:ColBERTAdapter"+ # Align the fallback with this adapter's faithful serving of the ModernBERT+ # ColBERT trio: no query expansion (their checkpoints set+ # do_query_expansion: false), no document punctuation skiplist (this flash+ # path applies none), and the flash default max_seq_length (ColBERTAdapter+ # defaults to 512). Applies ONLY to fallback instances created for models+ # configured with this adapter, never to models whose YAML names+ # colbert:ColBERTAdapter directly.+ fallback_kwargs_overrides: ClassVar[dict[str, Any]] = {+ "query_expansion": False,+ "doc_punctuation_skiplist": False,+ "max_seq_length": 8192,+ }spec = AdapterSpec(inputs=("text",),outputs=("multivector", "score"),- unload_fields=("_model", "_tokenizer"),+ unload_fields=("_model", "_tokenizer", "_dense_chain"),)def __init__(@@ -96,6 +110,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):self._model: Any = Noneself._tokenizer: PreTrainedTokenizerFast | None = Noneself._device: str | None = None+ self._dense_chain: list[torch.Tensor] | None = Nonedef load(self, device: str) -> None:"""Load the model onto the specified device.@@ -109,7 +124,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):if not device.startswith("cuda"):raise RuntimeError(_ERR_CPU_NOT_SUPPORTED)- from transformers import AutoModel, AutoTokenizer+ from transformers import AutoModelself._device = devicedtype = self._resolve_dtype()@@ -121,10 +136,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):dtype,)- self._tokenizer = AutoTokenizer.from_pretrained(- self._model_name_or_path,- trust_remote_code=True,- )+ self._tokenizer = self._load_tokenizer()# Load model with eager attention - we handle flash attention manuallyself._model = AutoModel.from_pretrained(@@ -136,12 +148,53 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):self._model.to(device)self._model.eval()+ self._dense_chain = load_pylate_dense_chain(+ self._model_name_or_path,+ hidden_size=self._model.config.hidden_size,+ token_dim=self._token_dim,+ device=self._device,+ dtype=dtype,+ )+ if self._dense_chain is None:+ logger.warning(+ "No usable pylate Dense chain for %s; using backbone truncation. "+ "If this checkpoint ships Dense modules (e.g. partial weight cache), embeddings are degraded.",+ self._model_name_or_path,+ )+logger.info(- "ColBERT ModernBERT: hidden=%d, token_dim=%d (Matryoshka truncation)",+ "ColBERT ModernBERT: hidden=%d, token_dim=%d, dense_chain=%s",self._model.config.hidden_size,self._token_dim,+ None if self._dense_chain is None else [tuple(w.shape) for w in self._dense_chain],)+ def _load_tokenizer(self) -> PreTrainedTokenizerFast:+ """Load the tokenizer, tolerating checkpoints saved by newer transformers.++ Some ModernBERT ColBERT checkpoints (e.g. topk-io/Iso-ModernColBERT) are+ saved by transformers>=5 and declare a tokenizer_class this transformers+ version cannot resolve (e.g. "TokenizersBackend"). These ship a standard+ fast tokenizer, so fall back to PreTrainedTokenizerFast, which is+ byte-equivalent to AutoTokenizer for the fast-tokenizer checkpoints this+ adapter serves.+ """+ from transformers import AutoTokenizer, PreTrainedTokenizerFast++ try:+ return AutoTokenizer.from_pretrained(+ self._model_name_or_path,+ trust_remote_code=True,+ )+ except (ValueError, KeyError) as exc:+ logger.warning(+ "AutoTokenizer could not resolve the tokenizer class for %s (%s); "+ "falling back to PreTrainedTokenizerFast",+ self._model_name_or_path,+ exc,+ )+ return PreTrainedTokenizerFast.from_pretrained(self._model_name_or_path)+def _resolve_dtype(self) -> torch.dtype:"""Resolve compute dtype (default: bfloat16)."""dtype_map = {@@ -151,6 +204,18 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):}return dtype_map.get(self._compute_precision, torch.bfloat16)+ def _project(self, hidden: torch.Tensor) -> torch.Tensor:+ """Apply the trained pylate Dense chain if available, then Matryoshka-truncate+ to token_dim. Dimension-preserving: output is always token_dim wide.++ The trailing truncation is the whole projection when the chain is absent+ and a no-op when it is present (the chain loader guarantees the chain+ ends at token_dim).+ """+ if self._dense_chain is not None:+ hidden = apply_dense_chain(hidden, self._dense_chain)+ return hidden[:, : self._token_dim]+def encode(self,items: list[Item],@@ -213,14 +278,30 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):# Run embeddingshidden = self._run_embeddings(input_ids_packed)- # Get RoPE cos/sin values- cos, sin = self._compute_rope(position_ids_packed)+ # Pre-compute RoPE cos/sin for global and local layers+ global_cos, global_sin = self._compute_rope(position_ids_packed, use_global=True)+ local_cos, local_sin = self._compute_rope(position_ids_packed, use_global=False)# Run transformer layers with flash attention and RoPE- hidden = self._run_transformer_flash(hidden, cu_seqlens, max_seqlen, total_tokens, cos, sin)+ hidden = self._run_transformer_flash(+ hidden,+ cu_seqlens,+ max_seqlen,+ total_tokens,+ global_cos,+ global_sin,+ local_cos,+ local_sin,+ )++ # Apply final layer norm (ModernBERT has a final_norm after all layers);+ # the trained Dense projection was fit on final-normed activations.+ if hasattr(self._model, "final_norm"):+ hidden = self._model.final_norm(hidden)- # Matryoshka truncation: take first token_dim dimensions- hidden = hidden[:, : self._token_dim]+ # Apply the trained pylate Dense chain (if the checkpoint ships one)+ # then Matryoshka-truncate to token_dim; see #1680.+ hidden = self._project(hidden)# L2 normalizeif self._normalize:@@ -298,27 +379,40 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):"""Build position IDs for packed sequences."""return build_position_ids(cu_seqlens)- def _compute_rope(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ def _compute_rope(+ self,+ position_ids: torch.Tensor,+ *,+ use_global: bool = True,+ ) -> tuple[torch.Tensor, torch.Tensor]:"""Compute RoPE cos/sin values for packed positions.+ ModernBERT uses different rope_theta values for global vs local attention+ layers: ``global_rope_theta`` (default 160000) for global layers and+ ``local_rope_theta`` (default 10000) for local (sliding-window) layers.++ Args:+ position_ids: Packed position IDs [total_tokens].+ use_global: If True, use global_rope_theta; otherwise local_rope_theta.+Returns:cos, sin tensors of shape [total_tokens, head_dim]."""head_dim = self._model.config.hidden_size // self._model.config.num_attention_heads+ cfg = self._model.config++ if use_global:+ base = getattr(cfg, "global_rope_theta", getattr(cfg, "rope_theta", 160000.0))+ else:+ base = getattr(cfg, "local_rope_theta", getattr(cfg, "rope_theta", 10000.0))- # ModernBERT uses rope_theta for base frequency- base = getattr(self._model.config, "rope_theta", 160000.0)inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=self._device).float() / head_dim))- # Compute sin/cos for all positionspos = position_ids.float()freqs = torch.outer(pos, inv_freq) # [total_tokens, head_dim/2]emb = torch.cat([freqs, freqs], dim=-1) # [total_tokens, head_dim]- cos = emb.cos()- sin = emb.sin()-- return cos.to(self._resolve_dtype()), sin.to(self._resolve_dtype())+ return emb.cos().to(self._resolve_dtype()), emb.sin().to(self._resolve_dtype())def _run_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:"""Compute embeddings for packed input (no position embeddings - RoPE in attention)."""@@ -339,22 +433,37 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):cu_seqlens: torch.Tensor,max_seqlen: int,total_tokens: int,- cos: torch.Tensor,- sin: torch.Tensor,+ global_cos: torch.Tensor,+ global_sin: torch.Tensor,+ local_cos: torch.Tensor,+ local_sin: torch.Tensor,) -> torch.Tensor:"""Run transformer layers using flash_attn_varlen_func with RoPE.- ModernBERT uses pre-norm architecture with local/global attention patterns.- We use global attention for all layers (no window restriction).+ ModernBERT uses pre-norm architecture with local/global attention+ patterns. Every ``global_attn_every_n_layers``-th layer (0-indexed)+ uses full (global) attention with ``global_rope_theta``; the remaining+ layers use sliding-window (local) attention of size+ ``local_attention`` with ``local_rope_theta``."""from flash_attn import flash_attn_varlen_func- num_heads = self._model.config.num_attention_heads- hidden_size = self._model.config.hidden_size+ cfg = self._model.config+ num_heads = cfg.num_attention_heads+ hidden_size = cfg.hidden_sizehead_dim = hidden_size // num_headssoftmax_scale = 1.0 / (head_dim**0.5)- for layer in self._model.layers:+ global_every_n = getattr(cfg, "global_attn_every_n_layers", 1)+ local_window = getattr(cfg, "local_attention", -1)+ # flash_attn_varlen_func expects window_size as (left, right) tuple+ window = (local_window // 2, local_window // 2) if local_window > 0 else (-1, -1)++ for layer_idx, layer in enumerate(self._model.layers):+ is_global = (layer_idx % global_every_n == 0) if global_every_n > 1 else True+ cos = global_cos if is_global else local_cos+ sin = global_sin if is_global else local_sin+# Pre-attention norm (ModernBERT is pre-norm)normed_hidden = layer.attn_norm(hidden)@@ -365,11 +474,15 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):key = qkv[:, 1]value = qkv[:, 2]- # Apply RoPE to Q and K+ # Apply RoPE to Q and K (using layer-appropriate theta)query, key = apply_rotary_pos_emb(query, key, cos, sin)- # Flash attention with variable-length sequences- # Note: We use global attention (no window_size) for simplicity+ # Flash attention — global layers use full attention,+ # local layers use sliding window+ attn_kwargs: dict[str, Any] = {}+ if not is_global and local_window > 0:+ attn_kwargs["window_size"] = window+attn_out = flash_attn_varlen_func(query,key,@@ -380,6 +493,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):max_seqlen_k=max_seqlen,causal=False,softmax_scale=softmax_scale,+ **attn_kwargs,)attn_out = attn_out.reshape(total_tokens, hidden_size)diff --git a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.pyindex 56a5bea19..75100f6db 100644--- a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py@@ -9,7 +9,7 @@ import torch.nn.functional as Ffrom torch import nnfrom sie_server.adapters._flash_base import FlashBaseAdapter-from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._flash_pack import build_position_ids, mean_pool_packedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types@@ -523,12 +523,7 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):cls_embeddings.append(hidden[start])pooled = torch.stack(cls_embeddings)else: # mean pooling- mean_embeddings = []- for i in range(num_seqs):- start = cu_seqlens[i].item()- end = cu_seqlens[i + 1].item()- mean_embeddings.append(hidden[start:end].mean(dim=0))- pooled = torch.stack(mean_embeddings)+ pooled = mean_pool_packed(hidden, cu_seqlens, num_seqs)if normalize:pooled = F.normalize(pooled, p=2, dim=-1)diff --git a/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.pyindex 1d92efcc8..557539131 100644--- a/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py@@ -97,6 +97,7 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):default_instruction: str | None = None,forward_kwargs: dict[str, Any] | None = None,uses_legacy_transformers_cache: bool = False,+ use_model_encode: bool = False,dense_dim: int | None = None,) -> None:r"""Initialize the adapter.@@ -134,6 +135,14 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):uses_legacy_transformers_cache: If True, disable the KV cache afterloading by setting model.config.use_cache = False. Required formodels that use the legacy transformers cache API (pre-4.54).+ use_model_encode: If True, delegate encoding to the checkpoint's own+ ``model.encode(prompts, instruction=...)`` method instead of the+ generic tokenize/forward/pool pipeline. For models whose recipe+ is not reproducible generically — e.g. NV-Embed-v2's instruction+ prepend + EOS append, right padding, and internal+ latent-attention pooling with instruction tokens masked out+ (#1692). The query/doc template's prefix (everything before+ ``{text}``) is rendered and passed as the ``instruction``.dense_dim: Catalog-declared dense embedding dimension. If provided,validated against the loaded model's hidden size."""@@ -150,6 +159,7 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):self._default_instruction = default_instructionself._forward_kwargs = forward_kwargs or {}self._uses_legacy_transformers_cache = uses_legacy_transformers_cache+ self._use_model_encode = use_model_encodeself._configured_dense_dim = dense_dimself._model: PreTrainedModel | None = None@@ -296,6 +306,17 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):)raise ValueError(msg)+ if self._use_model_encode:+ return self._encode_via_model(+ items,+ instruction,+ is_query=is_query,+ query_template=query_template,+ doc_template=doc_template,+ default_instruction=default_instruction,+ normalize=normalize,+ )+texts = self._format_texts(items,instruction,@@ -383,6 +404,70 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):msg = f"Unsupported output types: {unsupported}. This model only supports 'dense'."raise ValueError(msg)+ def _encode_via_model(+ self,+ items: list[Item],+ instruction: str | None,+ *,+ is_query: bool,+ query_template: str | None,+ doc_template: str | None,+ default_instruction: str | None,+ normalize: bool,+ ) -> EncodeOutput:+ r"""Delegate the whole batch to the checkpoint's own ``encode()``.++ Models like NV-Embed-v2 ship an ``encode(prompts, instruction=...)``+ that reproduces their published recipe end-to-end: instruction+ prepend + EOS append, right padding, and internal latent-attention+ pooling with instruction tokens masked out of the mean. The generic+ tokenize/forward/pool pipeline cannot reproduce that (calling the+ forward without ``pool_mask`` yields the *unpooled* latent sequence+ — the #1692 fidelity gap), so this path hands the raw texts and the+ rendered template prefix to the model and only normalizes on top.+ """+ model_encode = getattr(self._model, "encode", None)+ if not callable(model_encode):+ msg = (+ f"use_model_encode is set but {type(self._model).__name__} has no "+ "callable .encode() — remove the option or fix the checkpoint."+ )+ raise RuntimeError(msg)++ template = query_template if is_query else doc_template+ if template:+ if not template.endswith("{text}"):+ msg = (+ "use_model_encode requires a '<prefix>{text}'-shaped template "+ f"(the prefix is passed as the model's instruction); got {template!r}"+ )+ raise ValueError(msg)+ instr = instruction or default_instruction or ""+ prefix = template.format(instruction=instr, text="")+ else:+ # Mirror _format_texts' no-template fallback: a caller-provided+ # instruction is still honored (model.encode prepends and masks it).+ prefix = instruction or ""++ texts = []+ for item in items:+ if item.text is None:+ raise ValueError(ERR_REQUIRES_TEXT.format(adapter_name="PyTorchEmbeddingAdapter"))+ texts.append(item.text)++ with torch.inference_mode():+ embeddings = model_encode(texts, instruction=prefix, max_length=self._max_seq_length)+ if normalize:+ embeddings = functional.normalize(embeddings, p=2, dim=-1)++ embeddings_np = embeddings.float().cpu().numpy()+ return EncodeOutput(+ dense=embeddings_np,+ batch_size=len(items),+ is_query=is_query,+ dense_dim=self._dense_dim,+ )+def _format_texts(self,items: list[Item],diff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.pyindex 67492311c..bdbe8dc03 100644--- a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py@@ -9,7 +9,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter-from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._flash_pack import build_position_ids, mean_pool_packedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types@@ -476,13 +476,7 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):# Vectorized: extract last token of each sequencepooled = hidden[(cu_seqlens[1:] - 1).long()]else: # mean pooling- num_seqs = len(seq_lengths)- mean_embeddings = []- for i in range(num_seqs):- start = cu_seqlens[i].item()- end = cu_seqlens[i + 1].item()- mean_embeddings.append(hidden[start:end].mean(dim=0))- pooled = torch.stack(mean_embeddings)+ pooled = mean_pool_packed(hidden, cu_seqlens, len(seq_lengths))if self._dense_projection is not None:pooled = self._dense_projection(pooled)diff --git a/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.pyindex 92b86c092..9d7e23165 100644--- a/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/rope_flash/__init__.py@@ -8,6 +8,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import mean_pool_packedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types@@ -387,12 +388,7 @@ class RoPEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):pooled = torch.stack(cls_embeddings)else: # mean pooling# Average all tokens- mean_embeddings = []- for i in range(num_seqs):- start = cu_seqlens[i].item()- end = cu_seqlens[i + 1].item()- mean_embeddings.append(hidden[start:end].mean(dim=0))- pooled = torch.stack(mean_embeddings)+ pooled = mean_pool_packed(hidden, cu_seqlens, num_seqs)if normalize:pooled = functional.normalize(pooled, p=2, dim=-1)diff --git a/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.pyindex 6b77c23b7..3aaa2bd9b 100644--- a/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/splade_flash/__init__.py@@ -27,7 +27,17 @@ _Arch = Literal["bert", "roberta", "distilbert"]def _has_flash_attn() -> bool:- return importlib.util.find_spec("flash_attn") is not None+ # A bare find_spec check is not enough: the pre-release flash-attn-4+ # package installs a `flash_attn` stub without `flash_attn_varlen_func`,+ # which would route us onto the flash path only to crash at encode time+ # (see #1685 / the 824c2ec09 worker-image incident). Require the symbol.+ if importlib.util.find_spec("flash_attn") is None:+ return False+ try:+ from flash_attn import flash_attn_varlen_func+ except Exception: # noqa: BLE001 — any broken stub means "no flash"+ return False+ return Trueclass SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):diff --git a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.pyindex 0f73773f9..120700d8f 100644--- a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py@@ -10,7 +10,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter-from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._flash_pack import build_position_ids, mean_pool_packedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import extract_texts, validate_output_types@@ -412,12 +412,7 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):pooled = torch.stack(cls_embeddings)else: # mean pooling# Average all tokens (excluding padding - but we have none!)- mean_embeddings = []- for i in range(num_seqs):- start = cu_seqlens[i].item()- end = cu_seqlens[i + 1].item()- mean_embeddings.append(hidden[start:end].mean(dim=0))- pooled = torch.stack(mean_embeddings)+ pooled = mean_pool_packed(hidden, cu_seqlens, num_seqs)if normalize:pooled = functional.normalize(pooled, p=2, dim=-1)diff --git a/packages/sie_server/tests/adapters/test_colbert.py b/packages/sie_server/tests/adapters/test_colbert.pyindex 3db1c65c4..8d466a163 100644--- a/packages/sie_server/tests/adapters/test_colbert.py+++ b/packages/sie_server/tests/adapters/test_colbert.py@@ -1,9 +1,14 @@from __future__ import annotations+import json+from pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport numpy as npimport pytest+import torch+from safetensors.torch import save_filefrom sie_server.adapters.colbert import ColBERTAdapterfrom sie_server.adapters.colbert_modernbert_flash import ColBERTModernBERTFlashAdapterfrom sie_server.adapters.colbert_rotary_flash import ColBERTRotaryFlashAdapter@@ -14,6 +19,35 @@ from sie_server.types.inputs import Item_RNG = np.random.default_rng(42)+def stub_chain_loader(monkeypatch: pytest.MonkeyPatch) -> None:+ """Keep load-path unit tests offline: ColBERTAdapter.load() probes the pylate+ Dense chain, which would hf_hub_download modules.json for fake model IDs.+ """+ monkeypatch.setattr("sie_server.adapters.colbert.load_pylate_dense_chain", lambda *_args, **_kwargs: None)+++def _write_chain_checkpoint(root: Path) -> str:+ """Write a local pylate-style checkpoint with a single Dense module 384->64."""+ root.mkdir(parents=True, exist_ok=True)+ modules = [+ {"idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer"},+ {"idx": 1, "name": "1", "path": "1_Dense", "type": "pylate.models.Dense.Dense"},+ ]+ (root / "modules.json").write_text(json.dumps(modules))+ dense_dir = root / "1_Dense"+ dense_dir.mkdir()+ config = {+ "in_features": 384,+ "out_features": 64,+ "bias": False,+ "activation_function": "torch.nn.modules.linear.Identity",+ }+ (dense_dir / "config.json").write_text(json.dumps(config))+ save_file({"linear.weight": torch.randn(64, 384)}, str(dense_dir / "model.safetensors"))+ return str(root)++class TestColBERTAdapter:"""Tests for ColBERTAdapter with mocked model."""@@ -59,6 +93,7 @@ class TestColBERTAdapter:mock_model_class: MagicMock,mock_config_class: MagicMock,adapter: ColBERTAdapter,+ stub_chain_loader: None,) -> None:"""CPU device loads with eager attention (no flash attention required)."""mock_config = MagicMock()@@ -82,6 +117,237 @@ class TestColBERTAdapter:call_kwargs = mock_model_class.from_pretrained.call_argsassert call_kwargs.kwargs["attn_implementation"] == "eager"+ def test_should_use_native_mode_modernbert(self, adapter: ColBERTAdapter) -> None:+ """ModernBERT auto-detects native mode (the manual flash loop is BERT-only)."""+ assert adapter._should_use_native_mode(SimpleNamespace(model_type="modernbert")) is True+ assert adapter._should_use_native_mode(SimpleNamespace(model_type="bert")) is False+ # Sharp edge: the explicit override check runs FIRST and wins over the+ # ModernBERT autodetection.+ adapter._use_native_attention = False+ assert adapter._should_use_native_mode(SimpleNamespace(model_type="modernbert")) is False++ @patch("transformers.AutoConfig")+ @patch("transformers.AutoModel")+ @patch("transformers.AutoTokenizer")+ def test_native_load_without_flash_attn_uses_sdpa(+ self,+ mock_tokenizer_class: MagicMock,+ mock_model_class: MagicMock,+ mock_config_class: MagicMock,+ adapter: ColBERTAdapter,+ stub_chain_loader: None,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Native mode on CUDA without flash-attn loads with sdpa instead of crashing."""+ mock_config = MagicMock()+ mock_config.hidden_size = 384+ mock_config.model_type = "modernbert"+ mock_config_class.from_pretrained.return_value = mock_config++ mock_model = MagicMock()+ mock_model.config.hidden_size = 384+ mock_model.named_modules.return_value = []+ mock_model.linear = torch.nn.Linear(384, 128) # keep the projection probe offline+ mock_model_class.from_pretrained.return_value = mock_model++ mock_tokenizer = MagicMock()+ mock_tokenizer.mask_token_id = 103+ mock_tokenizer.vocab = {}+ mock_tokenizer_class.from_pretrained.return_value = mock_tokenizer++ monkeypatch.setattr("sie_server.core.inference.is_flash_attention_available", lambda _device=None: False)++ adapter.load("cuda")++ call_kwargs = mock_model_class.from_pretrained.call_args+ assert call_kwargs.kwargs["attn_implementation"] == "sdpa"++ @patch("transformers.AutoConfig")+ @patch("transformers.AutoModel")+ @patch("transformers.AutoTokenizer")+ def test_native_load_with_flash_attn_uses_flash_attention_2(+ self,+ mock_tokenizer_class: MagicMock,+ mock_model_class: MagicMock,+ mock_config_class: MagicMock,+ adapter: ColBERTAdapter,+ stub_chain_loader: None,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ """Native mode with flash-attn available is bit-unchanged: flash_attention_2."""+ mock_config = MagicMock()+ mock_config.hidden_size = 384+ mock_config.model_type = "modernbert"+ mock_config_class.from_pretrained.return_value = mock_config++ mock_model = MagicMock()+ mock_model.config.hidden_size = 384+ mock_model.named_modules.return_value = []+ mock_model.linear = torch.nn.Linear(384, 128) # keep the projection probe offline+ mock_model_class.from_pretrained.return_value = mock_model++ mock_tokenizer = MagicMock()+ mock_tokenizer.mask_token_id = 103+ mock_tokenizer.vocab = {}+ mock_tokenizer_class.from_pretrained.return_value = mock_tokenizer++ monkeypatch.setattr("sie_server.core.inference.is_flash_attention_available", lambda _device=None: True)++ adapter.load("cuda")++ call_kwargs = mock_model_class.from_pretrained.call_args+ assert call_kwargs.kwargs["attn_implementation"] == "flash_attention_2"++ @patch("transformers.AutoConfig")+ @patch("transformers.AutoModel")+ @patch("transformers.AutoTokenizer")+ def test_chain_probe_wins_over_projection_probes(+ self,+ mock_tokenizer_class: MagicMock,+ mock_model_class: MagicMock,+ mock_config_class: MagicMock,+ tmp_path: Path,+ ) -> None:+ """A checkpoint shipping a Dense chain uses it; the legacy probes must not run."""+ mock_config = MagicMock()+ mock_config.hidden_size = 384+ mock_config_class.from_pretrained.return_value = mock_config++ mock_model = MagicMock()+ mock_model.config.hidden_size = 384+ mock_model.named_modules.return_value = []+ mock_model.linear = torch.nn.Linear(384, 128) # the legacy probe would pick this+ mock_model_class.from_pretrained.return_value = mock_model++ mock_tokenizer = MagicMock()+ mock_tokenizer.mask_token_id = 103+ mock_tokenizer.vocab = {}+ mock_tokenizer_class.from_pretrained.return_value = mock_tokenizer++ adapter = ColBERTAdapter(_write_chain_checkpoint(tmp_path / "ckpt"), token_dim=64)+ adapter.load("cpu")++ assert adapter._dense_chain is not None+ assert [tuple(w.shape) for w in adapter._dense_chain] == [(64, 384)]+ assert adapter._linear is None+ assert adapter._actual_token_dim == 64++ @patch("transformers.AutoConfig")+ @patch("transformers.AutoModel")+ @patch("transformers.AutoTokenizer")+ def test_no_chain_falls_through_to_existing_probes(+ self,+ mock_tokenizer_class: MagicMock,+ mock_model_class: MagicMock,+ mock_config_class: MagicMock,+ adapter: ColBERTAdapter,+ stub_chain_loader: None,+ ) -> None:+ """Without a chain (no modules.json), _find_projection_layer runs as before."""+ mock_config = MagicMock()+ mock_config.hidden_size = 384+ mock_config_class.from_pretrained.return_value = mock_config++ linear = torch.nn.Linear(384, 128)+ mock_model = MagicMock()+ mock_model.config.hidden_size = 384+ mock_model.named_modules.return_value = []+ mock_model.linear = linear+ mock_model_class.from_pretrained.return_value = mock_model++ mock_tokenizer = MagicMock()+ mock_tokenizer.mask_token_id = 103+ mock_tokenizer.vocab = {}+ mock_tokenizer_class.from_pretrained.return_value = mock_tokenizer++ adapter.load("cpu")++ assert adapter._dense_chain is None+ assert adapter._linear is linear+ assert adapter._actual_token_dim == 128++ def test_encode_native_nonexpanded_query_drops_pad_rows(self) -> None:+ """Without expansion, PAD rows must not leak into query multivectors; the+ expansion path still keeps ALL rows (MASK tokens are semantic).+ """+ adapter = ColBERTAdapter("test-model", skip_special_tokens=False, query_expansion=False)+ adapter._device = "cpu"+ adapter._actual_token_dim = 8++ hidden = torch.arange(2 * 4 * 8, dtype=torch.float32).reshape(2, 4, 8) + 1.0++ class _FakeBatch(dict):+ def to(self, _device: str) -> _FakeBatch:+ return self++ batch = _FakeBatch(+ input_ids=torch.tensor([[1, 2, 3, 4], [1, 2, 0, 0]]),+ attention_mask=torch.tensor([[1, 1, 1, 1], [1, 1, 0, 0]]),+ )+ adapter._tokenizer = MagicMock(return_value=batch)+ adapter._model = MagicMock(return_value=SimpleNamespace(last_hidden_state=hidden))++ out = adapter._encode_native(["q one two", "q"], max_length=4, use_expansion=False, is_query=True)+ assert out[0].shape[0] == 4 # all real tokens kept+ assert out[1].shape[0] == 2 # PAD rows dropped++ out_expanded = adapter._encode_native(["q one two", "q"], max_length=4, use_expansion=True, is_query=True)+ assert out_expanded[0].shape[0] == 4+ assert out_expanded[1].shape[0] == 4 # expansion keeps all rows++ def test_fallback_kwargs_overrides_disable_expansion_and_skiplist(self) -> None:+ """The flash adapter's fallback overrides align ColBERTAdapter with the flash+ path (no expansion, no doc skiplist, matching max length) without changing+ the defaults of directly-configured ColBERTAdapter models.+ """+ yaml_kwargs = {"model_name_or_path": "x", "token_dim": 64, "skip_special_tokens": False}+ merged = {**yaml_kwargs, **ColBERTModernBERTFlashAdapter.fallback_kwargs_overrides}+ fallback = ColBERTAdapter(**merged)+ assert fallback._query_expansion is False+ assert fallback._doc_punctuation_skiplist is False+ assert fallback._max_seq_length == 8192+ assert fallback._doc_max_length == 8192 # doc_max_length defaults to max_seq_length++ plain = ColBERTAdapter("x")+ assert plain._query_expansion is True+ assert plain._doc_punctuation_skiplist is True+ assert plain._max_seq_length == 512++ @patch("transformers.AutoConfig")+ @patch("transformers.AutoModel")+ @patch("transformers.AutoTokenizer")+ def test_skiplist_disabled_builds_empty_skiplist(+ self,+ mock_tokenizer_class: MagicMock,+ mock_model_class: MagicMock,+ mock_config_class: MagicMock,+ stub_chain_loader: None,+ ) -> None:+ """doc_punctuation_skiplist=False leaves the skiplist empty; default builds it."""+ mock_config = MagicMock()+ mock_config.hidden_size = 384+ mock_config_class.from_pretrained.return_value = mock_config++ mock_model = MagicMock()+ mock_model.config.hidden_size = 384+ mock_model.named_modules.return_value = []+ mock_model.linear = torch.nn.Linear(384, 128) # keep the projection probe offline+ mock_model_class.from_pretrained.return_value = mock_model++ mock_tokenizer = MagicMock()+ mock_tokenizer.mask_token_id = 103+ mock_tokenizer.vocab = {}+ mock_tokenizer.encode.return_value = [42]+ mock_tokenizer_class.from_pretrained.return_value = mock_tokenizer++ disabled = ColBERTAdapter("test-colbert-model", doc_punctuation_skiplist=False)+ disabled.load("cpu")+ assert disabled._doc_skiplist_ids == set()++ enabled = ColBERTAdapter("test-colbert-model")+ enabled.load("cpu")+ assert 42 in enabled._doc_skiplist_ids+def test_validate_output_types(self, adapter: ColBERTAdapter) -> None:"""Only multivector output type is supported."""# This tests the validation logic without loadingdiff --git a/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.py b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.pynew file mode 100644index 000000000..5a1cacd21--- /dev/null+++ b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_projection.py@@ -0,0 +1,90 @@+from __future__ import annotations++from types import SimpleNamespace++import torch+from sie_server.adapters.colbert_modernbert_flash import ColBERTModernBERTFlashAdapter+++def _bare_adapter() -> ColBERTModernBERTFlashAdapter:+ """Construct without load() (which requires CUDA); set only what methods need."""+ return object.__new__(ColBERTModernBERTFlashAdapter)+++def _fake_model(hidden_size: int, **config_extra) -> SimpleNamespace:+ """Minimal stand-in for the loaded backbone; only config attrs are read."""+ return SimpleNamespace(config=SimpleNamespace(hidden_size=hidden_size, **config_extra))+++def test_project_applies_chain_then_truncates() -> None:+ """WITH a Dense chain ending at token_dim: sequential matmuls, then a no-op truncate."""+ adapter = _bare_adapter()+ adapter._token_dim = 4+ w0 = torch.randn(6, 8) # [out_features, in_features]+ w1 = torch.randn(4, 6)+ adapter._dense_chain = [w0, w1]++ hidden = torch.randn(5, 8)+ out = adapter._project(hidden)++ assert out.shape == (5, 4)+ expected = (hidden @ w0.T) @ w1.T+ assert torch.equal(out, expected)+++def test_project_single_weight_equivalent_to_old_math() -> None:+ """A length-1 chain must be byte-identical to the pre-#1680 single-head math+ (``hidden @ W.T`` then truncate) — GTE/Reason representations must NOT change.+ """+ adapter = _bare_adapter()+ adapter._token_dim = 4+ weight = torch.randn(6, 8)+ adapter._dense_chain = [weight]++ hidden = torch.randn(5, 8)+ out = adapter._project(hidden)++ assert out.shape == (5, 4)+ assert torch.equal(out, (hidden @ weight.T)[:, :4])+++def test_project_pure_truncation_without_chain() -> None:+ """WITHOUT a chain: falls back to backbone truncation (backward-compatible)."""+ adapter = _bare_adapter()+ adapter._token_dim = 4+ adapter._dense_chain = None++ hidden = torch.randn(5, 8)+ out = adapter._project(hidden)++ assert out.shape == (5, 4)+ assert torch.equal(out, hidden[:, :4])+++def test_compute_rope_uses_layer_appropriate_theta() -> None:+ """Global layers use global_rope_theta (160k), local layers local_rope_theta (10k).++ With different bases the rotation angles at position >= 1 must differ; at+ position 0 both are identity (cos=1, sin=0).+ """+ adapter = _bare_adapter()+ adapter._device = "cpu"+ adapter._compute_precision = "float32"+ adapter._model = _fake_model(+ hidden_size=8,+ num_attention_heads=2,+ global_rope_theta=160000.0,+ local_rope_theta=10000.0,+ )++ position_ids = torch.tensor([0, 1, 2, 3])+ global_cos, global_sin = adapter._compute_rope(position_ids, use_global=True)+ local_cos, local_sin = adapter._compute_rope(position_ids, use_global=False)++ assert global_cos.shape == local_cos.shape == (4, 4) # [total_tokens, head_dim]+ # Position 0 is base-independent (angle 0).+ assert torch.equal(global_cos[0], local_cos[0])+ assert torch.equal(global_sin[0], local_sin[0])+ # Positions >= 1 rotate at different frequencies for different bases.+ assert not torch.allclose(global_cos[1:], local_cos[1:])+ assert not torch.allclose(global_sin[1:], local_sin[1:])diff --git a/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_tokenizer.py b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_tokenizer.pynew file mode 100644index 000000000..6aa33bd3e--- /dev/null+++ b/packages/sie_server/tests/adapters/test_colbert_modernbert_flash_tokenizer.py@@ -0,0 +1,44 @@+from __future__ import annotations++import transformers+from sie_server.adapters.colbert_modernbert_flash import ColBERTModernBERTFlashAdapter+++def test_load_tokenizer_happy_path_uses_auto_tokenizer(monkeypatch) -> None:+ """GTE/Reason path: AutoTokenizer succeeds, so its result is returned unchanged."""+ adapter = ColBERTModernBERTFlashAdapter("lightonai/GTE-ModernColBERT-v1")++ sentinel_auto = object()++ def fake_auto(*_args, **_kwargs):+ return sentinel_auto++ def fail_fast(*_args, **_kwargs):+ raise AssertionError("PreTrainedTokenizerFast must not be called on the happy path")++ monkeypatch.setattr(transformers.AutoTokenizer, "from_pretrained", staticmethod(fake_auto))+ monkeypatch.setattr(transformers.PreTrainedTokenizerFast, "from_pretrained", staticmethod(fail_fast))++ assert adapter._load_tokenizer() is sentinel_auto+++def test_load_tokenizer_falls_back_when_auto_cannot_resolve_class(monkeypatch) -> None:+ """Iso-ModernColBERT path: transformers<5 cannot resolve the saved tokenizer_class.++ AutoTokenizer raises a ValueError ("Tokenizer class TokenizersBackend does not+ exist ...") and we must fall back to PreTrainedTokenizerFast.+ """+ adapter = ColBERTModernBERTFlashAdapter("topk-io/Iso-ModernColBERT")++ sentinel_fast = object()++ def fail_auto(*_args, **_kwargs):+ raise ValueError("Tokenizer class TokenizersBackend does not exist or is not currently imported.")++ def fake_fast(*_args, **_kwargs):+ return sentinel_fast++ monkeypatch.setattr(transformers.AutoTokenizer, "from_pretrained", staticmethod(fail_auto))+ monkeypatch.setattr(transformers.PreTrainedTokenizerFast, "from_pretrained", staticmethod(fake_fast))++ assert adapter._load_tokenizer() is sentinel_fastdiff --git a/packages/sie_server/tests/adapters/test_flash_pack.py b/packages/sie_server/tests/adapters/test_flash_pack.pyindex ca23206f9..d0b0aeca0 100644--- a/packages/sie_server/tests/adapters/test_flash_pack.py+++ b/packages/sie_server/tests/adapters/test_flash_pack.py@@ -8,7 +8,7 @@ pin it to be bit-identical to those loops (zero-based and padding-offset) acrossfrom __future__ import annotationsimport torch-from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._flash_pack import build_position_ids, mean_pool_packed# Includes a zero-length middle sequence ([0, 2, 2, 5]) and single-token seqs._CASES = [[0, 3, 7, 8], [0, 5], [0, 1, 4, 4, 9], [0, 2, 2, 5], [0, 1, 2, 3]]@@ -45,3 +45,27 @@ def test_result_is_int64() -> None:def test_single_token_sequences() -> None:cu = torch.tensor([0, 1, 2, 3])assert torch.equal(build_position_ids(cu), torch.tensor([0, 0, 0]))+++def _mean_loop(hidden: torch.Tensor, cu: torch.Tensor, num_seqs: int) -> torch.Tensor:+ """The exact per-sequence mean-pool loop the flash adapters carried inline."""+ means = []+ for i in range(num_seqs):+ start = cu[i].item()+ end = cu[i + 1].item()+ means.append(hidden[start:end].mean(dim=0))+ return torch.stack(means)+++# Non-empty sequence boundaries: real flash batches never mean-pool an empty+# slice (that is nan, and nan != nan under torch.equal).+_MEAN_CASES = [[0, 3, 7, 8], [0, 5], [0, 1, 4, 9], [0, 1, 2, 3]]+++def test_mean_pool_packed_matches_inline_loop() -> None:+ torch.manual_seed(0)+ for case in _MEAN_CASES:+ cu = torch.tensor(case)+ num_seqs = len(case) - 1+ hidden = torch.randn(case[-1], 4)+ assert torch.equal(mean_pool_packed(hidden, cu, num_seqs), _mean_loop(hidden, cu, num_seqs))diff --git a/packages/sie_server/tests/adapters/test_pylate_dense.py b/packages/sie_server/tests/adapters/test_pylate_dense.pynew file mode 100644index 000000000..3a9557ff3--- /dev/null+++ b/packages/sie_server/tests/adapters/test_pylate_dense.py@@ -0,0 +1,240 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import torch+from safetensors.torch import save_file+from sie_server.adapters import _pylate_dense+from sie_server.adapters._pylate_dense import apply_dense_chain, load_pylate_dense_chain++_MXBAI_DENSES = [(384, 768), (768, 768), (768, 64)] # (in_features, out_features)+_TRANSFORMER_MODULE = {"idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer"}+++def _write_checkpoint(+ root: Path,+ denses: list[tuple[int, int]],+ *,+ modules: list[dict[str, Any]] | None = None,+ config_overrides: dict[int, dict[str, Any]] | None = None,+ state_overrides: dict[int, dict[str, torch.Tensor]] | None = None,+) -> str:+ """Write a real pylate-style checkpoint dir: modules.json + N_Dense modules.++ ``denses`` lists (in_features, out_features) per Dense module. ``modules``+ replaces modules.json wholesale; ``config_overrides``/``state_overrides``+ patch a single Dense module (keyed by its 1-based position).+ """+ root.mkdir(parents=True, exist_ok=True)+ if modules is None:+ modules = [_TRANSFORMER_MODULE] + [+ {"idx": i, "name": str(i), "path": f"{i}_Dense", "type": "pylate.models.Dense.Dense"}+ for i in range(1, len(denses) + 1)+ ]+ (root / "modules.json").write_text(json.dumps(modules))++ for i, (in_features, out_features) in enumerate(denses, start=1):+ dense_dir = root / f"{i}_Dense"+ dense_dir.mkdir(exist_ok=True)+ config: dict[str, Any] = {+ "in_features": in_features,+ "out_features": out_features,+ "bias": False,+ "activation_function": "torch.nn.modules.linear.Identity",+ }+ config.update((config_overrides or {}).get(i, {}))+ (dense_dir / "config.json").write_text(json.dumps(config))+ state = {"linear.weight": torch.randn(out_features, in_features)}+ if state_overrides and i in state_overrides:+ state = state_overrides[i]+ save_file(state, str(dense_dir / "model.safetensors"))+ return str(root)+++def test_chain_loads_mxbai_shape(tmp_path: Path) -> None:+ """The mxbai-edge 3-Dense chain (384->768->768->64) loads in order, dtype honored."""+ path = _write_checkpoint(tmp_path / "ckpt", _MXBAI_DENSES)++ chain = load_pylate_dense_chain(path, hidden_size=384, token_dim=64, device="cpu", dtype=torch.bfloat16)++ assert chain is not None+ assert [tuple(w.shape) for w in chain] == [(768, 384), (768, 768), (64, 768)]+ assert all(w.dtype == torch.bfloat16 for w in chain)+++def test_chain_length_one_gte_shape(tmp_path: Path) -> None:+ """The GTE-style single-Dense chain (768->128) loads as one tensor."""+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)])++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is not None+ assert [tuple(w.shape) for w in chain] == [(128, 768)]+++def test_missing_modules_json_returns_none(tmp_path: Path, monkeypatch) -> None:+ """No modules.json (stanford-format repos) -> None, no exception."""++ def fail_download(*_args, **_kwargs):+ raise OSError("repo not found")++ monkeypatch.setattr(_pylate_dense, "hf_hub_download", fail_download)++ chain = load_pylate_dense_chain(str(tmp_path), hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_transformer_only_modules_json_returns_none(tmp_path: Path) -> None:+ """A Transformer-only modules.json (the real mxbai-colbert-large-v1 shape) -> None.++ LOAD-BEARING for the ColBERTAdapter fallback: this checkpoint's head is a+ root-safetensors linear.weight found by the legacy probes, which must run.+ """+ path = _write_checkpoint(tmp_path / "ckpt", [], modules=[_TRANSFORMER_MODULE])++ chain = load_pylate_dense_chain(path, hidden_size=1024, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_unknown_module_type_returns_none(tmp_path: Path) -> None:+ """Any non-Dense module after the Transformer (e.g. Normalize) -> None."""+ modules = [+ _TRANSFORMER_MODULE,+ {"idx": 1, "name": "1", "path": "1_Dense", "type": "pylate.models.Dense.Dense"},+ {"idx": 2, "name": "2", "path": "2_Normalize", "type": "sentence_transformers.models.Normalize"},+ ]+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)], modules=modules)++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_bias_true_rejected(tmp_path: Path) -> None:+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)], config_overrides={1: {"bias": True}})++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_use_residual_true_rejected(tmp_path: Path) -> None:+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)], config_overrides={1: {"use_residual": True}})++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_missing_use_residual_key_ok(tmp_path: Path) -> None:+ """GTE's Dense config has no use_residual key at all; missing == false."""+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)])+ config = json.loads((tmp_path / "ckpt" / "1_Dense" / "config.json").read_text())+ assert "use_residual" not in config # the regression being guarded++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is not None+++def test_non_identity_activation_rejected(tmp_path: Path) -> None:+ """Reject a non-Identity activation_function: pylate never applies it, but its+ presence means the checkpoint was trained with math we would not reproduce.+ """+ path = _write_checkpoint(+ tmp_path / "ckpt",+ [(768, 128)],+ config_overrides={1: {"activation_function": "torch.nn.modules.activation.ReLU"}},+ )++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_dim_discontinuity_rejected(tmp_path: Path) -> None:+ """Adjacent Dense modules must chain: 384->768 then 512->64 is invalid."""+ path = _write_checkpoint(tmp_path / "ckpt", [(384, 768), (512, 64)])++ chain = load_pylate_dense_chain(path, hidden_size=384, token_dim=64, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_first_in_features_mismatch_rejected(tmp_path: Path) -> None:+ """The first weight must consume the backbone hidden size."""+ path = _write_checkpoint(tmp_path / "ckpt", _MXBAI_DENSES)++ chain = load_pylate_dense_chain(path, hidden_size=999, token_dim=64, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_last_out_features_mismatch_rejected(tmp_path: Path) -> None:+ """A chain not landing on token_dim degrades to truncation — exactly the old+ single-head semantics (the pre-#1680 mxbai situation: only 1_Dense 384->768+ with token_dim 64).+ """+ path = _write_checkpoint(tmp_path / "ckpt", [(384, 768)])++ chain = load_pylate_dense_chain(path, hidden_size=384, token_dim=64, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_linear_bias_tensor_present_rejected(tmp_path: Path) -> None:+ """A linear.bias tensor in the safetensors means math we would not reproduce."""+ path = _write_checkpoint(+ tmp_path / "ckpt",+ [(768, 128)],+ state_overrides={1: {"linear.weight": torch.randn(128, 768), "linear.bias": torch.randn(128)}},+ )++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_weight_shape_config_mismatch_rejected(tmp_path: Path) -> None:+ """The weight tensor must match the config's (out_features, in_features)."""+ path = _write_checkpoint(+ tmp_path / "ckpt",+ [(768, 128)],+ state_overrides={1: {"linear.weight": torch.randn(64, 768)}},+ )++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_corrupt_safetensors_returns_none(tmp_path: Path) -> None:+ """A corrupt/truncated Dense weights file degrades instead of crashing load()."""+ path = _write_checkpoint(tmp_path / "ckpt", [(768, 128)])+ (tmp_path / "ckpt" / "1_Dense" / "model.safetensors").write_bytes(b"not a safetensors file")++ chain = load_pylate_dense_chain(path, hidden_size=768, token_dim=128, device="cpu", dtype=torch.float32)++ assert chain is None+++def test_apply_dense_chain_matches_hand_matmul() -> None:+ """apply_dense_chain == explicit sequential matmuls for 2D and 3D inputs."""+ w0 = torch.randn(6, 8)+ w1 = torch.randn(5, 6)+ w2 = torch.randn(4, 5)+ chain = [w0, w1, w2]++ hidden_2d = torch.randn(7, 8) # [tokens, hidden]+ out_2d = apply_dense_chain(hidden_2d, chain)+ assert out_2d.shape == (7, 4)+ assert torch.equal(out_2d, ((hidden_2d @ w0.T) @ w1.T) @ w2.T)++ hidden_3d = torch.randn(2, 3, 8) # [batch, seq, hidden]+ out_3d = apply_dense_chain(hidden_3d, chain)+ assert out_3d.shape == (2, 3, 4)+ assert torch.equal(out_3d, ((hidden_3d @ w0.T) @ w1.T) @ w2.T)diff --git a/packages/sie_server/tests/adapters/test_pytorch_embedding_model_encode.py b/packages/sie_server/tests/adapters/test_pytorch_embedding_model_encode.pynew file mode 100644index 000000000..36c36edde--- /dev/null+++ b/packages/sie_server/tests/adapters/test_pytorch_embedding_model_encode.py@@ -0,0 +1,117 @@+"""use_model_encode delegation in PyTorchEmbeddingAdapter (#1692).++Models like NV-Embed-v2 ship a checkpoint-native ``encode(prompts,+instruction=...)`` implementing their full recipe (instruction prepend ++EOS append, right padding, internal latent-attention pooling with the+instruction masked out of the mean). These tests pin the delegation+contract: raw texts go to the model, the rendered template prefix rides+the ``instruction`` kwarg, and the adapter only normalizes on top.+"""++from __future__ import annotations++from unittest.mock import MagicMock++import numpy as np+import pytest+import torch+from sie_server.adapters.pytorch_embedding import PyTorchEmbeddingAdapter+from sie_server.types.inputs import Item+++def _loaded_adapter(**kwargs: object) -> tuple[PyTorchEmbeddingAdapter, MagicMock]:+ adapter = PyTorchEmbeddingAdapter("test-model", use_model_encode=True, **kwargs)+ model = MagicMock()++ def fake_encode(texts, instruction="", max_length=None):+ return torch.arange(len(texts) * 4, dtype=torch.float32).reshape(len(texts), 4) + 1.0++ model.encode.side_effect = fake_encode+ adapter._model = model+ adapter._tokenizer = MagicMock()+ adapter._device = "cpu"+ adapter._dense_dim = 4+ return adapter, model+++class TestUseModelEncode:+ def test_queries_pass_rendered_prefix_as_instruction(self) -> None:+ adapter, model = _loaded_adapter()++ out = adapter.encode(+ [Item(text="what is entropy"), Item(text="define enthalpy")],+ output_types=["dense"],+ is_query=True,+ instruction="Given a question, retrieve relevant documents",+ options={"query_template": "Instruct: {instruction}\nQuery: {text}"},+ )++ args, kwargs = model.encode.call_args+ assert args[0] == ["what is entropy", "define enthalpy"]+ assert kwargs["instruction"] == ("Instruct: Given a question, retrieve relevant documents\nQuery: ")+ assert out.batch_size == 2+ assert out.dense is not None+ assert out.dense.shape == (2, 4)++ def test_documents_get_empty_instruction(self) -> None:+ adapter, model = _loaded_adapter()++ adapter.encode(+ [Item(text="a passage")],+ output_types=["dense"],+ is_query=False,+ options={"query_template": "Instruct: {instruction}\nQuery: {text}"},+ )++ args, kwargs = model.encode.call_args+ assert args[0] == ["a passage"]+ assert kwargs["instruction"] == ""++ def test_instruction_without_template_still_passes_through(self) -> None:+ """No template configured -> the caller-provided instruction is still+ forwarded (mirrors _format_texts' fallback), not silently dropped.+ """+ adapter, model = _loaded_adapter()++ adapter.encode(+ [Item(text="q")],+ output_types=["dense"],+ is_query=True,+ instruction="search the docs:",+ )++ _, kwargs = model.encode.call_args+ assert kwargs["instruction"] == "search the docs:"++ def test_normalize_applied_on_top(self) -> None:+ adapter, _ = _loaded_adapter()++ out = adapter.encode(+ [Item(text="q")],+ output_types=["dense"],+ is_query=True,+ options={"normalize": True},+ )++ assert out.dense is not None+ np.testing.assert_allclose(np.linalg.norm(out.dense, axis=-1), 1.0, rtol=1e-5)++ def test_rejects_non_prefix_template(self) -> None:+ adapter, _ = _loaded_adapter()++ with pytest.raises(ValueError, match="use_model_encode"):+ adapter.encode(+ [Item(text="q")],+ output_types=["dense"],+ is_query=True,+ options={"query_template": "{text} </s>"},+ )++ def test_missing_model_encode_raises(self) -> None:+ adapter, model = _loaded_adapter()+ del model.encode+ model.mock_add_spec([]) # spec without encode+ adapter._model = model++ with pytest.raises(RuntimeError, match="use_model_encode"):+ adapter.encode([Item(text="q")], output_types=["dense"], is_query=True)diff --git a/packages/sie_server/tests/adapters/test_splade_flash_parity.py b/packages/sie_server/tests/adapters/test_splade_flash_parity.pynew file mode 100644index 000000000..2c99d0d08--- /dev/null+++ b/packages/sie_server/tests/adapters/test_splade_flash_parity.py@@ -0,0 +1,70 @@+"""Flash-vs-native parity for SPLADEFlashAdapter (#1685).++The packed flash path (hand-rolled attention + ``flash_attn_varlen_func``)+and the native path (the model's own eager forward) must produce the same+sparse vectors within fp16 tolerance. The 13.5% StackOverflowQA regression+shipped precisely because nothing pinned the two paths (and the floors)+to each other.++Needs CUDA + a working flash_attn, so it runs on the GPU lanes and is+skipped elsewhere (also gated behind the ``model`` marker because it+downloads the checkpoint).+"""++from __future__ import annotations++import numpy as np+import pytest+import torch+from sie_server.adapters.splade_flash import SPLADEFlashAdapter, _has_flash_attn+from sie_server.types.inputs import Item++pytestmark = [+ pytest.mark.model,+ pytest.mark.skipif(+ not (torch.cuda.is_available() and _has_flash_attn()),+ reason="flash-vs-native parity needs CUDA and a working flash_attn",+ ),+]++MODEL_ID = "naver/splade-v3"++# Short single-segment queries — the shape that regressed on StackOverflowQA —+# plus a longer passage so the packed path exercises mixed sequence lengths.+TEXTS = [+ "how to sort a list in python",+ "segfault when freeing a pointer twice in C",+ "what does the yield keyword do",+ "SPLADE builds sparse lexical representations by max-pooling the "+ "log-saturated MLM logits over the sequence, producing one weight per "+ "vocabulary term; padding and structural tokens must not contribute.",+]+++def _encode_sparse(use_flash: bool) -> list[dict[int, float]]:+ adapter = SPLADEFlashAdapter(MODEL_ID)+ adapter.load("cuda:0")+ assert adapter._use_flash, "flash path unexpectedly unavailable on this runner"+ adapter._use_flash = use_flash+ items: list[Item] = [{"text": t} for t in TEXTS]+ out = adapter.encode(items, ["sparse"])+ return [dict(zip(sv.indices.tolist(), sv.values.tolist(), strict=True)) for sv in out.sparse]+++def test_flash_matches_native_within_fp16_tolerance() -> None:+ flash = _encode_sparse(use_flash=True)+ native = _encode_sparse(use_flash=False)++ for f, n in zip(flash, native, strict=True):+ union = set(f) | set(n)+ assert union, "empty sparse vector from both paths"+ diffs = np.array([abs(f.get(i, 0.0) - n.get(i, 0.0)) for i in union])+ # SPLADE weights sit in ~[0, 3.5]; fp16 accumulation across the two+ # attention implementations stays well inside this envelope. Terms+ # present on only one side must be threshold-boundary noise.+ assert diffs.max() < 0.05, f"max sparse-weight divergence {diffs.max():.4f}"++ f_top = {i for i, _ in sorted(f.items(), key=lambda kv: -kv[1])[:20]}+ n_top = {i for i, _ in sorted(n.items(), key=lambda kv: -kv[1])[:20]}+ overlap = len(f_top & n_top) / 20+ assert overlap >= 0.9, f"top-20 term overlap only {overlap:.2f}"diff --git a/packages/sie_server/tests/config/test_profile_template_inheritance.py b/packages/sie_server/tests/config/test_profile_template_inheritance.pynew file mode 100644index 000000000..f747a8ff6--- /dev/null+++ b/packages/sie_server/tests/config/test_profile_template_inheritance.py@@ -0,0 +1,67 @@+# Catalog guard: ``extends`` profiles must not silently drop the parent's+# text templates. Profile resolution replaces ``adapter_options.runtime``+# wholesale when the child block is non-empty, so a child that re-states+# ``pooling``/``normalize`` but forgets ``query_template``/``doc_template``+# serves the model without its required prefixes — a silent quality+# regression (issue #1595: multilingual-e5-large lost its ``query: `` /+# ``passage: `` prefixes on the sentence_transformer profile, −12 to −16%+# on retrieval). To intentionally serve a profile without a parent+# template, set the key explicitly to ``null`` in the child runtime block.++from __future__ import annotations++from pathlib import Path++import yaml++SIE_SERVER_ROOT = Path(__file__).resolve().parents[2]+MODELS_DIR = SIE_SERVER_ROOT / "models"++TEMPLATE_KEYS = ("query_template", "doc_template", "default_instruction")+++def _runtime_block(profile: dict) -> dict:+ adapter_options = profile.get("adapter_options") or {}+ if not isinstance(adapter_options, dict):+ return {}+ runtime = adapter_options.get("runtime") or {}+ return runtime if isinstance(runtime, dict) else {}+++def test_extends_profiles_do_not_silently_drop_templates() -> None:+ """Every ``extends`` child with a non-empty runtime block keeps the+ parent's template keys (an explicit ``null`` counts as a deliberate+ opt-out; a missing key is the silent-drop trap).+ """+ model_files = sorted(MODELS_DIR.glob("*.yaml"))+ assert model_files, f"No model configs found in {MODELS_DIR}"++ violations: list[str] = []+ for path in model_files:+ data = yaml.safe_load(path.read_text()) or {}+ profiles = data.get("profiles") or {}+ if not isinstance(profiles, dict):+ continue+ for name, profile in profiles.items():+ if not isinstance(profile, dict):+ continue+ parent_name = profile.get("extends")+ if parent_name is None:+ continue+ parent = profiles.get(parent_name)+ if not isinstance(parent, dict):+ continue+ child_runtime = _runtime_block(profile)+ if not child_runtime:+ # Empty child runtime inherits the parent's block wholesale.+ continue+ parent_runtime = _runtime_block(parent)+ dropped = [key for key in TEMPLATE_KEYS if key in parent_runtime and key not in child_runtime]+ if dropped:+ violations.append(f"{path.name} profile '{name}' (extends '{parent_name}') drops {dropped}")++ assert not violations, (+ "Profile runtime blocks are full replacements, not merges — these "+ "profiles silently lose the parent's text templates (see #1595). "+ "Re-state the template (or set it explicitly to null to opt out):\n " + "\n ".join(violations)+ )diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex d7ab6e582..759cbb647 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2463,7 +2463,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.15"+version = "0.6.16"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex eeefcd7fb..e5e6460b8 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.15"+version = "0.6.16"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex e83fe443f..4555ed5c4 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -3,12 +3,12 @@`packages/sie_server_sidecar` contains the Rust queue runtime used bysidecar-enabled SIE worker pods.-The sidecar runs next to `sie-server` in the same worker pod. It consumes NATS-JetStream work, talks to the Python adapter over Unix-domain-socket IPC, and-publishes results back to NATS Core.+The sidecar runs next to a SIE backend in the same worker pod. It consumes NATS+JetStream work, talks to the backend over Unix-domain-socket IPC, and publishes+results back to NATS Core.```text-gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> sie-server adapter+gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> worker backend|+-> NATS Core reply subject```@@ -58,7 +58,7 @@ Encode, score, and extract queue traffic follows this path:6. The sidecar calls `EnsureModelReady` over IPC.7. The scheduler batches compatible items by operation and LoRA key.8. The sidecar sends scheduled batches over IPC with `RunBatch`.-9. Python returns per-item outcomes.+9. The backend returns per-item outcomes.10. The sidecar publishes a `WorkResult` to the reply subject.11. The sidecar ACKs the JetStream message after successful reply publication.@@ -126,7 +126,7 @@ polls `GET /v1/pools` before pulling from the pool stream or theworker-specific direct-dispatch stream. It may pull when its physical `SIE_POOL` isadmitted directly, or when at least one assigned logical pool is backed by thatsame queue; each work item is then checked against its `admission_pool` before-Python IPC. The gateway normally direct-dispatches capped logical batch work to+backend IPC. The gateway normally direct-dispatches capped logical batch work toan assigned worker, so unassigned peers do not spend the item's JetStreamdelivery budget. Work items rejected by this per-item logical gate are stillNAKed and counted in `sie_worker_pool_admission_naks_total` as a defensive@@ -142,7 +142,7 @@ Source: [`pool_admission.rs`](../src/pool_admission.rs).## GenerationGeneration work uses `ProcessGenerate` over IPC. The sidecar passes the-msgpack-encoded `WorkItem` to Python and handles streaming IPC events.+msgpack-encoded `WorkItem` to the backend and handles streaming IPC events.The gateway streaming path selects either a pool subject or a worker-specificsubject. Worker-specific routing uses HRW over eligible workers. The gateway@@ -150,7 +150,7 @@ stores a pool fallback subject for streaming work and uses it for republishpaths such as NAK handling and first-chunk timeout handling.The sidecar subscribes to `cancel.>`. Subjects shaped as-`cancel.{router_id}.{request_id}` are forwarded to Python through+`cancel.{router_id}.{request_id}` are forwarded to the backend through`SignalGenerateCancel`.Source: [`lib.rs`](../src/lib.rs), [`dispatcher.rs`](../src/dispatcher.rs),@@ -204,8 +204,8 @@ request count, coalescing windows, adaptive pull timing, and model-specificscheduler state. Oversize items flush alone. Per-item outcomes are publishedwithout dropping the rest of the batch.-Routing remains gateway-owned. The sidecar has no local active-model allowlist-for queue routing.+Routing remains gateway-owned. The sidecar does not keep a separate local+active-model routing list.Source: [`scheduler/`](../src/scheduler/), [`latency.rs`](../src/latency.rs),and [`dispatcher.rs`](../src/dispatcher.rs).@@ -221,12 +221,12 @@ The sidecar performs GPU-independent preparation and framing:- dense, sparse, multivector, score, and generated-output framing;- `msgpack_numpy` sentinel-compatible payload handling.-Python retokenizes when prepared tokens are absent or the tokenizer hash does-not match. Score pair construction stays in Python. Extract tokenization stays-in Python.+The backend retokenizes when prepared tokens are absent or the tokenizer hash+does not match. Score pair construction stays backend-owned. Extract+tokenization stays backend-owned.Large generation and vision payloads are fetched from payload storage and-inlined before `ProcessGenerate`, so Python receives a self-contained msgpack+inlined before `ProcessGenerate`, so the backend receives a self-contained msgpackwork item.Source: [`prep/`](../src/prep/), [`tokenize/`](../src/tokenize/),@@ -245,7 +245,7 @@ The sidecar HTTP server exposes:Readiness state is shared with the NATS health publisher. The health publisheremits worker identity, bundle, machine profile, readiness, and the currentbundle config hash. It also mirrors the latest `loaded_models` list reported by-the Python IPC heartbeat so gateway pool/model gauges reflect live residency in+the backend IPC heartbeat so gateway pool/model gauges reflect live residency inNATS health mode.Source: [`metrics.rs`](../src/metrics.rs),@@ -261,13 +261,13 @@ sie.config.models.{bundle}```Each notification is checked for trusted producer, bundle, epoch, and payload-size. Accepted deltas are forwarded to Python through `ApplyModelConfig`.-Python returns the applied bundle config hash. The sidecar stores that hash in-`ConfigApplyState`.+size. Accepted deltas are forwarded to the colocated backend through+`ApplyModelConfig`. The backend returns the applied bundle config hash. The+sidecar stores that hash in `ConfigApplyState`.When `SIE_CONFIG_SERVICE_URL` is configured, the export reconciler fetches`/v1/configs/epoch` and `/v1/configs/export` from `sie-config`. Bundle-relevant-exports are sent to Python through `ReplaceModelConfigs`.+exports are sent to the backend through `ReplaceModelConfigs`.Export reconciliation skips unchanged periodic exports. Exports older than thelocal epoch are skipped unless the reconciler is handling an epoch-rewind@@ -279,7 +279,7 @@ config hash for the resolved pool and bundle. The dispatcher compares that hashwith the current local hash and the accepted recent-hash window before`EnsureModelReady`. Unknown hashes are NAKed.-Live config apply updates model configuration in the colocated Python registry.+Live config apply updates model configuration in the colocated backend registry/catalog.It does not update adapter code or bundle definitions inside the running workerimage.diff --git a/packages/sie_server_sidecar/src/backend/mod.rs b/packages/sie_server_sidecar/src/backend/mod.rsindex 240747f71..347bffcc3 100644--- a/packages/sie_server_sidecar/src/backend/mod.rs+++ b/packages/sie_server_sidecar/src/backend/mod.rs@@ -154,7 +154,7 @@ pub trait InferenceBackend: Send + Sync {////// A backend that serves every model (like [`PythonIpcBackend`])/// returns `true` unconditionally. A specialised backend returns- /// `true` only for its allow-list.+ /// `true` only for models in its responsibility set.fn supports(&self, model_id: &str) -> bool;/// Ensure the model is loaded (or kick off a load) and reportdiff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 69c8e7151..a8b89fb6d 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -18,22 +18,22 @@ pub struct WorkerConfig {/// so multiple bundles on the same pool don't step on each other.pub bundle: String,- /// Unix domain socket used to talk to the Python `ipc_server.py`.+ /// Unix domain socket used to talk to the colocated backend IPC server.pub ipc_socket_path: PathBuf,- /// Number of concurrent IPC connections to the Python sie-server process. `1`+ /// Number of concurrent IPC connections to the backend process. `1`/// preserves the legacy single-socket behaviour; higher values let/// the dispatcher's `SIE_MAX_CONCURRENT_BATCHES` actually drive- /// parallel Python-side batches. Sourced from `SIE_IPC_POOL_SIZE`+ /// parallel backend-side batches. Sourced from `SIE_IPC_POOL_SIZE`/// (see `main.rs`); when unset we default to/// `SIE_MAX_CONCURRENT_BATCHES`'s default (4).pub ipc_pool_size: usize,- /// Per-RPC timeout for ordinary sidecar → Python IPC calls. Sourced from+ /// Per-RPC timeout for ordinary sidecar-to-backend IPC calls. Sourced from/// `SIE_IPC_REQUEST_TIMEOUT_S`.pub ipc_request_timeout_s: u64,- /// Timeout for sidecar → Python `EnsureModelReady` calls. Must be at least+ /// Timeout for sidecar-to-backend `EnsureModelReady` calls. Must be at least/// as long as the slowest expected cold start; SGLang adapters may/// legitimately spend many minutes loading large models before they can/// answer the readiness handshake. Sourced from@@ -78,7 +78,7 @@ pub struct WorkerConfig {/// IPC `Ping`.pub worker_id: String,- /// How often to send `Ping` RPCs to the Python sie-server process.+ /// How often to send `Ping` RPCs to the backend process.pub ping_interval_ms: u64,/// Multiplier applied to `ping_interval_ms` to compute thediff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 3fff543d7..23391cca0 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -678,7 +678,6 @@ wherelet advertised_hash =advertised_bundle_hash(control_plane_hash.as_deref(), &resp.bundle_config_hash);applied = resp.applied_models.len();- state.set_loaded_models(resp.applied_models);if let (Some(control_hash), Some(applied_hash)) = (control_plane_hash.as_deref(),@@ -688,7 +687,7 @@ whereepoch = snapshot.epoch,advertised_hash = %control_hash,applied_hash = %applied_hash,- "worker-config: Python registry hash differs from control-plane export hash; advertising control-plane hash"+ "worker-config: worker config hash differs from control-plane export hash; advertising control-plane hash");}let state_updated = state.mark_export_reconciled(@@ -925,10 +924,7 @@ mod tests {state.bundle_config_hash().read().unwrap().as_str(),"hash-7");- assert_eq!(- state.loaded_models().read().unwrap().as_slice(),- ["target-model".to_string()]- );+ assert!(state.loaded_models().read().unwrap().is_empty());let applied = applied.lock().await;assert_eq!(applied.len(), 1);@@ -994,10 +990,7 @@ mod tests {state.bundle_config_hash().read().unwrap().as_str(),"default-pool-hash");- assert_eq!(- state.loaded_models().read().unwrap().as_slice(),- ["default-model".to_string()]- );+ assert!(state.loaded_models().read().unwrap().is_empty());let applied = applied.lock().await;assert_eq!(applied.len(), 1);diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex 8575a1ab4..f387da426 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -4,8 +4,8 @@//! `sie.config.models._all` (gateway replicas) and//! `sie.config.models.<bundle>` (workers). The gateway applies `_all` into its//! Rust registry; this module consumes the bundle-scoped subject in the-//! worker-sidecar and forwards the validated YAML to Python over IPC so the-//! adapter-local `ModelRegistry` changes in the process that serves inference.+//! worker-sidecar and forwards the validated YAML over IPC so the backend-local+//! model registry changes in the process that serves inference.use std::collections::{HashMap, VecDeque};use std::sync::atomic::{AtomicU64, Ordering};@@ -22,8 +22,7 @@ use tracing::{debug, info, warn};use crate::health_publisher::{SharedBundleConfigHash, SharedLoadedModels};use crate::ipc_client::{IpcClient, IpcError};use crate::ipc_types::{- ApplyModelConfigRequest, ReadinessState, ReplaceModelConfigsRequest,- ReplaceModelConfigsResponse,+ ApplyModelConfigRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,};use crate::metrics::MetricsRegistry;use crate::shutdown::Shutdown;@@ -44,7 +43,7 @@ pub struct ConfigApplyState {bundle_config_hash: SharedBundleConfigHash,loaded_models: SharedLoadedModels,accepted_bundle_config_hashes: RwLock<VecDeque<String>>,- /// Serializes Python registry mutations from live NATS deltas and export+ /// Serializes worker config mutations from live NATS deltas and export/// replay so an older snapshot cannot clobber a newer live apply.apply_lock: Mutex<()>,}@@ -146,22 +145,6 @@ impl ConfigApplyState {*guard = deduped;}- pub fn record_loaded_model(&self, model_id: &str) {- let model_id = model_id.trim();- if model_id.is_empty() {- return;- }- let mut guard = self- .loaded_models- .write()- .expect("loaded models lock poisoned");- if guard.iter().any(|known| known == model_id) {- return;- }- guard.push(model_id.to_string());- guard.sort();- }-fn remember_bundle_hash(&self, hash: &str) {if hash.is_empty() {return;@@ -390,60 +373,6 @@ fn retryable_ipc_error(e: &IpcError) -> bool {}}-fn requires_eager_model_ready(bundle_id: &str) -> bool {- bundle_id.trim() == "candle"-}--async fn ensure_candle_model_ready_if_needed(- ipc: &Arc<IpcClient>,- bundle_id: &str,- model_id: &str,- epoch: u64,-) -> Result<(), IpcError> {- if !requires_eager_model_ready(bundle_id) {- return Ok(());- }-- match ipc.ensure_model_ready(model_id).await {- Ok(resp) if resp.state == ReadinessState::Ready => {- info!(- model = %model_id,- epoch,- "worker-config: Candle model ready after config apply"- );- Ok(())- }- Ok(resp) => {- warn!(- model = %model_id,- epoch,- state = ?resp.state,- "worker-config: Candle model not ready after config apply; retrying"- );- Err(IpcError::Timeout)- }- Err(e) => Err(e),- }-}--async fn ensure_candle_models_ready_if_needed(- ipc: &Arc<IpcClient>,- bundle_id: &str,- model_ids: &[String],- epoch: u64,-) -> Result<Vec<String>, IpcError> {- if !requires_eager_model_ready(bundle_id) {- return Ok(model_ids.to_vec());- }-- let mut ready_models = Vec::with_capacity(model_ids.len());- for model_id in model_ids {- ensure_candle_model_ready_if_needed(ipc, bundle_id, model_id, epoch).await?;- ready_models.push(model_id.clone());- }- Ok(ready_models)-}-fn next_retry_delay(current: Duration) -> Duration {std::cmp::min(current.saturating_mul(2), RETRY_MAX_DELAY)}@@ -575,43 +504,7 @@ pub(crate) async fn apply_via_ipc_with_retry(let mut attempt = 0_u64;loop {match ipc.apply_model_config(req.clone()).await {- Ok(resp) => {- match ensure_candle_model_ready_if_needed(&ipc, &req.bundle_id, model_id, epoch)- .await- {- Ok(()) => return Ok(Some(resp)),- Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {- attempt = attempt.saturating_add(1);- if attempt == 1- || attempt == 5- || attempt == 30- || attempt.is_multiple_of(120)- {- warn!(- model = %model_id,- epoch,- attempt,- retry_delay_ms = retry_delay.as_millis() as u64,- error = %e,- "worker-config: Candle model readiness still waiting after apply; retrying"- );- } else {- debug!(- model = %model_id,- epoch,- attempt,- error = %e,- "worker-config: Candle model readiness still waiting"- );- }- if wait_retry_or_shutdown(&shutdown, retry_delay).await {- return Ok(None);- }- retry_delay = next_retry_delay(retry_delay);- }- Err(e) => return Err(e),- }- }+ Ok(resp) => return Ok(Some(resp)),Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {attempt = attempt.saturating_add(1);if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {@@ -621,7 +514,7 @@ pub(crate) async fn apply_via_ipc_with_retry(attempt,retry_delay_ms = retry_delay.as_millis() as u64,error = %e,- "worker-config: transient Python registry apply failure; retrying"+ "worker-config: transient worker config apply failure; retrying");} else {debug!(@@ -629,7 +522,7 @@ pub(crate) async fn apply_via_ipc_with_retry(epoch,attempt,error = %e,- "worker-config: Python registry apply still waiting"+ "worker-config: worker config apply still waiting");}if wait_retry_or_shutdown(&shutdown, retry_delay).await {@@ -652,49 +545,7 @@ pub(crate) async fn replace_via_ipc_with_retry(let mut attempt = 0_u64;loop {match ipc.replace_model_configs(req.clone()).await {- Ok(mut resp) => {- match ensure_candle_models_ready_if_needed(- &ipc,- &req.bundle_id,- &resp.applied_models,- epoch,- )- .await- {- Ok(ready_models) => {- resp.applied_models = ready_models;- return Ok(Some(resp));- }- Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {- attempt = attempt.saturating_add(1);- if attempt == 1- || attempt == 5- || attempt == 30- || attempt.is_multiple_of(120)- {- warn!(- epoch,- attempt,- retry_delay_ms = retry_delay.as_millis() as u64,- error = %e,- "worker-config: Candle model readiness still waiting after replace; retrying"- );- } else {- debug!(- epoch,- attempt,- error = %e,- "worker-config: Candle model readiness still waiting after replace"- );- }- if wait_retry_or_shutdown(&shutdown, retry_delay).await {- return Ok(None);- }- retry_delay = next_retry_delay(retry_delay);- }- Err(e) => return Err(e),- }- }+ Ok(resp) => return Ok(Some(resp)),Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {attempt = attempt.saturating_add(1);if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {@@ -703,14 +554,14 @@ pub(crate) async fn replace_via_ipc_with_retry(attempt,retry_delay_ms = retry_delay.as_millis() as u64,error = %e,- "worker-config: transient Python registry replace failure; retrying"+ "worker-config: transient worker config replace failure; retrying");} else {debug!(epoch,attempt,error = %e,- "worker-config: Python registry replace still waiting"+ "worker-config: worker config replace still waiting");}if wait_retry_or_shutdown(&shutdown, retry_delay).await {@@ -864,7 +715,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotmodel = %notification.model_id,epoch = notification.epoch,error = %e,- "worker-config: Python registry apply failed; epoch not advanced"+ "worker-config: worker config apply failed; epoch not advanced");record_delta(metrics, kind, "apply_error");return;@@ -875,7 +726,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotwarn!(model = %notification.model_id,epoch = notification.epoch,- "worker-config: Python registry reported applied=false; epoch not advanced"+ "worker-config: worker config reported applied=false; epoch not advanced");record_delta(metrics, kind, "apply_rejected");return;@@ -895,7 +746,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotepoch = notification.epoch,advertised_hash = %control_plane_hash,applied_hash = %resp.bundle_config_hash,- "worker-config: Python registry hash differs from control-plane hash; advertising control-plane hash"+ "worker-config: worker config hash differs from control-plane hash; advertising control-plane hash");record_delta(metrics, kind, "hash_mismatch");} else {@@ -903,9 +754,6 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNot}state.mark_applied(notification.epoch, advertised_hash);- if requires_eager_model_ready(¬ification.bundle_id) {- state.record_loaded_model(¬ification.model_id);- }metrics.config_epoch.set(notification.epoch as i64);}@@ -995,13 +843,6 @@ mod tests {assert_eq!(advertised_bundle_hash(None, "worker-hash"), "worker-hash");}- #[test]- fn eager_model_ready_is_candle_specific() {- assert!(requires_eager_model_ready("candle"));- assert!(!requires_eager_model_ready("default"));- assert!(!requires_eager_model_ready("sglang"));- }-#[test]fn config_notification_accepts_router_id_alias() {let json = r#"{@@ -1068,18 +909,14 @@ mod tests {}#[test]- fn loaded_models_are_deduped_and_sorted() {+ fn set_loaded_models_are_trimmed_deduped_and_sorted() {let state = ConfigApplyState::new("initial".into());- state.record_loaded_model("model/b");- state.record_loaded_model("model/a");- state.record_loaded_model("model/b");-- assert_eq!(- state.loaded_models().read().unwrap().as_slice(),- ["model/a".to_string(), "model/b".to_string()]- );-- state.set_loaded_models(vec!["model/d".into(), "".into(), " model/c ".into()]);+ state.set_loaded_models(vec![+ "model/d".into(),+ "".into(),+ " model/c ".into(),+ "model/d".into(),+ ]);assert_eq!(state.loaded_models().read().unwrap().as_slice(),["model/c".to_string(), "model/d".to_string()]diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex e328eef53..d06211d84 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -1,5 +1,5 @@//! Per-batch dispatcher: decode NATS JetStream messages into WorkItems,-//! fan out to the Python inference core over IPC, publish results, and+//! fan out to the backend over IPC, publish results, and//! ACK/NAK each message.//!//! fetch -> decode + validate (subject, reply_subject, model_id)@@ -2042,7 +2042,7 @@ impl Dispatcher {/// Remove and return all in-flight generation task handles. Called/// during shutdown after the pull loops stop so long-running streams can- /// settle before the backend drain RPC closes Python-side state.+ /// settle before the backend drain RPC closes backend-side state.pub async fn take_generation_handles(&self) -> Vec<JoinHandle<()>> {let mut guard = self.generation_handles.lock().await;guard.drain(..).collect()diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 011755bf6..abfce4260 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -96,10 +96,10 @@ pub struct HealthPublisherConfig {pub gpu_count: i32,/// Bundle-config hash so the gateway can correlate against its own/// model registry epoch. Updated by the config subscriber after a- /// successful Python registry apply.+ /// successful backend config apply.pub bundle_config_hash: SharedBundleConfigHash,- /// Models the colocated adapter reports as loaded or configured for- /// this runtime. Updated by config apply/reconcile paths.+ /// Models the colocated backend reports as loaded. Updated by the IPC+ /// heartbeat, not by config apply.pub loaded_models: SharedLoadedModels,/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].pub interval: Duration,diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex cffedcb73..138475acc 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -1,5 +1,5 @@//! Async IPC client over a Unix domain socket, speaking the length-prefixed-//! msgpack protocol defined by `sie_server.ipc_server`.+//! msgpack protocol shared by SIE backend IPC servers.//!//! # Concurrency model: connection pool//!@@ -8,14 +8,12 @@//! most one in-flight RPC; any second caller blocks behind the first.//!//! To let `SIE_MAX_CONCURRENT_BATCHES` actually translate into parallel-//! IPC calls — and thus let the Python-side adaptive batcher / GPU+//! IPC calls — and thus let the backend-side adaptive batcher / GPU//! pipeline overlap CPU preprocessing on one batch with GPU inference on//! another — we run a small **pool** of N independent connections to the-//! same `ipc_server.py`.+//! same backend IPC server.//!-//! * The Python server already accepts many connections concurrently-//! (`asyncio.start_unix_server`) and spawns an `asyncio.create_task`-//! per incoming frame, so no Python-side change is required; each+//! * Backend IPC servers accept concurrent connections in deployed runtimes; each//! Rust slot just looks like another sidecar.//! * Callers `acquire()` a `SlotGuard` — a fair FIFO checkout — do//! their round-trip, and drop it to return the slot. If all N slots@@ -69,7 +67,7 @@ const MAX_FRAME_BYTES: usize = 32 * 1024 * 1024;const DEFAULT_POOL_SIZE: usize = 1;/// WARN threshold for "slow" RPCs — emits one structured line per slow-/// call so an operator scanning `kubectl logs` sees Python-side+/// call so an operator scanning `kubectl logs` sees backend-side/// stalls without having to open Grafana. The `ipc_request_seconds`/// histogram is the primary source of truth; this is the ergonomic/// shortcut for live debugging. Keep the budget generous: model@@ -270,7 +268,7 @@ impl Pool {/// * a fully written frame but no response read yet.////// Either way the socket is **protocol-desynchronized**: the next-/// request's bytes would be misinterpreted by the Python server as a+/// request's bytes would be misinterpreted by the backend server as a/// continuation of the aborted one, producing either a silent hang or/// a corrupt decode.///@@ -473,11 +471,11 @@ impl IpcClient {/// slot only** and transparently retry exactly once, preferring a/// fresh slot from the pool so the retry isn't gated on the still-/// breaking connection. This avoids NAKing an entire batch just- /// because the Python side restarted between two fetches, while+ /// because the backend side restarted between two fetches, while/// also not taking out the other N-1 slots.////// We do *not* retry:- /// * `Timeout` — if Python is slow once, it'll likely be slow again,+ /// * `Timeout` — if the backend is slow once, it'll likely be slow again,/// and a retry would double our tail latency./// * `Server` / `VersionMismatch` — these are logical errors that/// won't go away on retry.@@ -733,7 +731,7 @@ impl IpcClient {result,elapsed_ms = elapsed_ms as u64,threshold_ms = SLOW_RPC_WARN_MS as u64,- "slow IPC RPC — Python side took longer than expected"+ "slow IPC RPC — backend side took longer than expected");}}@@ -819,7 +817,7 @@ impl IpcClient {/// this method receives a sequence of response envelopes:/// `publish` / `in_progress` / `ack` / `nak` events followed by/// `done`. The Rust sidecar owns the real NATS client and JetStream- /// message settlement; Python owns generation adapter execution and+ /// message settlement; the backend owns generation adapter execution and/// chunk encoding.pub async fn process_generate<F, Fut>(&self,diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex b1492ab19..0d3469f4d 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -126,7 +126,7 @@ fn nats_consumer_reconcile_interval() -> Option<Duration> {.map(Duration::from_millis)}-/// Drain deadline sent to the Python IPC on shutdown.+/// Drain deadline sent to the backend IPC on shutdown.const DRAIN_DEADLINE_MS: u64 = 15_000;/// Whether the pull-loop quantum's [`LatencyTracker`] should observe@@ -352,7 +352,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {});// Pinned-model reconciler: polls the pool's PoolSpec.pinned_models and pushes- // it to the Python worker over IPC. Decoupled from admission so pinned models+ // it to the backend over IPC. Decoupled from admission so pinned models// work even when the admission gate is disabled or fails open.let pinned_reconciler_handle =crate::pinned_reconciler::spawn(&config, Arc::clone(&ipc), Arc::clone(&shutdown))@@ -360,11 +360,10 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {// --- Backend router//- // The sidecar talks to whichever adapter is co-deployed over IPC;- // today that is the Python `sie_server` adapter. There is exactly- // one backend. `BackendRouter` is kept as the single integration- // point so the multi-backend fall-through plumbing stays available- // if we ever co-resident two adapters again.+ // The sidecar talks to whichever backend is co-deployed over IPC.+ // There is exactly one backend in the current deployment. `BackendRouter`+ // is kept as the single integration point so the multi-backend fall-through+ // plumbing stays available if we ever co-resident two adapters again.let python_backend: SharedBackend = Arc::new(PythonIpcBackend::new(Arc::clone(&ipc)));let backends: Vec<SharedBackend> = vec![Arc::clone(&python_backend)];@@ -998,7 +997,7 @@ fn request_id_from_cancel_subject(subject: &str) -> Option<String> {}}-/// Ping the Python IPC server on a ticker. A failure is logged but+/// Ping the backend IPC server on a ticker. A failure is logged but/// non-fatal — the consumer loop will surface real problems via/// EnsureModelReady / Process* errors.///@@ -1016,7 +1015,7 @@ fn spawn_heartbeat(tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);// Track consecutive failures so we warn on transitions// (0 -> 1 "heartbeat broke", N -> 0 "heartbeat recovered")- // without spamming once per tick while Python is down.+ // without spamming once per tick while the backend is down.let mut consecutive_failures: u64 = 0;loop {let wait = shutdown.wait();@@ -1156,7 +1155,7 @@ async fn build_pull_stream(/// the quantum deadline, whichever first./// 4. Hand the batch to the dispatcher **as a spawned task**, bounded by/// [`pull_loop_inflight`] so the next fetch can start immediately-/// while Python processes the previous batch. Without this, a single+/// while the backend processes the previous batch. Without this, a single/// pull loop serialises `fetch → IPC → GPU → NATS ACK → next fetch`,/// leaving the IPC pool and GPU under-fed under distributed load.///diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rsindex 1dbfddd96..42d08d1f8 100644--- a/packages/sie_server_sidecar/src/main.rs+++ b/packages/sie_server_sidecar/src/main.rs@@ -27,7 +27,7 @@ struct Cli {#[arg(long, env = "SIE_IPC_SOCKET_PATH", default_value = "/tmp/sie-ipc.sock")]ipc_socket_path: String,- /// Number of concurrent IPC connections to the Python adapter process.+ /// Number of concurrent IPC connections to the backend process./// Defaults to `SIE_MAX_CONCURRENT_BATCHES` when unset (falling/// back to the dispatcher's own default of 4), so the IPC pool/// never becomes the binding constraint on the dispatcher's@@ -35,7 +35,7 @@ struct Cli {#[arg(long, env = "SIE_IPC_POOL_SIZE")]ipc_pool_size: Option<usize>,- /// Timeout, in seconds, for ordinary sidecar → Python IPC calls.+ /// Timeout, in seconds, for ordinary sidecar-to-backend IPC calls.#[arg(long, env = "SIE_IPC_REQUEST_TIMEOUT_S", default_value = "60")]ipc_request_timeout_s: u64,@@ -45,7 +45,7 @@ struct Cli {#[arg(long, env = "SIE_MODEL_READY_TIMEOUT_S")]model_ready_timeout_s: Option<u64>,- /// Python worker liveness budget in seconds. When set by Helm, the sidecar+ /// Backend worker liveness budget in seconds. When set by Helm, the sidecar/// rejects an EnsureModelReady timeout kubelet would kill before completion.#[arg(long, env = "SIE_WORKER_LIVENESS_BUDGET_S")]worker_liveness_budget_s: Option<u64>,diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rsindex 70cc5197b..606af5842 100644--- a/packages/sie_server_sidecar/src/metrics.rs+++ b/packages/sie_server_sidecar/src/metrics.rs@@ -31,7 +31,7 @@ const BATCH_PROCESS_BUCKETS: &[f64] = &[0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,];-/// Finer buckets for sub-millisecond IPC RPCs (UDS to local Python).+/// Finer buckets for sub-millisecond IPC RPCs (UDS to the local backend).const IPC_REQUEST_BUCKETS: &[f64] = &[0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5,5.0, 10.0, 30.0,@@ -104,7 +104,7 @@ pub struct MetricsRegistry {/// `tokenization_ms` / `postprocessing_ms` fields on each/// `ItemOutcome`.///- /// Python IPC reports the backend sub-group wall time on every+ /// IPC backends report the backend sub-group wall time on every/// item in that sub-group, so percentiles are request-volume/// weighted backend times, not amortised per-item costs. Backends/// may use different timing semantics; compare distributionsdiff --git a/packages/sie_server_sidecar/src/observability/mod.rs b/packages/sie_server_sidecar/src/observability/mod.rsindex f1b4a8376..8ede5f7eb 100644--- a/packages/sie_server_sidecar/src/observability/mod.rs+++ b/packages/sie_server_sidecar/src/observability/mod.rs@@ -1,7 +1,7 @@//! Sidecar-side observability: OTLP tracing + W3C Trace Context.//!//! The sidecar sits on the queue hop between the gateway and the-//! Python worker. It owns the OpenTelemetry tracer-provider setup, the+//! backend worker. It owns the OpenTelemetry tracer-provider setup, the//! global W3C propagator install, and the helpers for extracting the//! inbound gateway context off the work envelope plus injecting the//! `sidecar.dispatch` span's context onto the IPC `RunBatchItem`s.diff --git a/packages/sie_server_sidecar/src/observability/tracing.rs b/packages/sie_server_sidecar/src/observability/tracing.rsindex ac588da72..1548dd172 100644--- a/packages/sie_server_sidecar/src/observability/tracing.rs+++ b/packages/sie_server_sidecar/src/observability/tracing.rs@@ -7,7 +7,7 @@//! The W3C [`TraceContextPropagator`] is installed globally regardless//! of that exporter gate so that the inbound gateway//! `traceparent` (carried on the work envelope) still propagates-//! through to the Python worker. Without an exporter the sidecar+//! through to the backend worker. Without an exporter the sidecar//! itself records no spans, but the IDs continue to flow — the//! `into_run_batch_item_with_trace` fallback in the dispatcher copies//! the gateway context onto the wire items unchanged.diff --git a/packages/sie_server_sidecar/src/pinned_reconciler.rs b/packages/sie_server_sidecar/src/pinned_reconciler.rsindex 58d0779d0..a0ac2fe8d 100644--- a/packages/sie_server_sidecar/src/pinned_reconciler.rs+++ b/packages/sie_server_sidecar/src/pinned_reconciler.rs@@ -3,8 +3,8 @@//! The gateway owns the pinned-model set per logical pool (`PoolSpec.pinned_models`,//! set via the `/v1/pools` API or `SIE_GATEWAY_STATIC_QUEUE_POOLS`). This//! module polls that source of truth on a timer, computes the union of pins for-//! logical pools that currently assign this worker, and pushes it to the Python-//! worker over IPC on change, so the worker eager-loads pinned models and+//! logical pools that currently assign this worker, and pushes it to the backend+//! over IPC on change, so the worker eager-loads pinned models and//! excludes them from eviction.//!//! It is deliberately decoupled from the pool admission gate: a deployment may@@ -13,7 +13,7 @@//! whenever a gateway URL is configured, independent of admission.//!//! There is no gateway push channel for pool changes, so delivery is poll-based-//! (mirroring `config_reconciler`). The Python `set_pinned_models` mutator is+//! (mirroring `config_reconciler`). The backend `set_pinned_models` mutator is//! idempotent, so a redundant push is harmless; we still suppress no-op pushes//! via change detection.diff --git a/packages/sie_server_sidecar/src/pool_admission.rs b/packages/sie_server_sidecar/src/pool_admission.rsindex 11d22f7aa..8f78e8134 100644--- a/packages/sie_server_sidecar/src/pool_admission.rs+++ b/packages/sie_server_sidecar/src/pool_admission.rs@@ -3,7 +3,7 @@//! The gateway owns pool assignment. The sidecar polls `/v1/pools`, opens its//! physical JetStream consumer only when the physical pool or at least one//! backed logical pool assigns this worker, then checks every work item's-//! `admission_pool` before Python IPC so direct NATS publishes cannot bypass+//! `admission_pool` before backend IPC so direct NATS publishes cannot bypass//! the gateway's admission decision.use std::collections::HashSet;diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex ca7799f47..00185dea5 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -266,9 +266,9 @@ pub struct EnsureModelReadyResponse {/// `sie.config.models.<bundle>` subscriber.////// Rust owns the NATS subscription, producer validation, epoch gating, and-/// health hash publication. Python owns schema validation and mutation of the-/// adapter-local `ModelRegistry`, so the actual registry write remains in the-/// process that serves inference.+/// health hash publication. The colocated backend owns schema validation and+/// mutation of its local registry/catalog, so the actual registry write remains+/// in the process that serves inference.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct ApplyModelConfigRequest {pub bundle_id: String,@@ -320,9 +320,9 @@ pub struct ReplaceModelConfigsResponse {/// worker. The sidecar polls the pool's `PoolSpec.pinned_models` (the single/// source of truth, set via the `/v1/pools` API or/// `SIE_GATEWAY_STATIC_QUEUE_POOLS`) and pushes it here on change. `models`-/// carries gateway-canonical ids (bare `sie_id` or `sie_id:profile`); Python-/// normalizes them. The set is authoritative and REPLACES the worker's current-/// pinned set.+/// carries gateway-canonical ids (bare `sie_id` or `sie_id:profile`); the+/// backend normalizes them. The set is authoritative and REPLACES the worker's+/// current pinned set.#[derive(Debug, Clone, Serialize, Deserialize)]pub struct SetPinnedModelsRequest {pub models: Vec<String>,@@ -371,7 +371,7 @@ pub struct GenerateEvent {#[derive(Debug, Clone, Default, Serialize, Deserialize)]pub struct WorkerCapabilitiesRequest {- // No fields: the method asks Python to describe its local registry.+ // No fields: the method asks the backend to describe its local registry.}#[derive(Debug, Clone, Default, Serialize, Deserialize)]diff --git a/packages/sie_server_sidecar/src/scheduler/engine.rs b/packages/sie_server_sidecar/src/scheduler/engine.rsindex e8e546cf1..d94861737 100644--- a/packages/sie_server_sidecar/src/scheduler/engine.rs+++ b/packages/sie_server_sidecar/src/scheduler/engine.rs@@ -6,7 +6,7 @@//! but **only the scheduling half** — admission, per-LoRA batch//! formation, FCFS fairness, and the adaptive-controller step after//! each batch. The forward pass + adapter I/O still happen-//! Python-side; this module decides *which batch* to dispatch and+//! backend-side; this module decides *which batch* to dispatch and//! *when*, then hands it off.//!//! ## Routingdiff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 9b25662df..0fa59740b 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.15",+ "version": "0.6.16","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 04b3a7fd5..5d2251a83 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.15"; // x-release-please-version+export const SDK_VERSION = "0.6.16"; // x-release-please-versiondiff --git a/pyproject.toml b/pyproject.tomlindex 842667975..549b40a24 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -120,7 +120,7 @@ members = [[tool.pytest.ini_options]# Note: integrations are NOT in testpaths because each has its own conftest.py# which causes pytest plugin conflicts. Run with: mise run test integrations/-testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", "packages/sie_tools/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests"]+testpaths = ["packages/sie_server/tests", "packages/sie_sdk/tests", "packages/sie_bench/tests", "packages/sie_admin/tests", "packages/sie_config/tests", "packages/sie_mcp/tests", "packages/sie_tools/tests", "tools/mise_tasks/tests", "tools/quality_eval/tests", "product/research/sie-cost-model/bill-cut-model/tests"]pythonpath = ["packages/sie_server/src", "packages/sie_sdk/src", "packages/sie_bench/src", "packages/sie_admin/src", "packages/sie_config/src", "packages/sie_mcp/src", "packages/sie_tools/src", "tools/mise_tasks"]addopts = "-m 'not integration and not docker and not model' --import-mode=importlib"asyncio_mode = "auto"diff --git a/uv.lock b/uv.lockindex a25075b44..f49f99ecb 100644--- a/uv.lock+++ b/uv.lock@@ -5719,7 +5719,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.15"+version = "0.6.16"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5752,7 +5752,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.15"+version = "0.6.16"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5837,7 +5837,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5909,7 +5909,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5934,7 +5934,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5959,7 +5959,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5986,7 +5986,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6013,7 +6013,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6040,7 +6040,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6106,7 +6106,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6129,7 +6129,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.15"+version = "0.6.16"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6182,7 +6182,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.15"+version = "0.6.16"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6318,7 +6318,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.15"+version = "0.6.16"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },