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
sync source: v0.7.3 sync authority: 403a93b8735a74a3a46856c8e22ac13ee957ba12
github-actions[bot]60996d9c3016
diff --git a/COMPATIBILITY.md b/COMPATIBILITY.mdindex 12eaada3a..46accf9d9 100644--- a/COMPATIBILITY.md+++ b/COMPATIBILITY.md@@ -14,9 +14,11 @@ All SIE packages are at **0.x pre-release** (currently 0.1.x). Per [SemVer 2.0.0## Versioning Scheme-### Mono-Version+### SIE Release Version-All packages share a **single version number**, managed by [release-please](https://github.com/googleapis/release-please). A release bumps the version across every artifact simultaneously:+Artifacts produced by this repository share a **single version number**,+managed by [release-please](https://github.com/googleapis/release-please). An+SIE release bumps these artifacts together:| Artifact | Registry | Example ||----------|----------|---------|@@ -25,13 +27,18 @@ All packages share a **single version number**, managed by [release-please](http| `@superlinked/sie-sdk`, `@superlinked/sie-langchain`, `@superlinked/sie-llamaindex`, `@superlinked/sie-chroma` | npm | 0.1.6 || `sie-cluster` Helm chart | OCI (`ghcr.io/superlinked/charts`) | 0.1.6 || `sie-server`, `sie-gateway` Docker images | ghcr.io | 0.1.6 |-| `superlinked/sie/google`, `superlinked/sie/aws` Terraform modules | Terraform Registry | 0.1.6 |`sie-server` and `sie-gateway` are distributed as Docker images rather than PyPI packages.-**Why mono-version:** Simplifies compatibility reasoning. Users deploy matching versions of SDK, server, gateway, and Helm chart. The version skew detection (see below) depends on this guarantee.+The Alibaba Cloud, AWS, Azure, and Google Cloud Terraform modules are+independently versioned libraries. Their public repositories own their source,+compatibility policy, tags, releases, and Terraform Registry versions. A+Terraform module version does not identify an SIE, image, or Helm chart+version; consumers pin a tested combination deliberately.-**Post-1.0 plan:** Re-evaluate independent versioning after 1.0 if package release cadences diverge significantly. Until then, mono-version remains the approach.+**Why one SIE release version:** It simplifies compatibility reasoning for the+SDK, server, gateway, images, and Helm chart. The version skew detection (see+below) depends on this guarantee.### SemVer Interpretation@@ -220,7 +227,7 @@ SIE will declare 1.0 when all of the following are true:### Publishing-- [ ] All packages published to public registries (PyPI, npm, ghcr.io, OCI Helm, Terraform Registry)+- [ ] All SIE release artifacts published to public registries (PyPI, npm, ghcr.io, OCI Helm)- [ ] CI/CD pipeline runs tests, linting, and type checking on every PR- [ ] Release automation produces changelogs and publishes artifacts on tagdiff --git a/Cargo.lock b/Cargo.lockindex f04553777..59b24616a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -488,9 +488,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"[[package]]name = "chacha20"-version = "0.10.1"+version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"dependencies = ["cfg-if","cpufeatures 0.3.0",@@ -3773,7 +3773,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-audio-prep"-version = "0.7.2"+version = "0.7.3"dependencies = ["audioadapter-buffers","opusic-sys",@@ -3787,7 +3787,7 @@ dependencies = [[[package]]name = "sie-gateway"-version = "0.7.2"+version = "0.7.3"dependencies = ["arc-swap","async-nats",@@ -3849,7 +3849,7 @@ dependencies = [[[package]]name = "sie-server-sidecar"-version = "0.7.2"+version = "0.7.3"dependencies = ["anyhow","async-nats",diff --git a/conformance/bundle_config_hash/serving_artifact_expanded_profile_vector.json b/conformance/bundle_config_hash/serving_artifact_expanded_profile_vector.jsonnew file mode 100644index 000000000..d428610fd--- /dev/null+++ b/conformance/bundle_config_hash/serving_artifact_expanded_profile_vector.json@@ -0,0 +1,45 @@+{+ "_comment": "One shared config-service/worker/gateway bundle-config-hash vector for an inherited profile whose effective loadtime selects the default profile's immutable derived serving artifact. Both manifest variants must match the exact expected SHA-256 in all three runtimes.",+ "bundle_id": "derived-bundle",+ "bundle": {+ "name": "derived-bundle",+ "priority": 10,+ "adapters": ["test.derived_adapter"]+ },+ "model": {+ "sie_id": "google/source-model",+ "hf_id": "google/source-model",+ "hf_revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "tasks": {},+ "profiles": {+ "default": {+ "adapter_path": "test.derived_adapter:Adapter",+ "max_batch_tokens": 128,+ "adapter_options": {+ "loadtime": {+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+ "compute_type": "bfloat16"+ }+ }+ }+ },+ "inherited": {+ "extends": "default",+ "max_batch_tokens": 64+ }+ }+ },+ "manifest_sha256": {+ "initial": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",+ "changed": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"+ },+ "expected_hash": {+ "initial": "b4ae71e7457e6f797a0d462464e155f1f85cbb03cf6dc4382842af7967e40865",+ "changed": "dafbb6dd7b743517f808699e5a3f322bb95270420acb7726066207a65d895f08"+ }+}diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex 9b667a58c..e1df26b00 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.7.2 # x-release-please-version-appVersion: v0.7.2 # x-release-please-version+version: 0.7.3 # x-release-please-version+appVersion: v0.7.3 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex 364f0b5aa..83b65e3ca 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -405,11 +405,16 @@ processors:log_record:- 'resource.attributes["service.name"] != "sie-gateway"'- 'attributes["event.name"] != "inference.request.completed"'- - 'attributes["event.schema.version"] != "1"'+ # Keep v1 readable while old gateway pods drain during a rolling update.+ - 'attributes["event.schema.version"] != "1" and attributes["event.schema.version"] != "2"'- 'body != "inference.request.completed"'- 'attributes["operation"] != "encode" and attributes["operation"] != "score" and attributes["operation"] != "extract" and attributes["operation"] != "generate" and attributes["operation"] != "embeddings" and attributes["operation"] != "moderations" and attributes["operation"] != "other"'- 'attributes["outcome"] != "success" and attributes["outcome"] != "redirect" and attributes["outcome"] != "client_error" and attributes["outcome"] != "server_error" and attributes["outcome"] != "other"'- 'attributes["http.status_code"] < 100 or attributes["http.status_code"] > 599'+ - 'attributes["event.schema.version"] == "2" and attributes["model"] == nil'+ - 'attributes["event.schema.version"] == "2" and attributes["machine_profile"] == nil'+ - 'attributes["event.schema.version"] == "2" and attributes["duration_ms"] == nil'+ - 'attributes["event.schema.version"] == "2" and attributes["admission_outcome"] != "admitted" and attributes["admission_outcome"] != "unauthenticated" and attributes["admission_outcome"] != "forbidden" and attributes["admission_outcome"] != "auth_misconfigured" and attributes["admission_outcome"] != "region_mismatch" and attributes["admission_outcome"] != "license_excluded" and attributes["admission_outcome"] != "payload_too_large" and attributes["admission_outcome"] != "invalid_request" and attributes["admission_outcome"] != "insufficient_credits" and attributes["admission_outcome"] != "key_spend_limit_exceeded" and attributes["admission_outcome"] != "rate_limited"'transform/contract_logs:error_mode: propagatelog_statements:@@ -425,9 +430,12 @@ processors:- set(schema_url, "")- context: logstatements:- - keep_keys(attributes, ["event.name", "event.schema.version", "operation", "outcome", "http.status_code"])+ - keep_keys(attributes, ["event.name", "event.schema.version", "operation", "outcome", "http.status_code", "model", "machine_profile", "duration_ms", "admission_outcome"])+ # Canonical release domains are rechecked at the collector boundary+ # so malformed producer values cannot become vendor dimensions.+ - 'set(attributes["model"], "other") where attributes["event.schema.version"] == "2" and not IsMatch(attributes["model"], "^(BAAI/bge-m3|IDEA-Research/grounding-dino-base|Qwen/Qwen3-Embedding-4B|Qwen/Qwen3-Reranker-0[.]6B|Qwen/Qwen3-Reranker-4B|Qwen/Qwen3-VL-Reranker-2B|Qwen/Qwen3[.]5-4B|Qwen/Qwen3[.]6-27B|Snowflake/snowflake-arctic-embed-l-v2[.]0|docling|fastino/gliguard-LLMGuardrails-300M|fastino/gliner2-base-v1|fastino/gliner2-large-v1|google/owlv2-base-patch16-ensemble|google/siglip-so400m-patch14-384|google/siglip2-base-patch16-224|ibm-granite/granite-guardian-3[.]0-2b|knowledgator/gliclass-large-v3[.]0|lightonai/GTE-ModernColBERT-v1|lightonai/LightOnOCR-2-1B|numind/NuNER_Zero|openai/whisper-large-v3-turbo|other|prithivida/Splade_PP_en_v2|tencent/R3-embedding-0[.]6b|tencent/R3-rerank-0[.]6b|urchade/gliner_multi-v2[.]1|urchade/gliner_multi_pii-v1)$")'+ - 'set(attributes["machine_profile"], "other") where attributes["event.schema.version"] == "2" and not IsMatch(attributes["machine_profile"], "^(a10|a100-40gb|a100-80gb|cpu|h100|l4|l4-spot|other|sglang-cu130|t4)$")'- set(attributes["event.name"], "inference.request.completed")- - set(attributes["event.schema.version"], "1")- set(body, "inference.request.completed")- set(severity_text, "INFO")- set(severity_number, SEVERITY_NUMBER_INFO)diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 38d5d5686..7c1f7e5ec 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -448,6 +448,8 @@ workers:bundlePlatforms:# SGLang cu130 (Gemma 4 plus newer Qwen profiles) ships only as a CUDA 13 image.sglang-cu130: cuda13+ # TensorRT-LLM direct-HF encoder-decoder workers ship only as CUDA 13 images.+ tensorrt-llm: cuda13# -- Image pre-pull DaemonSet (caches worker image on GPU nodes before worker pods schedule)imagePrepull:diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex a27d56425..4868b3b45 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.7.2"+version = "0.7.3"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 02e0035ac..39b354a91 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.7.2"+version = "0.7.3"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 347bfc27d..b08fe7889 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.7.2"+version = "0.7.3"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 325c81d54..18ad079ed 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.7.2"+version = "0.7.3"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 6447f7601..35d6d5dcb 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.7.2"+version = "0.7.3"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 0dce46fd9..01c01ebed 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.7.2"+version = "0.7.3"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex c907abca1..f82214f78 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.7.2"+version = "0.7.3"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 3c90b9f91..df3c7b915 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.7.2"+version = "0.7.3"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 e97dbcb60..0da843368 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.7.2",+ "version": "0.7.3","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 a640f9271..b272df37f 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.7.2",+ "version": "0.7.3","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 a57360e61..a6d2f1150 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.7.2",+ "version": "0.7.3","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 a0f05489d..5a02f2a09 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.7.2",+ "version": "0.7.3","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 dfc6b1163..933af0e3d 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.7.2"+version = "0.7.3"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_audio_prep/Cargo.toml b/packages/sie_audio_prep/Cargo.tomlindex 11d5dfde2..dfc654e45 100644--- a/packages/sie_audio_prep/Cargo.toml+++ b/packages/sie_audio_prep/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-audio-prep"-version = "0.7.2"+version = "0.7.3"edition = "2021"license = "Apache-2.0"description = "Bounded, shared audio decoding and resampling for SIE workers."diff --git a/packages/sie_audio_prep/build_wheel.py b/packages/sie_audio_prep/build_wheel.pyindex 4c61c2f0b..24405057f 100644--- a/packages/sie_audio_prep/build_wheel.py+++ b/packages/sie_audio_prep/build_wheel.py@@ -16,7 +16,7 @@ import zipfilefrom pathlib import PathMATURIN_VERSION = "1.13.3"-AUDIO_PREP_VERSION = "0.7.2" # x-release-please-version+AUDIO_PREP_VERSION = "0.7.3" # x-release-please-versionAUDIO_WHEEL_COMPATIBILITY = "manylinux_2_28"AUDIO_WHEEL_FILENAME = f"sie_audio_prep-{AUDIO_PREP_VERSION}-cp312-abi3-{AUDIO_WHEEL_COMPATIBILITY}_x86_64.whl"AUDIO_WHEEL_REMOTE = f"/opt/sie/wheels/{AUDIO_WHEEL_FILENAME}"diff --git a/packages/sie_audio_prep/pyproject.toml b/packages/sie_audio_prep/pyproject.tomlindex cdcec896b..d6af2081e 100644--- a/packages/sie_audio_prep/pyproject.toml+++ b/packages/sie_audio_prep/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "maturin"[project]name = "sie-audio-prep"-version = "0.7.2"+version = "0.7.3"description = "Bounded, shared audio decoding and resampling for SIE workers."requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_config/tests/test_hash_consistency.py b/packages/sie_config/tests/test_hash_consistency.pyindex b76fb3efd..b98459ca1 100644--- a/packages/sie_config/tests/test_hash_consistency.py+++ b/packages/sie_config/tests/test_hash_consistency.py@@ -1,3 +1,4 @@+import jsonimport tempfilefrom pathlib import Pathfrom types import SimpleNamespace@@ -233,6 +234,59 @@ class TestHashConsistency:assert second_config == second_workerassert first_config != second_config+ def test_serving_artifact_manifest_digest_changes_worker_parity_hash(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ) -> None:+ root = self._root / "serving_artifacts"+ bundles_dir = root / "bundles"+ models_dir = root / "models"+ bundles_dir.mkdir(parents=True)+ models_dir.mkdir(parents=True)+ fixture = (+ Path(__file__).resolve().parents[3]+ / "conformance"+ / "bundle_config_hash"+ / "serving_artifact_expanded_profile_vector.json"+ )+ vector = json.loads(fixture.read_text())+ bundle_id = vector["bundle_id"]+ (bundles_dir / f"{bundle_id}.yaml").write_text(json.dumps(vector["bundle"]))++ def resolve_worker_default_dir(name: str) -> Path:+ if name == "bundles":+ return bundles_dir+ return root / name++ monkeypatch.setattr(worker_ws, "_resolve_default_dir", resolve_worker_default_dir)++ def hashes(manifest_sha256: str) -> tuple[str, str]:+ model_config = json.loads(json.dumps(vector["model"]))+ model_config["profiles"]["default"]["adapter_options"]["loadtime"]["serving_artifact"][+ "manifest_sha256"+ ] = manifest_sha256+ (models_dir / "google__source-model.yaml").write_text(json.dumps(model_config))+ config_hash = ModelRegistry(bundles_dir, models_dir).compute_bundle_config_hash(bundle_id)+ worker_ws._bundle_adapter_modules.cache_clear()+ try:+ worker_registry = WorkerModelRegistry(+ models_dir=models_dir,+ model_filter=["google/source-model"],+ pool_name="default",+ enable_hot_reload=False,+ )+ worker_hash = compute_bundle_config_hash_cached(worker_registry, bundle_id)+ finally:+ worker_ws._bundle_adapter_modules.cache_clear()+ return config_hash, worker_hash++ first_config, first_worker = hashes(vector["manifest_sha256"]["initial"])+ second_config, second_worker = hashes(vector["manifest_sha256"]["changed"])++ assert first_config == first_worker == vector["expected_hash"]["initial"]+ assert second_config == second_worker == vector["expected_hash"]["changed"]+ assert first_config != second_config+def test_worker_hash_fails_closed_when_bundle_metadata_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:root = self._root / "missing_bundle"models_dir = root / "models"diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 2bcc03bbe..e0f0fe1c5 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.7.2"+version = "0.7.3"edition = "2021"publish = falsediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 9c1f1df97..0dba034b9 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -61,7 +61,7 @@ Rules enforced on the inference path:- 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`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.- 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.-- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.+- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, and `LORA_LOADING`. Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk; the gateway accepts only an integer in `1..=60` on that exact error class and otherwise uses the backward-compatible 5-second default. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 8b3978058..e06f3e02e 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -1578,6 +1578,22 @@},"message": {"type": "string"+ },+ "param": {+ "type": [+ "string",+ "null"+ ]+ },+ "retry_after_s": {+ "description": "Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null\nfor other terminal errors.",+ "format": "int32",+ "maximum": 60,+ "minimum": 1,+ "type": [+ "integer",+ "null"+ ]}},"required": [@@ -2136,6 +2152,13 @@"description": "Whether the model targets the SQL path — backs the ``model=\"sql\"``\nalias. Informational only; never request-gated. Precision-sensitive:\nSQL quality can regress sharply under FP8, so this model-level flag is a\nsupport signal, not a per-profile quality guarantee.","type": "boolean"},+ "streaming": {+ "description": "Whether the model supports incremental public generation output.\nDefaults to true for generation models when omitted from older configs.",+ "type": [+ "boolean",+ "null"+ ]+ },"tools": {"description": "Whether the model supports tool / function calling.","type": [@@ -3871,7 +3894,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.7.2"+ "version": "0.7.3"},"openapi": "3.1.0","paths": {@@ -4134,6 +4157,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -4423,6 +4453,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -4621,6 +4658,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -5205,6 +5249,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -5543,6 +5594,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -5882,6 +5940,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -6200,6 +6265,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -7181,6 +7253,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {@@ -7464,6 +7543,13 @@"type": "string"}},+ "X-SIE-Execution-Binding-SHA256": {+ "description": "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ "schema": {+ "pattern": "^[0-9a-f]{64}$",+ "type": "string"+ }+ },"X-SIE-Execution-Identity-SHA256": {"description": "Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available","schema": {diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 82254eb3d..01fe62512 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -287,6 +287,7 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {max_output_tokens: None,profile_max_output_tokens: HashMap::new(),grammar_capabilities: None,+ streaming_supported: None,grammar_profile: None,profile_parents: HashMap::new(),tools_supported: None,diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 37fc43cc1..98783cfdd 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -22,7 +22,11 @@ use crate::queue::dispatch::{DispatchDurability, DispatchError, PendingDispatchKind, WorkDispatcher, WorkDispatcherExt,};use crate::queue::publisher;-use crate::queue::streaming::is_lower_sha256;+use crate::queue::streaming::{+ client_safe_worker_error_code, client_safe_worker_error_message,+ client_safe_worker_error_param, is_lower_sha256, MODEL_LOAD_FAILED_ERROR_CODE,+ MODEL_LOAD_FAILED_PUBLIC_MESSAGE,+};use crate::server::{AppState, GenerationRequestIntent, GovernedGenerationRoute, ModelAccessPolicy,@@ -368,10 +372,6 @@ const RESOURCE_EXHAUSTED_RETRY_AFTER: &str = RetryAfter::DEFAULT.resource_exhaus/// see ``sie_sdk.client._shared.LORA_LOADING_*``.const LORA_LOADING_ERROR_CODE: &str = "LORA_LOADING";const LORA_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.lora_loading;-/// Terminal model load failure (non-retryable). Matches ``sie_server`` HTTP 502-/// contract so ``sie_sdk`` can short-circuit before the ``MODEL_LOADING`` retry-/// budget (see ``raise_if_model_load_failed``).-const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";const INVALID_INPUT_ERROR_CODE: &str = "INVALID_INPUT";const PAYLOAD_TOO_LARGE_ERROR_CODE: &str = err_code::PAYLOAD_TOO_LARGE;@@ -2235,6 +2235,18 @@ async fn proxy_request_inner(Err(resp) => return *resp,};+ if let Some((items, params)) = governed_generate_parsed.as_ref() {+ if let Some(response) = validate_native_generate_pre_admission(+ &state,+ &model_name,+ &dispatch_model,+ items,+ params,+ ) {+ return response;+ }+ }+// Publish the canonical `machine_profile` to the HTTP metrics// middleware via a request extension slot. The middleware reads// this AFTER the inner service responds, so every downstream@@ -2255,6 +2267,7 @@ async fn proxy_request_inner(// space stays bounded."invalid".to_string()},+ model: model_name.clone(),});}@@ -2566,6 +2579,158 @@ fn queue_parse_error_response(endpoint: &str, error: QueueParseError) -> Respons}}+fn unsupported_streaming_response(+ registry: &crate::state::model_registry::ModelRegistry,+ model: &str,+ display_model: &str,+ stream: bool,+) -> Option<Response> {+ if !stream {+ return None;+ }+ let streaming_supported = registry+ .get_model_info(model)+ .and_then(|info| info.info_extras.streaming_supported);+ if streaming_supported != Some(false) {+ return None;+ }+ Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!("Model '{display_model}' does not support streaming generation"),+ oai_type::INVALID_REQUEST,+ Some("stream"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response(),+ )+}++fn validate_native_generate_pre_admission(+ state: &AppState,+ display_model: &str,+ model: &str,+ items: &[rmpv::Value],+ params: &publisher::WorkParams,+) -> Option<Response> {+ if let Err(message) = publisher::validate_queue_request_item_count(items.len()) {+ return Some(endpoint_error_response(+ "generate",+ StatusCode::BAD_REQUEST,+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ message,+ ));+ }++ let Some(generate) = params.generate.as_ref() else {+ return Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ "generate request requires non-empty 'prompt' and positive integer 'max_new_tokens'",+ oai_type::INVALID_REQUEST,+ Some("prompt"),+ oai_code::INVALID_REQUEST,+ )),+ )+ .into_response(),+ );+ };++ if let Some(response) =+ unsupported_streaming_response(&state.model_registry, model, display_model, generate.stream)+ {+ return Some(response);+ }++ if let Some(grammar) = generate.grammar.as_ref() {+ let capabilities = state+ .model_registry+ .get_model_info(model)+ .as_ref()+ .and_then(|entry| entry.info_extras.grammar_capabilities.clone());+ if let Err(response) =+ super::grammar::check_capability(grammar, capabilities.as_deref(), display_model)+ {+ return Some(response);+ }+ }++ if let Some(requested_lora) = generate.lora_adapter.as_deref() {+ if let Some(info) = state.model_registry.get_model_info(model) {+ let profile_name = params+ .options+ .as_ref()+ .and_then(|options| options.get("profile"))+ .and_then(|value| value.as_str())+ .unwrap_or("default");+ match validate_lora_for_profile(&info, profile_name, requested_lora) {+ LoraValidation::Ok => {}+ LoraValidation::UnknownProfile => {+ return Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!(+ "unknown profile '{profile_name}' for model '{display_model}'"+ ),+ oai_type::INVALID_REQUEST,+ Some("profile"),+ oai_code::INVALID_REQUEST,+ )),+ )+ .into_response(),+ );+ }+ LoraValidation::UnknownAdapter => {+ return Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!(+ "unknown lora_adapter '{requested_lora}' for model '{display_model}'"+ ),+ oai_type::INVALID_REQUEST,+ Some("lora_adapter"),+ oai_code::UNKNOWN_LORA_ADAPTER,+ )),+ )+ .into_response(),+ );+ }+ }+ }+ }++ if generate_params_have_images(generate) {+ let image_supported = state+ .model_registry+ .get_model_info(model)+ .is_some_and(|info| info.info_extras.supports_vision_generation());+ if !native_generate_image_input_allowed(Some(generate), image_supported) {+ return Some(+ (+ StatusCode::BAD_REQUEST,+ Json(json_openai_error(+ format!("Model '{display_model}' does not support image input"),+ oai_type::INVALID_REQUEST,+ Some("images"),+ oai_code::UNSUPPORTED_FIELD,+ )),+ )+ .into_response(),+ );+ }+ }++ None+}+#[allow(clippy::too_many_arguments)]async fn queue_mode_proxy(state: &AppState,@@ -2623,121 +2788,6 @@ async fn queue_mode_proxy();}- // Generate requires the typed ``params.generate`` block from the parser.- // The parser returns ``None`` for missing/invalid prompt / max_new_tokens- // and we translate that to a 400 with an instructive message here. This- // is the gateway-side enforcement called out in §4.5.1.1 of the POC plan.- if endpoint == "generate" && params.generate.is_none() {- return (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- "generate request requires non-empty 'prompt' and positive integer 'max_new_tokens'",- oai_type::INVALID_REQUEST,- Some("prompt"),- oai_code::INVALID_REQUEST,- )),- )- .into_response();- }-- // Grammar capability gate. After ``parse_grammar`` has accepted- // the wire shape and enforced the safety caps, check the model's- // YAML-declared ``capabilities.grammar`` list. Rejecting here (not- // inside the parser) keeps :func:`parse_grammar` decoupled from- // the model registry and shareable with the chat translator- // upstream of model resolution.- if endpoint == "generate" {- if let Some(g) = params.generate.as_ref().and_then(|p| p.grammar.as_ref()) {- let caps = state- .model_registry- .get_model_info(model)- .as_ref()- .and_then(|m| m.info_extras.grammar_capabilities.clone());- // Look the capabilities up on the DISPATCH variant, but name the- // requested (DISPLAY) model in the rejection so the client never- // sees the internal ``:no-spec`` id (mirrors the chat path).- if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), display_model) {- return resp;- }- }- // M8/M10: lora_adapter allow-list gate (mirrors chat's gate).- // Cross-check the requested served-name against the *selected- // profile's* advertised adapters — not the union across- // profiles — before the request crosses the JetStream boundary.- // Worker still validates redundantly; this exists so SDKs see a- // fast 400 with the stable ``unknown_lora_adapter`` code- // instead of a queue-bounce error chunk. Profile selection- // follows the same idiom as ``generation_timeout_config``:- // ``options.profile`` (default ``"default"``).- if let Some(req_lora) = params- .generate- .as_ref()- .and_then(|p| p.lora_adapter.as_deref())- {- if let Some(info) = state.model_registry.get_model_info(model) {- let profile_name = params- .options- .as_ref()- .and_then(|opts| opts.get("profile"))- .and_then(|v| v.as_str())- .unwrap_or("default");- match validate_lora_for_profile(&info, profile_name, req_lora) {- LoraValidation::Ok => {}- LoraValidation::UnknownProfile => {- return (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- format!(- "unknown profile '{profile_name}' for model '{display_model}'"- ),- oai_type::INVALID_REQUEST,- Some("profile"),- oai_code::INVALID_REQUEST,- )),- )- .into_response();- }- LoraValidation::UnknownAdapter => {- return (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- format!(- "unknown lora_adapter '{req_lora}' for model '{display_model}'"- ),- oai_type::INVALID_REQUEST,- Some("lora_adapter"),- oai_code::UNKNOWN_LORA_ADAPTER,- )),- )- .into_response();- }- }- }- }- let has_images = params- .generate- .as_ref()- .is_some_and(generate_params_have_images);- if has_images {- let image_supported = state- .model_registry- .get_model_info(model)- .is_some_and(|info| info.info_extras.supports_vision_generation());- if !native_generate_image_input_allowed(params.generate.as_ref(), image_supported) {- return (- StatusCode::BAD_REQUEST,- Json(json_openai_error(- format!("Model '{display_model}' does not support image input"),- oai_type::INVALID_REQUEST,- Some("images"),- oai_code::UNSUPPORTED_FIELD,- )),- )- .into_response();- }- }- }-// Generate has its own publish + result-collection path// (streaming chunk aggregation instead of one-shot WorkResult fan-in).if endpoint == "generate" {@@ -3075,11 +3125,7 @@ async fn queue_mode_proxy(.iter().all(|r| r.error_code.as_deref() == Some(MODEL_LOAD_FAILED_ERROR_CODE)){- let first_msg = errors- .first()- .and_then(|r| r.error.as_deref())- .unwrap_or("Model load failed");- return build_model_load_failed_response(model, first_msg);+ return build_model_load_failed_response();}// Translate retryable worker error codes into the SDK-expected 503// contract. Without this every per-item failure surfaced as 500@@ -3213,6 +3259,7 @@ async fn queue_mode_proxy(&successful,);insert_execution_identity_header(response.headers_mut(), &successful);+ insert_execution_binding_header(response.headers_mut(), &successful);response.headers_mut().insert(HeaderName::from_static("x-sie-request-id"),HeaderValue::from_str(&request_id).unwrap_or_else(|_| HeaderValue::from_static("")),@@ -3491,11 +3538,13 @@ pub(crate) enum StreamingDriverErr {/// ``"first_chunk"`` | ``"inter_chunk"`` | ``"overall"``.Timeout { kind: &'static str },/// Worker emitted a terminal chunk with ``error`` populated. The- /// caller chooses the wire status/code mapping; this enum just- /// surfaces the raw worker fields.+ /// caller chooses the wire status/code mapping; message, parameter,+ /// and retry metadata are bounded at the worker trust boundary.WorkerError {code: String,message: String,+ param: Option<String>,+ retry_after_s: Option<u16>,request_id: String,attempt_id: String,},@@ -3993,8 +4042,10 @@ pub(crate) async fn run_streaming_generate(// failure. The caller chooses the HTTP status / wire envelope.if let Some(err) = outcome.error.as_ref() {return Err(StreamingDriverErr::WorkerError {- code: err.code.clone(),- message: err.message.clone(),+ code: err.client_safe_code().to_string(),+ message: err.client_safe_message().to_string(),+ param: err.client_safe_param().map(str::to_string),+ retry_after_s: err.validated_retry_after_s(),request_id: request_id.clone(),attempt_id: outcome.attempt_id.clone(),});@@ -4021,6 +4072,7 @@ pub(crate) fn worker_error_http_status(code: &str) -> StatusCode {RESOURCE_EXHAUSTED_ERROR_CODE | MODEL_LOADING_ERROR_CODE | LORA_LOADING_ERROR_CODE => {StatusCode::SERVICE_UNAVAILABLE}+ MODEL_LOAD_FAILED_ERROR_CODE => StatusCode::BAD_GATEWAY,"transport_failure" => StatusCode::SERVICE_UNAVAILABLE,"cancelled" => StatusCode::REQUEST_TIMEOUT,"rate_limit_exceeded" => StatusCode::TOO_MANY_REQUESTS,@@ -4052,14 +4104,26 @@ pub(crate) fn worker_error_openai_type(code: &str) -> &'static str {/// (SIE-native [`build_retryable_error_response`]) paths — the two surfaces/// render the error body differently but agree on the retry semantics. Pairs/// with [`worker_error_http_status`] / [`worker_error_openai_type`].-fn worker_error_retry_after(code: &str) -> Option<(&'static str, &'static str)> {+fn worker_error_retry_after(+ code: &str,+ resource_exhausted_retry_after_s: Option<u16>,+) -> Option<(String, &'static str)> {match code {RESOURCE_EXHAUSTED_ERROR_CODE => Some((- RESOURCE_EXHAUSTED_RETRY_AFTER,+ resource_exhausted_retry_after_s+ .filter(|value| (1..=60).contains(value))+ .map(|value| value.to_string())+ .unwrap_or_else(|| RESOURCE_EXHAUSTED_RETRY_AFTER.to_string()),RESOURCE_EXHAUSTED_ERROR_CODE,)),- MODEL_LOADING_ERROR_CODE => Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE)),- LORA_LOADING_ERROR_CODE => Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE)),+ MODEL_LOADING_ERROR_CODE => Some((+ MODEL_LOADING_RETRY_AFTER.to_string(),+ MODEL_LOADING_ERROR_CODE,+ )),+ LORA_LOADING_ERROR_CODE => Some((+ LORA_LOADING_RETRY_AFTER.to_string(),+ LORA_LOADING_ERROR_CODE,+ )),_ => None,}}@@ -4164,34 +4228,37 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {StreamingDriverErr::WorkerError {code,message,+ param,+ retry_after_s,request_id,attempt_id,} => {- let status = worker_error_http_status(code);- let err_type = worker_error_openai_type(code);- // Worker codes that already match our stable set get- // surfaced verbatim; unknowns fall back to a generic- // ``server_error`` discriminator.- let stable_code: &'static str = match code.as_str() {- "invalid_request" => oai_code::INVALID_REQUEST,- "unsupported_field" => oai_code::UNSUPPORTED_FIELD,- "context_exceeded" => oai_code::CONTEXT_EXCEEDED,+ if code == MODEL_LOAD_FAILED_ERROR_CODE {+ let mut resp = build_model_load_failed_response();+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-request-id"),+ HeaderValue::from_str(request_id)+ .unwrap_or_else(|_| HeaderValue::from_static("")),+ );+ return resp;+ }+ let stable_code = client_safe_worker_error_code(code);+ // OpenAI represents oversized request payloads as the canonical+ // invalid-request discriminator while the SIE code remains on the+ // response header. This is a compatibility rendering of an+ // already-classified safe code, not a second worker allowlist.+ let openai_code = match stable_code {PAYLOAD_TOO_LARGE_ERROR_CODE => oai_code::INVALID_REQUEST,- RESOURCE_EXHAUSTED_ERROR_CODE => RESOURCE_EXHAUSTED_ERROR_CODE,- MODEL_LOADING_ERROR_CODE => MODEL_LOADING_ERROR_CODE,- LORA_LOADING_ERROR_CODE => LORA_LOADING_ERROR_CODE,- "transport_failure" => oai_code::TRANSPORT_FAILURE,- "cancelled" => oai_code::CANCELLED,- "rate_limit_exceeded" => oai_code::RATE_LIMIT_EXCEEDED,- COLD_START_RATE_LIMITED_ERROR_CODE => COLD_START_RATE_LIMITED_ERROR_CODE,- // Terminal empty-output stamp (#3136): forwarded verbatim so- // buffered consumers see the same typed code the SSE path- // already streams. Same 500 / ``server_error`` / no-retry- // convention as the generic ``inference_error`` fallback.- oai_code::EMPTY_MODEL_OUTPUT => oai_code::EMPTY_MODEL_OUTPUT,- _ => "inference_error",+ _ => stable_code,};- let mut body = json_openai_error(message.clone(), err_type, None, stable_code);+ let status = worker_error_http_status(stable_code);+ let err_type = worker_error_openai_type(stable_code);+ let mut body = json_openai_error(+ client_safe_worker_error_message(code, message),+ err_type,+ client_safe_worker_error_param(code, param.as_deref()),+ openai_code,+ );// Surface the SIE-native ``attempt_id`` alongside the// OpenAI envelope so SIE-aware SDKs can correlate retries.if let Some(obj) = body.as_object_mut() {@@ -4213,24 +4280,27 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {// quota refusal, whose whole point is an HOURLY ceiling: a// 1-second retry hint would re-create the auto-retry hot loop// the rail exists to prevent (review finding).- if status == StatusCode::TOO_MANY_REQUESTS && code != COLD_START_RATE_LIMITED_ERROR_CODE+ if status == StatusCode::TOO_MANY_REQUESTS+ && stable_code != COLD_START_RATE_LIMITED_ERROR_CODE{resp.headers_mut().insert(HeaderName::from_static("retry-after"),HeaderValue::from_static("1"),);}- let retryable = worker_error_retry_after(code.as_str());+ let retryable = worker_error_retry_after(stable_code, *retry_after_s);if let Some((retry_after, error_code)) = retryable {resp.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_static(retry_after),+ HeaderValue::from_str(&retry_after).unwrap_or_else(|_| {+ HeaderValue::from_static(RESOURCE_EXHAUSTED_RETRY_AFTER)+ }),);resp.headers_mut().insert(HeaderName::from_static("x-sie-error-code"),HeaderValue::from_static(error_code),);- } else if code == PAYLOAD_TOO_LARGE_ERROR_CODE {+ } else if stable_code == PAYLOAD_TOO_LARGE_ERROR_CODE {resp.headers_mut().insert(HeaderName::from_static("x-sie-error-code"),HeaderValue::from_static(PAYLOAD_TOO_LARGE_ERROR_CODE),@@ -4386,6 +4456,7 @@ async fn queue_mode_streaming_generate(&outcome,);insert_stream_execution_identity_header(response.headers_mut(), &outcome);+ insert_stream_execution_binding_header(response.headers_mut(), &outcome);response.headers_mut().insert(HeaderName::from_static("x-sie-request-id"),HeaderValue::from_str(&request_id).unwrap_or_else(|_| HeaderValue::from_static("")),@@ -6717,6 +6788,7 @@ async fn resolve_generation_route(if let Some(slot) = metric_labels_slot {slot.set(telemetry::MetricLabels {machine_profile: effective_machine_profile.clone(),+ model: customer_model.to_string(),});}@@ -6955,6 +7027,14 @@ async fn proxy_chat_inner(// Gates resolve against the routed DISPATCH model so the profile-scoped// LoRA allow-list and capabilities match the profile that will serve.if let Some(info) = state.model_registry.get_model_info(&dispatch_model) {+ if let Some(response) = unsupported_streaming_response(+ &state.model_registry,+ &dispatch_model,+ &model_name,+ params.stream,+ ) {+ return response;+ }// Multi-LoRA: pre-validate the requested adapter against the// *selected profile's* advertised served-names — not the union// across profiles. The chat path has no explicit profile@@ -7250,6 +7330,7 @@ async fn proxy_chat_inner(&outcome,);insert_stream_execution_identity_header(response.headers_mut(), &outcome);+ insert_stream_execution_binding_header(response.headers_mut(), &outcome);response.headers_mut().insert(HeaderName::from_static("x-sie-request-id"),HeaderValue::from_str(&request_id).unwrap_or_else(|_| HeaderValue::from_static("")),@@ -7758,6 +7839,15 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)};let (explicit_bundle_override, _) = parse_model_spec(¶ms.model);+ if let Some(response) = unsupported_streaming_response(+ &state.model_registry,+ &model_name,+ &model_name,+ params.stream,+ ) {+ return response;+ }+let ResolvedRoute {physical_lane,bundle,@@ -7886,6 +7976,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)&outcome,);insert_stream_execution_identity_header(h, &outcome);+ insert_stream_execution_binding_header(h, &outcome);if let Ok(val) = HeaderValue::from_str(&request_id) {h.insert(HeaderName::from_static("x-sie-request-id"), val);}@@ -8485,6 +8576,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -&outcome,);insert_stream_execution_identity_header(h, &outcome);+ insert_stream_execution_binding_header(h, &outcome);if let Ok(val) = HeaderValue::from_str(&request_id) {h.insert(HeaderName::from_static("x-sie-request-id"), val);}@@ -8653,15 +8745,13 @@ pub(crate) fn enforce_first_chunk_invariant(}}-fn build_model_load_failed_response(model: &str, message: &str) -> Response {+fn build_model_load_failed_response() -> Response {let mut resp = (StatusCode::BAD_GATEWAY,Json(json!({"error": {"code": MODEL_LOAD_FAILED_ERROR_CODE,- "message": format!(- "Model '{model}' failed to load ({MODEL_LOAD_FAILED_ERROR_CODE}, attempts=1): {message}"- ),+ "message": MODEL_LOAD_FAILED_PUBLIC_MESSAGE,"error_class": MODEL_LOAD_FAILED_ERROR_CODE,"attempts": 1,"permanent": true,@@ -8893,7 +8983,7 @@ fn build_terminal_client_error_response(fn build_retryable_error_response(code: &'static str, message: &str) -> Response {// Retry hint via the shared `worker_error_retry_after` classifier — the// same source of truth the streaming path uses.- let retry_after = worker_error_retry_after(code)+ let retry_after = worker_error_retry_after(code, None).map(|(retry_after, _)| retry_after).unwrap_or_else(|| {// Defensive default. Should be unreachable given the@@ -8906,7 +8996,7 @@ fn build_retryable_error_response(code: &'static str, message: &str) -> Responsefalse,"build_retryable_error_response called with unmapped code: {code}");- MODEL_LOADING_RETRY_AFTER+ MODEL_LOADING_RETRY_AFTER.to_string()});let mut resp = (StatusCode::SERVICE_UNAVAILABLE,@@ -8920,7 +9010,7 @@ fn build_retryable_error_response(code: &'static str, message: &str) -> Response.into_response();resp.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_str(retry_after).unwrap_or_else(|_| HeaderValue::from_static("5")),+ HeaderValue::from_str(&retry_after).unwrap_or_else(|_| HeaderValue::from_static("5")),);resp.headers_mut().insert(HeaderName::from_static("x-sie-error-code"),@@ -9301,24 +9391,37 @@ fn insert_execution_identity_header(headers: &mut HeaderMap,successful: &[&publisher::WorkResult],) {- let Some(first) = successful- .first()- .and_then(|result| result.execution_identity_sha256.as_deref())- else {+ insert_unanimous_sha256_header(+ headers,+ successful,+ "x-sie-execution-identity-sha256",+ |result| result.execution_identity_sha256.as_deref(),+ );+}++fn insert_execution_binding_header(headers: &mut HeaderMap, successful: &[&publisher::WorkResult]) {+ insert_unanimous_sha256_header(+ headers,+ successful,+ "x-sie-execution-binding-sha256",+ |result| result.execution_binding_sha256.as_deref(),+ );+}++fn insert_unanimous_sha256_header<'a>(+ headers: &mut HeaderMap,+ successful: &[&'a publisher::WorkResult],+ header_name: &'static str,+ field: impl Fn(&'a publisher::WorkResult) -> Option<&'a str>,+) {+ let Some(first) = successful.first().and_then(|result| field(result)) else {return;};- if !is_lower_sha256(first)- || successful- .iter()- .any(|result| result.execution_identity_sha256.as_deref() != Some(first))- {+ if !is_lower_sha256(first) || successful.iter().any(|result| field(result) != Some(first)) {return;}if let Ok(value) = HeaderValue::from_str(first) {- headers.insert(- HeaderName::from_static("x-sie-execution-identity-sha256"),- value,- );+ headers.insert(HeaderName::from_static(header_name), value);}}@@ -9326,17 +9429,34 @@ fn insert_stream_execution_identity_header(headers: &mut HeaderMap,outcome: &crate::queue::streaming::StreamOutcome,) {- let Some(identity) = outcome.execution_identity_sha256.as_deref() else {+ insert_stream_sha256_header(+ headers,+ "x-sie-execution-identity-sha256",+ outcome.execution_identity_sha256.as_deref(),+ );+}++fn insert_stream_execution_binding_header(+ headers: &mut HeaderMap,+ outcome: &crate::queue::streaming::StreamOutcome,+) {+ insert_stream_sha256_header(+ headers,+ "x-sie-execution-binding-sha256",+ outcome.execution_binding_sha256.as_deref(),+ );+}++fn insert_stream_sha256_header(+ headers: &mut HeaderMap,+ header_name: &'static str,+ value: Option<&str>,+) {+ let Some(value) = value.filter(|value| is_lower_sha256(value)) else {return;};- if !is_lower_sha256(identity) {- return;- }- if let Ok(value) = HeaderValue::from_str(identity) {- headers.insert(- HeaderName::from_static("x-sie-execution-identity-sha256"),- value,- );+ if let Ok(value) = HeaderValue::from_str(value) {+ headers.insert(HeaderName::from_static(header_name), value);}}@@ -9397,6 +9517,7 @@ pub(crate) fn is_openai_compat_forwarded_header(name: &str) -> bool {"x-queue-time","x-sie-model-revision","x-sie-execution-identity-sha256",+ "x-sie-execution-binding-sha256","x-inference-time","x-tokenization-time","x-postprocessing-time",@@ -13806,11 +13927,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: Some(execution_hash.clone()),execution_identity_sha256: None,+ execution_binding_sha256: None,};insert_stream_model_revision_header(&mut headers,@@ -13913,11 +14036,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: Some(identity.clone()),+ execution_binding_sha256: None,};insert_stream_execution_identity_header(&mut headers, &outcome);assert_eq!(@@ -13933,13 +14058,96 @@ mod tests {assert!(headers.get("x-sie-execution-identity-sha256").is_none());}- #[tokio::test]- async fn test_endpoint_error_response_envelope_matches_endpoint() {- // generate/chat use the OpenAI `{error:{...}}` envelope; native endpoints- // keep `{detail:{...}}`. The engine-pin errors now route through this- // helper so a bad X-SIE-Engine on /v1/generate gets the OpenAI shape- // rather than the native one. See #1567.- let openai = endpoint_error_response(+ #[test]+ fn test_execution_binding_header_requires_valid_unanimous_worker_proof() {+ let binding = "e".repeat(64);+ let matching: publisher::WorkResult = serde_json::from_value(json!({+ "request_id": "request-1",+ "success": true,+ "execution_binding_sha256": binding.clone()+ }))+ .unwrap();+ let same: publisher::WorkResult = serde_json::from_value(json!({+ "request_id": "request-2",+ "success": true,+ "execution_binding_sha256": binding.clone()+ }))+ .unwrap();+ let mismatching: publisher::WorkResult = serde_json::from_value(json!({+ "request_id": "request-3",+ "success": true,+ "execution_binding_sha256": "f".repeat(64)+ }))+ .unwrap();+ let missing: publisher::WorkResult = serde_json::from_value(json!({+ "request_id": "request-4",+ "success": true+ }))+ .unwrap();+ let malformed: publisher::WorkResult = serde_json::from_value(json!({+ "request_id": "request-5",+ "success": true,+ "execution_binding_sha256": "E".repeat(64)+ }))+ .unwrap();++ let mut headers = HeaderMap::new();+ insert_execution_binding_header(&mut headers, &[&matching, &same]);+ assert_eq!(+ headers+ .get("x-sie-execution-binding-sha256")+ .and_then(|value| value.to_str().ok()),+ Some(binding.as_str())+ );++ for results in [+ vec![&matching, &mismatching],+ vec![&matching, &missing],+ vec![&malformed],+ Vec::new(),+ ] {+ headers.clear();+ insert_execution_binding_header(&mut headers, &results);+ assert!(headers.get("x-sie-execution-binding-sha256").is_none());+ }++ let mut outcome = crate::queue::streaming::StreamOutcome {+ text: "ok".to_string(),+ finish_reason: "stop".to_string(),+ usage: None,+ attempt_id: "attempt-1".to_string(),+ ttft_ms: None,+ tpot_ms: None,+ error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,+ tool_calls: None,+ logprobs: None,+ candidates: Vec::new(),+ executed_bundle_config_hash: None,+ execution_identity_sha256: None,+ execution_binding_sha256: Some(binding.clone()),+ };+ insert_stream_execution_binding_header(&mut headers, &outcome);+ assert_eq!(+ headers+ .get("x-sie-execution-binding-sha256")+ .and_then(|value| value.to_str().ok()),+ Some(binding.as_str())+ );++ headers.clear();+ outcome.execution_binding_sha256 = Some("bad".to_string());+ insert_stream_execution_binding_header(&mut headers, &outcome);+ assert!(headers.get("x-sie-execution-binding-sha256").is_none());+ }++ #[tokio::test]+ async fn test_endpoint_error_response_envelope_matches_endpoint() {+ // generate/chat use the OpenAI `{error:{...}}` envelope; native endpoints+ // keep `{detail:{...}}`. The engine-pin errors now route through this+ // helper so a bad X-SIE-Engine on /v1/generate gets the OpenAI shape+ // rather than the native one. See #1567.+ let openai = endpoint_error_response("generate",StatusCode::BAD_REQUEST,err_code::INVALID_REQUEST,@@ -14305,6 +14513,10 @@ mod tests {.pop().expect("generation publish target")}++ fn target_count(&self) -> usize {+ self.targets.lock().expect("target probe lock").len()+ }}#[async_trait::async_trait]@@ -14364,11 +14576,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}).expect("target probe outcome receiver");Ok((@@ -14464,9 +14678,10 @@ mod tests {extends: None,},);- let tasks: serde_yaml::Value =- serde_yaml::from_str("generate:\n capabilities:\n grammar: [json_schema]\n")- .expect("generation task");+ let tasks: serde_yaml::Value = serde_yaml::from_str(+ "generate:\n capabilities:\n grammar: [json_schema]\n streaming: false\n",+ )+ .expect("generation task");registry.add_model_config(ModelConfig {name: "org/h".to_string(),@@ -14818,6 +15033,152 @@ mod tests {}}+ #[tokio::test]+ async fn non_streaming_model_rejects_all_streaming_ingresses_before_publish() {+ let (state, probe) = mixed_governed_generation_state(false).await;+ let cases = [+ (+ "/v1/generate/org%2Fh",+ serde_json::json!({+ "prompt": "hello",+ "max_new_tokens": 4,+ "stream": true+ }),+ "generate",+ ),+ (+ "/v1/chat/completions",+ serde_json::json!({+ "model": "org/h",+ "messages": [{"role": "user", "content": "hello"}],+ "max_tokens": 4,+ "stream": true+ }),+ "chat",+ ),+ (+ "/v1/completions",+ serde_json::json!({+ "model": "org/h",+ "prompt": "hello",+ "max_tokens": 4,+ "stream": true+ }),+ "completions",+ ),+ ];++ for (uri, body, endpoint) in cases {+ let response = match endpoint {+ "generate" => {+ proxy_request(State(Arc::clone(&state)), json_request(uri, body), endpoint)+ .await+ }+ "chat" => proxy_chat(State(Arc::clone(&state)), json_request(uri, body)).await,+ "completions" => {+ proxy_completions(State(Arc::clone(&state)), json_request(uri, body)).await+ }+ _ => unreachable!("bounded streaming ingress"),+ };+ assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{endpoint}");+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .expect("error response body");+ let value: serde_json::Value =+ serde_json::from_slice(&body).expect("error response JSON");+ assert_eq!(+ value["error"]["code"],+ oai_code::UNSUPPORTED_FIELD,+ "{endpoint}"+ );+ assert_eq!(value["error"]["param"], "stream", "{endpoint}");+ assert_eq!(probe.target_count(), 0, "{endpoint} published queue work");+ }+ }++ #[tokio::test]+ async fn non_streaming_native_generate_rejects_before_cold_lane_demand() {+ let (state, probe) = mixed_governed_generation_state(false).await;+ let mut state = Arc::try_unwrap(state).unwrap_or_else(|_| panic!("unique test state"));+ state.registry = Arc::new(WorkerRegistry::new(Duration::from_secs(30), None));+ let state = Arc::new(state);++ let response = proxy_request(+ State(Arc::clone(&state)),+ json_request(+ "/v1/generate/org%2Fh",+ serde_json::json!({+ "prompt": "hello",+ "max_new_tokens": 4,+ "stream": true+ }),+ ),+ "generate",+ )+ .await;++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(state.demand_tracker.active_lanes().is_empty());+ assert_eq!(probe.target_count(), 0);+ }++ #[tokio::test]+ async fn non_streaming_native_generate_rejects_before_zero_cap_admission() {+ let pool_manager = Arc::new(PoolManager::new(vec!["l4".to_string()]));+ pool_manager.create_default_pool().await;+ pool_manager+ .create_pool_with_caps(+ "tenant",+ std::collections::HashMap::from([("l4".to_string(), 0)]),+ std::collections::HashMap::from([("l4".to_string(), 0)]),+ None,+ None,+ 0,+ vec![],+ )+ .await+ .expect("zero-cap test pool");+ let mut state = admission_test_state(pool_manager);+ state.model_registry = Arc::new(mixed_governed_registry());+ install_generation_policy(+ &mut state,+ Arc::new(MappedGenerationRoutePolicy {+ routes: [(+ ("org/h".to_string(), GenerationRequestIntent::Default),+ GovernedGenerationRoute {+ model: "org/h".to_string(),+ bundle: "default".to_string(),+ pool: "tenant".to_string(),+ machine_profile: "l4".to_string(),+ },+ )]+ .into_iter()+ .collect(),+ }),+ );+ let probe = Arc::new(GenerationTargetProbe::default());+ state.work_publisher = Some(probe.clone());+ let state = Arc::new(state);++ let response = proxy_request(+ State(Arc::clone(&state)),+ json_request(+ "/v1/generate/org%2Fh",+ serde_json::json!({+ "prompt": "hello",+ "max_new_tokens": 4,+ "stream": true+ }),+ ),+ "generate",+ )+ .await;++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(state.demand_tracker.active_lanes().is_empty());+ assert_eq!(probe.target_count(), 0);+ }+#[tokio::test]async fn self_hosted_native_grammar_dispatches_profile_variant_after_one_parse() {let (state, probe) = mixed_governed_generation_state(false).await;@@ -17231,6 +17592,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let body = build_generate_success_body("Qwen/Qwen3-4B-Instruct", &[&r], false);let value: serde_json::Value = serde_json::from_slice(&body).unwrap();@@ -17326,11 +17688,13 @@ mod tests {ttft_ms: Some(120.5),tpot_ms: Some(45.2),error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let body = build_generate_success_body_v2("Qwen/Qwen3-4B-Instruct", &outcome, false);let value: serde_json::Value = serde_json::from_slice(&body).unwrap();@@ -17401,7 +17765,7 @@ mod tests {#[tokio::test]async fn test_build_model_load_failed_response_uses_legacy_error_envelope_and_headers() {- let resp = build_model_load_failed_response("BAAI/bge-m3", "repository is gated");+ let resp = build_model_load_failed_response();assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);assert_eq!(resp.headers().get("x-sie-error-code").unwrap(),@@ -17415,6 +17779,7 @@ mod tests {let body: serde_json::Value =serde_json::from_slice(&body_bytes).expect("response body is valid JSON");assert_eq!(body["error"]["code"], MODEL_LOAD_FAILED_ERROR_CODE);+ assert_eq!(body["error"]["message"], MODEL_LOAD_FAILED_PUBLIC_MESSAGE);assert!(body.get("detail").is_none());}@@ -17600,6 +17965,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -17647,6 +18013,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -18013,6 +18380,8 @@ mod tests {"x-queue-publish-time","x-queue-wait-time","x-queue-time",+ "x-sie-execution-identity-sha256",+ "x-sie-execution-binding-sha256","x-inference-time","x-tokenization-time","x-postprocessing-time",@@ -19425,6 +19794,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let resp_body = result.result_msgpack.clone();assert_eq!(resp_body, payload);@@ -19464,6 +19834,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,},publisher::WorkResult {work_item_id: "r1.1".to_string(),@@ -19484,6 +19855,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,},];let items: Vec<serde_json::Value> = results@@ -20177,6 +20549,60 @@ mod tests {)}+ #[tokio::test]+ async fn non_streaming_model_rejects_stream_with_exact_parameter() {+ use crate::types::model::{ModelConfig, ProfileConfig};++ let registry = empty_registry();+ let profiles = [(+ "default".to_string(),+ ProfileConfig {+ kv_budget_tokens: None,+ max_output_tokens: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ )]+ .into_iter()+ .collect();+ let tasks =+ serde_yaml::from_str("generate:\n capabilities:\n streaming: false\n").unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/buffered".to_string(),+ hf_revision: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();++ let response =+ unsupported_streaming_response(®istry, "org/buffered", "org/buffered", true)+ .expect("streaming must be rejected");++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], oai_code::UNSUPPORTED_FIELD);+ assert_eq!(value["error"]["param"], "stream");+ assert!(+ unsupported_streaming_response(®istry, "org/buffered", "org/buffered", false,)+ .is_none()+ );+ }+fn grammar_routed_registry() -> crate::state::model_registry::ModelRegistry {use crate::types::model::{ModelConfig, ProfileConfig};use std::collections::HashMap as StdHashMap;@@ -21638,6 +22064,7 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: vec![@@ -21656,6 +22083,7 @@ mod tests {],executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "req", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -21691,6 +22119,7 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: vec![@@ -21716,6 +22145,7 @@ mod tests {],executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "req-tc", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -21756,6 +22186,7 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: vec![CandidateData {@@ -21766,6 +22197,7 @@ mod tests {}],executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "req-lp", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -22136,11 +22568,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_text_completion_body("m", "req-1", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -22757,11 +23191,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_responses_body("m", "req-1", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -22812,11 +23248,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("Qwen/Qwen3-4B-Instruct-2507", "req-1", &outcome).expect("ok");@@ -22900,6 +23338,7 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: Some(vec![serde_json::json!({"token": "Hi",@@ -22910,6 +23349,7 @@ mod tests {candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "r", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -22935,11 +23375,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "r", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -22965,6 +23407,7 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: Some(vec![crate::queue::streaming::AggregatedToolCall {index: 0,id: "call_xyz".to_string(),@@ -22976,6 +23419,7 @@ mod tests {candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "req-tc", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -23001,11 +23445,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let resp = build_chat_completion_body("m", "req-1", &outcome).expect_err("missing usage");assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);@@ -23090,6 +23536,8 @@ mod tests {let err = StreamingDriverErr::WorkerError {code: "rate_limit_exceeded".to_string(),message: "KV cache saturated and pool republish failed".to_string(),+ param: None,+ retry_after_s: None,request_id: "req-rl-1".to_string(),attempt_id: "att-rl-1".to_string(),};@@ -23121,6 +23569,8 @@ mod tests {let err = StreamingDriverErr::WorkerError {code: PAYLOAD_TOO_LARGE_ERROR_CODE.to_string(),message: "referenced payload exceeds the worker size limit".to_string(),+ param: None,+ retry_after_s: None,request_id: "req-large-1".to_string(),attempt_id: "att-large-1".to_string(),};@@ -23140,6 +23590,29 @@ mod tests {assert_eq!(value["error"]["attempt_id"], "att-large-1");}+ #[tokio::test]+ async fn test_streaming_unsupported_field_preserves_exact_parameter() {+ let err = StreamingDriverErr::WorkerError {+ code: oai_code::UNSUPPORTED_FIELD.to_string(),+ message: "top_k is unavailable".to_string(),+ param: Some("top_k".to_string()),+ retry_after_s: None,+ request_id: "req-unsupported-1".to_string(),+ attempt_id: "att-unsupported-1".to_string(),+ };+ let response = build_streaming_error_response(&err);++ assert_eq!(response.status(), StatusCode::BAD_REQUEST);+ assert!(response.headers().get("retry-after").is_none());+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], oai_code::UNSUPPORTED_FIELD);+ assert_eq!(value["error"]["param"], "top_k");+ assert_eq!(value["error"]["attempt_id"], "att-unsupported-1");+ }+/// The cold-start quota refusal must reach the wire with NO Retry-After:/// the blanket 429 header block previously stamped `Retry-After: 1` on it,/// re-creating the exact auto-retry hot loop the hourly ceiling exists to@@ -23150,6 +23623,8 @@ mod tests {let err = StreamingDriverErr::WorkerError {code: COLD_START_RATE_LIMITED_ERROR_CODE.to_string(),message: "org exceeded its sealed cold-starts-per-hour ceiling".to_string(),+ param: None,+ retry_after_s: None,request_id: "req-cold-1".to_string(),attempt_id: "att-cold-1".to_string(),};@@ -23175,6 +23650,8 @@ mod tests {let err = StreamingDriverErr::WorkerError {code: oai_code::EMPTY_MODEL_OUTPUT.to_string(),message: "model produced no visible output text".to_string(),+ param: None,+ retry_after_s: None,request_id: "req-empty-1".to_string(),attempt_id: "att-empty-1".to_string(),};@@ -23195,7 +23672,128 @@ mod tests {assert_eq!(v["error"]["code"], oai_code::EMPTY_MODEL_OUTPUT);assert_eq!(v["error"]["attempt_id"], "att-empty-1");// The retry classifier must keep treating it as terminal.- assert_eq!(worker_error_retry_after(oai_code::EMPTY_MODEL_OUTPUT), None);+ assert_eq!(+ worker_error_retry_after(oai_code::EMPTY_MODEL_OUTPUT, None),+ None+ );+ }++ #[tokio::test]+ async fn test_streaming_model_load_failed_uses_terminal_sdk_contract() {+ let err = StreamingDriverErr::WorkerError {+ code: MODEL_LOAD_FAILED_ERROR_CODE.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ request_id: "req-load-failed-1".to_string(),+ attempt_id: "att-load-failed-1".to_string(),+ };+ let resp = build_streaming_error_response(&err);++ assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);+ assert_eq!(+ resp.headers().get("x-sie-error-code").unwrap(),+ MODEL_LOAD_FAILED_ERROR_CODE+ );+ assert_eq!(+ resp.headers().get("x-sie-request-id").unwrap(),+ "req-load-failed-1"+ );+ assert!(resp.headers().get("retry-after").is_none());++ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], MODEL_LOAD_FAILED_ERROR_CODE);+ assert_eq!(value["error"]["message"], MODEL_LOAD_FAILED_PUBLIC_MESSAGE);+ assert_eq!(value["error"]["error_class"], MODEL_LOAD_FAILED_ERROR_CODE);+ assert_eq!(value["error"]["attempts"], 1);+ assert_eq!(value["error"]["permanent"], true);+ assert!(!String::from_utf8_lossy(&body).contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }++ #[tokio::test]+ async fn test_streaming_unknown_worker_error_fails_closed() {+ let err = StreamingDriverErr::WorkerError {+ code: "SENSITIVE_WORKER_ERROR_CODE_SENTINEL".to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ request_id: "req-unknown-1".to_string(),+ attempt_id: "att-unknown-1".to_string(),+ };+ let resp = build_streaming_error_response(&err);++ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);+ assert!(resp.headers().get("retry-after").is_none());+ let body = axum::body::to_bytes(resp.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], "inference_error");+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE+ );+ let serialized = String::from_utf8_lossy(&body);+ assert!(!serialized.contains("SENSITIVE_WORKER_ERROR_CODE_SENTINEL"));+ assert!(!serialized.contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }++ #[tokio::test]+ async fn test_buffered_worker_inference_error_sanitizes_untrusted_message() {+ let sentinel = "SENSITIVE_BACKEND_SENTINEL";+ let err = StreamingDriverErr::WorkerError {+ code: "inference_error".to_string(),+ message: sentinel.to_string(),+ param: Some(sentinel.to_string()),+ retry_after_s: None,+ request_id: "req-sensitive-1".to_string(),+ attempt_id: "att-sensitive-1".to_string(),+ };++ let response = build_streaming_error_response(&err);++ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(+ value["error"]["message"],+ "internal error during generation"+ );+ assert!(value["error"]["param"].is_null());+ assert!(!value.to_string().contains(sentinel));+ }++ #[tokio::test]+ async fn test_buffered_unknown_worker_error_sanitizes_untrusted_message() {+ let sentinel = "SENSITIVE_WORKER_ERROR_CODE_SENTINEL";+ let err = StreamingDriverErr::WorkerError {+ code: sentinel.to_string(),+ message: sentinel.to_string(),+ param: Some(sentinel.to_string()),+ retry_after_s: None,+ request_id: "req-future-1".to_string(),+ attempt_id: "att-future-1".to_string(),+ };++ let response = build_streaming_error_response(&err);++ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert_eq!(value["error"]["code"], "inference_error");+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE+ );+ assert!(value["error"]["param"].is_null());+ assert!(!value.to_string().contains(sentinel));}async fn assert_streaming_worker_error_is_retryable(@@ -23205,6 +23803,8 @@ mod tests {let err = StreamingDriverErr::WorkerError {code: code.to_string(),message: "Retryable worker error; retry later.".to_string(),+ param: None,+ retry_after_s: None,request_id: "req-retry-1".to_string(),attempt_id: "att-retry-1".to_string(),};@@ -23242,6 +23842,32 @@ mod tests {.await;}+ #[tokio::test]+ async fn test_resource_exhausted_uses_worker_configured_retry_hint() {+ let err = StreamingDriverErr::WorkerError {+ code: RESOURCE_EXHAUSTED_ERROR_CODE.to_string(),+ message: "scheduler full".to_string(),+ param: Some("SENSITIVE_CAPACITY_PARAM".to_string()),+ retry_after_s: Some(12),+ request_id: "req-retry-configured".to_string(),+ attempt_id: "att-retry-configured".to_string(),+ };++ let response = build_streaming_error_response(&err);++ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(response.headers().get("retry-after").unwrap(), "12");+ assert_eq!(+ response.headers().get("x-sie-error-code").unwrap(),+ RESOURCE_EXHAUSTED_ERROR_CODE+ );+ let body = axum::body::to_bytes(response.into_body(), 16 * 1024)+ .await+ .unwrap();+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(value["error"]["param"].is_null());+ }+/// HTTP status mapping unit test — guards against an off-by-one/// edit that drops the 429 mapping without touching/// ``build_streaming_error_response``.@@ -23253,6 +23879,14 @@ mod tests {);}+ #[test]+ fn test_worker_error_http_status_model_load_failed_is_502() {+ assert_eq!(+ worker_error_http_status(MODEL_LOAD_FAILED_ERROR_CODE),+ StatusCode::BAD_GATEWAY+ );+ }+/// The sealed cold-start quota refusal (#2426) is a deliberate 429 with/// a rate-limit envelope type — never a generic server error — and stays/// off the retryable lists (no Retry-After: an hourly quota must not@@ -23267,7 +23901,7 @@ mod tests {worker_error_openai_type(COLD_START_RATE_LIMITED_ERROR_CODE),oai_type::RATE_LIMIT);- assert!(worker_error_retry_after(COLD_START_RATE_LIMITED_ERROR_CODE).is_none());+ assert!(worker_error_retry_after(COLD_START_RATE_LIMITED_ERROR_CODE, None).is_none());}/// Envelope ``type`` mapping unit test.@@ -23286,23 +23920,45 @@ mod tests {#[test]fn test_worker_error_retry_after_maps_retryable_codes() {assert_eq!(- worker_error_retry_after(RESOURCE_EXHAUSTED_ERROR_CODE),+ worker_error_retry_after(RESOURCE_EXHAUSTED_ERROR_CODE, None),Some((- RESOURCE_EXHAUSTED_RETRY_AFTER,+ RESOURCE_EXHAUSTED_RETRY_AFTER.to_string(),RESOURCE_EXHAUSTED_ERROR_CODE)));assert_eq!(- worker_error_retry_after(MODEL_LOADING_ERROR_CODE),- Some((MODEL_LOADING_RETRY_AFTER, MODEL_LOADING_ERROR_CODE))+ worker_error_retry_after(MODEL_LOADING_ERROR_CODE, None),+ Some((+ MODEL_LOADING_RETRY_AFTER.to_string(),+ MODEL_LOADING_ERROR_CODE+ )));assert_eq!(- worker_error_retry_after(LORA_LOADING_ERROR_CODE),- Some((LORA_LOADING_RETRY_AFTER, LORA_LOADING_ERROR_CODE))+ worker_error_retry_after(LORA_LOADING_ERROR_CODE, None),+ Some((+ LORA_LOADING_RETRY_AFTER.to_string(),+ LORA_LOADING_ERROR_CODE+ )));// Terminal / non-retryable codes carry no retry hint.- assert_eq!(worker_error_retry_after("invalid_request"), None);- assert_eq!(worker_error_retry_after("transport_failure"), None);+ assert_eq!(worker_error_retry_after("invalid_request", None), None);+ assert_eq!(+ worker_error_retry_after("transport_failure", Some(12)),+ None+ );+ assert_eq!(+ worker_error_retry_after(RESOURCE_EXHAUSTED_ERROR_CODE, Some(12)),+ Some(("12".to_string(), RESOURCE_EXHAUSTED_ERROR_CODE))+ );+ for invalid in [0, 61] {+ assert_eq!(+ worker_error_retry_after(RESOURCE_EXHAUSTED_ERROR_CODE, Some(invalid)),+ Some((+ RESOURCE_EXHAUSTED_RETRY_AFTER.to_string(),+ RESOURCE_EXHAUSTED_ERROR_CODE+ ))+ );+ }}/// Regression guard: the non-streaming aggregating path (the@@ -23324,11 +23980,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: crate::queue::streaming::StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let bytes = build_chat_completion_body("m", "req-x", &outcome).expect("ok");let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();@@ -23364,6 +24022,7 @@ mod tests {max_output_tokens: None,profile_max_output_tokens: std::collections::HashMap::new(),grammar_capabilities: None,+ streaming_supported: None,grammar_profile: None,profile_parents: std::collections::HashMap::new(),tools_supported: None,@@ -23413,6 +24072,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex 1d7adc9fe..a9edc7069 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -62,7 +62,9 @@ use tracing::{debug, info, warn};use crate::observability::metrics as telemetry;use crate::queue::dispatch::{PendingDispatchKind, WorkDispatcher};use crate::queue::publisher;-use crate::queue::streaming::{ChunkEnvelope, StreamOutcome};+use crate::queue::streaming::{+ is_lower_sha256, ChunkEnvelope, ChunkError, StreamOutcome, StreamOutcomeOrigin,+};use crate::server::AppState;use crate::state::demand_tracker::{DemandTracker, PhysicalLane};@@ -806,11 +808,11 @@ async fn run_sse_driver(args: SseDriverArgs) {.await;return;}- // Terminal outcome arm. Ordered before the chunk-tap recv so- // a synthesised terminal error (NAK + pool-republish failure,- // surfaced via `fail_pending_stream`) wins over the generic- // broadcast-`Closed` path that fires when the collector is- // torn down at the same instant.+ // Terminal outcome arm. A worker outcome is only a completion+ // signal: its exact terminal was already queued on the ordered+ // chunk tap, so this arm must never bypass that tap. A gateway-+ // synthesized outcome has no tap terminal and must win over the+ // broadcast-`Closed` path that races collector teardown.outcome = &mut outcome_rx, if !outcome_done => {// One-shot: never poll the resolved receiver again (it// would panic). All branches below either return or@@ -818,21 +820,26 @@ async fn run_sse_driver(args: SseDriverArgs) {outcome_done = true;match outcome {Ok(o) => {- if let Some(err) = o.error {+ if o.origin == StreamOutcomeOrigin::GatewaySynthetic {+ let Some(err) = o.error else {+ // Defensive fallback for an impossible+ // synthetic success: let the closed tap emit+ // its ordinary transport-failure diagnostic.+ continue;+ };// Emit the typed code/message (e.g.// rate_limit_exceeded → 429-equivalent inside// the stream) instead of a generic// transport_failure. Same error shape as the// worker-error chunk path below.- send_error_chunk(+ send_synthetic_error_chunk(&event_tx,&endpoint,&stream_chat_id,created,&model,&request_id,- &err.code,- &err.message,+ &err,).await;send_done(&event_tx).await;@@ -841,13 +848,11 @@ async fn run_sse_driver(args: SseDriverArgs) {publisher.drop_pending_stream(&request_id);return;}- // A success outcome resolved here means the terminal- // chunk was already forwarded through the tap (which- // fires the oneshot on the same terminal apply). The- // chunk arm's `is_terminal` branch owns the `[DONE]`;- // latch that the generation completed server-side so the- // Lagged arm can skip a pointless cancel of an- // already-finished request. See #1602.+ // Every worker outcome means its terminal is already+ // queued on the tap (tap send precedes outcome build).+ // Drain the tap in order; that preserves all buffered+ // deltas plus the terminal's real seq/usage/TTFT and+ // execution identity. The terminal arm owns `[DONE]`.stream_succeeded = true;continue;}@@ -1259,15 +1264,7 @@ fn build_chat_chunk_event(});if let Some(err) = chunk.error.as_ref() {if let Some(obj) = body.as_object_mut() {- obj.insert(- "error".to_string(),- json!({- "message": err.message,- "type": worker_error_openai_type_for(&err.code),- "param": Value::Null,- "code": err.code,- }),- );+ obj.insert("error".to_string(), worker_error_value(err, true));// Gateway request id, in-band on the ERROR chunk only (#3136):// a streamed response has no terminal headers, and the// ``chatcmpl-*`` id is not the correlation key server logs use.@@ -1276,6 +1273,7 @@ fn build_chat_chunk_event(obj.insert("request_id".to_string(), json!(chunk.request_id));}}+ insert_terminal_execution_evidence(&mut body, chunk);body}@@ -1288,14 +1286,16 @@ fn build_text_completion_chunk_event(model: &str,chunk: &ChunkEnvelope,) -> Value {- let finish = if chunk.done {+ let finish = if chunk.done && chunk.error.is_some() {+ Value::Null+ } else if chunk.done {Value::String(map_chat_finish_reason(chunk.finish_reason.as_deref().unwrap_or("stop")).to_string(),)} else {Value::Null};- json!({+ let mut body = json!({"id": id,"object": "text_completion","created": created,@@ -1308,7 +1308,15 @@ fn build_text_completion_chunk_event("index": 0,"finish_reason": finish,}],- })+ });+ if let Some(err) = chunk.error.as_ref() {+ if let Some(object) = body.as_object_mut() {+ object.insert("error".to_string(), worker_error_value(err, true));+ object.insert("request_id".to_string(), json!(chunk.request_id));+ }+ }+ insert_terminal_execution_evidence(&mut body, chunk);+ body}/// Build the optional trailing usage-only chunk (OpenAI@@ -1396,6 +1404,25 @@ fn merge_terminal_usage_extras(usage: &mut Value, extras: &[(String, Value)]) {}}+fn insert_terminal_execution_evidence(body: &mut Value, chunk: &ChunkEnvelope) {+ if !chunk.done || chunk.error.is_some() {+ return;+ }+ let (Some(identity), Some(binding)) = (+ chunk.execution_identity_sha256.as_deref(),+ chunk.execution_binding_sha256.as_deref(),+ ) else {+ return;+ };+ if !is_lower_sha256(identity) || !is_lower_sha256(binding) {+ return;+ }+ if let Some(object) = body.as_object_mut() {+ object.insert("execution_identity_sha256".to_string(), json!(identity));+ object.insert("execution_binding_sha256".to_string(), json!(binding));+ }+}+/// SIE-native generate chunk shape.fn build_generate_chunk_event(chunk: &ChunkEnvelope, terminal_extras: &[(String, Value)]) -> Value {let mut body = json!({@@ -1424,18 +1451,31 @@ fn build_generate_chunk_event(chunk: &ChunkEnvelope, terminal_extras: &[(String,obj.insert("logprobs".to_string(), json!(logprobs));}if let Some(err) = chunk.error.as_ref() {- obj.insert(- "error".to_string(),- json!({- "code": err.code,- "message": err.message,- }),- );+ obj.insert("error".to_string(), worker_error_value(err, false));}}+ insert_terminal_execution_evidence(&mut body, chunk);body}+fn worker_error_value(error: &ChunkError, include_openai_type: bool) -> Value {+ let code = error.client_safe_code();+ let mut object = serde_json::Map::new();+ object.insert("message".to_string(), json!(error.client_safe_message()));+ if include_openai_type {+ object.insert(+ "type".to_string(),+ json!(worker_error_openai_type_for(code)),+ );+ }+ object.insert("param".to_string(), json!(error.client_safe_param()));+ object.insert("code".to_string(), json!(code));+ if let Some(retry_after_s) = error.validated_retry_after_s() {+ object.insert("retry_after_s".to_string(), json!(retry_after_s));+ }+ Value::Object(object)+}+/// Emit a synthesized error chunk (gateway-side timeout or/// transport failure) onto the SSE stream. Wraps the right shape/// for each endpoint.@@ -1494,11 +1534,53 @@ async fn send_error_chunk("system_fingerprint": crate::handlers::proxy::system_fingerprint(model),"choices": [{"text": "", "index": 0, "finish_reason": Value::Null, "logprobs": Value::Null}],"error": { "message": message, "type": "server_error", "param": Value::Null, "code": code },+ "request_id": request_id,}),};let _ = tx.send(Ok(Event::default().data(body.to_string()))).await;}+/// Emit a gateway-synthesized terminal error when no worker tap terminal exists.+#[allow(clippy::too_many_arguments)]+async fn send_synthetic_error_chunk(+ tx: &tokio::sync::mpsc::Sender<Result<Event, Infallible>>,+ endpoint: &SseEndpoint,+ chat_id: &str,+ created: u64,+ model: &str,+ request_id: &str,+ error: &ChunkError,+) {+ let chunk = ChunkEnvelope {+ kind: "chunk".to_string(),+ request_id: request_id.to_string(),+ attempt_id: String::new(),+ seq: 0,+ text_delta: String::new(),+ done: true,+ is_first: false,+ finish_reason: Some("error".to_string()),+ usage: None,+ ttft_ms: None,+ error: Some(error.clone()),+ tool_calls: None,+ logprobs: None,+ candidates: Vec::new(),+ choice_index: 0,+ executed_bundle_config_hash: None,+ execution_identity_sha256: None,+ execution_binding_sha256: None,+ };+ let body = match endpoint {+ SseEndpoint::Chat { .. } => build_chat_chunk_event(chat_id, created, model, &chunk, false),+ SseEndpoint::Completion { .. } => {+ build_text_completion_chunk_event(chat_id, created, model, &chunk)+ }+ SseEndpoint::Generate => build_generate_chunk_event(&chunk, &[]),+ };+ let _ = tx.send(Ok(Event::default().data(body.to_string()))).await;+}+async fn send_done(tx: &tokio::sync::mpsc::Sender<Result<Event, Infallible>>) {// The literal ``[DONE]`` terminator. axum's Event::data already// emits the trailing ``\n\n`` separator.@@ -1544,7 +1626,8 @@ fn worker_error_openai_type_for(code: &str) -> &'static str {mod tests {use super::*;use crate::queue::streaming::{- ChunkEnvelope, ChunkError, ToolCallDeltaWire, ToolCallFunctionWire, UsageBlock,+ ChunkApplied, ChunkEnvelope, ChunkError, ToolCallDeltaWire, ToolCallFunctionWire,+ UsageBlock,};mod client_disconnect_grace {@@ -1560,13 +1643,15 @@ mod tests {DispatchDurability, DispatchError, PendingGenerationSnapshot, WorkDispatcher,};use crate::queue::publisher::{PublishTarget, WorkParams};- use crate::queue::streaming::{ChunkEnvelope, StreamOutcome, UsageBlock};+ use crate::queue::streaming::{+ ChunkEnvelope, StreamOutcome, StreamOutcomeOrigin, UsageBlock,+ };/// Records exactly which teardown the SSE driver chose. The two are/// transport-identical and differ only in the billing signal they emit,/// so the choice IS the behaviour under test.#[derive(Default)]- struct TeardownRecorder {+ pub(super) struct TeardownRecorder {cancels: AtomicUsize,plain_drops: AtomicUsize,disconnect_drops: AtomicUsize,@@ -1704,11 +1789,13 @@ mod tests {ttft_ms: None,tpot_ms: None,error: None,+ origin: StreamOutcomeOrigin::WorkerTerminal,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -1855,6 +1942,368 @@ mod tests {}}+ #[derive(Clone, Copy)]+ enum WorkerTerminalDelivery {+ BackloggedBeforeFirstPoll,+ AfterFirstDelta,+ }++ async fn run_driver_worker_error_race(+ endpoint: SseEndpoint,+ delivery: WorkerTerminalDelivery,+ error: ChunkError,+ ) -> Vec<String> {+ use crate::queue::streaming::StreamCollector;+ use crate::state::demand_tracker::PhysicalLaneCatalog;++ let recorder = Arc::new(client_disconnect_grace::TeardownRecorder::default());+ let publisher: Arc<dyn WorkDispatcher> = recorder as Arc<dyn WorkDispatcher>;+ let catalog = PhysicalLaneCatalog::try_from_raw([(+ "default".to_string(),+ "default".to_string(),+ "default".to_string(),+ )])+ .expect("catalog");+ let demand_tracker = Arc::new(DemandTracker::new(catalog));+ let physical_lane = demand_tracker+ .resolve_lane("default", "default", "default")+ .expect("lane");++ let (collector_tx, _collector_rx) = tokio::sync::oneshot::channel();+ let mut collector = StreamCollector::new(+ collector_tx,+ "test/model".to_string(),+ "default".to_string(),+ );+ let chunk_rx = collector.install_chunk_tap();+ let (outcome_tx, outcome_rx) = tokio::sync::oneshot::channel();+ let (durability_tx, durability_completion) = tokio::sync::oneshot::channel();+ durability_tx+ .send(Ok::<(), String>(()))+ .expect("durability receiver is live");+ let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(8);++ let args = SseDriverArgs {+ event_tx,+ chunk_rx,+ outcome_rx,+ durability_completion,+ publisher,+ demand_tracker,+ physical_lane,+ request_id: "req-test".to_string(),+ model: "test/model".to_string(),+ pool: "default".to_string(),+ bundle: "default".to_string(),+ gpu: "test".to_string(),+ endpoint,+ stream_chat_id: "chatcmpl-test".to_string(),+ created: 1,+ first_chunk_timeout: Duration::from_secs(30),+ inter_chunk_timeout: Duration::from_secs(30),+ overall_timeout: Duration::from_secs(60),+ was_direct_dispatched: false,+ pool_fallback_lane_worker_count: 1,+ };++ let mut payloads = Vec::new();+ if matches!(delivery, WorkerTerminalDelivery::AfterFirstDelta) {+ let driver = tokio::spawn(run_sse_driver(args));+ assert!(matches!(+ collector.apply(_delta_chunk(41, "partial")),+ ChunkApplied::Delta+ ));+ let event = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())+ .await+ .expect("delta event timeout")+ .expect("delta event")+ .expect("infallible event");+ payloads.push(_event_data(event).await);++ let mut terminal = _terminal_chunk("error", None);+ terminal.seq = 42;+ terminal.usage = Some(UsageBlock {+ prompt_tokens: 3,+ completion_tokens: 2,+ total_tokens: 5,+ });+ terminal.ttft_ms = Some(17.5);+ terminal.executed_bundle_config_hash = Some("a".repeat(64));+ terminal.execution_identity_sha256 = Some("b".repeat(64));+ terminal.error = Some(error);+ assert!(matches!(collector.apply(terminal), ChunkApplied::Terminal));+ outcome_tx+ .send(collector.build_outcome().expect("terminal outcome"))+ .expect("outcome receiver is live");+ driver.await.expect("driver task");+ } else {+ assert!(matches!(+ collector.apply(_delta_chunk(41, "partial")),+ ChunkApplied::Delta+ ));+ let mut terminal = _terminal_chunk("error", None);+ terminal.seq = 42;+ terminal.usage = Some(UsageBlock {+ prompt_tokens: 3,+ completion_tokens: 2,+ total_tokens: 5,+ });+ terminal.ttft_ms = Some(17.5);+ terminal.executed_bundle_config_hash = Some("a".repeat(64));+ terminal.execution_identity_sha256 = Some("b".repeat(64));+ terminal.error = Some(error);+ assert!(matches!(collector.apply(terminal), ChunkApplied::Terminal));+ outcome_tx+ .send(collector.build_outcome().expect("terminal outcome"))+ .expect("outcome receiver is live");+ run_sse_driver(args).await;+ }++ loop {+ let Some(event) = tokio::time::timeout(Duration::from_secs(1), event_rx.recv())+ .await+ .expect("driver event timeout")+ else {+ break;+ };+ payloads.push(_event_data(event.expect("infallible event")).await);+ }+ payloads+ }++ #[tokio::test]+ async fn live_driver_worker_error_outcome_preserves_full_contract_before_and_after_delta() {+ for delivery in [+ WorkerTerminalDelivery::BackloggedBeforeFirstPoll,+ WorkerTerminalDelivery::AfterFirstDelta,+ ] {+ for endpoint in [+ SseEndpoint::Chat {+ include_usage: true,+ },+ SseEndpoint::Completion {+ include_usage: true,+ },+ SseEndpoint::Generate,+ ] {+ let payloads = run_driver_worker_error_race(+ endpoint,+ delivery,+ ChunkError {+ code: "RESOURCE_EXHAUSTED".to_string(),+ message: "scheduler full".to_string(),+ param: Some("model".to_string()),+ retry_after_s: Some(12),+ },+ )+ .await;+ assert_eq!(+ payloads+ .iter()+ .filter(|value| value.as_str() == "[DONE]")+ .count(),+ 1+ );+ assert_eq!(payloads.last().expect("done"), "[DONE]");+ let json_payloads = payloads[..payloads.len() - 1]+ .iter()+ .map(|payload| {+ serde_json::from_str::<Value>(payload).expect("worker event JSON")+ })+ .collect::<Vec<_>>();+ assert_eq!(+ json_payloads.len(),+ 3 - usize::from(matches!(endpoint, SseEndpoint::Generate))+ );+ let delta = &json_payloads[0];+ match endpoint {+ SseEndpoint::Chat { .. } => {+ assert_eq!(delta["choices"][0]["delta"]["content"], "partial")+ }+ SseEndpoint::Completion { .. } => {+ assert_eq!(delta["choices"][0]["text"], "partial")+ }+ SseEndpoint::Generate => {+ assert_eq!(delta["seq"], 41);+ assert_eq!(delta["text_delta"], "partial");+ }+ }+ let error_payload = json_payloads+ .iter()+ .find(|payload| payload.get("error").is_some())+ .expect("worker error event");+ assert_eq!(error_payload["error"]["code"], "RESOURCE_EXHAUSTED");+ assert!(error_payload["error"]["param"].is_null());+ assert_eq!(error_payload["error"]["retry_after_s"], 12);+ match endpoint {+ SseEndpoint::Chat { .. } | SseEndpoint::Completion { .. } => {+ assert_eq!(error_payload["error"]["type"], "server_error");+ }+ SseEndpoint::Generate => {+ assert!(error_payload["error"].get("type").is_none());+ assert_eq!(error_payload["seq"], 42);+ assert_eq!(error_payload["usage"]["prompt_tokens"], 3);+ assert_eq!(error_payload["usage"]["completion_tokens"], 2);+ assert_eq!(error_payload["ttft_ms"], 17.5);+ }+ }+ if !matches!(endpoint, SseEndpoint::Generate) {+ let usage = json_payloads+ .iter()+ .find(|payload| payload["choices"] == json!([]))+ .expect("usage-only event");+ assert_eq!(usage["usage"]["prompt_tokens"], 3);+ assert_eq!(usage["usage"]["completion_tokens"], 2);+ }+ }+ }+ }++ #[tokio::test]+ async fn live_driver_surfaces_synthetic_only_outcome_when_tap_closes() {+ use crate::state::demand_tracker::PhysicalLaneCatalog;++ for endpoint in [+ SseEndpoint::Chat {+ include_usage: false,+ },+ SseEndpoint::Completion {+ include_usage: false,+ },+ SseEndpoint::Generate,+ ] {+ let recorder = Arc::new(client_disconnect_grace::TeardownRecorder::default());+ let publisher: Arc<dyn WorkDispatcher> = recorder as Arc<dyn WorkDispatcher>;+ let catalog = PhysicalLaneCatalog::try_from_raw([(+ "default".to_string(),+ "default".to_string(),+ "default".to_string(),+ )])+ .expect("catalog");+ let demand_tracker = Arc::new(DemandTracker::new(catalog));+ let physical_lane = demand_tracker+ .resolve_lane("default", "default", "default")+ .expect("lane");+ let (chunk_tx, chunk_rx) = tokio::sync::broadcast::channel(4);+ drop(chunk_tx);+ let (outcome_tx, outcome_rx) = tokio::sync::oneshot::channel();+ outcome_tx+ .send(StreamOutcome {+ text: String::new(),+ finish_reason: "error".to_string(),+ usage: None,+ attempt_id: String::new(),+ ttft_ms: None,+ tpot_ms: None,+ error: Some(ChunkError {+ code: "rate_limit_exceeded".to_string(),+ message: "pool republish failed".to_string(),+ param: None,+ retry_after_s: None,+ }),+ origin: StreamOutcomeOrigin::GatewaySynthetic,+ tool_calls: None,+ logprobs: None,+ candidates: Vec::new(),+ executed_bundle_config_hash: None,+ execution_identity_sha256: None,+ execution_binding_sha256: None,+ })+ .expect("outcome receiver is live");+ let (durability_tx, durability_completion) = tokio::sync::oneshot::channel();+ durability_tx+ .send(Ok::<(), String>(()))+ .expect("durability receiver is live");+ let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(4);++ run_sse_driver(SseDriverArgs {+ event_tx,+ chunk_rx,+ outcome_rx,+ durability_completion,+ publisher,+ demand_tracker,+ physical_lane,+ request_id: "req-synthetic".to_string(),+ model: "test/model".to_string(),+ pool: "default".to_string(),+ bundle: "default".to_string(),+ gpu: "test".to_string(),+ endpoint,+ stream_chat_id: "chatcmpl-synthetic".to_string(),+ created: 1,+ first_chunk_timeout: Duration::from_secs(30),+ inter_chunk_timeout: Duration::from_secs(30),+ overall_timeout: Duration::from_secs(60),+ was_direct_dispatched: false,+ pool_fallback_lane_worker_count: 1,+ })+ .await;++ let error = _event_data(+ event_rx+ .recv()+ .await+ .expect("synthetic error event")+ .expect("infallible event"),+ )+ .await;+ let done = _event_data(+ event_rx+ .recv()+ .await+ .expect("done event")+ .expect("infallible event"),+ )+ .await;+ let error: Value = serde_json::from_str(&error).expect("synthetic error JSON");+ assert_eq!(error["error"]["code"], "rate_limit_exceeded");+ assert_eq!(error["error"]["message"], "pool republish failed");+ assert_eq!(done, "[DONE]");+ assert!(event_rx.recv().await.is_none());+ }+ }++ #[tokio::test]+ async fn live_driver_worker_validation_error_keeps_openai_type_and_exact_param() {+ for endpoint in [+ SseEndpoint::Chat {+ include_usage: false,+ },+ SseEndpoint::Completion {+ include_usage: false,+ },+ SseEndpoint::Generate,+ ] {+ let payloads = run_driver_worker_error_race(+ endpoint,+ WorkerTerminalDelivery::BackloggedBeforeFirstPoll,+ ChunkError {+ code: "unsupported_field".to_string(),+ message: "top_k is unavailable".to_string(),+ param: Some("top_k".to_string()),+ retry_after_s: None,+ },+ )+ .await;+ let error_payload = payloads+ .iter()+ .filter_map(|payload| serde_json::from_str::<Value>(payload).ok())+ .find(|payload| payload.get("error").is_some())+ .expect("worker error JSON");+ assert_eq!(error_payload["error"]["code"], "unsupported_field");+ assert_eq!(error_payload["error"]["param"], "top_k");+ match endpoint {+ SseEndpoint::Chat { .. } | SseEndpoint::Completion { .. } => {+ assert_eq!(error_payload["error"]["type"], "invalid_request_error");+ }+ SseEndpoint::Generate => {+ assert!(error_payload["error"].get("type").is_none());+ }+ }+ }+ }+#[tokio::test]async fn terminal_durability_ready_wins_over_closed_client_and_deadline() {let (event_tx, event_rx) = tokio::sync::mpsc::channel(1);@@ -1957,6 +2406,7 @@ mod tests {choice_index: 0,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -1979,6 +2429,7 @@ mod tests {choice_index: 0,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -2065,6 +2516,53 @@ mod tests {assert_eq!(v["choices"][0]["finish_reason"], "length");}+ #[test]+ fn test_sse_text_completion_model_load_failed_uses_safe_public_message() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ });++ let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);+ assert!(value["choices"][0]["finish_reason"].is_null());+ assert_eq!(+ value["error"]["code"],+ crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE+ );+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::MODEL_LOAD_FAILED_PUBLIC_MESSAGE+ );+ assert_eq!(value["error"]["type"], "server_error");+ assert!(value["error"]["param"].is_null());+ assert!(!value+ .to_string()+ .contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }++ #[test]+ fn test_build_text_completion_chunk_event_preserves_worker_error() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "unsupported_field".to_string(),+ message: "top_k is unavailable".to_string(),+ param: Some("top_k".to_string()),+ retry_after_s: None,+ });++ let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);++ assert!(value["choices"][0]["finish_reason"].is_null());+ assert_eq!(value["error"]["code"], "unsupported_field");+ assert_eq!(value["error"]["type"], "invalid_request_error");+ assert_eq!(value["error"]["param"], "top_k");+ assert_eq!(value["error"]["message"], "top_k is unavailable");+ assert_eq!(value["request_id"], "req-test");+ }+#[test]fn test_sse_chat_subsequent_chunk_omits_role() {let chunk = _delta_chunk(1, " world");@@ -2093,26 +2591,97 @@ mod tests {assert_eq!(v["choices"][0]["finish_reason"], "length");}+ #[test]+ fn test_sse_successful_terminal_exposes_execution_evidence() {+ let identity = "a".repeat(64);+ let binding = "b".repeat(64);+ let mut chunk = _terminal_chunk("stop", None);+ chunk.execution_identity_sha256 = Some(identity.clone());+ chunk.execution_binding_sha256 = Some(binding.clone());++ for value in [+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),+ build_generate_chunk_event(&chunk, &[]),+ ] {+ assert_eq!(value["execution_identity_sha256"], identity);+ assert_eq!(value["execution_binding_sha256"], binding);+ }+ }++ #[test]+ fn test_sse_execution_evidence_requires_complete_successful_terminal_pair() {+ let mut delta = _delta_chunk(0, "Hi");+ delta.execution_identity_sha256 = Some("a".repeat(64));+ delta.execution_binding_sha256 = Some("b".repeat(64));+ let mut partial = _terminal_chunk("stop", None);+ partial.execution_identity_sha256 = Some("a".repeat(64));+ let mut error = _terminal_chunk("error", None);+ error.execution_identity_sha256 = Some("a".repeat(64));+ error.execution_binding_sha256 = Some("b".repeat(64));+ error.error = Some(ChunkError {+ code: "transport_failure".to_string(),+ message: "upstream gone".to_string(),+ param: None,+ retry_after_s: None,+ });++ for value in [+ build_generate_chunk_event(&delta, &[]),+ build_generate_chunk_event(&partial, &[]),+ build_generate_chunk_event(&error, &[]),+ ] {+ assert!(value.get("execution_identity_sha256").is_none());+ assert!(value.get("execution_binding_sha256").is_none());+ }+ }+/// Worker-error chunks surface an ``error`` block alongside the/// normal envelope and trigger the SDK error path.#[test]fn test_sse_chat_error_chunk_attaches_error_block() {let mut chunk = _terminal_chunk("error", None);chunk.error = Some(ChunkError {- code: "context_exceeded".to_string(),- message: "prompt too long".to_string(),+ code: "unsupported_field".to_string(),+ message: "top_k is unavailable".to_string(),+ param: Some("top_k".to_string()),+ retry_after_s: None,});let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);- assert_eq!(v["error"]["code"], "context_exceeded");- assert_eq!(v["error"]["type"], "context_length_exceeded");- assert!(v["error"]["param"].is_null());- assert_eq!(v["error"]["message"], "prompt too long");+ assert_eq!(v["error"]["code"], "unsupported_field");+ assert_eq!(v["error"]["type"], "invalid_request_error");+ assert_eq!(v["error"]["param"], "top_k");+ assert_eq!(v["error"]["message"], "top_k is unavailable");// #3136: the ERROR chunk carries the gateway request id in-band// (additive member; OpenAI clients ignore it) so SDK consumers can// correlate stream failures with gateway logs.assert_eq!(v["request_id"], "req-test");}+ #[test]+ fn test_sse_chat_model_load_failed_uses_safe_public_message() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ });++ let value = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ assert_eq!(+ value["error"]["code"],+ crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE+ );+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::MODEL_LOAD_FAILED_PUBLIC_MESSAGE+ );+ assert!(!value+ .to_string()+ .contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }+/// #3136 scope guard: ``request_id`` rides ERROR chunks only — normal/// deltas and clean terminals keep the exact pre-existing chat shape.#[test]@@ -2177,12 +2746,206 @@ mod tests {chunk.error = Some(ChunkError {code: "transport_failure".to_string(),message: "upstream gone".to_string(),+ param: None,+ retry_after_s: None,});let v = build_generate_chunk_event(&chunk, &[]);assert_eq!(v["error"]["code"], "transport_failure");assert_eq!(v["error"]["message"], "upstream gone");}+ #[test]+ fn test_sse_generate_model_load_failed_uses_safe_public_message() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ });++ let value = build_generate_chunk_event(&chunk, &[]);+ assert_eq!(+ value["error"]["code"],+ crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE+ );+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::MODEL_LOAD_FAILED_PUBLIC_MESSAGE+ );+ assert!(!value+ .to_string()+ .contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }++ #[test]+ fn test_sse_unknown_worker_errors_fail_closed_on_all_generation_shapes() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "SENSITIVE_WORKER_ERROR_CODE_SENTINEL".to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ });++ let values = [+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),+ build_generate_chunk_event(&chunk, &[]),+ ];+ for value in values {+ assert_eq!(value["error"]["code"], "inference_error");+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE+ );+ let serialized = value.to_string();+ assert!(!serialized.contains("SENSITIVE_WORKER_ERROR_CODE_SENTINEL"));+ assert!(!serialized.contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ }+ }++ #[test]+ fn test_sse_payload_too_large_preserves_worker_code_on_all_generation_shapes() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "PAYLOAD_TOO_LARGE".to_string(),+ message: "payload exceeds limit".to_string(),+ param: None,+ retry_after_s: None,+ });++ for value in [+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),+ build_generate_chunk_event(&chunk, &[]),+ ] {+ assert_eq!(value["error"]["code"], "PAYLOAD_TOO_LARGE");+ assert_eq!(value["error"]["message"], "payload exceeds limit");+ }+ }++ #[test]+ fn worker_error_sse_shapes_preserve_validated_retry_after() {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "RESOURCE_EXHAUSTED".to_string(),+ message: "resource pressure".to_string(),+ param: Some("model".to_string()),+ retry_after_s: Some(12),+ });++ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);+ let generate = build_generate_chunk_event(&chunk, &[]);++ for value in [&chat, &completion, &generate] {+ assert_eq!(value["error"]["retry_after_s"], 12);+ assert!(value["error"]["param"].is_null());+ }+ }++ #[test]+ fn worker_error_sse_shapes_omit_untrusted_or_wrong_code_retry_after() {+ for error in [+ ChunkError {+ code: "RESOURCE_EXHAUSTED".to_string(),+ message: "resource pressure".to_string(),+ param: None,+ retry_after_s: Some(61),+ },+ ChunkError {+ code: "MODEL_LOADING".to_string(),+ message: "draining".to_string(),+ param: None,+ retry_after_s: Some(12),+ },+ ] {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(error);++ for value in [+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false),+ build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),+ build_generate_chunk_event(&chunk, &[]),+ ] {+ assert!(value["error"].get("retry_after_s").is_none());+ }+ }+ }++ #[test]+ fn worker_inference_error_sse_shapes_sanitize_untrusted_message() {+ let sentinel = "SENSITIVE_BACKEND_SENTINEL";+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "inference_error".to_string(),+ message: sentinel.to_string(),+ param: Some(sentinel.to_string()),+ retry_after_s: None,+ });++ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);+ let generate = build_generate_chunk_event(&chunk, &[]);++ for value in [&chat, &completion, &generate] {+ assert_eq!(+ value["error"]["message"],+ "internal error during generation"+ );+ assert!(value["error"]["param"].is_null());+ assert!(!value.to_string().contains(sentinel));+ }+ }++ #[test]+ fn worker_grammar_compile_error_sanitizes_untrusted_message() {+ let sentinel = "SENSITIVE_GRAMMAR_SENTINEL";+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "grammar_compile_failed".to_string(),+ message: sentinel.to_string(),+ param: Some(sentinel.to_string()),+ retry_after_s: None,+ });++ let value = build_generate_chunk_event(&chunk, &[]);++ assert_eq!(+ value["error"]["message"],+ "internal error compiling grammar"+ );+ assert!(value["error"]["param"].is_null());+ assert!(!value.to_string().contains(sentinel));+ }++ #[test]+ fn unknown_worker_error_sse_shapes_sanitize_untrusted_message() {+ let sentinel = "SENSITIVE_WORKER_ERROR_CODE_SENTINEL";+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: sentinel.to_string(),+ message: sentinel.to_string(),+ param: Some(sentinel.to_string()),+ retry_after_s: None,+ });++ let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false);+ let completion = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);+ let generate = build_generate_chunk_event(&chunk, &[]);++ for value in [&chat, &completion, &generate] {+ assert_eq!(+ value["error"]["message"],+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE+ );+ assert_eq!(value["error"]["code"], "inference_error");+ assert!(value["error"]["param"].is_null());+ assert!(!value.to_string().contains(sentinel));+ }+ }+// ── Synthesized error chunks (gateway-side timeouts) ──────────#[tokio::test]@@ -2236,6 +2999,72 @@ mod tests {assert_eq!(v["error"]["code"], "overall_timeout");}+ #[tokio::test]+ async fn test_sse_outcome_worker_errors_use_safe_contract_on_all_endpoints() {+ let cases = [+ (+ crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE,+ crate::queue::streaming::MODEL_LOAD_FAILED_ERROR_CODE,+ crate::queue::streaming::MODEL_LOAD_FAILED_PUBLIC_MESSAGE,+ ),+ (+ "SENSITIVE_WORKER_ERROR_CODE_SENTINEL",+ "inference_error",+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE,+ ),+ (+ "model_load_failed",+ "inference_error",+ crate::queue::streaming::UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE,+ ),+ ];++ for (worker_code, expected_code, expected_message) in cases {+ for endpoint in [+ SseEndpoint::Generate,+ SseEndpoint::Chat {+ include_usage: false,+ },+ SseEndpoint::Completion {+ include_usage: false,+ },+ ] {+ let error = ChunkError {+ code: worker_code.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ };+ let (tx, mut rx) = tokio::sync::mpsc::channel(4);+ send_synthetic_error_chunk(&tx, &endpoint, "cmpl-1", 1, "m", "req-1", &error).await;+ send_done(&tx).await;++ let error_event = rx.recv().await.expect("error event").expect("valid event");+ let value: Value = serde_json::from_str(&_event_data(error_event).await)+ .expect("valid worker error JSON");+ assert_eq!(value["error"]["code"], expected_code);+ assert_eq!(value["error"]["message"], expected_message);+ assert!(!value+ .to_string()+ .contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ match endpoint {+ SseEndpoint::Generate => {+ assert_eq!(value["finish_reason"], "error");+ }+ SseEndpoint::Chat { .. } | SseEndpoint::Completion { .. } => {+ assert!(value["choices"][0]["finish_reason"].is_null());+ assert_eq!(value["error"]["type"], "server_error");+ assert!(value["error"]["param"].is_null());+ assert_eq!(value["request_id"], "req-1");+ }+ }++ let done_event = rx.recv().await.expect("done event").expect("valid event");+ assert_eq!(_event_data(done_event).await, "[DONE]");+ }+ }+ }+#[tokio::test]async fn test_sse_done_terminator_literal() {let (tx, mut rx) = tokio::sync::mpsc::channel(4);@@ -2603,6 +3432,8 @@ mod tests {err_chunk.error = Some(ChunkError {code: "rate_limit_exceeded".to_string(),message: "saturated".to_string(),+ param: None,+ retry_after_s: None,});collector.apply(err_chunk);let got = tap.recv().await.unwrap();@@ -2616,6 +3447,40 @@ mod tests {assert_eq!(g["done"], true);}+ #[tokio::test]+ async fn text_completion_preserves_pre_first_and_mid_stream_worker_errors() {+ for preceding_delta in [false, true] {+ let (tx, _rx) = tokio::sync::oneshot::channel();+ let mut collector =+ crate::queue::streaming::StreamCollector::new(tx, "m".to_string(), "p".to_string());+ let mut tap = collector.install_chunk_tap();+ if preceding_delta {+ collector.apply(_delta_chunk(0, "partial"));+ let delta = tap.recv().await.unwrap();+ let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &delta);+ assert_eq!(value["choices"][0]["text"], "partial");+ assert!(value.get("error").is_none());+ }++ let mut error = _terminal_chunk("error", None);+ error.seq = if preceding_delta { 1 } else { 0 };+ error.error = Some(ChunkError {+ code: "unsupported_field".to_string(),+ message: "top_k is unavailable".to_string(),+ param: Some("top_k".to_string()),+ retry_after_s: None,+ });+ collector.apply(error);++ let terminal = tap.recv().await.unwrap();+ let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &terminal);+ assert_eq!(value["error"]["code"], "unsupported_field");+ assert_eq!(value["error"]["param"], "top_k");+ assert!(value["choices"][0]["finish_reason"].is_null());+ assert_eq!(value["request_id"], "req-test");+ }+ }+/// `/v1/generate/{model}` (SIE-native) uses the simpler shape —/// no `chat.completion.chunk` wrapper, no `delta` block.#[tokio::test]@@ -2682,6 +3547,7 @@ mod tests {choice_index: 0,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, true);let delta = &v["choices"][0]["delta"];diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rsindex f4b434273..9b16d812c 100644--- a/packages/sie_gateway/src/middleware/metrics.rs+++ b/packages/sie_gateway/src/middleware/metrics.rs@@ -65,6 +65,7 @@ struct RequestObservation {operation: &'static str,status: u16,machine_profile: String,+ model: String,}#[derive(Clone, Default)]@@ -189,11 +190,15 @@ where// the request exited before normalization (e.g. `model is// required`). Empty strings also collapse to `"other"`// so dashboards never render a blank label row.- let profile_label = slot- .get()+ let labels = slot.get();+ let profile_label = labels.map(|l| l.machine_profile.as_str()).filter(|s| !s.is_empty()).unwrap_or("other");+ let model_label = labels+ .map(|l| l.model.as_str())+ .filter(|s| !s.is_empty())+ .unwrap_or("other");request_span.record("http.response.status_code", status);request_span.record("sie.machine_profile", profile_label);@@ -202,13 +207,17 @@ wherelet admission_outcome = admission_slot.get().unwrap_or(telemetry::AdmissionOutcome::Admitted);- telemetry::record_request_completed(- Some(request_cx_for_log.span().span_context()),- endpoint,+ let observation = telemetry::RequestCompletionObservation {+ operation: endpoint,status,- profile_label,- elapsed,+ machine_profile: profile_label,+ model: model_label,+ duration_s: elapsed,admission_outcome,+ };+ telemetry::record_request_completed(+ Some(request_cx_for_log.span().span_context()),+ &observation,);#[cfg(test)]if let Some(observations) = observations {@@ -216,6 +225,7 @@ whereoperation: endpoint,status,machine_profile: profile_label.to_string(),+ model: model_label.to_string(),});}@@ -294,6 +304,7 @@ mod tests {if let Some(slot) = req.extensions().get::<telemetry::MetricLabelsSlot>() {slot.set(telemetry::MetricLabels {machine_profile: profile.to_string(),+ model: "org/model".to_string(),});}axum::response::IntoResponse::into_response((StatusCode::OK, "ok"))@@ -325,6 +336,7 @@ mod tests {if let Some(slot) = req.extensions().get::<telemetry::MetricLabelsSlot>() {slot.set(telemetry::MetricLabels {machine_profile: "a100".to_string(),+ model: "org/model".to_string(),});}axum::response::IntoResponse::into_response((@@ -444,6 +456,7 @@ mod tests {if let Some(slot) = req.extensions().get::<telemetry::MetricLabelsSlot>() {slot.set(telemetry::MetricLabels {machine_profile: "l4-spot".to_string(),+ model: "org/model".to_string(),});}StatusCode::OK@@ -531,6 +544,7 @@ mod tests {operation: "encode",status: 200,machine_profile: "l4-spot".to_string(),+ model: "org/model".to_string(),}]);}@@ -557,6 +571,7 @@ mod tests {operation: "score",status: 503,machine_profile: "other".to_string(),+ model: "other".to_string(),}]);}@@ -573,6 +588,7 @@ mod tests {operation: "extract",status: 504,machine_profile: "a100".to_string(),+ model: "org/model".to_string(),}]);}@@ -589,6 +605,7 @@ mod tests {operation: "embeddings",status: 200,machine_profile: "l4-spot".to_string(),+ model: "org/model".to_string(),}]);}@@ -611,6 +628,7 @@ mod tests {operation: "generate",status: 200,machine_profile: "a100".to_string(),+ model: "org/model".to_string(),}}));}@@ -627,6 +645,7 @@ mod tests {operation: "extract",status: 200,machine_profile: "l4-spot".to_string(),+ model: "org/model".to_string(),}]);}@@ -643,6 +662,7 @@ mod tests {operation: "moderations",status: 501,machine_profile: "other".to_string(),+ model: "other".to_string(),}]);}diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rsindex cb7f37dea..2e6c08105 100644--- a/packages/sie_gateway/src/observability/metrics.rs+++ b/packages/sie_gateway/src/observability/metrics.rs@@ -126,6 +126,19 @@ struct ResultChunkReservationObservableState {#[derive(Clone, Debug, Default)]pub struct MetricLabels {pub machine_profile: String,+ pub model: String,+}++/// One terminal inference-request observation. The type deliberately has no+/// customer, credential, request, URL, payload, or error-text field.+#[derive(Clone, Copy, Debug)]+pub struct RequestCompletionObservation<'a> {+ pub operation: &'a str,+ pub status: u16,+ pub machine_profile: &'a str,+ pub model: &'a str,+ pub duration_s: f64,+ pub admission_outcome: AdmissionOutcome,}/// First-write-wins request-extension carrier for [`MetricLabels`].@@ -1128,21 +1141,21 @@ impl GatewayTelemetry {}}- fn request_completed(- &self,- operation: &str,- status: u16,- machine_profile: &str,- duration_s: f64,- admission_outcome: AdmissionOutcome,- ) {- let request_attributes = request_attributes(operation, status, machine_profile);+ fn request_completed(&self, observation: &RequestCompletionObservation<'_>) {+ let request_attributes = request_attributes(+ observation.operation,+ observation.status,+ observation.machine_profile,+ );self.requests.add(1, &request_attributes);self.request_duration- .record(duration_s.max(0.0), &request_attributes);+ .record(observation.duration_s.max(0.0), &request_attributes);self.admission_decisions.add(1,- &admission_attributes(operation, admission_outcome.as_str()),+ &admission_attributes(+ observation.operation,+ observation.admission_outcome.as_str(),+ ),);}@@ -1629,7 +1642,7 @@ fn pinned_model_key(pool: &str, model: &str) -> PinnedModelKey {(sanitize_label(pool), sanitize_model_label(model))}-fn sanitize_model_label(value: &str) -> String {+pub(super) fn sanitize_model_label(value: &str) -> String {const MAX_MODEL_LABEL_LEN: usize = 256;if value.is_empty()|| value.len() > MAX_MODEL_LABEL_LEN@@ -1717,47 +1730,25 @@ fn record_lane_updates(instrument: &Gauge<f64>, values: &[LaneSnapshot]) {fn record_request_completed_to(telemetry: Option<&GatewayTelemetry>,span_context: Option<&SpanContext>,- operation: &str,- status: u16,- machine_profile: &str,- duration_s: f64,- admission_outcome: AdmissionOutcome,+ observation: &RequestCompletionObservation<'_>,) {if let Some(telemetry) = telemetry {- telemetry.request_completed(- operation,- status,- machine_profile,- duration_s,- admission_outcome,- );+ telemetry.request_completed(observation);}- super::tracing::record_inference_completion_log(- span_context,- bounded_operation(operation),- status,- );+ let bounded = RequestCompletionObservation {+ operation: bounded_operation(observation.operation),+ ..*observation+ };+ super::tracing::record_inference_completion_log(span_context, &bounded);}/// Record one completed inference request, its admission decision, and its one/// privacy-safe completion log from a single semantic call site.pub fn record_request_completed(span_context: Option<&SpanContext>,- operation: &str,- status: u16,- machine_profile: &str,- duration_s: f64,- admission_outcome: AdmissionOutcome,+ observation: &RequestCompletionObservation<'_>,) {- record_request_completed_to(- telemetry(),- span_context,- operation,- status,- machine_profile,- duration_s,- admission_outcome,- );+ record_request_completed_to(telemetry(), span_context, observation);}#[allow(dead_code)] // Managed composition API plus disabled-path benchmark seam.@@ -3288,7 +3279,14 @@ mod tests {#[test]fn request_and_keda_contract_exports_exact_names_units_labels_and_freshness() {let (telemetry, exporter, provider) = metric_points();- telemetry.request_completed("encode", 200, "l4-spot", 0.025, AdmissionOutcome::Admitted);+ telemetry.request_completed(&RequestCompletionObservation {+ operation: "encode",+ status: 200,+ machine_profile: "l4-spot",+ model: "BAAI/bge-m3",+ duration_s: 0.025,+ admission_outcome: AdmissionOutcome::Admitted,+ });let lane = |value| LaneSnapshot {pool: "DEFAULT".to_string(),machine_profile: "L4-SPOT".to_string(),@@ -3992,27 +3990,28 @@ mod tests {let (telemetry, _exporter, provider) = metric_points();let exercise_enabled = |target: &GatewayTelemetry, iterations: usize| {for index in 0..iterations {- record_request_completed_to(- Some(target),- None,- black_box("encode"),- black_box(200),- black_box("l4-spot"),- black_box((index % 100) as f64 / 1_000.0),- black_box(AdmissionOutcome::Admitted),- );+ let observation = RequestCompletionObservation {+ operation: black_box("encode"),+ status: black_box(200),+ machine_profile: black_box("l4-spot"),+ model: black_box("BAAI/bge-m3"),+ duration_s: black_box((index % 100) as f64 / 1_000.0),+ admission_outcome: black_box(AdmissionOutcome::Admitted),+ };+ record_request_completed_to(Some(target), None, black_box(&observation));}};let exercise_disabled = |iterations: usize| {for index in 0..iterations {- record_request_completed(- None,- black_box("encode"),- black_box(200),- black_box("l4-spot"),- black_box((index % 100) as f64 / 1_000.0),- black_box(AdmissionOutcome::Admitted),- );+ let observation = RequestCompletionObservation {+ operation: black_box("encode"),+ status: black_box(200),+ machine_profile: black_box("l4-spot"),+ model: black_box("BAAI/bge-m3"),+ duration_s: black_box((index % 100) as f64 / 1_000.0),+ admission_outcome: black_box(AdmissionOutcome::Admitted),+ };+ record_request_completed(None, black_box(&observation));}};diff --git a/packages/sie_gateway/src/observability/tracing.rs b/packages/sie_gateway/src/observability/tracing.rsindex a949d7bb5..18e1a92a6 100644--- a/packages/sie_gateway/src/observability/tracing.rs+++ b/packages/sie_gateway/src/observability/tracing.rs@@ -56,9 +56,10 @@ use tracing_subscriber::util::SubscriberInitExt;use tracing_subscriber::{EnvFilter, Layer};use crate::observability::metrics::{- ACTIVE_LEASE_GPUS_METRIC_NAME, KEDA_SCALE_UP_REJECTION_REASON_CARDINALITY,- LANE_QUEUE_DEPTH_METRIC_NAME, LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME,- PENDING_DEMAND_METRIC_NAME, POOL_WARM_FLOOR_METRIC_NAME, REJECTED_REQUESTS_METRIC_NAME,+ RequestCompletionObservation, ACTIVE_LEASE_GPUS_METRIC_NAME,+ KEDA_SCALE_UP_REJECTION_REASON_CARDINALITY, LANE_QUEUE_DEPTH_METRIC_NAME,+ LANE_QUEUE_SNAPSHOT_TIMESTAMP_METRIC_NAME, PENDING_DEMAND_METRIC_NAME,+ POOL_WARM_FLOOR_METRIC_NAME, REJECTED_REQUESTS_METRIC_NAME,};use crate::state::demand_tracker::MAX_CONFIGURED_PHYSICAL_LANES;@@ -156,7 +157,7 @@ pub fn install_metrics_benchmark_provider() {/// The only managed log event emitted by the first privacy-safe producer./// Both event name and body are fixed; no generic message reaches OTLP.pub const REQUEST_COMPLETION_LOG_EVENT: &str = "inference.request.completed";-const REQUEST_COMPLETION_LOG_SCHEMA: &str = "1";+const REQUEST_COMPLETION_LOG_SCHEMA: &str = "2";/// True when the OTLP trace exporter/provider is installed.pub fn exporter_enabled() -> bool {@@ -646,13 +647,12 @@ fn build_log_exporter(/// The record is deliberately omitted unless it can be joined to a valid,/// sampled gateway span. The metric above remains 100%; logs follow the same/// parent-based sampling decision as the trace to avoid orphan records and an-/// accidental independent-volume policy. Every field below is bounded and-/// produced by gateway code—no request/model/id/URL/header/body/error value is-/// accepted by this API.+/// accidental independent-volume policy. Every field below is bounded and+/// produced by gateway code. Customer identifiers, credential material,+/// request bodies, URLs, headers, and error text are not accepted by this API.pub fn record_inference_completion_log(span_context: Option<&SpanContext>,- operation: &str,- status: u16,+ observation: &RequestCompletionObservation<'_>,) {let Some(span_context) = sampled_log_span_context(span_context) else {return;@@ -664,8 +664,7 @@ pub fn record_inference_completion_log(logger.emit(build_request_completion_log_record(logger,span_context,- operation,- status,+ observation,));}@@ -676,10 +675,9 @@ fn sampled_log_span_context(span_context: Option<&SpanContext>) -> Option<&SpanCfn build_request_completion_log_record(logger: &SdkLogger,span_context: &SpanContext,- operation: &str,- status: u16,+ observation: &RequestCompletionObservation<'_>,) -> opentelemetry_sdk::logs::SdkLogRecord {- let status = super::metrics::bounded_http_status(status);+ let status = super::metrics::bounded_http_status(observation.status);let mut record = logger.create_log_record();record.set_timestamp(SystemTime::now());record.set_severity_number(Severity::Info);@@ -692,9 +690,19 @@ fn build_request_completion_log_record();record.add_attribute("event.name", REQUEST_COMPLETION_LOG_EVENT);record.add_attribute("event.schema.version", REQUEST_COMPLETION_LOG_SCHEMA);- record.add_attribute("operation", operation.to_string());+ record.add_attribute("operation", observation.operation.to_string());record.add_attribute("outcome", super::metrics::request_outcome(status));record.add_attribute("http.status_code", i64::from(status));+ record.add_attribute(+ "model",+ super::metrics::sanitize_model_label(observation.model),+ );+ record.add_attribute(+ "machine_profile",+ super::metrics::sanitize_label(observation.machine_profile),+ );+ record.add_attribute("duration_ms", observation.duration_s.max(0.0) * 1_000.0);+ record.add_attribute("admission_outcome", observation.admission_outcome.as_str());record}@@ -1568,7 +1576,15 @@ mod tests {);let provider = SdkLoggerProvider::builder().build();let logger = provider.logger("test");- let record = build_request_completion_log_record(&logger, &span_context, "encode", 200);+ let observation = RequestCompletionObservation {+ operation: "encode",+ status: 200,+ model: "BAAI/bge-m3",+ machine_profile: "l4-spot",+ duration_s: 0.125,+ admission_outcome: super::super::metrics::AdmissionOutcome::Admitted,+ };+ let record = build_request_completion_log_record(&logger, &span_context, &observation);assert_eq!(record.event_name(), None);assert_eq!(@@ -1585,21 +1601,26 @@ mod tests {.attributes_iter().map(|(key, value)| (key.as_str(), value.clone())).collect();- assert_eq!(attributes.len(), 5);+ assert_eq!(attributes.len(), 9);assert_eq!(attributes["event.name"],AnyValue::from("inference.request.completed"));- assert_eq!(attributes["event.schema.version"], AnyValue::from("1"));+ assert_eq!(attributes["event.schema.version"], AnyValue::from("2"));assert_eq!(attributes["operation"], AnyValue::from("encode"));assert_eq!(attributes["outcome"], AnyValue::from("success"));assert_eq!(attributes["http.status_code"], AnyValue::from(200_i64));+ assert_eq!(attributes["model"], AnyValue::from("BAAI/bge-m3"));+ assert_eq!(attributes["machine_profile"], AnyValue::from("l4-spot"));+ assert_eq!(attributes["duration_ms"], AnyValue::from(125.0_f64));+ assert_eq!(attributes["admission_outcome"], AnyValue::from("admitted"));for forbidden in ["request_id",- "model","url","header","error",+ "api_key",+ "email","prompt","document","embedding",@@ -1619,7 +1640,15 @@ mod tests {);let provider = SdkLoggerProvider::builder().build();let logger = provider.logger("test");- let record = build_request_completion_log_record(&logger, &span_context, "encode", 700);+ let observation = RequestCompletionObservation {+ operation: "encode",+ status: 700,+ model: "invalid model value with spaces",+ machine_profile: "invalid/profile",+ duration_s: 0.0,+ admission_outcome: super::super::metrics::AdmissionOutcome::Admitted,+ };+ let record = build_request_completion_log_record(&logger, &span_context, &observation);let attributes: HashMap<_, _> = record.attributes_iter().map(|(key, value)| (key.as_str(), value.clone()))@@ -1627,6 +1656,8 @@ mod tests {assert_eq!(attributes["outcome"], AnyValue::from("other"));assert_eq!(attributes["http.status_code"], AnyValue::from(0_i64));+ assert_eq!(attributes["model"], AnyValue::from("other"));+ assert_eq!(attributes["machine_profile"], AnyValue::from("other"));}#[test]diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 0465cc81d..6c2f62c95 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -1364,6 +1364,9 @@ fn inject_inference_response_headers(paths: &mut serde_json::Map<String, Value>)"X-SIE-Execution-Identity-SHA256": sha256_header("Worker-origin SHA-256 identity of the immutable release and realized serving resources, when available",),+ "X-SIE-Execution-Binding-SHA256": sha256_header(+ "Worker-origin runtime-independent SHA-256 binding of the release and deployment route, when available",+ ),"X-SIE-Request-Id": header("Gateway request id for queue-backed inference"),"X-SIE-Worker": header("Logical queue worker tag that produced the response"),"X-Queue-Publish-Time": header("Milliseconds spent publishing work to the queue"),@@ -1997,6 +2000,13 @@ pub struct GenerateResponse {pub struct GenerateChunkError {pub code: String,pub message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub param: Option<String>,+ /// Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null+ /// for other terminal errors.+ #[schema(minimum = 1, maximum = 60)]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub retry_after_s: Option<u16>,}/// One JSON payload from a SIE-native generation SSE ``data:`` event.@@ -2589,6 +2599,10 @@ pub struct ModelInfoWire {/// alias). Treat them as "can do this", not "guaranteed to score X".#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct ModelCapabilitiesWire {+ /// Whether the model supports incremental public generation output.+ /// Defaults to true for generation models when omitted from older configs.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub streaming: Option<bool>,/// Union of LoRA served-names across profiles. Back-compat summary/// for consumers that don't care about profile scope; validation/// MUST go through ``profile_lora_adapters``.@@ -3493,12 +3507,34 @@ mod tests {chunk["properties"]["error"]["oneOf"][1]["$ref"],"#/components/schemas/GenerateChunkError");+ let chunk_error = &spec["components"]["schemas"]["GenerateChunkError"];+ assert_eq!(+ chunk_error["properties"]["param"]["type"],+ json!(["string", "null"])+ );+ assert_eq!(chunk_error["required"], json!(["code", "message"]));+ assert_eq!(+ chunk_error["properties"]["retry_after_s"]["type"],+ json!(["integer", "null"])+ );+ assert_eq!(chunk_error["properties"]["retry_after_s"]["minimum"], 1);+ assert_eq!(chunk_error["properties"]["retry_after_s"]["maximum"], 60);assert_eq!(chunk["properties"]["logprobs"]["type"],json!(["array", "null"]));}+ #[test]+ fn openapi_json_documents_streaming_model_capability() {+ let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();+ assert_eq!(+ spec["components"]["schemas"]["ModelCapabilitiesWire"]["properties"]["streaming"]+ ["type"],+ json!(["boolean", "null"]),+ );+ }+#[test]fn openapi_json_documents_chat_privacy_and_constraints() {let spec: serde_json::Value = serde_json::from_str(&OPENAPI_JSON).unwrap();@@ -3836,6 +3872,12 @@ mod tests {.is_some(),"{path} missing documented worker execution identity header");+ assert!(+ responses["200"]["headers"]+ .get("X-SIE-Execution-Binding-SHA256")+ .is_some(),+ "{path} missing documented stable execution binding header"+ );}let pool_post = &spec["paths"]["/v1/pools"]["post"]["responses"];@@ -3902,6 +3944,7 @@ mod tests {"X-SIE-Request-Id","X-SIE-Model-Revision","X-SIE-Execution-Identity-SHA256",+ "X-SIE-Execution-Binding-SHA256",] {assert!(headers.get(name).is_some(),@@ -3912,6 +3955,10 @@ mod tests {headers["X-SIE-Execution-Identity-SHA256"]["schema"]["pattern"],"^[0-9a-f]{64}$");+ assert_eq!(+ headers["X-SIE-Execution-Binding-SHA256"]["schema"]["pattern"],+ "^[0-9a-f]{64}$"+ );}}diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 4f2f51381..6c4b87a0f 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -24,6 +24,7 @@ use super::payload_store::PayloadStore;use super::stream_durability;use super::streaming::{ChunkApplied, ChunkEnvelope, ChunkError, NakEnvelope, StreamCollector, StreamOutcome,+ StreamOutcomeOrigin,};use crate::endpoint::InferenceEndpoint;use crate::observability::metrics::{@@ -690,6 +691,10 @@ pub struct WorkResult {/// observed resource shape. Optional for rolling/self-host compatibility.#[serde(default)]pub execution_identity_sha256: Option<String>,+ /// Runtime-independent release and deployment-route binding. Optional for+ /// rolling/self-host compatibility.+ #[serde(default)]+ pub execution_binding_sha256: Option<String>,}/// One bounded fragment of a named-msgpack encoded [`WorkResult`].@@ -1530,6 +1535,7 @@ fn fail_pending_result_chunk_request(worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}).collect();if let Some(sender) = collector.sender.take() {@@ -3814,12 +3820,16 @@ impl WorkPublisher {error: Some(crate::queue::streaming::ChunkError {code: code.to_string(),message: message.to_string(),+ param: None,+ retry_after_s: None,}),+ origin: StreamOutcomeOrigin::GatewaySynthetic,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};if let Some(sender) = collector.sender.take() {if sender.send(outcome).is_err() {@@ -5099,12 +5109,16 @@ impl WorkPublisher {error: Some(ChunkError {code: "shutdown".to_string(),message: "gateway shutdown before stream completed".to_string(),+ param: None,+ retry_after_s: None,}),+ origin: StreamOutcomeOrigin::GatewaySynthetic,tool_calls: None,logprobs: None,candidates: Vec::new(),executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,});if let Some(sender) = collector.sender.take() {if sender.send(outcome).is_err() {@@ -6467,6 +6481,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -7070,6 +7085,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}),None,],@@ -7143,6 +7159,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let duplicate = WorkResult {result_msgpack: vec![2],@@ -7206,6 +7223,7 @@ mod tests {worker_direct: true,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let pool_result = WorkResult {result_msgpack: vec![2],@@ -7610,6 +7628,9 @@ mod tests {worker_direct: true,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: Some(+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".to_string(),+ ),};let encoded = rmp_serde::to_vec(&result).unwrap();@@ -7621,6 +7642,10 @@ mod tests {assert_eq!(decoded.result_msgpack, vec![5, 6, 7]);assert_eq!(decoded.units.and_then(|units| units.audio_ms), Some(1_001));assert!(decoded.worker_direct);+ assert_eq!(+ decoded.execution_binding_sha256.as_deref(),+ Some("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"),+ );}#[test]@@ -7819,6 +7844,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}).expect("encode work result")}@@ -7966,6 +7992,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let encoded = rmp_serde::to_vec(&result).unwrap();let extracted = extract_request_id_fast(&encoded);@@ -7993,6 +8020,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let encoded = rmp_serde::to_vec_named(&result).unwrap();let extracted = extract_request_id_fast(&encoded);@@ -8037,6 +8065,7 @@ mod tests {worker_direct: false,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,};let encoded = rmp_serde::to_vec(&result).unwrap();let extracted = extract_request_id_fast(&encoded);diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex ebcd20163..edd72a7ce 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -27,6 +27,7 @@ use std::time::Instant;use serde::{Deserialize, Serialize};use tokio::sync::{broadcast, oneshot, Notify};+use crate::http_error::openai_code;use crate::observability::metrics::{self as telemetry, GenerationEvent, GenerationEventOutcome, GenerationEventReason,};@@ -106,6 +107,10 @@ pub struct ChunkEnvelope {/// chunk; older and self-host workers omit it.#[serde(default, skip_serializing_if = "Option::is_none")]pub execution_identity_sha256: Option<String>,+ /// Runtime-independent release/deployment binding. Managed workers stamp+ /// it atomically with the full execution identity.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub execution_binding_sha256: Option<String>,}fn is_zero_u32(v: &u32) -> bool {@@ -203,9 +208,141 @@ pub struct ChunkError {pub code: String,#[serde(default)]pub message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub param: Option<String>,+ /// Operator-configured OOM retry hint. Additive for mixed-version+ /// gateway/worker rollouts; absent from older workers and non-capacity+ /// errors. The gateway validates code + bounds before trusting it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub retry_after_s: Option<u16>,}+impl ChunkError {+ /// Classify the worker discriminator before it crosses a public edge.+ pub(crate) fn client_safe_code(&self) -> &'static str {+ client_safe_worker_error_code(&self.code)+ }++ /// Accept only the server config's validated 1..=60 second domain and+ /// only on the RESOURCE_EXHAUSTED error class that owns this hint.+ pub(crate) fn validated_retry_after_s(&self) -> Option<u16> {+ match (self.code.as_str(), self.retry_after_s) {+ ("RESOURCE_EXHAUSTED", Some(value @ 1..=60)) => Some(value),+ _ => None,+ }+ }++ /// Treat worker terminal messages as untrusted. Expected typed/client+ /// errors remain exact; generic backend and grammar-internal failures use+ /// stable public text so mixed-version workers cannot disclose internals.+ pub(crate) fn client_safe_message(&self) -> &str {+ client_safe_worker_error_message(&self.code, &self.message)+ }++ /// Treat worker terminal parameters as untrusted. Only the typed+ /// unsupported-field contract and its finite public field set currently+ /// own a public parameter; every other code or value fails closed until+ /// explicitly admitted here.+ pub(crate) fn client_safe_param(&self) -> Option<&str> {+ client_safe_worker_error_param(&self.code, self.param.as_deref())+ }+}++/// Terminal model load failure (non-retryable). Matches the server's HTTP 502+/// contract so the SDK short-circuits before exhausting its loading retry budget.+pub(crate) const MODEL_LOAD_FAILED_ERROR_CODE: &str = "MODEL_LOAD_FAILED";+pub(crate) const MODEL_LOAD_FAILED_PUBLIC_MESSAGE: &str = "The requested model failed to load.";+pub(crate) const UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE: &str =+ "Generation terminated with an upstream error.";++/// Return the closed public discriminator for a worker terminal error.+///+/// Worker error metadata is untrusted even after the queue has bound it to a+/// request. Every reviewed code maps to its canonical public spelling; future,+/// malformed, or secret-bearing values collapse to the generic terminal code.+pub(crate) fn client_safe_worker_error_code(code: &str) -> &'static str {+ match code {+ "inference_error" => "inference_error",+ "grammar_compile_failed" => "grammar_compile_failed",+ "MODEL_LOADING" => "MODEL_LOADING",+ "MODEL_OUTPUT_PARSE_ERROR" => "MODEL_OUTPUT_PARSE_ERROR",+ "RESOURCE_EXHAUSTED" => "RESOURCE_EXHAUSTED",+ "COLD_START_RATE_LIMITED" => "COLD_START_RATE_LIMITED",+ "LORA_LOADING" => "LORA_LOADING",+ MODEL_LOAD_FAILED_ERROR_CODE => MODEL_LOAD_FAILED_ERROR_CODE,+ "PAYLOAD_TOO_LARGE" => "PAYLOAD_TOO_LARGE",+ openai_code::CANCELLED => openai_code::CANCELLED,+ openai_code::CONTEXT_EXCEEDED => openai_code::CONTEXT_EXCEEDED,+ openai_code::EMPTY_MODEL_OUTPUT => openai_code::EMPTY_MODEL_OUTPUT,+ "grammar_invalid" => "grammar_invalid",+ "invalid_request" => "invalid_request",+ "parallel_tool_calls_violated" => "parallel_tool_calls_violated",+ "rate_limit_exceeded" => "rate_limit_exceeded",+ "tool_call_parse_error" => "tool_call_parse_error",+ "transport_failure" => "transport_failure",+ "unsupported_field" => "unsupported_field",+ _ => "inference_error",+ }+}++pub(crate) fn client_safe_worker_error_message<'a>(code: &str, message: &'a str) -> &'a str {+ match client_safe_worker_error_code(code) {+ MODEL_LOAD_FAILED_ERROR_CODE => MODEL_LOAD_FAILED_PUBLIC_MESSAGE,+ "inference_error" if code == "inference_error" => "internal error during generation",+ "inference_error" => UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE,+ "grammar_compile_failed" => "internal error compiling grammar",+ _ => message,+ }+}++pub(crate) fn client_safe_worker_error_param<'a>(+ code: &str,+ param: Option<&'a str>,+) -> Option<&'a str> {+ match (client_safe_worker_error_code(code), param) {+ ("unsupported_field", Some(param))+ if CLIENT_SAFE_UNSUPPORTED_GENERATION_PARAMS.contains(¶m) =>+ {+ Some(param)+ }+ _ => None,+ }+}++/// Public generation fields that an adapter may reject through+/// `GenerationUnsupportedFieldError`, plus the response-mode `stream` flag+/// supplied separately to `GenerationAdapter::preflight_generate`. Keeping+/// this finite prevents a worker from selecting the otherwise-safe+/// `unsupported_field` code to disclose an arbitrary parameter string.+const CLIENT_SAFE_UNSUPPORTED_GENERATION_PARAMS: &[&str] = &[+ "prompt",+ "max_new_tokens",+ "temperature",+ "top_p",+ "stop",+ "frequency_penalty",+ "presence_penalty",+ "top_k",+ "repetition_penalty",+ "min_new_tokens",+ "grammar",+ "seed",+ "logit_bias",+ "logprobs",+ "top_logprobs",+ "images",+ "stream",+];+/// Outcome delivered to the HTTP handler once a terminal chunk arrives.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StreamOutcomeOrigin {+ /// A real worker terminal was first copied to the ordered chunk tap.+ WorkerTerminal,+ /// The gateway terminated transport state without a worker terminal.+ GatewaySynthetic,+}+#[derive(Debug)]pub struct StreamOutcome {pub text: String,@@ -215,6 +352,7 @@ pub struct StreamOutcome {pub ttft_ms: Option<f64>,pub tpot_ms: Option<f64>,pub error: Option<ChunkError>,+ pub origin: StreamOutcomeOrigin,/// Aggregated OpenAI tool calls observed across the request's/// chunk stream. ``None`` when no tool calls were emitted. Each/// entry is the fully-assembled ``{id, type, function: {name,@@ -234,6 +372,7 @@ pub struct StreamOutcome {pub candidates: Vec<CandidateData>,pub executed_bundle_config_hash: Option<String>,pub execution_identity_sha256: Option<String>,+ pub execution_binding_sha256: Option<String>,}/// Fully-assembled tool call ready to surface on the non-streaming@@ -356,6 +495,8 @@ pub struct StreamCollector {/// non-attestable while preserving ordinary streaming compatibility.execution_identity_sha256: Option<String>,execution_identity_consistent: bool,+ execution_binding_sha256: Option<String>,+ execution_binding_consistent: bool,/// Attempt id of the most recently abandoned attempt. Usually set by/// [`Self::bump_attempt_generation`] from the old ``current_attempt_id``;/// NAK-driven republish may also fill it from the NAK envelope when the@@ -411,6 +552,8 @@ struct AttemptSnapshot {last_applied_seq: Option<u32>,execution_identity_sha256: Option<String>,execution_identity_consistent: bool,+ execution_binding_sha256: Option<String>,+ execution_binding_consistent: bool,}#[derive(Debug, Clone)]@@ -449,6 +592,8 @@ impl StreamCollector {logprobs: Vec::new(),execution_identity_sha256: None,execution_identity_consistent: true,+ execution_binding_sha256: None,+ execution_binding_consistent: true,abandoned_attempt_id: None,client_disconnected: Arc::new(AtomicBool::new(false)),snapshot: None,@@ -526,6 +671,8 @@ impl StreamCollector {last_applied_seq: self.last_applied_seq,execution_identity_sha256: self.execution_identity_sha256.clone(),execution_identity_consistent: self.execution_identity_consistent,+ execution_binding_sha256: self.execution_binding_sha256.clone(),+ execution_binding_consistent: self.execution_binding_consistent,});// Record the abandoned attempt id so the ``None`` latch arm of// ``apply`` refuses to re-latch on a stale leftover chunk from@@ -544,6 +691,8 @@ impl StreamCollector {self.output_event_count = 0;self.execution_identity_sha256 = None;self.execution_identity_consistent = true;+ self.execution_binding_sha256 = None;+ self.execution_binding_consistent = true;// ``chunks`` / ``tool_calls_by_index`` were already emptied by// the ``std::mem::take`` above. Dropping the partial text from// the abandoned attempt prevents a mid-stream republish@@ -601,6 +750,8 @@ impl StreamCollector {self.last_applied_seq = snap.last_applied_seq;self.execution_identity_sha256 = snap.execution_identity_sha256;self.execution_identity_consistent = snap.execution_identity_consistent;+ self.execution_binding_sha256 = snap.execution_binding_sha256;+ self.execution_binding_consistent = snap.execution_binding_consistent;} else {// Defensive: a rewind with no matching snapshot (should not// happen — every rewind follows a bump). Fall back to the@@ -614,6 +765,8 @@ impl StreamCollector {self.output_event_count = 0;self.execution_identity_sha256 = None;self.execution_identity_consistent = true;+ self.execution_binding_sha256 = None;+ self.execution_binding_consistent = true;}// The abandoned-id guard is meaningless once we have rewound// back onto the prior attempt: clear it so the restored@@ -766,6 +919,23 @@ impl StreamCollector {}}+ match chunk.execution_binding_sha256.as_ref() {+ Some(value) if is_lower_sha256(value) && self.execution_binding_consistent => {+ if let Some(current) = self.execution_binding_sha256.as_ref() {+ if current != value {+ self.execution_binding_consistent = false;+ self.execution_binding_sha256 = None;+ }+ } else {+ self.execution_binding_sha256 = Some(value.clone());+ }+ }+ _ => {+ self.execution_binding_consistent = false;+ self.execution_binding_sha256 = None;+ }+ }+let now = Instant::now();// Arm ``first_chunk_at`` on the first applied chunk that carries// ANY payload — text OR tool-call deltas. Tool-call deltas ride@@ -789,13 +959,32 @@ impl StreamCollector {}self.last_chunk_at = Some(now);- // Fan out to the SSE tap before mutating ``chunks`` so the- // forwarded envelope reflects the wire-level chunk (including- // an empty terminal ``text_delta``). The clone is per-chunk- // and only happens when a tap is installed; non-streaming- // requests pay nothing extra.+ // Fan out to the SSE tap before mutating ``chunks``. Terminal+ // execution evidence is authoritative only when both digests+ // were valid and unanimous across the complete stream.if let Some(tap) = self.chunk_tap.as_ref() {- let _ = tap.send(chunk.clone());+ let mut tapped_chunk = chunk.clone();+ if tapped_chunk.done {+ let evidence =+ if self.execution_identity_consistent && self.execution_binding_consistent {+ self.execution_identity_sha256+ .clone()+ .zip(self.execution_binding_sha256.clone())+ } else {+ None+ };+ match evidence {+ Some((identity, binding)) => {+ tapped_chunk.execution_identity_sha256 = Some(identity);+ tapped_chunk.execution_binding_sha256 = Some(binding);+ }+ None => {+ tapped_chunk.execution_identity_sha256 = None;+ tapped_chunk.execution_binding_sha256 = None;+ }+ }+ }+ let _ = tap.send(tapped_chunk);}if !chunk.text_delta.is_empty() {@@ -916,6 +1105,7 @@ impl StreamCollector {ttft_ms,tpot_ms,error: meta.error.clone(),+ origin: StreamOutcomeOrigin::WorkerTerminal,tool_calls,logprobs,candidates: meta.candidates.clone(),@@ -924,6 +1114,10 @@ impl StreamCollector {.execution_identity_consistent.then(|| self.execution_identity_sha256.clone()).flatten(),+ execution_binding_sha256: self+ .execution_binding_consistent+ .then(|| self.execution_binding_sha256.clone())+ .flatten(),})}}@@ -984,6 +1178,8 @@ pub struct NakEnvelope {#[cfg(test)]mod tests {+ use std::collections::BTreeSet;+use super::*;fn _make_chunk(attempt: &str, seq: u32, text: &str, done: bool) -> ChunkEnvelope {@@ -1013,6 +1209,7 @@ mod tests {choice_index: 0,executed_bundle_config_hash: None,execution_identity_sha256: None,+ execution_binding_sha256: None,}}@@ -1030,6 +1227,8 @@ mod tests {term.error = Some(ChunkError {code: "MODEL_LOADING".to_string(),message: "Model 'Qwen/Qwen3-4B-Instruct-2507' is loading; retry later.".to_string(),+ param: None,+ retry_after_s: None,});assert_eq!(c.apply(term), ChunkApplied::Terminal);@@ -1042,6 +1241,182 @@ mod tests {assert!(err.message.contains("retry later"));}+ #[test]+ fn test_resource_exhausted_retry_hint_is_additive_and_fail_closed() {+ let decode = |retry_after_s: serde_json::Value, code: &str| {+ let bytes = rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "chunk",+ "request_id": "req-retry",+ "done": true,+ "error": {+ "code": code,+ "message": "capacity",+ "retry_after_s": retry_after_s,+ },+ }))+ .expect("encode test envelope");+ rmp_serde::from_slice::<ChunkEnvelope>(&bytes)+ };++ let valid = decode(serde_json::json!(12), "RESOURCE_EXHAUSTED").expect("valid hint");+ assert_eq!(valid.error.unwrap().validated_retry_after_s(), Some(12));++ for value in [serde_json::json!(0), serde_json::json!(61)] {+ let decoded = decode(value, "RESOURCE_EXHAUSTED").expect("typed but out-of-range hint");+ assert_eq!(decoded.error.unwrap().validated_retry_after_s(), None);+ }+ let wrong_code = decode(serde_json::json!(12), "MODEL_LOADING").expect("typed hint");+ assert_eq!(wrong_code.error.unwrap().validated_retry_after_s(), None);++ for value in [+ serde_json::json!(-1),+ serde_json::json!("12"),+ serde_json::json!(1.5),+ serde_json::json!(true),+ ] {+ assert!(decode(value, "RESOURCE_EXHAUSTED").is_err());+ }++ let explicit_null = decode(serde_json::Value::Null, "RESOURCE_EXHAUSTED")+ .expect("explicit null remains backwards compatible");+ assert_eq!(explicit_null.error.unwrap().validated_retry_after_s(), None);++ let legacy_bytes = rmp_serde::to_vec_named(&serde_json::json!({+ "kind": "chunk",+ "request_id": "req-legacy",+ "done": true,+ "error": {"code": "RESOURCE_EXHAUSTED", "message": "capacity"},+ }))+ .expect("encode legacy envelope");+ let legacy: ChunkEnvelope =+ rmp_serde::from_slice(&legacy_bytes).expect("legacy worker decodes");+ assert_eq!(legacy.error.unwrap().validated_retry_after_s(), None);+ }++ #[test]+ fn test_worker_error_public_contract_fails_closed_for_parameters() {+ let public_message = "PUBLIC_MESSAGE";+ let secret_param = "SENSITIVE_PARAM_SENTINEL";+ let cases = [+ ("unsupported_field", "top_k", public_message, Some("top_k")),+ ("unsupported_field", secret_param, public_message, None),+ ("invalid_request", "top_k", public_message, None),+ (+ "inference_error",+ secret_param,+ "internal error during generation",+ None,+ ),+ (+ "grammar_compile_failed",+ secret_param,+ "internal error compiling grammar",+ None,+ ),+ (+ "future_adapter_error",+ "top_k",+ UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE,+ None,+ ),+ ];++ for (code, param, expected_message, expected_param) in cases {+ let error = ChunkError {+ code: code.to_string(),+ message: public_message.to_string(),+ param: Some(param.to_string()),+ retry_after_s: None,+ };+ assert_eq!(error.client_safe_message(), expected_message, "{code}");+ assert_eq!(error.client_safe_param(), expected_param, "{code}");+ }++ for param in CLIENT_SAFE_UNSUPPORTED_GENERATION_PARAMS {+ assert_eq!(+ client_safe_worker_error_param("unsupported_field", Some(param)),+ Some(*param),+ "the reviewed public generation field set must stay synchronized"+ );+ }+ }++ #[test]+ fn test_client_safe_unsupported_generation_params_are_python_safe() {+ let python_source =+ include_str!("../../../sie_server/src/sie_server/adapters/_generation_base.py");+ let declaration = [+ "_CLIENT_SAFE_UNSUPPORTED_GENERATION_PARAMS = frozenset(",+ "_CLIENT_SAFE_GENERATION_PARAMS = frozenset(",+ ]+ .into_iter()+ .find_map(|marker| python_source.split_once(marker).map(|(_, suffix)| suffix))+ .expect("Python generation parameter allowlist must exist");+ let declaration = declaration+ .split_once('{')+ .expect("Python generation parameter allowlist must open")+ .1+ .split_once('}')+ .expect("Python generation parameter allowlist must close")+ .0;+ let python_params: BTreeSet<_> = declaration+ .lines()+ .filter_map(|line| line.trim().strip_prefix('"')?.strip_suffix("\","))+ .collect();+ let rust_params: BTreeSet<_> = CLIENT_SAFE_UNSUPPORTED_GENERATION_PARAMS+ .iter()+ .copied()+ .collect();++ assert!(rust_params.contains("stream"));+ assert!(rust_params.is_subset(&python_params));+ }++ #[test]+ fn test_worker_error_public_contract_preserves_only_sanctioned_codes() {+ for code in [+ "inference_error",+ "grammar_compile_failed",+ "MODEL_LOADING",+ "MODEL_OUTPUT_PARSE_ERROR",+ "RESOURCE_EXHAUSTED",+ "COLD_START_RATE_LIMITED",+ "LORA_LOADING",+ MODEL_LOAD_FAILED_ERROR_CODE,+ "PAYLOAD_TOO_LARGE",+ "cancelled",+ "context_exceeded",+ "empty_model_output",+ "grammar_invalid",+ "invalid_request",+ "parallel_tool_calls_violated",+ "rate_limit_exceeded",+ "tool_call_parse_error",+ "transport_failure",+ "unsupported_field",+ ] {+ assert_eq!(client_safe_worker_error_code(code), code, "{code}");+ }+ assert_eq!(+ client_safe_worker_error_code("SENSITIVE_WORKER_ERROR_CODE_SENTINEL"),+ "inference_error"+ );+ assert_eq!(+ client_safe_worker_error_message(+ MODEL_LOAD_FAILED_ERROR_CODE,+ "SENSITIVE_WORKER_FAILURE_SENTINEL"+ ),+ MODEL_LOAD_FAILED_PUBLIC_MESSAGE+ );+ assert_eq!(+ client_safe_worker_error_message(+ "SENSITIVE_WORKER_ERROR_CODE_SENTINEL",+ "SENSITIVE_WORKER_FAILURE_SENTINEL"+ ),+ UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE+ );+ }+/// Multi-candidate (`n>1`): the terminal chunk carries a `candidates`/// array which the collector passes through verbatim onto the/// `StreamOutcome` for the body builder to expand into `choices[]`.@@ -1118,12 +1493,15 @@ mod tests {#[test]fn test_collector_requires_execution_identity_on_every_chunk() {let identity = "a".repeat(64);+ let binding = "b".repeat(64);let (tx, _rx) = oneshot::channel();let mut consistent = StreamCollector::new(tx, "m".to_string(), "p".to_string());let mut delta = _make_chunk("att-A", 0, "Hi", false);delta.execution_identity_sha256 = Some(identity.clone());+ delta.execution_binding_sha256 = Some(binding.clone());let mut terminal = _make_chunk("att-A", 1, "", true);terminal.execution_identity_sha256 = Some(identity.clone());+ terminal.execution_binding_sha256 = Some(binding.clone());assert_eq!(consistent.apply(delta), ChunkApplied::Delta);assert_eq!(consistent.apply(terminal), ChunkApplied::Terminal);assert_eq!(@@ -1134,13 +1512,23 @@ mod tests {.as_deref(),Some(identity.as_str()));+ assert_eq!(+ consistent+ .build_outcome()+ .expect("terminal")+ .execution_binding_sha256+ .as_deref(),+ Some(binding.as_str())+ );let (tx, _rx) = oneshot::channel();let mut mismatching = StreamCollector::new(tx, "m".to_string(), "p".to_string());let mut delta = _make_chunk("att-B", 0, "Hi", false);delta.execution_identity_sha256 = Some(identity);+ delta.execution_binding_sha256 = Some(binding.clone());let mut terminal = _make_chunk("att-B", 1, "", true);terminal.execution_identity_sha256 = Some("b".repeat(64));+ terminal.execution_binding_sha256 = Some("c".repeat(64));assert_eq!(mismatching.apply(delta), ChunkApplied::Delta);assert_eq!(mismatching.apply(terminal), ChunkApplied::Terminal);assert!(mismatching@@ -1148,11 +1536,17 @@ mod tests {.expect("terminal").execution_identity_sha256.is_none());+ assert!(mismatching+ .build_outcome()+ .expect("terminal")+ .execution_binding_sha256+ .is_none());let (tx, _rx) = oneshot::channel();let mut missing = StreamCollector::new(tx, "m".to_string(), "p".to_string());let mut delta = _make_chunk("att-C", 0, "Hi", false);delta.execution_identity_sha256 = Some("c".repeat(64));+ delta.execution_binding_sha256 = Some(binding);assert_eq!(missing.apply(delta), ChunkApplied::Delta);assert_eq!(missing.apply(_make_chunk("att-C", 1, "", true)),@@ -1163,6 +1557,11 @@ mod tests {.expect("terminal").execution_identity_sha256.is_none());+ assert!(missing+ .build_outcome()+ .expect("terminal")+ .execution_binding_sha256+ .is_none());}/// ``ChunkEnvelope`` round-trips a ``logprobs`` field over the wire@@ -1333,6 +1732,49 @@ mod tests {assert_eq!(got.text_delta, "next");}+ #[tokio::test]+ async fn test_collector_tap_terminal_evidence_requires_stream_unanimity() {+ let identity = "a".repeat(64);+ let binding = "b".repeat(64);+ let (tx, _rx) = oneshot::channel();+ let mut collector = StreamCollector::new(tx, "m".to_string(), "p".to_string());+ let mut tap = collector.install_chunk_tap();+ let mut delta = _make_chunk("att-A", 0, "Hi", false);+ delta.execution_identity_sha256 = Some(identity.clone());+ delta.execution_binding_sha256 = Some(binding.clone());+ collector.apply(delta);+ tap.recv().await.unwrap();+ let mut terminal = _make_chunk("att-A", 1, "", true);+ terminal.execution_identity_sha256 = Some(identity.clone());+ terminal.execution_binding_sha256 = Some(binding.clone());+ collector.apply(terminal);+ let tapped_terminal = tap.recv().await.unwrap();+ assert_eq!(+ tapped_terminal.execution_identity_sha256.as_deref(),+ Some(identity.as_str())+ );+ assert_eq!(+ tapped_terminal.execution_binding_sha256.as_deref(),+ Some(binding.as_str())+ );++ let (tx, _rx) = oneshot::channel();+ let mut collector = StreamCollector::new(tx, "m".to_string(), "p".to_string());+ let mut tap = collector.install_chunk_tap();+ let mut delta = _make_chunk("att-B", 0, "Hi", false);+ delta.execution_identity_sha256 = Some(identity);+ delta.execution_binding_sha256 = Some(binding);+ collector.apply(delta);+ tap.recv().await.unwrap();+ let mut terminal = _make_chunk("att-B", 1, "", true);+ terminal.execution_identity_sha256 = Some("c".repeat(64));+ terminal.execution_binding_sha256 = Some("d".repeat(64));+ collector.apply(terminal);+ let tapped_terminal = tap.recv().await.unwrap();+ assert!(tapped_terminal.execution_identity_sha256.is_none());+ assert!(tapped_terminal.execution_binding_sha256.is_none());+ }+/// JetStream redelivery within an attempt re-sends a chunk with the/// *same* ``seq``. The collector must drop it (``Duplicate``) so the/// text is not double-counted and no duplicate SSE event fans out.diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 4363ed3fb..318ed0d32 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -2401,6 +2401,7 @@ impl ModelRegistry {// config — refresh here so a delta-update can rescind or// tighten the advertised set without a full reload.existing.grammar_capabilities = refreshed.grammar_capabilities;+ existing.streaming_supported = refreshed.streaming_supported;existing.tools_supported = refreshed.tools_supported;// ``grammar_profile`` is likewise derived from// ``tasks.generate`` — refresh it too so a delta that changes@@ -4231,6 +4232,100 @@ encode:assert_eq!(refreshed.info_extras.max_sequence_length, Some(1024));}+ #[test]+ fn test_tasks_delta_refreshes_streaming_capability_for_base_and_variants() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - module\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let profile = || crate::types::model::ProfileConfig {+ kv_budget_tokens: None,+ max_output_tokens: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ };+ registry+ .add_model_config(ModelConfig {+ name: "test/generator".to_string(),+ hf_revision: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles: HashMap::from([+ ("default".to_string(), profile()),+ ("buffered".to_string(), profile()),+ ]),+ inputs: None,+ max_sequence_length: None,+ tasks: Some(+ serde_yaml::from_str("generate:\n capabilities:\n streaming: false\n")+ .unwrap(),+ ),+ })+ .unwrap();++ for name in ["test/generator", "test/generator:buffered"] {+ assert_eq!(+ registry+ .get_model_info(name)+ .unwrap()+ .info_extras+ .streaming_supported,+ Some(false),+ "seeded capability for {name}",+ );+ }++ let apply_tasks_delta = |streaming: bool| {+ registry+ .add_model_config(ModelConfig {+ name: "test/generator".to_string(),+ hf_revision: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles: HashMap::from([+ ("default".to_string(), profile()),+ ("buffered".to_string(), profile()),+ ]),+ inputs: None,+ max_sequence_length: None,+ tasks: Some(+ serde_yaml::from_str(&format!(+ "generate:\n capabilities:\n streaming: {streaming}\n"+ ))+ .unwrap(),+ ),+ })+ .unwrap();+ };++ for expected in [true, false] {+ apply_tasks_delta(expected);+ for name in ["test/generator", "test/generator:buffered"] {+ let entry = registry.get_model_info(name).unwrap();+ assert_eq!(+ entry.info_extras.streaming_supported,+ Some(expected),+ "delta for {name}"+ );+ assert_eq!(+ entry.to_model_info_value(false)["capabilities"]["streaming"],+ serde_json::json!(expected),+ "discovery projection for {name}",+ );+ }+ }+ }+#[test]fn test_add_model_config_preserves_info_extras_for_profile_only_update() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -4836,6 +4931,65 @@ profiles:assert_ne!(first, second);}+ #[test]+ fn test_compute_bundle_config_hash_changes_with_serving_artifact_manifest() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ let vector: serde_json::Value = serde_json::from_str(include_str!(+ "../../../../conformance/bundle_config_hash/serving_artifact_expanded_profile_vector.json"+ ))+ .expect("valid shared serving-artifact hash vector");+ let bundle_id = vector["bundle_id"].as_str().expect("bundle id");+ fs::write(+ bundles_dir.join(format!("{bundle_id}.yaml")),+ serde_json::to_vec(&vector["bundle"]).expect("serialize bundle vector"),+ )+ .unwrap();+ let model_path = models_dir.join("derived.yaml");+ let write_model = |manifest_sha256: &str| {+ let mut model = vector["model"].clone();+ *model+ .pointer_mut(+ "/profiles/default/adapter_options/loadtime/serving_artifact/manifest_sha256",+ )+ .expect("manifest pointer") =+ serde_json::Value::String(manifest_sha256.to_string());+ fs::write(+ &model_path,+ serde_json::to_vec(&model).expect("serialize model vector"),+ )+ .unwrap();+ };+ write_model(+ vector["manifest_sha256"]["initial"]+ .as_str()+ .expect("initial manifest digest"),+ );+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let first = registry.compute_bundle_config_hash(bundle_id);++ write_model(+ vector["manifest_sha256"]["changed"]+ .as_str()+ .expect("changed manifest digest"),+ );+ registry.reload();+ let second = registry.compute_bundle_config_hash(bundle_id);++ assert_eq!(+ first,+ vector["expected_hash"]["initial"]+ .as_str()+ .expect("initial expected hash")+ );+ assert_eq!(+ second,+ vector["expected_hash"]["changed"]+ .as_str()+ .expect("changed expected hash")+ );+ assert_ne!(first, second);+ }+#[test]fn test_resolve_execution_evidence_is_one_snapshot_and_profile_exact() {let (_dir, bundles_dir, models_dir) = create_test_dirs();diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 67ce2ea75..446ed236e 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -32,6 +32,10 @@ pub struct ModelInfoExtras {/// ``generate`` task; empty ``Vec`` when grammar is explicitly/// disabled.pub grammar_capabilities: Option<Vec<String>>,+ /// Resolved ``tasks.generate.capabilities.streaming`` value. ``None``+ /// means the model has no generation task; a generation task with no+ /// explicit capability inherits the worker default of ``true``.+ pub streaming_supported: Option<bool>,/// ``tasks.generate.grammar_profile`` from the model YAML — the name of a/// profile that grammar-constrained requests must be served on. When set,/// the chat/completions/generate handlers rewrite a grammar request's model@@ -197,6 +201,12 @@ impl ModelInfoExtras {}).unwrap_or_default();extras.grammar_capabilities = Some(grammar);+ extras.streaming_supported = Some(+ capabilities+ .and_then(|m| m.get("streaming"))+ .and_then(|v| v.as_bool())+ .unwrap_or(true),+ );// ``tasks.generate.grammar_profile: <name>`` — optional profile// that grammar requests are routed to (the gateway rewrites the// model id to ``{model}:{name}``). Absent => no rewrite.@@ -344,6 +354,7 @@ impl ModelInfoExtras {max_output_tokens: None,profile_max_output_tokens: HashMap::new(),grammar_capabilities: None,+ streaming_supported: None,grammar_profile: None,profile_parents: HashMap::new(),tools_supported: None,@@ -478,6 +489,7 @@ impl ModelEntry {"lora_adapters": self.info_extras.lora_adapters,"profile_lora_adapters": self.info_extras.profile_lora_adapters,"grammar": self.info_extras.grammar_capabilities,+ "streaming": self.info_extras.streaming_supported,"tools": self.info_extras.tools_supported,"code": self.info_extras.code,"sql": self.info_extras.sql,@@ -1090,6 +1102,37 @@ tasks:assert_eq!(extras.tools_supported, Some(true));}+ #[test]+ fn test_model_info_extras_streaming_capability_is_resolved_and_advertised() {+ let disabled: serde_yaml::Value = serde_yaml::from_str(+ "name: m\ntasks:\n generate:\n capabilities:\n streaming: false\n",+ )+ .unwrap();+ let defaulted: serde_yaml::Value =+ serde_yaml::from_str("name: m\ntasks:\n generate: {}\n").unwrap();++ let disabled_extras = ModelInfoExtras::from_yaml_raw(&disabled);+ let defaulted_extras = ModelInfoExtras::from_yaml_raw(&defaulted);++ assert_eq!(disabled_extras.streaming_supported, Some(false));+ assert_eq!(defaulted_extras.streaming_supported, Some(true));+ assert_eq!(+ ModelEntry {+ name: "m".to_string(),+ canonical_base_model: "m".to_string(),+ canonical_profile: "default".to_string(),+ pool: None,+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: HashSet::new(),+ profile_configs: HashMap::new(),+ info_extras: disabled_extras,+ }+ .to_model_info_value(false)["capabilities"]["streaming"],+ json!(false)+ );+ }+#[test]fn test_model_info_extras_code_sql_guard_capabilities_parsed() {// Qwen3-4B-Instruct-2507 advertises code + sql (and tools); it isdiff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 80db89cc4..a1b13fb73 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.7.2"+version = "0.7.3"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 49a94a6d0..6fea3f0e7 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -426,6 +426,7 @@ def raise_if_estimate_unroutable(response: _HttpResponse) -> None:raise EstimateUnroutableError(str(message or "the active rate book cannot price this request"),code=code,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -532,6 +533,7 @@ SDK_VERSION_HEADER = "X-SIE-SDK-Version"SERVER_VERSION_HEADER = "X-SIE-Server-Version"MODEL_REVISION_HEADER = "X-SIE-Model-Revision"EXECUTION_IDENTITY_SHA256_HEADER = "X-SIE-Execution-Identity-SHA256"+EXECUTION_BINDING_SHA256_HEADER = "X-SIE-Execution-Binding-SHA256"REQUEST_ID_HEADER = "X-SIE-Request-ID"CREDITS_DEBITED_HEADER = "X-SIE-Credits-Debited"REQUEST_USAGE_HEADERS = {@@ -938,6 +940,14 @@ def parse_request_metadata(headers: Any, body: Any = None) -> RequestMetadata |):metadata["execution_identity_sha256"] = execution_identity_sha256+ execution_binding_sha256 = _header_value(headers, EXECUTION_BINDING_SHA256_HEADER)+ if (+ isinstance(execution_binding_sha256, str)+ and len(execution_binding_sha256) == 64+ and all(char in "0123456789abcdef" for char in execution_binding_sha256)+ ):+ metadata["execution_binding_sha256"] = execution_binding_sha256+return metadata or None@@ -1082,6 +1092,15 @@ def get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:return None+def get_error_param(response: _HttpResponse) -> str | None:+ """Return the exact field name from a typed error envelope, if present."""+ detail = get_error_detail(response)+ if detail is None:+ return None+ param = detail.get("param")+ return param if isinstance(param, str) else None++def raise_if_model_load_failed(response: _HttpResponse, model: str | None = None) -> None:"""Raise :class:`ModelLoadFailedError` if the response is 502 ``MODEL_LOAD_FAILED``.@@ -1129,6 +1148,7 @@ def raise_if_model_load_failed(response: _HttpResponse, model: str | None = Noneerror_class=str(error_class) if error_class is not None else None,permanent=permanent,attempts=attempts,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -1157,7 +1177,12 @@ def raise_if_input_too_long(response: _HttpResponse, model: str | None = None) -if detail.get("code") != INPUT_TOO_LONG_ERROR_CODE:returnmessage = str(detail.get("message") or "Input exceeds the model's maximum token capacity")- raise InputTooLongError(message, model=model, request=parse_request_metadata(response.headers))+ raise InputTooLongError(+ message,+ model=model,+ param=get_error_param(response),+ request=parse_request_metadata(response.headers),+ )def handle_error(response: _HttpResponse) -> NoReturn:@@ -1179,6 +1204,7 @@ def handle_error(response: _HttpResponse) -> NoReturn:ServerError: For other 5xx responses."""code = None+ param = Nonemessage = f"HTTP {response.status_code}"try:@@ -1193,6 +1219,8 @@ def handle_error(response: _HttpResponse) -> NoReturn:if isinstance(error, dict):code = error.get("code")message = error.get("message", message)+ error_param = error.get("param")+ param = error_param if isinstance(error_param, str) else Noneelse:# error is a string, use it as the messagemessage = str(error)@@ -1201,6 +1229,8 @@ def handle_error(response: _HttpResponse) -> NoReturn:if isinstance(detail, dict):code = detail.get("code")message = detail.get("message", str(detail))+ detail_param = detail.get("param")+ param = detail_param if isinstance(detail_param, str) else Noneelse:message = str(detail)except (ValueError, KeyError, TypeError, UnpackException):@@ -1218,33 +1248,33 @@ def handle_error(response: _HttpResponse) -> NoReturn:# Fallback dispatch — ``model`` is only attached by the helper-style# short-circuit (``raise_if_input_too_long``) on the extract path.if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == PROVISIONING_ERROR_CODE:- raise ProvisioningError(message, retry_after=get_retry_after(response))+ raise ProvisioningError(message, retry_after=get_retry_after(response), param=param)if response.status_code == HTTP_CLIENT_ERROR and code == INPUT_TOO_LONG_ERROR_CODE:- raise InputTooLongError(message, request=request)+ raise InputTooLongError(message, param=param, request=request)# Rate limit (pass-2 audit B1). Retried on the admission ladder in the# buffered loops; a give-up there raises RateLimitError directly. This arm# covers the terminal paths (streaming, list_models, estimate, …) so a 429# is always a typed RateLimitError rather than a generic RequestError.if response.status_code == HTTP_TOO_MANY_REQUESTS:- raise RateLimitError(message, code=code, retry_after=get_retry_after(response), request=request)+ raise RateLimitError(message, code=code, retry_after=get_retry_after(response), param=param, request=request)# Terminal credit / account failures (pass-2 audit B3). 402/403 are NEVER# retried — they have no arm on any retry ladder, so they surface here on# the first response. Unrecognised 402/403 codes stay generic RequestError.if response.status_code == HTTP_PAYMENT_REQUIRED:if code == INSUFFICIENT_CREDITS_ERROR_CODE:- raise InsufficientCreditsError(message, request=request)+ raise InsufficientCreditsError(message, param=param, request=request)if code == KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE:- raise SpendLimitError(message, request=request)+ raise SpendLimitError(message, param=param, request=request)if response.status_code == HTTP_FORBIDDEN and code in (ACCOUNT_SUSPENDED_ERROR_CODE,ACCOUNT_PENDING_REVIEW_ERROR_CODE,):- raise AccountInactiveError(message, code=code, request=request)+ raise AccountInactiveError(message, code=code, param=param, request=request)if response.status_code == HTTP_SERVICE_UNAVAILABLE and code == ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE:- raise AccountStateUnavailableError(message, request=request)+ raise AccountStateUnavailableError(message, param=param, request=request)if response.status_code >= HTTP_SERVER_ERROR:- raise ServerError(message, code=code, status_code=response.status_code, request=request)- raise RequestError(message, code=code, status_code=response.status_code, request=request)+ raise ServerError(message, code=code, status_code=response.status_code, param=param, request=request)+ raise RequestError(message, code=code, status_code=response.status_code, param=param, request=request)def provisioning_retry_delay(@@ -1257,13 +1287,14 @@ def provisioning_retry_delay() -> float:"""Return a retry delay for ``503 PROVISIONING`` or raise ``ProvisioningError``."""retry_after = get_retry_after(response)+ param = get_error_param(response)if not wait_for_capacity:msg = f"No capacity available for GPU '{gpu}'. Server is provisioning."- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)+ raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after, param=param)elapsed = time.monotonic() - start_timeif elapsed >= timeout:msg = f"Provisioning timeout after {elapsed:.1f}s waiting for GPU '{gpu}'"- raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after)+ raise ProvisioningError(msg, gpu=gpu, retry_after=retry_after, param=param)remaining = timeout - elapsedif retry_after is not None:return min(retry_after, remaining)@@ -1315,7 +1346,12 @@ def admission_retry_delay(delay = retry_after if retry_after is not None else apply_jitter(min(RATE_LIMIT_DEFAULT_DELAY_S, remaining))if remaining <= 0 or delay >= remaining:msg = f"Rate limited (429); retry budget ({timeout:.1f}s) exhausted after {elapsed:.1f}s"- raise RateLimitError(msg, retry_after=retry_after, request=parse_request_metadata(response.headers))+ raise RateLimitError(+ msg,+ retry_after=retry_after,+ param=get_error_param(response),+ request=parse_request_metadata(response.headers),+ )return delayif status == HTTP_SERVICE_UNAVAILABLE and get_error_code(response) in BACKPRESSURE_503_ERROR_CODES:retry_after = get_retry_after(response)@@ -1392,7 +1428,9 @@ def next_stream_retry_delay(msg,model=model,retries=oom_retries,+ param=get_error_param(response),request=parse_request_metadata(response.headers),+ retry_after=get_retry_after(response),)delay = compute_oom_backoff(get_retry_after(response), oom_retries)return min(delay, timeout - elapsed), oom_retries + 1@@ -1407,6 +1445,7 @@ def next_stream_retry_delay(msg,code=get_error_code(response),status_code=status,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -1428,6 +1467,7 @@ def next_stream_retry_delay(msg,code=get_error_code(response),status_code=status,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -1553,16 +1593,35 @@ def sse_headers(resolved_gpu: str | None, pool_name: str | None) -> dict[str, streturn headers-def sse_chunk_error(chunk: dict[str, Any]) -> tuple[str, str] | None:- """Return ``(code, message)`` if an SSE chunk carries a mid-stream error.+def sse_chunk_error(chunk: dict[str, Any]) -> tuple[str, str, str | None, int | None] | None:+ """Return ``(code, message, param, retry_after_s)`` for a typed SSE error.Both the chat and SIE-native generate surfaces put the error object at thetop level of the chunk (see ``send_error_chunk`` in- ``packages/sie_gateway/src/handlers/sse.rs``).+ ``packages/sie_gateway/src/handlers/sse.rs``). The additive retry hint is+ trusted only for ``RESOURCE_EXHAUSTED`` and only in the engine config's+ integer ``1..=60`` domain; booleans are integers in Python, so exclude+ them explicitly."""err = chunk.get("error")if isinstance(err, dict):- return str(err.get("code") or "error"), str(err.get("message") or "stream error")+ code = str(err.get("code") or "error")+ param = err.get("param")+ retry_after_s = err.get("retry_after_s")+ validated_retry_after_s = (+ retry_after_s+ if code == RESOURCE_EXHAUSTED_ERROR_CODE+ and isinstance(retry_after_s, int)+ and not isinstance(retry_after_s, bool)+ and 1 <= retry_after_s <= 60+ else None+ )+ return (+ code,+ str(err.get("message") or "stream error"),+ param if isinstance(param, str) else None,+ validated_retry_after_s,+ )return Nonediff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex 75407b8b9..1f6f3bf23 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -132,6 +132,7 @@ from ._shared import (convert_score_images_for_wire,copy_base_url_headers,get_error_code,+ get_error_param,get_retry_after,get_sdk_version,handle_error,@@ -299,7 +300,9 @@ async def _handle_oom_retry(msg,model=model,retries=oom_retries,+ param=get_error_param(response),request=parse_request_metadata(response.headers),+ retry_after=get_retry_after(response),)retry_after = get_retry_after(response)raw_delay = compute_oom_backoff(retry_after, oom_retries)@@ -319,7 +322,9 @@ async def _handle_oom_retry(msg,model=model,retries=oom_retries,+ param=get_error_param(response),request=parse_request_metadata(response.headers),+ retry_after=get_retry_after(response),)delay = raw_delay# First retry surfaces at WARNING so a user with default log level@@ -629,6 +634,7 @@ class SIEAsyncClient:*,start_time: float,budget_s: float,+ accept: str = JSON_CONTENT_TYPE,) -> _AioResponse:"""Consume bounded same-origin Modal 303 result URLs without replaying POST."""for _ in range(MODAL_CONTINUATION_MAX_HOPS):@@ -637,14 +643,14 @@ class SIEAsyncClient:return responseremaining = budget_s - (time.monotonic() - start_time)if remaining <= 0:- msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting generation result"+ msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting request result"raise ProvisioningError(msg)try:async with (self._throttle(),self._ensure_session().get(path,- headers=self._headers_for_request(path, {"Accept": JSON_CONTENT_TYPE}),+ headers=self._headers_for_request(path, {"Accept": accept}),timeout=aiohttp.ClientTimeout(total=min(self._timeout, remaining)),allow_redirects=False,) as raw,@@ -1363,6 +1369,13 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)@@ -1921,6 +1934,13 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)@@ -2244,6 +2264,7 @@ class SIEAsyncClient:msg,code=get_error_code(response),status_code=response.status_code,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -2757,7 +2778,7 @@ class SIEAsyncClient:if isinstance(chunk, dict):err = sse_chunk_error(chunk)if err is not None:- code, message = err+ code, message, param, retry_after_s = err# Terminal error chunks — on both the# SIE-native generate shape and the OpenAI# chat shape — carry the gateway request@@ -2766,12 +2787,25 @@ class SIEAsyncClient:# errors like ``empty_model_output`` stay# correlatable (#3136).request_id = valid_stream_request_id(chunk.get("request_id"))- error_headers = {REQUEST_ID_HEADER: request_id} if request_id else None+ error_headers: dict[str, str] = {}+ if request_id:+ error_headers[REQUEST_ID_HEADER] = request_id+ if retry_after_s is not None:+ error_headers["Retry-After"] = str(retry_after_s)if not yielded_chunk:capacity_response = _AioResponse(HTTP_SERVICE_UNAVAILABLE,- json.dumps({"error": {"code": code, "message": message}}).encode(),- error_headers or {},+ json.dumps(+ {+ "error": {+ "code": code,+ "message": message,+ "param": param,+ "retry_after_s": retry_after_s,+ }+ }+ ).encode(),+ error_headers,)retry_delay, oom_retries = next_stream_retry_delay(capacity_response,@@ -2787,7 +2821,9 @@ class SIEAsyncClient:raise ServerError(message,code=code,- request=parse_request_metadata(error_headers or {}),+ param=param,+ request=parse_request_metadata(error_headers),+ retry_after=float(retry_after_s) if retry_after_s is not None else None,)yield chunkyielded_chunk = True@@ -2977,6 +3013,13 @@ class SIEAsyncClient:msg = f"Failed to connect to {self._base_url}: {e}"raise SIEConnectionError(msg) from e+ response = await self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)diff --git a/packages/sie_sdk/src/sie_sdk/client/errors.py b/packages/sie_sdk/src/sie_sdk/client/errors.pyindex 401b8dcf6..a2654055f 100644--- a/packages/sie_sdk/src/sie_sdk/client/errors.py+++ b/packages/sie_sdk/src/sie_sdk/client/errors.py@@ -32,11 +32,13 @@ class RequestError(SIEError):code: str | None = None,status_code: int | None = None,*,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:super().__init__(message)self.code = codeself.status_code = status_code+ self.param = paramself.request = request@@ -45,6 +47,9 @@ class ServerError(SIEError):``request`` contains canonical request, usage, and debit metadata parsedfrom the terminal response headers when the server supplied any.+ ``retry_after`` preserves a validated server retry hint in seconds when+ the terminal error carries one; callers must not infer that retrying a+ non-idempotent request is safe merely because the hint is present."""def __init__(@@ -53,12 +58,16 @@ class ServerError(SIEError):code: str | None = None,status_code: int | None = None,*,+ param: str | None = None,request: RequestMetadata | None = None,+ retry_after: float | None = None,) -> None:super().__init__(message)self.code = codeself.status_code = status_code+ self.param = paramself.request = request+ self.retry_after = retry_afterclass ProvisioningError(SIEError):@@ -80,10 +89,12 @@ class ProvisioningError(SIEError):*,gpu: str | None = None,retry_after: float | None = None,+ param: str | None = None,) -> None:super().__init__(message)self.gpu = gpuself.retry_after = retry_after+ self.param = paramclass PoolError(SIEError):@@ -205,9 +216,10 @@ class ModelLoadFailedError(ServerError):error_class: str | None = None,permanent: bool = True,attempts: int = 1,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code="MODEL_LOAD_FAILED", status_code=502, request=request)+ super().__init__(message, code="MODEL_LOAD_FAILED", status_code=502, param=param, request=request)self.model = modelself.error_class = error_classself.permanent = permanent@@ -236,9 +248,10 @@ class InputTooLongError(RequestError):message: str,*,model: str | None = None,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code="INPUT_TOO_LONG", status_code=400, request=request)+ super().__init__(message, code="INPUT_TOO_LONG", status_code=400, param=param, request=request)self.model = model@@ -265,9 +278,10 @@ class EstimateUnroutableError(ServerError):message: str,*,code: str | None = None,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code=code, status_code=503, request=request)+ super().__init__(message, code=code, status_code=503, param=param, request=request)class RateLimitError(RequestError):@@ -294,9 +308,10 @@ class RateLimitError(RequestError):*,code: str | None = "RATE_LIMIT",retry_after: float | None = None,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code=code, status_code=429, request=request)+ super().__init__(message, code=code, status_code=429, param=param, request=request)self.retry_after = retry_after@@ -316,9 +331,10 @@ class InsufficientCreditsError(RequestError):self,message: str,*,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code="INSUFFICIENT_CREDITS", status_code=402, request=request)+ super().__init__(message, code="INSUFFICIENT_CREDITS", status_code=402, param=param, request=request)class SpendLimitError(RequestError):@@ -336,9 +352,10 @@ class SpendLimitError(RequestError):self,message: str,*,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code="KEY_SPEND_LIMIT_EXCEEDED", status_code=402, request=request)+ super().__init__(message, code="KEY_SPEND_LIMIT_EXCEEDED", status_code=402, param=param, request=request)class AccountInactiveError(RequestError):@@ -359,9 +376,10 @@ class AccountInactiveError(RequestError):message: str,*,code: str | None = None,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code=code, status_code=403, request=request)+ super().__init__(message, code=code, status_code=403, param=param, request=request)class AccountStateUnavailableError(ServerError):@@ -381,9 +399,10 @@ class AccountStateUnavailableError(ServerError):self,message: str,*,+ param: str | None = None,request: RequestMetadata | None = None,) -> None:- super().__init__(message, code="ACCOUNT_STATE_UNAVAILABLE", status_code=503, request=request)+ super().__init__(message, code="ACCOUNT_STATE_UNAVAILABLE", status_code=503, param=param, request=request)class ResourceExhaustedError(ServerError):@@ -401,6 +420,7 @@ class ResourceExhaustedError(ServerError):Attributes:model: The model that was requested.retries: Number of retry attempts made before giving up.+ retry_after: Last validated server retry hint, in seconds."""def __init__(@@ -409,9 +429,18 @@ class ResourceExhaustedError(ServerError):*,model: str | None = None,retries: int = 0,+ param: str | None = None,request: RequestMetadata | None = None,+ retry_after: float | None = None,) -> None:- super().__init__(message, code="RESOURCE_EXHAUSTED", status_code=503, request=request)+ super().__init__(+ message,+ code="RESOURCE_EXHAUSTED",+ status_code=503,+ param=param,+ request=request,+ retry_after=retry_after,+ )self.model = modelself.retries = retriesdiff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex f19640dbb..a74909c6a 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -142,6 +142,7 @@ from ._shared import (convert_score_images_for_wire,copy_base_url_headers,get_error_code,+ get_error_param,get_retry_after,get_sdk_version,handle_error,@@ -306,7 +307,9 @@ def _handle_oom_retry(msg,model=model,retries=oom_retries,+ param=get_error_param(response),request=parse_request_metadata(response.headers),+ retry_after=get_retry_after(response),)retry_after = get_retry_after(response)raw_delay = compute_oom_backoff(retry_after, oom_retries)@@ -335,7 +338,9 @@ def _handle_oom_retry(msg,model=model,retries=oom_retries,+ param=get_error_param(response),request=parse_request_metadata(response.headers),+ retry_after=get_retry_after(response),)delay = raw_delay# First retry surfaces at WARNING so a user with default log level@@ -548,6 +553,7 @@ class SIEClient:*,start_time: float,budget_s: float,+ accept: str = JSON_CONTENT_TYPE,) -> httpx.Response:"""Consume bounded same-origin Modal 303 result URLs without replaying POST."""for _ in range(MODAL_CONTINUATION_MAX_HOPS):@@ -556,12 +562,12 @@ class SIEClient:return responseremaining = budget_s - (time.monotonic() - start_time)if remaining <= 0:- msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting generation result"+ msg = f"Provision timeout ({budget_s:.1f}s) exceeded while awaiting request result"raise ProvisioningError(msg)try:response = self._client.get(path,- headers={"Accept": JSON_CONTENT_TYPE},+ headers={"Accept": accept},timeout=min(self._timeout, remaining),)except httpx.HTTPError as exc:@@ -1352,6 +1358,13 @@ class SIEClient:)raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures BEFORE engaging the# MODEL_LOADING retry budget. The server emits 502# MODEL_LOAD_FAILED for permanent classes (gated repos,@@ -2180,6 +2193,13 @@ class SIEClient:)raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)@@ -2580,6 +2600,7 @@ class SIEClient:msg,code=get_error_code(response),status_code=response.status_code,+ param=get_error_param(response),request=parse_request_metadata(response.headers),)@@ -3106,7 +3127,7 @@ class SIEClient:if isinstance(chunk, dict):err = sse_chunk_error(chunk)if err is not None:- code, message = err+ code, message, param, retry_after_s = err# Terminal error chunks — on both the# SIE-native generate shape and the OpenAI# chat shape — carry the gateway request@@ -3115,12 +3136,23 @@ class SIEClient:# errors like ``empty_model_output`` stay# correlatable (#3136).request_id = valid_stream_request_id(chunk.get("request_id"))- error_headers = {REQUEST_ID_HEADER: request_id} if request_id else None+ error_headers: dict[str, str] = {}+ if request_id:+ error_headers[REQUEST_ID_HEADER] = request_id+ if retry_after_s is not None:+ error_headers["Retry-After"] = str(retry_after_s)if not yielded_chunk:capacity_response = httpx.Response(HTTP_SERVICE_UNAVAILABLE,- json={"error": {"code": code, "message": message}},- headers=error_headers,+ json={+ "error": {+ "code": code,+ "message": message,+ "param": param,+ "retry_after_s": retry_after_s,+ }+ },+ headers=error_headers or None,)retry_delay, oom_retries = next_stream_retry_delay(capacity_response,@@ -3137,7 +3169,9 @@ class SIEClient:raise ServerError(message,code=code,- request=parse_request_metadata(error_headers or {}),+ param=param,+ request=parse_request_metadata(error_headers),+ retry_after=float(retry_after_s) if retry_after_s is not None else None,)yield chunkyielded_chunk = True@@ -3412,6 +3446,13 @@ class SIEClient:)raise SIEConnectionError(msg) from e+ response = self._follow_modal_continuations(+ response,+ start_time=start_time,+ budget_s=timeout,+ accept=MSGPACK_CONTENT_TYPE,+ )+# Short-circuit terminal load failures.raise_if_model_load_failed(response, model=model)diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.pyindex c556e4e12..0e0beff56 100644--- a/packages/sie_sdk/src/sie_sdk/types.py+++ b/packages/sie_sdk/src/sie_sdk/types.py@@ -223,6 +223,7 @@ class RequestMetadata(TypedDict, total=False):#: response reported one.rate_book_version: strexecution_identity_sha256: str+ execution_binding_sha256: strclass EncodeResult(TypedDict, total=False):@@ -278,6 +279,7 @@ class ModelCapabilities(TypedDict, total=False):alias). Treat them as "can do this", not "guaranteed to score X"."""+ streaming: bool | Nonegrammar: list[str]tools: boollora_adapters: list[str]@@ -628,6 +630,16 @@ class GenerateResult(TypedDict, total=False):request: RequestMetadata+class GenerateChunkError(TypedDict):+ """Typed terminal generation error carried by an SSE chunk."""++ code: str+ message: str+ type: NotRequired[str | None]+ param: NotRequired[str | None]+ retry_after_s: NotRequired[int | None]++class GenerateChunk(TypedDict, total=False):"""One SSE event from :meth:`SIEClient.stream_generate` (SIE-native shape).@@ -646,7 +658,9 @@ class GenerateChunk(TypedDict, total=False):finish_reason: Termination reason (terminal chunk only).usage: Prompt / completion / total token counts (terminal chunk only).ttft_ms: Time-to-first-token in milliseconds (terminal chunk only).- error: ``{code, message}`` when generation failed mid-stream.+ error: ``{code, message, param?, retry_after_s?}`` when generation+ failed mid-stream. ``retry_after_s`` is meaningful only for+ ``RESOURCE_EXHAUSTED``."""request_id: str@@ -657,7 +671,7 @@ class GenerateChunk(TypedDict, total=False):finish_reason: FinishReasonusage: GenerationUsagettft_ms: float- error: dict[str, str]+ error: GenerateChunkError# --- Chat completions (OpenAI-compatible) — /v1/chat/completions ------------@@ -769,6 +783,8 @@ class ChatCompletionChunk(TypedDict, total=False):system_fingerprint: str | Nonechoices: list[ChatChunkChoice]usage: ChatUsage+ request_id: str+ error: GenerateChunkError# --- Responses (OpenAI-compatible) — /v1/responses -------------------------diff --git a/packages/sie_sdk/tests/client/test_async.py b/packages/sie_sdk/tests/client/test_async.pyindex d775c0351..a7203fa79 100644--- a/packages/sie_sdk/tests/client/test_async.py+++ b/packages/sie_sdk/tests/client/test_async.py@@ -301,6 +301,7 @@ class TestAsyncEncode:"X-SIE-Units-Input-Tokens": "2","X-SIE-Credits-Debited": "5","X-SIE-Execution-Identity-SHA256": "b" * 64,+ "X-SIE-Execution-Binding-SHA256": "c" * 64,},)@@ -317,6 +318,7 @@ class TestAsyncEncode:"usage": {"input_tokens": 2},"credits_debited": 5,"execution_identity_sha256": "b" * 64,+ "execution_binding_sha256": "c" * 64,}await client.close()diff --git a/packages/sie_sdk/tests/client/test_chat.py b/packages/sie_sdk/tests/client/test_chat.pyindex 64afc8268..96afcf512 100644--- a/packages/sie_sdk/tests/client/test_chat.py+++ b/packages/sie_sdk/tests/client/test_chat.py@@ -17,7 +17,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom sie_sdk import SIEClient-from sie_sdk.client.errors import RequestError, ServerError+from sie_sdk.client.errors import RequestError, ResourceExhaustedError, ServerErrordef _ok_json(payload: dict[str, Any]) -> MagicMock:@@ -257,14 +257,15 @@ def test_stream_raises_server_error_on_error_chunk() -> None:"text_delta": "","done": True,"finish_reason": "error",- "error": {"code": "inference_error", "message": "boom"},+ "error": {"code": "unsupported_field", "message": "boom", "param": "top_k"},}with patch("sie_sdk.client.sync.httpx.Client") as mc:mc.return_value.stream.return_value = _FakeStream(lines=_sse(err))client = SIEClient("http://localhost:8080")with pytest.raises(ServerError) as ei:list(client.stream_generate("m", "hi", max_new_tokens=8))- assert ei.value.code == "inference_error"+ assert ei.value.code == "unsupported_field"+ assert ei.value.param == "top_k"assert ei.value.request == {"id": "r"}client.close()@@ -325,14 +326,15 @@ def test_stream_generate_error_after_output_retains_request_id() -> None:"text_delta": "","done": True,"finish_reason": "error",- "error": {"code": "inference_error", "message": "boom"},+ "error": {"code": "unsupported_field", "message": "boom", "param": "top_k"},}with patch("sie_sdk.client.sync.httpx.Client") as mc:mc.return_value.stream.return_value = _FakeStream(lines=_sse(delta, err))client = SIEClient("http://localhost:8080")with pytest.raises(ServerError) as ei:list(client.stream_generate("m", "hi", max_new_tokens=8))- assert ei.value.code == "inference_error"+ assert ei.value.code == "unsupported_field"+ assert ei.value.param == "top_k"assert ei.value.request == {"id": "req-mid-1"}client.close()@@ -355,6 +357,104 @@ def _chat_error_chunk(code: str, message: str, request_id: str) -> dict[str, Any}+def _capacity_error_chunk(surface: str, retry_after_s: object) -> dict[str, Any]:+ error: dict[str, Any] = {+ "message": "scheduler full",+ "type": "server_error",+ "param": "model",+ "code": "RESOURCE_EXHAUSTED",+ "retry_after_s": retry_after_s,+ }+ if surface == "chat":+ chunk = _chat_error_chunk("RESOURCE_EXHAUSTED", "scheduler full", "req-capacity")+ chunk["error"] = error+ return chunk+ return {+ "request_id": "req-capacity",+ "seq": 1,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": error,+ }+++def _stream_surface(client: SIEClient, surface: str, *, wait_for_capacity: bool = True):+ if surface == "chat":+ return client.stream_chat_completions(+ "m",+ [{"role": "user", "content": "hi"}],+ wait_for_capacity=wait_for_capacity,+ )+ return client.stream_generate(+ "m",+ "hi",+ max_new_tokens=8,+ wait_for_capacity=wait_for_capacity,+ )++[email protected]("surface", ["chat", "native"])+ ("retry_after_s", "expected"),+ [pytest.param(12, 12.0, id="valid"), pytest.param(True, None, id="malformed")],+)+def test_stream_capacity_give_up_preserves_validated_retry_hint(+ surface: str,+ retry_after_s: object,+ expected: float | None,+) -> None:+ error = _capacity_error_chunk(surface, retry_after_s)+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(error))+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ResourceExhaustedError) as exc_info:+ list(_stream_surface(client, surface, wait_for_capacity=False))++ assert exc_info.value.code == "RESOURCE_EXHAUSTED"+ assert exc_info.value.param == "model"+ assert exc_info.value.request == {"id": "req-capacity"}+ assert exc_info.value.retry_after == expected+ client.close()++[email protected]("surface", ["chat", "native"])+ ("retry_after_s", "expected"),+ [pytest.param(12, 12.0, id="valid"), pytest.param(True, None, id="malformed")],+)+def test_stream_capacity_after_output_preserves_hint_without_retry(+ surface: str,+ retry_after_s: object,+ expected: float | None,+) -> None:+ delta = (+ _chat_chunk("partial")+ if surface == "chat"+ else {+ "request_id": "req-capacity",+ "seq": 0,+ "text_delta": "partial",+ "done": False,+ }+ )+ error = _capacity_error_chunk(surface, retry_after_s)+ with patch("sie_sdk.client.sync.httpx.Client") as mc:+ mc.return_value.stream.return_value = _FakeStream(lines=_sse(delta, error))+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ServerError) as exc_info:+ list(_stream_surface(client, surface))++ assert exc_info.value.code == "RESOURCE_EXHAUSTED"+ assert exc_info.value.param == "model"+ assert exc_info.value.request == {"id": "req-capacity"}+ assert exc_info.value.retry_after == expected+ assert mc.return_value.stream.call_count == 1+ client.close()++def test_stream_chat_error_chunk_surfaces_request_id() -> None:"""#3136: a chat-shape stream error before any output must surface thein-band gateway request id — streamed responses carry no terminal headers,@@ -418,6 +518,59 @@ def test_stream_chat_retries_first_sse_model_loading_then_streams() -> None:client.close()+ ("code", "retry_after_s", "expected_hint", "expected_delay"),+ [+ pytest.param("RESOURCE_EXHAUSTED", 12, 12.0, 12.0, id="valid"),+ pytest.param("RESOURCE_EXHAUSTED", None, None, 0.25, id="missing"),+ pytest.param("RESOURCE_EXHAUSTED", True, None, 0.25, id="boolean"),+ pytest.param("RESOURCE_EXHAUSTED", 12.5, None, 0.25, id="fractional"),+ pytest.param("RESOURCE_EXHAUSTED", 61, None, 0.25, id="out-of-domain"),+ pytest.param("MODEL_LOADING", 12, None, 5.0, id="wrong-code"),+ ],+)+def test_stream_chat_first_sse_retry_hint_is_validated(+ code: str,+ retry_after_s: object,+ expected_hint: float | None,+ expected_delay: float,+) -> None:+ error: dict[str, Any] = {"code": code, "message": "capacity unavailable"}+ if retry_after_s is not None:+ error["retry_after_s"] = retry_after_s+ capacity = _FakeStream(lines=_sse({"error": error}))+ success = _FakeStream(lines=_sse(_chat_chunk("ok", finish="stop")))++ def backoff(retry_after: float | None, attempt: int) -> float:+ assert retry_after == expected_hint+ assert attempt == 0+ return retry_after if retry_after is not None else 0.25++ with (+ patch("sie_sdk.client.sync.httpx.Client") as mc,+ patch("sie_sdk.client.sync.time.sleep") as sleep,+ patch("sie_sdk.client._shared.compute_oom_backoff", side_effect=backoff) as oom_backoff,+ ):+ mc.return_value.stream.side_effect = [capacity, success]+ client = SIEClient("http://localhost:8080")++ out = list(+ client.stream_chat_completions(+ "m",+ [{"role": "user", "content": "hi"}],+ provision_timeout_s=60.0,+ )+ )++ assert [chunk["choices"][0]["delta"].get("content") for chunk in out] == ["ok"]+ sleep.assert_called_once_with(expected_delay)+ if code == "RESOURCE_EXHAUSTED":+ oom_backoff.assert_called_once()+ else:+ oom_backoff.assert_not_called()+ client.close()++def test_stream_chat_does_not_retry_sse_model_loading_after_output() -> None:loading = {"error": {"code": "MODEL_LOADING", "message": "loading"}}partial_then_loading = _FakeStream(lines=_sse(_chat_chunk("partial"), loading))diff --git a/packages/sie_sdk/tests/client/test_chat_async.py b/packages/sie_sdk/tests/client/test_chat_async.pyindex 112491593..4f840fbfe 100644--- a/packages/sie_sdk/tests/client/test_chat_async.py+++ b/packages/sie_sdk/tests/client/test_chat_async.py@@ -13,7 +13,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_sdk import SIEAsyncClient-from sie_sdk.client.errors import RequestError, ServerError+from sie_sdk.client.errors import RequestError, ResourceExhaustedError, ServerErrorclass _FakeRaw:@@ -258,13 +258,14 @@ async def test_async_stream_raises_on_error_chunk() -> None:"text_delta": "","done": True,"finish_reason": "error",- "error": {"code": "inference_error", "message": "boom"},+ "error": {"code": "unsupported_field", "message": "boom", "param": "top_k"},}client = SIEAsyncClient("http://localhost:8080")_patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(err)))with pytest.raises(ServerError) as ei:_ = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]- assert ei.value.code == "inference_error"+ assert ei.value.code == "unsupported_field"+ assert ei.value.param == "top_k"assert ei.value.request == {"id": "r"}await client.close()@@ -301,13 +302,14 @@ async def test_async_stream_generate_error_after_output_retains_request_id() ->"text_delta": "","done": True,"finish_reason": "error",- "error": {"code": "inference_error", "message": "boom"},+ "error": {"code": "unsupported_field", "message": "boom", "param": "top_k"},}client = SIEAsyncClient("http://localhost:8080")_patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(delta, err)))with pytest.raises(ServerError) as ei:_ = [c async for c in client.stream_generate("m", "hi", max_new_tokens=8)]- assert ei.value.code == "inference_error"+ assert ei.value.code == "unsupported_field"+ assert ei.value.param == "top_k"assert ei.value.request == {"id": "req-mid-1"}await client.close()@@ -329,6 +331,104 @@ def _chat_error_chunk(code: str, message: str, request_id: str) -> dict[str, Any}+def _capacity_error_chunk(surface: str, retry_after_s: object) -> dict[str, Any]:+ error: dict[str, Any] = {+ "message": "scheduler full",+ "type": "server_error",+ "param": "model",+ "code": "RESOURCE_EXHAUSTED",+ "retry_after_s": retry_after_s,+ }+ if surface == "chat":+ chunk = _chat_error_chunk("RESOURCE_EXHAUSTED", "scheduler full", "req-capacity")+ chunk["error"] = error+ return chunk+ return {+ "request_id": "req-capacity",+ "seq": 1,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": error,+ }+++def _stream_surface(client: SIEAsyncClient, surface: str, *, wait_for_capacity: bool = True):+ if surface == "chat":+ return client.stream_chat_completions(+ "m",+ [{"role": "user", "content": "hi"}],+ wait_for_capacity=wait_for_capacity,+ )+ return client.stream_generate(+ "m",+ "hi",+ max_new_tokens=8,+ wait_for_capacity=wait_for_capacity,+ )++[email protected]("surface", ["chat", "native"])+ ("retry_after_s", "expected"),+ [pytest.param(12, 12.0, id="valid"), pytest.param(True, None, id="malformed")],+)+async def test_async_stream_capacity_give_up_preserves_validated_retry_hint(+ surface: str,+ retry_after_s: object,+ expected: float | None,+) -> None:+ error = _capacity_error_chunk(surface, retry_after_s)+ client = SIEAsyncClient("http://localhost:8080")+ _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(error)))++ with pytest.raises(ResourceExhaustedError) as exc_info:+ _ = [chunk async for chunk in _stream_surface(client, surface, wait_for_capacity=False)]++ assert exc_info.value.code == "RESOURCE_EXHAUSTED"+ assert exc_info.value.param == "model"+ assert exc_info.value.request == {"id": "req-capacity"}+ assert exc_info.value.retry_after == expected+ await client.close()++[email protected]("surface", ["chat", "native"])+ ("retry_after_s", "expected"),+ [pytest.param(12, 12.0, id="valid"), pytest.param(True, None, id="malformed")],+)+async def test_async_stream_capacity_after_output_preserves_hint_without_retry(+ surface: str,+ retry_after_s: object,+ expected: float | None,+) -> None:+ delta = (+ _chat_chunk("partial")+ if surface == "chat"+ else {+ "request_id": "req-capacity",+ "seq": 0,+ "text_delta": "partial",+ "done": False,+ }+ )+ error = _capacity_error_chunk(surface, retry_after_s)+ client = SIEAsyncClient("http://localhost:8080")+ session = _patch_session(client, post_returns=_FakeRaw(status=200, line_bytes=_sse_bytes(delta, error)))++ with pytest.raises(ServerError) as exc_info:+ _ = [chunk async for chunk in _stream_surface(client, surface)]++ assert exc_info.value.code == "RESOURCE_EXHAUSTED"+ assert exc_info.value.param == "model"+ assert exc_info.value.request == {"id": "req-capacity"}+ assert exc_info.value.retry_after == expected+ assert session.post.call_count == 1+ await client.close()++@pytest.mark.asyncioasync def test_async_stream_chat_error_chunk_surfaces_request_id() -> None:"""#3136: async mirror — a chat-shape stream error must surface the@@ -398,6 +498,60 @@ async def test_async_stream_chat_retries_first_sse_model_loading_then_streams()await client.close()+ ("code", "retry_after_s", "expected_hint", "expected_delay"),+ [+ pytest.param("RESOURCE_EXHAUSTED", 12, 12.0, 12.0, id="valid"),+ pytest.param("RESOURCE_EXHAUSTED", None, None, 0.25, id="missing"),+ pytest.param("RESOURCE_EXHAUSTED", True, None, 0.25, id="boolean"),+ pytest.param("RESOURCE_EXHAUSTED", 12.5, None, 0.25, id="fractional"),+ pytest.param("RESOURCE_EXHAUSTED", 61, None, 0.25, id="out-of-domain"),+ pytest.param("MODEL_LOADING", 12, None, 5.0, id="wrong-code"),+ ],+)+async def test_async_stream_chat_first_sse_retry_hint_is_validated(+ code: str,+ retry_after_s: object,+ expected_hint: float | None,+ expected_delay: float,+) -> None:+ error: dict[str, Any] = {"code": code, "message": "capacity unavailable"}+ if retry_after_s is not None:+ error["retry_after_s"] = retry_after_s+ capacity = _FakeRaw(status=200, line_bytes=_sse_bytes({"error": error}))+ success = _FakeRaw(status=200, line_bytes=_sse_bytes(_chat_chunk("ok", finish="stop")))+ client = SIEAsyncClient("http://localhost:8080")+ session = _patch_session(client, post_side_effect=[capacity, success])++ def backoff(retry_after: float | None, attempt: int) -> float:+ assert retry_after == expected_hint+ assert attempt == 0+ return retry_after if retry_after is not None else 0.25++ with (+ patch("sie_sdk.client.async_.asyncio.sleep", new_callable=AsyncMock) as sleep,+ patch("sie_sdk.client._shared.compute_oom_backoff", side_effect=backoff) as oom_backoff,+ ):+ out = [+ chunk+ async for chunk in client.stream_chat_completions(+ "m",+ [{"role": "user", "content": "hi"}],+ provision_timeout_s=60.0,+ )+ ]++ assert [chunk["choices"][0]["delta"].get("content") for chunk in out] == ["ok"]+ sleep.assert_awaited_once_with(expected_delay)+ if code == "RESOURCE_EXHAUSTED":+ oom_backoff.assert_called_once()+ else:+ oom_backoff.assert_not_called()+ assert session.post.call_count == 2+ await client.close()++@pytest.mark.asyncioasync def test_async_stream_chat_does_not_retry_sse_model_loading_after_output() -> None:loading = {"error": {"code": "MODEL_LOADING", "message": "loading"}}diff --git a/packages/sie_sdk/tests/client/test_error_param_propagation.py b/packages/sie_sdk/tests/client/test_error_param_propagation.pynew file mode 100644index 000000000..b679fe81a--- /dev/null+++ b/packages/sie_sdk/tests/client/test_error_param_propagation.py@@ -0,0 +1,162 @@+from __future__ import annotations++import time+from unittest.mock import MagicMock++import pytest+from sie_sdk.client._shared import (+ handle_error,+ next_stream_retry_delay,+ raise_if_estimate_unroutable,+ raise_if_model_load_failed,+ sse_chunk_error,+)+from sie_sdk.client.errors import (+ AccountInactiveError,+ AccountStateUnavailableError,+ EstimateUnroutableError,+ InputTooLongError,+ InsufficientCreditsError,+ ModelLoadFailedError,+ ProvisioningError,+ RateLimitError,+ ResourceExhaustedError,+ ServerError,+ SpendLimitError,+)+++def _response(status_code: int, code: str, *, param: str | None = "top_k") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.headers = {"content-type": "application/json"}+ response.json.return_value = {+ "error": {+ "code": code,+ "message": "request failed",+ "param": param,+ }+ }+ response.text = ""+ return response+++ ("status_code", "code", "error_type"),+ [+ (503, "PROVISIONING", ProvisioningError),+ (400, "INPUT_TOO_LONG", InputTooLongError),+ (429, "RATE_LIMIT", RateLimitError),+ (402, "INSUFFICIENT_CREDITS", InsufficientCreditsError),+ (402, "KEY_SPEND_LIMIT_EXCEEDED", SpendLimitError),+ (403, "ACCOUNT_SUSPENDED", AccountInactiveError),+ (503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError),+ ],+)+def test_handle_error_preserves_param_on_specialized_errors(+ status_code: int,+ code: str,+ error_type: type[Exception],+) -> None:+ with pytest.raises(error_type) as exc_info:+ handle_error(_response(status_code, code))++ assert isinstance(+ exc_info.value,+ (+ ProvisioningError,+ InputTooLongError,+ RateLimitError,+ InsufficientCreditsError,+ SpendLimitError,+ AccountInactiveError,+ AccountStateUnavailableError,+ ),+ )+ assert exc_info.value.param == "top_k"+++def test_model_load_failed_preserves_param() -> None:+ with pytest.raises(ModelLoadFailedError) as exc_info:+ raise_if_model_load_failed(_response(502, "MODEL_LOAD_FAILED", param="model"), model="m")++ assert exc_info.value.param == "model"+++def test_estimate_unroutable_preserves_param() -> None:+ with pytest.raises(EstimateUnroutableError) as exc_info:+ raise_if_estimate_unroutable(_response(503, "QUEUE_UNAVAILABLE", param="model"))++ assert exc_info.value.param == "model"+++def test_streaming_resource_exhausted_preserves_param() -> None:+ with pytest.raises(ResourceExhaustedError) as exc_info:+ next_stream_retry_delay(+ _response(503, "RESOURCE_EXHAUSTED", param="model"),+ model="m",+ gpu=None,+ wait_for_capacity=False,+ start_time=time.monotonic(),+ timeout=10.0,+ oom_retries=0,+ max_oom_retries=3,+ )++ assert exc_info.value.param == "model"+++def test_streaming_gateway_timeout_preserves_param() -> None:+ with pytest.raises(ServerError) as exc_info:+ next_stream_retry_delay(+ _response(504, "GATEWAY_TIMEOUT", param="model"),+ model="m",+ gpu=None,+ wait_for_capacity=True,+ start_time=time.monotonic(),+ timeout=10.0,+ oom_retries=0,+ max_oom_retries=3,+ )++ assert exc_info.value.param == "model"+++ ("code", "retry_after_s", "expected"),+ [+ pytest.param("RESOURCE_EXHAUSTED", 12, 12, id="valid"),+ pytest.param("RESOURCE_EXHAUSTED", None, None, id="null"),+ pytest.param("RESOURCE_EXHAUSTED", True, None, id="boolean"),+ pytest.param("RESOURCE_EXHAUSTED", 12.5, None, id="fractional"),+ pytest.param("RESOURCE_EXHAUSTED", "12", None, id="string"),+ pytest.param("RESOURCE_EXHAUSTED", 0, None, id="below-domain"),+ pytest.param("RESOURCE_EXHAUSTED", 61, None, id="above-domain"),+ pytest.param("MODEL_LOADING", 12, None, id="wrong-code"),+ ],+)+def test_sse_chunk_error_validates_retry_after_s(+ code: str,+ retry_after_s: object,+ expected: int | None,+) -> None:+ parsed = sse_chunk_error(+ {+ "error": {+ "code": code,+ "message": "request failed",+ "retry_after_s": retry_after_s,+ }+ }+ )++ assert parsed == (code, "request failed", None, expected)+++def test_sse_chunk_error_tolerates_missing_retry_after_s() -> None:+ assert sse_chunk_error({"error": {"code": "RESOURCE_EXHAUSTED", "message": "full"}}) == (+ "RESOURCE_EXHAUSTED",+ "full",+ None,+ None,+ )diff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.pyindex 4d27a0878..a6873012f 100644--- a/packages/sie_sdk/tests/client/test_generate.py+++ b/packages/sie_sdk/tests/client/test_generate.py@@ -44,7 +44,9 @@ def _resp_504() -> MagicMock:"X-SIE-Units-Output-Tokens": "5","X-SIE-Credits-Debited": "13",}- response.json.return_value = {"detail": {"code": "GATEWAY_TIMEOUT", "message": "Timeout waiting for queue result"}}+ response.json.return_value = {+ "detail": {"code": "GATEWAY_TIMEOUT", "message": "Timeout waiting for queue result", "param": "model"}+ }response.content = json.dumps(response.json.return_value).encode("utf-8")return response@@ -598,6 +600,7 @@ class TestSyncGenerate:# No backoff sleep happened for the 504.mock_sleep.assert_not_called()assert excinfo.value.status_code == 504+ assert excinfo.value.param == "model"assert excinfo.value.request == {"id": "req-generate-timeout","usage": {"output_tokens": 5},@@ -922,7 +925,7 @@ class TestAsyncGenerate:side_effect=[_aio_resp(504,- {"error": {"code": "MODEL_LOADING", "message": "timeout"}},+ {"error": {"code": "GATEWAY_TIMEOUT", "message": "timeout"}},{"Retry-After": "0.01","content-type": "application/json",@@ -949,6 +952,8 @@ class TestAsyncGenerate:assert client._post.call_count == 1mock_sleep.assert_not_called()assert excinfo.value.status_code == 504+ assert excinfo.value.code == "GATEWAY_TIMEOUT"+ assert excinfo.value.param is Noneassert excinfo.value.request == {"id": "req-async-generate-timeout","usage": {"output_tokens": 5},diff --git a/packages/sie_sdk/tests/client/test_input_too_long.py b/packages/sie_sdk/tests/client/test_input_too_long.pyindex 2285154aa..a6286330b 100644--- a/packages/sie_sdk/tests/client/test_input_too_long.py+++ b/packages/sie_sdk/tests/client/test_input_too_long.py@@ -24,7 +24,7 @@ def _resp_input_too_long(message: str = "Input exceeds capacity (4096 tokens)")resp = MagicMock()resp.status_code = 400resp.headers = {"content-type": "application/json"}- resp.json.return_value = {"detail": {"code": "INPUT_TOO_LONG", "message": message}}+ resp.json.return_value = {"detail": {"code": "INPUT_TOO_LONG", "message": message, "param": "items[0].text"}}return resp@@ -58,6 +58,7 @@ class TestSyncInputTooLong:assert excinfo.value.model == "gliclass-large"assert excinfo.value.code == "INPUT_TOO_LONG"assert excinfo.value.status_code == 400+ assert excinfo.value.param == "items[0].text"assert str(excinfo.value) == "Too many tokens"# Critical: no retry happened.assert mock_client.return_value.post.call_count == 1@@ -92,7 +93,7 @@ class TestSyncInputTooLong:def _aio_input_too_long(message: str = "Input exceeds capacity (4096 tokens)") -> object:return _AioResponse(400,- json.dumps({"detail": {"code": "INPUT_TOO_LONG", "message": message}}).encode(),+ json.dumps({"detail": {"code": "INPUT_TOO_LONG", "message": message, "param": "items[0].text"}}).encode(),{"content-type": "application/json"},)@@ -121,6 +122,7 @@ class TestAsyncInputTooLong:assert excinfo.value.model == "gliclass-large"assert excinfo.value.code == "INPUT_TOO_LONG"assert excinfo.value.status_code == 400+ assert excinfo.value.param == "items[0].text"assert client._post.await_count == 1mock_sleep.assert_not_called()await client.close()@@ -152,6 +154,7 @@ class TestHandleErrorDispatch:handle_error(_resp_input_too_long("Too many tokens"))assert excinfo.value.code == "INPUT_TOO_LONG"assert excinfo.value.status_code == 400+ assert excinfo.value.param == "items[0].text"assert str(excinfo.value) == "Too many tokens"def test_dispatch_does_not_classify_other_400(self) -> None:diff --git a/packages/sie_sdk/tests/client/test_model_load_failed.py b/packages/sie_sdk/tests/client/test_model_load_failed.pyindex cc7e3c75f..3117178e9 100644--- a/packages/sie_sdk/tests/client/test_model_load_failed.py+++ b/packages/sie_sdk/tests/client/test_model_load_failed.py@@ -54,6 +54,15 @@ def _resp_model_loading() -> MagicMock:return resp+def _resp_gateway_load_failed() -> MagicMock:+ """Build the gateway's SDK-style buffered generation envelope."""+ resp = _resp_load_failed(error_class="MODEL_LOAD_FAILED", message="model failed to load")+ detail = resp.json.return_value.pop("detail")+ resp.json.return_value["error"] = detail+ resp.headers["x-sie-error-code"] = "MODEL_LOAD_FAILED"+ return resp++def _resp_200_encode() -> MagicMock:resp = MagicMock()resp.status_code = 200@@ -156,6 +165,27 @@ class TestSyncModelLoadFailed:mock_sleep.assert_not_called()client.close()+ def test_generate_gateway_envelope_short_circuits(self) -> None:+ """Buffered generation raises before any terminal retry can occur."""+ with (+ patch("sie_sdk.client.sync.httpx.Client") as mock_client,+ patch("sie_sdk.client.sync.time.sleep") as mock_sleep,+ ):+ mock_client.return_value.post = MagicMock(side_effect=[_resp_gateway_load_failed()])+ client = SIEClient("http://localhost:8080")++ with pytest.raises(ModelLoadFailedError) as excinfo:+ client.generate("org/test", "translate this", max_new_tokens=8)++ assert excinfo.value.model == "org/test"+ assert excinfo.value.error_class == "MODEL_LOAD_FAILED"+ assert excinfo.value.permanent is True+ assert excinfo.value.attempts == 1+ assert mock_client.return_value.post.call_count == 1+ assert client.last_retry_count == 0+ mock_sleep.assert_not_called()+ client.close()+# ---------------------------------------------------------------------------# Async clientdiff --git a/packages/sie_sdk/tests/client/test_oom_retry.py b/packages/sie_sdk/tests/client/test_oom_retry.pyindex 13fd2f091..4155be5f5 100644--- a/packages/sie_sdk/tests/client/test_oom_retry.py+++ b/packages/sie_sdk/tests/client/test_oom_retry.py@@ -25,7 +25,9 @@ def _resp_oom(retry_after: str = "0.01") -> MagicMock:resp = MagicMock()resp.status_code = 503resp.headers = {"Retry-After": retry_after, "content-type": "application/json"}- resp.json.return_value = {"detail": {"code": "RESOURCE_EXHAUSTED", "message": "Server resource pressure"}}+ resp.json.return_value = {+ "detail": {"code": "RESOURCE_EXHAUSTED", "message": "Server resource pressure", "param": "model"}+ }return resp@@ -86,6 +88,8 @@ class TestSyncOomRetry:assert excinfo.value.retries == 2assert excinfo.value.code == "RESOURCE_EXHAUSTED"assert excinfo.value.status_code == 503+ assert excinfo.value.param == "model"+ assert excinfo.value.retry_after == 0.01assert mock_client.return_value.post.call_count == 3client.close()@@ -241,7 +245,15 @@ class TestSyncOomRetry:def _aio_oom() -> object:return _AioResponse(503,- json.dumps({"detail": {"code": "RESOURCE_EXHAUSTED", "message": "Server resource pressure"}}).encode(),+ json.dumps(+ {+ "detail": {+ "code": "RESOURCE_EXHAUSTED",+ "message": "Server resource pressure",+ "param": "model",+ }+ }+ ).encode(),{"Retry-After": "0.01", "content-type": "application/json"},)@@ -283,5 +295,7 @@ class TestAsyncOomRetry:await client.encode("bge-m3", {"text": "hi"}, max_oom_retries=2)assert excinfo.value.retries == 2+ assert excinfo.value.param == "model"+ assert excinfo.value.retry_after == 0.01assert client._post.await_count == 3await client.close()diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.pyindex 4ae26ced1..e9cb3deb4 100644--- a/packages/sie_sdk/tests/client/test_sync.py+++ b/packages/sie_sdk/tests/client/test_sync.py@@ -210,9 +210,11 @@ class TestEncode:mock_response.status_code = 200revision = "a" * 64execution_identity = "b" * 64+ execution_binding = "c" * 64mock_response.headers = {"X-SIE-Model-Revision": revision,"X-SIE-Execution-Identity-SHA256": execution_identity,+ "X-SIE-Execution-Binding-SHA256": execution_binding,"X-SIE-Request-ID": "req-encode","X-SIE-Units-Input-Tokens": "2","X-SIE-Units-Pairs": "3",@@ -261,6 +263,7 @@ class TestEncode:},"credits_debited": 19,"execution_identity_sha256": execution_identity,+ "execution_binding_sha256": execution_binding,}assert client.last_model_revision == revisionclient.close()@@ -646,6 +649,7 @@ class TestListModels:"dims": {},"max_sequence_length": 32768,"capabilities": {+ "streaming": False,"grammar": ["json_schema", "regex"],"tools": True,"code": True,@@ -662,6 +666,7 @@ class TestListModels:models = client.list_models()caps: ModelCapabilities = models[0]["capabilities"]+ assert caps["streaming"] is Falseassert caps["grammar"] == ["json_schema", "regex"]assert caps["tools"] is Trueassert caps["code"] is Truediff --git a/packages/sie_sdk/tests/client/test_terminal_msgpack.py b/packages/sie_sdk/tests/client/test_terminal_msgpack.pyindex e74d6d5b8..c9b6b1a43 100644--- a/packages/sie_sdk/tests/client/test_terminal_msgpack.py+++ b/packages/sie_sdk/tests/client/test_terminal_msgpack.py@@ -1,8 +1,10 @@+from typing import Selffrom unittest.mock import AsyncMock, MagicMock, patch+import numpy as npimport pytestfrom msgpack.exceptions import UnpackException-from sie_sdk import RequestError, ServerError, SIEAsyncClient, SIEClient+from sie_sdk import ProvisioningError, RequestError, ServerError, SIEAsyncClient, SIEClientfrom sie_sdk._msgpack import packb as pack_msgpackfrom sie_sdk.client._shared import get_error_detail, handle_error, parse_terminal_msgpack_objectfrom sie_sdk.client.async_ import _AioResponse@@ -29,6 +31,172 @@ def _assert_content_safe_error(error: RequestError, *, expected: str, status_codassert error.request == {"id": request_id}+def _terminal_payload(operation: str) -> dict[str, object]:+ if operation == "encode":+ return {+ "model": "m",+ "items": [{"dense": {"dims": 1, "values": np.array([0.5], dtype=np.float32)}}],+ }+ if operation == "score":+ return {"model": "m", "scores": [{"item_id": "0", "score": 0.5, "rank": 0}]}+ return {"model": "m", "items": [{"entities": []}]}+++def _invoke_sync(client: SIEClient, operation: str) -> object:+ if operation == "encode":+ return client.encode("m", {"text": "input"})+ if operation == "score":+ return client.score("m", "query", ["candidate"])+ return client.extract("m", {"text": "input"}, labels=["entity"])+++async def _invoke_async(client: SIEAsyncClient, operation: str) -> object:+ if operation == "encode":+ return await client.encode("m", {"text": "input"})+ if operation == "score":+ return await client.score("m", "query", ["candidate"])+ return await client.extract("m", {"text": "input"}, labels=["entity"])+++class _AsyncResponseContext:+ def __init__(self, response: _AioResponse) -> None:+ self.status = response.status_code+ self.headers = response.headers+ self._content = response.content++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *_args: object) -> None:+ return None++ async def read(self) -> bytes:+ return self._content++[email protected]("operation", ["encode", "score", "extract"])+def test_sync_terminal_operation_consumes_same_origin_modal_continuation(operation: str) -> None:+ path = f"/v1/{operation}/m?__modal_attempt_token=opaque"+ redirect = MagicMock(status_code=303, content=b"", headers={"Location": path})+ terminal = MagicMock(+ status_code=200,+ content=pack_msgpack(_terminal_payload(operation)),+ headers={"content-type": "application/msgpack"},+ )++ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client_cls.return_value.post.return_value = redirect+ client_cls.return_value.get.return_value = terminal+ client = SIEClient(+ "https://gateway.example.test",+ api_key="sie-secret",+ base_url_headers={"Modal-Key": "edge-secret"},+ )+ try:+ with patch("sie_sdk.client.sync.time.monotonic", return_value=100):+ result = _invoke_sync(client, operation)+ finally:+ client.close()++ assert isinstance(result, dict)+ assert client_cls.call_args.kwargs["headers"]["Authorization"] == "Bearer sie-secret"+ assert "event_hooks" in client_cls.call_args.kwargs+ client_cls.return_value.post.assert_called_once()+ client_cls.return_value.get.assert_called_once_with(+ path,+ headers={"Accept": "application/msgpack"},+ timeout=30,+ )++[email protected]("operation", ["encode", "score", "extract"])+async def test_async_terminal_operation_consumes_same_origin_modal_continuation(operation: str) -> None:+ path = f"/v1/{operation}/m?__modal_attempt_token=opaque"+ redirect = _AioResponse(303, b"", {"Location": path})+ terminal = _AioResponse(+ 200,+ pack_msgpack(_terminal_payload(operation)),+ {"content-type": "application/msgpack"},+ )+ session = MagicMock()+ session.get.return_value = _AsyncResponseContext(terminal)+ session.close = AsyncMock()+ client = SIEAsyncClient(+ "https://gateway.example.test",+ api_key="sie-secret",+ base_url_headers={"Modal-Key": "edge-secret"},+ )+ client._session = session+ client._post = AsyncMock(return_value=redirect) # type: ignore[method-assign]++ try:+ with patch("sie_sdk.client.async_.time.monotonic", return_value=100):+ result = await _invoke_async(client, operation)+ finally:+ await client.close()++ assert isinstance(result, dict)+ client._post.assert_awaited_once() # type: ignore[attr-defined]+ get_call = session.get.call_args+ assert get_call.args == (path,)+ assert client._headers["Authorization"] == "Bearer sie-secret"+ assert get_call.kwargs["headers"]["Accept"] == "application/msgpack"+ assert get_call.kwargs["headers"]["Modal-Key"] == "edge-secret"+ assert get_call.kwargs["allow_redirects"] is False+++def test_sync_terminal_continuation_exhausted_budget_performs_no_get() -> None:+ redirect = MagicMock(+ status_code=303,+ content=b"",+ headers={"Location": "/result?__modal_attempt_token=opaque"},+ )++ with patch("sie_sdk.client.sync.httpx.Client") as client_cls:+ client = SIEClient("https://gateway.example.test")+ try:+ with (+ patch("sie_sdk.client.sync.time.monotonic", return_value=31),+ pytest.raises(ProvisioningError, match="awaiting request result"),+ ):+ client._follow_modal_continuations(+ redirect,+ start_time=0,+ budget_s=30,+ accept="application/msgpack",+ )+ finally:+ client.close()++ client_cls.return_value.get.assert_not_called()+++async def test_async_terminal_continuation_exhausted_budget_performs_no_get() -> None:+ redirect = _AioResponse(303, b"", {"Location": "/result?__modal_attempt_token=opaque"})+ session = MagicMock()+ session.close = AsyncMock()+ client = SIEAsyncClient("https://gateway.example.test")+ client._session = session++ try:+ with (+ patch("sie_sdk.client.async_.time.monotonic", return_value=31),+ pytest.raises(ProvisioningError, match="awaiting request result"),+ ):+ await client._follow_modal_continuations(+ redirect,+ start_time=0,+ budget_s=30,+ accept="application/msgpack",+ )+ finally:+ await client.close()++ session.get.assert_not_called()++@pytest.mark.parametrize(("status_code", "expected_prefix"),[diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpuindex 7325f478b..a6db66a2e 100644--- a/packages/sie_server/Dockerfile.cpu+++ b/packages/sie_server/Dockerfile.cpu@@ -101,8 +101,10 @@ RUN --mount=type=cache,target=/root/.cache/pip \# shared-deps resolver.RUN .venv/bin/python -c "import sie_audio_prep, torch; print(torch.__version__)"-# Register bundle-libs on sys.path. Content is identical across bundles.-RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \+# Register bundle-libs as a site directory so dependency-owned .pth files are+# processed, then move every discovered bundle path ahead of the shared venv so+# bundle versions shadow it. Content is identical across bundles.+RUN echo "import site, sys; _sie_bundle_start = len(sys.path); site.addsitedir('/app/bundle-libs'); sys.path[:] = sys.path[_sie_bundle_start:] + sys.path[:_sie_bundle_start]" \> /app/.venv/lib/python3.12/site-packages/_sie_bundle.pth# .venv cleanup + stdlib trim — runs here so /app/.venv reaches its finaldiff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12index a3eca8e8f..afa7fa797 100644--- a/packages/sie_server/Dockerfile.cuda12+++ b/packages/sie_server/Dockerfile.cuda12@@ -110,12 +110,12 @@ RUN --mount=type=cache,target=/root/.cache/pip \# intentionally not imported here.RUN .venv/bin/python -c "import sie_audio_prep, torch; print(torch.__version__)"-# Register bundle-libs on sys.path via a .pth file executed by site.py at-# interpreter startup. `sys.path.insert(0, ...)` puts bundle-libs at-# position 0 so bundle-specific versions SHADOW shared venv versions-# (required for the transformers5 bundle). Content is identical for every-# bundle, so writing it here keeps the shared venv layer byte-identical.-RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \+# Register bundle-libs as a site directory so dependency-owned .pth files are+# processed at interpreter startup. Then move every discovered bundle path+# ahead of the shared venv so bundle-specific versions SHADOW it (required for+# the transformers5 bundle). Content is identical for every bundle, so writing+# it here keeps the shared venv layer byte-identical.+RUN echo "import site, sys; _sie_bundle_start = len(sys.path); site.addsitedir('/app/bundle-libs'); sys.path[:] = sys.path[_sie_bundle_start:] + sys.path[:_sie_bundle_start]" \> /app/.venv/lib/python3.12/site-packages/_sie_bundle.pth# Conservative venv cleanup — only things known to be runtime-safe. Keep@@ -210,6 +210,8 @@ RUN set -eux; \# smaller CUDA base runtime; SGLang-family bundles need the devel toolkit# because flashinfer/tvm_ffi perform runtime JIT through nvcc on first decode.FROM nvidia/cuda:12.4.1-base-ubuntu22.04 AS runtime-default+# The CTranslate2 bundle uses the CUDA runtime image, not the devel toolchain.+FROM nvidia/cuda:12.4.1-runtime-ubuntu22.04 AS runtime-ctranslate2FROM nvidia/cuda:12.4.1-base-ubuntu22.04 AS runtime-transformers5FROM nvidia/cuda:12.9.1-cudnn-devel-ubuntu22.04 AS runtime-sglangENV CUDA_HOME=/usr/local/cuda \diff --git a/packages/sie_server/Dockerfile.cuda13 b/packages/sie_server/Dockerfile.cuda13index 09f624ca9..e9d8d6b13 100644--- a/packages/sie_server/Dockerfile.cuda13+++ b/packages/sie_server/Dockerfile.cuda13@@ -1,14 +1,12 @@# syntax=docker/dockerfile:1-# SIE Server - CUDA 13 Image (SGLang cu130 bundles)+# SIE Server - CUDA 13 Image (engine-isolated cu130 bundles)# Build from repo root:# docker build -f packages/sie_server/Dockerfile.cuda13 --build-arg BUNDLE=sglang-cu130 -t sie-server:cuda13-sglang-cu130 .#-# WHY A SEPARATE PLATFORM: the sglang-cu130 bundle needs sglang 0.5.13, which pins-# torch==2.11.0 (cu130) + transformers 5.8.x and JIT-compiles cu130 kernels-# (flashinfer / tvm_ffi) through nvcc on first decode — so it requires a CUDA 13-# devel runtime. Keeping it here (platform ``cuda13``) instead of inside-# Dockerfile.cuda12 means a ``cuda13-sglang-cu130`` image is honestly labelled CUDA 13,-# not a CUDA-13 image hiding under a ``cuda12-*`` tag (see #1415).+# WHY A SEPARATE PLATFORM: CUDA 13 engines carry independent exact Torch,+# Transformers, FlashInfer, and native-library closures. Keeping them here+# (platform ``cuda13``) instead of Dockerfile.cuda12 makes image tags honest+# while still sharing the expensive CUDA 13 base layers.## STRUCTURE: mirrors Dockerfile.cuda12's deps→base→builder→runtime stages so the# shared logic (standalone Python, editable installs, bundle-libs .pth shadow,@@ -18,7 +16,7 @@# cu130 bundle), so there is no per-bundle runtime indirection.## DUAL-TORCH CARRY: the shared base venv still installs torch 2.9 (cu129) from-# pyproject, and the sglang-cu130 bundle overlays torch 2.11 (cu130) into bundle-libs+# pyproject, and CUDA 13 bundles overlay torch 2.11 (cu130) into bundle-libs# (~+3 GB). Slimming torch out of sie-server core to drop the carry is a tracked# follow-up (#1415).@@ -50,13 +48,16 @@ ENV DEBIAN_FRONTEND=noninteractive \UV_PYTHON_INSTALL_DIR=/opt/python \PIP_DISABLE_PIP_VERSION_CHECK=1-# Minimal apt footprint: just enough for curl + git; no deadsnakes PPA.+# Minimal apt footprint: curl/git plus the MPI runtime required by+# TensorRT-LLM's Python import; no OpenMPI development headers are needed.RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \--mount=type=cache,target=/var/lib/apt/lists,sharing=locked \apt-get update && apt-get install -y --no-install-recommends \ca-certificates \curl \- git+ git \+ libopenmpi3 \+ openmpi-binARG UV_VERSIONRUN curl -LsSf https://astral.sh/uv/${UV_VERSION}/install.sh | sh \@@ -117,12 +118,12 @@ RUN --mount=type=cache,target=/root/.cache/pip \# Sanity-check shared venv imports.RUN .venv/bin/python -c "import sie_audio_prep, torch; print(torch.__version__)"-# Register bundle-libs on sys.path via a .pth executed by site.py at startup.-# sys.path.insert(0, ...) puts bundle-libs at position 0 so bundle-specific-# versions SHADOW the shared venv (the cu130 torch/transformers/sglang-# overlay). Content is identical for every bundle, so writing it here keeps the-# shared venv layer byte-identical.-RUN echo "import sys; sys.path.insert(0, '/app/bundle-libs')" \+# Register bundle-libs as a site directory so dependency-owned .pth files are+# processed at interpreter startup. Then move every discovered bundle path+# ahead of the shared venv so bundle-specific versions SHADOW it (the cu130+# torch/transformers/engine overlay). Content is identical for every bundle, so+# writing it here keeps the shared venv layer byte-identical.+RUN echo "import site, sys; _sie_bundle_start = len(sys.path); site.addsitedir('/app/bundle-libs'); sys.path[:] = sys.path[_sie_bundle_start:] + sys.path[:_sie_bundle_start]" \> /app/.venv/lib/python3.12/site-packages/_sie_bundle.pth# Conservative venv cleanup — only runtime-safe removals. Keep torch/include@@ -155,7 +156,7 @@ RUN .venv/bin/python -m sie_server.cli resolve-deps \&& cat /tmp/bundle-requirements.txt# cu130 bundle deps go into a separate site-packages tree (``bundle-libs``,-# prepended to sys.path via the .pth above). The sglang-cu130 bundle needs torch 2.11+# prepended to sys.path via the .pth above). CUDA 13 engines need torch 2.11# from the cu130 PyTorch index, where the only ``2.11.0`` is the ``+cu130``# local-version wheel; pip's multi-index resolution does not reliably prefer it# over PyPI's default-CUDA build, so cuda13 bundles resolve with ``uv`` and@@ -164,7 +165,7 @@ RUN .venv/bin/python -m sie_server.cli resolve-deps \# cu130-index resolution was validated with sglang 0.5.13, torch 2.11, and a# cu130 runtime in a fresh GPU environment.#-# COVERAGE NOTE: the cuda13 image CI smoke (.github/workflows/sglang-cu130-image.yml)+# COVERAGE NOTE: the CUDA 13 image CI callers# builds this image and asserts on CPU that the bundle-libs cu130 overlay# SHADOWS the base venv (import torch -> 2.11+cu130, transformers 5.x). It does# NOT exercise GPU init: the cu12 base venv + cu130 bundle-libs both expose the@@ -220,6 +221,8 @@ ENV DEBIAN_FRONTEND=noninteractive# libnuma1: required by sgl_kernel; import fails with a misleading SM-arch error# without it.# libgomp1: torch OpenMP runtime.+# libopenmpi3/openmpi-bin: TensorRT-LLM imports MPI at runtime; headers are not+# required by the qualified wheel closure.# libspatialindex-c6 / libgl1 / libglib2.0-0 / libice6 / libsm6 / libx11-6 /# libxcb1 / libxext6: docling/opencv dlopen chain (kept symmetric with the# cuda12 runtime so the same model bundle deps import cleanly).@@ -235,9 +238,11 @@ RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \libgomp1 \libice6 \libnuma1 \+ libopenmpi3 \libsm6 \libspatialindex-c6 \ninja-build \+ openmpi-bin \libx11-6 \libxcb1 \libxext6@@ -278,7 +283,8 @@ LABEL org.opencontainers.image.title="SIE Server" \org.opencontainers.image.description="Search Inference Engine - ${BUNDLE} bundle (CUDA 13)" \sie.bundle="${BUNDLE}"-ENV PATH="/app/.venv/bin:$PATH" \+# ``uv --target`` writes engine entrypoints beside the package overlay.+ENV PATH="/app/bundle-libs/bin:/app/.venv/bin:$PATH" \PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \HF_HOME=/app/.cache/huggingface \diff --git a/packages/sie_server/bundles/ctranslate2.yaml b/packages/sie_server/bundles/ctranslate2.yamlnew file mode 100644index 000000000..5bb3d9237--- /dev/null+++ b/packages/sie_server/bundles/ctranslate2.yaml@@ -0,0 +1,6 @@+name: ctranslate2+priority: 19+adapters:+- sie_server.adapters.ctranslate2.generation+deps:+ ctranslate2: '==4.8.1'diff --git a/packages/sie_server/bundles/tensorrt-llm.yaml b/packages/sie_server/bundles/tensorrt-llm.yamlnew file mode 100644index 000000000..3d6f4dff9--- /dev/null+++ b/packages/sie_server/bundles/tensorrt-llm.yaml@@ -0,0 +1,37 @@+name: tensorrt-llm+priority: 20+default: false+# Reusable direct-HF encoder-decoder runtime. This is a CUDA 13 engine lane,+# not a checkpoint-specific bundle; compatible T5/BART/mBART-family profiles+# opt in through the generic adapter module below.+platform: cuda13+adapters:+- sie_server.adapters.tensorrt_llm.generation+deps:+ # Exact prerelease qualified from tag commit+ # 1cef02e901be43081b1ba6d4981e94ed3bd9c1e8. Compatibility overlays verify+ # the complete rc24 source files they patch and refuse any other build.+ tensorrt-llm: '==1.3.0rc24'+ # rc24's direct-HF T5 closure. Torch resolves to the +cu130 wheel through+ # Dockerfile.cuda13's explicit PyTorch index.+ torch: '==2.11.0'+ transformers: '==5.5.4'+ flashinfer-python: '==0.6.16'+ triton: '==3.6.0'+ nvidia-cutlass-dsl: '==4.5.0'+ nvidia-cuda-tileiras: '==13.1.80'+ nvidia-matmul-heuristics: '==0.1.0.27'+ # cuda-python 13.3.1 permits cuda-pathfinder~=1.1, while cuda-core and+ # cuda-bindings only require >=1.4.2. Pin the import-proven rc24 closure so+ # a newer transitive release cannot silently change the engine image.+ cuda-pathfinder: '==1.7.0'+ # rc24 permits an NCCL range; lock the import-proven cu13 build so PyPI and+ # the cu130 indexes cannot choose a different ABI-compatible-looking wheel.+ nvidia-nccl-cu13: '==2.28.9'+ flash-attn-4: '==4.0.0b11'+ torch-c-dlpack-ext: '==0.1.3'+ xgrammar: '==0.1.32'+ apache-tvm-ffi: '==0.1.6'+ # The published rc24 closure leaves mpmath open; a newer resolution breaks+ # native import. 1.3.0 is the exact import-proven value.+ mpmath: '==1.3.0'diff --git a/packages/sie_server/models/google__madlad400-3b-mt.yaml b/packages/sie_server/models/google__madlad400-3b-mt.yamlnew file mode 100644index 000000000..9ab08c330--- /dev/null+++ b/packages/sie_server/models/google__madlad400-3b-mt.yaml@@ -0,0 +1,42 @@+sie_id: "google/madlad400-3b-mt"+hf_id: "google/madlad400-3b-mt"+hf_revision: fa184c675da0b5c9e1c8694fccd4e12e2d422094+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode: null+ score: null+ extract: null+ generate:+ context_length: 512+ max_output_tokens: 512+ capabilities:+ grammar: []+ streaming: true+ tools: false+ chat_template_kwargs: {}+max_sequence_length: 512+profiles:+ default:+ max_batch_tokens: 4096+ kv_budget_tokens: 4096+ compute_precision: float32+ adapter_path: sie_server.adapters.ctranslate2.generation:CTranslate2GenerationAdapter+ adapter_options:+ loadtime:+ serving_artifact:+ format: ctranslate2+ repo_id: superlinked/madlad400-3b-mt-ctranslate2-float32+ revision: 2cac811471ffb01ea6502ab4d317d5a7e9cb6f7d+ manifest_path: sie-serving-artifact.json+ manifest_sha256: 7583a4fbe2e51551dc61644983b305d22e3c54ec9e3c553d0030b68e70615768+ compute_type: float32+ native_batch_max_size: 8+ native_batch_max_tokens: 4096+ runtime:+ first_chunk_timeout_s: 180+ inter_chunk_timeout_s: 10+ overall_timeout_s: 600diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex e58e197e0..e9e8ddbad 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.7.2"+ "version": "0.7.3"},"paths": {"/healthz": {@@ -1428,6 +1428,11 @@},"ModelCapabilities": {"properties": {+ "streaming": {+ "type": "boolean",+ "title": "Streaming",+ "default": true+ },"grammar": {"items": {"type": "string"@@ -2985,6 +2990,34 @@"description": "Client-safe error message","title": "Message","type": "string"+ },+ "param": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Exact unsupported request field, when applicable",+ "title": "Param"+ },+ "retry_after_s": {+ "anyOf": [+ {+ "maximum": 60,+ "minimum": 1,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null for other terminal errors",+ "title": "Retry After S"}},"required": [diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex aa1eeea61..dd64c0b17 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.7.2"+version = "0.7.3"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/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex 0aaaf56db..035648889 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -14,10 +14,13 @@ terminal chunk carrying ``finish_reason`` and ``usage``.from __future__ import annotations+import asyncioimport gcimport logging+import sysfrom abc import abstractmethodfrom collections.abc import AsyncIterator, Mapping+from contextvars import ContextVarfrom dataclasses import dataclass, replacefrom typing import Any, ClassVar, Literal, cast@@ -50,6 +53,326 @@ _REASONING_BOUNDARIES: dict[ReasoningFormat, tuple[str, str]] = {FinishReason = Literal["stop", "length", "cancelled", "error", "tool_calls"]+class GenerationError(RuntimeError):+ """Base for adapter-declared generation failures with stable semantics."""++ code: ClassVar[str] = "inference_error"+ param: str | None = None+++class GenerationUnsupportedFieldError(GenerationError):+ """A request parameter is not supported by the active generation backend."""++ code = "unsupported_field"++ def __init__(self, param: str, message: str | None = None) -> None:+ self.param = param+ super().__init__(message or f"'{param}' is not supported by this generation backend")+++class GenerationInvalidRequestError(GenerationError):+ """An adapter-specific request relationship is invalid."""++ code = "invalid_request"++ def __init__(self, param: str, message: str) -> None:+ self.param = param+ super().__init__(message)+++class GenerationInputTooLongError(GenerationError):+ """The rendered input exceeds an adapter's qualified token ceiling."""++ code = "INPUT_TOO_LONG"++ def __init__(self, message: str, *, param: str = "prompt") -> None:+ self.param = param+ super().__init__(message)+++class GenerationCapacityError(GenerationError):+ """The generation backend is temporarily at bounded capacity."""++ code = "RESOURCE_EXHAUSTED"+++class GenerationDrainingError(GenerationCapacityError):+ """The generation backend is draining and cannot accept new work."""++ code = "MODEL_LOADING"+++_CLIENT_SAFE_GENERATION_ERROR_MESSAGES = {+ "inference_error": "internal error during generation",+ "grammar_compile_failed": "internal error compiling grammar",+}+_CLIENT_SAFE_GENERATION_ERROR_CODES = frozenset(+ {+ "inference_error",+ "grammar_compile_failed",+ "INPUT_TOO_LONG",+ "MODEL_LOADING",+ "MODEL_OUTPUT_PARSE_ERROR",+ "RESOURCE_EXHAUSTED",+ "COLD_START_RATE_LIMITED",+ "LORA_LOADING",+ "PAYLOAD_TOO_LARGE",+ "cancelled",+ "context_exceeded",+ "empty_model_output",+ "grammar_invalid",+ "invalid_request",+ "parallel_tool_calls_violated",+ "rate_limit_exceeded",+ "tool_call_parse_error",+ "transport_failure",+ "unsupported_field",+ }+)+_CLIENT_PASSTHROUGH_GENERATION_ERROR_CODES = frozenset(+ {+ "INPUT_TOO_LONG",+ "MODEL_LOADING",+ "MODEL_OUTPUT_PARSE_ERROR",+ "RESOURCE_EXHAUSTED",+ "empty_model_output",+ "grammar_invalid",+ "invalid_request",+ "parallel_tool_calls_violated",+ "tool_call_parse_error",+ "unsupported_field",+ }+)+_GENERIC_UPSTREAM_GENERATION_ERROR_MESSAGE = "generation terminated with an upstream error"+_CLIENT_SAFE_GENERATION_PARAMS = frozenset(+ {+ "prompt",+ "max_new_tokens",+ "n",+ "best_of",+ "lora_adapter",+ "temperature",+ "top_p",+ "stop",+ "frequency_penalty",+ "presence_penalty",+ "top_k",+ "repetition_penalty",+ "min_new_tokens",+ "grammar",+ "seed",+ "logit_bias",+ "logprobs",+ "top_logprobs",+ "images",+ "stream",+ }+)+_CLIENT_REFUSAL_ERROR_TYPES = (+ GenerationUnsupportedFieldError,+ GenerationInvalidRequestError,+ GenerationInputTooLongError,+)+_INTERNAL_TO_PUBLIC_GENERATION_PARAMS = {"lora_path": "lora_adapter"}+++def client_safe_generation_error_code(error_code: str | None) -> str:+ """Return the closed public discriminator for an adapter terminal error."""+ code = error_code or "inference_error"+ return code if code in _CLIENT_SAFE_GENERATION_ERROR_CODES else "inference_error"+++def client_safe_generation_error_message(error_code: str | None, error_message: str | None) -> str:+ """Return the public message for an adapter-yielded terminal error.++ Adapter terminal chunks are an untrusted backend boundary just like raised+ exceptions. Generic runtime/grammar-internal codes therefore use stable+ public text, while only explicitly approved client/model codes retain+ their actionable message. Unknown future adapter codes fail closed rather+ than making their backend-controlled message public. A terminal error+ without a code is the generic ``inference_error`` fallback used by every+ public generation surface.+ """+ code = error_code or "inference_error"+ if safe_message := _CLIENT_SAFE_GENERATION_ERROR_MESSAGES.get(code):+ return safe_message+ if code in _CLIENT_PASSTHROUGH_GENERATION_ERROR_CODES and error_message:+ return error_message+ return _GENERIC_UPSTREAM_GENERATION_ERROR_MESSAGE+++def client_safe_generation_error_param(error: GenerationError) -> str | None:+ """Return a bounded public parameter for an adapter-raised refusal.++ A generic/future ``GenerationError`` may set ``param`` arbitrarily, so the+ parameter is public only for concrete client-refusal types and the finite+ generation parameter contract. New types or fields require an explicit+ contract update and regression before they can cross this boundary.+ """+ if type(error) not in _CLIENT_REFUSAL_ERROR_TYPES:+ return None+ raw_param = error.param+ if raw_param is None:+ return None+ param = _INTERNAL_TO_PUBLIC_GENERATION_PARAMS.get(raw_param, raw_param)+ return param if param in _CLIENT_SAFE_GENERATION_PARAMS else None+++def _freeze_preflight_value(value: Any) -> Any:+ """Return a deeply immutable comparison snapshot for generation kwargs."""+ if isinstance(value, Mapping):+ return tuple(sorted((key, _freeze_preflight_value(item)) for key, item in value.items()))+ if isinstance(value, list | tuple):+ return tuple(_freeze_preflight_value(item) for item in value)+ if isinstance(value, set | frozenset):+ return frozenset(_freeze_preflight_value(item) for item in value)+ return value+++class GenerationPreflightResult:+ """Opaque, request-scoped adapter preflight evidence.++ The result is carried by the caller into :meth:`generate_with_preflight`+ and may be consumed exactly once by the adapter that produced it, for an+ exact deeply-immutable parameter snapshot. It is never stored on the+ adapter or keyed by prompt/model text, so concurrent requests cannot share+ evidence accidentally.+ """++ __slots__ = ("_adapter", "_consumed", "_parameters", "_payload")++ def __init__(self, adapter: object, parameters: Mapping[str, Any], payload: Any) -> None:+ self._adapter: object | None = adapter+ self._parameters: Any | None = _freeze_preflight_value(parameters)+ self._payload: Any | None = payload+ self._consumed = False++ def _consume(self, adapter: object, parameters: Mapping[str, Any]) -> Any | None:+ matches = (+ not self._consumed and self._adapter is adapter and self._parameters == _freeze_preflight_value(parameters)+ )+ payload = self._payload if matches else None+ self.discard()+ return payload++ def discard(self) -> None:+ """Erase request-owned references and make the result unusable."""+ self._adapter = None+ self._parameters = None+ self._payload = None+ self._consumed = True+++_ACTIVE_GENERATION_PREFLIGHT: ContextVar[GenerationPreflightResult | None] = ContextVar(+ "active_generation_preflight",+ default=None,+)+++def consume_generation_preflight(adapter: object, parameters: Mapping[str, Any]) -> Any | None:+ """Consume exact preflight evidence bound by ``generate_with_preflight``."""+ result = _ACTIVE_GENERATION_PREFLIGHT.get()+ return None if result is None else result._consume(adapter, parameters)+++class _PreflightBoundGenerationIterator(AsyncIterator["GenerationChunk"]):+ """Own one preflight result from binding through iterator teardown.++ A plain nested async generator cannot run its ``finally`` block when it is+ closed before its first ``__anext__``. This explicit owner discards the+ evidence from ``aclose()`` even in that unstarted state. The state lock+ also serializes first-start and close, while the queue remains free to run+ successive ``__anext__`` calls in distinct child tasks.+ """++ def __init__(+ self,+ adapter: Any,+ parameters: Mapping[str, Any],+ preflight: GenerationPreflightResult | None,+ ) -> None:+ self._adapter: Any | None = adapter+ self._parameters: dict[str, Any] | None = dict(parameters)+ self._preflight = preflight+ self._chunks: AsyncIterator[GenerationChunk] | None = None+ self._terminal_outcome_selected = False+ self._closed = False+ self._exhausted = False+ self._state_lock = asyncio.Lock()++ def __aiter__(self) -> _PreflightBoundGenerationIterator:+ return self++ async def __anext__(self) -> GenerationChunk:+ async with self._state_lock:+ if self._closed or self._exhausted:+ raise StopAsyncIteration++ if self._chunks is None:+ adapter = self._adapter+ parameters = self._parameters+ if adapter is None or parameters is None:+ raise StopAsyncIteration+ try:+ self._chunks = adapter.generate(**dict(parameters))+ except BaseException:+ await self._close_locked()+ raise++ token = _ACTIVE_GENERATION_PREFLIGHT.set(self._preflight)+ exhausted = False+ try:+ try:+ chunk = await self._chunks.__anext__()+ except StopAsyncIteration:+ exhausted = True+ except BaseException:+ await self._close_locked()+ raise+ finally:+ _ACTIVE_GENERATION_PREFLIGHT.reset(token)++ if exhausted:+ # The effective iterator's caller owns final closure. Defer+ # upstream ``aclose`` until that outer finally block so a+ # cleanup failure remains authoritative after clean+ # exhaustion instead of being misclassified as an inference+ # error from ``__anext__``.+ self._exhausted = True+ self._discard_owned_references()+ raise StopAsyncIteration+ if chunk.done:+ self._terminal_outcome_selected = True+ return chunk++ async def aclose(self) -> None:+ async with self._state_lock:+ await self._close_locked()++ async def _close_locked(self) -> None:+ if self._closed:+ return+ self._closed = True+ chunks = self._chunks+ self._chunks = None+ outcome_selected = self._terminal_outcome_selected+ self._discard_owned_references()+ if chunks is not None:+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=outcome_selected,+ context="preflight-bound adapter iterator",+ )++ def _discard_owned_references(self) -> None:+ preflight = self._preflight+ self._preflight = None+ self._adapter = None+ self._parameters = None+ if preflight is not None:+ preflight.discard()++@dataclass(frozen=True, slots=True)class ToolCallDelta:"""One streaming-shape OpenAI tool-call delta.@@ -259,6 +582,48 @@ def _candidates_have_visible_text(candidates: tuple[dict[str, Any], ...] | None)return any(isinstance(text := candidate.get("text"), str) and text.strip() for candidate in candidates)+async def aclose_with_error_precedence(+ resource: Any,+ *,+ outcome_selected: bool,+ context: str,+ timeout_s: float | None = None,+) -> None:+ """Close an async resource without replacing a primary outcome.++ ``finally: await resource.aclose()`` has a subtle failure mode: a cleanup+ exception replaces an exception already propagating through the+ ``finally`` block. That is especially harmful for ``CancelledError`` and+ ``GeneratorExit`` because an ordinary cleanup ``RuntimeError`` can then be+ translated into a successful/in-band response. Preserve the in-flight+ exception (or an already-selected public terminal outcome) and log the+ secondary close failure instead. With no primary exception or selected+ outcome, the close failure remains authoritative and is re-raised.+ """+ aclose = getattr(resource, "aclose", None)+ if aclose is None:+ return++ primary = sys.exception()+ try:+ close_awaitable = aclose()+ if timeout_s is None:+ await close_awaitable+ else:+ await asyncio.wait_for(close_awaitable, timeout=timeout_s)+ except BaseException as cleanup_error:+ if isinstance(cleanup_error, asyncio.CancelledError):+ raise+ if primary is not None or outcome_selected:+ logger.warning(+ "%s cleanup failed after a primary exception or selected outcome; preserving the primary",+ context,+ exc_info=True,+ )+ return+ raise++async def suppress_thinking_blocks(chunks: AsyncIterator[GenerationChunk],*,@@ -295,6 +660,7 @@ async def suppress_thinking_blocks(emitted_meaningful_text = Falseemitted_tool_call = Falsehid_reasoning = False+ terminal_outcome_selected = Falsetry:async for chunk in chunks:rewritten_candidates = chunk.candidates@@ -369,11 +735,15 @@ async def suppress_thinking_blocks():continue+ if rewritten.done:+ terminal_outcome_selected = Trueyield rewrittenfinally:- aclose = getattr(chunks, "aclose", None)- if aclose is not None:- await aclose()+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal_outcome_selected,+ context="thinking-suppression upstream iterator",+ )def thinking_blocks_must_be_hidden(config: Any) -> bool:@@ -455,26 +825,36 @@ async def collect_generation(completion_tokens = 0error_code: str | None = Noneerror_message: str | None = None- async for chunk in chunks:- if chunk.text_delta:- parts.append(chunk.text_delta)- if chunk.done:- finish_reason = chunk.finish_reason or "stop"- if chunk.prompt_tokens is not None:- prompt_tokens = chunk.prompt_tokens- if chunk.completion_tokens is not None:- completion_tokens = chunk.completion_tokens- error_code = chunk.error_code- error_message = chunk.error_message- break- return GenerationResult(- text="".join(parts),- finish_reason=cast("Any", finish_reason),- prompt_tokens=prompt_tokens,- completion_tokens=completion_tokens,- error_code=error_code,- error_message=error_message,- )+ result_selected = False+ try:+ async for chunk in chunks:+ if chunk.text_delta:+ parts.append(chunk.text_delta)+ if chunk.done:+ finish_reason = chunk.finish_reason or "stop"+ if chunk.prompt_tokens is not None:+ prompt_tokens = chunk.prompt_tokens+ if chunk.completion_tokens is not None:+ completion_tokens = chunk.completion_tokens+ error_code = chunk.error_code+ error_message = chunk.error_message+ break+ result = GenerationResult(+ text="".join(parts),+ finish_reason=cast("Any", finish_reason),+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens,+ error_code=error_code,+ error_message=error_message,+ )+ result_selected = True+ return result+ finally:+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=result_selected,+ context="buffered generation input iterator",+ )class GenerationAdapter(ModelAdapter):@@ -488,6 +868,14 @@ class GenerationAdapter(ModelAdapter):"""spec: ClassVar[AdapterSpec]+ # Decoder-only adapters share one prompt-plus-output context envelope.+ # Encoder-decoder adapters with separately bounded axes must opt in.+ context_length_accounting: ClassVar[Literal["shared", "independent"]] = "shared"+ # The worker-side context guard tokenizes the exact prompt string before+ # dispatch. The default preserves the currently qualified worker behavior;+ # adapters whose engine tokenizer adds boundary tokens must opt in so+ # context validation and terminal usage share one rule.+ prompt_tokenization_add_special_tokens: ClassVar[bool] = Falsedef __init_subclass__(cls, **kwargs: Any) -> None:super().__init_subclass__(**kwargs)@@ -520,6 +908,14 @@ class GenerationAdapter(ModelAdapter):# -- Lifecycle -----------------------------------------------------------+ async def drain_generation(self) -> None:+ """Stop admission and drain adapter-owned generation work.++ The registry awaits this hook before synchronous :meth:`unload`.+ In-process adapters without their own scheduler have nothing to drain.+ Implementations must be safe to call more than once.+ """+def unload(self) -> None:"""Unload model state. Iterates ``spec.unload_fields`` and clears each."""for attr in self.spec.unload_fields:@@ -530,6 +926,28 @@ class GenerationAdapter(ModelAdapter):# -- Contract ------------------------------------------------------------+ def preflight_generate(+ self,+ parameters: Mapping[str, Any],+ *,+ stream: bool,+ ) -> GenerationPreflightResult | None:+ """Validate one resolved request before admission or engine dispatch.++ ``parameters`` is the exact keyword mapping that will be passed to+ :meth:`generate`; ``stream`` is the public response mode even when the+ backend does not need it as a generation kwarg. Adapters should raise+ one of the typed generation exceptions above for expected refusals.+ """++ def generate_with_preflight(+ self,+ parameters: Mapping[str, Any],+ preflight: GenerationPreflightResult | None,+ ) -> AsyncIterator[GenerationChunk]:+ """Drive one request with its opaque, consume-once preflight result."""+ return _PreflightBoundGenerationIterator(self, parameters, preflight)+@abstractmethoddef generate(self,diff --git a/packages/sie_server/src/sie_server/adapters/ctranslate2/__init__.py b/packages/sie_server/src/sie_server/adapters/ctranslate2/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/ctranslate2/generation.py b/packages/sie_server/src/sie_server/adapters/ctranslate2/generation.pynew file mode 100644index 000000000..a5aa4f568--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/ctranslate2/generation.py@@ -0,0 +1,742 @@+"""In-process CTranslate2 sequence-to-sequence generation adapter."""++from __future__ import annotations++import asyncio+import importlib+import logging+import math+import threading+from collections import deque+from collections.abc import AsyncIterator, Mapping, Sequence+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Literal++from transformers import AutoTokenizer++from sie_server.adapters._generation_base import (+ GenerationAdapter,+ GenerationCapacityError,+ GenerationChunk,+ GenerationDrainingError,+ GenerationInputTooLongError,+ GenerationInvalidRequestError,+ GenerationPreflightResult,+ GenerationUnsupportedFieldError,+ consume_generation_preflight,+)+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import ImageInput++CTranslate2ComputeType = Literal[+ "default",+ "auto",+ "int8",+ "int8_float32",+ "int8_float16",+ "int8_bfloat16",+ "int16",+ "float16",+ "bfloat16",+ "float32",+]++_COMPUTE_TYPES = frozenset(+ {+ "default",+ "auto",+ "int8",+ "int8_float32",+ "int8_float16",+ "int8_bfloat16",+ "int16",+ "float16",+ "bfloat16",+ "float32",+ }+)+_AUTOMATIC_COMPUTE_TYPES = frozenset({"default", "auto"})+_EXPECTED_CTRANSLATE2_VERSION = "4.8.1"++logger = logging.getLogger(__name__)+++def _positive_int(name: str, value: int) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:+ raise ValueError(f"{name} must be an integer > 0")+ return value+++def _non_negative_float(name: str, value: float) -> float:+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise ValueError(f"{name} must be a finite number >= 0")+ result = float(value)+ if not math.isfinite(result) or result < 0:+ raise ValueError(f"{name} must be a finite number >= 0")+ return result+++def _parse_device(device: str) -> tuple[str, int]:+ if device == "cpu":+ return "cpu", 0+ if device == "cuda":+ return "cuda", 0+ if device.startswith("cuda:"):+ raw_index = device.removeprefix("cuda:")+ if raw_index.isdigit():+ return "cuda", int(raw_index)+ raise ValueError("CTranslate2 requires device='cpu', 'cuda', or 'cuda:<index>'")+++@dataclass(frozen=True, slots=True)+class _DecodeOptions:+ max_new_tokens: int+ min_new_tokens: int+ repetition_penalty: float+ seed: int+++@dataclass(frozen=True, slots=True)+class _PreparedGeneration:+ source_tokens: tuple[str, ...]+ prompt_tokens: int+ options: _DecodeOptions+++@dataclass(slots=True)+class _Request:+ prepared: _PreparedGeneration+ loop: asyncio.AbstractEventLoop+ enqueued_at: float+ wake: asyncio.Event = field(default_factory=asyncio.Event)+ cancelled: threading.Event = field(default_factory=threading.Event)+ final_text: str | None = None+ completion_tokens: int | None = None+ finish_reason: Literal["stop", "length"] | None = None+ error: BaseException | None = None+ done: bool = False++ @property+ def cost(self) -> int:+ return len(self.prepared.source_tokens)++ def complete(self, text: str, completion_tokens: int, finish_reason: Literal["stop", "length"]) -> None:+ if self.cancelled.is_set() or self.done:+ return+ self.final_text = text+ self.completion_tokens = completion_tokens+ self.finish_reason = finish_reason+ self.done = True+ self.wake.set()++ def fail(self, error: BaseException) -> None:+ if self.cancelled.is_set() or self.done:+ return+ self.error = error+ self.done = True+ self.wake.set()+++class CTranslate2GenerationAdapter(GenerationAdapter):+ """Serve a locally converted sequence-to-sequence artifact in process."""++ spec = AdapterSpec(+ inputs=("text",),+ outputs=("tokens",),+ unload_fields=("_translator", "_tokenizer", "_ctranslate2"),+ )+ requires_main_thread = False+ context_length_accounting = "independent"+ prompt_tokenization_add_special_tokens = True++ def __init__(+ self,+ *,+ artifact_path: str | Path,+ ct2_compute_type: CTranslate2ComputeType,+ max_seq_length: int = 4096,+ compute_precision: ComputePrecision = "float16",+ native_batch_max_size: int = 8,+ native_batch_max_tokens: int = 8192,+ native_batch_wait_ms: float = 2.0,+ max_pending_requests: int = 64,+ ) -> None:+ artifact = Path(artifact_path)+ if not str(artifact_path):+ raise ValueError("artifact_path must be a non-empty local path")+ if not isinstance(ct2_compute_type, str) or ct2_compute_type not in _COMPUTE_TYPES:+ choices = ", ".join(sorted(_COMPUTE_TYPES))+ raise ValueError(f"ct2_compute_type must be one of: {choices}")+ self._artifact_path = artifact+ self._ct2_compute_type = ct2_compute_type+ self._max_seq_length = _positive_int("max_seq_length", max_seq_length)+ self._compute_precision = compute_precision+ self._native_batch_max_size = _positive_int("native_batch_max_size", native_batch_max_size)+ self._native_batch_max_tokens = _positive_int("native_batch_max_tokens", native_batch_max_tokens)+ self._native_batch_wait_s = _non_negative_float("native_batch_wait_ms", native_batch_wait_ms) / 1000+ self._max_pending_requests = _positive_int("max_pending_requests", max_pending_requests)++ self._translator: Any | None = None+ self._tokenizer: Any | None = None+ self._ctranslate2: Any | None = None+ self._device: str | None = None+ self._owner_loop: asyncio.AbstractEventLoop | None = None+ self._pending: deque[_Request] = deque()+ self._pending_wake: asyncio.Event | None = None+ self._scheduler_task: asyncio.Task[None] | None = None+ self._active_batch: tuple[_Request, ...] = ()+ self._draining = False+ self._active_batches = 0+ self._idle: asyncio.Event | None = None+ self._force_stop = threading.Event()+ self._scheduler_stopped = threading.Event()+ self._scheduler_stopped.set()++ def load(self, device: str) -> None:+ if not self._scheduler_stopped.is_set():+ raise RuntimeError("CTranslate2 generation scheduler is still stopping")+ device_type, device_index = _parse_device(device)+ if not self._artifact_path.is_dir():+ raise ValueError(f"artifact_path is not a local directory: {self._artifact_path}")++ ctranslate2 = importlib.import_module("ctranslate2")+ version = getattr(ctranslate2, "__version__", None)+ if version != _EXPECTED_CTRANSLATE2_VERSION:+ raise RuntimeError(f"CTranslate2 {_EXPECTED_CTRANSLATE2_VERSION} is required, found {version or 'unknown'}")+ supported = set(ctranslate2.get_supported_compute_types(device_type, device_index))+ if self._ct2_compute_type not in _AUTOMATIC_COMPUTE_TYPES and self._ct2_compute_type not in supported:+ available = ", ".join(sorted(supported)) or "none"+ raise ValueError(+ f"ct2_compute_type={self._ct2_compute_type!r} is not supported on {device}; supported: {available}"+ )++ try:+ tokenizer = AutoTokenizer.from_pretrained(+ str(self._artifact_path),+ local_files_only=True,+ trust_remote_code=False,+ )+ translator = ctranslate2.Translator(+ str(self._artifact_path),+ device=device_type,+ device_index=device_index,+ compute_type=self._ct2_compute_type,+ inter_threads=1,+ max_queued_batches=1,+ )+ except BaseException:+ self._translator = None+ self._tokenizer = None+ self._ctranslate2 = None+ self._device = None+ raise++ self._ctranslate2 = ctranslate2+ self._tokenizer = tokenizer+ self._translator = translator+ self._device = device+ self._force_stop.clear()+ self._draining = False++ def _check_loaded(self) -> tuple[Any, Any, Any]:+ if self._translator is None or self._tokenizer is None or self._ctranslate2 is None:+ raise RuntimeError(ERR_NOT_LOADED)+ return self._translator, self._tokenizer, self._ctranslate2++ def _tokenize_prompt(self, prompt: str) -> tuple[tuple[str, ...], int]:+ _, tokenizer, _ = self._check_loaded()+ try:+ token_ids = tokenizer.encode(prompt, add_special_tokens=self.prompt_tokenization_add_special_tokens)+ source_tokens = tokenizer.convert_ids_to_tokens(token_ids)+ except Exception as exc:+ raise RuntimeError("CTranslate2 prompt tokenization failed") from exc+ if (+ not isinstance(token_ids, list)+ or not token_ids+ or any(+ isinstance(token_id, bool) or not isinstance(token_id, int) or token_id < 0 for token_id in token_ids+ )+ or not isinstance(source_tokens, list)+ or len(source_tokens) != len(token_ids)+ or any(not isinstance(token, str) or not token for token in source_tokens)+ ):+ raise RuntimeError("CTranslate2 prompt tokenization returned invalid tokens")+ return tuple(source_tokens), len(token_ids)++ def _decode_tokens(self, tokens: Sequence[str]) -> str:+ _, tokenizer, _ = self._check_loaded()+ try:+ token_ids = tokenizer.convert_tokens_to_ids(list(tokens))+ text = tokenizer.decode(+ token_ids,+ skip_special_tokens=True,+ )+ except Exception as exc:+ raise RuntimeError("CTranslate2 output detokenization failed") from exc+ if (+ not isinstance(token_ids, list)+ or len(token_ids) != len(tokens)+ or any(+ isinstance(token_id, bool) or not isinstance(token_id, int) or token_id < 0 for token_id in token_ids+ )+ or not isinstance(text, str)+ ):+ raise RuntimeError("CTranslate2 output detokenization returned invalid data")+ return text++ def _end_tokens(self) -> frozenset[str]:+ _, tokenizer, _ = self._check_loaded()+ token_ids = getattr(tokenizer, "eos_token_id", None)+ if isinstance(token_ids, int) and not isinstance(token_ids, bool):+ token_ids = [token_ids]+ if (+ not isinstance(token_ids, list)+ or not token_ids+ or any(+ isinstance(token_id, bool) or not isinstance(token_id, int) or token_id < 0 for token_id in token_ids+ )+ ):+ raise RuntimeError("CTranslate2 tokenizer has invalid end token IDs")+ try:+ tokens = tokenizer.convert_ids_to_tokens(token_ids)+ except Exception as exc:+ raise RuntimeError("CTranslate2 end token conversion failed") from exc+ if not isinstance(tokens, list):+ raise RuntimeError("CTranslate2 tokenizer returned invalid end tokens")+ end_tokens = [token for token in tokens if isinstance(token, str) and token]+ if len(end_tokens) != len(token_ids) or len(end_tokens) != len(tokens):+ raise RuntimeError("CTranslate2 tokenizer returned invalid end tokens")+ return frozenset(end_tokens)++ @staticmethod+ def _normalize_generate_parameters(parameters: Mapping[str, Any]) -> dict[str, Any]:+ normalized: dict[str, Any] = {+ "temperature": 0.0,+ "top_p": 1.0,+ "stop": None,+ "frequency_penalty": None,+ "presence_penalty": None,+ "top_k": None,+ "repetition_penalty": None,+ "min_new_tokens": None,+ "grammar": None,+ "seed": None,+ "logit_bias": None,+ "logprobs": False,+ "top_logprobs": None,+ "n": None,+ "best_of": None,+ "stream": False,+ "lora_path": None,+ "images": None,+ }+ normalized.update(parameters)+ return normalized++ def _prepare_generation(self, parameters: Mapping[str, Any]) -> _PreparedGeneration:+ prompt = parameters.get("prompt")+ if not isinstance(prompt, str) or not prompt:+ raise GenerationInvalidRequestError("prompt", "prompt must be a non-empty string")+ max_new_tokens = parameters.get("max_new_tokens")+ if isinstance(max_new_tokens, bool) or not isinstance(max_new_tokens, int) or max_new_tokens <= 0:+ raise GenerationInvalidRequestError("max_new_tokens", "max_new_tokens must be an integer > 0")++ if parameters.get("stop") not in (None, []):+ raise GenerationUnsupportedFieldError("stop")+ for name in ("frequency_penalty", "presence_penalty", "grammar", "logit_bias"):+ if parameters.get(name) is not None:+ raise GenerationUnsupportedFieldError(name)+ if parameters.get("images") not in (None, []):+ raise GenerationUnsupportedFieldError("images")+ if parameters.get("lora_path") is not None:+ raise GenerationUnsupportedFieldError(+ "lora_path",+ "'lora_adapter' is not supported by this generation backend",+ )+ if parameters.get("logprobs"):+ raise GenerationUnsupportedFieldError("logprobs")+ if parameters.get("top_logprobs") not in (None, 0):+ raise GenerationUnsupportedFieldError("top_logprobs")+ n = parameters.get("n")+ if n is not None and (isinstance(n, bool) or not isinstance(n, int) or n != 1):+ raise GenerationUnsupportedFieldError("n")+ best_of = parameters.get("best_of")+ if best_of is not None and (isinstance(best_of, bool) or not isinstance(best_of, int) or best_of != 1):+ raise GenerationUnsupportedFieldError("best_of")++ temperature = parameters.get("temperature", 0.0)+ if isinstance(temperature, bool) or not isinstance(temperature, int | float) or float(temperature) != 0.0:+ raise GenerationInvalidRequestError("temperature", "CTranslate2 greedy generation requires temperature=0")+ top_p = parameters.get("top_p", 1.0)+ if isinstance(top_p, bool) or not isinstance(top_p, int | float) or float(top_p) != 1.0:+ raise GenerationInvalidRequestError("top_p", "CTranslate2 greedy generation requires top_p=1")+ top_k = parameters.get("top_k")+ if top_k is not None and (isinstance(top_k, bool) or not isinstance(top_k, int) or top_k != 1):+ raise GenerationInvalidRequestError("top_k", "CTranslate2 greedy generation requires top_k=1")+ seed = parameters.get("seed")+ if seed is not None and (isinstance(seed, bool) or not isinstance(seed, int) or seed != 0):+ raise GenerationInvalidRequestError("seed", "CTranslate2 greedy generation requires seed=0")++ min_new_tokens = parameters.get("min_new_tokens")+ if min_new_tokens is None:+ min_new_tokens = 1+ if (+ isinstance(min_new_tokens, bool)+ or not isinstance(min_new_tokens, int)+ or min_new_tokens < 0+ or min_new_tokens > max_new_tokens+ ):+ raise GenerationInvalidRequestError(+ "min_new_tokens",+ "min_new_tokens must be an integer between 0 and max_new_tokens",+ )+ repetition_penalty = parameters.get("repetition_penalty")+ if repetition_penalty is None:+ repetition_penalty = 1.0+ if (+ isinstance(repetition_penalty, bool)+ or not isinstance(repetition_penalty, int | float)+ or not math.isfinite(float(repetition_penalty))+ or not 0.0 < float(repetition_penalty) <= 2.0+ ):+ raise GenerationInvalidRequestError(+ "repetition_penalty",+ "repetition_penalty must be a finite number in (0, 2]",+ )++ source_tokens, prompt_tokens = self._tokenize_prompt(prompt)+ if prompt_tokens > self._max_seq_length:+ raise GenerationInputTooLongError(+ f"prompt token count {prompt_tokens} exceeds max_seq_length={self._max_seq_length}"+ )+ if prompt_tokens > self._native_batch_max_tokens:+ raise GenerationInputTooLongError(+ f"prompt token count {prompt_tokens} exceeds native_batch_max_tokens={self._native_batch_max_tokens}"+ )+ return _PreparedGeneration(+ source_tokens=source_tokens,+ prompt_tokens=prompt_tokens,+ options=_DecodeOptions(+ max_new_tokens=max_new_tokens,+ min_new_tokens=min_new_tokens,+ repetition_penalty=float(repetition_penalty),+ seed=0,+ ),+ )++ def preflight_generate(+ self,+ parameters: Mapping[str, Any],+ *,+ stream: bool,+ ) -> GenerationPreflightResult:+ del stream+ self._check_loaded()+ if self._draining:+ raise GenerationDrainingError("CTranslate2 generation is draining")+ self._discard_cancelled_pending()+ if len(self._pending) >= self._max_pending_requests:+ raise GenerationCapacityError("CTranslate2 generation scheduler is at capacity")+ normalized = self._normalize_generate_parameters(parameters)+ prepared = self._prepare_generation(normalized)+ return GenerationPreflightResult(self, normalized, prepared)++ def _bind_owner_loop(self) -> asyncio.AbstractEventLoop:+ loop = asyncio.get_running_loop()+ if self._owner_loop is None:+ self._owner_loop = loop+ self._pending_wake = asyncio.Event()+ self._idle = asyncio.Event()+ self._idle.set()+ elif self._owner_loop is not loop:+ raise RuntimeError("CTranslate2 generation scheduler is bound to another event loop")+ return loop++ def _enqueue(self, prepared: _PreparedGeneration) -> _Request:+ loop = self._bind_owner_loop()+ if self._draining:+ raise GenerationDrainingError("CTranslate2 generation is draining")+ self._discard_cancelled_pending()+ if len(self._pending) >= self._max_pending_requests:+ raise GenerationCapacityError("CTranslate2 generation scheduler is at capacity")+ request = _Request(prepared=prepared, loop=loop, enqueued_at=loop.time())+ self._pending.append(request)+ if self._idle is not None:+ self._idle.clear()+ if self._pending_wake is not None:+ self._pending_wake.set()+ if self._scheduler_task is None or self._scheduler_task.done():+ self._scheduler_stopped.clear()+ self._scheduler_task = asyncio.create_task(self._scheduler_loop())+ return request++ def _discard_cancelled_pending(self) -> None:+ if self._pending:+ self._pending = deque(request for request in self._pending if not request.cancelled.is_set())++ def _take_batch(self) -> list[_Request]:+ while self._pending and self._pending[0].cancelled.is_set():+ self._pending.popleft()+ if not self._pending:+ return []+ first = self._pending.popleft()+ options = first.prepared.options+ batch = [first]+ cost = first.cost+ deferred: deque[_Request] = deque()+ while self._pending:+ request = self._pending.popleft()+ if request.cancelled.is_set():+ continue+ compatible = request.prepared.options == options+ fits = len(batch) < self._native_batch_max_size and cost + request.cost <= self._native_batch_max_tokens+ if compatible and fits:+ batch.append(request)+ cost += request.cost+ else:+ deferred.append(request)+ self._pending = deferred+ return batch++ async def _scheduler_loop(self) -> None:+ try:+ while True:+ if not self._pending:+ if self._draining:+ return+ if self._pending_wake is None:+ return+ self._pending_wake.clear()+ if not self._pending:+ await self._pending_wake.wait()+ continue++ deadline = self._pending[0].enqueued_at + self._native_batch_wait_s+ remaining = deadline - asyncio.get_running_loop().time()+ if remaining > 0 and len(self._pending) < self._native_batch_max_size:+ if self._pending_wake is not None:+ self._pending_wake.clear()+ try:+ await asyncio.wait_for(self._pending_wake.wait(), timeout=remaining)+ except TimeoutError:+ # Reaching the batching deadline is the expected path when no peer request arrives.+ pass+ continue++ batch = self._take_batch()+ if not batch:+ continue+ self._active_batch = tuple(batch)+ self._active_batches += 1+ try:+ await asyncio.to_thread(self._execute_native_batch, batch)+ except Exception as exc: # noqa: BLE001 - isolate a failed native batch from the scheduler.+ for request in batch:+ request.fail(exc)+ finally:+ self._active_batches -= 1+ self._active_batch = ()+ finally:+ if self._draining and not self._pending and self._active_batches == 0 and self._idle is not None:+ self._idle.set()+ self._scheduler_stopped.set()++ def _execute_native_batch(self, batch: list[_Request]) -> None:+ translator, _, ctranslate2 = self._check_loaded()+ end_tokens = self._end_tokens()+ options = batch[0].prepared.options+ ctranslate2.set_random_seed(options.seed)++ def callback(step: Any) -> bool:+ return self._force_stop.is_set() or batch[step.batch_id].cancelled.is_set()++ results = translator.translate_batch(+ [list(request.prepared.source_tokens) for request in batch],+ max_batch_size=self._native_batch_max_tokens,+ batch_type="tokens",+ beam_size=1,+ num_hypotheses=1,+ max_input_length=0,+ max_decoding_length=options.max_new_tokens,+ min_decoding_length=options.min_new_tokens,+ sampling_topk=1,+ sampling_topp=1.0,+ sampling_temperature=1.0,+ repetition_penalty=options.repetition_penalty,+ return_end_token=True,+ callback=callback,+ )+ if not isinstance(results, list) or len(results) != len(batch):+ raise RuntimeError("CTranslate2 returned an invalid native batch result")+ for request, result in zip(batch, results, strict=True):+ if self._force_stop.is_set() or request.cancelled.is_set():+ continue+ hypotheses = getattr(result, "hypotheses", None)+ if (+ not isinstance(hypotheses, list)+ or len(hypotheses) != 1+ or not isinstance(hypotheses[0], list)+ or any(not isinstance(token, str) for token in hypotheses[0])+ ):+ request.loop.call_soon_threadsafe(+ request.fail,+ RuntimeError("CTranslate2 returned an invalid translation hypothesis"),+ )+ continue+ result_tokens = hypotheses[0]+ ended = bool(result_tokens and result_tokens[-1] in end_tokens)+ output_tokens = result_tokens[:-1] if ended else result_tokens+ text = self._decode_tokens(output_tokens)+ completion_tokens = len(output_tokens)+ finish_reason: Literal["stop", "length"] = "stop" if ended else "length"+ request.loop.call_soon_threadsafe(request.complete, text, completion_tokens, finish_reason)++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float = 0.0,+ top_p: float = 1.0,+ stop: list[str] | None = None,+ frequency_penalty: float | None = None,+ presence_penalty: float | None = None,+ top_k: int | None = None,+ repetition_penalty: float | None = None,+ min_new_tokens: int | None = None,+ grammar: GrammarSpec | None = None,+ seed: int | None = None,+ logit_bias: dict[str, float] | None = None,+ logprobs: bool = False,+ top_logprobs: int | None = None,+ n: int | None = None,+ best_of: int | None = None,+ stream: bool = False,+ lora_path: str | None = None,+ images: list[ImageInput] | None = None,+ ) -> AsyncIterator[GenerationChunk]:+ parameters: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "repetition_penalty": repetition_penalty,+ "min_new_tokens": min_new_tokens,+ "grammar": grammar,+ "seed": seed,+ "logit_bias": logit_bias,+ "logprobs": logprobs,+ "top_logprobs": top_logprobs,+ "n": n,+ "best_of": best_of,+ "stream": stream,+ "lora_path": lora_path,+ "images": images,+ }+ normalized = self._normalize_generate_parameters(parameters)+ prepared = consume_generation_preflight(self, normalized)+ if not isinstance(prepared, _PreparedGeneration):+ prepared = self._prepare_generation(normalized)+ request = self._enqueue(prepared)+ terminal_yielded = False+ try:+ while True:+ await request.wake.wait()+ request.wake.clear()+ if request.error is not None:+ raise request.error+ if not request.done:+ continue+ if request.final_text is None or request.completion_tokens is None or request.finish_reason is None:+ raise RuntimeError("CTranslate2 generation completed without a terminal result")+ if request.final_text:+ yield GenerationChunk(+ text_delta=request.final_text,+ is_first=True,+ )+ terminal_yielded = True+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=request.finish_reason,+ prompt_tokens=prepared.prompt_tokens,+ completion_tokens=request.completion_tokens,+ )+ return+ finally:+ if not terminal_yielded:+ request.cancelled.set()+ request.wake.set()++ async def drain_generation(self) -> None:+ self._draining = True+ if self._owner_loop is None:+ return+ if self._owner_loop is not asyncio.get_running_loop():+ raise RuntimeError("CTranslate2 generation drain must run on the scheduler event loop")+ draining_error = GenerationDrainingError("CTranslate2 generation is draining")+ while self._pending:+ self._pending.popleft().fail(draining_error)+ if self._pending_wake is not None:+ self._pending_wake.set()+ if not self._pending and self._active_batches == 0:+ if self._idle is not None:+ self._idle.set()+ if self._idle is not None:+ await self._idle.wait()+ task = self._scheduler_task+ if task is not None:+ await task++ def _fail_undrained_generation(self) -> None:+ error = GenerationDrainingError("CTranslate2 generation was cancelled during unload")+ while self._pending:+ self._pending.popleft().fail(error)+ for request in self._active_batch:+ request.fail(error)+ request.cancelled.set()+ if self._pending_wake is not None:+ self._pending_wake.set()++ def unload(self) -> None:+ task = self._scheduler_task+ undrained = bool(self._pending) or self._active_batches > 0 or (task is not None and not task.done())+ if undrained:+ owner_loop = self._owner_loop+ if owner_loop is None or not owner_loop.is_running():+ raise RuntimeError("CTranslate2 generation cannot force-drain without its scheduler event loop")+ try:+ running_loop = asyncio.get_running_loop()+ except RuntimeError:+ running_loop = None+ if running_loop is owner_loop:+ raise RuntimeError("CTranslate2 generation unload must run off its scheduler event loop")+ logger.warning(+ "CTranslate2 generation did not drain before unload; cancelling %d pending and %d active requests",+ len(self._pending),+ len(self._active_batch),+ )+ self._draining = True+ self._force_stop.set()+ owner_loop.call_soon_threadsafe(self._fail_undrained_generation)+ self._scheduler_stopped.wait()+ translator = self._translator+ if translator is not None:+ translator.unload_model()+ self._translator = None+ self._tokenizer = None+ self._ctranslate2 = None+ self._device = None+ self._owner_loop = None+ self._pending_wake = None+ self._scheduler_task = None+ self._active_batch = ()+ self._active_batches = 0+ self._idle = Nonediff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex 6ba11e848..fb42d060c 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -834,6 +834,19 @@ class SGLangGenerationAdapter(GenerationAdapter):self._abort_tasks.add(task)task.add_done_callback(self._abort_tasks.discard)+ def _spawn_abort_request_if_live(self, client: httpx.AsyncClient, rid: str) -> None:+ """Schedule an abort only while the shared SGLang client is usable."""+ server_url = self._server_url+ if server_url is None:+ return+ if client.is_closed:+ logger.debug(+ "skipping /abort_request for rid=%s: shared HTTP client already closed",+ rid,+ )+ return+ self._spawn_abort_request(client, server_url, rid)+def _clear_pending_aclose(self, task: asyncio.Task[None]) -> None:# Only clear the slot if it still references *this* task. A second# ``unload()`` call between the first task finishing and its@@ -1196,11 +1209,12 @@ class SGLangGenerationAdapter(GenerationAdapter):if stream and return_count > 1:sp = dict(sampling_params)sp["n"] = return_count+ rid = uuid.uuid4().hexsbody: dict[str, Any] = {"text": prompt,"sampling_params": sp,"stream": True,- "rid": uuid.uuid4().hex,+ "rid": rid,}if lora_path:sbody["lora_path"] = lora_path@@ -1227,105 +1241,112 @@ class SGLangGenerationAdapter(GenerationAdapter):prompt_tokens: int | None = Nonetotal_completion = 0emitted_first = False- async with sclient.stream("POST", f"{self._server_url}/generate", json=sbody) as sresp:- sresp.raise_for_status()- async for raw_line in sresp.aiter_lines():- line = raw_line.strip()- if line.startswith("data:"):- line = line[len("data:") :].strip()- if not line or line == "[DONE]":- continue- try:- event = json.loads(line)- except json.JSONDecodeError:- continue- _raise_for_sglang_event_error(event)- idx = int(event.get("index", 0))- cumulative = event.get("text", "")- if not isinstance(cumulative, str):- cumulative = last_text.get(idx, "")- delta = cumulative[len(last_text.get(idx, "")) :]- last_text[idx] = cumulative- meta = event.get("meta_info") or {}- if prompt_tokens is None and isinstance(meta.get("prompt_tokens"), int):- prompt_tokens = meta["prompt_tokens"]- fr = meta.get("finish_reason")- fr_type = fr.get("type") if isinstance(fr, dict) else fr- candidate_done = fr_type is not None- if candidate_done and isinstance(meta.get("completion_tokens"), int):- total_completion += meta["completion_tokens"]- # Per-candidate logprob slice — same shape conversion as the- # single-candidate path (`_chunk_from_sglang_event`), but- # the cursor is keyed by candidate index so each candidate- # gets its own monotonic slice.- chunk_logprobs: tuple[dict[str, Any], ...] | None = None- if logprobs and isinstance(meta, dict):- all_token_lp = meta.get("output_token_logprobs")- all_top_lp = meta.get("output_top_logprobs")- prior = logprobs_surfaced.get(idx, 0)- if isinstance(all_token_lp, list) and len(all_token_lp) > prior:- new_slice = all_token_lp[prior:]- new_top_slice = (- all_top_lp[prior:]- if isinstance(all_top_lp, list) and len(all_top_lp) >= len(all_token_lp)- else [None] * len(new_slice)- )- built: list[dict[str, Any]] = []- for token_entry, top_entry in zip(new_slice, new_top_slice, strict=False):- tok_lp, _tok_id, tok_text = _unpack_sglang_token_logprob(token_entry)- if tok_lp is None:- continue- top_list: list[dict[str, Any]] = []- if isinstance(top_entry, list):- for top_token in top_entry:- t_lp, _t_id, t_text = _unpack_sglang_token_logprob(top_token)- if t_lp is None:- continue- top_list.append(- {- "token": t_text or "",- "logprob": float(t_lp),- "bytes": list((t_text or "").encode("utf-8")),- }- )- built.append(- {- "token": tok_text or "",- "logprob": float(tok_lp),- "bytes": list((tok_text or "").encode("utf-8")),- "top_logprobs": top_list,- }+ terminal_yielded = False+ try:+ async with sclient.stream("POST", f"{self._server_url}/generate", json=sbody) as sresp:+ sresp.raise_for_status()+ async for raw_line in sresp.aiter_lines():+ line = raw_line.strip()+ if line.startswith("data:"):+ line = line[len("data:") :].strip()+ if not line or line == "[DONE]":+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ continue+ _raise_for_sglang_event_error(event)+ idx = int(event.get("index", 0))+ cumulative = event.get("text", "")+ if not isinstance(cumulative, str):+ cumulative = last_text.get(idx, "")+ delta = cumulative[len(last_text.get(idx, "")) :]+ last_text[idx] = cumulative+ meta = event.get("meta_info") or {}+ if prompt_tokens is None and isinstance(meta.get("prompt_tokens"), int):+ prompt_tokens = meta["prompt_tokens"]+ fr = meta.get("finish_reason")+ fr_type = fr.get("type") if isinstance(fr, dict) else fr+ candidate_done = fr_type is not None+ if candidate_done and isinstance(meta.get("completion_tokens"), int):+ total_completion += meta["completion_tokens"]+ # Per-candidate logprob slice — same shape conversion as the+ # single-candidate path (`_chunk_from_sglang_event`), but+ # the cursor is keyed by candidate index so each candidate+ # gets its own monotonic slice.+ chunk_logprobs: tuple[dict[str, Any], ...] | None = None+ if logprobs and isinstance(meta, dict):+ all_token_lp = meta.get("output_token_logprobs")+ all_top_lp = meta.get("output_top_logprobs")+ prior = logprobs_surfaced.get(idx, 0)+ if isinstance(all_token_lp, list) and len(all_token_lp) > prior:+ new_slice = all_token_lp[prior:]+ new_top_slice = (+ all_top_lp[prior:]+ if isinstance(all_top_lp, list) and len(all_top_lp) >= len(all_token_lp)+ else [None] * len(new_slice))- if built:- chunk_logprobs = tuple(built)- # Advance to the cumulative reported length rather- # than incrementing by ``len(built)`` so a skipped- # malformed entry does not re-surface next event.- logprobs_surfaced[idx] = len(all_token_lp)- if not delta and not candidate_done and not chunk_logprobs:- continue- is_first = bool(delta) and not emitted_first- emitted_first = emitted_first or bool(delta)- yield GenerationChunk(- text_delta=delta,- done=False,- is_first=is_first,- finish_reason=cast("FinishReason | None", fr_type if candidate_done else None),- choice_index=idx,- logprobs=chunk_logprobs,- )- # Single global terminal closes the multi-candidate stream (carries- # aggregate usage). Each candidate already received its own- # ``finish_reason`` on the per-choice completion chunk above; this- # terminal is the stream-level "all candidates done" signal that- # drives the processor's loop break and the gateway's [DONE].- yield GenerationChunk(- text_delta="",- done=True,- finish_reason="stop",- prompt_tokens=prompt_tokens,- completion_tokens=total_completion,- )+ built: list[dict[str, Any]] = []+ for token_entry, top_entry in zip(new_slice, new_top_slice, strict=False):+ tok_lp, _tok_id, tok_text = _unpack_sglang_token_logprob(token_entry)+ if tok_lp is None:+ continue+ top_list: list[dict[str, Any]] = []+ if isinstance(top_entry, list):+ for top_token in top_entry:+ t_lp, _t_id, t_text = _unpack_sglang_token_logprob(top_token)+ if t_lp is None:+ continue+ top_list.append(+ {+ "token": t_text or "",+ "logprob": float(t_lp),+ "bytes": list((t_text or "").encode("utf-8")),+ }+ )+ built.append(+ {+ "token": tok_text or "",+ "logprob": float(tok_lp),+ "bytes": list((tok_text or "").encode("utf-8")),+ "top_logprobs": top_list,+ }+ )+ if built:+ chunk_logprobs = tuple(built)+ # Advance to the cumulative reported length rather+ # than incrementing by ``len(built)`` so a skipped+ # malformed entry does not re-surface next event.+ logprobs_surfaced[idx] = len(all_token_lp)+ if not delta and not candidate_done and not chunk_logprobs:+ continue+ is_first = bool(delta) and not emitted_first+ emitted_first = emitted_first or bool(delta)+ yield GenerationChunk(+ text_delta=delta,+ done=False,+ is_first=is_first,+ finish_reason=cast("FinishReason | None", fr_type if candidate_done else None),+ choice_index=idx,+ logprobs=chunk_logprobs,+ )+ # Single global terminal closes the multi-candidate stream (carries+ # aggregate usage). Each candidate already received its own+ # ``finish_reason`` on the per-choice completion chunk above; this+ # terminal is the stream-level "all candidates done" signal that+ # drives the processor's loop break and the gateway's [DONE].+ terminal_yielded = True+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=prompt_tokens,+ completion_tokens=total_completion,+ )+ except (GeneratorExit, asyncio.CancelledError):+ if not terminal_yielded:+ self._spawn_abort_request_if_live(sclient, rid)+ raisereturngen_count = best_of if (best_of is not None and best_of > 1) else return_count@@ -1479,6 +1500,7 @@ class SGLangGenerationAdapter(GenerationAdapter):# ``async with`` — we just borrow a reference. Cancellation /# GeneratorExit still cleans up the stream context below.client = await self._get_or_create_http_client()+ terminal_yielded = Falsetry:async with client.stream("POST", f"{self._server_url}/generate", json=body) as response:if response.status_code != 200:@@ -1493,7 +1515,6 @@ class SGLangGenerationAdapter(GenerationAdapter):last_cumulative_text = ""first_yield_done = False- terminal_yielded = False# Number of token-logprob entries already surfaced# on prior chunks. SGLang accumulates them on# ``meta_info.output_token_logprobs`` (a flat list,@@ -1627,7 +1648,7 @@ class SGLangGenerationAdapter(GenerationAdapter):if not terminal_yielded:raise RuntimeError("SGLang stream terminated without terminal event")- except GeneratorExit:+ except (GeneratorExit, asyncio.CancelledError):# Caller dropped the iterator (cancellation / aclose). Issue a# best-effort POST to /abort_request so SGLang frees the slot# promptly. CRITICAL: do NOT ``await`` the abort here. The@@ -1640,7 +1661,7 @@ class SGLangGenerationAdapter(GenerationAdapter):# ignored GeneratorExit`` if the await is interrupted. Instead# we spawn the abort as an independent, tracked background task# (bounded by ``_ABORT_REQUEST_TIMEOUT_S`` < the 2s cap) on the- # adapter's long-lived loop and re-raise GeneratorExit cleanly.+ # adapter's long-lived loop and re-raise cancellation cleanly.# The shared client is reused so the abort piggybacks on an# existing connection rather than paying a fresh TCP handshake.# If a concurrent ``unload()`` / ``aclose_client()`` already@@ -1648,14 +1669,8 @@ class SGLangGenerationAdapter(GenerationAdapter):# in ``_abort_request``) and the abort silently no-ops, leaking# the SGLang GPU slot until SGLang's own timeout. Skip the abort# in that case — there is no live client to drive it.- server_url = self._server_url- if server_url is not None and not client.is_closed:- self._spawn_abort_request(client, server_url, rid)- elif server_url is not None:- logger.debug(- "skipping /abort_request for rid=%s: shared HTTP client already closed",- rid,- )+ if not terminal_yielded:+ self._spawn_abort_request_if_live(client, rid)raisefinally:# Emit TPOT regardless of normal completion vs cancellation.diff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/__init__.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_compat/__init__.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_compat/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_compat/sitecustomize.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_compat/sitecustomize.pynew file mode 100644index 000000000..ac0d657b3--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_compat/sitecustomize.py@@ -0,0 +1,13 @@+import os++from sie_server.adapters.tensorrt_llm.compat import install_rc24_compatibility++if os.environ.get("SIE_TRTLLM_RC24_COMPAT") == "1":+ try:+ install_rc24_compatibility()+ except Exception as error:+ # CPython deliberately catches ordinary exceptions raised by+ # sitecustomize and continues interpreter startup. Convert every+ # compatibility failure into an uncaught BaseException so the engine+ # can never start after a missing, stale, or partially applied patch.+ raise SystemExit(f"TensorRT-LLM rc24 compatibility startup failed: {error}") from errordiff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.pynew file mode 100644index 000000000..d8078c7ec--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/_server.py@@ -0,0 +1,221 @@+"""Lifecycle helpers for one local TensorRT-LLM serve subprocess."""++from __future__ import annotations++import contextlib+import json+import logging+import os+import random+import signal+import socket+import subprocess+import tempfile+import threading+import time+from pathlib import Path+from typing import Any++import requests++logger = logging.getLogger(__name__)++DEFAULT_STARTUP_TIMEOUT_S = 900.0+HEALTH_CHECK_INTERVAL_S = 2.0+PROCESS_GROUP_POLL_INTERVAL_S = 0.05+PROCESS_GROUP_KILL_TIMEOUT_S = 5.0+BASE_PORT = 30200+_RESERVED_PORTS: set[int] = set()+_RESERVED_PORTS_LOCK = threading.Lock()+++def parse_cuda_device_index(device: str) -> int:+ if device == "cuda":+ return 0+ if device.startswith("cuda:"):+ try:+ index = int(device.partition(":")[2])+ except ValueError as exc:+ raise ValueError(f"invalid CUDA device {device!r}") from exc+ if index < 0:+ raise ValueError(f"invalid CUDA device {device!r}")+ return index+ raise ValueError("TensorRT-LLM generation requires a CUDA device")+++def reserve_port(start_port: int = BASE_PORT) -> int:+ span = 100+ offset = random.randrange(span) # noqa: S311 - availability spreading, not security+ with _RESERVED_PORTS_LOCK:+ for index in range(span):+ port = start_port + ((offset + index) % span)+ if port in _RESERVED_PORTS:+ continue+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ try:+ probe.bind(("127.0.0.1", port))+ except OSError:+ continue+ _RESERVED_PORTS.add(port)+ return port+ raise RuntimeError(f"no free TensorRT-LLM port in {start_port}-{start_port + span - 1}")+++def release_port(port: int | None) -> None:+ if port is None:+ return+ with _RESERVED_PORTS_LOCK:+ _RESERVED_PORTS.discard(port)+++def open_output_log() -> tempfile._TemporaryFileWrapper:+ return tempfile.NamedTemporaryFile(prefix="trtllm_", suffix=".log", delete=False)+++def log_tail(output_file: tempfile._TemporaryFileWrapper | None, *, chars: int = 5000) -> str:+ if output_file is None or chars <= 0:+ return ""+ with contextlib.suppress(OSError):+ output_file.flush()+ try:+ with Path(output_file.name).open("rb") as log:+ log.seek(0, os.SEEK_END)+ log.seek(max(0, log.tell() - (chars * 4)))+ return log.read(chars * 4).decode("utf-8", errors="replace")[-chars:]+ except OSError:+ return ""+++def launch(+ command: list[str],+ *,+ device_index: int,+ output_file: tempfile._TemporaryFileWrapper,+ environment: dict[str, str],+) -> subprocess.Popen[bytes]:+ child_env = os.environ.copy()+ child_env.update(environment)+ child_env["CUDA_VISIBLE_DEVICES"] = str(device_index)+ return subprocess.Popen( # noqa: S603 - command is entirely code/profile owned+ command,+ stdout=output_file,+ stderr=subprocess.STDOUT,+ env=child_env,+ start_new_session=True,+ )+++def wait_until_ready(+ process: subprocess.Popen[bytes],+ server_url: str,+ *,+ served_model_name: str,+ output_file: tempfile._TemporaryFileWrapper | None,+ timeout_s: float,+) -> None:+ deadline = time.monotonic() + timeout_s+ health_url = f"{server_url}/health"+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"trtllm-serve exited during startup: {log_tail(output_file)}")+ try:+ response = requests.get(health_url, timeout=5)+ if response.status_code == 200:+ break+ except requests.RequestException:+ # Connection failures are expected while the child is starting.+ pass+ time.sleep(HEALTH_CHECK_INTERVAL_S)+ else:+ raise RuntimeError(f"trtllm-serve did not become healthy: {log_tail(output_file)}")++ remaining_s = deadline - time.monotonic()+ if remaining_s <= 0:+ raise RuntimeError(f"trtllm-serve exhausted its startup budget before warmup: {log_tail(output_file)}")+ warmup = requests.post(+ f"{server_url}/v1/completions",+ json={+ "model": served_model_name,+ "prompt": "warmup",+ "max_tokens": 1,+ "temperature": 0.0,+ "stream": False,+ },+ timeout=remaining_s,+ )+ warmup.raise_for_status()+ payload: Any = warmup.json()+ if not isinstance(payload, dict) or not isinstance(payload.get("choices"), list):+ raise RuntimeError(f"invalid trtllm-serve warmup response: {json.dumps(payload)[:500]}")+++def _process_group_exists(process_group_id: int) -> bool:+ try:+ os.killpg(process_group_id, 0)+ except ProcessLookupError:+ return False+ return True+++def _reap_owned_process_group_children(process_group_id: int) -> None:+ while True:+ try:+ reaped_pid, _status = os.waitpid(-process_group_id, os.WNOHANG)+ except ChildProcessError:+ return+ if reaped_pid == 0:+ return+++def _wait_for_process_group_exit(+ process: subprocess.Popen[bytes],+ process_group_id: int,+ *,+ deadline: float,+) -> bool:+ while True:+ launcher_exited = process.poll() is not None+ if launcher_exited:+ # The server container runs Python as PID 1, so orphaned+ # TensorRT/MPI descendants are adopted here. Reap killed children+ # in this adapter-owned session before treating zombie-only PGIDs+ # as a failed SIGKILL.+ _reap_owned_process_group_children(process_group_id)+ if not _process_group_exists(process_group_id):+ return True+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ return False+ interval = min(PROCESS_GROUP_POLL_INTERVAL_S, remaining)+ if not launcher_exited:+ with contextlib.suppress(subprocess.TimeoutExpired):+ process.wait(timeout=interval)+ else:+ time.sleep(interval)+++def terminate(process: subprocess.Popen[bytes] | None, *, timeout_s: float = 10.0) -> None:+ if process is None:+ return+ process_group_id = process.pid+ try:+ os.killpg(process_group_id, signal.SIGTERM)+ except ProcessLookupError:+ with contextlib.suppress(subprocess.TimeoutExpired):+ process.wait(timeout=0)+ return++ term_deadline = time.monotonic() + max(float(timeout_s), 0.0)+ if _wait_for_process_group_exit(process, process_group_id, deadline=term_deadline):+ with contextlib.suppress(subprocess.TimeoutExpired):+ process.wait(timeout=max(term_deadline - time.monotonic(), 0.0))+ return++ with contextlib.suppress(ProcessLookupError):+ os.killpg(process_group_id, signal.SIGKILL)+ kill_deadline = time.monotonic() + PROCESS_GROUP_KILL_TIMEOUT_S+ exited = _wait_for_process_group_exit(process, process_group_id, deadline=kill_deadline)+ with contextlib.suppress(subprocess.TimeoutExpired):+ process.wait(timeout=max(kill_deadline - time.monotonic(), 0.0))+ if not exited:+ raise RuntimeError(f"TensorRT-LLM process group {process_group_id} survived SIGKILL")diff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/compat.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/compat.pynew file mode 100644index 000000000..35650f8ab--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/compat.py@@ -0,0 +1,188 @@+"""Exact-source compatibility overlay for the TensorRT-LLM 1.3.0rc24 lane.++The selected runtime has three generic T5 direct-HF gaps: its T5 converter+requires ``shared.weight`` even when ``safetensors.torch.save_model`` retained+only a known encoder/decoder embedding key, its T5 model always scales decoder+outputs before the LM head, and Transformers 5.5.4 reconstructs a custom T5+tokenizer pipeline instead of preserving a checkpoint's ``tokenizer.json``.+The child process installs this overlay through a code-owned ``sitecustomize``+directory, while the parent adapter installs the tokenizer-only part before it+counts prompt tokens. Package versions and complete source-file hashes are+checked before patching so a future runtime cannot silently inherit an overlay+written for different code.+"""++from __future__ import annotations++import hashlib+import importlib.metadata+import inspect+from pathlib import Path+from typing import Any, Protocol, runtime_checkable++TRTLLM_VERSION = "1.3.0rc24"+TRANSFORMERS_VERSION = "5.5.4"+HF_WEIGHT_LOADER_SHA256 = "d8464ac2257b167c8e127606b495b1021ff69f7d3ff1ce663abc09fffa8b932a"+MODELING_T5_SHA256 = "248f80484668b8dee1480b3b49ab81d68193bdd9d4eecd29bd53068ba2dd3d46"+T5_TOKENIZATION_SHA256 = "6fa6696aa2bf6bf40bcd7c7aea81b5b581e365ada45c6d7768d53609174496d5"+TOKENIZERS_BACKEND_SHA256 = "b76df59838488e19539bc50f2a8cf7c8f16c48ef96859fcc1236f5dfe467d29d"+_PATCH_MARKER = "_sie_rc24_compatibility_installed"+_T5_SHARED_EMBEDDING_KEY = "shared.weight"+_T5_INPUT_EMBEDDING_KEYS = ("encoder.embed_tokens.weight", "decoder.embed_tokens.weight")+++@runtime_checkable+class _MutableWeights(Protocol):+ """Structural subset shared by dict and rc24 ConsumableWeightsDict."""++ def __contains__(self, key: object) -> bool:+ pass++ def __getitem__(self, key: str) -> Any:+ pass++ def __setitem__(self, key: str, value: Any) -> None:+ pass+++def _source_sha256(module: Any) -> str:+ source = inspect.getsourcefile(module)+ if source is None:+ raise RuntimeError(f"cannot locate source for {module.__name__}")+ return hashlib.sha256(Path(source).read_bytes()).hexdigest()+++def verify_exact_rc24_sources(weight_loader_module: Any, modeling_t5_module: Any) -> None:+ """Fail closed unless the installed distribution and patched files match."""+ installed = importlib.metadata.version("tensorrt-llm")+ if installed != TRTLLM_VERSION:+ raise RuntimeError(f"TensorRT-LLM compatibility requires {TRTLLM_VERSION}, found {installed}")+ expected = (+ (weight_loader_module, HF_WEIGHT_LOADER_SHA256),+ (modeling_t5_module, MODELING_T5_SHA256),+ )+ for module, expected_sha in expected:+ actual_sha = _source_sha256(module)+ if actual_sha != expected_sha:+ raise RuntimeError(+ f"refusing TensorRT-LLM compatibility for changed source {module.__name__}: "+ f"expected sha256 {expected_sha}, found {actual_sha}"+ )+++def verify_exact_transformers_5_sources(+ t5_tokenization_module: Any,+ tokenizers_backend_module: Any,+) -> None:+ """Fail closed unless the installed Transformers tokenizer sources match."""+ installed = importlib.metadata.version("transformers")+ if installed != TRANSFORMERS_VERSION:+ raise RuntimeError(+ f"T5 tokenizer compatibility requires Transformers {TRANSFORMERS_VERSION}, found {installed}"+ )+ expected = (+ (t5_tokenization_module, T5_TOKENIZATION_SHA256),+ (tokenizers_backend_module, TOKENIZERS_BACKEND_SHA256),+ )+ for module, expected_sha in expected:+ actual_sha = _source_sha256(module)+ if actual_sha != expected_sha:+ raise RuntimeError(+ f"refusing T5 tokenizer compatibility for changed source {module.__name__}: "+ f"expected sha256 {expected_sha}, found {actual_sha}"+ )+++def _restore_t5_shared_embedding(weights: _MutableWeights) -> None:+ """Supply rc24's required T5 key from exact input-embedding semantics."""+ if _T5_SHARED_EMBEDDING_KEY in weights:+ return+ # The guarded rc24 T5 source always shares encoder/decoder input+ # embeddings. ``tie_word_embeddings`` controls only the LM head, which is+ # deliberately not a restoration source here.+ sources = [key for key in _T5_INPUT_EMBEDDING_KEYS if key in weights]+ if not sources:+ return+ source_tensor = weights[sources[0]]+ if any(weights[key] is not source_tensor for key in sources[1:]):+ rendered = ", ".join(repr(key) for key in sources)+ raise RuntimeError(f"ambiguous T5 shared embedding tensors: {rendered}")+ weights[_T5_SHARED_EMBEDDING_KEY] = source_tensor+++def _install_t5_weight_patch(modeling_t5_module: Any) -> None:+ model_class = modeling_t5_module.T5ForConditionalGeneration+ original = model_class.load_weights+ if getattr(original, _PATCH_MARKER, False):+ return++ def _load_weights_with_shared_embedding(self: Any, weights: Any, *args: Any, **kwargs: Any) -> Any:+ if not isinstance(weights, _MutableWeights):+ raise RuntimeError("TensorRT-LLM T5 loader received a non-mutable weight mapping")+ _restore_t5_shared_embedding(weights)+ return original(self, weights, *args, **kwargs)++ setattr(_load_weights_with_shared_embedding, _PATCH_MARKER, True)+ model_class.load_weights = _load_weights_with_shared_embedding+++def _install_t5_scaling_patch(modeling_t5_module: Any) -> None:+ model_class = modeling_t5_module.T5ForConditionalGeneration+ original = model_class.__init__+ if getattr(original, _PATCH_MARKER, False):+ return++ def _init_with_saved_scaling_semantics(self: Any, model_config: Any, *args: Any, **kwargs: Any) -> None:+ original(self, model_config, *args, **kwargs)+ pretrained_config = getattr(model_config, "pretrained_config", None)+ if pretrained_config is None:+ raise RuntimeError("TensorRT-LLM T5 ModelConfig is missing pretrained_config")+ legacy_default = getattr(pretrained_config, "tie_word_embeddings", True)+ self.rescale_before_lm_head = bool(getattr(pretrained_config, "scale_decoder_outputs", legacy_default))++ setattr(_init_with_saved_scaling_semantics, _PATCH_MARKER, True)+ model_class.__init__ = _init_with_saved_scaling_semantics+++def _install_t5_tokenizer_serialization_patch(t5_tokenization_module: Any, tokenizers_backend_module: Any) -> None:+ tokenizer_class = t5_tokenization_module.T5Tokenizer+ original = tokenizer_class.convert_to_native_format+ original_function = original.__func__+ if getattr(original_function, _PATCH_MARKER, False):+ return++ def _convert_to_native_format(+ cls: Any,+ trust_remote_code: bool = False,+ **kwargs: Any,+ ) -> dict[str, Any]:+ tokenizer_file = kwargs.get("tokenizer_file")+ if not trust_remote_code and isinstance(tokenizer_file, str) and Path(tokenizer_file).is_file():+ converted = dict(kwargs)+ converted.pop("tokenizer_file")+ converted["tokenizer_object"] = tokenizers_backend_module.TokenizerFast.from_file(tokenizer_file)+ return converted+ return original_function(cls, trust_remote_code=trust_remote_code, **kwargs)++ setattr(_convert_to_native_format, _PATCH_MARKER, True)+ tokenizer_class.convert_to_native_format = classmethod(_convert_to_native_format)+++def install_transformers_5_t5_tokenizer_compatibility() -> None:+ """Make exact Transformers 5.5.4 T5 loads honor ``tokenizer.json``."""+ t5_tokenization = importlib.import_module("transformers.models.t5.tokenization_t5")+ tokenizers_backend = importlib.import_module("transformers.tokenization_utils_tokenizers")++ verify_exact_transformers_5_sources(t5_tokenization, tokenizers_backend)+ _install_t5_tokenizer_serialization_patch(t5_tokenization, tokenizers_backend)+++def install_rc24_compatibility() -> None:+ """Verify and install the narrowly scoped direct-HF compatibility patches."""+ modeling_t5 = importlib.import_module("tensorrt_llm._torch.models.modeling_t5")+ weight_loader = importlib.import_module("tensorrt_llm._torch.models.checkpoints.hf.weight_loader")++ verify_exact_rc24_sources(weight_loader, modeling_t5)+ install_transformers_5_t5_tokenizer_compatibility()+ _install_t5_weight_patch(modeling_t5)+ _install_t5_scaling_patch(modeling_t5)diff --git a/packages/sie_server/src/sie_server/adapters/tensorrt_llm/generation.py b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/generation.pynew file mode 100644index 000000000..0cf4cfcff--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/tensorrt_llm/generation.py@@ -0,0 +1,777 @@+"""Generic TensorRT-LLM encoder-decoder generation adapter."""++from __future__ import annotations++import asyncio+import contextlib+import json+import logging+import math+import os+import subprocess+import tempfile+import threading+from collections.abc import AsyncGenerator, AsyncIterator, Mapping+from pathlib import Path+from typing import Any, cast++import httpx+from transformers import AutoTokenizer++from sie_server.adapters._generation_base import (+ FinishReason,+ GenerationAdapter,+ GenerationChunk,+ GenerationDrainingError,+ GenerationInputTooLongError,+ GenerationInvalidRequestError,+ GenerationPreflightResult,+ GenerationUnsupportedFieldError,+ aclose_with_error_precedence,+ consume_generation_preflight,+)+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.adapters.tensorrt_llm import _server+from sie_server.adapters.tensorrt_llm.compat import install_transformers_5_t5_tokenizer_compatibility+from sie_server.config.model import is_immutable_revision+from sie_server.types.grammar import GrammarSpec+from sie_server.types.inputs import ImageInput++logger = logging.getLogger(__name__)++_CONNECT_TIMEOUT_S = 10.0+_READ_TIMEOUT_S = 300.0+_WRITE_TIMEOUT_S = 10.0+_POOL_TIMEOUT_S = 10.0+_CLIENT_CLOSE_TIMEOUT_S = 2.0+++def _positive_int(name: str, value: int) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value <= 0:+ raise ValueError(f"{name} must be an integer > 0")+ return value+++def _batch_sizes(name: str, values: list[int] | tuple[int, ...], *, maximum: int) -> list[int]:+ result = [_positive_int(name, value) for value in values]+ if not result or result != sorted(set(result)) or result[-1] > maximum:+ raise ValueError(f"{name} must be sorted unique positive integers <= {maximum}")+ return result+++def _fraction(name: str, value: float) -> float:+ if isinstance(value, bool) or not isinstance(value, int | float):+ raise ValueError(f"{name} must be a number in (0, 1)")+ result = float(value)+ if not math.isfinite(result) or not 0.0 < result < 1.0:+ raise ValueError(f"{name} must be a finite number in (0, 1)")+ return result+++def _boolean(name: str, value: bool) -> bool:+ if not isinstance(value, bool):+ raise ValueError(f"{name} must be a boolean")+ return value+++def _completion_logprobs(payload: Any) -> tuple[dict[str, Any], ...] | None:+ if payload is None:+ return None+ if not isinstance(payload, Mapping):+ raise RuntimeError("TensorRT-LLM completion logprobs must be an object")+ tokens = payload.get("tokens")+ token_logprobs = payload.get("token_logprobs")+ top_logprobs = payload.get("top_logprobs")+ if not isinstance(tokens, list) or not isinstance(token_logprobs, list) or len(tokens) != len(token_logprobs):+ raise RuntimeError("TensorRT-LLM completion logprobs have misaligned token arrays")+ if top_logprobs is None:+ top_logprobs = [{} for _ in tokens]+ if not isinstance(top_logprobs, list) or len(top_logprobs) != len(tokens):+ raise RuntimeError("TensorRT-LLM completion logprobs have misaligned top-logprob arrays")++ built: list[dict[str, Any]] = []+ for token, token_logprob, alternatives in zip(tokens, token_logprobs, top_logprobs, strict=True):+ if not isinstance(token, str) or isinstance(token_logprob, bool) or not isinstance(token_logprob, int | float):+ raise RuntimeError("TensorRT-LLM completion logprobs contain an invalid token")+ if alternatives is None:+ alternatives = {}+ if not isinstance(alternatives, Mapping):+ raise RuntimeError("TensorRT-LLM top logprobs must be token-to-logprob objects")+ top: list[dict[str, Any]] = []+ for alternative, logprob in alternatives.items():+ if not isinstance(alternative, str) or isinstance(logprob, bool) or not isinstance(logprob, int | float):+ raise RuntimeError("TensorRT-LLM top logprobs contain an invalid entry")+ top.append(+ {+ "token": alternative,+ "logprob": float(logprob),+ "bytes": list(alternative.encode("utf-8")),+ }+ )+ built.append(+ {+ "token": token,+ "logprob": float(token_logprob),+ "bytes": list(token.encode("utf-8")),+ "top_logprobs": top,+ }+ )+ return tuple(built) or None+++class TensorRTLLMGenerationAdapter(GenerationAdapter):+ """Serve a direct-HF encoder-decoder model through one local rc24 child."""++ spec = AdapterSpec(+ inputs=("text",),+ outputs=("tokens",),+ unload_fields=("_process", "_server_url", "_tokenizer"),+ )+ requires_main_thread = False+ manages_own_load_timeout = True+ context_length_accounting = "independent"+ prompt_tokenization_add_special_tokens = True++ def __init__(+ self,+ model_name_or_path: str,+ *,+ revision: str,+ served_model_name: str | None = None,+ max_seq_length: int = 4096,+ max_input_len: int = 2048,+ max_batch_size: int = 8,+ max_num_tokens: int = 8192,+ encoder_max_num_tokens: int = 8192,+ compute_precision: ComputePrecision = "bfloat16",+ decoder_cuda_graph_batch_sizes: list[int] | tuple[int, ...] = (1, 2, 4, 8),+ encoder_cuda_graph_batch_sizes: list[int] | tuple[int, ...] = (1, 2, 4, 8),+ encoder_cuda_graph_num_tokens: list[int] | tuple[int, ...] = (64, 256, 1024, 2048),+ encoder_cuda_graph_seq_lens: list[int] | tuple[int, ...] = (64, 256, 1024, 2048),+ enable_decoder_cuda_graphs: bool = True,+ enable_encoder_cuda_graphs: bool = True,+ decoder_cuda_graph_enable_padding: bool = True,+ encoder_cuda_graph_enable_padding: bool = True,+ enable_encoder_decoder_mixed_cuda_graph: bool = True,+ disable_overlap_scheduler: bool = False,+ kv_cache_free_gpu_memory_fraction: float = 0.85,+ cross_kv_cache_fraction: float = 0.5,+ startup_timeout_s: float = _server.DEFAULT_STARTUP_TIMEOUT_S,+ ) -> None:+ if not isinstance(model_name_or_path, str) or not model_name_or_path:+ raise ValueError("TensorRT-LLM requires a Hugging Face model id")+ if not is_immutable_revision(revision):+ raise ValueError("TensorRT-LLM requires revision to be an immutable 40-character commit SHA")+ if not isinstance(compute_precision, str) or compute_precision not in {"bfloat16", "float32"}:+ raise ValueError("TensorRT-LLM rc24 requires compute_precision=bfloat16 or compute_precision=float32")++ self._model_name_or_path = model_name_or_path+ self._revision = revision+ self._served_model_name = served_model_name or model_name_or_path+ self._max_seq_length = _positive_int("max_seq_length", max_seq_length)+ self._max_input_len = _positive_int("max_input_len", max_input_len)+ self._max_batch_size = _positive_int("max_batch_size", max_batch_size)+ self._max_num_tokens = _positive_int("max_num_tokens", max_num_tokens)+ self._encoder_max_num_tokens = _positive_int("encoder_max_num_tokens", encoder_max_num_tokens)+ if self._max_input_len > self._max_seq_length:+ raise ValueError("max_input_len must not exceed max_seq_length")+ if self._max_num_tokens < self._max_batch_size:+ raise ValueError("max_num_tokens must be at least max_batch_size")+ if self._encoder_max_num_tokens < self._max_input_len:+ raise ValueError("encoder_max_num_tokens must be at least max_input_len")++ self._decoder_graph_batches = _batch_sizes(+ "decoder_cuda_graph_batch_sizes", decoder_cuda_graph_batch_sizes, maximum=self._max_batch_size+ )+ self._encoder_graph_batches = _batch_sizes(+ "encoder_cuda_graph_batch_sizes", encoder_cuda_graph_batch_sizes, maximum=self._max_batch_size+ )+ self._encoder_graph_tokens = _batch_sizes(+ "encoder_cuda_graph_num_tokens", encoder_cuda_graph_num_tokens, maximum=self._encoder_max_num_tokens+ )+ self._encoder_graph_seq_lens = _batch_sizes(+ "encoder_cuda_graph_seq_lens", encoder_cuda_graph_seq_lens, maximum=self._max_input_len+ )+ self._enable_decoder_cuda_graphs = _boolean("enable_decoder_cuda_graphs", enable_decoder_cuda_graphs)+ self._enable_encoder_cuda_graphs = _boolean("enable_encoder_cuda_graphs", enable_encoder_cuda_graphs)+ self._decoder_cuda_graph_enable_padding = _boolean(+ "decoder_cuda_graph_enable_padding", decoder_cuda_graph_enable_padding+ )+ self._encoder_cuda_graph_enable_padding = _boolean(+ "encoder_cuda_graph_enable_padding", encoder_cuda_graph_enable_padding+ )+ self._enable_encoder_decoder_mixed_cuda_graph = _boolean(+ "enable_encoder_decoder_mixed_cuda_graph", enable_encoder_decoder_mixed_cuda_graph+ )+ self._disable_overlap_scheduler = _boolean("disable_overlap_scheduler", disable_overlap_scheduler)+ if compute_precision == "float32" and self._enable_decoder_cuda_graphs:+ raise ValueError("compute_precision=float32 requires enable_decoder_cuda_graphs=false")+ if compute_precision == "float32" and self._enable_encoder_decoder_mixed_cuda_graph:+ raise ValueError("compute_precision=float32 requires enable_encoder_decoder_mixed_cuda_graph=false")+ if self._enable_encoder_decoder_mixed_cuda_graph and (+ not self._enable_decoder_cuda_graphs or not self._enable_encoder_cuda_graphs+ ):+ raise ValueError("enable_encoder_decoder_mixed_cuda_graph requires both CUDA graph families")+ self._compute_precision = compute_precision+ self._kv_cache_fraction = _fraction("kv_cache_free_gpu_memory_fraction", kv_cache_free_gpu_memory_fraction)+ self._cross_kv_fraction = _fraction("cross_kv_cache_fraction", cross_kv_cache_fraction)+ if not math.isfinite(startup_timeout_s) or startup_timeout_s <= 0:+ raise ValueError("startup_timeout_s must be finite and > 0")+ self._startup_timeout_s = float(startup_timeout_s)++ self._process: subprocess.Popen[bytes] | None = None+ self._server_url: str | None = None+ self._tokenizer: Any | None = None+ self._port: int | None = None+ self._device: str | None = None+ self._output_file: tempfile._TemporaryFileWrapper | None = None+ self._config_path: Path | None = None+ self._http_client: httpx.AsyncClient | None = None+ self._http_client_lock: asyncio.Lock | None = None+ self._http_client_init_lock = threading.Lock()+ self._pending_aclose: asyncio.Task[None] | None = None+ self._generation_draining = False+ self._active_generations = 0+ self._generation_idle: asyncio.Event | None = None++ @classmethod+ def create_for_device(cls, device: str, **kwargs: Any) -> GenerationAdapter:+ _server.parse_cuda_device_index(device)+ return cls(**kwargs)++ @property+ def runtime_config(self) -> dict[str, Any]:+ """Return the checked TensorRT-LLM LLM-API profile written for the child."""+ decoder_graph_config = (+ {+ "batch_sizes": self._decoder_graph_batches,+ "enable_padding": self._decoder_cuda_graph_enable_padding,+ }+ if self._enable_decoder_cuda_graphs+ else None+ )+ encoder_graph_config = (+ {+ "batch_sizes": self._encoder_graph_batches,+ "num_tokens": self._encoder_graph_tokens,+ "seq_lens": self._encoder_graph_seq_lens,+ "enable_padding": self._encoder_cuda_graph_enable_padding,+ }+ if self._enable_encoder_cuda_graphs+ else None+ )+ return {+ "attn_backend": "TRTLLM",+ "dtype": self._compute_precision,+ # rc24's encoder-decoder KV dtype inference also consults the HF+ # model kwargs. The top-level dtype alone leaves+ # ``model_engine.dtype`` unset; both fields are required by the+ # qualified direct-HF path.+ "model_kwargs": {"torch_dtype": self._compute_precision},+ "enable_chunked_prefill": False,+ "max_batch_size": self._max_batch_size,+ "max_beam_width": 1,+ "max_input_len": self._max_input_len,+ "max_num_tokens": self._max_num_tokens,+ "max_seq_len": self._max_seq_length,+ "encoder_max_batch_size": self._max_batch_size,+ "encoder_max_num_tokens": self._encoder_max_num_tokens,+ # rc24 default-constructs decoder graphs when this key is absent;+ # explicit null is the only supported way to disable them.+ "cuda_graph_config": decoder_graph_config,+ "encoder_cuda_graph_config": encoder_graph_config,+ "enable_encoder_decoder_mixed_cuda_graph": self._enable_encoder_decoder_mixed_cuda_graph,+ "disable_overlap_scheduler": self._disable_overlap_scheduler,+ "kv_cache_config": {+ "enable_block_reuse": False,+ "free_gpu_memory_fraction": self._kv_cache_fraction,+ "cross_kv_cache_fraction": self._cross_kv_fraction,+ "use_kv_cache_manager_v2": False,+ },+ "scheduler_config": {"use_python_scheduler": True},+ }++ def load(self, device: str) -> None:+ device_index = _server.parse_cuda_device_index(device)+ self._device = device+ try:+ self._port = _server.reserve_port()+ self._tokenizer = self._load_tokenizer()+ self._server_url = f"http://127.0.0.1:{self._port}"+ with tempfile.NamedTemporaryFile(+ mode="w", prefix="trtllm_", suffix=".json", encoding="utf-8", delete=False+ ) as config_file:+ json.dump(self.runtime_config, config_file, sort_keys=True)+ config_file.write("\n")+ self._config_path = Path(config_file.name)+ self._output_file = _server.open_output_log()+ command = [+ "trtllm-serve",+ self._model_name_or_path,+ "--backend",+ "pytorch",+ "--host",+ "127.0.0.1",+ "--port",+ str(self._port),+ "--config",+ str(self._config_path),+ "--hf_revision",+ self._revision,+ "--served_model_name",+ self._served_model_name,+ "--no-telemetry",+ ]+ compat_dir = Path(__file__).with_name("_compat")+ inherited_pythonpath = os.environ.get("PYTHONPATH")+ pythonpath = os.pathsep.join(str(path) for path in (compat_dir, inherited_pythonpath) if path)+ self._process = _server.launch(+ command,+ device_index=device_index,+ output_file=self._output_file,+ environment={+ "PYTHONPATH": pythonpath,+ "SIE_TRTLLM_RC24_COMPAT": "1",+ },+ )+ _server.wait_until_ready(+ self._process,+ self._server_url,+ served_model_name=self._served_model_name,+ output_file=self._output_file,+ timeout_s=self._startup_timeout_s,+ )+ self._generation_draining = False+ except BaseException:+ self._teardown_child()+ raise++ def _load_tokenizer(self) -> Any:+ install_transformers_5_t5_tokenizer_compatibility()+ return AutoTokenizer.from_pretrained(+ self._model_name_or_path,+ revision=self._revision,+ trust_remote_code=False,+ )++ def _check_loaded(self) -> str:+ if self._server_url is None or self._process is None or self._tokenizer is None:+ raise RuntimeError(ERR_NOT_LOADED)+ return self._server_url++ def _count_prompt_tokens(self, prompt: str) -> int:+ tokenizer = self._tokenizer+ if tokenizer is None:+ raise RuntimeError(ERR_NOT_LOADED)+ try:+ token_ids = tokenizer.encode(+ prompt,+ add_special_tokens=self.prompt_tokenization_add_special_tokens,+ )+ except Exception as exc:+ raise RuntimeError("TensorRT-LLM encoder prompt tokenization failed") from exc+ if (+ not isinstance(token_ids, list)+ or not token_ids+ or any(+ isinstance(token_id, bool) or not isinstance(token_id, int) or token_id < 0 for token_id in token_ids+ )+ ):+ raise RuntimeError("TensorRT-LLM encoder prompt tokenization returned invalid token ids")+ return len(token_ids)++ def _ensure_generation_accepting(self) -> None:+ if self._generation_draining:+ raise GenerationDrainingError("TensorRT-LLM generation is draining")++ @staticmethod+ def _normalize_generate_parameters(parameters: Mapping[str, Any]) -> dict[str, Any]:+ normalized: dict[str, Any] = {+ "temperature": 1.0,+ "top_p": 1.0,+ "stop": None,+ "frequency_penalty": None,+ "presence_penalty": None,+ "top_k": None,+ "repetition_penalty": None,+ "min_new_tokens": None,+ "grammar": None,+ "seed": None,+ "logit_bias": None,+ "logprobs": False,+ "top_logprobs": None,+ "n": None,+ "best_of": None,+ "stream": False,+ "lora_path": None,+ "images": None,+ }+ normalized.update(parameters)+ return normalized++ def _validate_generate_parameters(self, parameters: Mapping[str, Any]) -> tuple[dict[str, Any], int]:+ normalized = self._normalize_generate_parameters(parameters)+ prompt = normalized.get("prompt")+ if not isinstance(prompt, str) or not prompt:+ raise GenerationInvalidRequestError("prompt", "prompt must be a non-empty string")+ max_new_tokens = normalized.get("max_new_tokens")+ if isinstance(max_new_tokens, bool) or not isinstance(max_new_tokens, int) or max_new_tokens <= 0:+ raise GenerationInvalidRequestError(+ "max_new_tokens",+ "max_new_tokens must be an integer > 0",+ )+ if normalized.get("grammar") is not None:+ raise GenerationUnsupportedFieldError("grammar")+ if normalized.get("images"):+ raise GenerationUnsupportedFieldError("images")+ if normalized.get("lora_path"):+ raise GenerationUnsupportedFieldError(+ "lora_path",+ "'lora_adapter' is not supported by this generation backend",+ )+ if normalized.get("n") not in (None, 1):+ raise GenerationUnsupportedFieldError("n", "TensorRT-LLM completions support n=1 only")+ if normalized.get("best_of") not in (None, 1):+ raise GenerationUnsupportedFieldError(+ "best_of",+ "TensorRT-LLM completions support best_of=1 only",+ )+ if normalized.get("top_logprobs") is not None and not normalized.get("logprobs", False):+ raise GenerationInvalidRequestError("top_logprobs", "top_logprobs requires logprobs=true")+ min_new_tokens = normalized.get("min_new_tokens")+ if min_new_tokens is not None and min_new_tokens > max_new_tokens:+ raise GenerationInvalidRequestError(+ "min_new_tokens",+ "min_new_tokens must not exceed max_new_tokens",+ )+ prompt_token_count = self._count_prompt_tokens(prompt)+ if prompt_token_count > self._max_input_len:+ raise GenerationInputTooLongError(+ f"prompt token count ({prompt_token_count}) exceeds max_input_len ({self._max_input_len})"+ )+ return normalized, prompt_token_count++ def preflight_generate(+ self,+ parameters: Mapping[str, Any],+ *,+ stream: bool,+ ) -> GenerationPreflightResult:+ """Reject unsupported or oversized requests before shared admission."""+ _ = stream # TensorRT streams internally for buffered and SSE callers.+ self._ensure_generation_accepting()+ self._check_loaded()+ normalized, prompt_token_count = self._validate_generate_parameters(parameters)+ return GenerationPreflightResult(self, normalized, prompt_token_count)++ def _begin_generation(self) -> None:+ self._ensure_generation_accepting()+ self._active_generations += 1+ if self._generation_idle is not None:+ self._generation_idle.clear()++ def _finish_generation(self) -> None:+ self._active_generations -= 1+ if self._active_generations == 0 and self._generation_idle is not None:+ self._generation_idle.set()++ async def drain_generation(self) -> None:+ """Close admission, await in-flight streams, then close the client."""+ self._generation_draining = True+ if self._active_generations:+ if self._generation_idle is None:+ self._generation_idle = asyncio.Event()+ self._generation_idle.clear()+ await self._generation_idle.wait()+ await self.aclose_client()++ async def _get_or_create_http_client(self) -> httpx.AsyncClient:+ if self._http_client is not None:+ return self._http_client+ if self._http_client_lock is None:+ with self._http_client_init_lock:+ if self._http_client_lock is None:+ self._http_client_lock = asyncio.Lock()+ async with self._http_client_lock:+ if self._http_client is None:+ self._http_client = httpx.AsyncClient(+ timeout=httpx.Timeout(+ connect=_CONNECT_TIMEOUT_S,+ read=_READ_TIMEOUT_S,+ write=_WRITE_TIMEOUT_S,+ pool=_POOL_TIMEOUT_S,+ ),+ limits=httpx.Limits(max_connections=256, max_keepalive_connections=128),+ http2=False,+ )+ return self._http_client++ async def aclose_client(self) -> None:+ pending = self._pending_aclose+ if pending is not None:+ with contextlib.suppress(Exception):+ await asyncio.wait_for(asyncio.shield(pending), timeout=_CLIENT_CLOSE_TIMEOUT_S)+ client = self._http_client+ if client is None:+ return+ self._http_client = None+ with contextlib.suppress(Exception):+ await asyncio.wait_for(client.aclose(), timeout=_CLIENT_CLOSE_TIMEOUT_S)++ def _teardown_child(self) -> None:+ self._generation_draining = True+ try:+ _server.terminate(self._process)+ finally:+ self._process = None+ self._tokenizer = None+ _server.release_port(self._port)+ self._port = None+ self._server_url = None+ self._device = None+ if self._output_file is not None:+ with contextlib.suppress(OSError):+ self._output_file.close()+ with contextlib.suppress(OSError):+ Path(self._output_file.name).unlink()+ self._output_file = None+ if self._config_path is not None:+ with contextlib.suppress(OSError):+ self._config_path.unlink()+ self._config_path = None++ def _clear_pending_aclose(self, task: asyncio.Task[None]) -> None:+ if self._pending_aclose is task:+ self._pending_aclose = None++ def unload(self) -> None:+ self._generation_draining = True+ client = self._http_client+ self._http_client = None+ if client is not None:+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError:+ loop = None+ if loop is not None:+ task = loop.create_task(client.aclose())+ self._pending_aclose = task+ task.add_done_callback(self._clear_pending_aclose)+ else:+ with contextlib.suppress(Exception):+ asyncio.run(asyncio.wait_for(client.aclose(), timeout=_CLIENT_CLOSE_TIMEOUT_S))+ self._teardown_child()++ def memory_footprint(self) -> int:+ return 0++ def load_required_memory_bytes(self, *, device_type: str, device_total_bytes: int) -> int | None:+ if device_type != "cuda" or device_total_bytes <= 0:+ return None+ return min(int(device_total_bytes * self._kv_cache_fraction) + 1024**3, device_total_bytes)++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float = 1.0,+ top_p: float = 1.0,+ stop: list[str] | None = None,+ frequency_penalty: float | None = None,+ presence_penalty: float | None = None,+ top_k: int | None = None,+ repetition_penalty: float | None = None,+ min_new_tokens: int | None = None,+ grammar: GrammarSpec | None = None,+ seed: int | None = None,+ logit_bias: dict[str, float] | None = None,+ logprobs: bool = False,+ top_logprobs: int | None = None,+ n: int | None = None,+ best_of: int | None = None,+ stream: bool = False,+ lora_path: str | None = None,+ images: list[ImageInput] | None = None,+ ) -> AsyncIterator[GenerationChunk]:+ parameters: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "repetition_penalty": repetition_penalty,+ "min_new_tokens": min_new_tokens,+ "grammar": grammar,+ "seed": seed,+ "logit_bias": logit_bias,+ "logprobs": logprobs,+ "top_logprobs": top_logprobs,+ "n": n,+ "best_of": best_of,+ "stream": stream,+ "lora_path": lora_path,+ "images": images,+ }+ self._ensure_generation_accepting()+ server_url = self._check_loaded()+ normalized = self._normalize_generate_parameters(parameters)+ preflight_prompt_token_count = consume_generation_preflight(self, normalized)+ if isinstance(preflight_prompt_token_count, int):+ prompt_token_count = preflight_prompt_token_count+ else:+ _, prompt_token_count = self._validate_generate_parameters(parameters)+ self._begin_generation()++ request: dict[str, Any] = {+ "model": self._served_model_name,+ "prompt": prompt,+ "max_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stream": True,+ "stream_options": {"include_usage": True},+ "n": 1,+ }+ optional = {+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "repetition_penalty": repetition_penalty,+ "min_tokens": min_new_tokens,+ "seed": seed,+ "logit_bias": logit_bias,+ }+ request.update({name: value for name, value in optional.items() if value is not None})+ if logprobs:+ request["logprobs"] = top_logprobs if top_logprobs is not None else 1++ completion: AsyncIterator[GenerationChunk] | None = None+ terminal_outcome_selected = False+ try:+ completion = self._stream_completion(+ server_url,+ request,+ logprobs_requested=logprobs,+ prompt_token_count=prompt_token_count,+ )+ async for chunk in completion:+ if chunk.done:+ terminal_outcome_selected = True+ yield chunk+ finally:+ try:+ if completion is not None:+ await aclose_with_error_precedence(+ completion,+ outcome_selected=terminal_outcome_selected,+ context="TensorRT-LLM completion iterator",+ )+ finally:+ self._finish_generation()++ async def _stream_completion(+ self,+ server_url: str,+ request: dict[str, Any],+ *,+ logprobs_requested: bool,+ prompt_token_count: int,+ ) -> AsyncGenerator[GenerationChunk]:+ client = await self._get_or_create_http_client()+ finish_reason: FinishReason | None = None+ usage_completion_tokens: int | None = None+ first_text_emitted = False+ saw_done = False++ async with client.stream("POST", f"{server_url}/v1/completions", json=request) as response:+ if response.status_code != 200:+ await response.aread()+ response.raise_for_status()+ async for raw_line in response.aiter_lines():+ line = raw_line.strip()+ if not line:+ continue+ if not line.startswith("data:"):+ raise RuntimeError("TensorRT-LLM completion stream emitted a non-SSE line")+ data = line.removeprefix("data:").strip()+ if data == "[DONE]":+ if finish_reason is None or usage_completion_tokens is None:+ raise RuntimeError("TensorRT-LLM completion ended without finish reason and usage")+ saw_done = True+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=finish_reason,+ prompt_tokens=prompt_token_count,+ completion_tokens=usage_completion_tokens,+ )+ break+ try:+ event = json.loads(data)+ except json.JSONDecodeError as exc:+ raise RuntimeError("TensorRT-LLM completion stream emitted invalid JSON") from exc+ if not isinstance(event, Mapping):+ raise RuntimeError("TensorRT-LLM completion stream event must be an object")+ if "error" in event:+ error = event["error"]+ message = error.get("message") if isinstance(error, Mapping) else error+ raise RuntimeError(f"TensorRT-LLM completion error: {str(message)[:500]}")++ choices = event.get("choices")+ if not isinstance(choices, list):+ raise RuntimeError("TensorRT-LLM completion event is missing choices")+ if choices:+ if len(choices) != 1 or not isinstance(choices[0], Mapping) or choices[0].get("index", 0) != 0:+ raise RuntimeError("TensorRT-LLM completion emitted unsupported multiple choices")+ choice = choices[0]+ text = choice.get("text", "")+ if not isinstance(text, str):+ raise RuntimeError("TensorRT-LLM completion text must be a string")+ event_finish = choice.get("finish_reason")+ if event_finish is not None:+ if event_finish not in {"stop", "length"}:+ raise RuntimeError(f"unsupported TensorRT-LLM finish reason {event_finish!r}")+ if finish_reason is not None:+ raise RuntimeError("TensorRT-LLM completion emitted multiple finish reasons")+ finish_reason = cast("FinishReason", event_finish)+ if text:+ if finish_reason is not None and event_finish is None:+ raise RuntimeError("TensorRT-LLM emitted text after its terminal choice")+ choice_logprobs = _completion_logprobs(choice.get("logprobs"))+ if logprobs_requested and choice_logprobs is None:+ raise RuntimeError("TensorRT-LLM omitted requested completion logprobs")+ yield GenerationChunk(+ text_delta=text,+ is_first=not first_text_emitted,+ logprobs=choice_logprobs,+ )+ first_text_emitted = True++ event_usage = event.get("usage")+ if event_usage is not None:+ if usage_completion_tokens is not None or not isinstance(event_usage, Mapping):+ raise RuntimeError("TensorRT-LLM completion emitted invalid duplicate usage")+ child_prompt_tokens = event_usage.get("prompt_tokens")+ child_completion_tokens = event_usage.get("completion_tokens")+ if (+ isinstance(child_prompt_tokens, bool)+ or not isinstance(child_prompt_tokens, int)+ or child_prompt_tokens < 0+ or isinstance(child_completion_tokens, bool)+ or not isinstance(child_completion_tokens, int)+ or child_completion_tokens < 0+ ):+ raise RuntimeError("TensorRT-LLM completion usage is invalid")+ # rc24 reports its internal decoder prefix here for+ # encoder-decoder models. Validate the wire shape, but only+ # the local encoder count is prompt-usage authority.+ usage_completion_tokens = child_completion_tokens++ if not saw_done:+ raise RuntimeError("TensorRT-LLM completion stream ended before [DONE]")diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.pyindex 3aa407e44..b49cc15a1 100644--- a/packages/sie_server/src/sie_server/api/encode.py+++ b/packages/sie_server/src/sie_server/api/encode.py@@ -394,7 +394,7 @@ async def encode(except ValueError as e:raise error_handler.handle_value_error(e) from eexcept Exception as e:- raise error_handler.handle_inference_error(e) from e+ raise error_handler.handle_inference_error(e, "Encoding") from e# Build response (quantization already done by postprocessor)response_items = _build_response_items(items, results, config)diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.pyindex 860f5dc82..60bcc7a61 100644--- a/packages/sie_server/src/sie_server/api/generate.py+++ b/packages/sie_server/src/sie_server/api/generate.py@@ -52,7 +52,7 @@ import uuidfrom collections.abc import AsyncIteratorfrom functools import lru_cachefrom pathlib import Path-from typing import Annotated, Any, cast+from typing import TYPE_CHECKING, Annotated, Any, castfrom fastapi import APIRouter, Header, HTTPException, Request, statusfrom fastapi.responses import JSONResponse, StreamingResponse@@ -60,14 +60,25 @@ from sie_sdk.queue_types import denormalize_model_idfrom sie_server.adapters._generation_base import (GenerationAdapter,+ GenerationCapacityError,+ GenerationDrainingError,+ GenerationError,+ GenerationInputTooLongError,+ GenerationInvalidRequestError,+ GenerationPreflightResult,+ GenerationUnsupportedFieldError,ReasoningFormat,+ aclose_with_error_precedence,+ client_safe_generation_error_code,+ client_safe_generation_error_message,+ client_safe_generation_error_param,collect_generation,reasoning_starts_in_prompt,resolve_reasoning_format,suppress_thinking_blocks,thinking_blocks_must_be_hidden,)-from sie_server.api.helpers import ModelStateChecker+from sie_server.api.helpers import ModelStateChecker, oom_retry_after_from_registryfrom sie_server.api.validation import validate_machine_profile_header, validate_signed_i64from sie_server.core.runtime_options import apply_generation_runtime_optionsfrom sie_server.core.tokenizer import image_first_chat_message, load_tokenizer@@ -81,8 +92,13 @@ from sie_server.types.openapi import ()from sie_server.types.responses import ErrorCode+if TYPE_CHECKING:+ from sie_server.core.registry import ModelRegistry+logger = logging.getLogger(__name__)+_MAX_RETRY_AFTER_S = 60+router = APIRouter(prefix="/v1", tags=["generate"])@@ -668,6 +684,79 @@ async def _read_bounded_request_body(request: Request, limit: int) -> bytes:return bytes(body)+def _generation_http_exception(error: GenerationError, registry: ModelRegistry | None = None) -> HTTPException:+ """Map an expected adapter refusal without rewriting it as a 500."""+ if isinstance(+ error,+ GenerationUnsupportedFieldError | GenerationInvalidRequestError | GenerationInputTooLongError,+ ):+ return _bad_request(+ client_safe_generation_error_message(error.code, str(error)),+ param=client_safe_generation_error_param(error),+ code=client_safe_generation_error_code(error.code),+ )+ if isinstance(error, GenerationCapacityError):+ retry_after = (+ "5" if isinstance(error, GenerationDrainingError) else str(oom_retry_after_from_registry(registry))+ )+ return HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "code": client_safe_generation_error_code(error.code),+ "message": client_safe_generation_error_message(error.code, str(error)),+ },+ headers={"Retry-After": retry_after},+ )+ return HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={+ "code": "inference_error",+ "message": client_safe_generation_error_message("inference_error", str(error)),+ },+ )+++def _native_adapter_generate_parameters(+ *,+ prompt: str,+ max_new_tokens: int,+ temperature: float,+ top_p: float,+ stop: list[str] | None,+ frequency_penalty: float | None,+ presence_penalty: float | None,+ top_k: int | None,+ min_new_tokens: int | None,+ grammar: GrammarSpec | None,+ seed: int | None,+ logit_bias: dict[str, float] | None,+ logprobs: bool,+ top_logprobs: int | None,+ images: list[ImageInput] | None,+) -> dict[str, Any]:+ """Build the exact native adapter kwargs used for preflight and dispatch."""+ values: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stop": stop,+ "frequency_penalty": frequency_penalty,+ "presence_penalty": presence_penalty,+ "top_k": top_k,+ "min_new_tokens": min_new_tokens,+ "seed": seed,+ "logit_bias": logit_bias,+ "logprobs": logprobs,+ "top_logprobs": top_logprobs,+ }+ if grammar is not None:+ values["grammar"] = grammar+ if images is not None:+ values["images"] = images+ return values++async def _stream_generate_events(adapter: GenerationAdapter,*,@@ -689,6 +778,9 @@ async def _stream_generate_events(thinking_starts_in_prompt: bool = False,reasoning_format: ReasoningFormat = "qwen3",images: list[ImageInput] | None = None,+ generation_parameters: dict[str, Any] | None = None,+ preflight_result: GenerationPreflightResult | None = None,+ oom_retry_after_s: int = 5,) -> AsyncIterator[str]:"""Yield SIE-native ``GenerateChunk`` SSE lines for ``SIEClient.stream_generate``.@@ -708,14 +800,12 @@ async def _stream_generate_events(prompt_tokens = 0completion_tokens = 0saw_terminal = False- terminal_error: dict[str, str] | None = None- optional_adapter_inputs: dict[str, Any] = {}- if grammar is not None:- optional_adapter_inputs["grammar"] = grammar- if images is not None:- optional_adapter_inputs["images"] = images+ terminal_error: dict[str, Any] | None = None+ terminal_outcome_selected = False+ cleanup_failed = False+ chunks: AsyncIterator[Any] | None = Nonetry:- chunks = adapter.generate(+ parameters = generation_parameters or _native_adapter_generate_parameters(prompt=prompt,max_new_tokens=max_new_tokens,temperature=temperature,@@ -729,8 +819,19 @@ async def _stream_generate_events(logit_bias=logit_bias,logprobs=logprobs,top_logprobs=top_logprobs,- **optional_adapter_inputs,+ grammar=grammar,+ images=images,)+ if preflight_result is None:+ # Keep this lower-level shaper compatible with the deliberately+ # duck-typed generation contract used by direct callers and+ # lifecycle tests. The real endpoint always supplies its explicit+ # preflight result when an adapter produced one.+ chunks = adapter.generate(**parameters)+ else:+ # A non-null result is request-owned evidence and must be consumed+ # by the adapter-bound bridge; never bypass it via ``generate``.+ chunks = adapter.generate_with_preflight(parameters, preflight_result)if suppress_thinking:chunks = suppress_thinking_blocks(chunks,@@ -744,8 +845,8 @@ async def _stream_generate_events(if chunk.error_code is not None or chunk.error_message is not None or finish_reason == "error":finish_reason = "error"terminal_error = {- "code": chunk.error_code or "inference_error",- "message": chunk.error_message or "generation terminated with an upstream error",+ "code": client_safe_generation_error_code(chunk.error_code),+ "message": client_safe_generation_error_message(chunk.error_code, chunk.error_message),}if chunk.prompt_tokens is not None:prompt_tokens = chunk.prompt_tokens@@ -781,7 +882,36 @@ async def _stream_generate_events(event["logprobs"] = list(chunk.logprobs)seq += 1yield f"data: {json.dumps(event)}\n\n"+ except GenerationError as exc:+ terminal_outcome_selected = True+ logger.info("stream_generate refused after preflight: %s", exc)+ error: dict[str, Any] = {+ "code": client_safe_generation_error_code(exc.code),+ "message": client_safe_generation_error_message(exc.code, str(exc)),+ }+ if (param := client_safe_generation_error_param(exc)) is not None:+ error["param"] = param+ if (+ isinstance(exc, GenerationCapacityError)+ and not isinstance(exc, GenerationDrainingError)+ and isinstance(oom_retry_after_s, int)+ and not isinstance(oom_retry_after_s, bool)+ and 1 <= oom_retry_after_s <= _MAX_RETRY_AFTER_S+ ):+ error["retry_after_s"] = oom_retry_after_s+ err = {+ "request_id": request_id,+ "seq": seq,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": error,+ }+ yield f"data: {json.dumps(err)}\n\n"+ yield "data: [DONE]\n\n"+ returnexcept Exception: # noqa: BLE001 — surface as a terminal error chunk, never 500 mid-stream+ terminal_outcome_selected = Truelogger.warning("stream_generate failed mid-stream", exc_info=True)err = {"request_id": request_id,@@ -796,8 +926,31 @@ async def _stream_generate_events(yield f"data: {json.dumps(err)}\n\n"yield "data: [DONE]\n\n"return+ finally:+ # Close the iterator actually driven above on every exit path. When+ # thinking suppression is active this closes the wrapper, whose own+ # ``finally`` closes the upstream adapter iterator; otherwise it+ # closes the adapter iterator directly. This is deliberately tied to+ # the effective iterator so normal terminal ``break``, adapter errors,+ # and consumer cancellation all reach backend teardown exactly once.+ if chunks is not None:+ try:+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal_outcome_selected or saw_terminal,+ context="native generate effective iterator",+ )+ except Exception: # noqa: BLE001 - establish the native terminal error contract below+ cleanup_failed = True+ logger.warning("stream_generate iterator cleanup failed", exc_info=True)- if not saw_terminal:+ if cleanup_failed:+ finish_reason = "error"+ terminal_error = {+ "code": "inference_error",+ "message": "internal error during generation cleanup",+ }+ elif not saw_terminal:finish_reason = "error"terminal_error = {"code": "inference_error",@@ -1056,6 +1209,12 @@ async def generate(stream_raw = body.get("stream", False)if stream_raw is not None and not isinstance(stream_raw, bool):raise _bad_request("'stream' must be a boolean", param="stream")+ if stream_raw and not gen_task.capabilities.streaming:+ raise _bad_request(+ f"Model '{model}' does not support streaming generation",+ param="stream",+ code="unsupported_field",+ )for field in ("logprobs", "top_logprobs"):if not stream_raw and body.get(field) is not None:raise _bad_request(@@ -1086,6 +1245,39 @@ async def generate(reasoning_format,)+ generation_parameters = _native_adapter_generate_parameters(+ prompt=generation_prompt,+ max_new_tokens=max_new_tokens,+ temperature=temperature,+ top_p=top_p,+ stop=stop,+ frequency_penalty=frequency_penalty,+ presence_penalty=presence_penalty,+ top_k=top_k,+ min_new_tokens=min_new_tokens,+ grammar=grammar,+ seed=seed,+ logit_bias=logit_bias,+ logprobs=logprobs,+ top_logprobs=top_logprobs,+ images=images,+ )+ if not stream_raw:+ # Preserve the historical blocking-call signature: logprob+ # controls are streaming-only and were absent, not false/null.+ generation_parameters.pop("logprobs")+ generation_parameters.pop("top_logprobs")+ try:+ preflight_result = adapter.preflight_generate(generation_parameters, stream=bool(stream_raw))+ except GenerationError as exc:+ raise _generation_http_exception(exc, registry) from exc+ except Exception as exc:+ logger.warning("generation preflight failed for %s", model, exc_info=True)+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={"code": "inference_error", "message": "internal error during generation preflight"},+ ) from exc+if stream_raw:return StreamingResponse(_stream_generate_events(@@ -1108,6 +1300,9 @@ async def generate(thinking_starts_in_prompt=thinking_starts_in_prompt,reasoning_format=reasoning_format,images=images,+ generation_parameters=generation_parameters,+ preflight_result=preflight_result,+ oom_retry_after_s=oom_retry_after_from_registry(registry),),media_type="text/event-stream",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},@@ -1118,25 +1313,7 @@ async def generate(# local-dev route keeps the walking-skeleton's blocking response shape# for backwards compatibility — drain the iterator into an# aggregate. SDK / gateway consume the iterator directly.- optional_adapter_inputs: dict[str, Any] = {}- if grammar is not None:- optional_adapter_inputs["grammar"] = grammar- if images is not None:- optional_adapter_inputs["images"] = images- chunks = adapter.generate(- prompt=generation_prompt,- max_new_tokens=max_new_tokens,- temperature=temperature,- top_p=top_p,- stop=stop,- frequency_penalty=frequency_penalty,- presence_penalty=presence_penalty,- top_k=top_k,- min_new_tokens=min_new_tokens,- seed=seed,- logit_bias=logit_bias,- **optional_adapter_inputs,- )+ chunks = adapter.generate_with_preflight(generation_parameters, preflight_result)if suppress_thinking:chunks = suppress_thinking_blocks(chunks,@@ -1144,11 +1321,13 @@ async def generate(reasoning_format=reasoning_format,)result = await collect_generation(chunks)+ except GenerationError as exc:+ raise _generation_http_exception(exc, registry) from excexcept Exception as e:logger.warning("generate failed for %s", model, exc_info=True)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail={"code": "inference_error", "message": str(e)},+ detail={"code": "inference_error", "message": "internal error during generation"},) from e# A stream that finished cleanly may still carry a *terminal* error /@@ -1168,14 +1347,14 @@ async def generate(if result.finish_reason == "error" or result.error_code is not None:logger.warning("generate produced terminal error code=%s for %s",- result.error_code or "inference_error",+ client_safe_generation_error_code(result.error_code),model,)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail={- "code": result.error_code or "inference_error",- "message": result.error_message or "generation terminated with an upstream error",+ "code": client_safe_generation_error_code(result.error_code),+ "message": client_safe_generation_error_message(result.error_code, result.error_message),},)if result.finish_reason == "cancelled":diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.pyindex f24386055..2d83abc19 100644--- a/packages/sie_server/src/sie_server/api/helpers.py+++ b/packages/sie_server/src/sie_server/api/helpers.py@@ -607,7 +607,7 @@ class InferenceErrorHandler:status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail={"code": ErrorCode.INFERENCE_ERROR.value,- "message": f"{operation} error: {error}",+ "message": f"internal error during {operation.lower()}",},)diff --git a/packages/sie_server/src/sie_server/api/models.py b/packages/sie_server/src/sie_server/api/models.pyindex 759d25af7..2b3998910 100644--- a/packages/sie_server/src/sie_server/api/models.py+++ b/packages/sie_server/src/sie_server/api/models.py@@ -62,6 +62,7 @@ class ModelCapabilities(BaseModel):alias)."""+ streaming: bool = Truegrammar: list[str] = []tools: bool = Falsecode: bool = False@@ -156,6 +157,7 @@ def _resolve_capabilities(config: Any) -> ModelCapabilities | None:return Nonecaps = generate.capabilitiesreturn ModelCapabilities(+ streaming=caps.streaming,grammar=list(caps.grammar),tools=caps.tools,code=caps.code,diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex 7248e194b..ddfac76e2 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -620,7 +620,7 @@ async def _create_embeddings(detail={"error": {"code": "inference_error",- "message": f"Inference error: {e}",+ "message": "internal error during embeddings","type": "server_error",}},diff --git a/packages/sie_server/src/sie_server/api/openai_completions.py b/packages/sie_server/src/sie_server/api/openai_completions.pyindex ae5e2db31..262de3f73 100644--- a/packages/sie_server/src/sie_server/api/openai_completions.py+++ b/packages/sie_server/src/sie_server/api/openai_completions.py@@ -30,11 +30,16 @@ from sie_sdk.queue_types import denormalize_model_idfrom sie_server.adapters._generation_base import (GenerationAdapter,GenerationChunk,+ GenerationError,+ aclose_with_error_precedence,+ client_safe_generation_error_code,+ client_safe_generation_error_message,reasoning_starts_in_prompt,resolve_reasoning_format,suppress_thinking_blocks,thinking_blocks_must_be_hidden,)+from sie_server.api.generate import _generation_http_exceptionfrom sie_server.api.helpers import ModelStateChecker, check_sdk_versionfrom sie_server.api.validation import validate_machine_profile_header, validate_signed_i64from sie_server.core.runtime_options import apply_generation_runtime_options@@ -49,6 +54,7 @@ _MAX_COMPLETIONS_BODY_BYTES = int(os.environ.get("SIE_GENERATE_MAX_BODY_BYTES",_MAX_PROMPT_BYTES = int(os.environ.get("SIE_GENERATE_MAX_PROMPT_BYTES", str(4 * 1024 * 1024)))_MAX_U32 = (1 << 32) - 1_MAX_F32 = 3.4028234663852886e38+_MAX_RETRY_AFTER_S = 60_SUPPORTED_FIELDS = frozenset({"model",@@ -143,6 +149,22 @@ def _from_http_exception(exc: HTTPException) -> _CompletionError:)+def _from_generation_error(error: GenerationError, registry: Any) -> _CompletionError:+ """Preserve the native generation error contract on compatibility routes."""+ return _from_http_exception(_generation_http_exception(error, registry))+++def _validated_retry_after_s(error: _CompletionError) -> int | None:+ """Read the trusted direct-route retry authority for in-band SSE use."""+ if error.code != "RESOURCE_EXHAUSTED" or error.headers is None:+ return None+ raw = error.headers.get("Retry-After")+ if raw is None or not raw.isascii() or not raw.isdecimal():+ return None+ value = int(raw)+ return value if 1 <= value <= _MAX_RETRY_AFTER_S else None++async def _read_json_body(request: Request) -> dict[str, Any]:content_length = request.headers.get("content-length")if content_length is not None:@@ -371,19 +393,27 @@ async def _stream_completion(created: int,model: str,include_usage: bool,+ registry: Any,) -> AsyncIterator[str]:terminal: GenerationChunk | None = None+ terminal_outcome_selected = False+ cleanup_failed = Falsetry:async for chunk in chunks:if chunk.done:terminal = chunkcancelled = chunk.done and chunk.finish_reason == "cancelled"+ errored = chunk.done and (+ chunk.finish_reason == "error" or chunk.error_code is not None or chunk.error_message is not None+ )body = _chunk_body(completion_id=completion_id,created=created,model=model,text=chunk.text_delta,- finish_reason=None if cancelled else (_finish_reason(chunk.finish_reason) if chunk.done else None),+ finish_reason=(+ None if cancelled or errored else (_finish_reason(chunk.finish_reason) if chunk.done else None)+ ),)if cancelled:body["error"] = {@@ -392,46 +422,80 @@ async def _stream_completion("param": None,"code": "generation_cancelled",}- elif chunk.done and (chunk.finish_reason == "error" or chunk.error_code or chunk.error_message):+ elif errored:body["error"] = {- "message": chunk.error_message or "generation terminated with an upstream error",+ "message": client_safe_generation_error_message(chunk.error_code, chunk.error_message),"type": "server_error","param": None,- "code": chunk.error_code or "inference_error",+ "code": client_safe_generation_error_code(chunk.error_code),}yield f"data: {json.dumps(body)}\n\n"if chunk.done:break- except Exception: # noqa: BLE001 - the stream must terminate in-band after headers are committed- logger.warning("OpenAI completion failed mid-stream", exc_info=True)+ except Exception as exc: # noqa: BLE001 - the stream must terminate in-band after headers are committed+ terminal_outcome_selected = True+ if isinstance(exc, GenerationError):+ error = _from_generation_error(exc, registry)+ logger.info("OpenAI completion received typed generation refusal mid-stream: %s", error.code)+ else:+ error = _CompletionError(+ "internal error during generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ )+ logger.warning("OpenAI completion failed mid-stream", exc_info=True)body = _chunk_body(completion_id=completion_id,created=created,model=model,text="",- finish_reason="stop",+ finish_reason=None,)- body["error"] = {- "message": "internal error during generation",- "type": "server_error",- "param": None,- "code": "inference_error",+ error_body: dict[str, Any] = {+ "message": error.message,+ "type": error.error_type,+ "param": error.param,+ "code": error.code,}+ if (retry_after_s := _validated_retry_after_s(error)) is not None:+ error_body["retry_after_s"] = retry_after_s+ body["error"] = error_bodyyield f"data: {json.dumps(body)}\n\n"yield "data: [DONE]\n\n"returnfinally:- aclose = getattr(chunks, "aclose", None)- if aclose is not None:- await aclose()+ try:+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal_outcome_selected or terminal is not None,+ context="OpenAI completion effective iterator",+ )+ except Exception: # noqa: BLE001 - establish the streaming terminal below+ cleanup_failed = True+ logger.warning("OpenAI completion iterator cleanup failed", exc_info=True)- if terminal is None:+ if cleanup_failed:body = _chunk_body(completion_id=completion_id,created=created,model=model,text="",- finish_reason="stop",+ finish_reason=None,+ )+ body["error"] = {+ "message": "internal error during generation cleanup",+ "type": "server_error",+ "param": None,+ "code": "inference_error",+ }+ yield f"data: {json.dumps(body)}\n\n"+ elif terminal is None:+ body = _chunk_body(+ completion_id=completion_id,+ created=created,+ model=model,+ text="",+ finish_reason=None,)body["error"] = {"message": "generation stream ended before a terminal event",@@ -480,9 +544,11 @@ async def _collect_completion(chunks: AsyncIterator[GenerationChunk]) -> tuple[sterminal = chunkbreakfinally:- aclose = getattr(chunks, "aclose", None)- if aclose is not None:- await aclose()+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal is not None,+ context="buffered OpenAI completion iterator",+ )if terminal is None:raise _CompletionError("generation stream ended before a terminal event",@@ -491,9 +557,9 @@ async def _collect_completion(chunks: AsyncIterator[GenerationChunk]) -> tuple[s)if terminal.finish_reason == "error" or terminal.error_code or terminal.error_message:raise _CompletionError(- terminal.error_message or "generation terminated with an upstream error",+ client_safe_generation_error_message(terminal.error_code, terminal.error_message),status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- code=terminal.error_code or "inference_error",+ code=client_safe_generation_error_code(terminal.error_code),)if terminal.finish_reason == "cancelled":raise _CompletionError(@@ -558,6 +624,12 @@ async def completions(param="model",code="model_not_found",)+ if params.stream and not generate_task.capabilities.streaming:+ raise _CompletionError(+ f"Model '{params.model}' does not support streaming generation",+ param="stream",+ code="unsupported_field",+ )if params.max_tokens > generate_task.max_output_tokens:raise _CompletionError(f"max_tokens ({params.max_tokens}) exceeds model cap ({generate_task.max_output_tokens})",@@ -597,21 +669,37 @@ async def completions(code="inference_error",)+ generation_parameters: dict[str, Any] = {+ "prompt": params.prompt,+ "max_new_tokens": params.max_tokens,+ "temperature": float(runtime_params.get("temperature", 1.0)),+ "top_p": float(runtime_params.get("top_p", 1.0)),+ "stop": runtime_params.get("stop"),+ "frequency_penalty": runtime_params.get("frequency_penalty"),+ "presence_penalty": runtime_params.get("presence_penalty"),+ "top_k": runtime_params.get("top_k"),+ "min_new_tokens": runtime_params.get("min_tokens"),+ "seed": runtime_params.get("seed"),+ }+ try:+ adapter.preflight_generate(generation_parameters, stream=params.stream)+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from exc+ except Exception as exc:+ logger.warning("OpenAI completion preflight failed for %s", params.model, exc_info=True)+ raise _CompletionError(+ "internal error during generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ ) from exc+canonical_model = getattr(config, "name", None) or registry_keycompletion_id = f"cmpl-{uuid.uuid4().hex}"created = int(time.time())- chunks = adapter.generate(- prompt=params.prompt,- max_new_tokens=params.max_tokens,- temperature=float(runtime_params.get("temperature", 1.0)),- top_p=float(runtime_params.get("top_p", 1.0)),- stop=runtime_params.get("stop"),- frequency_penalty=runtime_params.get("frequency_penalty"),- presence_penalty=runtime_params.get("presence_penalty"),- top_k=runtime_params.get("top_k"),- min_new_tokens=runtime_params.get("min_tokens"),- seed=runtime_params.get("seed"),- )+ try:+ chunks = adapter.generate(**generation_parameters)+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from excif thinking_blocks_must_be_hidden(config):reasoning_format = resolve_reasoning_format(config, adapter)chunks = suppress_thinking_blocks(@@ -627,6 +715,7 @@ async def completions(created=created,model=canonical_model,include_usage=params.include_usage,+ registry=registry,),media_type="text/event-stream",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},@@ -636,6 +725,8 @@ async def completions(text, terminal = await _collect_completion(chunks)except _CompletionError:raise+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from excexcept Exception as exc:logger.warning("OpenAI completion failed for %s", params.model, exc_info=True)raise _CompletionError(diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex 5363a1d39..c6bb422b0 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -37,6 +37,7 @@ from sie_sdk.queue_types import denormalize_model_idfrom sie_server.adapters._generation_base import (ReasoningFormat,ThinkingBlockStripper,+ aclose_with_error_precedence,resolve_reasoning_format,thinking_blocks_must_be_hidden,)@@ -687,11 +688,13 @@ async def _sanitize_sse_stream(buffered = bytearray()received = 0saw_done = False+ terminal_outcome_selected = Falsetry:async for chunk in response.aiter_bytes():received += len(chunk)if received > _MAX_CHAT_RESPONSE_BYTES:logger.error("generation child SSE exceeded %d bytes", _MAX_CHAT_RESPONSE_BYTES)+ terminal_outcome_selected = Trueyield _upstream_error_event("upstream response exceeded the byte limit")returnbuffered.extend(chunk)@@ -707,6 +710,7 @@ async def _sanitize_sse_stream(data = line[len(b"data:") :].lstrip()if data == b"[DONE]":saw_done = True+ terminal_outcome_selected = Trueyield b"data: [DONE]\n"continueif not data:@@ -729,21 +733,36 @@ async def _sanitize_sse_stream(line = bytes(buffered).removesuffix(b"\r")if line.startswith(b"data:") and line[len(b"data:") :].lstrip() == b"[DONE]":saw_done = True+ terminal_outcome_selected = Trueyield b"data: [DONE]\n"elif line:raise ValueError("upstream SSE ended with an incomplete event")if not saw_done:logger.warning("generation child SSE ended without [DONE]")+ terminal_outcome_selected = Trueyield _upstream_error_event("upstream stream ended unexpectedly")except (httpx.HTTPError, UnicodeError, ValueError, json.JSONDecodeError):logger.warning("generation child chat proxy stream failed", exc_info=True)if not saw_done:+ terminal_outcome_selected = Trueyield _upstream_error_event()finally:- await response.aclose()- await client.aclose()- if slot is not None:- slot.release()+ try:+ await aclose_with_error_precedence(+ response,+ outcome_selected=terminal_outcome_selected,+ context="generation child SSE response",+ )+ finally:+ try:+ await aclose_with_error_precedence(+ client,+ outcome_selected=terminal_outcome_selected,+ context="generation child SSE client",+ )+ finally:+ if slot is not None:+ slot.release()# -- /v1/chat/completions (proxy to the managed generation child) ------------@@ -822,6 +841,13 @@ async def _chat_completions(raise _bad_request(f"Model '{model}' does not support generation (no generate task). Use a generation model.")+ streaming_supported = getattr(getattr(gen_task, "capabilities", None), "streaming", True)+ if bool(stream_opt) and not streaming_supported:+ raise _bad_request(+ f"Model '{model}' does not support streaming generation",+ param="stream",+ code="unsupported_field",+ )if str(device).startswith("cuda"):_validate_cuda_chat_body(body)else:@@ -1086,7 +1112,7 @@ async def _rerank(logger.warning("rerank failed for %s", model, exc_info=True)raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail={"code": "inference_error", "message": str(exc)},+ detail={"code": "inference_error", "message": "internal error during reranking"},) from excscore_output: ScoreOutput = worker_result.outputdiff --git a/packages/sie_server/src/sie_server/api/openai_responses.py b/packages/sie_server/src/sie_server/api/openai_responses.pyindex 0e3f27854..d4ec37789 100644--- a/packages/sie_server/src/sie_server/api/openai_responses.py+++ b/packages/sie_server/src/sie_server/api/openai_responses.py@@ -19,6 +19,7 @@ from sie_sdk.queue_types import denormalize_model_idfrom sie_server.adapters._generation_base import (GenerationAdapter,+ GenerationError,reasoning_starts_in_prompt,resolve_reasoning_format,suppress_thinking_blocks,@@ -32,6 +33,7 @@ from sie_server.api.openai_completions import (_collect_completion,_CompletionError,_error_response,+ _from_generation_error,_from_http_exception,_number,_read_json_body,@@ -305,18 +307,34 @@ async def responses(code="inference_error",)- chunks = adapter.generate(- prompt=prompt,- max_new_tokens=params.max_output_tokens,- temperature=float(runtime_params.get("temperature", 1.0)),- top_p=float(runtime_params.get("top_p", 1.0)),- stop=runtime_params.get("stop"),- frequency_penalty=runtime_params.get("frequency_penalty"),- presence_penalty=runtime_params.get("presence_penalty"),- top_k=runtime_params.get("top_k"),- min_new_tokens=runtime_params.get("min_tokens"),- seed=runtime_params.get("seed"),- )+ generation_parameters: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": params.max_output_tokens,+ "temperature": float(runtime_params.get("temperature", 1.0)),+ "top_p": float(runtime_params.get("top_p", 1.0)),+ "stop": runtime_params.get("stop"),+ "frequency_penalty": runtime_params.get("frequency_penalty"),+ "presence_penalty": runtime_params.get("presence_penalty"),+ "top_k": runtime_params.get("top_k"),+ "min_new_tokens": runtime_params.get("min_tokens"),+ "seed": runtime_params.get("seed"),+ }+ try:+ adapter.preflight_generate(generation_parameters, stream=False)+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from exc+ except Exception as exc:+ logger.warning("OpenAI Responses preflight failed for %s", params.model, exc_info=True)+ raise _CompletionError(+ "internal error during generation",+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ code="inference_error",+ ) from exc++ try:+ chunks = adapter.generate(**generation_parameters)+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from excif thinking_blocks_must_be_hidden(config):reasoning_format = resolve_reasoning_format(config, adapter)chunks = suppress_thinking_blocks(@@ -328,6 +346,8 @@ async def responses(text, terminal = await _collect_completion(chunks)except _CompletionError:raise+ except GenerationError as exc:+ raise _from_generation_error(exc, registry) from excexcept Exception as exc:logger.warning("OpenAI Responses generation failed for %s", params.model, exc_info=True)raise _CompletionError(diff --git a/packages/sie_server/src/sie_server/api/score.py b/packages/sie_server/src/sie_server/api/score.pyindex 478c649fa..cb412e73a 100644--- a/packages/sie_server/src/sie_server/api/score.py+++ b/packages/sie_server/src/sie_server/api/score.py@@ -273,7 +273,7 @@ async def score(except ValueError as e:raise error_handler.handle_value_error(e) from eexcept Exception as e:- raise error_handler.handle_inference_error(e) from e+ raise error_handler.handle_inference_error(e, "Scoring") from e# Fail closed on non-finite (NaN/inf) model output before it reaches# serialization: JSON would 500 un-enveloped and msgpack would silentlydiff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex 8c2a6fa83..2798e7fbb 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -15,6 +15,10 @@ from sie_server.config.package_artifacts import (has_package_artifact_declaration,parse_package_artifact_declaration,)+from sie_server.config.serving_artifacts import (+ ServingArtifactDeclaration,+ parse_serving_artifact_declaration,+)logger = logging.getLogger(__name__)@@ -26,6 +30,14 @@ _MAX_POOL_NAME_LEN = 128_CHAT_TEMPLATE_KWARGS = frozenset({"enable_thinking", "guardian_config"})_GUARDIAN_CONFIG_KWARGS = frozenset({"risk_name"})_MAX_GUARDIAN_RISK_NAME_LEN = 128+_SERVING_ARTIFACT_PRECISION: dict[str, ComputePrecision] = {+ "bfloat16": "bfloat16",+ "float16": "float16",+ "float32": "float32",+ "int8_bfloat16": "bfloat16",+ "int8_float16": "float16",+ "int8_float32": "float32",+}def validate_chat_template_kwargs(value: dict[str, Any] | None) -> dict[str, Any] | None:@@ -211,9 +223,12 @@ class PrewarmGrammar(BaseModel):class GenerateTask(BaseModel):"""Generation task declaration.- ``context_length`` is the maximum total tokens (prompt + completion) the- model can process. ``max_output_tokens`` is the per-request hard cap on- ``max_new_tokens`` enforced by the gateway.+ ``context_length`` is the maximum shared prompt-plus-completion envelope by+ default. Encoder-decoder adapters may instead declare independent axes, in+ which case it bounds encoder input and ``max_output_tokens`` independently+ caps decoder output. The gateway uses ``max_output_tokens`` for+ pre-admission, and the worker authoritatively enforces it as the per-request+ hard cap on ``max_new_tokens`` before adapter dispatch.``chat_template_kwargs`` are a bounded operator-owned mapping forwardedto the tokenizer's ``apply_chat_template(**kwargs)`` call when the worker@@ -350,6 +365,13 @@ class AdapterOptions(BaseModel):raise ValueError(msg)return self+ @model_validator(mode="after")+ def validate_serving_artifact_shape(self) -> "AdapterOptions":+ # Source identity lives on ModelConfig, so only parse the closed nested+ # declaration and reject loader-owned injection fields at this layer.+ parse_serving_artifact_declaration(self.loadtime)+ return self+class ProfileAdaptiveBatching(BaseModel):"""Per-model adaptive batching overrides.@@ -933,6 +955,42 @@ class ModelConfig(BaseModel):raise ValueError("all profiles of a package-backed model must declare identical package artifacts")return self+ @model_validator(mode="after")+ def validate_serving_artifacts(self) -> "ModelConfig":+ resolved_profiles = {name: self._resolve_profile_uncached(name) for name in self.profiles}+ declarations = {+ name: parse_serving_artifact_declaration(dict(resolved.loadtime))+ for name, resolved in resolved_profiles.items()+ }+ if not any(declarations.values()):+ return self+ if self.package_backed or self.weights_path is not None:+ raise ValueError("derived serving artifacts require an HF source checkpoint")+ if self.hf_id is None or not is_immutable_revision(self.hf_revision):+ raise ValueError("derived serving artifacts require source hf_id and an immutable 40-char hf_revision")+ for name, declaration in declarations.items():+ if declaration is None:+ continue+ # Bare CT2 ``int8`` leaves the floating-point accumulation type to+ # runtime/device selection. Only the explicit compute types can be+ # compared to SIE's declared profile precision without guessing.+ expected_precision = _SERVING_ARTIFACT_PRECISION.get(declaration.compute_type)+ if expected_precision is None:+ continue+ actual_precision = resolved_profiles[name].compute_precision+ if actual_precision is not None and actual_precision != expected_precision:+ raise ValueError(+ f"Profile '{name}' compute_precision={actual_precision!r} does not match "+ f"serving artifact compute_type={declaration.compute_type!r}; "+ f"expected {expected_precision!r}"+ )+ return self++ def serving_artifact_declaration(self, profile: str = "default") -> ServingArtifactDeclaration | None:+ """Return the effective profile's immutable derived-artifact declaration."""+ loadtime = dict(self.resolve_profile(profile).loadtime)+ return parse_serving_artifact_declaration(loadtime)+def _effective_package_artifact_loadtime(self, name: str) -> dict[str, Any]:# Keep artifact validation on the exact same inheritance/replacement# path as adapter construction. Do not duplicate profile resolutiondiff --git a/packages/sie_server/src/sie_server/config/serving_artifacts.py b/packages/sie_server/src/sie_server/config/serving_artifacts.pynew file mode 100644index 000000000..71cc1c77b--- /dev/null+++ b/packages/sie_server/src/sie_server/config/serving_artifacts.py@@ -0,0 +1,574 @@+"""Immutable derived serving-artifact declarations and materialization."""++from __future__ import annotations++import ctypes+import errno+import hashlib+import json+import os+import shutil+import stat+import tempfile+from dataclasses import dataclass+from itertools import pairwise+from pathlib import Path, PurePosixPath+from typing import Literal++from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator++SERVING_ARTIFACT_KEY = "serving_artifact"+SERVING_ARTIFACT_PATH_KEY = "artifact_path"+SERVING_ARTIFACT_COMPUTE_TYPE_KEY = "ct2_compute_type"++SERVING_ARTIFACT_SCHEMA = "sie-ctranslate2-serving-artifact-v1"+CTRANSLATE2_VERSION = "4.8.1"+CTRANSLATE2_TORCH_VERSION = "2.9.1"+CTRANSLATE2_TRANSFORMERS_VERSION = "4.57.6"+CTRANSLATE2_COMPUTE_TYPES = (+ "bfloat16",+ "float16",+ "float32",+ "int8",+ "int8_bfloat16",+ "int8_float16",+ "int8_float32",+)++_SHA256_PATTERN = r"^[0-9a-f]{64}$"+_REVISION_PATTERN = r"^[0-9a-f]{40}$"+_REPO_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}/[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$"+_ROLE_PATTERN = r"^[a-z][a-z0-9_.-]{0,63}$"+_MAX_MANIFEST_BYTES = 8 * 1024 * 1024+_MAX_TOKENIZER_CONFIG_BYTES = 1024 * 1024+_HASH_CHUNK_BYTES = 1024 * 1024+++def _validate_relative_posix_path(value: str, *, label: str) -> str:+ if "\\" in value or value.startswith("/"):+ raise ValueError(f"{label} must be a relative POSIX path")+ segments = value.split("/")+ if any(segment in {"", ".", ".."} for segment in segments):+ raise ValueError(f"{label} must not contain empty, '.' or '..' segments")+ if PurePosixPath(value).is_absolute():+ raise ValueError(f"{label} must be relative")+ return value+++class ServingArtifactDeclaration(BaseModel):+ """Catalog identity of one immutable derived serving repository snapshot."""++ model_config = ConfigDict(extra="forbid", frozen=True)++ format: Literal["ctranslate2"]+ repo_id: str = Field(pattern=_REPO_ID_PATTERN)+ revision: str = Field(pattern=_REVISION_PATTERN)+ manifest_path: str = Field(min_length=1, max_length=1024)+ manifest_sha256: str = Field(pattern=_SHA256_PATTERN)+ compute_type: str = Field(pattern=_ROLE_PATTERN)++ @field_validator("manifest_path")+ @classmethod+ def validate_manifest_path(cls, value: str) -> str:+ return _validate_relative_posix_path(value, label="serving artifact manifest_path")++ @field_validator("compute_type")+ @classmethod+ def validate_compute_type(cls, value: str) -> str:+ if value not in CTRANSLATE2_COMPUTE_TYPES:+ raise ValueError("serving artifact compute_type is unsupported")+ return value+++class ServingArtifactSource(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ hf_id: str = Field(pattern=_REPO_ID_PATTERN)+ hf_revision: str = Field(pattern=_REVISION_PATTERN)+++class ServingArtifactConverter(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ name: Literal["ct2-transformers-converter"]+ version: Literal["4.8.1"]+ torch_version: Literal["2.9.1"]+ transformers_version: Literal["4.57.6"]+ compute_type: str = Field(pattern=_ROLE_PATTERN)+ recipe_sha256: str = Field(pattern=_SHA256_PATTERN)++ @field_validator("compute_type")+ @classmethod+ def validate_compute_type(cls, value: str) -> str:+ if value not in CTRANSLATE2_COMPUTE_TYPES:+ raise ValueError("serving artifact compute_type is unsupported")+ return value+++class ServingArtifactRuntime(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ minimum_version: Literal["4.8.1"]+ maximum_version: Literal["4.8.1"]+++class ServingArtifactEntry(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ path: str = Field(min_length=1, max_length=1024)+ role: str = Field(pattern=_ROLE_PATTERN)+ size_bytes: int = Field(ge=0)+ sha256: str = Field(pattern=_SHA256_PATTERN)++ @field_validator("path")+ @classmethod+ def validate_path(cls, value: str) -> str:+ return _validate_relative_posix_path(value, label="serving artifact path")++ @field_validator("size_bytes", mode="before")+ @classmethod+ def reject_boolean_size(cls, value: object) -> object:+ if isinstance(value, bool):+ raise ValueError("serving artifact size_bytes must be an integer")+ return value+++class TokenizerArtifactReference(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ path: str = Field(min_length=1, max_length=1024)+ role: str = Field(pattern=r"^tokenizer\.[a-z][a-z0-9_.-]{0,53}$")++ @field_validator("path")+ @classmethod+ def validate_path(cls, value: str) -> str:+ return _validate_relative_posix_path(value, label="tokenizer artifact path")+++class ServingArtifactTokenizer(BaseModel):+ model_config = ConfigDict(extra="forbid", frozen=True)++ class_name: str = Field(min_length=1, max_length=256, pattern=r"^[A-Za-z_][A-Za-z0-9_.]*$")+ config_sha256: str = Field(pattern=_SHA256_PATTERN)+ files: tuple[TokenizerArtifactReference, ...] = Field(min_length=1, max_length=128)++ @model_validator(mode="after")+ def validate_unique_files(self) -> ServingArtifactTokenizer:+ paths = [entry.path for entry in self.files]+ if len(paths) != len(set(paths)):+ raise ValueError("tokenizer artifact inventory contains duplicate paths")+ return self+++class ServingArtifactManifest(BaseModel):+ """Closed canonical manifest for a CTranslate2 serving tree."""++ model_config = ConfigDict(extra="forbid", frozen=True)++ schema_id: Literal["sie-ctranslate2-serving-artifact-v1"] = Field(alias="schema")+ source: ServingArtifactSource+ converter: ServingArtifactConverter+ runtime: ServingArtifactRuntime+ tokenizer: ServingArtifactTokenizer+ artifacts: tuple[ServingArtifactEntry, ...] = Field(min_length=1, max_length=10_000)++ @model_validator(mode="after")+ def validate_inventory(self) -> ServingArtifactManifest:+ paths = [artifact.path for artifact in self.artifacts]+ if len(paths) != len(set(paths)):+ raise ValueError("serving artifact manifest contains duplicate paths")+ sorted_paths = sorted(paths)+ for parent, candidate in pairwise(sorted_paths):+ if candidate.startswith(f"{parent}/"):+ raise ValueError("serving artifact manifest contains a file/directory path collision")++ artifacts_by_path = {artifact.path: artifact for artifact in self.artifacts}+ tokenizer_paths = {entry.path for entry in self.tokenizer.files}+ declared_tokenizer_paths = {+ artifact.path for artifact in self.artifacts if artifact.role.startswith("tokenizer.")+ }+ if tokenizer_paths != declared_tokenizer_paths:+ raise ValueError("tokenizer file inventory must exactly match tokenizer-role artifacts")+ for entry in self.tokenizer.files:+ artifact = artifacts_by_path.get(entry.path)+ if artifact is None or artifact.role != entry.role:+ raise ValueError("tokenizer file role must match its artifact entry")+ tokenizer_configs = [+ artifacts_by_path[entry.path] for entry in self.tokenizer.files if entry.role == "tokenizer.config"+ ]+ if len(tokenizer_configs) != 1 or tokenizer_configs[0].sha256 != self.tokenizer.config_sha256:+ raise ValueError("tokenizer config digest must match exactly one tokenizer.config artifact")+ return self+++@dataclass(frozen=True, slots=True)+class VerifiedServingArtifact:+ root: Path+ manifest_sha256: str+ repo_id: str+ revision: str+ compute_type: str+ artifact_count: int+ manifest: ServingArtifactManifest+++def parse_serving_artifact_declaration(loadtime: dict[str, object]) -> ServingArtifactDeclaration | None:+ """Parse one effective profile's nested serving-artifact declaration."""+ for key in (+ SERVING_ARTIFACT_PATH_KEY,+ SERVING_ARTIFACT_COMPUTE_TYPE_KEY,+ ):+ if key in loadtime:+ raise ValueError(f"'{key}' is loader-owned and must not be declared")++ if SERVING_ARTIFACT_KEY not in loadtime:+ return None+ value = loadtime[SERVING_ARTIFACT_KEY]+ try:+ return ServingArtifactDeclaration.model_validate(value)+ except ValueError as exc:+ raise ValueError("loadtime.serving_artifact is invalid") from exc+++def canonical_manifest_bytes(manifest: ServingArtifactManifest) -> bytes:+ """Return the one accepted byte representation of a serving manifest."""+ payload = manifest.model_dump(mode="json", by_alias=True)+ return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + b"\n"+++def normalized_recipe_sha256(recipe: dict[str, object]) -> str:+ """Hash a normalized conversion recipe without filesystem or timestamp data."""+ encoded = json.dumps(recipe, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()+ return hashlib.sha256(encoded).hexdigest()+++def _sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for chunk in iter(lambda: source.read(_HASH_CHUNK_BYTES), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def _load_manifest(+ declaration: ServingArtifactDeclaration,+ *,+ cached_repo_root: Path,+) -> tuple[Path, ServingArtifactManifest]:+ repo_root = cached_repo_root.resolve(strict=True)+ snapshot_root = repo_root / "snapshots" / declaration.revision+ try:+ resolved_snapshot = snapshot_root.resolve(strict=True)+ except OSError as exc:+ raise ValueError("derived serving artifact snapshot is not staged at the declared revision") from exc+ if (+ resolved_snapshot != snapshot_root+ or not resolved_snapshot.is_dir()+ or not resolved_snapshot.is_relative_to(repo_root)+ ):+ raise ValueError("derived serving artifact snapshot escapes its repository cache")++ manifest_path = snapshot_root.joinpath(*PurePosixPath(declaration.manifest_path).parts)+ try:+ resolved_manifest = manifest_path.resolve(strict=True)+ except OSError as exc:+ raise ValueError("derived serving artifact manifest does not exist") from exc+ if not resolved_manifest.is_file() or not resolved_manifest.is_relative_to(repo_root):+ raise ValueError("derived serving artifact manifest is not a safe regular file")+ if resolved_manifest.stat().st_size > _MAX_MANIFEST_BYTES:+ raise ValueError("derived serving artifact manifest exceeds the size limit")++ manifest_bytes = resolved_manifest.read_bytes()+ if hashlib.sha256(manifest_bytes).hexdigest() != declaration.manifest_sha256:+ raise ValueError("derived serving artifact manifest sha256 does not match the catalog declaration")+ try:+ manifest = ServingArtifactManifest.model_validate_json(manifest_bytes)+ except ValueError as exc:+ raise ValueError("derived serving artifact manifest is invalid") from exc+ if manifest_bytes != canonical_manifest_bytes(manifest):+ raise ValueError("derived serving artifact manifest is not canonical JSON")+ return resolved_snapshot, manifest+++def _verify_manifest_compatibility(+ declaration: ServingArtifactDeclaration,+ manifest: ServingArtifactManifest,+ *,+ source_hf_id: str,+ source_hf_revision: str,+ runtime_version: str,+) -> None:+ if manifest.source.hf_id != source_hf_id or manifest.source.hf_revision != source_hf_revision:+ raise ValueError("derived serving artifact source identity does not match the model catalog")+ if manifest.converter.version != CTRANSLATE2_VERSION:+ raise ValueError("derived serving artifact converter version is unsupported")+ if manifest.converter.torch_version != CTRANSLATE2_TORCH_VERSION:+ raise ValueError("derived serving artifact torch converter version is unsupported")+ if manifest.converter.transformers_version != CTRANSLATE2_TRANSFORMERS_VERSION:+ raise ValueError("derived serving artifact transformers converter version is unsupported")+ if manifest.converter.compute_type != declaration.compute_type:+ raise ValueError("derived serving artifact compute_type does not match the effective profile")+ if runtime_version not in {manifest.runtime.minimum_version, manifest.runtime.maximum_version}:+ raise ValueError("derived serving artifact runtime compatibility does not include this worker")+ if declaration.format != "ctranslate2":+ raise ValueError("unsupported derived serving artifact format")+ if declaration.manifest_path in {artifact.path for artifact in manifest.artifacts}:+ raise ValueError("derived serving artifact manifest must not be part of the served file inventory")+++def _expected_directories(manifest: ServingArtifactManifest) -> set[str]:+ return {+ parent.as_posix()+ for artifact in manifest.artifacts+ for parent in PurePosixPath(artifact.path).parents+ if parent != PurePosixPath(".")+ }+++def _verify_materialized_tree(root: Path, manifest: ServingArtifactManifest) -> None:+ try:+ resolved_root = root.resolve(strict=True)+ except OSError as exc:+ raise ValueError("materialized serving artifact tree does not exist") from exc+ if resolved_root != root or not root.is_dir():+ raise ValueError("materialized serving artifact root must be a non-symlink directory")+ if root.stat().st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH):+ raise ValueError("materialized serving artifact root is writable")++ expected_files = {artifact.path for artifact in manifest.artifacts}+ expected_directories = _expected_directories(manifest)+ observed_files: set[str] = set()+ observed_directories: set[str] = set()++ def scan(directory: Path) -> None:+ try:+ with os.scandir(directory) as entries:+ for entry in entries:+ path = Path(entry.path)+ relative = path.relative_to(root).as_posix()+ if entry.is_symlink():+ raise ValueError(f"materialized serving artifact tree contains a symlink: {relative!r}")+ if entry.is_dir(follow_symlinks=False):+ if relative not in expected_directories:+ raise ValueError(+ f"materialized serving artifact tree contains an unlisted directory: {relative!r}"+ )+ observed_directories.add(relative)+ if path.stat().st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH):+ raise ValueError(f"materialized serving artifact directory is writable: {relative!r}")+ scan(path)+ elif entry.is_file(follow_symlinks=False):+ if relative not in expected_files:+ raise ValueError(+ f"materialized serving artifact tree contains an unlisted file: {relative!r}"+ )+ observed_files.add(relative)+ else:+ raise ValueError(f"materialized serving artifact tree contains a special node: {relative!r}")+ except OSError as exc:+ raise ValueError("materialized serving artifact tree cannot be inventoried") from exc++ scan(root)+ missing_files = sorted(expected_files - observed_files)+ missing_directories = sorted(expected_directories - observed_directories)+ if missing_files or missing_directories:+ raise ValueError(+ "materialized serving artifact tree does not match the manifest: "+ f"missing_files={missing_files!r}, missing_directories={missing_directories!r}"+ )++ for artifact in manifest.artifacts:+ path = root.joinpath(*PurePosixPath(artifact.path).parts)+ resolved = path.resolve(strict=True)+ if resolved != path or not path.is_file() or not resolved.is_relative_to(root):+ raise ValueError(f"materialized serving artifact is not a safe regular file: {artifact.path!r}")+ file_stat = path.stat()+ if file_stat.st_size != artifact.size_bytes:+ raise ValueError(f"materialized serving artifact size does not match the manifest: {artifact.path!r}")+ if _sha256_file(path) != artifact.sha256:+ raise ValueError(f"materialized serving artifact sha256 does not match the manifest: {artifact.path!r}")+ if file_stat.st_mode & (stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH):+ raise ValueError(f"materialized serving artifact is writable: {artifact.path!r}")+++def _safe_source_file(snapshot_root: Path, repo_root: Path, artifact: ServingArtifactEntry) -> Path:+ source_path = snapshot_root.joinpath(*PurePosixPath(artifact.path).parts)+ try:+ resolved = source_path.resolve(strict=True)+ except OSError as exc:+ raise ValueError(f"derived serving artifact is missing: {artifact.path!r}") from exc+ if not resolved.is_file() or not resolved.is_relative_to(repo_root):+ raise ValueError(f"derived serving artifact escapes its repository cache: {artifact.path!r}")+ file_stat = resolved.stat()+ if file_stat.st_size != artifact.size_bytes:+ raise ValueError(f"derived serving artifact size does not match the manifest: {artifact.path!r}")+ if _sha256_file(resolved) != artifact.sha256:+ raise ValueError(f"derived serving artifact sha256 does not match the manifest: {artifact.path!r}")+ return resolved+++def _make_read_only(root: Path) -> None:+ for directory, directory_names, file_names in os.walk(root, topdown=False):+ directory_path = Path(directory)+ for file_name in file_names:+ (directory_path / file_name).chmod(0o444)+ for directory_name in directory_names:+ (directory_path / directory_name).chmod(0o555)+ directory_path.chmod(0o555)+++def _remove_staging_tree(root: Path) -> None:+ if not root.exists():+ return+ for directory, directory_names, file_names in os.walk(root):+ directory_path = Path(directory)+ directory_path.chmod(0o700)+ for directory_name in directory_names:+ (directory_path / directory_name).chmod(0o700)+ # Unlinking read-only files only requires a writable parent directory.+ shutil.rmtree(root)+++def atomic_rename_directory_noreplace(source: Path, destination: Path) -> None:+ """Atomically publish a directory without replacing an existing path."""+ libc = ctypes.CDLL(None, use_errno=True)+ renameat2 = getattr(libc, "renameat2", None)+ if renameat2 is not None:+ result = renameat2(+ ctypes.c_int(-100),+ ctypes.c_char_p(os.fsencode(source)),+ ctypes.c_int(-100),+ ctypes.c_char_p(os.fsencode(destination)),+ ctypes.c_uint(1),+ )+ else:+ renamex_np = getattr(libc, "renamex_np", None)+ if renamex_np is None:+ raise OSError(errno.ENOTSUP, "atomic no-replace directory publication is unavailable")+ result = renamex_np(+ ctypes.c_char_p(os.fsencode(source)),+ ctypes.c_char_p(os.fsencode(destination)),+ ctypes.c_uint(4),+ )+ if result == 0:+ return+ error_number = ctypes.get_errno()+ raise OSError(error_number, os.strerror(error_number), destination)+++def _rename_verified_nonempty_directory(source: Path, destination: Path) -> None:+ """Atomically publish a verified tree on filesystems without no-replace rename."""+ if source.is_symlink() or not source.is_dir() or next(source.iterdir(), None) is None:+ raise ValueError("portable serving-artifact publication requires a nonempty directory")+ if destination.exists() or destination.is_symlink():+ raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), destination)+ # This private cache has only cooperating materializers. Every valid tree+ # is nonempty, so a concurrent winner makes this rename fail instead of+ # being replaced. Keep the strict primitive for general create-only paths.+ source.rename(destination)+++def _publish_materialized_tree(source: Path, destination: Path) -> None:+ try:+ atomic_rename_directory_noreplace(source, destination)+ except OSError as exc:+ unsupported_errors = {errno.EINVAL, errno.ENOSYS, errno.ENOTSUP, errno.EOPNOTSUPP}+ if exc.errno not in unsupported_errors:+ raise+ # Some FUSE filesystems expose renameat2 but reject RENAME_NOREPLACE.+ _rename_verified_nonempty_directory(source, destination)+++def _verify_tokenizer_config(root: Path, manifest: ServingArtifactManifest) -> None:+ config_ref = next(entry for entry in manifest.tokenizer.files if entry.role == "tokenizer.config")+ config_path = root.joinpath(*PurePosixPath(config_ref.path).parts)+ if config_path.stat().st_size > _MAX_TOKENIZER_CONFIG_BYTES:+ raise ValueError("materialized tokenizer config exceeds the size limit")+ try:+ value = json.loads(config_path.read_bytes())+ except (OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:+ raise ValueError("materialized tokenizer config is invalid JSON") from exc+ if not isinstance(value, dict) or value.get("tokenizer_class") != manifest.tokenizer.class_name:+ raise ValueError("materialized tokenizer class does not match the serving artifact manifest")+++def _materialize(+ *,+ snapshot_root: Path,+ cached_repo_root: Path,+ cache_root: Path,+ manifest_sha256: str,+ manifest: ServingArtifactManifest,+) -> Path:+ cache_root.mkdir(parents=True, exist_ok=True)+ cache_root = cache_root.resolve(strict=True)+ destination = cache_root / manifest_sha256+ if destination.exists() or destination.is_symlink():+ _verify_materialized_tree(destination, manifest)+ _verify_tokenizer_config(destination, manifest)+ return destination++ staging = Path(tempfile.mkdtemp(prefix=f".{manifest_sha256}.", dir=cache_root))+ staging.chmod(0o700)+ repo_root = cached_repo_root.resolve(strict=True)+ try:+ for artifact in manifest.artifacts:+ source = _safe_source_file(snapshot_root, repo_root, artifact)+ target = staging.joinpath(*PurePosixPath(artifact.path).parts)+ target.parent.mkdir(parents=True, exist_ok=True)+ # A hardlink cannot be made immutable for the worker: the cache+ # owner can chmod and rewrite the shared inode after admission.+ # Always create an independently owned inode, then verify the copy.+ shutil.copyfile(source, target)++ _make_read_only(staging)+ _verify_materialized_tree(staging, manifest)+ _verify_tokenizer_config(staging, manifest)+ try:+ _publish_materialized_tree(staging, destination)+ except OSError as exc:+ if exc.errno not in {errno.EEXIST, errno.ENOTEMPTY}:+ raise+ _remove_staging_tree(staging)+ _verify_materialized_tree(destination, manifest)+ _verify_tokenizer_config(destination, manifest)+ return destination+ except Exception:+ _remove_staging_tree(staging)+ raise+++def verify_and_materialize_serving_artifact(+ declaration: ServingArtifactDeclaration,+ *,+ source_hf_id: str,+ source_hf_revision: str,+ cached_repo_root: Path,+ materialized_cache_root: Path,+ runtime_version: str = CTRANSLATE2_VERSION,+) -> VerifiedServingArtifact:+ """Verify an exact derived snapshot and atomically materialize its served files."""+ snapshot_root, manifest = _load_manifest(declaration, cached_repo_root=cached_repo_root)+ _verify_manifest_compatibility(+ declaration,+ manifest,+ source_hf_id=source_hf_id,+ source_hf_revision=source_hf_revision,+ runtime_version=runtime_version,+ )+ root = _materialize(+ snapshot_root=snapshot_root,+ cached_repo_root=cached_repo_root,+ cache_root=materialized_cache_root,+ manifest_sha256=declaration.manifest_sha256,+ manifest=manifest,+ )+ return VerifiedServingArtifact(+ root=root,+ manifest_sha256=declaration.manifest_sha256,+ repo_id=declaration.repo_id,+ revision=declaration.revision,+ compute_type=declaration.compute_type,+ artifact_count=len(manifest.artifacts),+ manifest=manifest,+ )diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 4142e1903..f540eebe0 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -35,6 +35,12 @@ from sie_server.config.package_artifacts import (PackageArtifactMode,verify_staged_package_artifacts,)+from sie_server.config.serving_artifacts import (+ SERVING_ARTIFACT_COMPUTE_TYPE_KEY,+ SERVING_ARTIFACT_KEY,+ SERVING_ARTIFACT_PATH_KEY,+ VerifiedServingArtifact,+)from sie_server.core.inference import AttentionBackendlogger = logging.getLogger(__name__)@@ -410,6 +416,7 @@ def load_adapter(device: str,default_compute_precision: ComputePrecision = "float16",attention_backend: AttentionBackend = "auto",+ verified_serving_artifact: VerifiedServingArtifact | None = None,) -> ModelAdapter:"""Load and instantiate a model adapter.@@ -454,7 +461,11 @@ def load_adapter(effective_default_precision: ComputePrecision = (default_compute_precision if device.startswith("cuda") else "float32")- adapter_kwargs = _build_adapter_kwargs(config, effective_default_precision)+ adapter_kwargs = _build_adapter_kwargs(+ config,+ effective_default_precision,+ verified_serving_artifact=verified_serving_artifact,+ )# MPS bfloat16 support is incomplete in torch and can HANG model load (verified:# bge-m3 bf16 load wedges at ~1% CPU on Apple Silicon). fp16 is the MPS-verified@@ -614,6 +625,8 @@ def _import_custom_adapter(file_path: Path, class_name: str) -> type[ModelAdaptedef _build_adapter_kwargs(config: ModelConfig,default_compute_precision: ComputePrecision,+ *,+ verified_serving_artifact: VerifiedServingArtifact | None = None,) -> dict[str, Any]:"""Build keyword arguments for adapter instantiation.@@ -661,6 +674,25 @@ def _build_adapter_kwargs(kwargs.update(resolved.loadtime)+ serving_artifact = config.serving_artifact_declaration()+ kwargs.pop(SERVING_ARTIFACT_KEY, None)+ if serving_artifact is not None:+ if verified_serving_artifact is None:+ raise ValueError(+ f"Model '{config.sie_id}' declares a derived serving artifact but the loader did not verify it"+ )+ if (+ verified_serving_artifact.repo_id != serving_artifact.repo_id+ or verified_serving_artifact.revision != serving_artifact.revision+ or verified_serving_artifact.manifest_sha256 != serving_artifact.manifest_sha256+ or verified_serving_artifact.compute_type != serving_artifact.compute_type+ ):+ raise ValueError(f"Model '{config.sie_id}' received a stale or mismatched verified serving artifact")+ kwargs[SERVING_ARTIFACT_PATH_KEY] = verified_serving_artifact.root+ kwargs[SERVING_ARTIFACT_COMPUTE_TYPE_KEY] = verified_serving_artifact.compute_type+ kwargs.pop("model_name_or_path", None)+ kwargs.pop("revision", None)+# Adapter constructors take ``lora_paths`` as served-name -> bare path/id# (the sglang ``--lora-paths`` shape). A pinned ``{id, revision}`` value# (#2113) is a *config* spelling: collapse it to the bare id here so nodiff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.pyindex ec8fdf967..4dcba5c28 100644--- a/packages/sie_server/src/sie_server/core/model_loader.py+++ b/packages/sie_server/src/sie_server/core/model_loader.py@@ -12,6 +12,10 @@ from typing import TYPE_CHECKING, Anyfrom sie_server.adapters.base import ModelAdapterfrom sie_server.config.model import ModelConfig, ProfileAdaptiveBatching, lora_entry_ref+from sie_server.config.serving_artifacts import (+ VerifiedServingArtifact,+ verify_and_materialize_serving_artifact,+)from sie_server.core.inference import AttentionBackend, ComputePrecisionfrom sie_server.core.load_errors import ModelLoadTimeoutErrorfrom sie_server.core.loader import load_adapter@@ -174,6 +178,9 @@ class ModelLoader:self._oom_recovery = oom_recovery or OomRecoveryConfig()self._registry_callbacks = registry_callbacksself._load_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="model-load")+ # Loader-owned admission results. Catalog data can identify a derived+ # artifact but can never inject a filesystem root into an adapter.+ self._verified_serving_artifacts: dict[str, VerifiedServingArtifact] = {}# Post-download budget (instantiate + adapter.load + warmup). 0.0# disables the outer ``wait_for``. Download is bounded separately# by ``HF_HUB_DOWNLOAD_TIMEOUT``.@@ -225,6 +232,7 @@ class ModelLoader:device=device,default_compute_precision=self._default_compute_precision,attention_backend=self._attention_backend,+ verified_serving_artifact=self._verified_serving_artifacts.get(config.sie_id),)def ensure_weights_cached(self, config: ModelConfig) -> None:@@ -249,10 +257,49 @@ class ModelLoader:model_id = config.hf_idcache_config = get_cache_config()+ serving_artifact = config.serving_artifact_declaration()++ # Never let an earlier successful admission survive a failed restage or+ # a hot-reloaded declaration. The verified root is registered only+ # after the exact derived snapshot and every manifest entry pass.+ self._verified_serving_artifacts.pop(config.sie_id, None)# Base-model caching applies only to HF models, while an external# speculative assistant still needs staging for local weights_path.- if model_id is not None:+ if serving_artifact is not None:+ if model_id is None or config.hf_revision is None:+ raise ValueError("derived serving artifacts require an immutable HF source identity")+ derived_id = serving_artifact.repo_id+ if self._disk_cache is not None:+ evicted = self._disk_cache.ensure_space_before_download(derived_id)+ if evicted:+ logger.info(+ "Pre-download disk eviction: freed %d model(s): %s",+ len(evicted),+ evicted,+ )+ cached_repo_root = ensure_model_cached(+ derived_id,+ cache_config,+ revision=serving_artifact.revision,+ )+ verified = verify_and_materialize_serving_artifact(+ serving_artifact,+ source_hf_id=model_id,+ source_hf_revision=config.hf_revision,+ cached_repo_root=cached_repo_root,+ materialized_cache_root=cache_config.local_cache / "sie-serving-artifacts-v1",+ )+ self._verified_serving_artifacts[config.sie_id] = verified+ if self._disk_cache is not None:+ self._disk_cache.touch(derived_id)+ logger.debug(+ "Derived serving artifact %s@%s materialized at %s",+ derived_id,+ serving_artifact.revision,+ verified.root,+ )+ elif model_id is not None:if self._disk_cache is not None:evicted = self._disk_cache.ensure_space_before_download(model_id)if evicted:@@ -799,6 +846,10 @@ class ModelLoader:# Unregister postprocessorsself._postprocessor_registry.unregister(name)+ # Keep the immutable content-addressed tree on disk for reuse, but do+ # not retain loader admission state across unload/hot-reload.+ self._verified_serving_artifacts.pop(name, None)+logger.debug("Unregistered pre/postprocessors for model '%s'", name)def shutdown(self) -> None:diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 6e7fa5d6a..6dc46cb37 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -17,13 +17,15 @@ import contextlibimport hashlibimport jsonimport logging+import threadingimport time-from collections.abc import Iterable+from collections.abc import Coroutine, Iterablefrom pathlib import Pathfrom typing import Anyfrom sie_sdk.storage import is_cloud_path+from sie_server.adapters._generation_base import GenerationAdapterfrom sie_server.adapters.base import ModelAdapterfrom sie_server.config.engine import EngineConfigfrom sie_server.config.model import ModelConfig@@ -261,6 +263,13 @@ class ModelRegistry:# Concurrency-safe loadingself._load_lock: asyncio.Lock | None = None # Created lazily on first useself._config_update_lock: asyncio.Lock | None = None+ # Async lifecycle state is owned by one long-lived server event loop.+ # Legacy synchronous callers are serialized independently until that+ # loop is known; after binding they submit work back to the owner loop.+ self._lifecycle_loop: asyncio.AbstractEventLoop | None = None+ self._lifecycle_state_lock = threading.Lock()+ self._sync_lifecycle_lock = threading.RLock()+ self._sync_lifecycle_depth = 0self._loading: set[str] = set() # Models currently being loadedself._unloading: set[str] = set() # Models currently being unloaded# Terminal-failed state. Populated by ``_load_model_background`` when a@@ -356,25 +365,31 @@ class ModelRegistry:def _pinned_disk_repo_ids(self) -> set[str]:"""HF repo ids of pinned models, for disk-cache eviction protection.- Matched at BASE-model granularity: a profile variant shares its base- model's ``hf_id`` (disk weights), so a pinned ``org/model:fp8`` protects- the same repo as ``org/model``. Mapping pinned ids to the configs'- ``hf_id`` keeps a long-tail download from evicting a pinned model's- weights and reintroducing its cold start.+ Matched at BASE-model granularity. Every materialized profile variant+ of a pinned model is protected: ordinary HF profiles name their source+ repo, while profiles backed by a derived serving artifact name the+ downloaded derived repo instead. This mirrors ``ModelLoader`` cache+ accounting and prevents an offline reload from losing a pinned derived+ snapshot while its source repo remains unnecessarily protected.The disk cache matches by exact ``hf_id`` (no case-folding, unlike thein-memory sie_id path), which is safe because the cache key also derives- from ``config.hf_id`` (model_loader passes it to ``ensure_space_before_download``- and ``touch``).+ from the same effective source/derived repo id that ``ModelLoader``+ passes to ``ensure_space_before_download`` and ``touch``."""if not self._pinned_models:return set()pinned_bases = {_base_model_id(pinned_id) for pinned_id in self._pinned_models}- return {- config.hf_id- for sie_id, config in self._configs.items()- if config.hf_id and _base_model_id(sie_id) in pinned_bases- }+ repo_ids: set[str] = set()+ for sie_id, config in self._configs.items():+ if _base_model_id(sie_id) not in pinned_bases:+ continue+ serving_artifact = config.serving_artifact_declaration()+ if serving_artifact is not None:+ repo_ids.add(serving_artifact.repo_id)+ elif config.hf_id is not None:+ repo_ids.add(config.hf_id)+ return repo_idsasync def _eager_load_pinned(self) -> None:"""Eager-load every pinned model that has a config and is not yet resident.@@ -718,14 +733,75 @@ class ModelRegistry:"""return self._failed.pop(name, None) is not None+ def _bind_lifecycle_loop(self) -> asyncio.AbstractEventLoop:+ """Bind every asynchronous registry lifecycle operation to one loop."""+ loop = asyncio.get_running_loop()+ with self._lifecycle_state_lock:+ if self._sync_lifecycle_depth > 0:+ msg = "a synchronous model lifecycle operation is already in progress"+ raise RuntimeError(msg)+ if self._lifecycle_loop is None:+ self._lifecycle_loop = loop+ elif self._lifecycle_loop is not loop:+ msg = "model lifecycle is bound to a different event loop"+ raise RuntimeError(msg)+ return loop++ @staticmethod+ def _reject_sync_on_running_loop(operation: str) -> None:+ """Fail before taking a thread lock that a foreign bridge may hold."""+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ return+ msg = f"synchronous {operation} is unsafe inside a running event loop; await {operation}_async()"+ raise RuntimeError(msg)++ def _begin_sync_lifecycle(self, operation: str) -> asyncio.AbstractEventLoop | None:+ """Select the owner-loop bridge or enter the serialized sync-only path."""+ self._reject_sync_on_running_loop(operation)++ with self._lifecycle_state_lock:+ owner = self._lifecycle_loop+ if owner is None:+ self._sync_lifecycle_depth += 1+ return None++ if owner.is_closed() or not owner.is_running():+ msg = f"cannot run synchronous {operation}: the registry lifecycle event loop is not running"+ raise RuntimeError(msg)+ return owner++ def _end_sync_lifecycle(self) -> None:+ with self._lifecycle_state_lock:+ if self._sync_lifecycle_depth <= 0:+ msg = "synchronous model lifecycle depth underflow"+ raise RuntimeError(msg)+ self._sync_lifecycle_depth -= 1++ @staticmethod+ def _run_on_lifecycle_loop(+ loop: asyncio.AbstractEventLoop,+ coroutine: Coroutine[Any, Any, Any],+ ) -> Any:+ """Submit one synchronous caller to the registry's owning event loop."""+ try:+ future = asyncio.run_coroutine_threadsafe(coroutine, loop)+ except BaseException:+ coroutine.close()+ raise+ return future.result()+def _get_load_lock(self) -> asyncio.Lock:- """Get or create the load lock (must be called from async context)."""+ """Get or create the load lock on the registry lifecycle loop."""+ self._bind_lifecycle_loop()if self._load_lock is None:self._load_lock = asyncio.Lock()return self._load_lockdef _get_config_update_lock(self) -> asyncio.Lock:"""Serialize async config mutations across IPC/hot-reload entrypoints."""+ self._bind_lifecycle_loop()if self._config_update_lock is None:self._config_update_lock = asyncio.Lock()return self._config_update_lock@@ -832,7 +908,10 @@ class ModelRegistry:def load(self, name: str, device: str) -> ModelAdapter:"""Load a model onto a device.- If loading fails due to OOM, attempts to evict LRU model and retry once.+ Before the registry belongs to an async server loop, this legacy+ entrypoint uses a serialized synchronous lifecycle. Once the server+ loop is bound, callers from other threads submit to ``load_async`` on+ that loop; callers already on an event loop must await ``load_async``.Args:name: Model name.@@ -847,6 +926,18 @@ class ModelRegistry:ImportError: If adapter cannot be loaded.RuntimeError: If OOM persists after eviction."""+ self._reject_sync_on_running_loop("load")+ with self._sync_lifecycle_lock:+ owner = self._begin_sync_lifecycle("load")+ if owner is not None:+ return self._run_on_lifecycle_loop(owner, self.load_async(name, device))+ try:+ return self._load_sync(name, device)+ finally:+ self._end_sync_lifecycle()++ def _load_sync(self, name: str, device: str) -> ModelAdapter:+ """Synchronous-only load implementation under ``_sync_lifecycle_lock``."""# Pre-load validation: config existence + dependency checkingconfig, model_dir = self._check_model_loadable(name)@@ -888,7 +979,7 @@ class ModelRegistry:lru_model,name,)- self.unload(lru_model, reason="preload_pressure")+ self._unload_sync(lru_model, reason="preload_pressure")# Try to load onto device, with OOM retry.try:@@ -908,7 +999,7 @@ class ModelRegistry:name,lru_model,)- self.unload(lru_model, reason="load_oom")+ self._unload_sync(lru_model, reason="load_oom")# Retry once after eviction - weights still on disk so we# skip ``ensure_weights_cached`` here.@@ -1115,6 +1206,8 @@ class ModelRegistry:Raises:KeyError: If model not found."""+ self._bind_lifecycle_loop()+# Already loaded - no action neededif name in self._loaded:return False@@ -1229,14 +1322,33 @@ class ModelRegistry:)def unload(self, name: str, *, reason: str = "manual") -> None:- """Unload a model and free resources.+ """Unload a model through the serialized registry lifecycle.Args:name: Model name.+ reason: Bounded telemetry reason for the eviction.Raises:KeyError: If model not found or not loaded."""+ self._reject_sync_on_running_loop("unload")+ with self._sync_lifecycle_lock:+ owner = self._begin_sync_lifecycle("unload")+ if owner is not None:+ self._run_on_lifecycle_loop(owner, self.unload_async(name, reason=reason))+ return+ try:+ self._unload_sync(name, reason=reason)+ finally:+ self._end_sync_lifecycle()++ def _unload_sync(self, name: str, *, reason: str) -> None:+ """Synchronous-only unload under ``_sync_lifecycle_lock``.++ Generation adapters own asynchronous drain work and therefore require+ an owning lifecycle loop. A sync-only registry fails closed instead of+ inventing a temporary event loop for that teardown.+ """if name not in self._configs:msg = _ERR_MODEL_NOT_FOUND.format(name=name)raise KeyError(msg)@@ -1245,6 +1357,10 @@ class ModelRegistry:msg = _ERR_MODEL_NOT_LOADED.format(name=name)raise KeyError(msg)+ if isinstance(self._loaded[name].adapter, GenerationAdapter):+ msg = "synchronous unload of a generation adapter requires an owning event loop; await unload_async()"+ raise RuntimeError(msg)+logger.info("Unloading model '%s'", name)loaded = self._loaded.pop(name)@@ -1309,6 +1425,33 @@ class ModelRegistry:await asyncio.shield(unload_future)raise+ async def _drain_generation_before_deadline(+ self,+ adapter: GenerationAdapter,+ *,+ deadline: float,+ ) -> None:+ """Enter the adapter drain hook even when the shared budget is spent.++ ``asyncio.wait_for(coro, 0)`` cancels ``coro`` before its first line,+ which can leave adapter admission open during teardown. Starting a+ task and yielding one scheduler turn establishes the drain barrier;+ any remaining deadline then bounds only the asynchronous wait.+ """+ task = asyncio.create_task(adapter.drain_generation())+ await asyncio.sleep(0)+ if task.done():+ await task+ return++ remaining = max(0.0, deadline - asyncio.get_running_loop().time())+ if remaining == 0:+ task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await task+ raise TimeoutError+ await asyncio.wait_for(task, timeout=remaining)+async def _do_unload(self, name: str, *, reason: str = "other") -> None:"""Unload a model safely (drains worker first).@@ -1327,12 +1470,14 @@ class ModelRegistry:try:logger.info("Unloading model '%s' (draining worker first)", name)+ drain_deadline = asyncio.get_running_loop().time() + self._drain_timeout_s+# Stop worker (waits for pending batches, up to drain_timeout_s)if loaded.worker is not None and loaded.worker.is_running:try:await asyncio.wait_for(loaded.worker.stop(),- timeout=self._drain_timeout_s,+ timeout=max(0.0, drain_deadline - asyncio.get_running_loop().time()),)logger.info("Worker drained for model '%s'", name)except TimeoutError:@@ -1343,6 +1488,26 @@ class ModelRegistry:)# Force stop is handled by the worker.stop() method+ # Generation adapters bypass ``ModelWorker`` and can own their+ # own queue or child-runtime scheduler. Drain that async work under+ # the same unload deadline, while the registry still advertises+ # the loaded entry and before the synchronous teardown begins.+ if isinstance(loaded.adapter, GenerationAdapter):+ try:+ await self._drain_generation_before_deadline(+ loaded.adapter,+ deadline=drain_deadline,+ )+ logger.info("Generation adapter drained for model '%s'", name)+ except TimeoutError:+ logger.warning(+ "Generation adapter drain timeout for model '%s' after %.1fs, continuing unload",+ name,+ self._drain_timeout_s,+ )+ except Exception: # noqa: BLE001 - teardown continues after best-effort drain+ logger.warning("Generation adapter drain failed during unload of '%s'", name, exc_info=True)+# Remove from loaded dict before unloading adapterdel self._loaded[name]device = loaded.device@@ -1415,7 +1580,7 @@ class ModelRegistry:finally:self._unloading.discard(name)- async def unload_async(self, name: str) -> None:+ async def unload_async(self, name: str, *, reason: str = "manual") -> None:"""Unload a model and free resources (async, concurrency-safe).This method acquires the load lock and safely drains the worker@@ -1423,6 +1588,7 @@ class ModelRegistry:Args:name: Model name.+ reason: Bounded telemetry reason for the eviction.Raises:KeyError: If model not found or not loaded.@@ -1437,12 +1603,28 @@ class ModelRegistry:msg = _ERR_MODEL_NOT_LOADED.format(name=name)raise KeyError(msg)- await self._do_unload(name, reason="manual")+ await self._do_unload(name, reason=reason)def unload_all(self) -> None:- """Unload all loaded models (sync version, for non-async contexts)."""+ """Unload all models through the serialized registry lifecycle."""+ self._reject_sync_on_running_loop("unload_all")+ with self._sync_lifecycle_lock:+ owner = self._begin_sync_lifecycle("unload_all")+ if owner is not None:+ self._run_on_lifecycle_loop(owner, self.unload_all_async())+ return+ try:+ self._unload_all_sync()+ finally:+ self._end_sync_lifecycle()++ def _unload_all_sync(self) -> None:+ """Synchronous-only bulk unload under ``_sync_lifecycle_lock``."""+ if any(isinstance(loaded.adapter, GenerationAdapter) for loaded in self._loaded.values()):+ msg = "synchronous unload_all with a generation adapter requires an owning event loop; await unload_all_async()"+ raise RuntimeError(msg)for name in list(self._loaded.keys()):- self.unload(name, reason="shutdown")+ self._unload_sync(name, reason="shutdown")async def unload_all_async(self) -> None:"""Unload all loaded models (async, concurrency-safe)."""@@ -1986,6 +2168,7 @@ class ModelRegistry:The monitor periodically checks memory pressure and evicts LRU modelsif needed. This catches memory growth during inference."""+ self._bind_lifecycle_loop()if self._monitor_task is not None:return # Already runningdiff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex ed77f997c..2f8c32c2b 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport contextvarsimport hashlib+import jsonimport loggingimport osimport struct@@ -214,8 +215,10 @@ class IpcServer:self._drain_deadline_s: float | None = Noneself._streaming_processor: Any | None = Noneself._streaming_processor_lock = asyncio.Lock()- self._generation_prewarm_lock = asyncio.Lock()- self._generation_prewarmed = False+ self._generation_prewarm_metadata_lock = asyncio.Lock()+ self._generation_prewarm_locks: dict[str, asyncio.Lock] = {}+ self._generation_prewarm_completed: dict[str, tuple[int, str]] = {}+ self._generation_prewarm_authority_cache: dict[str, tuple[int, str]] = {}# -- Public surface ----------------------------------------------------@@ -725,7 +728,7 @@ class IpcServer:) -> SignalGenerateCancelResponse:if not req.request_id:return SignalGenerateCancelResponse(matched=False)- processor = await self._get_streaming_processor(prewarm=False)+ processor = await self._get_streaming_processor()return SignalGenerateCancelResponse(matched=bool(processor.signal_cancel(req.request_id)))async def _handle_process_generate(@@ -741,20 +744,20 @@ class IpcServer:try:# Keep the JetStream lease alive while the first generation# request lazily constructs the streaming processor and prewarms- # grammars. The processor's own heartbeat starts later, once- # request processing reaches the decode path.+ # the requested model's grammars. The processor's own heartbeat+ # starts later, once request processing reaches the decode path.await msg.in_progress()- processor = await self._get_streaming_processor()+ processor = await self._get_streaming_processor(prewarm_model_id=req.model_id)await processor.process(msg, req.model_id)await sink.send(GenerateEvent(kind="done"))finally:_GENERATE_SINK.reset(token)- async def _get_streaming_processor(self, *, prewarm: bool = True) -> Any:+ async def _get_streaming_processor(self, *, prewarm_model_id: str | None = None) -> Any:if self._streaming_processor is not None:processor = self._streaming_processor- if prewarm:- await self._prewarm_generation_grammars(processor)+ if prewarm_model_id is not None:+ await self._prewarm_generation_grammars(processor, prewarm_model_id)return processorasync with self._streaming_processor_lock:if self._streaming_processor is None:@@ -767,8 +770,8 @@ class IpcServer:admission_resolver=self._resolve_generation_admission,)processor = self._streaming_processor- if prewarm:- await self._prewarm_generation_grammars(processor)+ if prewarm_model_id is not None:+ await self._prewarm_generation_grammars(processor, prewarm_model_id)return processordef _resolve_generation_admission(self, model_id: str) -> tuple[int | None, bool | None]:@@ -792,23 +795,63 @@ class IpcServer:profile_admission = Nonereturn budget, resolve_admission_enabled(profile_admission=profile_admission)- async def _prewarm_generation_grammars(self, processor: Any) -> None:- async with self._generation_prewarm_lock:- if self._generation_prewarmed:+ async def _prewarm_generation_grammars(self, processor: Any, model_id: str) -> None:+ authority = self._generation_prewarm_authority(model_id)+ if authority is None:+ return+ async with self._generation_prewarm_metadata_lock:+ if self._generation_prewarm_completed.get(model_id) == authority:+ return+ model_lock = self._generation_prewarm_locks.setdefault(model_id, asyncio.Lock())++ async with model_lock:+ authority = self._generation_prewarm_authority(model_id)+ if authority is None:return- self._generation_prewarmed = True+ async with self._generation_prewarm_metadata_lock:+ if self._generation_prewarm_completed.get(model_id) == authority:+ returntry:- configs = self._executor.registry.get_configs_snapshot()+ await processor.prewarm_grammars_for_model(model_id)except Exception: # noqa: BLE001- logger.debug("Could not snapshot configs for generation grammar prewarm", exc_info=True)+ logger.warning("Generation grammar prewarm failed for %s", model_id, exc_info=True)return- for model_id, config in configs.items():- try:- if config.tasks.generate is None:- continue- await processor.prewarm_grammars_for_model(model_id)- except Exception: # noqa: BLE001- logger.warning("Generation grammar prewarm failed for %s", model_id, exc_info=True)+ async with self._generation_prewarm_metadata_lock:+ if self._generation_prewarm_authority(model_id) == authority:+ self._generation_prewarm_completed[model_id] = authority++ def _generation_prewarm_authority(self, model_id: str) -> tuple[int, str] | None:+ try:+ registry = self._executor.registry+ version_before = registry._config_version+ if isinstance(version_before, bool) or not isinstance(version_before, int) or version_before < 0:+ return None+ cached = self._generation_prewarm_authority_cache.get(model_id)+ if cached is not None and cached[0] == version_before:+ if registry._config_version == version_before:+ return cached+ return None+ config = registry.get_config(model_id)+ if config.tasks.generate is None:+ return None+ payload = json.dumps(+ config.model_dump(mode="json"),+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=True,+ ).encode()+ if registry._config_version != version_before:+ return None+ authority = version_before, hashlib.sha256(payload).hexdigest()+ if registry._config_version != version_before:+ return None+ self._generation_prewarm_authority_cache[model_id] = authority+ except KeyError:+ return None+ except Exception: # noqa: BLE001+ logger.debug("Could not inspect requested model for generation grammar prewarm", exc_info=True)+ return None+ return authority# -- Error helper ------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 8d2bd8237..088684c4f 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -36,9 +36,10 @@ import jsonimport loggingimport mathimport os+import sysimport timeimport uuid-from collections.abc import AsyncGenerator, Callable+from collections.abc import AsyncIterator, Callable, Mappingfrom concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom pathlib import Path@@ -52,14 +53,23 @@ from sie_sdk.queue_types import WorkItemfrom sie_server.adapters._generation_base import (FinishReason,GenerationAdapter,+ GenerationCapacityError,GenerationChunk,+ GenerationDrainingError,+ GenerationError,+ GenerationPreflightResult,ReasoningFormat,ToolCallDelta,+ aclose_with_error_precedence,+ client_safe_generation_error_code,+ client_safe_generation_error_message,+ client_safe_generation_error_param,reasoning_starts_in_prompt,resolve_reasoning_format,suppress_thinking_blocks,thinking_blocks_must_be_hidden,)+from sie_server.api.helpers import oom_retry_after_from_registryfrom sie_server.config.model import validate_chat_template_kwargsfrom sie_server.core.runtime_options import apply_generation_runtime_optionsfrom sie_server.core.text_tokens import estimate_tokens_from_chars@@ -178,6 +188,12 @@ class NatsPublisher(Protocol):logger = logging.getLogger(__name__)+_INTERNAL_GENERATION_PREFLIGHT_MESSAGE = "internal error during generation preflight"+_INTERNAL_GENERATION_MESSAGE = "internal error during generation"+_INTERNAL_GRAMMAR_COMPILE_MESSAGE = "internal error compiling grammar"+_INTERNAL_CHAT_TEMPLATE_MESSAGE = "failed to render the model-native message prompt"+_GENERATION_ITERATOR_CLOSE_TIMEOUT_S = 2.0+# Default delay when NAKing a generate item because the model is not yet# loaded — matches the encode/extract path's behavior._NAK_DELAY_S = 5.0@@ -203,6 +219,10 @@ _CHUNK_QUEUE_MAX = 64# Per H6 remediation (workstream C)._CHUNK_PUT_TIMEOUT_S = 0.1+# Matches the validated EngineConfig.oom_recovery.retry_after_s domain and+# the gateway's independent trust-boundary check.+_RESOURCE_EXHAUSTED_RETRY_AFTER_MAX_S = 60+# Longer timeout for enqueuing the ``transport_failure`` terminal itself.# Reached only after a content-chunk enqueue already gave up: the publisher# is likely under brief sustained pressure (slow NATS, fan-out backlog).@@ -682,6 +702,53 @@ class _GenerateRequestParams:lora_adapter: str | None = None+def _adapter_generate_parameters(+ *,+ prompt: str,+ params: _GenerateRequestParams,+ grammar: GrammarSpec | None,+ images: list[ImageInput] | None,+) -> dict[str, Any]:+ """Build the exact adapter keyword mapping used for preflight and dispatch."""+ values: dict[str, Any] = {+ "prompt": prompt,+ "max_new_tokens": params.max_new_tokens,+ "temperature": params.temperature,+ "top_p": params.top_p,+ "stop": params.stop,+ }+ if params.frequency_penalty is not None:+ values["frequency_penalty"] = params.frequency_penalty+ if params.presence_penalty is not None:+ values["presence_penalty"] = params.presence_penalty+ if params.top_k is not None:+ values["top_k"] = params.top_k+ if params.repetition_penalty is not None:+ values["repetition_penalty"] = params.repetition_penalty+ if params.min_tokens is not None:+ values["min_new_tokens"] = params.min_tokens+ if grammar is not None:+ values["grammar"] = grammar+ if params.seed is not None:+ values["seed"] = params.seed+ if params.logit_bias:+ values["logit_bias"] = params.logit_bias+ if params.logprobs:+ values["logprobs"] = True+ if params.top_logprobs is not None and params.top_logprobs > 0:+ values["top_logprobs"] = params.top_logprobs+ if params.n is not None and params.n > 1:+ values["n"] = params.n+ values["stream"] = params.stream+ if params.best_of is not None and params.best_of > 1:+ values["best_of"] = params.best_of+ if params.lora_adapter:+ values["lora_path"] = params.lora_adapter+ if images:+ values["images"] = images+ return values++class StreamingProcessor:"""Process a single generate work item end-to-end (streaming)."""@@ -795,9 +862,8 @@ class StreamingProcessor:async def prewarm_grammars_for_model(self, model_id: str) -> None:"""Compile and cache ``tasks.generate.prewarm_grammars`` for ``model_id``.- Called once per generation model at worker boot through- ``IpcServer`` after the registry knows the config but before the- sidecar dispatches request-shape work.+ Called once for the requested generation model through ``IpcServer``+ before its first routed request reaches generation processing.The cache key shape mirrors :meth:`_ensure_grammar_ready` exactlyso a request hitting one of the prewarmed grammars takes thecache-hit branch.@@ -808,10 +874,9 @@ class StreamingProcessor:continues to the next entry. The model still loads. Operatorssee the failure via metrics + logs rather than as a startup crash.- Non-generation models are silent no-ops (the- :func:`~sie_server.core.pool_isolation.is_generation_model` gate- runs at the call site; this method also short-circuits on- missing ``tasks.generate`` for defence-in-depth).+ Non-generation models are silent no-ops. ``IpcServer`` checks the+ requested config before calling, and this method also short-circuits+ on missing ``tasks.generate`` for defence-in-depth."""try:config = self._registry.get_config(model_id)@@ -1598,6 +1663,23 @@ class StreamingProcessor:)returnparams = validation+ if (+ params.stream+ and config is not None+ and config.tasks.generate is not None+ and not config.tasks.generate.capabilities.streaming+ ):+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code="unsupported_field",+ message=f"Model '{model_id}' does not support streaming generation",+ param="stream",+ msg=msg,+ )+ returnsuppress_thinking = thinking_blocks_must_be_hidden(config)reasoning_format = resolve_reasoning_format(config, adapter)@@ -1689,6 +1771,7 @@ class StreamingProcessor:model_id,prompt_str,params.max_new_tokens,+ adapter=adapter,num_images=len(request_images) if request_images else 0,)if ctx_error is not None:@@ -1779,6 +1862,40 @@ class StreamingProcessor:)return+ generation_parameters = _adapter_generate_parameters(+ prompt=prompt_str,+ params=params,+ grammar=effective_grammar,+ images=request_images,+ )+ try:+ preflight_result = adapter.preflight_generate(generation_parameters, stream=params.stream)+ except GenerationError as exc:+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code=exc.code,+ message=client_safe_generation_error_message(exc.code, str(exc)),+ param=client_safe_generation_error_param(exc),+ retry_after_s=_generation_error_retry_after_s(exc, self._registry),+ msg=msg,+ )+ return+ except Exception: # noqa: BLE001 - unexpected backend faults are terminal+ logger.warning("Generate preflight failed for %s/%s", request_id, attempt_id, exc_info=True)+ await self._terminal_error_then_settle(+ reply_subject,+ request_id=request_id,+ attempt_id=attempt_id,+ seq=0,+ code="inference_error",+ message=_INTERNAL_GENERATION_PREFLIGHT_MESSAGE,+ msg=msg,+ )+ return+# KV-cache admission control. The reservation covers# both the (cheap, char-based) input-token estimate and the# client-requested ``max_new_tokens``. When admission is on and@@ -1848,17 +1965,6 @@ class StreamingProcessor:request_id=request_id,attempt_id=attempt_id,received_at=received_at,- prompt=prompt_str,- max_new_tokens=params.max_new_tokens,- temperature=params.temperature,- top_p=params.top_p,- stop=params.stop,- frequency_penalty=params.frequency_penalty,- presence_penalty=params.presence_penalty,- top_k=params.top_k,- repetition_penalty=params.repetition_penalty,- min_tokens=params.min_tokens,- chat_template_kwargs=params.chat_template_kwargs,suppress_thinking=suppress_thinking,thinking_starts_in_prompt=thinking_starts_in_prompt,reasoning_format=reasoning_format,@@ -1867,15 +1973,10 @@ class StreamingProcessor:enable_tool_parser=enable_tool_parser,tool_call_format=tool_call_format,parallel_tool_calls=params.parallel_tool_calls,- seed=params.seed,- logit_bias=params.logit_bias,- logprobs=params.logprobs,- top_logprobs=params.top_logprobs,n=params.n,- best_of=params.best_of,stream=params.stream,- lora_adapter=params.lora_adapter,- images=request_images,+ generation_parameters=generation_parameters,+ preflight_result=preflight_result,cancel_event=cancel_event,)finally:@@ -1907,21 +2008,6 @@ class StreamingProcessor:request_id: str,attempt_id: str,received_at: float,- prompt: str,- max_new_tokens: int,- temperature: float,- top_p: float,- stop: list[str] | None,- frequency_penalty: float | None = None,- presence_penalty: float | None = None,- top_k: int | None = None,- repetition_penalty: float | None = None,- min_tokens: int | None = None,- # ``chat_template_kwargs`` is consumed upstream in- # :meth:`_render_chat_template`; accepted here only so the- # caller can forward the whole ``params`` block without sniffing- # which fields belong to which stage.- chat_template_kwargs: dict[str, Any] | None = None,suppress_thinking: bool = False,thinking_starts_in_prompt: bool = False,reasoning_format: ReasoningFormat = "qwen3",@@ -1930,15 +2016,10 @@ class StreamingProcessor:enable_tool_parser: bool | None = None,tool_call_format: ToolCallFormat = "auto",parallel_tool_calls: bool = True,- seed: int | None = None,- logit_bias: dict[str, float] | None = None,- logprobs: bool = False,- top_logprobs: int | None = None,n: int | None = None,- best_of: int | None = None,stream: bool = False,- lora_adapter: str | None = None,- images: list[ImageInput] | None = None,+ generation_parameters: Mapping[str, Any],+ preflight_result: GenerationPreflightResult | None = None,cancel_event: asyncio.Event,) -> None:# ``adapter.generate`` is typed as returning ``AsyncIterator`` on@@ -1946,68 +2027,10 @@ class StreamingProcessor:# ``yield``) — narrow here so we can call ``aclose()`` for# cancellation cleanup.#- # ``grammar`` is passed via ``**kwargs`` so existing- # GenerationAdapter implementations that don't accept the kwarg- # still work for non-grammar requests (``grammar is None`` →- # not forwarded). The SGLang adapter accepts the kwarg and- # forwards the raw schema/regex to its ``/generate`` endpoint.- gen_kwargs: dict[str, Any] = {- "prompt": prompt,- "max_new_tokens": max_new_tokens,- "temperature": temperature,- "top_p": top_p,- "stop": stop,- }- # Only forward penalties when set. Older adapters that don't- # accept the kwarg still work for the (overwhelmingly common)- # no-penalty path; the SGLang adapter accepts both.- if frequency_penalty is not None:- gen_kwargs["frequency_penalty"] = frequency_penalty- if presence_penalty is not None:- gen_kwargs["presence_penalty"] = presence_penalty- # Non-OpenAI sampler knobs — forward only when set so older- # adapters that don't accept the kwargs still work for the common- # path; the SGLang adapter accepts both.- if top_k is not None:- gen_kwargs["top_k"] = top_k- if repetition_penalty is not None:- gen_kwargs["repetition_penalty"] = repetition_penalty- if min_tokens is not None:- # SGLang names the knob ``min_new_tokens`` server-side; the- # OpenAI-compat surface (mirroring vLLM / Together) takes it- # as ``min_tokens``. Translate at this edge.- gen_kwargs["min_new_tokens"] = min_tokens- # ``chat_template_kwargs`` is consumed in _render_chat_template- # upstream; nothing to forward from here.- _ = chat_template_kwargs- if grammar is not None:- gen_kwargs["grammar"] = grammar- # Optional sampler controls: seed / logit_bias / logprobs / top_logprobs. Only- # forward when set so older adapters that don't accept the- # kwargs still work for the (common) no-extra-sampler path.- if seed is not None:- gen_kwargs["seed"] = seed- if logit_bias:- gen_kwargs["logit_bias"] = logit_bias- if logprobs:- gen_kwargs["logprobs"] = logprobs- if top_logprobs is not None and top_logprobs > 0:- gen_kwargs["top_logprobs"] = top_logprobs- if n is not None and n > 1:- gen_kwargs["n"] = n- # Streaming n>1 fans candidates out as per-choice_index deltas;- # non-streaming collects them into the terminal candidates[].- gen_kwargs["stream"] = stream- if best_of is not None and best_of > 1:- gen_kwargs["best_of"] = best_of- if lora_adapter:- # SGLang selects the adapter by its registered served-name via- # sampling_params.lora_path; no path resolution needed here.- gen_kwargs["lora_path"] = lora_adapter- # Vision: forward decoded images only when present so text-only- # requests (and adapters that don't accept the kwarg) are unaffected.- if images:- gen_kwargs["images"] = images+ # The exact mapping was built once and already passed to preflight.+ # Dispatch a copy of that mapping so admission and execution cannot+ # drift through a second set of keyword-construction rules.+ gen_kwargs = dict(generation_parameters)# Worker-side phase boundary (#3136): everything between work receipt# and this adapter dispatch — deserialization, validation, model load,# chat-template render, context checks, and KV-admission wait — is the@@ -2021,18 +2044,12 @@ class StreamingProcessor:grammar="none" if grammar is None else grammar.kind,duration_s=time.perf_counter() - received_at,)- chunks_iter = cast(- "AsyncGenerator[GenerationChunk, None]",- adapter.generate(**gen_kwargs),- )+ chunks_iter: AsyncIterator[GenerationChunk] = adapter.generate_with_preflight(gen_kwargs, preflight_result)if suppress_thinking:- chunks_iter = cast(- "AsyncGenerator[GenerationChunk, None]",- suppress_thinking_blocks(- chunks_iter,- start_inside=thinking_starts_in_prompt,- reasoning_format=reasoning_format,- ),+ chunks_iter = suppress_thinking_blocks(+ chunks_iter,+ start_inside=thinking_starts_in_prompt,+ reasoning_format=reasoning_format,)# OpenAI tools: when enabled, wrap the adapter iterator with the# tool-call parser so ``<tool_call>{...}</tool_call>`` blocks@@ -2044,13 +2061,10 @@ class StreamingProcessor:# ``parallel_tool_calls`` is honoured by the parser.wrap_parser = enable_tool_parser if enable_tool_parser is not None else bool(tools)if wrap_parser:- chunks_iter = cast(- "AsyncGenerator[GenerationChunk, None]",- parse_tool_call_stream(- chunks_iter,- tool_call_format=tool_call_format,- parallel_tool_calls=parallel_tool_calls,- ),+ chunks_iter = parse_tool_call_stream(+ chunks_iter,+ tool_call_format=tool_call_format,+ parallel_tool_calls=parallel_tool_calls,)# Bounded chunk queue + a single publisher task drains it. If the@@ -2134,6 +2148,8 @@ class StreamingProcessor:last_flush_ts = time.monotonic()return True+ next_task: asyncio.Task[GenerationChunk] | None = None+ cancel_task: asyncio.Task[bool] | None = Nonetry:# Drive the iterator and the cancel-event together. When the# cancel event fires, we close the adapter iterator which@@ -2148,7 +2164,7 @@ class StreamingProcessor:while True:next_task = asyncio.create_task(_next_chunk())cancel_task = asyncio.create_task(cancel_event.wait())- done, _pending = await asyncio.wait(+ await asyncio.wait({next_task, cancel_task},return_when=asyncio.FIRST_COMPLETED,)@@ -2156,30 +2172,18 @@ class StreamingProcessor:# tick as the next chunk resolved, treat it as a cancel so# the caller's intent is honoured promptly.if cancel_event.is_set():- if next_task in done:- # Drain the result (or exception) to avoid warnings.- with _suppress():- next_task.result()- else:- next_task.cancel()- with _suppress():- await next_task- # Bound the time we spend in adapter teardown. The- # SGLang adapter's aclose handler spawns /abort_request- # as an independent background task (bounded separately)- # rather than awaiting it here, so aclose returns- # promptly; the cap is defence-in-depth against a- # misbehaving adapter blocking the publisher loop and- # stalling the JetStream heartbeat for the inflight- # window. ``TimeoutError`` is a subclass of ``Exception``- # so a single ``except Exception`` covers the cap.- try:- await asyncio.wait_for(chunks_iter.aclose(), timeout=2.0)- except Exception: # noqa: BLE001- logger.warning(- "adapter aclose timed out / errored on cancel for %s; continuing teardown",- request_id,- )+ await _cancel_and_drain_generation_task(+ next_task,+ preserve_failure=True,+ context="generation next-chunk task",+ )+ next_task = None+ await _cancel_and_drain_generation_task(+ cancel_task,+ preserve_failure=True,+ context="generation cancel-wait task",+ )+ cancel_task = None# Flush whatever we have, then emit a cancelled terminal.# If the pending flush fails, do NOT enqueue the cancel# terminal — putting the terminal ahead of unflushed text@@ -2214,9 +2218,12 @@ class StreamingProcessor:_record_failure()break- cancel_task.cancel()- with _suppress():- await cancel_task+ await _cancel_and_drain_generation_task(+ cancel_task,+ preserve_failure=True,+ context="generation cancel-wait task",+ )+ cancel_task = Nonetry:chunk: GenerationChunk = next_task.result()@@ -2254,6 +2261,16 @@ class StreamingProcessor:breakexcept Exception as exc: # noqa: BLE001logger.warning("Generate iterator raised for %s/%s", request_id, attempt_id, exc_info=True)+ if isinstance(exc, GenerationError):+ error_code = exc.code+ error_message = client_safe_generation_error_message(exc.code, str(exc))+ error_param = client_safe_generation_error_param(exc)+ error_retry_after_s = _generation_error_retry_after_s(exc, self._registry)+ else:+ error_code = "inference_error"+ error_message = _INTERNAL_GENERATION_MESSAGE+ error_param = None+ error_retry_after_s = Noneerr_payload = _encode_chunk(kind="chunk",request_id=request_id,@@ -2262,8 +2279,10 @@ class StreamingProcessor:text_delta="",done=True,finish_reason="error",- error_code="inference_error",- error_message=str(exc),+ error_code=error_code,+ error_message=error_message,+ error_param=error_param,+ error_retry_after_s=error_retry_after_s,)try:await _wait_for(@@ -2274,6 +2293,8 @@ class StreamingProcessor:except (asyncio.QueueFull, TimeoutError):_record_failure()break+ finally:+ next_task = None# Record first-text timing for TTFT.if chunk.text_delta and first_text_at is None:@@ -2348,6 +2369,11 @@ class StreamingProcessor:# gateway can surface the parse failure as a normal# error chunk instead of swallowing it under the# default ``stop`` reason.+ terminal_has_error = (+ chunk.error_code is not None+ or chunk.error_message is not None+ or chunk.finish_reason == "error"+ )terminal = _encode_chunk(kind="chunk",request_id=request_id,@@ -2359,8 +2385,12 @@ class StreamingProcessor:prompt_tokens=chunk.prompt_tokens,completion_tokens=chunk.completion_tokens,ttft_ms=_compute_ttft_ms(publish_at, first_text_at),- error_code=chunk.error_code,- error_message=chunk.error_message,+ error_code=(chunk.error_code or "inference_error") if terminal_has_error else None,+ error_message=(+ client_safe_generation_error_message(chunk.error_code, chunk.error_message)+ if terminal_has_error+ else None+ ),candidates=list(chunk.candidates) if chunk.candidates else None,)try:@@ -2438,6 +2468,38 @@ class StreamingProcessor:terminal_sent = await self._enqueue_transport_failure(chunk_queue, request_id, attempt_id, seq)breakfinally:+ # The per-iteration tasks are owned by this method. An outer-task+ # cancellation can land while ``asyncio.wait`` is pending, so drain+ # both children before closing the effective iterator. Then close+ # the outermost thinking/tool wrapper exactly once: each wrapper's+ # own ``finally`` recursively closes its upstream adapter iterator.+ # The two-second cap prevents a broken backend teardown from+ # holding the JetStream heartbeat and publisher forever.+ preserve_cleanup_failure = sys.exception() is not None or terminal_sent+ await _cancel_and_drain_generation_task(+ next_task,+ preserve_failure=preserve_cleanup_failure,+ context="generation next-chunk task",+ )+ await _cancel_and_drain_generation_task(+ cancel_task,+ preserve_failure=preserve_cleanup_failure,+ context="generation cancel-wait task",+ )+ iterator_close_error: BaseException | None = None+ try:+ await aclose_with_error_precedence(+ chunks_iter,+ outcome_selected=terminal_sent,+ context=f"queue generation iterator for {request_id}",+ timeout_s=_GENERATION_ITERATOR_CLOSE_TIMEOUT_S,+ )+ except BaseException as exc: # noqa: BLE001 - teardown must run even when this task is cancelled+ # Keep the close failure authoritative, but only after the+ # heartbeat and publisher tasks owned by this request have+ # been stopped and awaited below.+ iterator_close_error = exc+# Stop the heartbeat before draining the publisher so a# late in_progress() call doesn't race the final ACK.heartbeat_stop.set()@@ -2470,6 +2532,9 @@ class StreamingProcessor:await publisher_taskpublisher_ok = False+ if iterator_close_error is not None:+ raise iterator_close_error+# ACK after terminal publish (durable guarantee per §4.4 ACK timing).# H6: withhold ACK when the terminal we published was a# ``transport_failure`` — required content was dropped on the@@ -2698,6 +2763,13 @@ class StreamingProcessor:code="invalid_request",message="'max_new_tokens' must be a positive integer",)+ generate_task = config.tasks.generate if config is not None else None+ max_output_tokens = getattr(generate_task, "max_output_tokens", None)+ if isinstance(max_output_tokens, int) and max_new_tokens > max_output_tokens:+ return _ValidationError(+ code="context_exceeded",+ message=f"max_new_tokens ({max_new_tokens}) exceeds model cap ({max_output_tokens})",+ )has_prompt = "prompt" in paramshas_messages = "messages" in params@@ -3228,7 +3300,7 @@ class StreamingProcessor:"""try:tok = await self._get_tokenizer(model_id)- except Exception as exc: # noqa: BLE001+ except Exception: # noqa: BLE001logger.warning("Failed to load tokenizer for chat-template rendering on %s",model_id,@@ -3236,7 +3308,7 @@ class StreamingProcessor:)return _ValidationError(code="invalid_request",- message=f"failed to load tokenizer for chat-template rendering: {exc}",+ message=_INTERNAL_CHAT_TEMPLATE_MESSAGE,)# Tokenizer-extension kwargs (e.g. Qwen3's ``enable_thinking``).@@ -3323,15 +3395,15 @@ class StreamingProcessor:**kwargs,),)- except Exception as exc: # noqa: BLE001- logger.info(- "chat template render failed for %s: %s",+ except Exception: # noqa: BLE001+ logger.warning(+ "Chat template render failed for %s",model_id,- exc,+ exc_info=True,)return _ValidationError(code="invalid_request",- message=f"chat template render failed: {exc}",+ message=_INTERNAL_CHAT_TEMPLATE_MESSAGE,)if not isinstance(rendered, str):return _ValidationError(@@ -3345,12 +3417,16 @@ class StreamingProcessor:model_id: str,prompt: str,max_new_tokens: int,+ *,+ adapter: GenerationAdapter,num_images: int = 0,) -> _ValidationError | None:- """Worker-side ``prompt_tokens + max_new_tokens > context_length``- guard. Emits a terminal ``code: "context_exceeded"`` chunk when- the rendered prompt already overflows the budget the model- config declares.+ """Worker-side context-length guard.++ Shared accounting checks prompt plus requested output against one+ envelope. Independent accounting checks only the encoder input axis.+ Prompt tokenization follows the adapter's declared special-token+ policy so the guard matches backend usage accounting.Returns ``None`` if the budget is OK or if the model has nodeclared ``context_length`` (defensive — config validation@@ -3404,7 +3480,12 @@ class StreamingProcessor:loop = asyncio.get_running_loop()prompt_tokens = await loop.run_in_executor(_GRAMMAR_EXECUTOR,- lambda: len(tok.encode(encode_prompt, add_special_tokens=False)),+ lambda: len(+ tok.encode(+ encode_prompt,+ add_special_tokens=adapter.prompt_tokenization_add_special_tokens,+ )+ ),)except Exception: # noqa: BLE001logger.debug(@@ -3418,9 +3499,20 @@ class StreamingProcessor:# many tokens at inference. Add a coarse per-image estimate so the# guard fires before SGLang overflows its context window.image_tokens = num_images * _VISION_TOKENS_PER_IMAGE_ESTIMATE- total = prompt_tokens + image_tokens + max_new_tokens+ input_tokens = prompt_tokens + image_tokens+ image_note = f" + ~image_tokens ({image_tokens})" if image_tokens else ""+ if adapter.context_length_accounting == "independent":+ if input_tokens > context_length:+ return _ValidationError(+ code="context_exceeded",+ message=(+ f"prompt_tokens ({prompt_tokens}){image_note} = {input_tokens} "+ f"exceeds context_length ({context_length}) for model '{model_id}'"+ ),+ )+ return None+ total = input_tokens + max_new_tokensif total > context_length:- image_note = f" + ~image_tokens ({image_tokens})" if image_tokens else ""return _ValidationError(code="context_exceeded",message=(@@ -3534,16 +3626,22 @@ class StreamingProcessor:# follower settles its own work item rather than hanging# until ack_wait and triggering redelivery.await _wait_for(future_to_await, timeout=_GRAMMAR_FOLLOWER_TIMEOUT_S)- except Exception as exc: # noqa: BLE001+ except Exception: # noqa: BLE001# Leader's compile failed, was cancelled, or did not# resolve in time; surface the same terminal-error path.+ logger.warning(+ "Shared grammar compile failed for %s/%s",+ request_id,+ attempt_id,+ exc_info=True,+ )await self._terminal_error_then_settle(reply_subject,request_id=request_id,attempt_id=attempt_id,seq=0,code="grammar_compile_failed",- message=f"shared grammar compile failed: {exc}",+ message=_INTERNAL_GRAMMAR_COMPILE_MESSAGE,msg=msg,)return False@@ -3631,13 +3729,19 @@ class StreamingProcessor:except Exception as exc: # noqa: BLE001record_compile("error")future_to_await.set_exception(exc)+ logger.warning(+ "Tokenizer load failed during grammar compile for %s/%s",+ request_id,+ attempt_id,+ exc_info=True,+ )await self._terminal_error_then_settle(reply_subject,request_id=request_id,attempt_id=attempt_id,seq=0,code="grammar_compile_failed",- message=f"failed to load tokenizer for grammar compile: {exc}",+ message=_INTERNAL_GRAMMAR_COMPILE_MESSAGE,msg=msg,)return False@@ -3690,13 +3794,19 @@ class StreamingProcessor:# code rather than ``inference_error``.record_compile("error")future_to_await.set_exception(exc)+ logger.warning(+ "Unexpected grammar compile failure for %s/%s",+ request_id,+ attempt_id,+ exc_info=True,+ )await self._terminal_error_then_settle(reply_subject,request_id=request_id,attempt_id=attempt_id,seq=0,code="grammar_compile_failed",- message=f"grammar compile raised: {exc}",+ message=_INTERNAL_GRAMMAR_COMPILE_MESSAGE,msg=msg,)return False@@ -3765,6 +3875,8 @@ class StreamingProcessor:seq: int,code: str,message: str,+ param: str | None = None,+ retry_after_s: int | None = None,msg: Any,) -> None:"""Publish a terminal error chunk, then ACK on success / NAK on failure.@@ -3783,6 +3895,8 @@ class StreamingProcessor:seq=seq,code=code,message=message,+ param=param,+ retry_after_s=retry_after_s,)if published:await _safe_ack(msg)@@ -3836,6 +3950,8 @@ class StreamingProcessor:seq: int,code: str,message: str,+ param: str | None = None,+ retry_after_s: int | None = None,) -> bool:"""Publish a terminal error chunk to the inbox.@@ -3856,6 +3972,8 @@ class StreamingProcessor:finish_reason="error",error_code=code,error_message=message,+ error_param=param,+ error_retry_after_s=retry_after_s,)try:await self._publish_terminal_envelope(reply_subject, payload)@@ -3891,12 +4009,52 @@ class _Suppress:_suppress = _Suppress+async def _cancel_and_drain_generation_task(+ task: asyncio.Task[Any] | None,+ *,+ preserve_failure: bool,+ context: str,+) -> None:+ """Cancel and await one iterator-driver child task.++ A child cancellation is the expected cleanup result. Any other child+ failure remains authoritative only when there is no primary exception or+ already-selected terminal outcome to preserve.+ """+ if task is None:+ return+ if not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ return+ except BaseException:+ if preserve_failure:+ logger.warning(+ "%s failed during generation cleanup; preserving the primary outcome",+ context,+ exc_info=True,+ )+ return+ raise++def _compute_ttft_ms(publish_at: float, first_text_at: float | None) -> float | None:if first_text_at is None:return Nonereturn max(0.0, (first_text_at - publish_at) * 1000.0)+def _generation_error_retry_after_s(error: GenerationError, registry: Any) -> int | None:+ """Return the configured hint only for a true OOM-capacity refusal."""+ if isinstance(error, GenerationDrainingError):+ return None+ if isinstance(error, GenerationCapacityError):+ return oom_retry_after_from_registry(registry)+ return None++def _encode_chunk(*,kind: str,@@ -3912,6 +4070,8 @@ def _encode_chunk(ttft_ms: float | None = None,error_code: str | None = None,error_message: str | None = None,+ error_param: str | None = None,+ error_retry_after_s: int | None = None,tool_call_delta: ToolCallDelta | None = None,logprobs: list[dict[str, Any]] | None = None,candidates: list[dict[str, Any]] | None = None,@@ -3948,10 +4108,21 @@ def _encode_chunk(if ttft_ms is not None:payload["ttft_ms"] = ttft_msif error_code is not None or error_message is not None:- payload["error"] = {- "code": error_code or "error",+ safe_error_code = client_safe_generation_error_code(error_code)+ error: dict[str, Any] = {+ "code": safe_error_code,"message": error_message or "",}+ if error_param is not None:+ error["param"] = error_param+ if (+ safe_error_code == "RESOURCE_EXHAUSTED"+ and isinstance(error_retry_after_s, int)+ and not isinstance(error_retry_after_s, bool)+ and 1 <= error_retry_after_s <= _RESOURCE_EXHAUSTED_RETRY_AFTER_MAX_S+ ):+ error["retry_after_s"] = error_retry_after_s+ payload["error"] = errorif logprobs:# OpenAI ``ChatCompletionTokenLogprob`` entries, produced by the# adapter for the tokens in ``text_delta``. Forwarded verbatim;diff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.pyindex 7000bea36..6e89696e6 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py@@ -25,7 +25,12 @@ from collections.abc import AsyncIteratorfrom dataclasses import dataclass, fieldfrom typing import Literal, cast-from sie_server.adapters._generation_base import FinishReason, GenerationChunk, ToolCallDelta+from sie_server.adapters._generation_base import (+ FinishReason,+ GenerationChunk,+ ToolCallDelta,+ aclose_with_error_precedence,+)logger = logging.getLogger(__name__)@@ -82,17 +87,22 @@ async def parse_tool_call_stream(always ``aclose()``d (on cancel, early parse-error ``return``, and normalcompletion alike)."""+ terminal_outcome_selected = Falsetry:async for out in _parse_tool_call_stream_impl(chunks,tool_call_format=tool_call_format,parallel_tool_calls=parallel_tool_calls,):+ if out.done:+ terminal_outcome_selected = Trueyield outfinally:- aclose = getattr(chunks, "aclose", None)- if aclose is not None:- await aclose()+ await aclose_with_error_precedence(+ chunks,+ outcome_selected=terminal_outcome_selected,+ context="tool-call parser upstream iterator",+ )@dataclass@@ -432,6 +442,8 @@ async def _parse_tool_call_stream_impl(completion_tokens=chunk.completion_tokens,candidates=tuple(updated_candidates),logprobs=chunk.logprobs,+ error_code=chunk.error_code,+ error_message=chunk.error_message,)# Global terminal. Close any choices that did not see a# per-choice finish event (single-candidate path: this is@@ -476,6 +488,8 @@ async def _parse_tool_call_stream_impl(finish_reason=global_finish, # type: ignore[arg-type]prompt_tokens=chunk.prompt_tokens,completion_tokens=chunk.completion_tokens,+ error_code=chunk.error_code,+ error_message=chunk.error_message,# Preserve ``candidates`` (with any per-candidate# ``tool_calls`` injected above for the non-streaming# ``n>1`` + tools path) through the wrap.diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.pyindex 2cfbdd70d..986bb869f 100644--- a/packages/sie_server/src/sie_server/types/openapi.py+++ b/packages/sie_server/src/sie_server/types/openapi.py@@ -690,6 +690,13 @@ class GenerateChunkErrorModel(BaseModel):code: str = Field(..., description="Stable error code")message: str = Field(..., description="Client-safe error message")+ param: str | None = Field(default=None, description="Exact unsupported request field, when applicable")+ retry_after_s: int | None = Field(+ default=None,+ ge=1,+ le=60,+ description=("Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null for other terminal errors"),+ )class GenerateChunk(BaseModel):diff --git a/packages/sie_server/tests/adapters/test_adapter_revision_contract.py b/packages/sie_server/tests/adapters/test_adapter_revision_contract.pyindex 703673bbd..a0cad9fdc 100644--- a/packages/sie_server/tests/adapters/test_adapter_revision_contract.py+++ b/packages/sie_server/tests/adapters/test_adapter_revision_contract.py@@ -1,4 +1,4 @@-"""Loader contract: every adapter must accept (and honor) a pinned HF ``revision``.+"""Loader contract: every adapter must accept its loader-owned source identity.The model loader adds ``revision=config.hf_revision`` to the adapter constructorkwargs whenever a model YAML pins ``hf_revision`` (version identity).@@ -7,10 +7,14 @@ An adapter whose ``__init__`` rejects ``revision`` hard-fails at loadCI eval-loader failure this suite regresses against), and an adapter that acceptsit via ``**kwargs`` but never forwards it silently drops the pin.-This module enforces the *acceptance* half of that contract for EVERY adapter-class the package exposes, parameterized so a future adapter cannot regress-silently, plus *forwarding* spot-checks (clip / siglip / a flash adapter) that a-pinned revision actually reaches the HuggingFace ``from_pretrained`` call.+An adapter backed by a verified derived serving artifact is the deliberate+exception: the loader removes the source repo and revision and injects only the+explicit ``artifact_path`` and ``ct2_compute_type`` constructor fields.++This module enforces the applicable acceptance contract for EVERY adapter class+the package exposes, parameterized so a future adapter cannot regress silently,+plus forwarding spot-checks (clip / siglip / a flash adapter) that a pinned+revision actually reaches the HuggingFace ``from_pretrained`` call.Pure and offline: no weights are downloaded and no model is loaded — HF loadersare mocked, and signature inspection imports only the adapter modules.@@ -68,6 +72,12 @@ def _accepts_revision(cls: type) -> bool:return any(param.name == "revision" or param.kind is inspect.Parameter.VAR_KEYWORD for param in params)+def _accepts_verified_serving_artifact(cls: type) -> bool:+ """True when ``cls`` explicitly accepts the complete loader-owned artifact identity."""+ params = inspect.signature(cls.__init__).parameters+ return {"artifact_path", "ct2_compute_type"}.issubset(params)++def test_discovery_imported_the_adapter_package() -> None:"""Guard: discovery actually walked the package (not a mass import failure)."""# There are dozens of adapters; a tiny count means imports broke wholesale.@@ -81,7 +91,9 @@ def test_discovery_imported_the_adapter_package() -> None:@pytest.mark.parametrize("adapter_cls", _ADAPTER_CLASSES, ids=lambda cls: cls.__name__)def test_adapter_init_accepts_revision(adapter_cls: type) -> None:- """Every adapter ``__init__`` must accept the loader's pinned ``revision`` kwarg."""+ """HF-source adapters accept ``revision``; verified-artifact adapters accept their injected identity."""+ if _accepts_verified_serving_artifact(adapter_cls):+ returnassert _accepts_revision(adapter_cls), (f"{adapter_cls.__module__}.{adapter_cls.__name__}.__init__ must accept a 'revision' keyword ""(explicit 'revision: str | None = None' or **kwargs) so a YAML-pinned hf_revision is not "diff --git a/packages/sie_server/tests/adapters/test_ctranslate2_generation.py b/packages/sie_server/tests/adapters/test_ctranslate2_generation.pynew file mode 100644index 000000000..1734c84c5--- /dev/null+++ b/packages/sie_server/tests/adapters/test_ctranslate2_generation.py@@ -0,0 +1,510 @@+from __future__ import annotations++import asyncio+import threading+from dataclasses import dataclass+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest+from sie_server.adapters._generation_base import (+ GenerationCapacityError,+ GenerationDrainingError,+ GenerationError,+ GenerationInvalidRequestError,+ GenerationUnsupportedFieldError,+)+from sie_server.adapters.ctranslate2.generation import CTranslate2GenerationAdapter+++class _FakeTokenizer:+ def __init__(self, *, clean_up_tokenization_spaces: bool = False) -> None:+ self.encode_calls = 0+ self.decode_cleanup_calls: list[bool | None] = []+ self.clean_up_tokenization_spaces = clean_up_tokenization_spaces+ self._tokens = ["<s>", "</s>", "hello", "world", "bonjour", " monde", " !", "!"]+ self.eos_token_id = 1++ def encode(self, text: str, *, add_special_tokens: bool) -> list[int]:+ self.encode_calls += 1+ ids = [self._tokens.index(token) for token in text.split()]+ return [0, *ids, 1] if add_special_tokens else ids++ def convert_ids_to_tokens(self, token_ids: list[int]) -> list[str]:+ return [self._tokens[token_id] for token_id in token_ids]++ def convert_tokens_to_ids(self, tokens: list[str]) -> list[int]:+ return [self._tokens.index(token) for token in tokens]++ def decode(+ self,+ token_ids: list[int],+ *,+ skip_special_tokens: bool,+ clean_up_tokenization_spaces: bool | None = None,+ ) -> str:+ assert skip_special_tokens is True+ self.decode_cleanup_calls.append(clean_up_tokenization_spaces)+ clean_up = (+ self.clean_up_tokenization_spaces if clean_up_tokenization_spaces is None else clean_up_tokenization_spaces+ )+ text = "".join(self._tokens[token_id] for token_id in token_ids if token_id not in (0, 1))+ return text.replace(" !", "!") if clean_up else text+++@dataclass+class _FakeResult:+ hypotheses: list[list[str]]+++class _FakeTranslator:+ def __init__(self, *, block: threading.Event | None = None, append_end_token: bool = False) -> None:+ self.calls: list[dict[str, Any]] = []+ self.block = block+ self.append_end_token = append_end_token+ self.started = threading.Event()+ self.callback_stops: list[bool] = []+ self.unload_calls = 0++ def translate_batch(self, source: list[list[str]], **kwargs: Any) -> list[_FakeResult]:+ self.calls.append({"source": source, **kwargs})+ self.started.set()+ if self.block is not None:+ self.block.wait(timeout=2)+ max_length = kwargs["max_decoding_length"]+ outputs = ["bonjour", " monde"][:max_length]+ callback = kwargs["callback"]+ for batch_id in range(len(source)):+ for token in outputs:+ should_stop = callback(SimpleNamespace(batch_id=batch_id, hypothesis_id=0, token=token))+ self.callback_stops.append(should_stop)+ if should_stop:+ break+ result_tokens = [*outputs, "</s>"] if self.append_end_token else outputs+ return [_FakeResult(hypotheses=[list(result_tokens)]) for _ in source]++ def unload_model(self) -> None:+ self.unload_calls += 1+++class _FakeCTranslate2:+ __version__ = "4.8.1"++ def __init__(self, translator: _FakeTranslator | None = None) -> None:+ self.translator = translator or _FakeTranslator()+ self.translator_kwargs: dict[str, Any] | None = None+ self.seeds: list[int] = []++ @staticmethod+ def get_supported_compute_types(device: str, device_index: int) -> set[str]:+ assert device_index >= 0+ return {"float16", "int8_float16"} if device == "cuda" else {"float32", "int8_float32"}++ def Translator(self, _path: str, **kwargs: Any) -> _FakeTranslator: # noqa: N802+ self.translator_kwargs = kwargs+ return self.translator++ def set_random_seed(self, seed: int) -> None:+ self.seeds.append(seed)+++def _adapter(+ tmp_path: Path,+ *,+ translator: _FakeTranslator | None = None,+ native_batch_max_size: int = 8,+ native_batch_max_tokens: int = 64,+ native_batch_wait_ms: float = 5,+ max_pending_requests: int = 64,+) -> tuple[CTranslate2GenerationAdapter, _FakeTranslator, _FakeCTranslate2, _FakeTokenizer]:+ fake_translator = translator or _FakeTranslator()+ fake_module = _FakeCTranslate2(fake_translator)+ tokenizer = _FakeTokenizer()+ adapter = CTranslate2GenerationAdapter(+ artifact_path=tmp_path,+ ct2_compute_type="float16",+ max_seq_length=32,+ native_batch_max_size=native_batch_max_size,+ native_batch_max_tokens=native_batch_max_tokens,+ native_batch_wait_ms=native_batch_wait_ms,+ max_pending_requests=max_pending_requests,+ )+ adapter._translator = fake_translator+ adapter._tokenizer = tokenizer+ adapter._ctranslate2 = fake_module+ adapter._device = "cuda:0"+ return adapter, fake_translator, fake_module, tokenizer+++async def _collect(iterator: Any) -> list[Any]:+ return [chunk async for chunk in iterator]+++def test_context_length_accounting_is_independent() -> None:+ assert CTranslate2GenerationAdapter.context_length_accounting == "independent"+++def test_load_uses_verified_local_artifact_and_validates_compute_capability(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ adapter = CTranslate2GenerationAdapter(+ artifact_path=tmp_path,+ ct2_compute_type="int8_float16",+ )+ module = _FakeCTranslate2()+ tokenizer = _FakeTokenizer()+ tokenizer_load: dict[str, Any] = {}++ monkeypatch.setattr(+ "sie_server.adapters.ctranslate2.generation.importlib.import_module",+ lambda name: module if name == "ctranslate2" else pytest.fail(name),+ )++ def from_pretrained(path: str, **kwargs: Any) -> _FakeTokenizer:+ tokenizer_load.update({"path": path, **kwargs})+ return tokenizer++ monkeypatch.setattr(+ "sie_server.adapters.ctranslate2.generation.AutoTokenizer.from_pretrained",+ from_pretrained,+ )++ adapter.load("cuda:2")++ assert tokenizer_load == {+ "path": str(tmp_path),+ "local_files_only": True,+ "trust_remote_code": False,+ }+ assert module.translator_kwargs == {+ "device": "cuda",+ "device_index": 2,+ "compute_type": "int8_float16",+ "inter_threads": 1,+ "max_queued_batches": 1,+ }+++def test_load_rejects_unsupported_compute_type_before_translator_construction(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ adapter = CTranslate2GenerationAdapter(+ artifact_path=tmp_path,+ ct2_compute_type="int8_bfloat16",+ )+ module = _FakeCTranslate2()+ monkeypatch.setattr(+ "sie_server.adapters.ctranslate2.generation.importlib.import_module",+ lambda _name: module,+ )++ with pytest.raises(ValueError, match="not supported on cuda:0"):+ adapter.load("cuda:0")++ assert module.translator_kwargs is None+++def test_preflight_evidence_streams_and_reports_usage_with_exact_greedy_kwargs(tmp_path: Path) -> None:+ adapter, translator, module, tokenizer = _adapter(tmp_path)+ parameters = {+ "prompt": "hello world",+ "max_new_tokens": 2,+ "temperature": 0.0,+ "top_p": 1.0,+ "seed": 0,+ }+ preflight = adapter.preflight_generate(parameters, stream=True)++ chunks = asyncio.run(_collect(adapter.generate_with_preflight(parameters, preflight)))++ assert tokenizer.encode_calls == 1+ assert "".join(chunk.text_delta for chunk in chunks) == "bonjour monde"+ assert chunks[0].is_first is True+ assert chunks[-1].done is True+ assert chunks[-1].finish_reason == "length"+ assert (chunks[-1].prompt_tokens, chunks[-1].completion_tokens) == (4, 2)+ assert module.seeds == [0]+ call = translator.calls[0]+ assert call["source"] == [["<s>", "hello", "world", "</s>"]]+ assert {+ key: call[key]+ for key in (+ "max_batch_size",+ "batch_type",+ "beam_size",+ "num_hypotheses",+ "max_input_length",+ "max_decoding_length",+ "min_decoding_length",+ "sampling_topk",+ "sampling_topp",+ "sampling_temperature",+ "repetition_penalty",+ "return_end_token",+ )+ } == {+ "max_batch_size": 64,+ "batch_type": "tokens",+ "beam_size": 1,+ "num_hypotheses": 1,+ "max_input_length": 0,+ "max_decoding_length": 2,+ "min_decoding_length": 1,+ "sampling_topk": 1,+ "sampling_topp": 1.0,+ "sampling_temperature": 1.0,+ "repetition_penalty": 1.0,+ "return_end_token": True,+ }+++ ("clean_up_tokenization_spaces", "expected"),+ [(False, "bonjour monde !"), (True, "bonjour monde!")],+)+def test_output_detokenization_honors_tokenizer_cleanup_config(+ tmp_path: Path,+ clean_up_tokenization_spaces: bool,+ expected: str,+) -> None:+ adapter, _, _, tokenizer = _adapter(tmp_path)+ tokenizer.clean_up_tokenization_spaces = clean_up_tokenization_spaces++ assert adapter._decode_tokens(["bonjour", " monde", " !"]) == expected+ assert tokenizer.decode_cleanup_calls == [None]+++def test_natural_end_token_at_max_length_reports_stop_without_counting_or_decoding_it(tmp_path: Path) -> None:+ adapter, _, _, _ = _adapter(tmp_path, translator=_FakeTranslator(append_end_token=True))++ chunks = asyncio.run(_collect(adapter.generate("hello", max_new_tokens=2, seed=0)))++ assert "".join(chunk.text_delta for chunk in chunks) == "bonjour monde"+ assert chunks[-1].finish_reason == "stop"+ assert chunks[-1].completion_tokens == 2+++def test_scheduler_batches_only_exact_compatible_requests(tmp_path: Path) -> None:+ async def run() -> tuple[list[Any], list[Any], list[Any]]:+ adapter, translator, _, _ = _adapter(tmp_path, native_batch_wait_ms=20)+ first, second = await asyncio.gather(+ _collect(adapter.generate("hello", max_new_tokens=2, seed=0)),+ _collect(adapter.generate("world", max_new_tokens=2, seed=0)),+ )+ third = await _collect(adapter.generate("hello", max_new_tokens=1, seed=0))+ await adapter.drain_generation()+ assert [len(call["source"]) for call in translator.calls] == [2, 1]+ return first, second, third++ first, second, third = asyncio.run(run())+ assert first[-1].completion_tokens == second[-1].completion_tokens == 2+ assert third[-1].completion_tokens == 1+++def test_scheduler_enforces_native_source_token_bound(tmp_path: Path) -> None:+ async def run() -> None:+ adapter, translator, _, _ = _adapter(+ tmp_path,+ native_batch_max_tokens=5,+ native_batch_wait_ms=20,+ )+ await asyncio.gather(+ _collect(adapter.generate("hello", max_new_tokens=2, seed=0)),+ _collect(adapter.generate("world", max_new_tokens=2, seed=0)),+ )+ await adapter.drain_generation()+ assert [len(call["source"]) for call in translator.calls] == [1, 1]++ asyncio.run(run())+++ ("kwargs", "error_type", "param"),+ [+ ({"temperature": 0.5}, GenerationInvalidRequestError, "temperature"),+ ({"top_p": 0.9}, GenerationInvalidRequestError, "top_p"),+ ({"seed": 1}, GenerationInvalidRequestError, "seed"),+ ({"stop": ["!"]}, GenerationUnsupportedFieldError, "stop"),+ ({"frequency_penalty": 0.0}, GenerationUnsupportedFieldError, "frequency_penalty"),+ ({"n": 2}, GenerationUnsupportedFieldError, "n"),+ ({"n": True}, GenerationUnsupportedFieldError, "n"),+ ({"best_of": True}, GenerationUnsupportedFieldError, "best_of"),+ ({"top_k": True}, GenerationInvalidRequestError, "top_k"),+ ({"seed": False}, GenerationInvalidRequestError, "seed"),+ ({"logprobs": True}, GenerationUnsupportedFieldError, "logprobs"),+ ],+)+def test_preflight_rejects_non_greedy_or_unsupported_controls(+ tmp_path: Path,+ kwargs: dict[str, Any],+ error_type: type[Exception],+ param: str,+) -> None:+ adapter, translator, _, _ = _adapter(tmp_path)+ parameters = {+ "prompt": "hello",+ "max_new_tokens": 2,+ "temperature": 0.0,+ "top_p": 1.0,+ "seed": 0,+ **kwargs,+ }++ with pytest.raises(error_type) as raised:+ adapter.preflight_generate(parameters, stream=False)++ assert isinstance(raised.value, GenerationError)+ assert raised.value.param == param+ assert translator.calls == []+++def test_capacity_is_bounded_while_native_batch_is_running(tmp_path: Path) -> None:+ async def run() -> None:+ release = threading.Event()+ adapter, translator, _, _ = _adapter(+ tmp_path,+ translator=_FakeTranslator(block=release),+ native_batch_max_size=1,+ native_batch_wait_ms=0,+ max_pending_requests=1,+ )+ active = asyncio.create_task(_collect(adapter.generate("hello", max_new_tokens=2, seed=0)))+ assert await asyncio.to_thread(translator.started.wait, 1)+ queued = asyncio.create_task(_collect(adapter.generate("world", max_new_tokens=2, seed=0)))+ await asyncio.sleep(0)+ assert len(adapter._pending) == 1+ with pytest.raises(GenerationCapacityError):+ adapter.preflight_generate(+ {"prompt": "hello", "max_new_tokens": 2, "temperature": 0.0, "top_p": 1.0, "seed": 0},+ stream=False,+ )+ queued.cancel()+ with pytest.raises(asyncio.CancelledError):+ await queued+ release.set()+ chunks = await active+ assert chunks[-1].done is True+ await adapter.drain_generation()++ asyncio.run(run())+++def test_cancelling_running_member_discards_it_without_stopping_neighbor(tmp_path: Path) -> None:+ async def run() -> None:+ release = threading.Event()+ translator = _FakeTranslator(block=release)+ adapter, _, _, _ = _adapter(+ tmp_path,+ translator=translator,+ native_batch_max_size=2,+ native_batch_wait_ms=20,+ )+ cancelled, neighbor = (+ asyncio.create_task(_collect(adapter.generate("hello", max_new_tokens=2, seed=0))),+ asyncio.create_task(_collect(adapter.generate("world", max_new_tokens=2, seed=0))),+ )+ assert await asyncio.to_thread(translator.started.wait, 1)+ cancelled.cancel()+ with pytest.raises(asyncio.CancelledError):+ await cancelled+ release.set()+ chunks = await neighbor+ await adapter.drain_generation()+ assert chunks[-1].done is True+ assert translator.callback_stops+ assert any(translator.callback_stops)+ assert not all(translator.callback_stops)++ asyncio.run(run())+++def test_cancelling_all_running_members_stops_native_batch(tmp_path: Path) -> None:+ async def run() -> None:+ release = threading.Event()+ translator = _FakeTranslator(block=release)+ adapter, _, _, _ = _adapter(+ tmp_path,+ translator=translator,+ native_batch_max_size=1,+ native_batch_wait_ms=0,+ )+ request = asyncio.create_task(_collect(adapter.generate("hello", max_new_tokens=2, seed=0)))+ assert await asyncio.to_thread(translator.started.wait, 1)+ request.cancel()+ with pytest.raises(asyncio.CancelledError):+ await request+ release.set()+ await adapter.drain_generation()+ assert translator.callback_stops+ assert translator.callback_stops[0] is True++ asyncio.run(run())+++def test_drain_fails_queued_request_and_is_idempotent(tmp_path: Path) -> None:+ async def run() -> None:+ release = threading.Event()+ translator = _FakeTranslator(block=release)+ adapter, _, _, _ = _adapter(+ tmp_path,+ translator=translator,+ native_batch_max_size=1,+ native_batch_wait_ms=0,+ )+ active = asyncio.create_task(_collect(adapter.generate("hello", max_new_tokens=2, seed=0)))+ assert await asyncio.to_thread(translator.started.wait, 1)+ queued = asyncio.create_task(_collect(adapter.generate("world", max_new_tokens=2, seed=0)))+ await asyncio.sleep(0)+ assert len(adapter._pending) == 1+ drain = asyncio.create_task(adapter.drain_generation())+ with pytest.raises(GenerationDrainingError):+ await queued+ release.set()+ chunks = await active+ assert chunks[-1].done is True+ await drain+ await adapter.drain_generation()+ adapter.unload()+ adapter.unload()+ assert translator.unload_calls == 1++ asyncio.run(run())+++def test_unload_force_stops_undrained_native_batch_before_releasing_model(tmp_path: Path) -> None:+ async def run() -> None:+ release = threading.Event()+ translator = _FakeTranslator(block=release)+ adapter, _, _, _ = _adapter(+ tmp_path,+ translator=translator,+ native_batch_max_size=1,+ native_batch_wait_ms=0,+ )+ active = asyncio.create_task(_collect(adapter.generate("hello", max_new_tokens=2, seed=0)))+ assert await asyncio.to_thread(translator.started.wait, 1)+ queued = asyncio.create_task(_collect(adapter.generate("world", max_new_tokens=2, seed=0)))+ await asyncio.sleep(0)+ assert len(adapter._pending) == 1++ unloading = asyncio.create_task(asyncio.to_thread(adapter.unload))+ assert await asyncio.to_thread(adapter._force_stop.wait, 1)+ assert not unloading.done()+ assert translator.unload_calls == 0++ release.set()+ with pytest.raises(GenerationDrainingError):+ await active+ with pytest.raises(GenerationDrainingError):+ await queued+ await unloading++ assert translator.unload_calls == 1+ assert adapter._translator is None+ assert adapter._scheduler_task is None+ assert adapter._active_batch == ()+ assert adapter._active_batches == 0+ assert adapter._scheduler_stopped.is_set()++ asyncio.run(run())diff --git a/packages/sie_server/tests/adapters/test_generation_base.py b/packages/sie_server/tests/adapters/test_generation_base.pyindex 4a66a5bb2..add6a2224 100644--- a/packages/sie_server/tests/adapters/test_generation_base.py+++ b/packages/sie_server/tests/adapters/test_generation_base.py@@ -1,11 +1,19 @@from __future__ import annotations+import asynciofrom collections.abc import AsyncIteratorimport pytestfrom sie_server.adapters._generation_base import (GenerationChunk,+ GenerationError,+ GenerationInputTooLongError,+ GenerationInvalidRequestError,+ GenerationUnsupportedFieldError,ToolCallDelta,+ client_safe_generation_error_code,+ client_safe_generation_error_message,+ client_safe_generation_error_param,collect_generation,reasoning_starts_in_prompt,suppress_thinking_blocks,@@ -15,11 +23,124 @@ _GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"_GEMMA_CLOSE = "<" + "channel|" + ">"+class _FutureUnsupportedFieldError(GenerationUnsupportedFieldError):+ pass+++ ("code", "message", "expected"),+ [+ ("inference_error", "SENSITIVE_RUNTIME", "internal error during generation"),+ ("MODEL_OUTPUT_PARSE_ERROR", "invalid model JSON", "invalid model JSON"),+ ("future_adapter_error", "SENSITIVE_FUTURE_DETAIL", "generation terminated with an upstream error"),+ ],+)+def test_client_safe_generation_error_message_is_allowlisted(+ code: str,+ message: str,+ expected: str,+) -> None:+ assert client_safe_generation_error_message(code, message) == expected+++def test_client_safe_generation_error_code_is_closed() -> None:+ for code in [+ "inference_error",+ "grammar_compile_failed",+ "INPUT_TOO_LONG",+ "MODEL_LOADING",+ "MODEL_OUTPUT_PARSE_ERROR",+ "RESOURCE_EXHAUSTED",+ "COLD_START_RATE_LIMITED",+ "LORA_LOADING",+ "PAYLOAD_TOO_LARGE",+ "cancelled",+ "context_exceeded",+ "empty_model_output",+ "grammar_invalid",+ "invalid_request",+ "parallel_tool_calls_violated",+ "rate_limit_exceeded",+ "tool_call_parse_error",+ "transport_failure",+ "unsupported_field",+ ]:+ assert client_safe_generation_error_code(code) == code+ assert client_safe_generation_error_code("SENSITIVE_ADAPTER_ERROR_CODE_SENTINEL") == "inference_error"+++def test_client_safe_generation_error_param_is_subtype_and_value_bounded() -> None:+ internal = GenerationError("internal")+ internal.param = "n"++ assert client_safe_generation_error_param(internal) is None+ assert client_safe_generation_error_param(_FutureUnsupportedFieldError("n")) is None+ assert client_safe_generation_error_param(GenerationUnsupportedFieldError("SENSITIVE_FIELD")) is None+ assert client_safe_generation_error_param(GenerationUnsupportedFieldError("top_k")) == "top_k"+ assert client_safe_generation_error_param(GenerationUnsupportedFieldError("n")) == "n"+ assert client_safe_generation_error_param(GenerationUnsupportedFieldError("best_of")) == "best_of"+ assert client_safe_generation_error_param(GenerationInvalidRequestError("SENSITIVE_FIELD", "bad")) is None+ assert client_safe_generation_error_param(GenerationInvalidRequestError("top_logprobs", "bad")) == "top_logprobs"+ assert client_safe_generation_error_param(GenerationInputTooLongError("too long")) == "prompt"+ assert client_safe_generation_error_param(GenerationUnsupportedFieldError("lora_path")) == "lora_adapter"+ assert client_safe_generation_error_param(GenerationInvalidRequestError("lora_path", "bad")) == "lora_adapter"+ assert (+ client_safe_generation_error_param(GenerationInputTooLongError("too long", param="lora_path")) == "lora_adapter"+ )++async def _chunks(*chunks: GenerationChunk) -> AsyncIterator[GenerationChunk]:for chunk in chunks:yield chunk+class _FailingCloseSource:+ def __init__(self, chunks: list[GenerationChunk]) -> None:+ self._chunks = chunks+ self._index = 0+ self.close_calls = 0++ def __aiter__(self) -> _FailingCloseSource:+ return self++ async def __anext__(self) -> GenerationChunk:+ if self._index >= len(self._chunks):+ raise StopAsyncIteration+ chunk = self._chunks[self._index]+ self._index += 1+ return chunk++ async def aclose(self) -> None:+ self.close_calls += 1+ raise RuntimeError("cleanup failed")+++class _CloseTrackingSource:+ def __init__(self, chunks: list[GenerationChunk], *, error: BaseException | None = None) -> None:+ self._chunks = chunks+ self._index = 0+ self._error = error+ self.close_calls = 0+ self.next_started = asyncio.Event()++ def __aiter__(self) -> _CloseTrackingSource:+ return self++ async def __anext__(self) -> GenerationChunk:+ self.next_started.set()+ if self._index < len(self._chunks):+ chunk = self._chunks[self._index]+ self._index += 1+ return chunk+ if self._error is not None:+ raise self._error+ await asyncio.Event().wait()+ raise AssertionError("unreachable") # pragma: no cover++ async def aclose(self) -> None:+ self.close_calls += 1++@pytest.mark.asyncioasync def test_suppress_thinking_blocks_handles_delimiters_split_across_chunks() -> None:raw = "<think>private chain of thought</think>Visible answer"@@ -277,6 +398,27 @@ async def test_suppress_thinking_blocks_closes_upstream_on_client_cancel() -> Noassert closed is True+async def test_suppress_thinking_blocks_preserves_selected_terminal_when_close_fails() -> None:+ source = _FailingCloseSource([GenerationChunk(text_delta="visible", done=True, finish_reason="stop")])++ normalized = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert normalized[-1].done is True+ assert normalized[-1].finish_reason == "stop"+ assert source.close_calls == 1+++async def test_suppress_thinking_blocks_surfaces_standalone_close_failure() -> None:+ source = _FailingCloseSource([])++ with pytest.raises(RuntimeError, match="cleanup failed"):+ _ = [chunk async for chunk in suppress_thinking_blocks(source)]++ assert source.close_calls == 1++@pytest.mark.asyncioasync def test_reasoning_consuming_the_whole_budget_stamps_empty_output_error() -> None:"""#3104/#3136: budget exhausted inside a think block -> only whitespace is@@ -432,3 +574,46 @@ async def test_collect_generation_defaults_error_fields_to_none_on_success() ->assert result.text == "Visible answer"assert result.error_code is Noneassert result.error_message is None+++async def test_collect_generation_closes_terminal_input_exactly_once() -> None:+ source = _CloseTrackingSource([GenerationChunk(text_delta="done", done=True, finish_reason="stop")])++ result = await collect_generation(source)++ assert result.text == "done"+ assert source.close_calls == 1+++async def test_collect_generation_closes_input_and_preserves_iterator_error() -> None:+ source = _CloseTrackingSource([], error=RuntimeError("primary iterator failure"))++ with pytest.raises(RuntimeError, match="primary iterator failure"):+ await collect_generation(source)++ assert source.close_calls == 1+++async def test_collect_generation_closes_input_on_cancellation() -> None:+ source = _CloseTrackingSource([])+ task = asyncio.create_task(collect_generation(source))+ await asyncio.wait_for(source.next_started.wait(), timeout=1.0)++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert source.close_calls == 1+++async def test_collect_generation_preserves_selected_result_when_close_fails() -> None:+ source = _FailingCloseSource([GenerationChunk(text_delta="done", done=True, finish_reason="stop")])++ result = await collect_generation(source)++ assert result.text == "done"+ assert source.close_calls == 1diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex 5f5ef2819..ec234323b 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -423,7 +423,8 @@ def test_generate_collect_into_result(mock_async_client: MagicMock, adapter) ->'data: {"text": "abcdef", "meta_info": {"prompt_tokens": 1, "completion_tokens": 2, "finish_reason": {"type": "length"}}}',]stream = _FakeStreamingResponse(sse_lines)- mock_async_client.return_value = _make_client_with_stream(stream)+ client_instance = _make_client_with_stream(stream)+ mock_async_client.return_value = client_instanceadapter._server_url = "http://localhost:30005"result = asyncio.run(@@ -433,6 +434,34 @@ def test_generate_collect_into_result(mock_async_client: MagicMock, adapter) ->assert result.finish_reason == "length"assert result.prompt_tokens == 1assert result.completion_tokens == 2+ client_instance.post.assert_not_awaited()+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_queue_child_task_wrapper_close_does_not_abort_terminal_request(+ mock_async_client: MagicMock,+ adapter,+) -> None:+ stream = _FakeStreamingResponse(+ [+ 'data: {"text": "done", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}',+ ]+ )+ client_instance = _make_client_with_stream(stream)+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _run() -> None:+ chunks = suppress_thinking_blocks(adapter.generate(prompt="Hi", max_new_tokens=8))+ while True:+ chunk = await asyncio.create_task(anext(chunks))+ if chunk.done:+ break+ await chunks.aclose()++ asyncio.run(_run())++ client_instance.post.assert_not_awaited()@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")@@ -706,6 +735,100 @@ def test_generate_streaming_n_gt_one_fans_out_choice_index(mock_async_client: Maassert body["stream"] is True+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_streaming_n_gt_one_aclose_aborts_incomplete_request(+ mock_async_client: MagicMock,+ adapter,+) -> None:+ class _NeverEnding(_FakeStreamingResponse):+ async def aiter_lines(self):+ yield 'data: {"index": 0, "text": "first", "meta_info": {"prompt_tokens": 1}}'+ await asyncio.Event().wait() # pragma: no cover - closed by the test++ client_instance = _make_client_with_stream(_NeverEnding(lines=[]))+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _run() -> None:+ chunks = adapter.generate(prompt="Hi", max_new_tokens=8, n=2, stream=True)+ first = await anext(chunks)+ assert first.text_delta == "first"+ await chunks.aclose()+ if adapter._abort_tasks:+ await asyncio.gather(*tuple(adapter._abort_tasks))++ asyncio.run(_run())++ request_rid = client_instance.stream.call_args.kwargs["json"]["rid"]+ client_instance.post.assert_awaited_once()+ args, kwargs = client_instance.post.await_args+ assert args[0].endswith("/abort_request")+ assert kwargs["json"] == {"rid": request_rid}+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_streaming_n_gt_one_cancellation_aborts_incomplete_request(+ mock_async_client: MagicMock,+ adapter,+) -> None:+ class _NeverEnding(_FakeStreamingResponse):+ async def aiter_lines(self):+ yield 'data: {"index": 0, "text": "first", "meta_info": {"prompt_tokens": 1}}'+ await asyncio.Event().wait() # pragma: no cover - cancelled by the test++ client_instance = _make_client_with_stream(_NeverEnding(lines=[]))+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _run() -> None:+ chunks = adapter.generate(prompt="Hi", max_new_tokens=8, n=2, stream=True)+ assert (await anext(chunks)).text_delta == "first"+ pending = asyncio.create_task(anext(chunks))+ await asyncio.sleep(0)+ pending.cancel()+ with pytest.raises(asyncio.CancelledError):+ await pending+ if adapter._abort_tasks:+ await asyncio.gather(*tuple(adapter._abort_tasks))++ asyncio.run(_run())++ request_rid = client_instance.stream.call_args.kwargs["json"]["rid"]+ client_instance.post.assert_awaited_once()+ args, kwargs = client_instance.post.await_args+ assert args[0].endswith("/abort_request")+ assert kwargs["json"] == {"rid": request_rid}+++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_streaming_n_gt_one_terminal_close_does_not_abort(+ mock_async_client: MagicMock,+ adapter,+) -> None:+ stream = _FakeStreamingResponse(+ [+ 'data: {"index": 0, "text": "A", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}',+ 'data: {"index": 1, "text": "B", "meta_info": {"prompt_tokens": 1, "completion_tokens": 1, "finish_reason": {"type": "stop"}}}',+ "data: [DONE]",+ ]+ )+ client_instance = _make_client_with_stream(stream)+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _run() -> None:+ chunks = adapter.generate(prompt="Hi", max_new_tokens=8, n=2, stream=True)+ while not (await anext(chunks)).done:+ pass+ await chunks.aclose()+ if adapter._abort_tasks:+ await asyncio.gather(*tuple(adapter._abort_tasks))++ asyncio.run(_run())++ client_instance.post.assert_not_awaited()++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_generate_request_body_uses_stream_true(mock_async_client: MagicMock, adapter) -> None:sse_lines = [@@ -984,6 +1107,35 @@ def test_generate_aclose_triggers_abort_request(mock_async_client: MagicMock, adassert args[0].endswith("/abort_request")+@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")+def test_generate_task_cancellation_triggers_abort_request(mock_async_client: MagicMock, adapter) -> None:+ class _NeverEnding(_FakeStreamingResponse):+ async def aiter_lines(self):+ yield 'data: {"text": "first"}'+ await asyncio.Event().wait() # pragma: no cover - cancelled by the test++ client_instance = _make_client_with_stream(_NeverEnding(lines=[]))+ mock_async_client.return_value = client_instance+ adapter._server_url = "http://localhost:30005"++ async def _run() -> None:+ chunks = adapter.generate(prompt="Hi", max_new_tokens=64)+ assert (await anext(chunks)).text_delta == "first"+ pending = asyncio.create_task(anext(chunks))+ await asyncio.sleep(0)+ pending.cancel()+ with pytest.raises(asyncio.CancelledError):+ await pending+ if adapter._abort_tasks:+ await asyncio.gather(*tuple(adapter._abort_tasks))++ asyncio.run(_run())++ client_instance.post.assert_awaited_once()+ args, _ = client_instance.post.await_args+ assert args[0].endswith("/abort_request")++@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")def test_abort_completes_even_when_aclose_capped(mock_async_client: MagicMock, adapter) -> None:"""B2 regression: the /abort_request POST must be issued and completediff --git a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py b/packages/sie_server/tests/adapters/test_sglang_vision_extract.pyindex 1c2650756..fb459a3cf 100644--- a/packages/sie_server/tests/adapters/test_sglang_vision_extract.py+++ b/packages/sie_server/tests/adapters/test_sglang_vision_extract.py@@ -9,6 +9,7 @@ from pathlib import Pathfrom typing import Anyfrom unittest.mock import MagicMock, patch+import httpximport pytestimport yamlfrom sie_server.adapters._generation_base import GenerationChunk@@ -240,6 +241,81 @@ async def test_extract_async_refills_bounded_requests_and_preserves_order(assert peak_active == 2+async def test_extract_async_closes_each_buffered_generation_iterator(+ adapter: SGLangVisionExtractAdapter,+) -> None:+ sources: list[Any] = []++ class _TrackingPageGeneration:+ def __init__(self, marker: str) -> None:+ self.marker = marker+ self.yielded = False+ self.close_calls = 0++ def __aiter__(self) -> _TrackingPageGeneration:+ return self++ async def __anext__(self) -> GenerationChunk:+ if self.yielded:+ raise StopAsyncIteration+ self.yielded = True+ return GenerationChunk(+ text_delta=self.marker,+ done=True,+ finish_reason="stop",+ prompt_tokens=1,+ completion_tokens=1,+ )++ async def aclose(self) -> None:+ self.close_calls += 1++ def generate(*args: Any, images: list[ImageInput], **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ _ = (args, kwargs)+ source = _TrackingPageGeneration(images[0]["data"].decode())+ sources.append(source)+ return source++ adapter.generate = generate # ty: ignore[invalid-assignment]++ results = await adapter._extract_async(+ "rendered prompt",+ [_image("one"), _image("two")],+ max_new_tokens=32,+ )++ assert [result.text for result in results] == ["one", "two"]+ assert len(sources) == 2+ assert all(source.close_calls == 1 for source in sources)+++async def test_extract_async_success_does_not_abort_completed_sglang_request(+ adapter: SGLangVisionExtractAdapter,+) -> None:+ paths: list[str] = []++ def handle(request: httpx.Request) -> httpx.Response:+ paths.append(request.url.path)+ return httpx.Response(+ 200,+ content=(+ b'data: {"text": "page", "meta_info": {"prompt_tokens": 10, '+ b'"completion_tokens": 1, "finish_reason": {"type": "stop"}}}\n\n'+ ),+ )++ client = httpx.AsyncClient(transport=httpx.MockTransport(handle))+ adapter._http_client = client++ results = await adapter._extract_async("rendered prompt", [_image("page")], max_new_tokens=32)+ await client.aclose()++ assert [result.text for result in results] == ["page"]+ assert paths == ["/generate"]++def test_extract_requires_loaded_request_loop(adapter: SGLangVisionExtractAdapter) -> None:with pytest.raises(RuntimeError, match="Model not loaded"):adapter.extract([Item(images=[_image("page")])])diff --git a/packages/sie_server/tests/adapters/test_tensorrt_llm_compat.py b/packages/sie_server/tests/adapters/test_tensorrt_llm_compat.pynew file mode 100644index 000000000..68115f034--- /dev/null+++ b/packages/sie_server/tests/adapters/test_tensorrt_llm_compat.py@@ -0,0 +1,504 @@+from __future__ import annotations++import hashlib+import os+import subprocess+import sys+from pathlib import Path+from types import ModuleType, SimpleNamespace+from typing import Any++import pytest+import torch+from safetensors import safe_open+from safetensors.torch import load_file, save_file, save_model+from sie_server.adapters.tensorrt_llm import compat++_SITECUSTOMIZE_DIR = Path(compat.__file__).parent / "_compat"+_PINNED_MADLAD_EMBEDDING_SHAPE = (256_000, 1_024)+++def _compat_environment(prepend: Path) -> dict[str, str]:+ environment = os.environ.copy()+ environment["SIE_TRTLLM_RC24_COMPAT"] = "1"+ python_paths = (str(_SITECUSTOMIZE_DIR), str(prepend), environment.get("PYTHONPATH", ""))+ environment["PYTHONPATH"] = os.pathsep.join(path for path in python_paths if path)+ return environment+++def _write_fake_tensorrt_llm(root: Path, *, version: str) -> None:+ package = root / "tensorrt_llm"+ sources = {+ "__init__.py": "",+ "_torch/__init__.py": "",+ "_torch/models/__init__.py": "",+ "_torch/models/modeling_t5.py": "class T5ForConditionalGeneration:\n pass\n",+ "_torch/models/checkpoints/__init__.py": "",+ "_torch/models/checkpoints/hf/__init__.py": "",+ "_torch/models/checkpoints/hf/weight_loader.py": "class HfWeightLoader:\n pass\n",+ }+ for relative, contents in sources.items():+ path = package / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(contents, encoding="utf-8")+ metadata_dir = root / f"tensorrt_llm-{version}.dist-info"+ metadata_dir.mkdir()+ (metadata_dir / "METADATA").write_text(+ f"Metadata-Version: 2.1\nName: tensorrt-llm\nVersion: {version}\n",+ encoding="utf-8",+ )+++def _load_t5_weights(+ weights: dict[str, object], *, tie_word_embeddings: bool = True+) -> tuple[dict[str, object], object]:+ observed: dict[str, object] = {}+ sentinel = object()++ class Model:+ def __init__(self) -> None:+ self.model_config = SimpleNamespace(+ pretrained_config=SimpleNamespace(tie_word_embeddings=tie_word_embeddings)+ )++ def load_weights(self, incoming: dict[str, object], **_kwargs: object) -> object:+ observed.update(incoming)+ return sentinel++ module = SimpleNamespace(T5ForConditionalGeneration=Model)+ compat._install_t5_weight_patch(module)+ compat._install_t5_weight_patch(module)+ result = Model().load_weights(weights)+ assert result is sentinel+ return observed, result+++def _save_model_t5(checkpoint: Path, *, metadata: dict[str, str] | None = None) -> None:+ class SaveModelT5(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.shared = torch.nn.Embedding(4, 3)+ self.encoder = torch.nn.Module()+ self.encoder.embed_tokens = self.shared+ self.decoder = torch.nn.Module()+ self.decoder.embed_tokens = self.shared+ self.lm_head = torch.nn.Linear(3, 4, bias=False)++ save_model(SaveModelT5(), checkpoint, metadata=metadata)+++def test_t5_weight_patch_restores_legitimate_save_model_t5_alias(tmp_path: Path) -> None:+ checkpoint = tmp_path / "model.safetensors"+ _save_model_t5(checkpoint)+ with safe_open(checkpoint, framework="pt", device="cpu") as handle:+ assert handle.metadata() == {+ "encoder.embed_tokens.weight": "decoder.embed_tokens.weight",+ "shared.weight": "decoder.embed_tokens.weight",+ }+ weights = load_file(checkpoint)+ assert set(weights) == {"decoder.embed_tokens.weight", "lm_head.weight"}++ observed, _result = _load_t5_weights(weights)++ assert observed["shared.weight"] is weights["decoder.embed_tokens.weight"]+ assert observed["lm_head.weight"] is weights["lm_head.weight"]+++def test_t5_weight_patch_leaves_legitimate_non_t5_save_model_alias_opaque(tmp_path: Path) -> None:+ class TopLevelAlias(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.weight = torch.nn.Parameter(torch.zeros(2, 2))+ self.alias = self.weight++ checkpoint = tmp_path / "model.safetensors"+ save_model(TopLevelAlias(), checkpoint)+ with safe_open(checkpoint, framework="pt", device="cpu") as handle:+ assert handle.metadata() == {"weight": "alias"}+ weights = load_file(checkpoint)+ assert set(weights) == {"alias"}++ observed, _result = _load_t5_weights(weights)++ assert observed == weights+ assert "weight" not in observed+++def test_t5_weight_patch_ignores_user_metadata_collision_with_real_tensor_name(tmp_path: Path) -> None:+ checkpoint = tmp_path / "model.safetensors"+ _save_model_t5(checkpoint, metadata={"shared.weight": "lm_head.weight"})+ with safe_open(checkpoint, framework="pt", device="cpu") as handle:+ assert handle.metadata()["shared.weight"] == "lm_head.weight"+ weights = load_file(checkpoint)+ assert set(weights) == {"decoder.embed_tokens.weight", "lm_head.weight"}++ observed, _result = _load_t5_weights(weights, tie_word_embeddings=False)++ assert observed["shared.weight"] is weights["decoder.embed_tokens.weight"]+ assert observed["shared.weight"] is not weights["lm_head.weight"]+++def test_t5_weight_patch_restores_pinned_madlad_retained_embedding_shape() -> None:+ decoder_embedding = torch.empty(_PINNED_MADLAD_EMBEDDING_SHAPE, device="meta")+ lm_head = torch.empty(_PINNED_MADLAD_EMBEDDING_SHAPE, device="meta")++ observed, _result = _load_t5_weights(+ {+ "decoder.embed_tokens.weight": decoder_embedding,+ "lm_head.weight": lm_head,+ },+ tie_word_embeddings=False,+ )++ assert observed["shared.weight"] is decoder_embedding+ assert isinstance(observed["shared.weight"], torch.Tensor)+ assert tuple(observed["shared.weight"].shape) == _PINNED_MADLAD_EMBEDDING_SHAPE+ assert observed["lm_head.weight"] is lm_head+++def test_t5_weight_patch_ignores_arbitrary_dotted_metadata_chains_and_conflicts(tmp_path: Path) -> None:+ first = tmp_path / "first.safetensors"+ second = tmp_path / "second.safetensors"+ save_file(+ {"decoder.embed_tokens.weight": torch.zeros(2, 2)},+ first,+ metadata={+ "shared.weight": "unrelated.actual.weight",+ "attacker.chain.destination": "attacker.chain.source",+ "attacker.cycle.left": "attacker.cycle.right",+ },+ )+ save_file(+ {"unrelated.actual.weight": torch.ones(2, 2)},+ second,+ metadata={+ "shared.weight": "decoder.embed_tokens.weight",+ "attacker.chain.source": "decoder.embed_tokens.weight",+ "attacker.cycle.right": "attacker.cycle.left",+ },+ )+ with safe_open(first, framework="pt", device="cpu") as handle:+ assert handle.metadata()["shared.weight"] == "unrelated.actual.weight"+ with safe_open(second, framework="pt", device="cpu") as handle:+ assert handle.metadata()["shared.weight"] == "decoder.embed_tokens.weight"+ weights = {**load_file(first), **load_file(second)}++ observed, _result = _load_t5_weights(weights)++ assert observed["shared.weight"] is weights["decoder.embed_tokens.weight"]+ assert "attacker.chain.destination" not in observed+ assert "attacker.chain.source" not in observed+ assert "attacker.cycle.left" not in observed+ assert "attacker.cycle.right" not in observed+++ "source_key",+ ["encoder.embed_tokens.weight", "decoder.embed_tokens.weight"],+)+def test_t5_weight_patch_accepts_each_known_top_level_input_embedding(source_key: str) -> None:+ tensor = object()++ observed, _result = _load_t5_weights({source_key: tensor})++ assert observed["shared.weight"] is tensor++[email protected]("tie_word_embeddings", [True, False])+def test_t5_weight_patch_never_uses_lm_head_as_missing_shared_embedding(+ tie_word_embeddings: bool,+) -> None:+ lm_head = object()++ observed, _result = _load_t5_weights(+ {"lm_head.weight": lm_head},+ tie_word_embeddings=tie_word_embeddings,+ )++ assert observed == {"lm_head.weight": lm_head}+++def test_t5_weight_patch_accepts_identical_known_embedding_candidates() -> None:+ tensor = object()+ observed, _result = _load_t5_weights(+ {+ "encoder.embed_tokens.weight": tensor,+ "decoder.embed_tokens.weight": tensor,+ }+ )++ assert observed["shared.weight"] is tensor+++def test_t5_weight_patch_preserves_existing_shared_embedding() -> None:+ shared = object()+ decoder = object()++ observed, _result = _load_t5_weights(+ {+ "shared.weight": shared,+ "decoder.embed_tokens.weight": decoder,+ }+ )++ assert observed["shared.weight"] is shared+++def test_t5_weight_patch_rejects_distinct_known_embedding_candidates() -> None:+ with pytest.raises(RuntimeError, match="ambiguous T5 shared embedding tensors"):+ _load_t5_weights(+ {+ "encoder.embed_tokens.weight": object(),+ "decoder.embed_tokens.weight": object(),+ }+ )+++def test_rc24_install_leaves_generic_weight_loader_untouched(monkeypatch: pytest.MonkeyPatch) -> None:+ class Loader:+ def _prefetch_and_load(self, weight_files: tuple[str, ...]) -> tuple[str, ...]:+ return weight_files++ class Model:+ def __init__(self, _config: object) -> None:+ pass++ def load_weights(self, _weights: dict[str, object]) -> None:+ return None++ original_loader = Loader._prefetch_and_load+ weight_loader = SimpleNamespace(HfWeightLoader=Loader)+ modeling_t5 = SimpleNamespace(T5ForConditionalGeneration=Model)+ monkeypatch.setattr(compat, "verify_exact_rc24_sources", lambda *_args: None)+ monkeypatch.setattr(compat, "install_transformers_5_t5_tokenizer_compatibility", lambda: None)+ monkeypatch.setattr(+ compat.importlib,+ "import_module",+ lambda name: modeling_t5 if name.endswith("modeling_t5") else weight_loader,+ )++ compat.install_rc24_compatibility()++ assert Loader._prefetch_and_load is original_loader+++ ("scale_decoder_outputs", "tie_word_embeddings", "expected"),+ [(True, False, True), (False, True, False), (None, True, True), (None, False, False)],+)+def test_t5_patch_uses_saved_scaling_then_legacy_fallback(+ scale_decoder_outputs: bool | None,+ tie_word_embeddings: bool,+ expected: bool,+) -> None:+ class Model:+ def __init__(self, config: Any) -> None:+ _ = config+ self.rescale_before_lm_head = True++ compat._install_t5_scaling_patch(SimpleNamespace(T5ForConditionalGeneration=Model))+ fields: dict[str, Any] = {"tie_word_embeddings": tie_word_embeddings}+ if scale_decoder_outputs is not None:+ fields["scale_decoder_outputs"] = scale_decoder_outputs++ model = Model(SimpleNamespace(pretrained_config=SimpleNamespace(**fields)))++ assert model.rescale_before_lm_head is expected+++def test_t5_patch_rejects_missing_pretrained_config() -> None:+ class Model:+ def __init__(self, model_config: Any) -> None:+ _ = model_config+ self.rescale_before_lm_head = True++ compat._install_t5_scaling_patch(SimpleNamespace(T5ForConditionalGeneration=Model))++ with pytest.raises(RuntimeError, match="missing pretrained_config"):+ Model(SimpleNamespace(scale_decoder_outputs=False))+++def test_t5_tokenizer_patch_preserves_checkpoint_serialization(tmp_path: Path) -> None:+ tokenizer_path = tmp_path / "tokenizer.json"+ tokenizer_path.write_text("{}\n", encoding="utf-8")+ sentinel = object()+ calls: list[str] = []++ class Backend:+ @classmethod+ def convert_to_native_format(cls, trust_remote_code: bool = False, **kwargs: Any) -> dict[str, Any]:+ return {"fallback": cls.__name__, "trust_remote_code": trust_remote_code, **kwargs}++ class T5Tokenizer(Backend):+ pass++ class TokenizerFast:+ @staticmethod+ def from_file(path: str) -> object:+ calls.append(path)+ return sentinel++ module = SimpleNamespace(T5Tokenizer=T5Tokenizer)+ backend = SimpleNamespace(TokenizerFast=TokenizerFast)+ compat._install_t5_tokenizer_serialization_patch(module, backend)+ compat._install_t5_tokenizer_serialization_patch(module, backend)++ converted = T5Tokenizer.convert_to_native_format(+ tokenizer_file=str(tokenizer_path),+ trust_remote_code=False,+ revision="a" * 40,+ )++ assert converted == {"revision": "a" * 40, "tokenizer_object": sentinel}+ assert calls == [str(tokenizer_path)]+++def test_t5_tokenizer_patch_delegates_without_a_trusted_local_serialization(tmp_path: Path) -> None:+ missing = tmp_path / "missing.json"++ class Backend:+ @classmethod+ def convert_to_native_format(cls, trust_remote_code: bool = False, **kwargs: Any) -> dict[str, Any]:+ return {"fallback": cls.__name__, "trust_remote_code": trust_remote_code, **kwargs}++ class T5Tokenizer(Backend):+ pass++ module = SimpleNamespace(T5Tokenizer=T5Tokenizer)+ backend = SimpleNamespace(TokenizerFast=SimpleNamespace())+ compat._install_t5_tokenizer_serialization_patch(module, backend)++ assert T5Tokenizer.convert_to_native_format(+ tokenizer_file=str(missing),+ trust_remote_code=False,+ ) == {+ "fallback": "T5Tokenizer",+ "tokenizer_file": str(missing),+ "trust_remote_code": False,+ }+ assert T5Tokenizer.convert_to_native_format(+ tokenizer_file=str(missing),+ trust_remote_code=True,+ ) == {+ "fallback": "T5Tokenizer",+ "tokenizer_file": str(missing),+ "trust_remote_code": True,+ }+++def test_exact_source_guard_rejects_version_and_hash_drift(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ weight_path = tmp_path / "weight_loader.py"+ t5_path = tmp_path / "modeling_t5.py"+ weight_path.write_text("weight source\n")+ t5_path.write_text("t5 source\n")+ weight_module = ModuleType("weight_loader")+ weight_module.__file__ = str(weight_path)+ t5_module = ModuleType("modeling_t5")+ t5_module.__file__ = str(t5_path)++ monkeypatch.setattr(compat.importlib.metadata, "version", lambda _name: "1.3.0rc25")+ with pytest.raises(RuntimeError, match=r"requires 1\.3\.0rc24"):+ compat.verify_exact_rc24_sources(weight_module, t5_module)++ monkeypatch.setattr(compat.importlib.metadata, "version", lambda _name: "1.3.0rc24")+ monkeypatch.setattr(compat, "HF_WEIGHT_LOADER_SHA256", hashlib.sha256(weight_path.read_bytes()).hexdigest())+ monkeypatch.setattr(compat, "MODELING_T5_SHA256", "0" * 64)+ with pytest.raises(RuntimeError, match="changed source modeling_t5"):+ compat.verify_exact_rc24_sources(weight_module, t5_module)+++def test_exact_transformers_source_guard_rejects_version_and_hash_drift(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ t5_tokenization_path = tmp_path / "tokenization_t5.py"+ backend_path = tmp_path / "tokenization_utils_tokenizers.py"+ t5_tokenization_path.write_text("t5 tokenizer source\n")+ backend_path.write_text("backend source\n")+ t5_tokenization_module = ModuleType("tokenization_t5")+ t5_tokenization_module.__file__ = str(t5_tokenization_path)+ backend_module = ModuleType("tokenization_utils_tokenizers")+ backend_module.__file__ = str(backend_path)++ monkeypatch.setattr(compat.importlib.metadata, "version", lambda _name: "5.5.5")+ with pytest.raises(RuntimeError, match=r"requires Transformers 5\.5\.4"):+ compat.verify_exact_transformers_5_sources(t5_tokenization_module, backend_module)++ monkeypatch.setattr(compat.importlib.metadata, "version", lambda _name: "5.5.4")+ monkeypatch.setattr(+ compat,+ "T5_TOKENIZATION_SHA256",+ hashlib.sha256(t5_tokenization_path.read_bytes()).hexdigest(),+ )+ monkeypatch.setattr(compat, "TOKENIZERS_BACKEND_SHA256", "0" * 64)+ with pytest.raises(RuntimeError, match="changed source tokenization_utils_tokenizers"):+ compat.verify_exact_transformers_5_sources(t5_tokenization_module, backend_module)+++ ("failure", "expected_error"),+ [+ ("missing", "synthetic missing TensorRT-LLM"),+ ("version", "requires 1.3.0rc24, found 1.3.0rc25"),+ ("hash", "changed source"),+ ],+)+def test_sitecustomize_aborts_interpreter_on_compatibility_failure(+ tmp_path: Path,+ failure: str,+ expected_error: str,+) -> None:+ if failure == "missing":+ (tmp_path / "tensorrt_llm.py").write_text(+ 'raise ModuleNotFoundError("synthetic missing TensorRT-LLM")\n',+ encoding="utf-8",+ )+ else:+ _write_fake_tensorrt_llm(+ tmp_path,+ version="1.3.0rc25" if failure == "version" else "1.3.0rc24",+ )++ completed = subprocess.run(+ [sys.executable, "-c", 'print("INTERPRETER_CONTINUED")'],+ check=False,+ capture_output=True,+ env=_compat_environment(tmp_path),+ text=True,+ )++ assert completed.returncode != 0+ assert "INTERPRETER_CONTINUED" not in completed.stdout+ assert "TensorRT-LLM rc24 compatibility startup failed" in completed.stderr+ assert expected_error in completed.stderr+++def test_sitecustomize_allows_startup_after_successful_install(tmp_path: Path) -> None:+ package = tmp_path / "sie_server/adapters/tensorrt_llm"+ for relative in (+ "sie_server/__init__.py",+ "sie_server/adapters/__init__.py",+ "sie_server/adapters/tensorrt_llm/__init__.py",+ ):+ path = tmp_path / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text("", encoding="utf-8")+ (package / "compat.py").write_text(+ "import builtins\n\ndef install_rc24_compatibility():\n builtins.SIE_TRTLLM_COMPAT_INSTALLED = True\n",+ encoding="utf-8",+ )++ completed = subprocess.run(+ [+ sys.executable,+ "-c",+ "import builtins; assert builtins.SIE_TRTLLM_COMPAT_INSTALLED; print('PATCHED_STARTUP')",+ ],+ check=False,+ capture_output=True,+ env=_compat_environment(tmp_path),+ text=True,+ )++ assert completed.returncode == 0, completed.stderr+ assert completed.stdout == "PATCHED_STARTUP\n"+ assert "Error in sitecustomize" not in completed.stderrdiff --git a/packages/sie_server/tests/adapters/test_tensorrt_llm_generation.py b/packages/sie_server/tests/adapters/test_tensorrt_llm_generation.pynew file mode 100644index 000000000..2a9ac5d06--- /dev/null+++ b/packages/sie_server/tests/adapters/test_tensorrt_llm_generation.py@@ -0,0 +1,1393 @@+from __future__ import annotations++import asyncio+import json+import signal+import subprocess+import sys+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any, cast++import httpx+import pytest+from sie_server.adapters._generation_base import (+ GenerationDrainingError,+ GenerationInputTooLongError,+ GenerationInvalidRequestError,+ GenerationUnsupportedFieldError,+)+from sie_server.adapters._types import ComputePrecision+from sie_server.adapters.tensorrt_llm import _server+from sie_server.adapters.tensorrt_llm.generation import TensorRTLLMGenerationAdapter, _completion_logprobs+from transformers import AutoTokenizer++_REVISION = "a" * 40+++class _FixtureTokenizer:+ def __init__(self) -> None:+ self.calls: list[tuple[str, bool]] = []++ def encode(self, prompt: str, *, add_special_tokens: bool) -> list[int]:+ self.calls.append((prompt, add_special_tokens))+ return list(range(len(prompt.split()) + int(add_special_tokens)))+++def _adapter(**kwargs: Any) -> TensorRTLLMGenerationAdapter:+ adapter = TensorRTLLMGenerationAdapter(+ "fixture/t5",+ revision=_REVISION,+ max_seq_length=256,+ max_input_len=128,+ max_batch_size=2,+ max_num_tokens=256,+ encoder_max_num_tokens=256,+ decoder_cuda_graph_batch_sizes=[1, 2],+ encoder_cuda_graph_batch_sizes=[1, 2],+ encoder_cuda_graph_num_tokens=[64, 128],+ encoder_cuda_graph_seq_lens=[64, 128],+ **kwargs,+ )+ adapter._server_url = "http://127.0.0.1:30200"+ adapter._process = object() # type: ignore[assignment]+ adapter._tokenizer = _FixtureTokenizer()+ return adapter+++async def _collect(iterator: AsyncIterator[Any]) -> list[Any]:+ return [chunk async for chunk in iterator]+++def _sse(*events: object) -> bytes:+ lines = [f"data: {json.dumps(event)}\n\n" for event in events]+ lines.append("data: [DONE]\n\n")+ return "".join(lines).encode()+++def test_context_length_accounting_is_independent() -> None:+ assert TensorRTLLMGenerationAdapter.context_length_accounting == "independent"+++def test_runtime_config_requires_dual_bf16_and_bounded_encoder_decoder_profile() -> None:+ config = _adapter().runtime_config++ assert config == {+ "attn_backend": "TRTLLM",+ "dtype": "bfloat16",+ "model_kwargs": {"torch_dtype": "bfloat16"},+ "enable_chunked_prefill": False,+ "max_batch_size": 2,+ "max_beam_width": 1,+ "max_input_len": 128,+ "max_num_tokens": 256,+ "max_seq_len": 256,+ "encoder_max_batch_size": 2,+ "encoder_max_num_tokens": 256,+ "cuda_graph_config": {"batch_sizes": [1, 2], "enable_padding": True},+ "encoder_cuda_graph_config": {+ "batch_sizes": [1, 2],+ "num_tokens": [64, 128],+ "seq_lens": [64, 128],+ "enable_padding": True,+ },+ "enable_encoder_decoder_mixed_cuda_graph": True,+ "disable_overlap_scheduler": False,+ "kv_cache_config": {+ "enable_block_reuse": False,+ "free_gpu_memory_fraction": 0.85,+ "cross_kv_cache_fraction": 0.5,+ "use_kv_cache_manager_v2": False,+ },+ "scheduler_config": {"use_python_scheduler": True},+ }+++def test_runtime_config_supports_fp32_with_encoder_graphs_only() -> None:+ config = _adapter(+ compute_precision="float32",+ enable_decoder_cuda_graphs=False,+ enable_encoder_decoder_mixed_cuda_graph=False,+ ).runtime_config++ assert config["dtype"] == "float32"+ assert config["model_kwargs"] == {"torch_dtype": "float32"}+ assert config["cuda_graph_config"] is None+ assert config["encoder_cuda_graph_config"] == {+ "batch_sizes": [1, 2],+ "num_tokens": [64, 128],+ "seq_lens": [64, 128],+ "enable_padding": True,+ }+ assert config["enable_encoder_decoder_mixed_cuda_graph"] is False+++def test_runtime_config_supports_fp32_without_cuda_graphs() -> None:+ config = _adapter(+ compute_precision="float32",+ enable_decoder_cuda_graphs=False,+ enable_encoder_cuda_graphs=False,+ enable_encoder_decoder_mixed_cuda_graph=False,+ ).runtime_config++ assert config["dtype"] == "float32"+ assert config["model_kwargs"] == {"torch_dtype": "float32"}+ assert config["cuda_graph_config"] is None+ assert config["encoder_cuda_graph_config"] is None+ assert config["enable_encoder_decoder_mixed_cuda_graph"] is False+++ ("kwargs", "expected"),+ [+ (+ {"enable_decoder_cuda_graphs": False, "enable_encoder_decoder_mixed_cuda_graph": False},+ {"cuda_graph_config": None},+ ),+ (+ {"enable_encoder_cuda_graphs": False, "enable_encoder_decoder_mixed_cuda_graph": False},+ {"encoder_cuda_graph_config": None},+ ),+ (+ {"decoder_cuda_graph_enable_padding": False},+ {"cuda_graph_config": {"batch_sizes": [1, 2], "enable_padding": False}},+ ),+ (+ {"encoder_cuda_graph_enable_padding": False},+ {+ "encoder_cuda_graph_config": {+ "batch_sizes": [1, 2],+ "num_tokens": [64, 128],+ "seq_lens": [64, 128],+ "enable_padding": False,+ }+ },+ ),+ ({"enable_encoder_decoder_mixed_cuda_graph": False}, {"enable_encoder_decoder_mixed_cuda_graph": False}),+ ({"disable_overlap_scheduler": True}, {"disable_overlap_scheduler": True}),+ ],+)+def test_runtime_config_exposes_independent_generic_graph_controls(+ kwargs: dict[str, Any], expected: dict[str, Any]+) -> None:+ values = {+ "revision": _REVISION,+ "max_seq_length": 256,+ "max_input_len": 128,+ "max_batch_size": 2,+ "max_num_tokens": 256,+ "encoder_max_num_tokens": 256,+ "decoder_cuda_graph_batch_sizes": [1, 2],+ "encoder_cuda_graph_batch_sizes": [1, 2],+ "encoder_cuda_graph_num_tokens": [64, 128],+ "encoder_cuda_graph_seq_lens": [64, 128],+ }+ config = TensorRTLLMGenerationAdapter("fixture/t5", **values, **kwargs).runtime_config++ assert {name: config[name] for name in expected} == expected+++ "name",+ [+ "enable_decoder_cuda_graphs",+ "enable_encoder_cuda_graphs",+ "decoder_cuda_graph_enable_padding",+ "encoder_cuda_graph_enable_padding",+ "enable_encoder_decoder_mixed_cuda_graph",+ "disable_overlap_scheduler",+ ],+)[email protected]("value", [0, 1, "true", None])[email protected]("compute_precision", ["bfloat16", "float32"])+def test_graph_controls_require_actual_booleans(name: str, value: object, compute_precision: ComputePrecision) -> None:+ with pytest.raises(ValueError, match=f"{name} must be a boolean"):+ TensorRTLLMGenerationAdapter( # type: ignore[arg-type]+ "fixture/t5",+ revision=_REVISION,+ compute_precision=compute_precision,+ **{name: value},+ )++[email protected]("disabled_graph", ["enable_decoder_cuda_graphs", "enable_encoder_cuda_graphs"])+def test_mixed_graphs_require_both_graph_families(disabled_graph: str) -> None:+ with pytest.raises(ValueError, match="requires both CUDA graph families"):+ TensorRTLLMGenerationAdapter("fixture/t5", revision=_REVISION, **{disabled_graph: False})+++ ("enable_decoder_cuda_graphs", "enable_encoder_decoder_mixed_cuda_graph", "message"),+ [+ (True, True, "enable_decoder_cuda_graphs=false"),+ (True, False, "enable_decoder_cuda_graphs=false"),+ (False, True, "enable_encoder_decoder_mixed_cuda_graph=false"),+ ],+)+def test_fp32_rejects_decoder_and_mixed_cuda_graphs(+ enable_decoder_cuda_graphs: bool,+ enable_encoder_decoder_mixed_cuda_graph: bool,+ message: str,+) -> None:+ with pytest.raises(ValueError, match=message):+ TensorRTLLMGenerationAdapter(+ "fixture/t5",+ revision=_REVISION,+ compute_precision="float32",+ enable_decoder_cuda_graphs=enable_decoder_cuda_graphs,+ enable_encoder_decoder_mixed_cuda_graph=enable_encoder_decoder_mixed_cuda_graph,+ )+++ ("kwargs", "message"),+ [+ ({"revision": "main"}, "immutable"),+ ({"revision": _REVISION, "compute_precision": "float16"}, "bfloat16 or compute_precision=float32"),+ ({"revision": _REVISION, "compute_precision": []}, "bfloat16 or compute_precision=float32"),+ ({"revision": _REVISION, "compute_precision": {}}, "bfloat16 or compute_precision=float32"),+ ({"revision": _REVISION, "max_seq_length": 64, "max_input_len": 65}, "max_input_len"),+ ({"revision": _REVISION, "cross_kv_cache_fraction": 1.0}, "cross_kv_cache_fraction"),+ ],+)+def test_profile_validation_fails_closed(kwargs: dict[str, Any], message: str) -> None:+ with pytest.raises(ValueError, match=message):+ TensorRTLLMGenerationAdapter("fixture/t5", **kwargs)+++def test_factory_rejects_non_cuda_device() -> None:+ with pytest.raises(ValueError, match="requires a CUDA device"):+ TensorRTLLMGenerationAdapter.create_for_device("cpu", model_name_or_path="fixture/t5", revision=_REVISION)++[email protected]("device", ["cuda:-1", "cuda:not-an-index"])+def test_factory_rejects_invalid_cuda_device(device: str) -> None:+ with pytest.raises(ValueError, match="invalid CUDA device"):+ TensorRTLLMGenerationAdapter.create_for_device(+ device,+ model_name_or_path="fixture/t5",+ revision=_REVISION,+ )+++def test_load_uses_exact_cli_warmup_and_cleans_generated_files(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ adapter = _adapter(+ enable_decoder_cuda_graphs=False,+ enable_encoder_cuda_graphs=False,+ enable_encoder_decoder_mixed_cuda_graph=False,+ )+ adapter._server_url = None+ adapter._process = None+ captured: dict[str, Any] = {}+ process = object()+ tokenizer = _FixtureTokenizer()++ monkeypatch.setattr(_server, "reserve_port", lambda: 30241)+ monkeypatch.setattr(adapter, "_load_tokenizer", lambda: tokenizer)++ def launch(command: list[str], **kwargs: Any) -> object:+ captured["command"] = command+ captured.update(kwargs)+ return process++ def wait_until_ready(child: object, url: str, **kwargs: Any) -> None:+ assert child is process+ assert url == "http://127.0.0.1:30241"+ assert kwargs["served_model_name"] == "fixture/t5"+ config_path = Path(captured["command"][captured["command"].index("--config") + 1])+ captured["config_path"] = config_path+ written_config = json.loads(config_path.read_text())+ assert written_config == adapter.runtime_config+ assert written_config["cuda_graph_config"] is None+ assert written_config["encoder_cuda_graph_config"] is None++ monkeypatch.setattr(_server, "launch", launch)+ monkeypatch.setattr(_server, "wait_until_ready", wait_until_ready)+ monkeypatch.setattr(_server, "terminate", lambda child: captured.setdefault("terminated", child))+ monkeypatch.setattr(_server, "release_port", lambda port: captured.setdefault("released", port))++ adapter.load("cuda:1")++ assert captured["command"] == [+ "trtllm-serve",+ "fixture/t5",+ "--backend",+ "pytorch",+ "--host",+ "127.0.0.1",+ "--port",+ "30241",+ "--config",+ str(captured["config_path"]),+ "--hf_revision",+ _REVISION,+ "--served_model_name",+ "fixture/t5",+ "--no-telemetry",+ ]+ assert captured["device_index"] == 1+ assert captured["environment"]["SIE_TRTLLM_RC24_COMPAT"] == "1"+ assert captured["environment"]["PYTHONPATH"].split(":")[0].endswith("tensorrt_llm/_compat")+ config_path = captured["config_path"]+ log_path = Path(adapter._output_file.name) # type: ignore[union-attr]+ adapter.unload()+ assert captured["terminated"] is process+ assert captured["released"] == 30241+ assert adapter._tokenizer is None+ assert not config_path.exists()+ assert not log_path.exists()+++def test_startup_warmup_uses_only_remaining_deadline(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, Any] = {}+ monotonic_values = iter((10.0, 11.0, 13.0))++ class Process:+ @staticmethod+ def poll() -> None:+ return None++ class Response:+ status_code = 200++ @staticmethod+ def raise_for_status() -> None:+ return None++ @staticmethod+ def json() -> dict[str, list[object]]:+ return {"choices": []}++ monkeypatch.setattr(_server.time, "monotonic", lambda: next(monotonic_values))+ monkeypatch.setattr(_server.requests, "get", lambda *_args, **_kwargs: Response())++ def post(*_args: Any, **kwargs: Any) -> Response:+ captured.update(kwargs)+ return Response()++ monkeypatch.setattr(_server.requests, "post", post)++ _server.wait_until_ready(+ Process(), # type: ignore[arg-type]+ "http://127.0.0.1:30200",+ served_model_name="fixture/t5",+ output_file=None,+ timeout_s=5.0,+ )++ assert captured["timeout"] == 2.0+++def test_log_tail_reads_only_a_bounded_suffix(monkeypatch: pytest.MonkeyPatch) -> None:+ output_file = _server.open_output_log()+ try:+ output_file.write(("prefix-" + ("x" * 100_000) + "-suffix").encode())+ monkeypatch.setattr(Path, "read_text", lambda *_args, **_kwargs: pytest.fail("read whole log"))++ assert _server.log_tail(output_file, chars=12) == "xxxxx-suffix"+ finally:+ output_file.close()+ Path(output_file.name).unlink()+++def test_default_http_client_has_bounded_stream_read_timeout() -> None:+ adapter = _adapter()++ client = asyncio.run(adapter._get_or_create_http_client())++ assert client.timeout.read == 300.0+ asyncio.run(adapter.aclose_client())+++def test_tokenizer_load_is_revision_pinned_and_disables_remote_code(monkeypatch: pytest.MonkeyPatch) -> None:+ adapter = _adapter()+ tokenizer = _FixtureTokenizer()+ captured: dict[str, Any] = {}+ compatibility_calls = 0++ def install_compatibility() -> None:+ nonlocal compatibility_calls+ compatibility_calls += 1++ def from_pretrained(model_name_or_path: str, **kwargs: Any) -> _FixtureTokenizer:+ captured["model_name_or_path"] = model_name_or_path+ captured.update(kwargs)+ return tokenizer++ monkeypatch.setattr(AutoTokenizer, "from_pretrained", from_pretrained)+ monkeypatch.setattr(+ "sie_server.adapters.tensorrt_llm.generation.install_transformers_5_t5_tokenizer_compatibility",+ install_compatibility,+ )++ assert adapter._load_tokenizer() is tokenizer+ assert compatibility_calls == 1+ assert captured == {+ "model_name_or_path": "fixture/t5",+ "revision": _REVISION,+ "trust_remote_code": False,+ }+++def test_load_clears_lifecycle_state_when_port_reservation_fails(monkeypatch: pytest.MonkeyPatch) -> None:+ adapter = _adapter()+ adapter._server_url = None+ adapter._process = None++ def fail_reservation() -> int:+ raise RuntimeError("no ports")++ monkeypatch.setattr(_server, "reserve_port", fail_reservation)++ with pytest.raises(RuntimeError, match="no ports"):+ adapter.load("cuda:0")++ assert adapter._device is None+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._tokenizer is None+++def test_load_releases_reserved_port_when_tokenizer_load_fails(monkeypatch: pytest.MonkeyPatch) -> None:+ adapter = _adapter()+ adapter._server_url = None+ adapter._process = None+ released: list[int | None] = []++ monkeypatch.setattr(_server, "reserve_port", lambda: 30242)+ monkeypatch.setattr(_server, "release_port", released.append)++ def fail_tokenizer_load() -> Any:+ raise RuntimeError("tokenizer unavailable")++ monkeypatch.setattr(adapter, "_load_tokenizer", fail_tokenizer_load)++ with pytest.raises(RuntimeError, match="tokenizer unavailable"):+ adapter.load("cuda:0")++ assert released == [30242]+ assert adapter._device is None+ assert adapter._port is None+ assert adapter._server_url is None+ assert adapter._tokenizer is None+++def test_terminate_signals_process_group_after_launcher_exit(monkeypatch: pytest.MonkeyPatch) -> None:+ signals: list[tuple[int, signal.Signals]] = []+ waits: list[float] = []++ class ExitedLauncher:+ pid = 2345++ def poll(self) -> int:+ return 1++ def wait(self, *, timeout: float) -> int:+ waits.append(timeout)+ return 1++ monkeypatch.setattr(_server.os, "killpg", lambda pid, sig: signals.append((pid, sig)))+ monkeypatch.setattr(_server, "_wait_for_process_group_exit", lambda *_args, **_kwargs: True)++ _server.terminate(ExitedLauncher(), timeout_s=3.0) # type: ignore[arg-type]++ assert signals == [(2345, signal.SIGTERM)]+ assert len(waits) == 1+ assert 0 <= waits[0] <= 3.0+++def test_terminate_escalates_timed_out_process_group(monkeypatch: pytest.MonkeyPatch) -> None:+ signals: list[tuple[int, signal.Signals]] = []+ waits: list[float] = []++ class StuckLauncher:+ pid = 3456++ def poll(self) -> None:+ return None++ def wait(self, *, timeout: float) -> int:+ waits.append(timeout)+ return -signal.SIGKILL++ monkeypatch.setattr(_server.os, "killpg", lambda pid, sig: signals.append((pid, sig)))+ group_waits = iter((False, True))+ monkeypatch.setattr(+ _server,+ "_wait_for_process_group_exit",+ lambda *_args, **_kwargs: next(group_waits),+ )++ _server.terminate(StuckLauncher(), timeout_s=2.0) # type: ignore[arg-type]++ assert signals == [(3456, signal.SIGTERM), (3456, signal.SIGKILL)]+ assert len(waits) == 1+ assert 0 <= waits[0] <= _server.PROCESS_GROUP_KILL_TIMEOUT_S+++def test_terminate_raises_when_process_group_survives_sigkill(monkeypatch: pytest.MonkeyPatch) -> None:+ signals: list[tuple[int, signal.Signals]] = []++ class StuckLauncher:+ pid = 4567++ def poll(self) -> None:+ return None++ def wait(self, *, timeout: float) -> int:+ return -signal.SIGKILL++ monkeypatch.setattr(_server.os, "killpg", lambda pid, sig: signals.append((pid, sig)))+ monkeypatch.setattr(_server, "_wait_for_process_group_exit", lambda *_args, **_kwargs: False)++ with pytest.raises(RuntimeError, match="survived SIGKILL"):+ _server.terminate(cast("subprocess.Popen[bytes]", StuckLauncher()), timeout_s=0.0)++ assert signals == [(4567, signal.SIGTERM), (4567, signal.SIGKILL)]++[email protected](sys.platform != "linux", reason="Linux child-subreaper semantics")+def test_terminate_reaps_adopted_descendant_after_launcher_exits() -> None:+ server_script = """+import signal+import subprocess+import sys+import time++descendant = subprocess.Popen([+ sys.executable,+ "-c",+ "import signal,time; signal.signal(signal.SIGTERM, signal.SIG_IGN); print('READY', flush=True); time.sleep(60)",+], stdout=subprocess.PIPE, text=True)+assert descendant.stdout is not None+assert descendant.stdout.readline().strip() == "READY"+print(descendant.pid, flush=True)+time.sleep(60)+"""+ subreaper_script = f"""+import ctypes+import os+import subprocess+import sys++from sie_server.adapters.tensorrt_llm import _server++PR_SET_CHILD_SUBREAPER = 36+libc = ctypes.CDLL(None, use_errno=True)+if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:+ raise OSError(ctypes.get_errno(), "prctl(PR_SET_CHILD_SUBREAPER) failed")+process = subprocess.Popen(+ [sys.executable, "-c", {server_script!r}],+ stdout=subprocess.PIPE,+ text=True,+ start_new_session=True,+)+assert process.stdout is not None+descendant_pid = int(process.stdout.readline())+_server.terminate(process, timeout_s=0.2)+if _server._process_group_exists(process.pid):+ raise RuntimeError("GROUP_SURVIVED")+try:+ os.kill(descendant_pid, 0)+except ProcessLookupError:+ pass+else:+ raise RuntimeError("DESCENDANT_SURVIVED")+print("GROUP_GONE")+"""+ completed = subprocess.run( # noqa: S603+ [sys.executable, "-c", subreaper_script],+ capture_output=True,+ check=False,+ text=True,+ timeout=15,+ )++ assert completed.returncode == 0, completed.stderr+ assert completed.stdout == "GROUP_GONE\n"+++def test_generation_maps_completion_controls_text_finish_usage_and_logprobs() -> None:+ adapter = _adapter()+ captured: dict[str, Any] = {}++ async def handler(request: httpx.Request) -> httpx.Response:+ captured["path"] = request.url.path+ captured["body"] = json.loads(request.content)+ return httpx.Response(+ 200,+ content=_sse(+ {+ "choices": [+ {+ "index": 0,+ "text": " bonjour",+ "finish_reason": None,+ "logprobs": {+ "tokens": [" bonjour"],+ "token_logprobs": [-0.2],+ "top_logprobs": [{" bonjour": -0.2, " salut": -1.0}],+ "text_offset": [0],+ },+ }+ ]+ },+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}]},+ {+ "choices": [],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ },+ ),+ )++ adapter._http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ chunks = asyncio.run(+ _collect(+ adapter.generate(+ "<2fr> hello",+ max_new_tokens=9,+ temperature=0.2,+ top_p=0.9,+ top_k=12,+ frequency_penalty=0.1,+ presence_penalty=0.2,+ repetition_penalty=1.1,+ min_new_tokens=1,+ stop=["!"],+ seed=7,+ logit_bias={"12": -1.5},+ logprobs=True,+ top_logprobs=2,+ )+ )+ )++ assert captured["path"] == "/v1/completions"+ assert captured["body"] == {+ "model": "fixture/t5",+ "prompt": "<2fr> hello",+ "max_tokens": 9,+ "temperature": 0.2,+ "top_p": 0.9,+ "stream": True,+ "stream_options": {"include_usage": True},+ "n": 1,+ "stop": ["!"],+ "frequency_penalty": 0.1,+ "presence_penalty": 0.2,+ "top_k": 12,+ "repetition_penalty": 1.1,+ "min_tokens": 1,+ "seed": 7,+ "logit_bias": {"12": -1.5},+ "logprobs": 2,+ }+ assert len(chunks) == 2+ assert chunks[0].text_delta == " bonjour"+ assert chunks[0].is_first is True+ assert chunks[0].logprobs == (+ {+ "token": " bonjour",+ "logprob": -0.2,+ "bytes": list(b" bonjour"),+ "top_logprobs": [+ {"token": " bonjour", "logprob": -0.2, "bytes": list(b" bonjour")},+ {"token": " salut", "logprob": -1.0, "bytes": list(b" salut")},+ ],+ },+ )+ assert chunks[1].done is True+ assert chunks[1].finish_reason == "stop"+ assert (chunks[1].prompt_tokens, chunks[1].completion_tokens) == (3, 1)+ assert isinstance(adapter._tokenizer, _FixtureTokenizer)+ assert adapter._tokenizer.calls == [("<2fr> hello", True)]++ asyncio.run(adapter.aclose_client())+++def test_completion_logprobs_normalizes_null_top_alternative_per_token() -> None:+ assert _completion_logprobs(+ {+ "tokens": [" bonjour", " monde"],+ "token_logprobs": [-0.2, -0.3],+ "top_logprobs": [None, {" monde": -0.3}],+ }+ ) == (+ {+ "token": " bonjour",+ "logprob": -0.2,+ "bytes": list(b" bonjour"),+ "top_logprobs": [],+ },+ {+ "token": " monde",+ "logprob": -0.3,+ "bytes": list(b" monde"),+ "top_logprobs": [+ {"token": " monde", "logprob": -0.3, "bytes": list(b" monde")},+ ],+ },+ )+++ ("top_logprobs", "message"),+ [+ ([None], "misaligned top-logprob arrays"),+ ([None, []], "token-to-logprob objects"),+ ([None, 0], "token-to-logprob objects"),+ ([None, False], "token-to-logprob objects"),+ ([None, "bad"], "token-to-logprob objects"),+ ([None, {" monde": "invalid"}], "invalid entry"),+ ],+)+def test_completion_logprobs_rejects_malformed_non_null_and_misaligned_alternatives(+ top_logprobs: object,+ message: str,+) -> None:+ with pytest.raises(RuntimeError, match=message):+ _completion_logprobs(+ {+ "tokens": [" bonjour", " monde"],+ "token_logprobs": [-0.2, -0.3],+ "top_logprobs": top_logprobs,+ }+ )+++def test_stream_completion_normalizes_null_top_alternatives() -> None:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {+ "choices": [+ {+ "index": 0,+ "text": " bonjour monde",+ "finish_reason": None,+ "logprobs": {+ "tokens": [" bonjour", " monde"],+ "token_logprobs": [-0.2, -0.3],+ "top_logprobs": [None, {" monde": -0.3, " monde!": -1.0}],+ },+ }+ ]+ },+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}]},+ {+ "choices": [],+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},+ },+ ),+ )+ )+ )++ chunks = asyncio.run(_collect(adapter.generate("<2fr> hello", max_new_tokens=4, logprobs=True)))++ assert chunks[0].logprobs == (+ {+ "token": " bonjour",+ "logprob": -0.2,+ "bytes": list(b" bonjour"),+ "top_logprobs": [],+ },+ {+ "token": " monde",+ "logprob": -0.3,+ "bytes": list(b" monde"),+ "top_logprobs": [+ {"token": " monde", "logprob": -0.3, "bytes": list(b" monde")},+ {"token": " monde!", "logprob": -1.0, "bytes": list(b" monde!")},+ ],+ },+ )+ assert chunks[1].done is True+ asyncio.run(adapter.aclose_client())+++def test_unload_closes_http_client_before_child_teardown(monkeypatch: pytest.MonkeyPatch) -> None:+ class CloseTrackingClient:+ def __init__(self) -> None:+ self.closed = False++ async def aclose(self) -> None:+ self.closed = True++ adapter = _adapter()+ client = CloseTrackingClient()+ adapter._http_client = cast("httpx.AsyncClient", client)+ close_state_at_teardown: list[bool] = []+ monkeypatch.setattr(adapter, "_teardown_child", lambda: close_state_at_teardown.append(client.closed))++ adapter.unload()++ assert client.closed+ assert close_state_at_teardown == [True]+++ ("events", "message"),+ [+ (+ ({"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},),+ "ended without finish reason and usage",+ ),+ (+ ({"choices": [{"index": 0, "text": "x", "finish_reason": "stop"}]},),+ "ended without finish reason and usage",+ ),+ (({"error": {"message": "engine rejected"}, "choices": []},), "completion error: engine rejected"),+ (({"choices": [{"index": 1, "text": "x", "finish_reason": None}]},), "unsupported multiple choices"),+ ],+)+def test_stream_fails_closed_on_incomplete_or_invalid_events(events: tuple[object, ...], message: str) -> None:+ adapter = _adapter()++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(200, content=_sse(*events))++ adapter._http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ with pytest.raises(RuntimeError, match=message):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4)))+ asyncio.run(adapter.aclose_client())+++def test_stream_fails_when_eof_arrives_without_done() -> None:+ adapter = _adapter()++ def handler(_request: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ content=b'data: {"choices":[{"index":0,"text":"x","finish_reason":"stop"}]}\n\n'+ b'data: {"choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}\n\n',+ )++ adapter._http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ with pytest.raises(RuntimeError, match=r"before \[DONE\]"):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4)))+ asyncio.run(adapter.aclose_client())+++ "token_ids",+ [None, [], [True], [-1], ["1"], [[1]]],+)+def test_generation_fails_before_dispatch_when_encoder_token_ids_are_invalid(token_ids: object) -> None:+ adapter = _adapter()+ adapter._tokenizer = type("MalformedTokenizer", (), {"encode": lambda *_args, **_kwargs: token_ids})()++ with pytest.raises(RuntimeError, match="invalid token ids"):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4)))++ assert adapter._http_client is None+++def test_generation_fails_before_dispatch_when_encoder_tokenization_raises() -> None:+ adapter = _adapter()++ def fail_tokenization(*_args: Any, **_kwargs: Any) -> list[int]:+ raise ValueError("bad tokenizer state")++ adapter._tokenizer = type("FailingTokenizer", (), {"encode": fail_tokenization})()++ with pytest.raises(RuntimeError, match="tokenization failed"):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4)))++ assert adapter._http_client is None+++def test_generation_allows_encoder_limit_after_special_token_accounting() -> None:+ adapter = _adapter()+ prompt = " ".join(["token"] * 127)++ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 128, "completion_tokens": 1}},+ ),+ )+ )+ )+ chunks = asyncio.run(_collect(adapter.generate(prompt, max_new_tokens=4)))++ assert chunks[-1].prompt_tokens == 128+ asyncio.run(adapter.aclose_client())+++def test_generation_rejects_encoder_overflow_before_dispatch_after_special_token_accounting() -> None:+ adapter = _adapter()+ prompt = " ".join(["token"] * 128)++ with pytest.raises(+ GenerationInputTooLongError,+ match=r"prompt token count \(129\) exceeds max_input_len \(128\)",+ ) as exc_info:+ asyncio.run(_collect(adapter.generate(prompt, max_new_tokens=4)))++ assert exc_info.value.code == "INPUT_TOO_LONG"+ assert exc_info.value.param == "prompt"+ assert adapter._http_client is None+++ ("events", "message"),+ [+ (+ (+ {+ "choices": [+ {+ "index": 0,+ "text": "x",+ "finish_reason": None,+ "logprobs": {"tokens": ["x"], "token_logprobs": []},+ }+ ]+ },+ ),+ "misaligned token arrays",+ ),+ (+ (+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}]},+ {"choices": [{"index": 0, "text": "late", "finish_reason": None}]},+ ),+ "text after its terminal choice",+ ),+ (+ (+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": True, "completion_tokens": 1}},+ ),+ "usage is invalid",+ ),+ (+ (+ {"choices": [{"index": 0, "text": "", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ ),+ "duplicate usage",+ ),+ ],+)+def test_stream_rejects_malformed_terminal_logprob_and_usage_shapes(events: tuple[object, ...], message: str) -> None:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _request: httpx.Response(200, content=_sse(*events)))+ )++ with pytest.raises(RuntimeError, match=message):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4, logprobs=True)))+ asyncio.run(adapter.aclose_client())+++ ("status_code", "content", "error"),+ [+ (200, b"event: completion\n\n", RuntimeError),+ (503, b"unavailable", httpx.HTTPStatusError),+ ],+)+def test_stream_rejects_non_sse_and_http_errors(status_code: int, content: bytes, error: type[Exception]) -> None:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _request: httpx.Response(status_code, content=content))+ )++ with pytest.raises(error):+ asyncio.run(_collect(adapter.generate("prompt", max_new_tokens=4)))+ asyncio.run(adapter.aclose_client())+++ ("kwargs", "error_type", "param", "code"),+ [+ ({"grammar": object()}, GenerationUnsupportedFieldError, "grammar", "unsupported_field"),+ ({"images": [{"data": b"image"}]}, GenerationUnsupportedFieldError, "images", "unsupported_field"),+ ({"lora_path": "adapter"}, GenerationUnsupportedFieldError, "lora_path", "unsupported_field"),+ ({"n": 2}, GenerationUnsupportedFieldError, "n", "unsupported_field"),+ ({"best_of": 2}, GenerationUnsupportedFieldError, "best_of", "unsupported_field"),+ ({"top_logprobs": 2}, GenerationInvalidRequestError, "top_logprobs", "invalid_request"),+ ({"min_new_tokens": 5}, GenerationInvalidRequestError, "min_new_tokens", "invalid_request"),+ ],+)[email protected]("through_preflight", [True, False])+def test_request_refusals_are_typed_before_dispatch(+ kwargs: dict[str, Any],+ error_type: type[Exception],+ param: str,+ code: str,+ *,+ through_preflight: bool,+) -> None:+ adapter = _adapter()+ parameters = {"prompt": "prompt", "max_new_tokens": 4, **kwargs}++ with pytest.raises(error_type) as exc_info:+ if through_preflight:+ adapter.preflight_generate(parameters, stream=False)+ else:+ asyncio.run(_collect(adapter.generate(**parameters)))++ error = cast("Any", exc_info.value)+ assert error.code == code+ assert error.param == param+ if param == "lora_path":+ assert "lora_path" not in str(error)+ assert "lora_adapter" in str(error)+ assert adapter._http_client is None+++def test_preflight_prompt_count_is_reused_by_matching_dispatch() -> None:+ async def scenario() -> list[tuple[str, bool]]:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ ),+ )+ )+ )+ parameters = {"prompt": "translate this", "max_new_tokens": 4}+ preflight_result = adapter.preflight_generate(parameters, stream=False)+ chunks = adapter.generate_with_preflight(parameters, preflight_result)+ await asyncio.create_task(_collect(chunks))+ assert adapter._active_generations == 0+ await adapter.aclose_client()+ return adapter._tokenizer.calls++ assert asyncio.run(scenario()) == [("translate this", True)]+++def test_preflight_result_is_consumed_once_even_for_an_identical_second_dispatch() -> None:+ async def scenario() -> list[tuple[str, bool]]:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ ),+ )+ )+ )+ parameters = {"prompt": "translate this", "max_new_tokens": 4}+ preflight_result = adapter.preflight_generate(parameters, stream=False)++ await _collect(adapter.generate_with_preflight(parameters, preflight_result))+ await _collect(adapter.generate_with_preflight(parameters, preflight_result))++ assert adapter._active_generations == 0+ await adapter.aclose_client()+ return adapter._tokenizer.calls++ assert asyncio.run(scenario()) == [+ ("translate this", True),+ ("translate this", True),+ ]+++def test_abandoned_unstarted_preflight_dispatch_cannot_reuse_prompt_count() -> None:+ async def scenario() -> list[tuple[str, bool]]:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ ),+ )+ )+ )+ parameters = {"prompt": "same request text", "max_new_tokens": 4}+ preflight_result = adapter.preflight_generate(parameters, stream=False)++ abandoned = adapter.generate_with_preflight(parameters, preflight_result)+ await abandoned.aclose()+ await _collect(adapter.generate_with_preflight(parameters, preflight_result))++ assert adapter._active_generations == 0+ await adapter.aclose_client()+ return adapter._tokenizer.calls++ assert asyncio.run(scenario()) == [+ ("same request text", True),+ ("same request text", True),+ ]+++def test_preflight_result_cannot_cross_adapter_ownership() -> None:+ async def scenario() -> tuple[list[tuple[str, bool]], list[tuple[str, bool]]]:+ first = _adapter()+ second = _adapter()+ second._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 2, "completion_tokens": 1}},+ ),+ )+ )+ )+ parameters = {"prompt": "same prompt", "max_new_tokens": 4}+ preflight_result = first.preflight_generate(parameters, stream=False)++ await _collect(second.generate_with_preflight(parameters, preflight_result))++ await second.aclose_client()+ return first._tokenizer.calls, second._tokenizer.calls++ first_calls, second_calls = asyncio.run(scenario())+ assert first_calls == [("same prompt", True)]+ assert second_calls == [("same prompt", True)]+++def test_preflight_cache_cannot_bypass_changed_dispatch_controls() -> None:+ async def scenario() -> None:+ adapter = _adapter()+ parameters = {"prompt": "translate this", "max_new_tokens": 4}+ preflight_result = adapter.preflight_generate(parameters, stream=False)+ changed_parameters = {**parameters, "grammar": object()}+ with pytest.raises(GenerationUnsupportedFieldError) as exc_info:+ await _collect(adapter.generate_with_preflight(changed_parameters, preflight_result))+ assert exc_info.value.param == "grammar"+ assert adapter._http_client is None++ asyncio.run(scenario())+++def test_preflight_results_are_request_scoped_across_concurrent_child_tasks() -> None:+ async def scenario() -> list[tuple[str, bool]]:+ adapter = _adapter()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda _request: httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "ok", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 2, "completion_tokens": 1}},+ ),+ )+ )+ )++ async def run(parameters: dict[str, Any]) -> None:+ preflight_result = adapter.preflight_generate(parameters, stream=True)+ chunks = adapter.generate_with_preflight(parameters, preflight_result)+ await asyncio.create_task(_collect(chunks))++ await asyncio.gather(+ run({"prompt": "same prompt", "max_new_tokens": 4}),+ run({"prompt": "same prompt", "max_new_tokens": 8}),+ )+ assert adapter._active_generations == 0+ await adapter.aclose_client()+ return adapter._tokenizer.calls++ assert asyncio.run(scenario()) == [("same prompt", True), ("same prompt", True)]+++class _CancellableStream(httpx.AsyncByteStream):+ def __init__(self) -> None:+ self.closed = False+ self.block = asyncio.Event()++ async def __aiter__(self) -> AsyncIterator[bytes]:+ yield b'data: {"choices":[{"index":0,"text":"x","finish_reason":null}]}\n\n'+ await self.block.wait()++ async def aclose(self) -> None:+ self.closed = True+ self.block.set()+++def test_closing_generation_closes_incomplete_upstream_response() -> None:+ async def scenario() -> bool:+ adapter = _adapter()+ stream = _CancellableStream()+ adapter._http_client = httpx.AsyncClient(+ transport=httpx.MockTransport(lambda _request: httpx.Response(200, stream=stream))+ )+ iterator = adapter.generate("prompt", max_new_tokens=4)+ first = await anext(iterator)+ assert first.text_delta == "x"+ await iterator.aclose()+ await adapter.aclose_client()+ return stream.closed++ assert asyncio.run(scenario()) is True+++def test_generation_drain_blocks_new_admission_and_waits_for_active_stream() -> None:+ async def scenario() -> tuple[bool, bool, int]:+ adapter = _adapter()+ stream = _CancellableStream()+ client = httpx.AsyncClient(transport=httpx.MockTransport(lambda _request: httpx.Response(200, stream=stream)))+ adapter._http_client = client+ parameters = {"prompt": "prompt", "max_new_tokens": 4}+ preflight_result = adapter.preflight_generate(parameters, stream=True)+ iterator = adapter.generate_with_preflight(parameters, preflight_result)+ first = await anext(iterator)+ assert first.text_delta == "x"++ drain = asyncio.create_task(adapter.drain_generation())+ await asyncio.sleep(0)+ assert not drain.done()+ with pytest.raises(GenerationDrainingError):+ adapter.preflight_generate(parameters, stream=True)++ await iterator.aclose()+ await drain+ return stream.closed, client.is_closed, adapter._active_generations++ assert asyncio.run(scenario()) == (True, True, 0)+++class _BlockingCloseFailureCompletion:+ def __init__(self) -> None:+ self.started = asyncio.Event()+ self.close_calls = 0++ def __aiter__(self) -> _BlockingCloseFailureCompletion:+ return self++ async def __anext__(self) -> Any:+ self.started.set()+ await asyncio.Event().wait()++ async def aclose(self) -> None:+ self.close_calls += 1+ raise RuntimeError("secondary close failure")+++def test_cancellation_is_not_masked_by_completion_close_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ async def scenario() -> tuple[int, int]:+ adapter = _adapter()+ completion = _BlockingCloseFailureCompletion()+ monkeypatch.setattr(adapter, "_stream_completion", lambda *_args, **_kwargs: completion)+ consume = asyncio.create_task(anext(adapter.generate("prompt", max_new_tokens=4)))+ await completion.started.wait()+ consume.cancel()+ with pytest.raises(asyncio.CancelledError):+ await consume+ return completion.close_calls, adapter._active_generations++ assert asyncio.run(scenario()) == (1, 0)+++class _TerminalCloseFailureCompletion:+ def __init__(self) -> None:+ self.yielded = False+ self.close_calls = 0++ def __aiter__(self) -> _TerminalCloseFailureCompletion:+ return self++ async def __anext__(self) -> Any:+ if self.yielded:+ raise StopAsyncIteration+ self.yielded = True+ return type("Terminal", (), {"done": True})()++ async def aclose(self) -> None:+ self.close_calls += 1+ raise RuntimeError("secondary close failure")+++def test_terminal_outcome_is_not_replaced_by_completion_close_failure(monkeypatch: pytest.MonkeyPatch) -> None:+ async def scenario() -> tuple[list[Any], int, int]:+ adapter = _adapter()+ completion = _TerminalCloseFailureCompletion()+ monkeypatch.setattr(adapter, "_stream_completion", lambda *_args, **_kwargs: completion)+ chunks = await _collect(adapter.generate("prompt", max_new_tokens=4))+ return chunks, completion.close_calls, adapter._active_generations++ chunks, close_calls, active = asyncio.run(scenario())+ assert len(chunks) == 1+ assert chunks[0].done is True+ assert (close_calls, active) == (1, 0)+++class _TerminalBlockingCloseCompletion:+ def __init__(self) -> None:+ self.yielded = False+ self.close_started = asyncio.Event()++ def __aiter__(self) -> _TerminalBlockingCloseCompletion:+ return self++ async def __anext__(self) -> Any:+ if self.yielded:+ raise StopAsyncIteration+ self.yielded = True+ return type("Terminal", (), {"done": True})()++ async def aclose(self) -> None:+ self.close_started.set()+ await asyncio.Event().wait()+++def test_cancellation_during_completion_cleanup_propagates(monkeypatch: pytest.MonkeyPatch) -> None:+ async def scenario() -> int:+ adapter = _adapter()+ completion = _TerminalBlockingCloseCompletion()+ monkeypatch.setattr(adapter, "_stream_completion", lambda *_args, **_kwargs: completion)+ consume = asyncio.create_task(_collect(adapter.generate("prompt", max_new_tokens=4)))+ await completion.close_started.wait()+ consume.cancel()+ with pytest.raises(asyncio.CancelledError):+ await consume+ return adapter._active_generations++ assert asyncio.run(scenario()) == 0+++def test_independent_requests_share_client_and_reach_transport_concurrently() -> None:+ async def scenario() -> int:+ adapter = _adapter()+ active = 0+ peak = 0++ async def handler(_request: httpx.Request) -> httpx.Response:+ nonlocal active, peak+ active += 1+ peak = max(peak, active)+ await asyncio.sleep(0.01)+ active -= 1+ return httpx.Response(+ 200,+ content=_sse(+ {"choices": [{"index": 0, "text": "x", "finish_reason": "stop"}]},+ {"choices": [], "usage": {"prompt_tokens": 1, "completion_tokens": 1}},+ ),+ )++ adapter._http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))+ await asyncio.gather(+ _collect(adapter.generate("one", max_new_tokens=2)),+ _collect(adapter.generate("two", max_new_tokens=2)),+ )+ await adapter.aclose_client()+ return peak++ assert asyncio.run(scenario()) == 2diff --git a/packages/sie_server/tests/api/test_error_code_hygiene.py b/packages/sie_server/tests/api/test_error_code_hygiene.pyindex 7c1c1861b..638dc6b60 100644--- a/packages/sie_server/tests/api/test_error_code_hygiene.py+++ b/packages/sie_server/tests/api/test_error_code_hygiene.py@@ -28,6 +28,7 @@ from typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport msgpack_numpy as m+import pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClientfrom sie_server.adapters.base import ModelCapabilities, ModelDims@@ -255,3 +256,26 @@ class TestInputTooLongMapping:assert response.status_code == 400, response.textassert _detail(response)["code"] == "INVALID_INPUT"+++class TestUnexpectedInferenceErrorSanitization:+ @pytest.mark.parametrize(+ ("post", "build_client", "message"),+ [+ (_post_encode, _build_encode_client, "internal error during encoding"),+ (_post_score, _build_score_client, "internal error during scoring"),+ ],+ ids=["encode", "score"],+ )+ def test_internal_exception_text_is_not_returned(+ self,+ post: Any,+ build_client: Any,+ message: str,+ ) -> None:+ response = post(build_client(RuntimeError("sensitive worker detail")))++ assert response.status_code == 500+ detail = _detail(response)+ assert detail == {"code": "INFERENCE_ERROR", "message": message}+ assert "sensitive worker detail" not in response.textdiff --git a/packages/sie_server/tests/api/test_extract_oom.py b/packages/sie_server/tests/api/test_extract_oom.pyindex 9540fbdd3..a2d8b24b7 100644--- a/packages/sie_server/tests/api/test_extract_oom.py+++ b/packages/sie_server/tests/api/test_extract_oom.py@@ -117,9 +117,9 @@ def test_extract_oom_maps_to_503_resource_exhausted(failure: BaseException) -> Nassert "Extraction" in detail["message"] or "extract" in detail["message"].lower()-def test_extract_non_oom_keeps_500_inference_error() -> None:- """Regression guard: a non-OOM exception still maps to 500 INFERENCE_ERROR."""- client = _build_client(RuntimeError("model produced bad shape"))+def test_extract_non_oom_keeps_500_inference_error_without_leaking_details() -> None:+ """A non-OOM exception maps to a sanitized 500 INFERENCE_ERROR."""+ client = _build_client(RuntimeError("sensitive extraction detail"))response = client.post("/v1/extract/test-extractor",@@ -132,6 +132,8 @@ def test_extract_non_oom_keeps_500_inference_error() -> None:body = response.json()detail = body.get("detail", body)assert detail["code"] == "INFERENCE_ERROR"+ assert detail["message"] == "internal error during extraction"+ assert "sensitive extraction detail" not in response.textdef test_extract_oom_retry_after_honours_engine_config() -> None:diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.pyindex 67f9934b6..b74be5857 100644--- a/packages/sie_server/tests/api/test_generate.py+++ b/packages/sie_server/tests/api/test_generate.py@@ -10,18 +10,27 @@ from __future__ import annotationsimport asyncioimport json-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom typing import Literalfrom unittest.mock import AsyncMock, MagicMockimport pytestfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.testclient import TestClient-from sie_server.adapters._generation_base import GenerationAdapter, GenerationChunk+from sie_server.adapters._generation_base import (+ GenerationAdapter,+ GenerationCapacityError,+ GenerationChunk,+ GenerationDrainingError,+ GenerationError,+ GenerationInputTooLongError,+ GenerationUnsupportedFieldError,+)from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.base import ModelCapabilities, ModelDimsfrom sie_server.api import generate as generate_apifrom sie_server.api.generate import router as generate_router+from sie_server.config.engine import EngineConfigfrom sie_server.config.model import (AdapterOptions,GenerateCapabilities,@@ -39,6 +48,51 @@ _GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"_GEMMA_CLOSE = "<" + "channel|" + ">"+class _UntrustedUnsupportedFieldError(GenerationUnsupportedFieldError):+ code = "SENSITIVE_UNSUPPORTED_CODE"+++class _UntrustedCapacityError(GenerationCapacityError):+ code = "SENSITIVE_CAPACITY_CODE"+++class _FutureUnsupportedFieldError(GenerationUnsupportedFieldError):+ pass+++ ("error", "expected_param"),+ [+ (GenerationUnsupportedFieldError("n", "n refusal"), "n"),+ (GenerationUnsupportedFieldError("best_of", "best_of refusal"), "best_of"),+ (+ GenerationUnsupportedFieldError(+ "lora_path",+ "'lora_adapter' is not supported by this generation backend",+ ),+ "lora_adapter",+ ),+ ],+)+def test_generation_http_exception_preserves_public_refusal_param(+ error: GenerationUnsupportedFieldError,+ expected_param: str,+) -> None:+ exception = generate_api._generation_http_exception(error)++ assert exception.status_code == 400+ assert exception.detail["param"] == expected_param+ assert exception.detail["param"] != "lora_path"+ assert "lora_path" not in str(exception.detail)+++def test_generation_http_exception_redacts_future_refusal_subclass_param() -> None:+ exception = generate_api._generation_http_exception(_FutureUnsupportedFieldError("n", "future refusal"))++ assert exception.status_code == 400+ assert exception.detail == {"code": "unsupported_field", "message": "future refusal"}++class _FakeGenAdapter(GenerationAdapter):"""Minimal in-memory GenerationAdapter for route tests."""@@ -206,10 +260,37 @@ class _ThinkingGenAdapter(_FakeGenAdapter):)+class _PreflightAdapter(_FakeGenAdapter):+ def __init__(self, error: Exception | None = None, *, raise_during_generate: bool = False) -> None:+ super().__init__()+ self.error = error+ self.raise_during_generate = raise_during_generate+ self.preflight_parameters: dict[str, object] | None = None+ self.preflight_stream: bool | None = None+ self.dispatched_parameters: dict[str, object] | None = None+ self.events: list[str] = []++ def preflight_generate(self, parameters: Mapping[str, object], *, stream: bool) -> None:+ self.events.append("preflight")+ self.preflight_parameters = dict(parameters)+ self.preflight_stream = stream+ if self.error is not None and not self.raise_during_generate:+ raise self.error++ async def generate(self, prompt: str, **kwargs: object) -> AsyncIterator[GenerationChunk]:+ self.events.append("generate")+ self.dispatched_parameters = {"prompt": prompt, **kwargs}+ if self.error is not None and self.raise_during_generate:+ raise self.error+ async for chunk in super().generate(prompt, **kwargs): # type: ignore[arg-type]+ yield chunk++def _make_config(*,model_id: str = "Qwen/Qwen3-4B-Instruct",grammar: list[Literal["json_schema", "regex", "ebnf"]] | None = None,+ streaming: bool = True,) -> ModelConfig:return ModelConfig(sie_id=model_id,@@ -218,7 +299,7 @@ def _make_config(generate=GenerateTask(context_length=32768,max_output_tokens=4096,- capabilities=GenerateCapabilities(grammar=grammar or []),+ capabilities=GenerateCapabilities(grammar=grammar or [], streaming=streaming),),),profiles={@@ -1280,6 +1361,58 @@ class TestGenerateEndpoint:assert detail["code"] == "tool_call_parse_error"assert detail["message"] == "model emitted a malformed tool call"+ @pytest.mark.parametrize(+ ("code", "message", "expected_code", "expected_message"),+ [+ (+ "inference_error",+ "SENSITIVE_NATIVE_BUFFERED_RUNTIME",+ "inference_error",+ "internal error during generation",+ ),+ (+ "grammar_compile_failed",+ "SENSITIVE_NATIVE_BUFFERED_GRAMMAR",+ "grammar_compile_failed",+ "internal error compiling grammar",+ ),+ (+ "MODEL_OUTPUT_PARSE_ERROR",+ "invalid model JSON",+ "MODEL_OUTPUT_PARSE_ERROR",+ "invalid model JSON",+ ),+ (+ "SENSITIVE_NATIVE_BUFFERED_ERROR_CODE",+ "SENSITIVE_NATIVE_BUFFERED_ERROR_CODE",+ "inference_error",+ "generation terminated with an upstream error",+ ),+ ],+ )+ def test_terminal_error_message_is_classified_at_buffered_boundary(+ self,+ client: TestClient,+ fake_adapter: _FakeGenAdapter,+ code: str,+ message: str,+ expected_code: str,+ expected_message: str,+ ) -> None:+ fake_adapter.finish_reason = "error"+ fake_adapter.error_code = code+ fake_adapter.error_message = message++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 500, response.text+ assert response.json()["detail"] == {"code": expected_code, "message": expected_message}+ if message.startswith("SENSITIVE_"):+ assert message not in response.text+def test_terminal_cancelled_finish_reason_returns_503(self, client: TestClient, fake_adapter: _FakeGenAdapter) -> None:@@ -1303,3 +1436,223 @@ class TestGenerateEndpoint:json={"prompt": "Hi", "max_new_tokens": 8},)assert response.status_code == 200, response.text++ @pytest.mark.parametrize("stream", [False, True])+ def test_preflight_receives_exact_dispatched_parameters(+ self,+ client: TestClient,+ registry: MagicMock,+ stream: bool,+ ) -> None:+ adapter = _PreflightAdapter()+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8, "stream": stream},+ )++ assert response.status_code == 200, response.text+ assert adapter.events[:2] == ["preflight", "generate"]+ assert adapter.preflight_stream is stream+ assert adapter.preflight_parameters == adapter.dispatched_parameters+ if stream:+ assert adapter.preflight_parameters is not None+ assert adapter.preflight_parameters["logprobs"] is False+ assert adapter.preflight_parameters["top_logprobs"] is None+ else:+ assert adapter.preflight_parameters is not None+ assert "logprobs" not in adapter.preflight_parameters+ assert "top_logprobs" not in adapter.preflight_parameters++ def test_streaming_capability_rejects_before_adapter_lookup(+ self,+ client: TestClient,+ registry: MagicMock,+ ) -> None:+ registry.get_config.return_value = _make_config(streaming=False)++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8, "stream": True},+ )++ assert response.status_code == 400+ assert response.json()["detail"] == {+ "code": "unsupported_field",+ "message": "Model 'Qwen__Qwen3-4B-Instruct' does not support streaming generation",+ "param": "stream",+ }+ registry.get.assert_not_called()++ def test_preflight_unsupported_field_is_exact_400(+ self,+ client: TestClient,+ registry: MagicMock,+ ) -> None:+ adapter = _PreflightAdapter(GenerationUnsupportedFieldError("top_k"))+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "unsupported_field"+ assert response.json()["detail"]["param"] == "top_k"+ assert adapter.events == ["preflight"]++ def test_preflight_input_too_long_is_exact_400(+ self,+ client: TestClient,+ registry: MagicMock,+ ) -> None:+ adapter = _PreflightAdapter(+ GenerationInputTooLongError(+ "prompt token count (129) exceeds max_input_len (128)",+ )+ )+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 400+ assert response.json()["detail"] == {+ "code": "INPUT_TOO_LONG",+ "message": "prompt token count (129) exceeds max_input_len (128)",+ "param": "prompt",+ }+ assert adapter.events == ["preflight"]++ @pytest.mark.parametrize(+ ("error", "status_code"),+ [+ (_UntrustedUnsupportedFieldError("top_k", "private unsupported detail"), 400),+ (_UntrustedCapacityError("private capacity detail"), 503),+ ],+ )+ def test_typed_generation_errors_sanitize_untrusted_codes(+ self,+ client: TestClient,+ registry: MagicMock,+ error: GenerationError,+ status_code: int,+ ) -> None:+ adapter = _PreflightAdapter(error)+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == status_code+ assert response.json()["detail"]["code"] == "inference_error"+ assert "SENSITIVE_" not in response.text++ @pytest.mark.parametrize(+ ("raise_during_generate", "message", "events"),+ [+ (False, "internal error during generation preflight", ["preflight"]),+ (True, "internal error during generation", ["preflight", "generate"]),+ ],+ )+ def test_unexpected_generation_errors_do_not_leak_exception_text(+ self,+ client: TestClient,+ registry: MagicMock,+ raise_during_generate: bool,+ message: str,+ events: list[str],+ ) -> None:+ adapter = _PreflightAdapter(+ RuntimeError("sensitive internal generation detail"),+ raise_during_generate=raise_during_generate,+ )+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 500+ assert response.json()["detail"] == {"code": "inference_error", "message": message}+ assert "sensitive internal generation detail" not in response.text+ assert adapter.events == events++ @pytest.mark.parametrize("raise_during_generate", [False, True])+ def test_generic_typed_generation_error_does_not_leak_exception_text(+ self,+ client: TestClient,+ registry: MagicMock,+ raise_during_generate: bool,+ ) -> None:+ sentinel = "SENSITIVE_TYPED_NATIVE_BUFFERED"+ adapter = _PreflightAdapter(+ GenerationError(sentinel),+ raise_during_generate=raise_during_generate,+ )+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 500+ assert response.json()["detail"] == {+ "code": "inference_error",+ "message": "internal error during generation",+ }+ assert sentinel not in response.text++ @pytest.mark.parametrize(+ ("error", "code", "retry_after"),+ [+ (GenerationCapacityError("scheduler full"), "RESOURCE_EXHAUSTED", "5"),+ (GenerationDrainingError("scheduler draining"), "MODEL_LOADING", "5"),+ ],+ )+ def test_typed_capacity_after_preflight_remains_retryable(+ self,+ client: TestClient,+ registry: MagicMock,+ error: GenerationError,+ code: str,+ retry_after: str,+ ) -> None:+ adapter = _PreflightAdapter(error, raise_during_generate=True)+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 503+ assert response.json()["detail"]["code"] == code+ assert response.headers["retry-after"] == retry_after+ assert adapter.events == ["preflight", "generate"]++ def test_generation_capacity_uses_configured_resource_exhausted_retry_hint(+ self,+ client: TestClient,+ registry: MagicMock,+ ) -> None:+ registry.engine_config = EngineConfig.model_validate({"oom_recovery": {"retry_after_s": 12}})+ adapter = _PreflightAdapter(GenerationCapacityError("scheduler full"))+ registry.get.return_value = adapter++ response = client.post(+ "/v1/generate/Qwen__Qwen3-4B-Instruct",+ json={"prompt": "Hi", "max_new_tokens": 8},+ )++ assert response.status_code == 503+ assert response.json()["detail"]["code"] == "RESOURCE_EXHAUSTED"+ assert response.headers["retry-after"] == "12"diff --git a/packages/sie_server/tests/api/test_generate_stream.py b/packages/sie_server/tests/api/test_generate_stream.pyindex e0c355027..de35f5b02 100644--- a/packages/sie_server/tests/api/test_generate_stream.py+++ b/packages/sie_server/tests/api/test_generate_stream.py@@ -9,11 +9,18 @@ only the Mac nightly.from __future__ import annotations+import asyncioimport jsonfrom collections.abc import AsyncIteratorfrom typing import Any-from sie_server.adapters._generation_base import GenerationChunk+import pytest+from sie_server.adapters._generation_base import (+ GenerationCapacityError,+ GenerationChunk,+ GenerationError,+ GenerationPreflightResult,+)from sie_server.api.generate import _stream_generate_events@@ -24,13 +31,102 @@ class _FakeAdapter:self._chunks = chunksself._raise_after = raise_afterself.last_kwargs: dict[str, Any] | None = None+ self.closed = 0async def generate(self, **kwargs: Any) -> AsyncIterator[GenerationChunk]:self.last_kwargs = kwargs- for i, c in enumerate(self._chunks):- if self._raise_after is not None and i == self._raise_after:- raise RuntimeError("boom")- yield c+ try:+ for i, c in enumerate(self._chunks):+ if self._raise_after is not None and i == self._raise_after:+ raise RuntimeError("boom")+ yield c+ finally:+ self.closed += 1+++class _BlockingAdapter:+ """Yield once, then block until the consuming task is cancelled."""++ def __init__(self) -> None:+ self.blocked = asyncio.Event()+ self.closed = 0++ async def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ try:+ yield GenerationChunk(text_delta="visible", done=False)+ self.blocked.set()+ await asyncio.Event().wait()+ finally:+ self.closed += 1+++class _FailingCloseIterator:+ """Adversarial iterator whose explicit cleanup always fails."""++ def __init__(+ self,+ chunks: list[GenerationChunk],+ *,+ block_after_chunks: bool = False,+ next_error: Exception | None = None,+ ) -> None:+ self._chunks = chunks+ self._block_after_chunks = block_after_chunks+ self._next_error = next_error+ self._index = 0+ self.blocked = asyncio.Event()+ self.close_calls = 0++ def __aiter__(self) -> _FailingCloseIterator:+ return self++ async def __anext__(self) -> GenerationChunk:+ if self._index < len(self._chunks):+ chunk = self._chunks[self._index]+ self._index += 1+ return chunk+ if self._next_error is not None:+ error = self._next_error+ self._next_error = None+ raise error+ if self._block_after_chunks:+ self.blocked.set()+ await asyncio.Event().wait()+ raise StopAsyncIteration++ async def aclose(self) -> None:+ self.close_calls += 1+ raise RuntimeError("cleanup failed")+++class _IteratorAdapter:+ def __init__(self, iterator: AsyncIterator[GenerationChunk]) -> None:+ self.iterator = iterator++ def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ return self.iterator+++class _PreflightDispatchAdapter:+ """Observe which lower-level generation entrypoint owns a request."""++ def __init__(self) -> None:+ self.generate_calls = 0+ self.generate_with_preflight_calls = 0+ self.received_preflight: GenerationPreflightResult | None = None++ async def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ self.generate_calls += 1+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop")++ async def generate_with_preflight(+ self,+ _parameters: dict[str, Any],+ preflight: GenerationPreflightResult,+ ) -> AsyncIterator[GenerationChunk]:+ self.generate_with_preflight_calls += 1+ self.received_preflight = preflight+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop")def _parse_sse(raw: list[str]) -> tuple[list[dict[str, Any]], bool]:@@ -50,27 +146,59 @@ def _parse_sse(raw: list[str]) -> tuple[list[dict[str, Any]], bool]:return events, saw_done-async def _drain(adapter: Any) -> list[str]:- return [- s- async for s in _stream_generate_events(- adapter,- prompt="hi",- max_new_tokens=8,- temperature=0.0,- top_p=1.0,- stop=None,- frequency_penalty=0.25,- presence_penalty=-0.5,- top_k=12,- min_new_tokens=2,- grammar=None,- seed=None,- logit_bias=None,- logprobs=True,- top_logprobs=3,- )- ]+def _events(+ adapter: Any,+ *,+ suppress_thinking: bool = False,+ preflight_result: GenerationPreflightResult | None = None,+) -> AsyncIterator[str]:+ return _stream_generate_events(+ adapter,+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=0.25,+ presence_penalty=-0.5,+ top_k=12,+ min_new_tokens=2,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=True,+ top_logprobs=3,+ suppress_thinking=suppress_thinking,+ preflight_result=preflight_result,+ )+++async def _drain(adapter: Any, *, suppress_thinking: bool = False) -> list[str]:+ return [event async for event in _events(adapter, suppress_thinking=suppress_thinking)]+++async def test_stream_without_preflight_uses_duck_typed_generate() -> None:+ adapter = _PreflightDispatchAdapter()++ events, saw_done = _parse_sse([event async for event in _events(adapter)])++ assert saw_done is True+ assert events[-1]["finish_reason"] == "stop"+ assert adapter.generate_calls == 1+ assert adapter.generate_with_preflight_calls == 0+++async def test_stream_with_preflight_cannot_bypass_bound_entrypoint() -> None:+ adapter = _PreflightDispatchAdapter()+ preflight = GenerationPreflightResult(adapter, {}, payload="request-evidence")++ events, saw_done = _parse_sse([event async for event in _events(adapter, preflight_result=preflight)])++ assert saw_done is True+ assert events[-1]["finish_reason"] == "stop"+ assert adapter.generate_calls == 0+ assert adapter.generate_with_preflight_calls == 1+ assert adapter.received_preflight is preflightasync def test_stream_shapes_generatechunk() -> None:@@ -141,7 +269,8 @@ async def test_stream_error_emits_terminal_error_chunk() -> None:GenerationChunk(text_delta="partial", done=False, is_first=True),GenerationChunk(text_delta="never", done=False),]- raw = await _drain(_FakeAdapter(chunks, raise_after=1))+ adapter = _FakeAdapter(chunks, raise_after=1)+ raw = await _drain(adapter)events, saw_done = _parse_sse(raw)assert saw_done is Trueterminal = next(e for e in events if e.get("done"))@@ -151,6 +280,222 @@ async def test_stream_error_emits_terminal_error_chunk() -> None:# it is logged server-side only. The client gets a generic message.assert "boom" not in terminal["error"]["message"]assert terminal["error"]["message"] == "internal error during generation"+ assert adapter.closed == 1+++async def test_stream_capacity_error_carries_configured_retry_hint() -> None:+ iterator = _FailingCloseIterator(+ [GenerationChunk(text_delta="partial", done=False)],+ next_error=GenerationCapacityError("scheduler full"),+ )+ raw = [+ event+ async for event in _stream_generate_events(+ _IteratorAdapter(iterator),+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=None,+ presence_penalty=None,+ top_k=None,+ min_new_tokens=None,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=False,+ top_logprobs=None,+ oom_retry_after_s=12,+ )+ ]++ events, saw_done = _parse_sse(raw)+ terminal = next(event for event in events if event.get("done"))+ assert saw_done is True+ assert terminal["error"] == {+ "code": "RESOURCE_EXHAUSTED",+ "message": "scheduler full",+ "retry_after_s": 12,+ }+++async def test_stream_terminal_break_closes_adapter_iterator_once() -> None:+ adapter = _FakeAdapter([GenerationChunk(text_delta="done", done=True, finish_reason="stop")])++ await _drain(adapter)++ assert adapter.closed == 1+++async def test_stream_consumer_close_closes_adapter_iterator_once() -> None:+ adapter = _FakeAdapter(+ [+ GenerationChunk(text_delta="first", done=False),+ GenerationChunk(text_delta="never", done=False),+ ]+ )+ events = _stream_generate_events(+ adapter,+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=None,+ presence_penalty=None,+ top_k=None,+ min_new_tokens=None,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=False,+ top_logprobs=None,+ )++ assert "first" in await anext(events)+ await events.aclose()++ assert adapter.closed == 1+++async def test_stream_consumer_close_through_thinking_wrapper_closes_upstream_once() -> None:+ adapter = _FakeAdapter(+ [+ GenerationChunk(text_delta="<think>private</think>visible", done=False),+ GenerationChunk(text_delta="never", done=False),+ ]+ )+ events = _stream_generate_events(+ adapter,+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=None,+ presence_penalty=None,+ top_k=None,+ min_new_tokens=None,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=False,+ top_logprobs=None,+ suppress_thinking=True,+ )++ assert "visible" in await anext(events)+ await events.aclose()++ assert adapter.closed == 1+++async def test_stream_consumer_cancellation_through_thinking_wrapper_closes_upstream_once() -> None:+ adapter = _BlockingAdapter()+ events = _stream_generate_events(+ adapter,+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=None,+ presence_penalty=None,+ top_k=None,+ min_new_tokens=None,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=False,+ top_logprobs=None,+ suppress_thinking=True,+ )++ assert "visible" in await anext(events)+ pending = asyncio.create_task(anext(events))+ await adapter.blocked.wait()+ pending.cancel()++ with pytest.raises(asyncio.CancelledError):+ await pending++ assert adapter.closed == 1++[email protected]("suppress_thinking", [False, True])+async def test_stream_cancellation_preserves_cancelled_error_when_cleanup_fails(+ suppress_thinking: bool,+) -> None:+ iterator = _FailingCloseIterator(+ [GenerationChunk(text_delta="visible", done=False)],+ block_after_chunks=True,+ )+ events = _events(_IteratorAdapter(iterator), suppress_thinking=suppress_thinking)++ assert "visible" in await anext(events)+ pending = asyncio.create_task(anext(events))+ await iterator.blocked.wait()+ pending.cancel()++ with pytest.raises(asyncio.CancelledError):+ await pending++ assert iterator.close_calls == 1++[email protected]("suppress_thinking", [False, True])+async def test_stream_explicit_close_is_not_masked_by_cleanup_failure(suppress_thinking: bool) -> None:+ iterator = _FailingCloseIterator(+ [GenerationChunk(text_delta="visible", done=False)],+ block_after_chunks=True,+ )+ events = _events(_IteratorAdapter(iterator), suppress_thinking=suppress_thinking)++ assert "visible" in await anext(events)+ await events.aclose()++ assert iterator.close_calls == 1++[email protected]("suppress_thinking", [False, True])+async def test_stream_terminal_outcome_is_not_masked_by_cleanup_failure(suppress_thinking: bool) -> None:+ iterator = _FailingCloseIterator([GenerationChunk(text_delta="done", done=True, finish_reason="stop")])++ events, saw_done = _parse_sse(await _drain(_IteratorAdapter(iterator), suppress_thinking=suppress_thinking))++ assert saw_done is True+ assert events[-1]["finish_reason"] == "stop"+ assert "error" not in events[-1]+ assert iterator.close_calls == 1++[email protected]("suppress_thinking", [False, True])+async def test_stream_generation_error_is_not_masked_by_cleanup_failure(suppress_thinking: bool) -> None:+ iterator = _FailingCloseIterator([], next_error=RuntimeError("generation failed"))++ events, saw_done = _parse_sse(await _drain(_IteratorAdapter(iterator), suppress_thinking=suppress_thinking))++ assert saw_done is True+ assert events[-1]["finish_reason"] == "error"+ assert events[-1]["error"] == {+ "code": "inference_error",+ "message": "internal error during generation",+ }+ assert iterator.close_calls == 1++[email protected]("suppress_thinking", [False, True])+async def test_stream_standalone_cleanup_failure_is_a_terminal_error(suppress_thinking: bool) -> None:+ iterator = _FailingCloseIterator([])++ events, saw_done = _parse_sse(await _drain(_IteratorAdapter(iterator), suppress_thinking=suppress_thinking))++ assert saw_done is True+ assert events[-1]["finish_reason"] == "error"+ assert events[-1]["error"]["code"] == "inference_error"+ assert "cleanup failed" not in events[-1]["error"]["message"]+ assert iterator.close_calls == 1async def test_stream_propagates_typed_terminal_error_chunk() -> None:@@ -175,6 +520,82 @@ async def test_stream_propagates_typed_terminal_error_chunk() -> None:assert terminal["error"] == {"code": "grammar_invalid", "message": "invalid grammar"}+ ("code", "message", "expected_code", "expected_message"),+ [+ (+ "inference_error",+ "SENSITIVE_NATIVE_SSE_RUNTIME",+ "inference_error",+ "internal error during generation",+ ),+ (+ "grammar_compile_failed",+ "SENSITIVE_NATIVE_SSE_GRAMMAR",+ "grammar_compile_failed",+ "internal error compiling grammar",+ ),+ (+ "MODEL_OUTPUT_PARSE_ERROR",+ "invalid model JSON",+ "MODEL_OUTPUT_PARSE_ERROR",+ "invalid model JSON",+ ),+ (+ "SENSITIVE_NATIVE_SSE_ERROR_CODE",+ "SENSITIVE_NATIVE_SSE_ERROR_CODE",+ "inference_error",+ "generation terminated with an upstream error",+ ),+ ],+)+async def test_stream_sanitizes_adapter_yielded_terminal_message(+ code: str,+ message: str,+ expected_code: str,+ expected_message: str,+) -> None:+ adapter = _FakeAdapter(+ [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="error",+ error_code=code,+ error_message=message,+ )+ ]+ )++ events, saw_done = _parse_sse(await _drain(adapter))++ assert saw_done is True+ assert events[-1]["finish_reason"] == "error"+ assert events[-1]["error"] == {"code": expected_code, "message": expected_message}+ if message.startswith("SENSITIVE_"):+ assert message not in str(events)+++async def test_stream_sanitizes_generic_typed_generation_exception() -> None:+ sentinel = "SENSITIVE_TYPED_NATIVE_SSE"+ failure = GenerationError(sentinel)+ failure.param = sentinel++ class _TypedFailureAdapter:+ async def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ raise failure+ yield GenerationChunk(text_delta="unreachable") # pragma: no cover++ events, saw_done = _parse_sse(await _drain(_TypedFailureAdapter()))++ assert saw_done is True+ assert events[-1]["error"] == {+ "code": "inference_error",+ "message": "internal error during generation",+ }+ assert sentinel not in str(events[-1])++async def test_stream_exhaustion_without_terminal_is_an_error() -> None:adapter = _FakeAdapter([GenerationChunk(text_delta="partial", done=False)])diff --git a/packages/sie_server/tests/api/test_generation_cleanup_precedence.py b/packages/sie_server/tests/api/test_generation_cleanup_precedence.pynew file mode 100644index 000000000..980aec304--- /dev/null+++ b/packages/sie_server/tests/api/test_generation_cleanup_precedence.py@@ -0,0 +1,223 @@+"""Cancellation precedence across generation async cleanup boundaries."""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from typing import Any++import pytest+from sie_server.adapters._generation_base import (+ GenerationChunk,+ aclose_with_error_precedence,+ suppress_thinking_blocks,+)+from sie_server.api.generate import _stream_generate_events+from sie_server.api.openai_completions import _collect_completion, _stream_completion+from sie_server.api.openai_local import _sanitize_sse_stream+from sie_server.processors.tool_call_parser import parse_tool_call_stream+++class _BlockingCloseIterator:+ """Finite iterator whose explicit close blocks until cancelled."""++ def __init__(self, values: list[Any]) -> None:+ self._values = list(values)+ self.close_started = asyncio.Event()+ self.close_calls = 0++ def __aiter__(self) -> _BlockingCloseIterator:+ return self++ async def __anext__(self) -> Any:+ if self._values:+ return self._values.pop(0)+ raise StopAsyncIteration++ async def aclose(self) -> None:+ self.close_calls += 1+ self.close_started.set()+ await asyncio.Event().wait()+++class _IteratorAdapter:+ def __init__(self, source: _BlockingCloseIterator) -> None:+ self.source = source++ def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ return self.source+++def _native_stream(+ source: _BlockingCloseIterator,+ *,+ suppress_thinking: bool,+) -> AsyncIterator[str]:+ return _stream_generate_events(+ _IteratorAdapter(source),+ prompt="hi",+ max_new_tokens=8,+ temperature=0.0,+ top_p=1.0,+ stop=None,+ frequency_penalty=None,+ presence_penalty=None,+ top_k=None,+ min_new_tokens=None,+ grammar=None,+ seed=None,+ logit_bias=None,+ logprobs=False,+ top_logprobs=None,+ suppress_thinking=suppress_thinking,+ )+++async def _cancel_during_close(+ stream: AsyncIterator[Any],+ source: _BlockingCloseIterator,+) -> None:+ await anext(stream)+ close_task = asyncio.create_task(stream.aclose())+ await source.close_started.wait()+ close_task.cancel()++ with pytest.raises(asyncio.CancelledError):+ await close_task+++async def test_cleanup_cancellation_supersedes_ordinary_primary_exception() -> None:+ source = _BlockingCloseIterator([])++ async def run() -> None:+ try:+ raise RuntimeError("primary")+ finally:+ await aclose_with_error_precedence(+ source,+ outcome_selected=False,+ context="test helper",+ )++ task = asyncio.create_task(run())+ await source.close_started.wait()+ task.cancel()++ with pytest.raises(asyncio.CancelledError):+ await task++ assert source.close_calls == 1++[email protected]("suppress_thinking", [False, True])+async def test_native_stream_cleanup_cancellation_supersedes_generator_exit(+ suppress_thinking: bool,+) -> None:+ source = _BlockingCloseIterator(+ [+ GenerationChunk(text_delta="visible", done=False),+ GenerationChunk(text_delta="later", done=False),+ ]+ )++ await _cancel_during_close(+ _native_stream(source, suppress_thinking=suppress_thinking),+ source,+ )++ assert source.close_calls == 1+++async def test_thinking_wrapper_cleanup_cancellation_supersedes_generator_exit() -> None:+ source = _BlockingCloseIterator(+ [+ GenerationChunk(text_delta="visible", done=False),+ GenerationChunk(text_delta="later", done=False),+ ]+ )++ await _cancel_during_close(suppress_thinking_blocks(source), source)++ assert source.close_calls == 1+++async def test_tool_parser_cleanup_cancellation_supersedes_generator_exit() -> None:+ source = _BlockingCloseIterator(+ [+ GenerationChunk(text_delta="visible long enough", done=False, is_first=True),+ GenerationChunk(text_delta="later", done=False),+ ]+ )++ await _cancel_during_close(parse_tool_call_stream(source), source)++ assert source.close_calls == 1+++async def test_completion_stream_cleanup_cancellation_supersedes_generator_exit() -> None:+ source = _BlockingCloseIterator(+ [+ GenerationChunk(text_delta="visible", done=False),+ GenerationChunk(text_delta="later", done=False),+ ]+ )+ stream = _stream_completion(+ source,+ completion_id="cmpl-cleanup",+ created=1,+ model="cleanup-model",+ include_usage=False,+ registry=object(),+ )++ await _cancel_during_close(stream, source)++ assert source.close_calls == 1+++async def test_completion_collector_cleanup_cancellation_supersedes_selected_outcome() -> None:+ source = _BlockingCloseIterator([GenerationChunk(text_delta="done", done=True, finish_reason="stop")])+ task = asyncio.create_task(_collect_completion(source))+ await source.close_started.wait()+ task.cancel()++ with pytest.raises(asyncio.CancelledError):+ await task++ assert source.close_calls == 1+++class _BlockingCloseResponse(_BlockingCloseIterator):+ def aiter_bytes(self) -> AsyncIterator[bytes]:+ return self+++class _CountingClient:+ def __init__(self) -> None:+ self.close_calls = 0++ async def aclose(self) -> None:+ self.close_calls += 1+++async def test_child_sse_cleanup_cancellation_closes_all_and_releases_slot() -> None:+ response = _BlockingCloseResponse([b'data: {"choices":[]}\n', b"data: [DONE]\n"])+ client = _CountingClient()+ slot = asyncio.Semaphore(0)+ stream = _sanitize_sse_stream(+ response, # type: ignore[arg-type]+ client, # type: ignore[arg-type]+ requested_model="cleanup-model",+ hide_thinking_blocks=False,+ initial_inside_thinking=False,+ reasoning_format="qwen3",+ slot=slot,+ )++ await _cancel_during_close(stream, response)++ assert response.close_calls == 1+ assert client.close_calls == 1+ await asyncio.wait_for(slot.acquire(), timeout=0.1)+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(slot.acquire(), timeout=0.01)diff --git a/packages/sie_server/tests/api/test_models.py b/packages/sie_server/tests/api/test_models.pyindex 3525a0fc0..b1f7af505 100644--- a/packages/sie_server/tests/api/test_models.py+++ b/packages/sie_server/tests/api/test_models.py@@ -284,6 +284,7 @@ class TestModelCapabilitiesField:"gen-model","org/gen-model",capabilities=GenerateCapabilities(+ streaming=False,grammar=["json_schema", "regex"],tools=True,code=True,@@ -317,6 +318,7 @@ class TestModelCapabilitiesField:assert response.status_code == 200caps = response.json()["capabilities"]assert caps is not None+ assert caps["streaming"] is Falseassert caps["grammar"] == ["json_schema", "regex"]assert caps["tools"] is Trueassert caps["code"] is True@@ -334,6 +336,7 @@ class TestModelCapabilitiesField:response = caps_client.get("/v1/models")assert response.status_code == 200by_name = {m["name"]: m for m in response.json()["models"]}+ assert by_name["gen-model"]["capabilities"]["streaming"] is Falseassert by_name["gen-model"]["capabilities"]["code"] is Trueassert by_name["enc-model"]["capabilities"] is Nonediff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex 83d029026..38bb0eba7 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -336,7 +336,7 @@ class TestOpenAIEmbeddings:with patch("sie_server.api.openai_compat.EncodePipeline.run_encode",new_callable=AsyncMock,- side_effect=RuntimeError("boom"),+ side_effect=RuntimeError("sensitive embeddings detail"),):response = client.post("/v1/embeddings",@@ -349,7 +349,8 @@ class TestOpenAIEmbeddings:error = data["error"]assert error["code"] == "inference_error"assert error["type"] == "server_error"- assert "message" in error+ assert error["message"] == "internal error during embeddings"+ assert "sensitive embeddings detail" not in response.textclass TestOpenAIEmbeddingsModelLoadStates:diff --git a/packages/sie_server/tests/api/test_openai_completions.py b/packages/sie_server/tests/api/test_openai_completions.pyindex f687b0355..f0d6ceb12 100644--- a/packages/sie_server/tests/api/test_openai_completions.py+++ b/packages/sie_server/tests/api/test_openai_completions.py@@ -3,15 +3,25 @@from __future__ import annotationsimport json-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom unittest.mock import MagicMockimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from sie_server.adapters._generation_base import FinishReason, GenerationAdapter, GenerationChunk+from sie_server.adapters._generation_base import (+ FinishReason,+ GenerationAdapter,+ GenerationCapacityError,+ GenerationChunk,+ GenerationDrainingError,+ GenerationError,+ GenerationUnsupportedFieldError,+)from sie_server.adapters._spec import AdapterSpec-from sie_server.api.openai_completions import router+from sie_server.api import openai_completions+from sie_server.api.openai_completions import _CompletionError, _stream_completion, router+from sie_server.config.engine import EngineConfigfrom sie_server.config.model import AdapterOptions, GenerateTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.registry import ModelRegistryfrom sie_server.types.grammar import GrammarSpec@@ -21,17 +31,38 @@ _GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"_GEMMA_CLOSE = "<" + "channel|" + ">"+class _UntrustedUnsupportedFieldError(GenerationUnsupportedFieldError):+ code = "SENSITIVE_UNSUPPORTED_CODE"+++class _UntrustedCapacityError(GenerationCapacityError):+ code = "SENSITIVE_CAPACITY_CODE"++class _FakeCompletionAdapter(GenerationAdapter):spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())def __init__(self) -> None:self.last_call: dict[str, object] | None = None+ self.preflight_call: dict[str, object] | None = None+ self.preflight_stream: bool | None = None+ self.preflight_error: GenerationError | None = None+ self.generate_error_after_chunks: int | None = None+ self.closed = Falseself.text_chunks = ["hello", " world"]self.finish_reason: FinishReason = "stop"+ self.error_code: str | None = None+ self.error_message: str | None = Nonedef load(self, device: str) -> None: # pragma: no cover - registry is mocked loaded_ = device+ def preflight_generate(self, parameters: Mapping[str, object], *, stream: bool) -> None:+ self.preflight_call = dict(parameters)+ self.preflight_stream = stream+ if self.preflight_error is not None:+ raise self.preflight_error+async def generate(self,prompt: str,@@ -65,15 +96,24 @@ class _FakeCompletionAdapter(GenerationAdapter):"seed": seed,}_ = repetition_penalty, grammar, logit_bias, logprobs, top_logprobs, images- for index, text in enumerate(self.text_chunks):- yield GenerationChunk(text_delta=text, is_first=index == 0)- yield GenerationChunk(- text_delta="",- done=True,- finish_reason=self.finish_reason,- prompt_tokens=3,- completion_tokens=2,- )+ try:+ if self.generate_error_after_chunks == 0:+ raise GenerationUnsupportedFieldError("top_k")+ for index, text in enumerate(self.text_chunks):+ yield GenerationChunk(text_delta=text, is_first=index == 0)+ if self.generate_error_after_chunks == index + 1:+ raise GenerationUnsupportedFieldError("top_k")+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=self.finish_reason,+ prompt_tokens=3,+ completion_tokens=2,+ error_code=self.error_code,+ error_message=self.error_message,+ )+ finally:+ self.closed = Truedef _config(model_id: str = "Qwen/Qwen3-4B-Instruct") -> ModelConfig:@@ -168,6 +208,8 @@ def test_blocking_completion_uses_direct_adapter_and_openai_shape("min_new_tokens": 2,"seed": -1,}+ assert adapter.preflight_call == adapter.last_call+ assert adapter.preflight_stream is Falsedef test_completion_uses_profile_frequency_penalty_and_seed_defaults(@@ -266,6 +308,324 @@ def test_streaming_completion_surfaces_cancelled_terminal_as_error(assert all("usage" not in event for event in events)+def test_completion_preflight_preserves_exact_parameter_and_skips_dispatch(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ adapter.preflight_error = GenerationUnsupportedFieldError("top_k")++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"+ assert adapter.preflight_call is not None+ assert adapter.last_call is None+++ ("error", "status_code"),+ [+ (_UntrustedUnsupportedFieldError("top_k", "private unsupported detail"), 400),+ (_UntrustedCapacityError("private capacity detail"), 503),+ ],+)+def test_completion_sanitizes_untrusted_typed_error_codes(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+ error: GenerationError,+ status_code: int,+) -> None:+ adapter.preflight_error = error++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x"},+ )++ assert response.status_code == status_code+ assert response.json()["error"]["code"] == "inference_error"+ assert "SENSITIVE_" not in response.text+++def test_completion_preserves_typed_synchronous_dispatch_error(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def refuse(**parameters: object) -> AsyncIterator[GenerationChunk]:+ _ = parameters+ raise GenerationUnsupportedFieldError("top_k")++ monkeypatch.setattr(adapter, "generate", refuse)++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"++[email protected]("error_after", [0, 1])+def test_blocking_completion_preserves_typed_iterator_error_and_closes(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+ error_after: int,+) -> None:+ adapter.generate_error_after_chunks = error_after++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"+ assert adapter.closed is True+++def test_streaming_completion_preserves_typed_iterator_error_and_closes(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+) -> None:+ adapter.generate_error_after_chunks = 1++ response = client.post(+ "/v1/completions",+ json={+ "model": "Qwen/Qwen3-4B-Instruct",+ "prompt": "x",+ "stream": True,+ },+ )++ assert response.status_code == 200+ payloads = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ error = json.loads(payloads[-2])+ assert error["choices"][0]["finish_reason"] is None+ assert error["error"]["code"] == "unsupported_field"+ assert error["error"]["param"] == "top_k"+ assert payloads[-1] == "[DONE]"+ assert adapter.closed is True++[email protected]("stream", [False, True])+ ("code", "message", "expected_code", "expected_message"),+ [+ (+ "inference_error",+ "SENSITIVE_COMPLETION_RUNTIME",+ "inference_error",+ "internal error during generation",+ ),+ (+ "grammar_compile_failed",+ "SENSITIVE_COMPLETION_GRAMMAR",+ "grammar_compile_failed",+ "internal error compiling grammar",+ ),+ (+ "empty_model_output",+ "model produced no visible output",+ "empty_model_output",+ "model produced no visible output",+ ),+ (+ "SENSITIVE_COMPLETION_ERROR_CODE",+ "SENSITIVE_COMPLETION_ERROR_CODE",+ "inference_error",+ "generation terminated with an upstream error",+ ),+ ],+)+def test_completion_classifies_adapter_yielded_terminal_errors(+ client: TestClient,+ adapter: _FakeCompletionAdapter,+ stream: bool,+ code: str,+ message: str,+ expected_code: str,+ expected_message: str,+) -> None:+ adapter.finish_reason = "error"+ adapter.error_code = code+ adapter.error_message = message++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x", "stream": stream},+ )++ if stream:+ assert response.status_code == 200, response.text+ payloads = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ error_event = json.loads(payloads[-2])+ assert error_event["choices"][0]["finish_reason"] is None+ assert error_event["error"]["code"] == expected_code+ assert error_event["error"]["message"] == expected_message+ assert payloads[-1] == "[DONE]"+ else:+ assert response.status_code == 500, response.text+ assert response.json()["error"]["code"] == expected_code+ assert response.json()["error"]["message"] == expected_message+ if message.startswith("SENSITIVE_"):+ assert message not in response.text++[email protected]("after_delta", [False, True])+ ("error", "expected_retry_after_s"),+ [+ (+ _CompletionError(+ "scheduler full",+ status_code=503,+ code="RESOURCE_EXHAUSTED",+ headers={"Retry-After": "12"},+ ),+ 12,+ ),+ (+ _CompletionError(+ "scheduler full",+ status_code=503,+ code="RESOURCE_EXHAUSTED",+ headers={"Retry-After": "malformed"},+ ),+ None,+ ),+ (+ _CompletionError(+ "wrong code",+ status_code=503,+ code="MODEL_LOADING",+ headers={"Retry-After": "12"},+ ),+ None,+ ),+ (+ _CompletionError(+ "scheduler draining",+ status_code=503,+ code="MODEL_LOADING",+ headers={"Retry-After": "5"},+ ),+ None,+ ),+ ],+)+async def test_streaming_completion_in_band_retry_authority_matches_gateway_shape(+ monkeypatch: pytest.MonkeyPatch,+ after_delta: bool,+ error: _CompletionError,+ expected_retry_after_s: int | None,+) -> None:+ async def chunks() -> AsyncIterator[GenerationChunk]:+ if after_delta:+ yield GenerationChunk(text_delta="partial")+ if error.code == "MODEL_LOADING" and error.message == "scheduler draining":+ raise GenerationDrainingError(error.message)+ raise GenerationCapacityError(error.message)++ monkeypatch.setattr(openai_completions, "_from_generation_error", lambda _exc, _registry: error)++ raw = [+ event+ async for event in _stream_completion(+ chunks(),+ completion_id="cmpl-test",+ created=1,+ model="test/model",+ include_usage=False,+ registry=MagicMock(),+ )+ ]+ payloads = [line.removeprefix("data: ").strip() for block in raw for line in block.splitlines() if line]+ assert payloads[-1] == "[DONE]"+ events = [json.loads(payload) for payload in payloads[:-1]]+ if after_delta:+ assert events[0]["choices"][0]["text"] == "partial"+ error_event = events[-1]+ assert error_event["choices"][0]["finish_reason"] is None+ assert error_event["error"]["code"] == error.code+ assert error_event["error"]["type"] == error.error_type+ assert error_event["error"]["param"] == error.param+ if expected_retry_after_s is None:+ assert "retry_after_s" not in error_event["error"]+ else:+ assert error_event["error"]["retry_after_s"] == expected_retry_after_s++[email protected]("after_delta", [False, True])+def test_streaming_completion_capacity_error_uses_configured_retry_authority(+ client: TestClient,+ registry: MagicMock,+ adapter: _FakeCompletionAdapter,+ monkeypatch: pytest.MonkeyPatch,+ after_delta: bool,+) -> None:+ registry.engine_config = EngineConfig.model_validate({"oom_recovery": {"retry_after_s": 12}})++ async def refuse(**_parameters: object) -> AsyncIterator[GenerationChunk]:+ if after_delta:+ yield GenerationChunk(text_delta="partial")+ raise GenerationCapacityError("scheduler full")++ monkeypatch.setattr(adapter, "generate", refuse)++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x", "stream": True},+ )++ assert response.status_code == 200, response.text+ payloads = [line.removeprefix("data: ") for line in response.text.splitlines() if line.startswith("data: ")]+ assert payloads[-1] == "[DONE]"+ events = [json.loads(payload) for payload in payloads[:-1]]+ if after_delta:+ assert events[0]["choices"][0]["text"] == "partial"+ error_event = events[-1]+ assert error_event["choices"][0]["finish_reason"] is None+ assert error_event["error"] == {+ "message": "scheduler full",+ "type": "server_error",+ "param": None,+ "code": "RESOURCE_EXHAUSTED",+ "retry_after_s": 12,+ }+++def test_completion_rejects_unsupported_streaming_before_load(+ client: TestClient,+ registry: MagicMock,+) -> None:+ config = _config()+ assert config.tasks.generate is not None+ config.tasks.generate.capabilities.streaming = False+ registry.get_config.return_value = config+ registry.is_loaded.return_value = False++ response = client.post(+ "/v1/completions",+ json={"model": "Qwen/Qwen3-4B-Instruct", "prompt": "x", "stream": True},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "stream"+ registry.start_load_async.assert_not_called()+ registry.get.assert_not_called()++@pytest.mark.parametrize("stream", [False, True])@pytest.mark.parametrize("enable_thinking", [False, True])@pytest.mark.parametrize("model_id", ["Qwen/Qwen3.5-4B", "google/gemma-4-E2B-it"])diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pyindex 6893f57e0..37586a075 100644--- a/packages/sie_server/tests/api/test_openai_local.py+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -213,6 +213,31 @@ def test_chat_rejects_non_bool_stream() -> None:assert r.json()["error"]["param"] == "stream"+def test_chat_rejects_unsupported_streaming_before_load(monkeypatch: pytest.MonkeyPatch) -> None:+ client, registry = _cuda_chat_client(+ monkeypatch,+ lambda _request: pytest.fail("unsupported streaming must not reach the child"),+ )+ generate_task = registry.get_config.return_value.tasks.generate+ generate_task.capabilities = SimpleNamespace(streaming=False)+ registry.is_loaded.return_value = False++ response = client.post(+ "/v1/chat/completions",+ json={+ "model": "Qwen/Qwen3.5-4B",+ "messages": [{"role": "user", "content": "hi"}],+ "stream": True,+ },+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "stream"+ registry.start_load_async.assert_not_called()+ registry.get.assert_not_called()++def test_chat_rejects_invalid_max_tokens() -> None:msgs = [{"role": "user", "content": "hi"}]for bad in (0, -5, "100", True):@@ -1084,7 +1109,7 @@ def test_rerank_inference_error_returns_top_level_openai_500() -> None:client, registry = _rerank_client()async def _boom() -> None:- raise RuntimeError("boom")+ raise RuntimeError("sensitive reranker detail")worker = MagicMock()worker.submit_score = AsyncMock(return_value=_boom())@@ -1097,7 +1122,8 @@ def test_rerank_inference_error_returns_top_level_openai_500() -> None:error = body["error"]assert error["code"] == "inference_error"assert error["type"] == "server_error"- assert error["message"] == "boom"+ assert error["message"] == "internal error during reranking"+ assert "sensitive reranker detail" not in r.text@pytest.mark.parametrize("bad", [float("nan"), float("inf"), float("-inf")])diff --git a/packages/sie_server/tests/api/test_openai_responses.py b/packages/sie_server/tests/api/test_openai_responses.pyindex 19b7ed998..7486624cb 100644--- a/packages/sie_server/tests/api/test_openai_responses.py+++ b/packages/sie_server/tests/api/test_openai_responses.py@@ -3,14 +3,20 @@from __future__ import annotationsimport json-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom pathlib import Pathfrom unittest.mock import AsyncMock, MagicMockimport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient-from sie_server.adapters._generation_base import GenerationAdapter, GenerationChunk+from sie_server.adapters._generation_base import (+ GenerationAdapter,+ GenerationCapacityError,+ GenerationChunk,+ GenerationError,+ GenerationUnsupportedFieldError,+)from sie_server.adapters._spec import AdapterSpecfrom sie_server.api import openai_responsesfrom sie_server.api.openai_completions import _CompletionError@@ -22,17 +28,37 @@ from sie_server.types.inputs import ImageInput_VECTORS = Path(__file__).parents[4] / "conformance" / "openai_generation" / "responses_request_vectors.json"+class _UntrustedUnsupportedFieldError(GenerationUnsupportedFieldError):+ code = "SENSITIVE_UNSUPPORTED_CODE"+++class _UntrustedCapacityError(GenerationCapacityError):+ code = "SENSITIVE_CAPACITY_CODE"++class _FakeResponsesAdapter(GenerationAdapter):spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())def __init__(self) -> None:self.last_call: dict[str, object] | None = None+ self.preflight_call: dict[str, object] | None = None+ self.preflight_error: GenerationError | None = None+ self.generate_error_after_chunks: int | None = None+ self.closed = Falseself.text_chunks = ["hello", " world"]self.include_usage = True+ self.error_code: str | None = None+ self.error_message: str | None = Nonedef load(self, device: str) -> None: # pragma: no cover - registry is mocked loaded_ = device+ def preflight_generate(self, parameters: Mapping[str, object], *, stream: bool) -> None:+ assert stream is False+ self.preflight_call = dict(parameters)+ if self.preflight_error is not None:+ raise self.preflight_error+async def generate(self,prompt: str,@@ -66,15 +92,24 @@ class _FakeResponsesAdapter(GenerationAdapter):"seed": seed,}_ = repetition_penalty, grammar, logit_bias, logprobs, top_logprobs, images- for index, text in enumerate(self.text_chunks):- yield GenerationChunk(text_delta=text, is_first=index == 0)- yield GenerationChunk(- text_delta="",- done=True,- finish_reason="stop",- prompt_tokens=3 if self.include_usage else None,- completion_tokens=2 if self.include_usage else None,- )+ try:+ if self.generate_error_after_chunks == 0:+ raise GenerationUnsupportedFieldError("top_k")+ for index, text in enumerate(self.text_chunks):+ yield GenerationChunk(text_delta=text, is_first=index == 0)+ if self.generate_error_after_chunks == index + 1:+ raise GenerationUnsupportedFieldError("top_k")+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=3 if self.include_usage else None,+ completion_tokens=2 if self.include_usage else None,+ error_code=self.error_code,+ error_message=self.error_message,+ )+ finally:+ self.closed = Truedef _config(*, chat_template_kwargs: dict[str, object] | None = None) -> ModelConfig:@@ -174,6 +209,7 @@ def test_blocking_responses_uses_direct_adapter_and_openai_shape("min_new_tokens": 2,"seed": -1,}+ assert adapter.preflight_call == adapter.last_calldef test_message_input_uses_model_native_template(@@ -278,6 +314,58 @@ def test_responses_rejects_terminal_event_without_usage(assert response.json()["error"]["code"] == "malformed_worker_response"+ ("code", "message", "expected_code", "expected_message"),+ [+ (+ "inference_error",+ "SENSITIVE_RESPONSES_RUNTIME",+ "inference_error",+ "internal error during generation",+ ),+ (+ "grammar_compile_failed",+ "SENSITIVE_RESPONSES_GRAMMAR",+ "grammar_compile_failed",+ "internal error compiling grammar",+ ),+ (+ "empty_model_output",+ "model produced no visible output",+ "empty_model_output",+ "model produced no visible output",+ ),+ (+ "SENSITIVE_RESPONSES_ERROR_CODE",+ "SENSITIVE_RESPONSES_ERROR_CODE",+ "inference_error",+ "generation terminated with an upstream error",+ ),+ ],+)+def test_responses_classifies_adapter_yielded_terminal_errors(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+ code: str,+ message: str,+ expected_code: str,+ expected_message: str,+) -> None:+ adapter.error_code = code+ adapter.error_message = message++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 500, response.text+ assert response.json()["error"]["code"] == expected_code+ assert response.json()["error"]["message"] == expected_message+ if message.startswith("SENSITIVE_"):+ assert message not in response.text++def test_responses_rejects_oversized_rendered_input(client: TestClient,monkeypatch: pytest.MonkeyPatch,@@ -292,3 +380,86 @@ def test_responses_rejects_oversized_rendered_input(assert response.status_code == 413assert response.json()["error"]["param"] == "input"assert response.json()["error"]["code"] == "context_exceeded"+++def test_responses_preflight_preserves_exact_parameter_and_skips_dispatch(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+) -> None:+ adapter.preflight_error = GenerationUnsupportedFieldError("top_k")++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"+ assert adapter.preflight_call is not None+ assert adapter.last_call is None+++ ("error", "status_code"),+ [+ (_UntrustedUnsupportedFieldError("top_k", "private unsupported detail"), 400),+ (_UntrustedCapacityError("private capacity detail"), 503),+ ],+)+def test_responses_sanitizes_untrusted_typed_error_codes(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+ error: GenerationError,+ status_code: int,+) -> None:+ adapter.preflight_error = error++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == status_code+ assert response.json()["error"]["code"] == "inference_error"+ assert "SENSITIVE_" not in response.text+++def test_responses_preserves_typed_synchronous_dispatch_error(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def refuse(**parameters: object) -> AsyncIterator[GenerationChunk]:+ _ = parameters+ raise GenerationUnsupportedFieldError("top_k")++ monkeypatch.setattr(adapter, "generate", refuse)++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"++[email protected]("error_after", [0, 1])+def test_responses_preserves_typed_iterator_error_and_closes(+ client: TestClient,+ adapter: _FakeResponsesAdapter,+ error_after: int,+) -> None:+ adapter.generate_error_after_chunks = error_after++ response = client.post(+ "/v1/responses",+ json={"model": "Qwen/Qwen3-4B-Instruct", "input": "x"},+ )++ assert response.status_code == 400+ assert response.json()["error"]["code"] == "unsupported_field"+ assert response.json()["error"]["param"] == "top_k"+ assert adapter.closed is Truediff --git a/packages/sie_server/tests/config/test_serving_artifact_config.py b/packages/sie_server/tests/config/test_serving_artifact_config.pynew file mode 100644index 000000000..db754ab6d--- /dev/null+++ b/packages/sie_server/tests/config/test_serving_artifact_config.py@@ -0,0 +1,166 @@+from __future__ import annotations++import pytest+from pydantic import ValidationError+from sie_server.config.engine import ComputePrecision+from sie_server.config.model import AdapterOptions, ModelConfig, ProfileConfig, Tasks+from sie_server.core.loader import expand_profile_variants++SOURCE_REVISION = "a" * 40+++def _declaration(+ digest: str,+ *,+ revision: str = "b" * 40,+ compute_type: str = "bfloat16",+) -> dict[str, str]:+ return {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": revision,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": digest,+ "compute_type": compute_type,+ }+++def _profile(+ *,+ loadtime: dict[str, object],+ extends: str | None = None,+ compute_precision: ComputePrecision | None = "bfloat16",+) -> ProfileConfig:+ return ProfileConfig(+ extends=extends,+ adapter_path=None if extends else "test.adapter:Adapter",+ max_batch_tokens=None if extends else 128,+ compute_precision=None if extends else compute_precision,+ adapter_options=AdapterOptions(loadtime=loadtime),+ )+++def test_requires_immutable_hf_source_identity() -> None:+ with pytest.raises(ValidationError, match="immutable 40-char hf_revision"):+ ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision="main",+ tasks=Tasks(),+ profiles={"default": _profile(loadtime={"serving_artifact": _declaration("c" * 64)})},+ )+++ "loader_field",+ [+ "artifact_path",+ "ct2_compute_type",+ ],+)+def test_rejects_loader_owned_catalog_fields(loader_field: str) -> None:+ with pytest.raises(ValidationError, match="loader-owned"):+ _profile(loadtime={loader_field: "operator-injected"})+++def test_effective_profiles_may_select_distinct_immutable_artifacts() -> None:+ default_declaration = _declaration("c" * 64)+ quantized_declaration = _declaration("d" * 64, revision="e" * 40, compute_type="int8_bfloat16")+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=SOURCE_REVISION,+ tasks=Tasks(),+ profiles={+ "default": _profile(loadtime={"serving_artifact": default_declaration}),+ "inherited": _profile(loadtime={}, extends="default"),+ "quantized": _profile(loadtime={"serving_artifact": quantized_declaration}),+ },+ )++ assert config.serving_artifact_declaration("default").manifest_sha256 == "c" * 64+ assert config.serving_artifact_declaration("inherited").manifest_sha256 == "c" * 64+ assert config.serving_artifact_declaration("quantized").manifest_sha256 == "d" * 64+ assert config.serving_artifact_declaration("quantized").compute_type == "int8_bfloat16"++ expanded = expand_profile_variants([config])+ assert expanded["google/source-model:inherited"].serving_artifact_declaration().manifest_sha256 == "c" * 64+ assert expanded["google/source-model:quantized"].serving_artifact_declaration().manifest_sha256 == "d" * 64+ assert expanded["google/source-model:quantized"].serving_artifact_declaration().compute_type == "int8_bfloat16"+++def test_closed_nested_declaration_rejects_unknown_fields() -> None:+ declaration = _declaration("c" * 64)+ declaration["filesystem_root"] = "/operator/path"++ with pytest.raises(ValidationError, match="serving_artifact is invalid"):+ _profile(loadtime={"serving_artifact": declaration})+++def test_explicit_null_serving_artifact_is_not_treated_as_absent() -> None:+ with pytest.raises(ValidationError, match="serving_artifact is invalid"):+ _profile(loadtime={"serving_artifact": None})+++ ("compute_type", "compute_precision"),+ [+ ("bfloat16", "float16"),+ ("float16", "float32"),+ ("float32", "bfloat16"),+ ("int8_bfloat16", "float16"),+ ("int8_float16", "bfloat16"),+ ("int8_float32", "float16"),+ ],+)+def test_rejects_profile_precision_that_misrepresents_artifact_compute(+ compute_type: str,+ compute_precision: ComputePrecision,+) -> None:+ profile = _profile(+ loadtime={"serving_artifact": _declaration("c" * 64, compute_type=compute_type)},+ compute_precision=compute_precision,+ )++ with pytest.raises(ValidationError, match="does not match serving artifact compute_type"):+ ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=SOURCE_REVISION,+ tasks=Tasks(),+ profiles={"default": profile},+ )+++def test_bare_int8_artifact_does_not_guess_runtime_float_precision() -> None:+ profile = _profile(+ loadtime={"serving_artifact": _declaration("c" * 64, compute_type="int8")},+ compute_precision="float16",+ )++ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=SOURCE_REVISION,+ tasks=Tasks(),+ profiles={"default": profile},+ )++ assert config.resolve_profile("default").compute_precision == "float16"+++def test_omitted_profile_precision_does_not_invent_artifact_conflict() -> None:+ profile = _profile(+ loadtime={"serving_artifact": _declaration("c" * 64, compute_type="bfloat16")},+ compute_precision=None,+ )++ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=SOURCE_REVISION,+ tasks=Tasks(),+ profiles={"default": profile},+ )++ assert config.resolve_profile("default").compute_precision is Nonediff --git a/packages/sie_server/tests/config/test_serving_artifacts.py b/packages/sie_server/tests/config/test_serving_artifacts.pynew file mode 100644index 000000000..0ad1ea537--- /dev/null+++ b/packages/sie_server/tests/config/test_serving_artifacts.py@@ -0,0 +1,355 @@+from __future__ import annotations++import errno+import hashlib+import json+import os+import threading+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path++import pytest+from pydantic import ValidationError+from sie_server.config import serving_artifacts+from sie_server.config.serving_artifacts import (+ CTRANSLATE2_TORCH_VERSION,+ CTRANSLATE2_TRANSFORMERS_VERSION,+ CTRANSLATE2_VERSION,+ SERVING_ARTIFACT_SCHEMA,+ ServingArtifactDeclaration,+ ServingArtifactManifest,+ atomic_rename_directory_noreplace,+ canonical_manifest_bytes,+ verify_and_materialize_serving_artifact,+)++SOURCE_ID = "google/source-model"+SOURCE_REVISION = "a" * 40+DERIVED_ID = "superlinked/derived-model"+DERIVED_REVISION = "b" * 40+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _stage_artifact(+ root: Path,+ *,+ source_id: str = SOURCE_ID,+ source_revision: str = SOURCE_REVISION,+) -> tuple[ServingArtifactDeclaration, Path]:+ repo_root = root / "models--superlinked--derived-model"+ snapshot = repo_root / "snapshots" / DERIVED_REVISION+ snapshot.mkdir(parents=True)+ artifacts = {+ "config.json": (b'{"model_type":"Transformer"}\n', "model.config"),+ "model.bin": (b"converted model bytes", "model.weights"),+ "tokenizer_config.json": (b'{"tokenizer_class":"T5Tokenizer"}\n', "tokenizer.config"),+ "spiece.model": (b"sentencepiece bytes", "tokenizer.sentencepiece"),+ }+ entries = []+ for relative, (content, role) in artifacts.items():+ path = snapshot / relative+ path.write_bytes(content)+ entries.append(+ {+ "path": relative,+ "role": role,+ "size_bytes": len(content),+ "sha256": _sha256(content),+ }+ )+ tokenizer_config = artifacts["tokenizer_config.json"][0]+ manifest = ServingArtifactManifest.model_validate(+ {+ "schema": SERVING_ARTIFACT_SCHEMA,+ "source": {"hf_id": source_id, "hf_revision": source_revision},+ "converter": {+ "name": "ct2-transformers-converter",+ "version": CTRANSLATE2_VERSION,+ "torch_version": CTRANSLATE2_TORCH_VERSION,+ "transformers_version": CTRANSLATE2_TRANSFORMERS_VERSION,+ "compute_type": "bfloat16",+ "recipe_sha256": "c" * 64,+ },+ "runtime": {"minimum_version": CTRANSLATE2_VERSION, "maximum_version": CTRANSLATE2_VERSION},+ "tokenizer": {+ "class_name": "T5Tokenizer",+ "config_sha256": _sha256(tokenizer_config),+ "files": [+ {"path": "spiece.model", "role": "tokenizer.sentencepiece"},+ {"path": "tokenizer_config.json", "role": "tokenizer.config"},+ ],+ },+ "artifacts": entries,+ }+ )+ manifest_bytes = canonical_manifest_bytes(manifest)+ manifest_path = snapshot / "sie-serving-artifact.json"+ manifest_path.write_bytes(manifest_bytes)+ declaration = ServingArtifactDeclaration(+ format="ctranslate2",+ repo_id=DERIVED_ID,+ revision=DERIVED_REVISION,+ manifest_path="sie-serving-artifact.json",+ manifest_sha256=_sha256(manifest_bytes),+ compute_type="bfloat16",+ )+ return declaration, repo_root+++def _materialize(+ declaration: ServingArtifactDeclaration,+ repo_root: Path,+ cache_root: Path,+):+ return verify_and_materialize_serving_artifact(+ declaration,+ source_hf_id=SOURCE_ID,+ source_hf_revision=SOURCE_REVISION,+ cached_repo_root=repo_root,+ materialized_cache_root=cache_root,+ )++[email protected]("path", ["/manifest.json", "../manifest.json", "a//manifest.json", "a\\manifest.json"])+def test_declaration_rejects_unsafe_manifest_path(path: str) -> None:+ with pytest.raises(ValidationError, match=r"relative POSIX|must not contain"):+ ServingArtifactDeclaration(+ format="ctranslate2",+ repo_id=DERIVED_ID,+ revision=DERIVED_REVISION,+ manifest_path=path,+ manifest_sha256="d" * 64,+ compute_type="bfloat16",+ )+++def test_declaration_rejects_mutable_revision_and_uppercase_digest() -> None:+ with pytest.raises(ValidationError):+ ServingArtifactDeclaration(+ format="ctranslate2",+ repo_id=DERIVED_ID,+ revision="main",+ manifest_path="manifest.json",+ manifest_sha256="D" * 64,+ compute_type="bfloat16",+ )+++def test_atomic_publish_refuses_existing_directory(tmp_path: Path) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "destination"+ source.mkdir()+ destination.mkdir()++ with pytest.raises(FileExistsError):+ atomic_rename_directory_noreplace(source, destination)++ assert source.is_dir()+ assert destination.is_dir()+++def test_materialization_falls_back_when_noreplace_is_unsupported(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")++ def unsupported_rename(_source: Path, destination: Path) -> None:+ raise OSError(errno.EINVAL, os.strerror(errno.EINVAL), destination)++ monkeypatch.setattr(serving_artifacts, "atomic_rename_directory_noreplace", unsupported_rename)++ first = _materialize(declaration, repo_root, tmp_path / "materialized")+ second = _materialize(declaration, repo_root, tmp_path / "materialized")++ assert first.root == second.root+ assert (first.root / "model.bin").read_bytes() == b"converted model bytes"+++def test_portable_publish_requires_nonempty_source_and_absent_destination(tmp_path: Path) -> None:+ source = tmp_path / "source"+ destination = tmp_path / "destination"+ source.mkdir()++ with pytest.raises(ValueError, match="nonempty"):+ serving_artifacts._rename_verified_nonempty_directory(source, destination)++ (source / "model.bin").write_bytes(b"model")+ destination.mkdir()+ with pytest.raises(FileExistsError):+ serving_artifacts._rename_verified_nonempty_directory(source, destination)+++def test_concurrent_portable_publishers_cannot_replace_nonempty_winner(tmp_path: Path) -> None:+ destination = tmp_path / "destination"+ sources = [tmp_path / "source-a", tmp_path / "source-b"]+ for index, source in enumerate(sources):+ source.mkdir()+ (source / "model.bin").write_bytes(str(index).encode())+ barrier = threading.Barrier(2)++ def publish(source: Path) -> int | None:+ barrier.wait()+ try:+ serving_artifacts._rename_verified_nonempty_directory(source, destination)+ except OSError as exc:+ return exc.errno+ return None++ with ThreadPoolExecutor(max_workers=2) as executor:+ results = list(executor.map(publish, sources))++ assert results.count(None) == 1+ assert next(result for result in results if result is not None) in {errno.EEXIST, errno.ENOTEMPTY}+ assert (destination / "model.bin").read_bytes() in {b"0", b"1"}+++def test_materializes_canonical_read_only_tree_and_reuses_verified_bytes(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ cache_root = tmp_path / "materialized"++ first = _materialize(declaration, repo_root, cache_root)+ second = _materialize(declaration, repo_root, cache_root)++ assert first.root == second.root == cache_root / declaration.manifest_sha256+ assert first.manifest_sha256 == declaration.manifest_sha256+ assert first.artifact_count == 4+ assert sorted(path.relative_to(first.root).as_posix() for path in first.root.rglob("*") if path.is_file()) == [+ "config.json",+ "model.bin",+ "spiece.model",+ "tokenizer_config.json",+ ]+ assert all(path.stat().st_mode & 0o222 == 0 for path in first.root.rglob("*") if path.is_file())+++def test_materialized_bytes_are_independent_from_later_source_mutation(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ source = repo_root / "snapshots" / DERIVED_REVISION / "model.bin"+ source.chmod(0o444)++ verified = _materialize(declaration, repo_root, tmp_path / "materialized")+ served = verified.root / "model.bin"++ assert source.stat().st_ino != served.stat().st_ino+ source.chmod(0o644)+ source.write_bytes(b"mutated after admission")+ assert served.read_bytes() == b"converted model bytes"+ assert served.stat().st_mode & 0o222 == 0+++def test_rejects_source_identity_mismatch(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub", source_id="other/source")++ with pytest.raises(ValueError, match="source identity"):+ _materialize(declaration, repo_root, tmp_path / "materialized")+++def test_rejects_effective_profile_compute_type_mismatch(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ mismatched = declaration.model_copy(update={"compute_type": "int8_bfloat16"})++ with pytest.raises(ValueError, match="compute_type does not match the effective profile"):+ _materialize(mismatched, repo_root, tmp_path / "materialized")+++def test_rejects_manifest_digest_and_noncanonical_json(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ manifest_path = repo_root / "snapshots" / DERIVED_REVISION / declaration.manifest_path+ parsed = json.loads(manifest_path.read_bytes())+ noncanonical = json.dumps(parsed, indent=2).encode()+ manifest_path.write_bytes(noncanonical)+ matching = declaration.model_copy(update={"manifest_sha256": _sha256(noncanonical)})++ with pytest.raises(ValueError, match="not canonical"):+ _materialize(matching, repo_root, tmp_path / "materialized")+++def test_rejects_file_drift_before_materialization(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ (repo_root / "snapshots" / DERIVED_REVISION / "model.bin").write_bytes(b"drifted model bytes")++ with pytest.raises(ValueError, match=r"size|sha256"):+ _materialize(declaration, repo_root, tmp_path / "materialized")+++def test_rejects_tokenizer_class_mismatch_before_publishing_materialized_root(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ manifest_path = repo_root / "snapshots" / DERIVED_REVISION / declaration.manifest_path+ payload = json.loads(manifest_path.read_bytes())+ payload["tokenizer"]["class_name"] = "OtherTokenizer"+ manifest = ServingArtifactManifest.model_validate(payload)+ manifest_bytes = canonical_manifest_bytes(manifest)+ manifest_path.write_bytes(manifest_bytes)+ declaration = declaration.model_copy(update={"manifest_sha256": _sha256(manifest_bytes)})+ cache_root = tmp_path / "materialized"++ with pytest.raises(ValueError, match="tokenizer class"):+ _materialize(declaration, repo_root, cache_root)++ assert not (cache_root / declaration.manifest_sha256).exists()+++def test_rejects_source_symlink_escaping_repository_cache(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ model = repo_root / "snapshots" / DERIVED_REVISION / "model.bin"+ outside = tmp_path / "outside.bin"+ model.rename(outside)+ model.symlink_to(outside)++ with pytest.raises(ValueError, match="escapes"):+ _materialize(declaration, repo_root, tmp_path / "materialized")+++def test_rejects_snapshot_revision_alias(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ snapshot = repo_root / "snapshots" / DERIVED_REVISION+ actual_snapshot = repo_root / "snapshots" / ("e" * 40)+ snapshot.rename(actual_snapshot)+ snapshot.symlink_to(actual_snapshot, target_is_directory=True)++ with pytest.raises(ValueError, match="snapshot escapes"):+ _materialize(declaration, repo_root, tmp_path / "materialized")+++def test_rejects_partial_or_extra_reused_tree(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ cache_root = tmp_path / "materialized"+ destination = cache_root / declaration.manifest_sha256+ destination.mkdir(parents=True)+ (destination / "extra.bin").write_bytes(b"unbound")+ (destination / "extra.bin").chmod(0o444)+ destination.chmod(0o555)++ with pytest.raises(ValueError, match="unlisted file"):+ _materialize(declaration, repo_root, cache_root)+++def test_rejects_writable_reused_tree(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ cache_root = tmp_path / "materialized"+ verified = _materialize(declaration, repo_root, cache_root)+ verified.root.chmod(0o755)++ with pytest.raises(ValueError, match="root is writable"):+ _materialize(declaration, repo_root, cache_root)++[email protected](not hasattr(os, "mkfifo"), reason="FIFO nodes are unavailable on this platform")+def test_rejects_special_node_in_reused_tree(tmp_path: Path) -> None:+ declaration, repo_root = _stage_artifact(tmp_path / "hub")+ cache_root = tmp_path / "materialized"+ destination = cache_root / declaration.manifest_sha256+ destination.mkdir(parents=True)+ os.mkfifo(destination / "model.bin")+ destination.chmod(0o555)++ try:+ with pytest.raises(ValueError, match="special node"):+ _materialize(declaration, repo_root, cache_root)+ finally:+ destination.chmod(0o700)+ (destination / "model.bin").unlink()+ destination.rmdir()diff --git a/packages/sie_server/tests/core/test_loader.py b/packages/sie_server/tests/core/test_loader.pyindex 05d857606..a9910d824 100644--- a/packages/sie_server/tests/core/test_loader.py+++ b/packages/sie_server/tests/core/test_loader.py@@ -17,6 +17,7 @@ from sie_server.config.model import (ScoreTask,Tasks,)+from sie_server.config.serving_artifacts import VerifiedServingArtifactfrom sie_server.core.loader import (_build_adapter_kwargs,load_adapter,@@ -544,6 +545,116 @@ class TestBuildAdapterKwargs:with pytest.raises(ValueError, match="live external downloads"):_build_adapter_kwargs(config, "float16")+ def test_serving_artifact_requires_loader_verification(self) -> None:+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision="a" * 40,+ tasks=Tasks(),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:Adapter",+ max_batch_tokens=128,+ adapter_options=AdapterOptions(+ loadtime={+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": "b" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ ),+ )+ },+ )++ with pytest.raises(ValueError, match="loader did not verify"):+ _build_adapter_kwargs(config, "float16")++ def test_serving_artifact_declaration_is_removed_and_verified_root_is_injected(self, tmp_path: Path) -> None:+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision="a" * 40,+ tasks=Tasks(),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:Adapter",+ max_batch_tokens=128,+ adapter_options=AdapterOptions(+ loadtime={+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": "b" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ ),+ )+ },+ )+ verified = VerifiedServingArtifact(+ root=tmp_path / "materialized" / ("c" * 64),+ manifest_sha256="c" * 64,+ repo_id="superlinked/derived-model",+ revision="b" * 40,+ compute_type="bfloat16",+ artifact_count=4,+ manifest=None, # ty: ignore[invalid-argument-type] -- constructor ownership is tested, not manifest parsing+ )++ kwargs = _build_adapter_kwargs(config, "float16", verified_serving_artifact=verified)++ assert "serving_artifact" not in kwargs+ assert kwargs["artifact_path"] == verified.root+ assert kwargs["ct2_compute_type"] == "bfloat16"+ assert "model_name_or_path" not in kwargs+ assert "revision" not in kwargs++ def test_serving_artifact_rejects_stale_loader_registration(self, tmp_path: Path) -> None:+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision="a" * 40,+ tasks=Tasks(),+ profiles={+ "default": ProfileConfig(+ adapter_path="test:Adapter",+ max_batch_tokens=128,+ adapter_options=AdapterOptions(+ loadtime={+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": "b" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ ),+ )+ },+ )+ stale = VerifiedServingArtifact(+ root=tmp_path,+ manifest_sha256="d" * 64,+ repo_id="superlinked/derived-model",+ revision="b" * 40,+ compute_type="bfloat16",+ artifact_count=1,+ manifest=None, # ty: ignore[invalid-argument-type]+ )++ with pytest.raises(ValueError, match="stale or mismatched"):+ _build_adapter_kwargs(config, "float16", verified_serving_artifact=stale)+class TestLoadAdapter:"""Tests for load_adapter."""diff --git a/packages/sie_server/tests/core/test_model_loader_cache.py b/packages/sie_server/tests/core/test_model_loader_cache.pyindex a83843ff5..766b5533c 100644--- a/packages/sie_server/tests/core/test_model_loader_cache.py+++ b/packages/sie_server/tests/core/test_model_loader_cache.py@@ -1,9 +1,13 @@+import hashlibfrom concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport pytest+from sie_sdk.cache import CacheConfigfrom sie_server.config.model import AdapterOptions, ModelConfig, ProfileConfig, Tasks+from sie_server.config.serving_artifacts import ServingArtifactManifest, canonical_manifest_bytesfrom sie_server.core.model_loader import ModelLoaderfrom sie_server.core.postprocessor_registry import PostprocessorRegistryfrom sie_server.core.preprocessor_registry import PreprocessorRegistry@@ -70,3 +74,202 @@ def test_ensure_weights_cached_stages_pinned_speculative_draft(finally:loader._load_executor.shutdown(wait=True)cpu_pool.shutdown(wait=True)+++def test_ensure_weights_cached_stages_derived_repo_instead_of_source(tmp_path: Path) -> None:+ source_revision = "a" * 40+ derived_revision = "b" * 40+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=source_revision,+ tasks=Tasks(),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=128,+ adapter_options=AdapterOptions(+ loadtime={+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": derived_revision,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ ),+ )+ },+ )+ cpu_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cpu")+ disk_cache = MagicMock()+ loader = ModelLoader(+ preprocessor_registry=PreprocessorRegistry(),+ postprocessor_registry=PostprocessorRegistry(cpu_pool),+ all_configs={},+ disk_cache_manager=disk_cache,+ )+ cache_config = SimpleNamespace(local_cache=tmp_path / "hub")+ cached_repo = tmp_path / "hub" / "models--superlinked--derived-model"+ verified = SimpleNamespace(+ root=tmp_path / "materialized" / ("c" * 64),+ manifest_sha256="c" * 64,+ repo_id="superlinked/derived-model",+ revision=derived_revision,+ compute_type="bfloat16",+ )++ try:+ with (+ patch("sie_sdk.cache.get_cache_config", return_value=cache_config),+ patch("sie_sdk.cache.ensure_model_cached", return_value=cached_repo) as ensure,+ patch(+ "sie_server.core.model_loader.verify_and_materialize_serving_artifact",+ return_value=verified,+ ) as materialize,+ ):+ loader.ensure_weights_cached(config)++ ensure.assert_called_once_with(+ "superlinked/derived-model",+ cache_config,+ revision=derived_revision,+ )+ materialize.assert_called_once()+ assert materialize.call_args.kwargs == {+ "source_hf_id": "google/source-model",+ "source_hf_revision": source_revision,+ "cached_repo_root": cached_repo,+ "materialized_cache_root": cache_config.local_cache / "sie-serving-artifacts-v1",+ }+ assert loader._verified_serving_artifacts[config.sie_id] is verified+ disk_cache.ensure_space_before_download.assert_called_once_with("superlinked/derived-model")+ disk_cache.touch.assert_called_once_with("superlinked/derived-model")+ finally:+ loader._load_executor.shutdown(wait=True)+ cpu_pool.shutdown(wait=True)+++def test_unregister_clears_only_in_memory_serving_artifact_registration(tmp_path: Path) -> None:+ cpu_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cpu")+ preprocessor_registry = PreprocessorRegistry()+ postprocessor_registry = PostprocessorRegistry(cpu_pool)+ loader = ModelLoader(+ preprocessor_registry=preprocessor_registry,+ postprocessor_registry=postprocessor_registry,+ all_configs={},+ )+ artifact_root = tmp_path / "materialized" / ("c" * 64)+ artifact_root.mkdir(parents=True)+ loader._verified_serving_artifacts["google/source-model"] = MagicMock(root=artifact_root)++ try:+ loader.unregister("google/source-model", "cpu")++ assert "google/source-model" not in loader._verified_serving_artifacts+ assert artifact_root.is_dir()+ finally:+ loader._load_executor.shutdown(wait=True)+ cpu_pool.shutdown(wait=True)+++def test_offline_cache_only_derived_snapshot_materializes_without_hub_fallback(tmp_path: Path) -> None:+ source_revision = "a" * 40+ derived_revision = "b" * 40+ hub = tmp_path / "hub"+ snapshot = hub / "models--superlinked--derived-model" / "snapshots" / derived_revision+ snapshot.mkdir(parents=True)+ files = {+ "config.json": (b'{"model_type":"Transformer"}\n', "model.config"),+ "model.bin": (b"converted", "model.weights"),+ "tokenizer_config.json": (b'{"tokenizer_class":"T5Tokenizer"}\n', "tokenizer.config"),+ "spiece.model": (b"sentencepiece", "tokenizer.sentencepiece"),+ }+ artifacts = []+ for relative, (content, role) in files.items():+ (snapshot / relative).write_bytes(content)+ artifacts.append(+ {+ "path": relative,+ "role": role,+ "size_bytes": len(content),+ "sha256": hashlib.sha256(content).hexdigest(),+ }+ )+ manifest = ServingArtifactManifest.model_validate(+ {+ "schema": "sie-ctranslate2-serving-artifact-v1",+ "source": {"hf_id": "google/source-model", "hf_revision": source_revision},+ "converter": {+ "name": "ct2-transformers-converter",+ "version": "4.8.1",+ "torch_version": "2.9.1",+ "transformers_version": "4.57.6",+ "compute_type": "bfloat16",+ "recipe_sha256": "c" * 64,+ },+ "runtime": {"minimum_version": "4.8.1", "maximum_version": "4.8.1"},+ "tokenizer": {+ "class_name": "T5Tokenizer",+ "config_sha256": hashlib.sha256(files["tokenizer_config.json"][0]).hexdigest(),+ "files": [+ {"path": "spiece.model", "role": "tokenizer.sentencepiece"},+ {"path": "tokenizer_config.json", "role": "tokenizer.config"},+ ],+ },+ "artifacts": artifacts,+ }+ )+ manifest_bytes = canonical_manifest_bytes(manifest)+ (snapshot / "sie-serving-artifact.json").write_bytes(manifest_bytes)+ manifest_sha256 = hashlib.sha256(manifest_bytes).hexdigest()+ config = ModelConfig(+ sie_id="google/source-model",+ hf_id="google/source-model",+ hf_revision=source_revision,+ tasks=Tasks(),+ profiles={+ "default": ProfileConfig(+ adapter_path="mod:Cls",+ max_batch_tokens=128,+ adapter_options=AdapterOptions(+ loadtime={+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "superlinked/derived-model",+ "revision": derived_revision,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": manifest_sha256,+ "compute_type": "bfloat16",+ }+ }+ ),+ )+ },+ )+ cpu_pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="test-cpu")+ loader = ModelLoader(+ preprocessor_registry=PreprocessorRegistry(),+ postprocessor_registry=PostprocessorRegistry(cpu_pool),+ all_configs={},+ )++ try:+ with (+ patch(+ "sie_sdk.cache.get_cache_config",+ return_value=CacheConfig(local_cache=hub, cluster_cache=None, hf_fallback=False),+ ),+ patch("huggingface_hub.snapshot_download") as hub_download,+ ):+ loader.ensure_weights_cached(config)++ hub_download.assert_not_called()+ verified = loader._verified_serving_artifacts[config.sie_id]+ assert verified.root == hub / "sie-serving-artifacts-v1" / manifest_sha256+ assert (verified.root / "model.bin").read_bytes() == b"converted"+ finally:+ loader._load_executor.shutdown(wait=True)+ cpu_pool.shutdown(wait=True)diff --git a/packages/sie_server/tests/core/test_registry_generation_drain.py b/packages/sie_server/tests/core/test_registry_generation_drain.pynew file mode 100644index 000000000..021829b6e--- /dev/null+++ b/packages/sie_server/tests/core/test_registry_generation_drain.py@@ -0,0 +1,302 @@+from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from typing import Any+from unittest.mock import MagicMock, patch++import pytest+import sie_server.core.registry as registry_module+from sie_server.adapters._generation_base import GenerationAdapter, GenerationChunk+from sie_server.adapters._spec import AdapterSpec+from sie_server.config.model import ModelConfig+from sie_server.core.model_loader import LoadedModel+++class _DrainAdapter(GenerationAdapter):+ spec = AdapterSpec(inputs=("text",), outputs=("tokens",), unload_fields=())++ def __init__(self, events: list[str], *, block_drain: bool = False) -> None:+ self.events = events+ self.block_drain = block_drain+ self._device = "cpu"++ def load(self, device: str) -> None:+ self._device = device++ async def drain_generation(self) -> None:+ self.events.append("drain")+ if self.block_drain:+ await asyncio.Event().wait()++ def unload(self) -> None:+ self.events.append("unload")++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ **kwargs: Any,+ ) -> AsyncIterator[GenerationChunk]:+ _ = (prompt, max_new_tokens, kwargs)+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop")+++def _config() -> ModelConfig:+ return ModelConfig.model_validate(+ {+ "sie_id": "test/generator",+ "hf_id": "test/generator",+ "inputs": {"text": True},+ "tasks": {"generate": {"context_length": 1024, "max_output_tokens": 128}},+ "profiles": {+ "default": {+ "adapter_path": "tests.fake:Adapter",+ "max_batch_tokens": 1024,+ "kv_budget_tokens": 1024,+ }+ },+ }+ )+++def _registry(+ adapter: GenerationAdapter,+ *,+ drain_timeout_s: float = 1.0,+) -> registry_module.ModelRegistry:+ registry = registry_module.ModelRegistry(drain_timeout_s=drain_timeout_s)+ config = _config()+ registry.add_config(config)+ registry._loaded[config.name] = LoadedModel(config=config, adapter=adapter, device="cpu")+ registry._loader.unregister = MagicMock()+ return registry+++async def test_generation_drain_precedes_removal_and_sync_unload() -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events)+ registry = _registry(adapter)++ async def drain_with_visibility_check() -> None:+ assert registry.is_loaded("test/generator")+ events.append("drain")++ def unload_with_visibility_check() -> None:+ assert not registry.is_loaded("test/generator")+ events.append("unload")++ adapter.drain_generation = drain_with_visibility_check # type: ignore[method-assign]+ adapter.unload = unload_with_visibility_check # type: ignore[method-assign]++ await registry._do_unload("test/generator")++ assert events == ["drain", "unload"]+ assert not registry.is_loaded("test/generator")+++async def test_worker_and_generation_drain_share_one_deadline(monkeypatch: pytest.MonkeyPatch) -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events, block_drain=True)+ registry = _registry(adapter, drain_timeout_s=0.5)+ worker = MagicMock()+ worker.is_running = True++ async def stop_worker() -> None:+ events.append("worker")+ await asyncio.sleep(0.02)++ worker.stop = stop_worker+ registry._loaded["test/generator"].worker = worker++ real_wait_for = asyncio.wait_for+ timeouts: list[float | None] = []++ async def recording_wait_for(awaitable: Any, **kwargs: Any) -> Any:+ timeout_value = kwargs.get("timeout")+ timeouts.append(timeout_value)+ return await real_wait_for(awaitable, **kwargs)++ monkeypatch.setattr(registry_module.asyncio, "wait_for", recording_wait_for)++ await registry._do_unload("test/generator")++ assert events == ["worker", "drain", "unload"]+ assert len(timeouts) == 2+ worker_timeout, generation_timeout = timeouts+ assert worker_timeout is not None+ assert generation_timeout is not None+ assert generation_timeout < worker_timeout - 0.01+++async def test_generation_drain_is_entered_after_worker_exhausts_deadline() -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events, block_drain=True)+ registry = _registry(adapter, drain_timeout_s=0.01)+ worker = MagicMock()+ worker.is_running = True++ async def stop_worker() -> None:+ events.append("worker")+ await asyncio.Event().wait()++ worker.stop = stop_worker+ registry._loaded["test/generator"].worker = worker++ await registry._do_unload("test/generator")++ assert events == ["worker", "drain", "unload"]+ assert not registry.is_loaded("test/generator")+++async def test_generation_drain_timeout_still_completes_unload() -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events, block_drain=True)+ registry = _registry(adapter, drain_timeout_s=0.01)++ await registry._do_unload("test/generator")++ assert events == ["drain", "unload"]+ assert not registry.is_loaded("test/generator")+++async def test_generation_drain_exception_still_completes_unload() -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events)+ registry = _registry(adapter)++ async def failing_drain() -> None:+ events.append("drain")+ raise RuntimeError("drain failed")++ adapter.drain_generation = failing_drain # type: ignore[method-assign]++ await registry._do_unload("test/generator")++ assert events == ["drain", "unload"]+ assert not registry.is_loaded("test/generator")+++def test_sync_only_generation_unload_requires_async_lifecycle() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))++ with pytest.raises(RuntimeError, match="requires an owning event loop"):+ registry.unload("test/generator", reason="preload_pressure")++ assert registry.is_loaded("test/generator")+ assert events == []+++async def test_foreign_thread_generation_unload_runs_on_owner_loop() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))+ telemetry = MagicMock()+ owner = asyncio.get_running_loop()+ registry._get_load_lock()++ drain_loops: list[asyncio.AbstractEventLoop] = []++ async def drain_on_owner() -> None:+ drain_loops.append(asyncio.get_running_loop())+ events.append("drain")++ registry.get("test/generator").drain_generation = drain_on_owner # type: ignore[method-assign]++ with patch("sie_server.core.registry.worker_telemetry", return_value=telemetry):+ await asyncio.to_thread(registry.unload, "test/generator", reason="preload_pressure")++ assert drain_loops == [owner]+ assert events == ["drain", "unload"]+ telemetry.model_evicted.assert_called_once_with(model="test/generator", reason="preload_pressure")+++async def test_same_loop_sync_unload_rejects_while_foreign_bridge_holds_thread_lock() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))+ registry._get_load_lock()+ drain_started = asyncio.Event()+ release_drain = asyncio.Event()++ async def blocking_drain() -> None:+ events.append("drain")+ drain_started.set()+ await release_drain.wait()++ registry.get("test/generator").drain_generation = blocking_drain # type: ignore[method-assign]+ foreign_unload = asyncio.create_task(asyncio.to_thread(registry.unload, "test/generator"))+ await asyncio.wait_for(drain_started.wait(), timeout=1.0)++ with pytest.raises(RuntimeError, match="await unload_async"):+ registry.unload("test/generator")++ release_drain.set()+ await asyncio.wait_for(foreign_unload, timeout=2.0)+ assert events == ["drain", "unload"]+++async def test_async_generation_unload_preserves_reason() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))+ telemetry = MagicMock()++ with patch("sie_server.core.registry.worker_telemetry", return_value=telemetry):+ await registry.unload_async("test/generator", reason="config_change")++ assert events == ["drain", "unload"]+ telemetry.model_evicted.assert_called_once_with(model="test/generator", reason="config_change")+++def test_sync_only_generation_unload_all_requires_async_lifecycle() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))++ with pytest.raises(RuntimeError, match="requires an owning event loop"):+ registry.unload_all()++ assert registry.is_loaded("test/generator")+ assert events == []+++async def test_sync_generation_unload_cannot_bypass_drain_inside_event_loop() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))++ with pytest.raises(RuntimeError, match="await unload_async"):+ registry.unload("test/generator")++ assert registry.is_loaded("test/generator")+ assert events == []+++async def test_repeated_generation_unload_is_idempotent() -> None:+ events: list[str] = []+ registry = _registry(_DrainAdapter(events))++ await registry._do_unload("test/generator")+ await registry._do_unload("test/generator")++ assert events == ["drain", "unload"]+++async def test_default_generation_drain_hook_is_noop() -> None:+ events: list[str] = []+ adapter = _DrainAdapter(events)+ adapter.drain_generation = GenerationAdapter.drain_generation.__get__(adapter) # type: ignore[method-assign]+ registry = _registry(adapter)++ await registry._do_unload("test/generator")++ assert events == ["unload"]diff --git a/packages/sie_server/tests/core/test_registry_lifecycle_loop.py b/packages/sie_server/tests/core/test_registry_lifecycle_loop.pynew file mode 100644index 000000000..f57db985b--- /dev/null+++ b/packages/sie_server/tests/core/test_registry_lifecycle_loop.py@@ -0,0 +1,180 @@+from __future__ import annotations++import asyncio+import threading+from collections.abc import Iterator+from concurrent.futures import ThreadPoolExecutor+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.registry import ModelRegistry+++def _config(name: str) -> ModelConfig:+ return ModelConfig(+ sie_id=name,+ hf_id=f"org/{name}",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ },+ )+++def _adapter() -> MagicMock:+ adapter = MagicMock()+ adapter.capabilities.outputs = ["dense"]+ adapter.load_required_memory_bytes.return_value = None+ adapter.memory_footprint.return_value = 1000+ adapter.requires_main_thread = False+ del adapter.aclose_client+ return adapter++[email protected](autouse=True)+def _cached_weights() -> Iterator[MagicMock]:+ with patch("sie_sdk.cache.ensure_model_cached", return_value=Path("/fake/cache/model")) as mocked:+ yield mocked+++async def test_foreign_thread_sync_load_eviction_and_unload_all_use_owner_loop() -> None:+ registry = ModelRegistry()+ for name in ("model-a", "model-b"):+ registry.add_config(_config(name))++ adapter_a = _adapter()+ adapter_b = _adapter()+ owner = asyncio.get_running_loop()+ unload_loops: list[asyncio.AbstractEventLoop] = []+ original_do_unload = registry._do_unload++ async def record_unload_loop(name: str, *, reason: str = "other") -> None:+ unload_loops.append(asyncio.get_running_loop())+ await original_do_unload(name, reason=reason)++ registry._do_unload = record_unload_loop # type: ignore[method-assign]++ with patch("sie_server.core.model_loader.load_adapter", side_effect=[adapter_a, adapter_b]):+ with patch.object(registry._memory_manager, "should_evict_for_load", return_value=False):+ await registry.load_async("model-a", "cpu")++ with patch.object(registry._memory_manager, "should_evict_for_load", side_effect=[True, False]):+ loaded = await asyncio.to_thread(registry.load, "model-b", "cpu")++ assert loaded is adapter_b+ assert not registry.is_loaded("model-a")+ assert registry.is_loaded("model-b")+ assert unload_loops == [owner]++ await asyncio.to_thread(registry.unload_all)++ assert registry.loaded_model_names == []+ assert unload_loops == [owner, owner]+ adapter_a.unload.assert_called_once()+ adapter_b.unload.assert_called_once()+++async def test_async_lifecycle_rejects_a_second_event_loop() -> None:+ registry = ModelRegistry()+ registry._get_load_lock()++ def use_another_loop() -> str:+ try:+ asyncio.run(registry.unload_all_async())+ except RuntimeError as exc:+ return str(exc)+ raise AssertionError("second event loop unexpectedly entered the registry lifecycle")++ message = await asyncio.to_thread(use_another_loop)++ assert message == "model lifecycle is bound to a different event loop"+++def test_sync_only_load_and_unload_share_thread_safe_boundary() -> None:+ registry = ModelRegistry()+ registry.add_config(_config("model"))+ adapter = _adapter()+ load_started = threading.Event()+ release_load = threading.Event()+ unload_attempted = threading.Event()+ unload_entered = threading.Event()+ original_unload_sync = registry._unload_sync++ def blocking_load(_device: str) -> None:+ load_started.set()+ assert release_load.wait(timeout=2.0)++ def record_unload(name: str, *, reason: str) -> None:+ unload_entered.set()+ original_unload_sync(name, reason=reason)++ def unload_from_thread() -> None:+ unload_attempted.set()+ registry.unload("model")++ adapter.load.side_effect = blocking_load+ registry._unload_sync = record_unload # type: ignore[method-assign]++ with (+ patch("sie_server.core.model_loader.load_adapter", return_value=adapter),+ ThreadPoolExecutor(max_workers=2) as executor,+ ):+ load_future = executor.submit(registry.load, "model", "cpu")+ assert load_started.wait(timeout=2.0)+ unload_future = executor.submit(unload_from_thread)+ assert unload_attempted.wait(timeout=2.0)+ assert not unload_entered.is_set()++ release_load.set()+ assert load_future.result(timeout=2.0) is adapter+ unload_future.result(timeout=2.0)++ assert unload_entered.is_set()+ assert not registry.is_loaded("model")+ adapter.unload.assert_called_once()+++def test_nested_sync_lifecycle_cannot_expose_outer_load_to_async_binding() -> None:+ registry = ModelRegistry()+ registry.add_config(_config("model"))+ adapter = _adapter()+ nested_returned = threading.Event()+ release_outer_load = threading.Event()++ def reentrant_load(_device: str) -> None:+ assert registry._sync_lifecycle_depth == 1+ registry.unload_all()+ assert registry._sync_lifecycle_depth == 1+ nested_returned.set()+ assert release_outer_load.wait(timeout=2.0)++ adapter.load.side_effect = reentrant_load++ with (+ patch("sie_server.core.model_loader.load_adapter", return_value=adapter),+ ThreadPoolExecutor(max_workers=1) as executor,+ ):+ outer_load = executor.submit(registry.load, "model", "cpu")+ assert nested_returned.wait(timeout=2.0)++ with pytest.raises(RuntimeError, match="synchronous model lifecycle operation is already in progress"):+ asyncio.run(registry.unload_all_async())++ assert registry._lifecycle_loop is None+ assert registry._sync_lifecycle_depth == 1+ release_outer_load.set()+ assert outer_load.result(timeout=2.0) is adapter++ assert registry._sync_lifecycle_depth == 0+ assert registry._lifecycle_loop is None+ assert registry.loaded_model_names == ["model"]++ registry.unload("model")+ assert registry.loaded_model_names == []diff --git a/packages/sie_server/tests/core/test_registry_memory.py b/packages/sie_server/tests/core/test_registry_memory.pyindex 163de0c02..0d37c1c9f 100644--- a/packages/sie_server/tests/core/test_registry_memory.py+++ b/packages/sie_server/tests/core/test_registry_memory.py@@ -365,6 +365,92 @@ class TestRegistryPinnedModels:registry.add_config(_make_config(name="Org/Model", hf_id="org/model-hf"))assert registry._pinned_disk_repo_ids() == {"org/model-hf"}+ def test_pinned_disk_repo_ids_protects_all_expanded_derived_repos_with_dedup(self) -> None:+ """Inherited duplicates collapse while a distinct effective artifact is also protected."""+ registry = ModelRegistry(pinned_models=["Org/Model:alternate"])+ config = ModelConfig.model_validate(+ {+ "sie_id": "Org/Model",+ "hf_id": "org/source-hf",+ "hf_revision": "a" * 40,+ "tasks": {"encode": {"dense": {"dim": 3}}},+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.sentence_transformer:Adapter",+ "max_batch_tokens": 128,+ "adapter_options": {+ "loadtime": {+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "derived/shared",+ "revision": "b" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ },+ },+ "inherited": {"extends": "default"},+ "alternate": {+ "extends": "default",+ "adapter_options": {+ "loadtime": {+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "derived/alternate",+ "revision": "d" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "e" * 64,+ "compute_type": "int8_bfloat16",+ }+ }+ },+ },+ },+ }+ )++ registry.add_config(config)++ assert registry._pinned_disk_repo_ids() == {"derived/shared", "derived/alternate"}++ def test_pinned_disk_repo_ids_protects_source_and_derived_for_mixed_profiles(self) -> None:+ registry = ModelRegistry(pinned_models=["Org/Mixed"])+ config = ModelConfig.model_validate(+ {+ "sie_id": "Org/Mixed",+ "hf_id": "org/source-hf",+ "hf_revision": "a" * 40,+ "tasks": {"encode": {"dense": {"dim": 3}}},+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.sentence_transformer:Adapter",+ "max_batch_tokens": 128,+ },+ "derived": {+ "extends": "default",+ "adapter_options": {+ "loadtime": {+ "serving_artifact": {+ "format": "ctranslate2",+ "repo_id": "derived/mixed",+ "revision": "b" * 40,+ "manifest_path": "sie-serving-artifact.json",+ "manifest_sha256": "c" * 64,+ "compute_type": "bfloat16",+ }+ }+ },+ },+ },+ }+ )++ registry.add_config(config)++ assert registry._pinned_disk_repo_ids() == {"org/source-hf", "derived/mixed"}+def test_disk_cache_manager_wired_with_pinned_provider(self) -> None:"""The registry feeds its pinned set into the disk cache manager's eviction guard."""registry = ModelRegistry(pinned_models=["org/pinned"])diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.pyindex 8dc1b7c91..cad1b9743 100644--- a/packages/sie_server/tests/processors/test_streaming.py+++ b/packages/sie_server/tests/processors/test_streaming.py@@ -17,7 +17,7 @@ import asyncioimport base64import threadingimport time-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mappingfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -25,14 +25,20 @@ import msgpackimport pytestfrom sie_server.adapters._generation_base import (GenerationAdapter,+ GenerationCapacityError,GenerationChunk,+ GenerationError,+ GenerationInputTooLongError,+ GenerationUnsupportedFieldError,)from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.base import ModelCapabilities, ModelDims+from sie_server.config.engine import EngineConfigfrom sie_server.config.model import ModelConfigfrom sie_server.observability import worker_telemetry as worker_metricsfrom sie_server.processors import streaming as streaming_modfrom sie_server.processors.streaming import StreamingProcessor, _ValidationError+from sie_server.types.grammar import GrammarSpec_GEMMA_OPEN = "<" + "|channel" + ">" + "thought\n"_GEMMA_CLOSE = "<" + "channel|" + ">"@@ -47,6 +53,7 @@ class _FakeGenAdapter(GenerationAdapter):self._device = Noneself._script = scriptself._hold = hold_event+ self.close_calls = 0def load(self, device: str) -> None: # pragma: no cover — registry-mockedself._device = device@@ -70,11 +77,47 @@ class _FakeGenAdapter(GenerationAdapter):**kwargs: Any,) -> AsyncIterator[GenerationChunk]:_ = (prompt, max_new_tokens, temperature, top_p, stop, kwargs)- for chunk in self._script:- if self._hold is not None:- # Block here until externally released — used for cancel test.- await self._hold.wait()- yield chunk+ try:+ for chunk in self._script:+ if self._hold is not None:+ # Block here until externally released — used for cancel test.+ await self._hold.wait()+ yield chunk+ finally:+ self.close_calls += 1+++class _IndependentContextGenAdapter(_FakeGenAdapter):+ context_length_accounting = "independent"+++class _PreflightGenAdapter(_FakeGenAdapter):+ def __init__(self, error: Exception | None = None, *, raise_during_generate: bool = False) -> None:+ super().__init__([GenerationChunk(text_delta="", done=True, finish_reason="stop")])+ self.error = error+ self.raise_during_generate = raise_during_generate+ self.preflight_parameters: dict[str, Any] | None = None+ self.preflight_stream: bool | None = None+ self.dispatched_parameters: dict[str, Any] | None = None++ def preflight_generate(self, parameters: Mapping[str, Any], *, stream: bool) -> None:+ self.preflight_parameters = dict(parameters)+ self.preflight_stream = stream+ if self.error is not None and not self.raise_during_generate:+ raise self.error++ async def generate(self, prompt: str, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ self.dispatched_parameters = {"prompt": prompt, **kwargs}+ try:+ if self.error is not None and self.raise_during_generate:+ raise self.error+ yield GenerationChunk(text_delta="", done=True, finish_reason="stop")+ finally:+ self.close_calls += 1+++class _FutureUnsupportedFieldError(GenerationUnsupportedFieldError):+ passdef _make_work_item(@@ -113,13 +156,19 @@ def _make_work_item(return wi-def _make_generation_config(*, min_new_tokens: int = 10) -> ModelConfig:+def _make_generation_config(*, min_new_tokens: int = 10, streaming: bool = True) -> ModelConfig:return ModelConfig.model_validate({"sie_id": "test/model","hf_id": "test/model","inputs": {"text": True},- "tasks": {"generate": {"context_length": 4096, "max_output_tokens": 512}},+ "tasks": {+ "generate": {+ "context_length": 4096,+ "max_output_tokens": 512,+ "capabilities": {"streaming": streaming},+ }+ },"max_sequence_length": 4096,"profiles": {"default": {@@ -235,6 +284,7 @@ async def test_streaming_publishes_per_chunk_with_terminal(monkeypatch: pytest.Massert seqs == sorted(seqs)# ACK happened.msg.ack.assert_awaited()+ assert adapter.close_calls == 1_assert_one_generation_completion(telemetry, outcome="success")# Worker-side phase boundary (#3136): one worker-wait observation per# dispatched request, labeled with the grammar mode ("none" here) so the@@ -246,6 +296,342 @@ async def test_streaming_publishes_per_chunk_with_terminal(monkeypatch: pytest.Massert wait_kwargs["duration_s"] >= 0+async def test_adapter_preflight_matches_dispatch_and_precedes_admission(monkeypatch: pytest.MonkeyPatch) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter()+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ original_reserve = proc._try_reserve++ async def reserve_after_preflight(*args: Any, **kwargs: Any) -> bool:+ assert adapter.preflight_parameters is not None+ return await original_reserve(*args, **kwargs)++ monkeypatch.setattr(proc, "_try_reserve", reserve_after_preflight)++ await proc.process(_make_msg(_make_work_item()), "test/model")++ assert adapter.preflight_parameters == adapter.dispatched_parameters+ assert adapter.preflight_stream is False+++ ("error", "expected_error"),+ [+ (+ GenerationUnsupportedFieldError("top_k"),+ {+ "code": "unsupported_field",+ "message": "'top_k' is not supported by this generation backend",+ "param": "top_k",+ },+ ),+ (+ GenerationUnsupportedFieldError("n", "TensorRT-LLM completions support n=1 only"),+ {+ "code": "unsupported_field",+ "message": "TensorRT-LLM completions support n=1 only",+ "param": "n",+ },+ ),+ (+ GenerationUnsupportedFieldError("best_of", "TensorRT-LLM completions support best_of=1 only"),+ {+ "code": "unsupported_field",+ "message": "TensorRT-LLM completions support best_of=1 only",+ "param": "best_of",+ },+ ),+ (+ GenerationUnsupportedFieldError(+ "lora_path",+ "'lora_adapter' is not supported by this generation backend",+ ),+ {+ "code": "unsupported_field",+ "message": "'lora_adapter' is not supported by this generation backend",+ "param": "lora_adapter",+ },+ ),+ ],+)+async def test_adapter_preflight_refusal_preserves_code_param_and_skips_admission(+ monkeypatch: pytest.MonkeyPatch,+ error: GenerationUnsupportedFieldError,+ expected_error: dict[str, str],+) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(error)+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ reserve = AsyncMock(return_value=True)+ monkeypatch.setattr(proc, "_try_reserve", reserve)+ msg = _make_msg(_make_work_item())++ await proc.process(msg, "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == expected_error+ assert terminal["error"].get("param") != "lora_path"+ assert "lora_path" not in str(terminal["error"])+ reserve.assert_not_awaited()+ assert adapter.dispatched_parameters is None+ msg.ack.assert_awaited_once()++[email protected]("raise_during_generate", [False, True])+async def test_future_refusal_subclass_param_is_sanitized_on_worker_wire(+ monkeypatch: pytest.MonkeyPatch,+ raise_during_generate: bool,+) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(+ _FutureUnsupportedFieldError("n", "future refusal"),+ raise_during_generate=raise_during_generate,+ )+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ assert _decode_chunks(nc)[-1]["error"] == {+ "code": "unsupported_field",+ "message": "future refusal",+ }+++async def test_input_too_long_preflight_preserves_code_param_and_skips_admission(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(GenerationInputTooLongError("prompt token count (129) exceeds max_input_len (128)"))+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ reserve = AsyncMock(return_value=True)+ monkeypatch.setattr(proc, "_try_reserve", reserve)+ msg = _make_msg(_make_work_item())++ await proc.process(msg, "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {+ "code": "INPUT_TOO_LONG",+ "message": "prompt token count (129) exceeds max_input_len (128)",+ "param": "prompt",+ }+ reserve.assert_not_awaited()+ assert adapter.dispatched_parameters is None+ msg.ack.assert_awaited_once()+++async def test_typed_capacity_raised_by_iterator_keeps_retryable_code(monkeypatch: pytest.MonkeyPatch) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(GenerationCapacityError("scheduler full"), raise_during_generate=True)+ registry = _make_registry(adapter)+ registry.engine_config = EngineConfig.model_validate({"oom_recovery": {"retry_after_s": 12}})+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"]["code"] == "RESOURCE_EXHAUSTED"+ assert terminal["error"]["message"] == "scheduler full"+ assert terminal["error"]["retry_after_s"] == 12+ assert adapter.close_calls == 1++[email protected]("raise_during_generate", [False, True])+async def test_generic_typed_generation_error_is_sanitized_on_worker_wire(+ monkeypatch: pytest.MonkeyPatch,+ raise_during_generate: bool,+) -> None:+ sentinel = "SENSITIVE_TYPED_WORKER_ERROR"+ nc = AsyncMock()+ error = GenerationError(sentinel)+ error.param = sentinel+ adapter = _PreflightGenAdapter(+ error,+ raise_during_generate=raise_during_generate,+ )+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {+ "code": "inference_error",+ "message": "internal error during generation",+ }+ assert sentinel not in str(terminal)+++async def test_typed_capacity_preflight_keeps_configured_retry_hint_and_skips_admission(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(GenerationCapacityError("scheduler full"))+ registry = _make_registry(adapter)+ registry.engine_config = EngineConfig.model_validate({"oom_recovery": {"retry_after_s": 12}})+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ reserve = AsyncMock(return_value=True)+ monkeypatch.setattr(proc, "_try_reserve", reserve)++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {+ "code": "RESOURCE_EXHAUSTED",+ "message": "scheduler full",+ "retry_after_s": 12,+ }+ reserve.assert_not_awaited()+ assert adapter.dispatched_parameters is None+++async def test_unexpected_preflight_error_is_sanitized_on_worker_wire(monkeypatch: pytest.MonkeyPatch) -> None:+ sentinel = "SENSITIVE_PREFLIGHT_SENTINEL"+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(RuntimeError(sentinel))+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {+ "code": "inference_error",+ "message": "internal error during generation preflight",+ }+ assert sentinel not in str(terminal)+ assert adapter.close_calls == 0+++async def test_unexpected_iterator_error_is_sanitized_on_worker_wire(monkeypatch: pytest.MonkeyPatch) -> None:+ sentinel = "SENSITIVE_ITERATOR_SENTINEL"+ nc = AsyncMock()+ adapter = _PreflightGenAdapter(RuntimeError(sentinel), raise_during_generate=True)+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {+ "code": "inference_error",+ "message": "internal error during generation",+ }+ assert sentinel not in str(terminal)+ assert adapter.close_calls == 1+++ ("code", "message", "expected_code", "expected_message"),+ [+ (+ "inference_error",+ "SENSITIVE_YIELDED_RUNTIME",+ "inference_error",+ "internal error during generation",+ ),+ (+ "grammar_compile_failed",+ "SENSITIVE_YIELDED_GRAMMAR",+ "grammar_compile_failed",+ "internal error compiling grammar",+ ),+ (+ "grammar_invalid",+ "invalid grammar at byte 4",+ "grammar_invalid",+ "invalid grammar at byte 4",+ ),+ (+ "SENSITIVE_WORKER_WIRE_ERROR_CODE",+ "SENSITIVE_WORKER_WIRE_ERROR_CODE",+ "inference_error",+ "generation terminated with an upstream error",+ ),+ ],+)+async def test_adapter_yielded_terminal_error_is_sanitized_before_worker_wire(+ monkeypatch: pytest.MonkeyPatch,+ code: str,+ message: str,+ expected_code: str,+ expected_message: str,+) -> None:+ nc = AsyncMock()+ adapter = _FakeGenAdapter(+ [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="error",+ error_code=code,+ error_message=message,+ )+ ]+ )+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))++ await proc.process(_make_msg(_make_work_item()), "test/model")++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"] == {"code": expected_code, "message": expected_message}+ if message.startswith("SENSITIVE_"):+ assert message not in str(terminal)+++async def test_non_streaming_capability_rejects_stream_before_preflight() -> None:+ nc = AsyncMock()+ adapter = _PreflightGenAdapter()+ registry = _make_registry(adapter)+ registry.get_config.return_value = _make_generation_config(streaming=False)+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")++ await proc.process(+ _make_msg(_make_work_item(generate={"prompt": "Hello", "max_new_tokens": 64, "stream": True})),+ "test/model",+ )++ terminal = _decode_chunks(nc)[-1]+ assert terminal["error"]["code"] == "unsupported_field"+ assert terminal["error"]["param"] == "stream"+ assert adapter.preflight_parameters is None+ assert adapter.dispatched_parameters is None++@pytest.mark.asyncioasync def test_coalescing_keeps_message_count_bounded() -> None:"""100 tiny yields should coalesce into ≤ N chunks (≤32 chars/flush)."""@@ -311,10 +697,13 @@ async def test_cancel_event_emits_cancelled_terminal(monkeypatch: pytest.MonkeyPclass _AdapterFirstFree(_FakeGenAdapter):async def generate(self, prompt, *, max_new_tokens, temperature=1.0, top_p=1.0, stop=None):- for i, chunk in enumerate(self._script):- if i > 0 and self._hold is not None:- await self._hold.wait()- yield chunk+ try:+ for i, chunk in enumerate(self._script):+ if i > 0 and self._hold is not None:+ await self._hold.wait()+ yield chunk+ finally:+ self.close_calls += 1adapter = _AdapterFirstFree(script, hold_event=hold)proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")@@ -338,9 +727,115 @@ async def test_cancel_event_emits_cancelled_terminal(monkeypatch: pytest.MonkeyPassert terminal["done"] is Trueassert terminal["finish_reason"] == "cancelled"msg.ack.assert_awaited()+ assert adapter.close_calls == 1_assert_one_generation_completion(telemetry, outcome="cancelled")+async def test_outer_task_cancellation_drains_children_and_closes_iterator_once() -> None:+ nc = AsyncMock()+ started = asyncio.Event()++ class _BlockingAdapter(_FakeGenAdapter):+ async def generate(self, *args: Any, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ _ = (args, kwargs)+ try:+ started.set()+ await asyncio.Event().wait()+ yield GenerationChunk(text_delta="unreachable") # pragma: no cover+ finally:+ self.close_calls += 1++ adapter = _BlockingAdapter([])+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")+ task = asyncio.create_task(proc.process(_make_msg(_make_work_item()), "test/model"))+ await asyncio.wait_for(started.wait(), timeout=1.0)++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, timeout=3.0)++ assert adapter.close_calls == 1+++async def test_iterator_close_failure_waits_for_heartbeat_and_publisher_teardown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _EmptyFailingCloseIterator:+ def __init__(self) -> None:+ self.close_calls = 0++ def __aiter__(self) -> _EmptyFailingCloseIterator:+ return self++ async def __anext__(self) -> GenerationChunk:+ raise StopAsyncIteration++ async def aclose(self) -> None:+ self.close_calls += 1+ raise RuntimeError("iterator close failed")++ class _CloseFailureAdapter(_FakeGenAdapter):+ def __init__(self, source: _EmptyFailingCloseIterator) -> None:+ super().__init__([])+ self.source = source++ def generate(self, *args: Any, **kwargs: Any) -> AsyncIterator[GenerationChunk]:+ _ = (args, kwargs)+ return self.source++ heartbeat_stopped = asyncio.Event()+ publisher_stopped = asyncio.Event()++ async def _tracking_heartbeat(_self: Any, _msg: Any, stop: asyncio.Event) -> None:+ try:+ await stop.wait()+ finally:+ heartbeat_stopped.set()++ async def _tracking_publisher(+ _self: Any,+ chunk_queue: asyncio.Queue[tuple[bytes, bool] | None],+ _reply_subject: str,+ ) -> bool:+ while await chunk_queue.get() is not None:+ pass+ publisher_stopped.set()+ return False++ real_wait_for = streaming_mod._wait_for+ failed_terminal_put = False++ async def _fail_terminal_put_once(awaitable: Any, **options: float) -> Any:+ nonlocal failed_terminal_put+ if not failed_terminal_put:+ failed_terminal_put = True+ awaitable.close()+ raise TimeoutError+ return await real_wait_for(awaitable, timeout=options["timeout"])++ monkeypatch.setattr(StreamingProcessor, "_heartbeat_loop", _tracking_heartbeat)+ monkeypatch.setattr(StreamingProcessor, "_publisher_loop", _tracking_publisher)+ monkeypatch.setattr(streaming_mod, "_wait_for", _fail_terminal_put_once)++ source = _EmptyFailingCloseIterator()+ proc = StreamingProcessor(+ nc=AsyncMock(),+ registry=_make_registry(_CloseFailureAdapter(source)),+ worker_id="w1",+ )+ msg = _make_msg(_make_work_item())++ with pytest.raises(RuntimeError, match="iterator close failed"):+ await proc.process(msg, "test/model")++ assert source.close_calls == 1+ assert heartbeat_stopped.is_set()+ assert publisher_stopped.is_set()+ msg.ack.assert_not_awaited()++@pytest.mark.asyncioasync def test_full_queue_at_finally_never_drops_terminal_chunk(monkeypatch) -> None:"""Fix #1 regression: when the chunk queue is full as the producer@@ -542,6 +1037,7 @@ def _make_registry_with_chat_config(*,chat_template_kwargs: dict[str, Any] | None = None,context_length: int = 32768,+ max_output_tokens: int = 512,hf_id: str = "test/model",hf_revision: str | None = None,reasoning_parser: str | None = None,@@ -561,6 +1057,7 @@ def _make_registry_with_chat_config(config.weights_path = Noneconfig.tasks.generate.chat_template_kwargs = chat_template_kwargs or {}config.tasks.generate.context_length = context_length+ config.tasks.generate.max_output_tokens = max_output_tokensprofile = MagicMock()profile.loadtime = {"reasoning_parser": reasoning_parser} if reasoning_parser is not None else {}config.resolve_profile.return_value = profile@@ -619,6 +1116,7 @@ async def test_streaming_processor_hides_reasoning_for_every_resolved_profile(decoded = _decode_chunks(nc)visible = "".join(chunk.get("text_delta", "") for chunk in decoded)assert visible == "Visible answer"+ assert adapter.close_calls == 1@pytest.mark.asyncio@@ -728,14 +1226,15 @@ async def test_streaming_processor_pins_tokenizer_revision(monkeypatch) -> None:@pytest.mark.asyncioasync def test_streaming_processor_chat_template_render_error_becomes_terminal_chunk(monkeypatch) -> None:- """A tokenizer that raises mid-render → terminal ``invalid_request``."""+ """A tokenizer that raises mid-render never discloses backend details."""+ sentinel = "SENSITIVE_TEMPLATE_RENDER_SENTINEL"nc = AsyncMock()adapter = _FakeGenAdapter([])registry = _make_registry_with_chat_config(adapter)class _BrokenTok:def apply_chat_template(self, *a, **kw):- raise ValueError("template not found")+ raise ValueError(sentinel)def encode(self, text, *, add_special_tokens): # pragma: no coverreturn []@@ -754,10 +1253,39 @@ async def test_streaming_processor_chat_template_render_error_becomes_terminal_cterminal = decoded[-1]assert terminal["done"] is Trueassert terminal["error"]["code"] == "invalid_request"- assert "chat template render failed" in terminal["error"]["message"]+ assert terminal["error"]["message"] == "failed to render the model-native message prompt"+ assert sentinel not in str(terminal)msg.ack.assert_awaited()+async def test_streaming_processor_tokenizer_load_error_never_discloses_backend_details(monkeypatch) -> None:+ sentinel = "SENSITIVE_TOKENIZER_LOAD_SENTINEL"+ nc = AsyncMock()+ adapter = _FakeGenAdapter([])+ registry = _make_registry_with_chat_config(adapter)++ def _raise_tokenizer_error(*args: Any, **kwargs: Any) -> Any:+ _ = (args, kwargs)+ raise RuntimeError(sentinel)++ monkeypatch.setattr(streaming_mod, "load_tokenizer", _raise_tokenizer_error)++ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ wi = _make_work_item(messages=[{"role": "user", "content": "hi"}])+ msg = _make_msg(wi)+ await proc.process(msg, "test/model")++ [terminal] = _decode_chunks(nc)+ assert terminal["done"] is True+ assert terminal["error"] == {+ "code": "invalid_request",+ "message": "failed to render the model-native message prompt",+ }+ assert sentinel not in str(terminal)+ msg.ack.assert_awaited_once()++@pytest.mark.asyncioasync def test_streaming_processor_rejects_invalid_role() -> None:"""A messages entry with an unsupported role is rejected pre-template."""@@ -859,6 +1387,187 @@ async def test_streaming_processor_context_exceeded_emits_terminal_chunk(monkeypmsg.ack.assert_awaited()+ "adapter_type",+ [_FakeGenAdapter, _IndependentContextGenAdapter],+ ids=["shared", "independent"],+)[email protected](("max_new_tokens", "should_reject"), [(8, False), (9, True)])+async def test_worker_enforces_resolved_output_cap_before_context_check(+ monkeypatch: pytest.MonkeyPatch,+ adapter_type: type[_FakeGenAdapter],+ max_new_tokens: int,+ should_reject: bool,+) -> None:+ class _StubTok:+ def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:+ assert add_special_tokens is False+ return [0]++ adapter = adapter_type(+ [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ prompt_tokens=1,+ completion_tokens=max_new_tokens,+ )+ ]+ )+ registry = _make_registry_with_chat_config(+ adapter,+ context_length=32,+ max_output_tokens=8,+ )+ nc = AsyncMock()+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ get_tokenizer = AsyncMock(return_value=_StubTok())+ monkeypatch.setattr(proc, "_get_tokenizer", get_tokenizer)++ await proc.process(+ _make_msg(_make_work_item(generate={"prompt": "boundary", "max_new_tokens": max_new_tokens})),+ "test/model",+ )++ terminal = _decode_chunks(nc)[-1]+ if should_reject:+ assert terminal["error"] == {+ "code": "context_exceeded",+ "message": "max_new_tokens (9) exceeds model cap (8)",+ }+ assert adapter.close_calls == 0+ get_tokenizer.assert_not_awaited()+ else:+ assert terminal.get("error") is None+ assert adapter.close_calls == 1+ get_tokenizer.assert_awaited_once()+++async def test_context_guard_matches_adapter_special_token_policy_at_boundary(monkeypatch) -> None:+ class _SpecialTokenAdapter(_FakeGenAdapter):+ prompt_tokenization_add_special_tokens = True++ class _StubTok:+ def __init__(self, tokens_without_specials: int) -> None:+ self.tokens_without_specials = tokens_without_specials+ self.calls: list[bool] = []++ def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:+ self.calls.append(add_special_tokens)+ return list(range(self.tokens_without_specials + int(add_special_tokens)))++ adapter = _SpecialTokenAdapter([])+ registry = _make_registry_with_chat_config(adapter, context_length=512)+ proc = StreamingProcessor(nc=AsyncMock(), registry=registry, worker_id="w1")+ overflow_tokenizer = _StubTok(511)+ equality_tokenizer = _StubTok(510)+ monkeypatch.setattr(+ proc,+ "_get_tokenizer",+ AsyncMock(side_effect=(overflow_tokenizer, equality_tokenizer)),+ )++ error = await proc._check_context_length(+ "test/model",+ "boundary prompt",+ 1,+ adapter=adapter,+ )++ assert error is not None+ assert error.code == "context_exceeded"+ assert "prompt_tokens (512) + max_new_tokens (1) = 513" in error.message+ assert overflow_tokenizer.calls == [True]++ allowed = await proc._check_context_length(+ "test/model",+ "exact boundary prompt",+ 1,+ adapter=adapter,+ )++ assert allowed is None+ assert equality_tokenizer.calls == [True]+++async def test_context_guard_keeps_shared_default_and_allows_independent_output(monkeypatch) -> None:+ class _StubTok:+ def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:+ assert add_special_tokens is False+ return list(range(400))++ shared_adapter = _FakeGenAdapter([])+ independent_adapter = _IndependentContextGenAdapter([])+ registry = _make_registry_with_chat_config(shared_adapter, context_length=512)+ proc = StreamingProcessor(nc=AsyncMock(), registry=registry, worker_id="w1")+ monkeypatch.setattr(proc, "_get_tokenizer", AsyncMock(return_value=_StubTok()))++ shared_error = await proc._check_context_length(+ "test/model",+ "boundary prompt",+ 200,+ adapter=shared_adapter,+ )+ independent_error = await proc._check_context_length(+ "test/model",+ "boundary prompt",+ 200,+ adapter=independent_adapter,+ )++ assert shared_error is not None+ assert shared_error.code == "context_exceeded"+ assert "prompt_tokens (400) + max_new_tokens (200) = 600" in shared_error.message+ assert independent_error is None+++async def test_independent_context_guard_checks_input_axis_with_images(monkeypatch) -> None:+ class _StubTok:+ def __init__(self, token_count: int) -> None:+ self.token_count = token_count++ def encode(self, _text: str, *, add_special_tokens: bool) -> list[int]:+ assert add_special_tokens is False+ return list(range(self.token_count))++ adapter = _IndependentContextGenAdapter([])+ registry = _make_registry_with_chat_config(adapter, context_length=1281)+ proc = StreamingProcessor(nc=AsyncMock(), registry=registry, worker_id="w1")+ monkeypatch.setattr(+ proc,+ "_get_tokenizer",+ AsyncMock(side_effect=(_StubTok(1), _StubTok(2))),+ )++ allowed = await proc._check_context_length(+ "test/model",+ "exact boundary prompt",+ 64,+ adapter=adapter,+ num_images=1,+ )+ error = await proc._check_context_length(+ "test/model",+ "overflow prompt",+ 64,+ adapter=adapter,+ num_images=1,+ )++ assert allowed is None+ assert error is not None+ assert error.code == "context_exceeded"+ assert (+ error.message == "prompt_tokens (2) + ~image_tokens (1280) = 1282 exceeds context_length "+ "(1281) for model 'test/model'"+ )++@pytest.mark.asyncioasync def test_streaming_processor_ignores_routing_key_this_slice() -> None:"""Inert routing-affinity fields don't disturb the happy path."""@@ -1179,6 +1888,97 @@ async def test_grammar_compile_validation_error_surfaces_with_code(msg.ack.assert_awaited()+async def test_unexpected_grammar_compile_error_is_sanitized(monkeypatch: pytest.MonkeyPatch) -> None:+ sentinel = "SENSITIVE_GRAMMAR_COMPILE_SENTINEL"++ def _fail(_tok: Any, _g: Any) -> Any:+ raise RuntimeError(sentinel)++ nc = AsyncMock()+ proc = StreamingProcessor(nc=nc, registry=_make_registry(_FakeGenAdapter([])), worker_id="w1")+ _patch_compile(monkeypatch, _fail)++ msg = _make_msg(+ _make_work_item(+ generate={+ "prompt": "Hi",+ "max_new_tokens": 8,+ "grammar": {"kind": "regex", "value": r"\d+"},+ }+ )+ )+ await proc.process(msg, "test/model")++ terminal = _terminal_chunk(nc)+ assert terminal["error"] == {+ "code": "grammar_compile_failed",+ "message": "internal error compiling grammar",+ }+ assert sentinel not in str(terminal)+++async def test_grammar_tokenizer_load_error_is_sanitized(monkeypatch: pytest.MonkeyPatch) -> None:+ sentinel = "SENSITIVE_TOKENIZER_SENTINEL"+ nc = AsyncMock()+ registry = _make_registry(_FakeGenAdapter([]))+ registry.get_config.side_effect = KeyError("no config")+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")++ async def _fail_tokenizer(_model_id: str) -> Any:+ raise RuntimeError(sentinel)++ monkeypatch.setattr(proc, "_get_tokenizer", _fail_tokenizer)+ result = await proc._ensure_grammar_ready(+ GrammarSpec(kind="regex", value=r"\d+"),+ model_id="test/model",+ reply_subject="_INBOX.test",+ request_id="req-tokenizer",+ attempt_id="att-tokenizer",+ msg=_make_msg(_make_work_item()),+ )++ assert result is False+ terminal = _terminal_chunk(nc)+ assert terminal["error"] == {+ "code": "grammar_compile_failed",+ "message": "internal error compiling grammar",+ }+ assert sentinel not in str(terminal)+++async def test_shared_grammar_compile_error_is_sanitized() -> None:+ sentinel = "SENSITIVE_SHARED_GRAMMAR_SENTINEL"+ nc = AsyncMock()+ registry = _make_registry(_FakeGenAdapter([]))+ registry.get_config.side_effect = KeyError("no config")+ proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")+ grammar = GrammarSpec(kind="regex", value=r"\d+")+ key = ("test/model", streaming_mod.hash_grammar(grammar), "outlines")+ failed = asyncio.get_running_loop().create_future()+ failed.set_exception(RuntimeError(sentinel))+ proc._grammar_inflight[key] = failed++ result = await proc._ensure_grammar_ready(+ grammar,+ model_id="test/model",+ reply_subject="_INBOX.test",+ request_id="req-follower",+ attempt_id="att-follower",+ msg=_make_msg(_make_work_item()),+ )++ assert result is False+ terminal = _terminal_chunk(nc)+ assert terminal["error"] == {+ "code": "grammar_compile_failed",+ "message": "internal error compiling grammar",+ }+ assert sentinel not in str(terminal)++@pytest.mark.asyncioasync def test_grammar_absent_skips_compile(monkeypatch: pytest.MonkeyPatch) -> None:"""Default request path: no grammar → no compile, no metric activity."""@@ -1854,10 +2654,11 @@ _WEATHER_TOOLS = [@pytest.mark.asyncio-async def test_streaming_tool_call_emits_incremental_deltas() -> None:+async def test_streaming_tool_call_emits_incremental_deltas(monkeypatch: pytest.MonkeyPatch) -> None:"""A <tool_call> block in the model output surfaces as well-formedincremental OpenAI ``delta.tool_calls`` (id+name first, args after)."""+ telemetry = _capture_worker_completion(monkeypatch)nc = AsyncMock()script = [GenerationChunk(@@ -1866,11 +2667,15 @@ async def test_streaming_tool_call_emits_incremental_deltas() -> None:),GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=5, completion_tokens=9),]- proc = StreamingProcessor(nc=nc, registry=_make_registry(_FakeGenAdapter(script)), worker_id="w1")+ adapter = _FakeGenAdapter(script)+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")wi = _make_work_item(generate={"prompt": "weather?", "max_new_tokens": 64, "tools": _WEATHER_TOOLS})- await proc.process(_make_msg(wi), "test/model")+ msg = _make_msg(wi)+ await proc.process(msg, "test/model")decoded = _decode_chunks(nc)+ terminals = [chunk for chunk in decoded if chunk.get("done") is True]+ assert len(terminals) == 1tcs = _tool_call_deltas(decoded)assert len(tcs) == 2# Announcement delta: id + function name, empty arguments.@@ -1883,6 +2688,66 @@ async def test_streaming_tool_call_emits_incremental_deltas() -> None:assert tcs[1]["function"]["arguments"] == '{"city":"Tokyo"}'# Terminal reason flips to tool_calls.assert decoded[-1]["finish_reason"] == "tool_calls"+ assert "error" not in decoded[-1]+ msg.ack.assert_awaited_once()+ _assert_one_generation_completion(telemetry, outcome="success")+ assert adapter.close_calls == 1+++ ("finish_reason", "error_code", "error_message", "expected_message"),+ [+ (+ "stop",+ "empty_model_output",+ "model produced no visible output text",+ "model produced no visible output text",+ ),+ ("error", "grammar_invalid", "invalid grammar", "invalid grammar"),+ (+ "error",+ "inference_error",+ "SECRET engine path /models/private",+ "internal error during generation",+ ),+ ],+)+async def test_tools_enabled_queue_preserves_safe_terminal_error_semantics(+ monkeypatch: pytest.MonkeyPatch,+ finish_reason: str,+ error_code: str,+ error_message: str,+ expected_message: str,+) -> None:+ telemetry = _capture_worker_completion(monkeypatch)+ nc = AsyncMock()+ script = [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=finish_reason, # type: ignore[arg-type]+ error_code=error_code,+ error_message=error_message,+ )+ ]+ adapter = _FakeGenAdapter(script)+ proc = StreamingProcessor(nc=nc, registry=_make_registry(adapter), worker_id="w1")+ wi = _make_work_item(generate={"prompt": "weather?", "max_new_tokens": 64, "tools": _WEATHER_TOOLS})+ msg = _make_msg(wi)++ await proc.process(msg, "test/model")++ decoded = _decode_chunks(nc)+ terminals = [chunk for chunk in decoded if chunk.get("done") is True]+ assert len(terminals) == 1+ terminal = terminals[0]+ assert terminal["finish_reason"] == finish_reason+ assert terminal["error"] == {"code": error_code, "message": expected_message}+ assert "SECRET" not in repr(terminal)+ msg.ack.assert_awaited_once()+ _assert_one_generation_completion(telemetry, outcome="error")+ assert adapter.close_calls == 1@pytest.mark.asynciodiff --git a/packages/sie_server/tests/processors/test_tool_call_parser.py b/packages/sie_server/tests/processors/test_tool_call_parser.pyindex 9e930a3c4..2f20ecc9d 100644--- a/packages/sie_server/tests/processors/test_tool_call_parser.py+++ b/packages/sie_server/tests/processors/test_tool_call_parser.py@@ -241,6 +241,61 @@ async def test_parse_tool_call_stream_terminal_propagates_usage_and_tool_calls_rassert terminal.completion_tokens == 13+async def test_parse_tool_call_stream_preserves_terminal_error_metadata() -> None:+ out = [+ item+ async for item in parse_tool_call_stream(+ _chunks(+ [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="error",+ error_code="grammar_invalid",+ error_message="invalid grammar",+ )+ ]+ )+ )+ ]++ terminal = out[-1]+ assert terminal.done is True+ assert terminal.finish_reason == "error"+ assert terminal.error_code == "grammar_invalid"+ assert terminal.error_message == "invalid grammar"+++async def test_parse_tool_call_stream_candidate_rewrite_preserves_terminal_error_metadata() -> None:+ out = [+ item+ async for item in parse_tool_call_stream(+ _chunks(+ [+ GenerationChunk(+ text_delta="",+ done=True,+ finish_reason="stop",+ candidates=({"text": "plain answer", "finish_reason": "stop", "logprobs": None},),+ error_code="empty_model_output",+ error_message="model produced no visible output text",+ )+ ]+ )+ )+ ]++ terminal = out[-1]+ assert terminal.done is True+ assert terminal.finish_reason == "stop"+ assert terminal.error_code == "empty_model_output"+ assert terminal.error_message == "model produced no visible output text"+ assert terminal.candidates is not None+ assert terminal.candidates[0]["text"] == "plain answer"++# ── Qwen XML format ────────────────────────────────────────────────diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex a3bccccd2..1747fb9a4 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -149,15 +149,29 @@ def _make_executor() -> tuple[QueueExecutor, MagicMock]:reg.loaded_model_names = ["test/model"]reg.is_loaded.return_value = Truereg.is_loading.return_value = False+ reg._config_version = 0config = MagicMock()config.sie_id = "test/model"config.outputs = ["dense"]+ config.tasks.generate = object()+ config.model_dump.return_value = {"sie_id": "test/model", "tasks": {"generate": {}}}config.resolve_profile.return_value.runtime = {}reg.get_config.return_value = configreg.get_configs_snapshot.return_value = {}return QueueExecutor(reg), reg+def _generation_config(model_id: str, *, revision: str = "v1", generation: bool = True) -> MagicMock:+ config = MagicMock()+ config.tasks.generate = object() if generation else None+ config.model_dump.return_value = {+ "sie_id": model_id,+ "revision": revision,+ "tasks": {"generate": {} if generation else None},+ }+ return config++@pytest.fixture(autouse=True)def _reset_readiness_state() -> Iterator[None]:register_liveness_probe(None)@@ -1758,7 +1772,7 @@ class TestGenerationSidecarIpc:assert resp["ok"] is Trueassert resp["body"] == {"matched": True}- srv._get_streaming_processor.assert_awaited_once_with(prewarm=False) # type: ignore[attr-defined]+ srv._get_streaming_processor.assert_awaited_once_with() # type: ignore[attr-defined]processor.signal_cancel.assert_called_once_with("req-123")@pytest.mark.asyncio@@ -1780,7 +1794,7 @@ class TestGenerationSidecarIpc:processor.signal_cancel.assert_called_once_with("req-123")@pytest.mark.asyncio- async def test_cancel_created_processor_still_prewarms_on_generate(self) -> None:+ async def test_cancel_created_processor_still_prewarms_requested_model_on_generate(self) -> None:executor, _reg = _make_executor()processor = MagicMock()sock = _short_sock_path()@@ -1788,12 +1802,262 @@ class TestGenerationSidecarIpc:srv._prewarm_generation_grammars = AsyncMock() # type: ignore[method-assign]with patch("sie_server.processors.streaming.StreamingProcessor", return_value=processor):- cancel_processor = await srv._get_streaming_processor(prewarm=False)- generate_processor = await srv._get_streaming_processor()+ cancel_processor = await srv._get_streaming_processor()+ generate_processor = await srv._get_streaming_processor(prewarm_model_id="google/madlad400-3b-mt")assert cancel_processor is processorassert generate_processor is processor- srv._prewarm_generation_grammars.assert_awaited_once_with(processor) # type: ignore[attr-defined]+ srv._prewarm_generation_grammars.assert_awaited_once_with( # type: ignore[attr-defined]+ processor,+ "google/madlad400-3b-mt",+ )++ @pytest.mark.asyncio+ async def test_generation_prewarm_does_not_touch_unrelated_grammar_model(self) -> None:+ executor, reg = _make_executor()+ madlad = _generation_config("google/madlad400-3b-mt")+ qwen = _generation_config("Qwen/Qwen3.5-4B")+ reg.get_config.return_value = madlad+ reg.get_configs_snapshot.return_value = {+ "google/madlad400-3b-mt": madlad,+ "Qwen/Qwen3.5-4B": qwen,+ }+ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock()+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id="google/madlad400-3b-mt")++ processor.prewarm_grammars_for_model.assert_awaited_once_with("google/madlad400-3b-mt")+ assert all(+ args != ("Qwen/Qwen3.5-4B",) for args, _kwargs in processor.prewarm_grammars_for_model.await_args_list+ )+ assert reg.get_config.call_count == 1+ assert all(call.args == ("google/madlad400-3b-mt",) for call in reg.get_config.call_args_list)+ madlad.model_dump.assert_called_once_with(mode="json")+ reg.get_configs_snapshot.assert_not_called()++ @pytest.mark.asyncio+ async def test_generation_prewarm_runs_once_per_requested_model(self) -> None:+ executor, reg = _make_executor()+ config = _generation_config("google/madlad400-3b-mt")+ reg.get_config.return_value = config+ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock()+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id="google/madlad400-3b-mt")+ await srv._get_streaming_processor(prewarm_model_id="google/madlad400-3b-mt")++ processor.prewarm_grammars_for_model.assert_awaited_once_with("google/madlad400-3b-mt")+ config.model_dump.assert_called_once_with(mode="json")++ @pytest.mark.asyncio+ async def test_generation_prewarm_rejects_unknown_model_before_allocating_state(self) -> None:+ executor, reg = _make_executor()+ reg.get_config.side_effect = KeyError("attacker/unknown")+ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock()+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id="attacker/unknown")++ processor.prewarm_grammars_for_model.assert_not_awaited()+ assert srv._generation_prewarm_locks == {}+ assert srv._generation_prewarm_completed == {}+ assert srv._generation_prewarm_authority_cache == {}++ @pytest.mark.asyncio+ async def test_generation_prewarm_rejects_non_generation_model_before_allocating_state(self) -> None:+ executor, reg = _make_executor()+ reg.get_config.return_value = _generation_config("embed/model", generation=False)+ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock()+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id="embed/model")++ processor.prewarm_grammars_for_model.assert_not_awaited()+ assert srv._generation_prewarm_locks == {}+ assert srv._generation_prewarm_completed == {}+ assert srv._generation_prewarm_authority_cache == {}++ @pytest.mark.asyncio+ async def test_generation_prewarm_different_models_run_concurrently(self) -> None:+ executor, reg = _make_executor()+ model_ids = ("google/madlad400-3b-mt", "Qwen/Qwen3.5-4B")+ configs = {model_id: _generation_config(model_id) for model_id in model_ids}+ reg.get_config.side_effect = lambda model_id: configs[model_id]+ started = {model_id: asyncio.Event() for model_id in model_ids}+ release = asyncio.Event()++ async def prewarm(model_id: str) -> None:+ started[model_id].set()+ await release.wait()++ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock(side_effect=prewarm)+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor+ tasks: list[asyncio.Task[object]] = []+ results: list[object] = []+ try:+ tasks.append(asyncio.create_task(srv._get_streaming_processor(prewarm_model_id=model_ids[0])))+ await asyncio.wait_for(started[model_ids[0]].wait(), timeout=1)+ tasks.append(asyncio.create_task(srv._get_streaming_processor(prewarm_model_id=model_ids[1])))+ await asyncio.wait_for(started[model_ids[1]].wait(), timeout=1)+ finally:+ release.set()+ results = list(await asyncio.gather(*tasks, return_exceptions=True))++ assert processor.prewarm_grammars_for_model.await_count == 2+ assert results == [processor, processor]++ @pytest.mark.asyncio+ async def test_generation_prewarm_same_model_converges_under_concurrency(self) -> None:+ executor, reg = _make_executor()+ model_id = "google/madlad400-3b-mt"+ reg.get_config.return_value = _generation_config(model_id)+ started = asyncio.Event()+ release = asyncio.Event()++ async def prewarm(_model_id: str) -> None:+ started.set()+ await release.wait()++ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock(side_effect=prewarm)+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor+ first = asyncio.create_task(srv._get_streaming_processor(prewarm_model_id=model_id))+ await asyncio.wait_for(started.wait(), timeout=1)+ second = asyncio.create_task(srv._get_streaming_processor(prewarm_model_id=model_id))+ try:+ await asyncio.sleep(0)+ assert processor.prewarm_grammars_for_model.await_count == 1+ assert second.done() is False+ finally:+ release.set()++ assert await asyncio.gather(first, second) == [processor, processor]+ processor.prewarm_grammars_for_model.assert_awaited_once_with(model_id)++ @pytest.mark.asyncio+ async def test_generation_prewarm_retries_after_ordinary_failure(self) -> None:+ executor, reg = _make_executor()+ model_id = "google/madlad400-3b-mt"+ reg.get_config.return_value = _generation_config(model_id)+ attempts = 0++ async def prewarm(_model_id: str) -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ raise RuntimeError("compile failed")++ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock(side_effect=prewarm)+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id=model_id)+ assert model_id not in srv._generation_prewarm_completed+ await srv._get_streaming_processor(prewarm_model_id=model_id)++ assert attempts == 2+ assert srv._generation_prewarm_completed[model_id] == srv._generation_prewarm_authority(model_id)++ @pytest.mark.asyncio+ async def test_generation_prewarm_retries_after_cancellation(self) -> None:+ executor, reg = _make_executor()+ model_id = "google/madlad400-3b-mt"+ reg.get_config.return_value = _generation_config(model_id)+ started = asyncio.Event()+ blocker = asyncio.Event()+ attempts = 0++ async def prewarm(_model_id: str) -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ started.set()+ await blocker.wait()++ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock(side_effect=prewarm)+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ first = asyncio.create_task(srv._get_streaming_processor(prewarm_model_id=model_id))+ await asyncio.wait_for(started.wait(), timeout=1)+ first.cancel()+ with pytest.raises(asyncio.CancelledError):+ await first+ assert model_id not in srv._generation_prewarm_completed++ await srv._get_streaming_processor(prewarm_model_id=model_id)++ assert attempts == 2+ assert model_id in srv._generation_prewarm_completed++ @pytest.mark.asyncio+ async def test_generation_prewarm_repeats_after_config_hot_reload(self) -> None:+ executor, reg = _make_executor()+ model_id = "google/madlad400-3b-mt"+ config_v1 = _generation_config(model_id, revision="v1")+ config_v2 = _generation_config(model_id, revision="v2")+ current = [config_v1]+ reg.get_config.side_effect = lambda _model_id: current[0]+ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock()+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id=model_id)+ first_authority = srv._generation_prewarm_completed[model_id]+ current[0] = config_v2+ reg._config_version += 1+ await srv._get_streaming_processor(prewarm_model_id=model_id)++ assert processor.prewarm_grammars_for_model.await_count == 2+ assert srv._generation_prewarm_completed[model_id] != first_authority+ assert srv._generation_prewarm_completed[model_id] == srv._generation_prewarm_authority(model_id)+ config_v1.model_dump.assert_called_once_with(mode="json")+ config_v2.model_dump.assert_called_once_with(mode="json")++ @pytest.mark.asyncio+ async def test_generation_prewarm_inflight_aba_does_not_publish_false_completion(self) -> None:+ executor, reg = _make_executor()+ model_id = "google/madlad400-3b-mt"+ current = [_generation_config(model_id, revision="A")]+ reg.get_config.side_effect = lambda _model_id: current[0]+ attempts = 0++ async def prewarm(_model_id: str) -> None:+ nonlocal attempts+ attempts += 1+ if attempts == 1:+ current[0] = _generation_config(model_id, revision="B", generation=False)+ reg._config_version += 1+ assert reg.get_config(model_id).tasks.generate is None+ current[0] = _generation_config(model_id, revision="A")+ reg._config_version += 1++ processor = MagicMock()+ processor.prewarm_grammars_for_model = AsyncMock(side_effect=prewarm)+ srv = IpcServer(_short_sock_path(), executor, worker_id="w")+ srv._streaming_processor = processor++ await srv._get_streaming_processor(prewarm_model_id=model_id)++ assert model_id not in srv._generation_prewarm_completed+ await srv._get_streaming_processor(prewarm_model_id=model_id)+ assert attempts == 2+ assert srv._generation_prewarm_completed[model_id] == srv._generation_prewarm_authority(model_id)@pytest.mark.asyncioasync def test_process_generate_sends_progress_before_lazy_processor(self) -> None:@@ -1805,9 +2069,10 @@ class TestGenerationSidecarIpc:writer = _CapturingWriter()work_item_msgpack = msgpack.packb({"request_id": "req-1"}, use_bin_type=True)- async def get_processor() -> MagicMock:+ async def get_processor(*, prewarm_model_id: str | None = None) -> MagicMock:frames = _decode_written_frames(writer)assert [frame["body"]["kind"] for frame in frames] == ["in_progress"]+ assert prewarm_model_id == "test/model"return processorget_processor_mock = AsyncMock(side_effect=get_processor)@@ -1822,7 +2087,7 @@ class TestGenerationSidecarIpc:frames = _decode_written_frames(writer)assert [frame["body"]["kind"] for frame in frames] == ["in_progress", "done"]assert [frame["request_id"] for frame in frames] == ["ipc-req-1", "ipc-req-1"]- get_processor_mock.assert_awaited_once()+ get_processor_mock.assert_awaited_once_with(prewarm_model_id="test/model")processor.process.assert_awaited_once()diff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.pyindex 0ce3d4808..e488e9388 100644--- a/packages/sie_server/tests/test_openapi_export.py+++ b/packages/sie_server/tests/test_openapi_export.py@@ -92,6 +92,14 @@ def test_openapi_documents_generate_contract() -> None:assert chunk_schema["properties"]["usage"]["anyOf"][0] == {"$ref": "#/components/schemas/GenerateUsageModel"}assert chunk_schema["properties"]["error"]["anyOf"][0] == {"$ref": "#/components/schemas/GenerateChunkErrorModel"}assert chunk_schema["properties"]["logprobs"]["anyOf"][0]["type"] == "array"+ chunk_error_schema = spec["components"]["schemas"]["GenerateChunkErrorModel"]+ assert chunk_error_schema["properties"]["param"]["anyOf"][0] == {"type": "string"}+ assert "param" not in chunk_error_schema["required"]+ retry_after = chunk_error_schema["properties"]["retry_after_s"]+ assert retry_after["anyOf"][0]["type"] == "integer"+ assert retry_after["anyOf"][0]["minimum"] == 1+ assert retry_after["anyOf"][0]["maximum"] == 60+ assert "retry_after_s" not in chunk_error_schema["required"]responses = operation["responses"]assert "INPUT_TOO_LONG" in responses["413"]["description"]@@ -118,6 +126,15 @@ def test_openapi_documents_generate_contract() -> None:assert model_load_failed_detail["properties"]["code"]["const"] == "MODEL_LOAD_FAILED"+def test_openapi_documents_streaming_model_capability() -> None:+ result = runner.invoke(app, ["openapi"])+ assert result.exit_code == 0, result.output+ spec = json.loads(result.output)+ streaming = spec["components"]["schemas"]["ModelCapabilities"]["properties"]["streaming"]+ assert streaming["type"] == "boolean"+ assert streaming["default"] is True++def test_openapi_documents_direct_completions_contract() -> None:result = runner.invoke(app, ["openapi"])assert result.exit_code == 0, result.outputdiff --git a/packages/sie_server_rust/Cargo.lock b/packages/sie_server_rust/Cargo.locknew file mode 100644index 000000000..76bb8e34d--- /dev/null+++ b/packages/sie_server_rust/Cargo.lock@@ -0,0 +1,4677 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "accelerate-src"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "415ed64958754dbe991900f3940677e6a7eefb4d7367afd70d642677b0c7d19d"++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "ahash"+version = "0.8.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"+dependencies = [+ "cfg-if",+ "getrandom 0.3.4",+ "once_cell",+ "serde",+ "version_check",+ "zerocopy",+]++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "anstream"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"+dependencies = [+ "anstyle",+ "anstyle-parse",+ "anstyle-query",+ "anstyle-wincon",+ "colorchoice",+ "is_terminal_polyfill",+ "utf8parse",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anstyle-parse"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"+dependencies = [+ "utf8parse",+]++[[package]]+name = "anstyle-query"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "anstyle-wincon"+version = "3.0.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"+dependencies = [+ "anstyle",+ "once_cell_polyfill",+ "windows-sys 0.61.2",+]++[[package]]+name = "anyhow"+version = "1.0.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"++[[package]]+name = "arrayref"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"++[[package]]+name = "arrayvec"+version = "0.7.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"++[[package]]+name = "async-trait"+version = "0.1.89"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "aws-lc-rs"+version = "1.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4342d8937fc7e5dd9b1c60292261c0670c882a2cd1719cfc11b1af41731e32ad"+dependencies = [+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.42.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d9ceb1da931507a12f4fccea479dccd00da1943e1b4ae72d8e502d707361444"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",+ "pkg-config",+]++[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"++[[package]]+name = "bindgen_cuda"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be55fb326843bb67cccceeeaf21c961ef303f60018f9a2ab69494dad8eaf9"+dependencies = [+ "glob",+ "num_cpus",+ "rayon",+]++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"++[[package]]+name = "blake3"+version = "1.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce"+dependencies = [+ "arrayref",+ "arrayvec",+ "cc",+ "cfg-if",+ "constant_time_eq",+ "cpufeatures 0.3.0",+]++[[package]]+name = "block"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6aedf8ae72766347502cf3cb4f41cf5e9cc37d28bee90f1fdaaae15f9cf9424"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "byteorder"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "candle-core"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6bd9895436c1ba5dc1037a19935d084b838db066ff4e15ef7dded020b7c12a4a"+dependencies = [+ "accelerate-src",+ "byteorder",+ "candle-kernels",+ "candle-metal-kernels",+ "candle-ug",+ "cudarc 0.19.8",+ "float8",+ "gemm 0.19.0",+ "half",+ "libc",+ "libm",+ "memmap2",+ "num-traits",+ "num_cpus",+ "objc2-foundation",+ "objc2-metal",+ "rand 0.9.5",+ "rand_distr",+ "rayon",+ "safetensors 0.7.0",+ "thiserror 2.0.18",+ "tokenizers",+ "yoke 0.8.3",+ "zip",+]++[[package]]+name = "candle-cublaslt"+version = "0.0.1"+dependencies = [+ "candle-core",+ "cudarc 0.19.8",+ "half",+]++[[package]]+name = "candle-flash-attn"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12512cf8e706744642e9a8579305a6ed1e44a0c636ce20c416cd5c519de19b7d"+dependencies = [+ "anyhow",+ "candle-core",+ "cudaforge",+ "half",+]++[[package]]+name = "candle-gated-activation"+version = "0.0.1"+dependencies = [+ "anyhow",+ "candle-core",+ "half",+ "num_cpus",+ "rayon",+]++[[package]]+name = "candle-index-select-cu"+version = "0.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d776145d1dfa52ab0c254ec678ae7765a120ee0bab999dbfea95d648c883a47b"+dependencies = [+ "anyhow",+ "candle-core",+ "half",+ "num_cpus",+ "rayon",+]++[[package]]+name = "candle-kernels"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "742e2ac226b777134436e9e692f44e77c278b8a7abb1554dc10e44dc911b349f"+dependencies = [+ "cudaforge",+]++[[package]]+name = "candle-layer-norm"+version = "0.0.1"+dependencies = [+ "anyhow",+ "candle-core",+ "half",+ "num_cpus",+ "rayon",+]++[[package]]+name = "candle-metal-kernels"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b6b5a4cae6b4e1ab0efcee4dc05272d11b374a3d1ba121b3a961e36be54ab60"+dependencies = [+ "half",+ "objc2",+ "objc2-foundation",+ "objc2-metal",+ "once_cell",+ "thiserror 2.0.18",+ "tracing",+]++[[package]]+name = "candle-nn"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9317a09d6530b758990ed7f625ac69ff43653bc9ee28b0464644ad1169ada87"+dependencies = [+ "accelerate-src",+ "candle-core",+ "candle-metal-kernels",+ "half",+ "libc",+ "num-traits",+ "objc2-metal",+ "rayon",+ "safetensors 0.7.0",+ "serde",+ "thiserror 2.0.18",+]++[[package]]+name = "candle-rotary"+version = "0.0.1"+dependencies = [+ "anyhow",+ "bindgen_cuda",+ "candle-core",+ "half",+]++[[package]]+name = "candle-splade-pool"+version = "0.0.1"+dependencies = [+ "anyhow",+ "candle-core",+ "half",+]++[[package]]+name = "candle-transformers"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f59d08c89e9f4af9c464e2f3a8e16199e7cc601e6f34538c2cfbb42b623b1783"+dependencies = [+ "accelerate-src",+ "byteorder",+ "candle-core",+ "candle-nn",+ "fancy-regex",+ "num-traits",+ "rand 0.9.5",+ "rayon",+ "serde",+ "serde_json",+ "serde_plain",+ "tracing",+]++[[package]]+name = "candle-ug"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca0fc3167cbc99c8ec1be618cb620aa21dca95038f118c3579a79370e3dc5f77"+dependencies = [+ "ug",+ "ug-cuda",+ "ug-metal",+]++[[package]]+name = "castaway"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"+dependencies = [+ "rustversion",+]++[[package]]+name = "cc"+version = "1.2.67"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"+dependencies = [+ "find-msvc-tools",+ "jobserver",+ "libc",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "cfg_aliases"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "rand_core 0.10.1",+]++[[package]]+name = "clap"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"+dependencies = [+ "clap_builder",+ "clap_derive",+]++[[package]]+name = "clap_builder"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"+dependencies = [+ "anstream",+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_derive"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "clap_lex"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"++[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]++[[package]]+name = "colorchoice"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "compact_str"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"+dependencies = [+ "castaway",+ "cfg-if",+ "itoa",+ "rustversion",+ "ryu",+ "serde",+ "static_assertions",+]++[[package]]+name = "console"+version = "0.16.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c"+dependencies = [+ "encode_unicode",+ "libc",+ "unicode-width",+ "windows-sys 0.61.2",+]++[[package]]+name = "constant_time_eq"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"++[[package]]+name = "cookie"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"+dependencies = [+ "percent-encoding",+ "time",+ "version_check",+]++[[package]]+name = "cookie_store"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206"+dependencies = [+ "cookie",+ "document-features",+ "idna",+ "indexmap",+ "log",+ "serde",+ "serde_derive",+ "serde_json",+ "time",+ "url",+]++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics-types"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf"+dependencies = [+ "bitflags 1.3.2",+ "core-foundation 0.9.4",+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "crunchy"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cudaforge"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d475ff95b9e4096878f47fe0ca5dbad0e23849a79fc225305ea06c2f25771cd"+dependencies = [+ "anyhow",+ "fs2",+ "glob",+ "num_cpus",+ "rayon",+ "serde",+ "serde_json",+ "sha2",+ "thiserror 2.0.18",+ "walkdir",+ "which",+]++[[package]]+name = "cudarc"+version = "0.17.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf99ab37ee7072d64d906aa2dada9a3422f1d975cdf8c8055a573bc84897ed8"+dependencies = [+ "half",+ "libloading 0.8.9",+]++[[package]]+name = "cudarc"+version = "0.19.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42310153e06cf4cd532901f7096beb27504d681736a29ee90728ae4e2d93b2a8"+dependencies = [+ "float8",+ "half",+ "libloading 0.9.0",+]++[[package]]+name = "darling"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn",+]++[[package]]+name = "darling_macro"+version = "0.20.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"+dependencies = [+ "darling_core",+ "quote",+ "syn",+]++[[package]]+name = "dary_heap"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"+dependencies = [+ "serde",+]++[[package]]+name = "der"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a69dedd701da44b0536442edf09c81a64b0ab97a7a4a5e3d1971f00027cbc63d"+dependencies = [+ "pem-rfc7468",+ "zeroize",+]++[[package]]+name = "deranged"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"++[[package]]+name = "derive_builder"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"+dependencies = [+ "derive_builder_macro",+]++[[package]]+name = "derive_builder_core"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "derive_builder_macro"+version = "0.20.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"+dependencies = [+ "derive_builder_core",+ "syn",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"+dependencies = [+ "libc",+ "option-ext",+ "redox_users",+ "windows-sys 0.61.2",+]++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.0",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "document-features"+version = "0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"+dependencies = [+ "litrs",+]++[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"++[[package]]+name = "dyn-stack"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c4713e43e2886ba72b8271aa66c93d722116acf7a75555cce11dcde84388fe8"+dependencies = [+ "bytemuck",+ "dyn-stack-macros",+]++[[package]]+name = "dyn-stack-macros"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d926b4d407d372f141f93bb444696142c29d32962ccbd3531117cf3aa0bfa9"++[[package]]+name = "either"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"++[[package]]+name = "encode_unicode"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"++[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]++[[package]]+name = "enum-as-inner"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "env_home"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.52.0",+]++[[package]]+name = "esaxx-rs"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"++[[package]]+name = "fancy-regex"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72cf461f865c862bb7dc573f643dd6a2b6842f7c30b07882b56bd148cc2761b8"+dependencies = [+ "bit-set",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "float8"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2d1f04709a8ac06e8e8042875a3c466cc4832d3c1a18dbcb9dba3c6e83046bc"+dependencies = [+ "half",+ "num-traits",+ "rand 0.9.5",+ "rand_distr",+]++[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared 0.1.1",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared 0.3.1",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "fs2"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"+dependencies = [+ "libc",+ "winapi",+]++[[package]]+name = "fs_extra"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"++[[package]]+name = "futures"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-executor"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "futures-sink"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gemm"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab96b703d31950f1aeddded248bc95543c9efc7ac9c4a21fda8703a83ee35451"+dependencies = [+ "dyn-stack",+ "gemm-c32 0.18.2",+ "gemm-c64 0.18.2",+ "gemm-common 0.18.2",+ "gemm-f16 0.18.2",+ "gemm-f32 0.18.2",+ "gemm-f64 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa0673db364b12263d103b68337a68fbecc541d6f6b61ba72fe438654709eacb"+dependencies = [+ "dyn-stack",+ "gemm-c32 0.19.0",+ "gemm-c64 0.19.0",+ "gemm-common 0.19.0",+ "gemm-f16 0.19.0",+ "gemm-f32 0.19.0",+ "gemm-f64 0.19.0",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c32"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6db9fd9f40421d00eea9dd0770045a5603b8d684654816637732463f4073847"+dependencies = [+ "dyn-stack",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c32"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "086936dbdcb99e37aad81d320f98f670e53c1e55a98bee70573e83f95beb128c"+dependencies = [+ "dyn-stack",+ "gemm-common 0.19.0",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c64"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfcad8a3d35a43758330b635d02edad980c1e143dc2f21e6fd25f9e4eada8edf"+dependencies = [+ "dyn-stack",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-c64"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20c8aeeeec425959bda4d9827664029ba1501a90a0d1e6228e48bef741db3a3f"+dependencies = [+ "dyn-stack",+ "gemm-common 0.19.0",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-common"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a352d4a69cbe938b9e2a9cb7a3a63b7e72f9349174a2752a558a8a563510d0f3"+dependencies = [+ "bytemuck",+ "dyn-stack",+ "half",+ "libm",+ "num-complex",+ "num-traits",+ "once_cell",+ "paste",+ "pulp 0.21.5",+ "raw-cpuid",+ "rayon",+ "seq-macro",+ "sysctl",+]++[[package]]+name = "gemm-common"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88027625910cc9b1085aaaa1c4bc46bb3a36aad323452b33c25b5e4e7c8e2a3e"+dependencies = [+ "bytemuck",+ "dyn-stack",+ "half",+ "libm",+ "num-complex",+ "num-traits",+ "once_cell",+ "paste",+ "pulp 0.22.3",+ "raw-cpuid",+ "rayon",+ "seq-macro",+ "sysctl",+]++[[package]]+name = "gemm-f16"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cff95ae3259432f3c3410eaa919033cd03791d81cebd18018393dc147952e109"+dependencies = [+ "dyn-stack",+ "gemm-common 0.18.2",+ "gemm-f32 0.18.2",+ "half",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "rayon",+ "seq-macro",+]++[[package]]+name = "gemm-f16"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3df7a55202e6cd6739d82ae3399c8e0c7e1402859b30e4cb780e61525d9486e"+dependencies = [+ "dyn-stack",+ "gemm-common 0.19.0",+ "gemm-f32 0.19.0",+ "half",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "rayon",+ "seq-macro",+]++[[package]]+name = "gemm-f32"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc8d3d4385393304f407392f754cd2dc4b315d05063f62cf09f47b58de276864"+dependencies = [+ "dyn-stack",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-f32"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02e0b8c9da1fbec6e3e3ab2ce6bc259ef18eb5f6f0d3e4edf54b75f9fd41a81c"+dependencies = [+ "dyn-stack",+ "gemm-common 0.19.0",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-f64"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35b2a4f76ce4b8b16eadc11ccf2e083252d8237c1b589558a49b0183545015bd"+dependencies = [+ "dyn-stack",+ "gemm-common 0.18.2",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "gemm-f64"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "056131e8f2a521bfab322f804ccd652520c79700d81209e9d9275bbdecaadc6a"+dependencies = [+ "dyn-stack",+ "gemm-common 0.19.0",+ "num-complex",+ "num-traits",+ "paste",+ "raw-cpuid",+ "seq-macro",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi 5.3.0",+ "wasip2",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi 6.0.0",+ "rand_core 0.10.1",+ "wasm-bindgen",+]++[[package]]+name = "glob"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"++[[package]]+name = "h2"+version = "0.4.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]++[[package]]+name = "half"+version = "2.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"+dependencies = [+ "bytemuck",+ "cfg-if",+ "crunchy",+ "num-traits",+ "rand 0.9.5",+ "rand_distr",+ "zerocopy",+]++[[package]]+name = "hashbrown"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash",+ "serde",+ "serde_core",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hermit-abi"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"++[[package]]+name = "hf-hub"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aef3982638978efa195ff11b305f51f1f22f4f0a6cabee7af79b383ebee6a213"+dependencies = [+ "dirs",+ "futures",+ "http",+ "indicatif",+ "libc",+ "log",+ "native-tls",+ "num_cpus",+ "rand 0.9.5",+ "reqwest 0.12.28",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "ureq",+ "windows-sys 0.61.2",+]++[[package]]+name = "http"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "hyper"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "h2",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "tokio",+ "tokio-rustls",+ "tower-service",+]++[[package]]+name = "hyper-timeout"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"+dependencies = [+ "hyper",+ "hyper-util",+ "pin-project-lite",+ "tokio",+ "tower-service",+]++[[package]]+name = "hyper-tls"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"+dependencies = [+ "bytes",+ "http-body-util",+ "hyper",+ "hyper-util",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tower-service",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "system-configuration",+ "tokio",+ "tower-service",+ "tracing",+ "windows-registry",+]++[[package]]+name = "icu_collections"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke 0.8.3",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"++[[package]]+name = "icu_properties"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"++[[package]]+name = "icu_provider"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke 0.8.3",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "ident_case"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+]++[[package]]+name = "indicatif"+version = "0.18.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9433806cd6b4ec1aba79c021c7e4c58fb4c3b9977c085062e611ac929998fb0c"+dependencies = [+ "console",+ "portable-atomic",+ "unicode-width",+ "unit-prefix",+ "web-time",+]++[[package]]+name = "ipnet"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"++[[package]]+name = "is_terminal_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"++[[package]]+name = "itertools"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys",+ "log",+ "simd_cesu8",+ "thiserror 2.0.18",+ "walkdir",+ "windows-link",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "jobserver"+version = "0.1.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"+dependencies = [+ "getrandom 0.4.3",+ "libc",+]++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libloading"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"++[[package]]+name = "libredox"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"+dependencies = [+ "libc",+]++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litemap"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"++[[package]]+name = "litrs"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "lru-slab"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"++[[package]]+name = "macro_rules_attribute"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520"+dependencies = [+ "macro_rules_attribute-proc_macro",+ "paste",+]++[[package]]+name = "macro_rules_attribute-proc_macro"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"++[[package]]+name = "malloc_buf"+version = "0.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb"+dependencies = [+ "libc",+]++[[package]]+name = "matchers"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"+dependencies = [+ "regex-automata",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"+dependencies = [+ "libc",+ "stable_deref_trait",+]++[[package]]+name = "metal"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21"+dependencies = [+ "bitflags 2.13.0",+ "block",+ "core-graphics-types",+ "foreign-types 0.5.0",+ "log",+ "objc",+ "paste",+]++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "monostate"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"+dependencies = [+ "monostate-impl",+ "serde",+ "serde_core",+]++[[package]]+name = "monostate-impl"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe",+ "openssl-sys",+ "schannel",+ "security-framework",+ "security-framework-sys",+ "tempfile",+]++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "num"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"+dependencies = [+ "num-bigint",+ "num-complex",+ "num-integer",+ "num-iter",+ "num-rational",+ "num-traits",+]++[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "bytemuck",+ "num-traits",+]++[[package]]+name = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[package]]+name = "num-integer"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-iter"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+ "libm",+]++[[package]]+name = "num_cpus"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"+dependencies = [+ "hermit-abi",+ "libc",+]++[[package]]+name = "objc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1"+dependencies = [+ "malloc_buf",+]++[[package]]+name = "objc2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.0",+ "dispatch2",+ "objc2",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.0",+ "block2",+ "libc",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags 2.13.0",+ "block2",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "once_cell_polyfill"+version = "1.70.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"++[[package]]+name = "onig"+version = "6.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"+dependencies = [+ "bitflags 2.13.0",+ "libc",+ "once_cell",+ "onig_sys",+]++[[package]]+name = "onig_sys"+version = "69.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"+dependencies = [+ "cc",+ "pkg-config",+]++[[package]]+name = "openssl"+version = "0.10.81"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"+dependencies = [+ "bitflags 2.13.0",+ "cfg-if",+ "foreign-types 0.3.2",+ "libc",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "openssl-sys"+version = "0.9.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]++[[package]]+name = "opentelemetry"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682"+dependencies = [+ "futures-core",+ "futures-sink",+ "js-sys",+ "pin-project-lite",+ "thiserror 2.0.18",+ "tracing",+]++[[package]]+name = "opentelemetry-http"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331"+dependencies = [+ "async-trait",+ "bytes",+ "http",+ "opentelemetry",+ "reqwest 0.13.4",+]++[[package]]+name = "opentelemetry-otlp"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35"+dependencies = [+ "http",+ "opentelemetry",+ "opentelemetry-http",+ "opentelemetry-proto",+ "opentelemetry_sdk",+ "prost",+ "reqwest 0.13.4",+ "thiserror 2.0.18",+ "tokio",+ "tonic",+ "tonic-types",+]++[[package]]+name = "opentelemetry-proto"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638"+dependencies = [+ "opentelemetry",+ "opentelemetry_sdk",+ "prost",+ "tonic",+ "tonic-prost",+]++[[package]]+name = "opentelemetry_sdk"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9"+dependencies = [+ "futures-channel",+ "futures-executor",+ "futures-util",+ "opentelemetry",+ "percent-encoding",+ "portable-atomic",+ "rand 0.9.5",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+]++[[package]]+name = "option-ext"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"++[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "pem-rfc7468"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9"+dependencies = [+ "base64ct",+]++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"+dependencies = [+ "pin-project-internal",+]++[[package]]+name = "pin-project-internal"+version = "1.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"++[[package]]+name = "portable-atomic"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"++[[package]]+name = "potential_utf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"+dependencies = [+ "zerovec",+]++[[package]]+name = "powerfmt"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "prost"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"+dependencies = [+ "bytes",+ "prost-derive",+]++[[package]]+name = "prost-derive"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"+dependencies = [+ "anyhow",+ "itertools",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "prost-types"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"+dependencies = [+ "prost",+]++[[package]]+name = "pulp"+version = "0.21.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96b86df24f0a7ddd5e4b95c94fc9ed8a98f1ca94d3b01bdce2824097e7835907"+dependencies = [+ "bytemuck",+ "cfg-if",+ "libm",+ "num-complex",+ "reborrow",+ "version_check",+]++[[package]]+name = "pulp"+version = "0.22.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a"+dependencies = [+ "bytemuck",+ "cfg-if",+ "libm",+ "num-complex",+ "paste",+ "pulp-wasm-simd-flag",+ "raw-cpuid",+ "reborrow",+ "version_check",+]++[[package]]+name = "pulp-wasm-simd-flag"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740"++[[package]]+name = "quinn"+version = "0.11.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"+dependencies = [+ "aws-lc-rs",+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand 0.10.2",+ "rand_pcg",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.18",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.52.0",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]++[[package]]+name = "rand"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_distr"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"+dependencies = [+ "num-traits",+ "rand 0.9.5",+]++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]++[[package]]+name = "raw-cpuid"+version = "11.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186"+dependencies = [+ "bitflags 2.13.0",+]++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-cond"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"+dependencies = [+ "either",+ "itertools",+ "rayon",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "reborrow"+version = "0.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430"++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags 2.13.0",+]++[[package]]+name = "redox_users"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 2.0.18",+]++[[package]]+name = "regex"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "encoding_rs",+ "futures-core",+ "futures-util",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-tls",+ "hyper-util",+ "js-sys",+ "log",+ "mime",+ "native-tls",+ "percent-encoding",+ "pin-project-lite",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-native-tls",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]++[[package]]+name = "reqwest"+version = "0.13.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-channel",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "rustls-platform-verifier",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rmp"+version = "0.8.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"+dependencies = [+ "num-traits",+]++[[package]]+name = "rmp-serde"+version = "1.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"+dependencies = [+ "rmp",+ "serde",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustc_version"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"+dependencies = [+ "semver",+]++[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags 2.13.0",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustls"+version = "0.23.41"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"+dependencies = [+ "aws-lc-rs",+ "log",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+dependencies = [+ "openssl-probe",+ "rustls-pki-types",+ "schannel",+ "security-framework",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-platform-verifier"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"+dependencies = [+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "jni",+ "log",+ "once_cell",+ "rustls",+ "rustls-native-certs",+ "rustls-platform-verifier-android",+ "rustls-webpki",+ "security-framework",+ "security-framework-sys",+ "webpki-root-certs",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustls-platform-verifier-android"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"++[[package]]+name = "rustls-webpki"+version = "0.103.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"+dependencies = [+ "aws-lc-rs",+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "safetensors"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44560c11236a6130a46ce36c836a62936dc81ebf8c36a37947423571be0e55b6"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "safetensors"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "675656c1eabb620b921efea4f9199f97fc86e36dd6ffd1fbbe48d0f59a4987f5"+dependencies = [+ "hashbrown 0.16.1",+ "serde",+ "serde_json",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schannel"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags 2.13.0",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "seq-macro"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc"++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_bytes"+version = "0.11.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.150"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_plain"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ce1fc6db65a611022b23a0dec6975d63fb80a302cb3388835ff02c097258d50"+dependencies = [+ "serde",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "serde_yaml"+version = "0.9.34+deprecated"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"+dependencies = [+ "indexmap",+ "itoa",+ "ryu",+ "serde",+ "unsafe-libyaml",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "sie-server-rust"+version = "0.4.2"+dependencies = [+ "anyhow",+ "blake3",+ "candle-core",+ "candle-cublaslt",+ "candle-flash-attn",+ "candle-gated-activation",+ "candle-index-select-cu",+ "candle-layer-norm",+ "candle-nn",+ "candle-rotary",+ "candle-splade-pool",+ "candle-transformers",+ "clap",+ "half",+ "hf-hub",+ "opentelemetry",+ "opentelemetry-otlp",+ "opentelemetry_sdk",+ "reqwest 0.13.4",+ "rmp-serde",+ "rustls",+ "serde",+ "serde_bytes",+ "serde_json",+ "serde_yaml",+ "sha2",+ "sie-telemetry",+ "tempfile",+ "thiserror 2.0.18",+ "tokenizers",+ "tokio",+ "tracing",+ "tracing-opentelemetry",+ "tracing-subscriber",+ "uuid",+]++[[package]]+name = "sie-telemetry"+version = "0.1.0"+dependencies = [+ "opentelemetry",+ "opentelemetry-otlp",+ "opentelemetry_sdk",+ "reqwest 0.13.4",+ "uuid",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "simd_cesu8"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"+dependencies = [+ "rustc_version",+ "simdutf8",+]++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "socket2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "socks"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b"+dependencies = [+ "byteorder",+ "libc",+ "winapi",+]++[[package]]+name = "spm_precompiled"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"+dependencies = [+ "base64 0.13.1",+ "nom",+ "serde",+ "unicode-segmentation",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "sysctl"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "01198a2debb237c62b6826ec7081082d951f46dbb64b0e8c7649a452230d1dfc"+dependencies = [+ "bitflags 2.13.0",+ "byteorder",+ "enum-as-inner",+ "libc",+ "thiserror 1.0.69",+ "walkdir",+]++[[package]]+name = "system-configuration"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"+dependencies = [+ "bitflags 2.13.0",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration-sys"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.52.0",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thread_local"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"+dependencies = [+ "cfg-if",+]++[[package]]+name = "time"+version = "0.3.53"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18dfaaeddcb932337b5e7866ee7d0ce9b76d2fd092997146f187ec09b4558a50"+dependencies = [+ "deranged",+ "num-conv",+ "powerfmt",+ "serde_core",+ "time-core",+ "time-macros",+]++[[package]]+name = "time-core"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"++[[package]]+name = "time-macros"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c431b87111666e491a90baa837f914fb45cd5dc3c268591b0220ff5057f2085f"+dependencies = [+ "num-conv",+ "time-core",+]++[[package]]+name = "tinystr"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokenizers"+version = "0.22.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"+dependencies = [+ "ahash",+ "aho-corasick",+ "compact_str",+ "dary_heap",+ "derive_builder",+ "esaxx-rs",+ "getrandom 0.3.4",+ "itertools",+ "log",+ "macro_rules_attribute",+ "monostate",+ "onig",+ "paste",+ "rand 0.9.5",+ "rayon",+ "rayon-cond",+ "regex",+ "regex-syntax",+ "serde",+ "serde_json",+ "spm_precompiled",+ "thiserror 2.0.18",+ "unicode-normalization-alignments",+ "unicode-segmentation",+ "unicode_categories",+]++[[package]]+name = "tokio"+version = "1.52.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "parking_lot",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tokio-native-tls"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"+dependencies = [+ "native-tls",+ "tokio",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-stream"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tonic"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"+dependencies = [+ "async-trait",+ "base64 0.22.1",+ "bytes",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-timeout",+ "hyper-util",+ "percent-encoding",+ "pin-project",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tokio-stream",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tonic-prost"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"+dependencies = [+ "bytes",+ "prost",+ "tonic",+]++[[package]]+name = "tonic-types"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8"+dependencies = [+ "prost",+ "prost-types",+ "tonic",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "indexmap",+ "pin-project-lite",+ "slab",+ "sync_wrapper",+ "tokio",+ "tokio-util",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags 2.13.0",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+ "valuable",+]++[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core",+]++[[package]]+name = "tracing-opentelemetry"+version = "0.33.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26"+dependencies = [+ "js-sys",+ "opentelemetry",+ "smallvec",+ "tracing",+ "tracing-core",+ "tracing-log",+ "tracing-subscriber",+ "web-time",+]++[[package]]+name = "tracing-serde"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"+dependencies = [+ "serde",+ "tracing-core",+]++[[package]]+name = "tracing-subscriber"+version = "0.3.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "serde",+ "serde_json",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",+ "tracing-serde",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typed-path"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "ug"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76b761acf8af3494640d826a8609e2265e19778fb43306c7f15379c78c9b05b0"+dependencies = [+ "gemm 0.18.2",+ "half",+ "libloading 0.8.9",+ "memmap2",+ "num",+ "num-traits",+ "num_cpus",+ "rayon",+ "safetensors 0.4.5",+ "serde",+ "thiserror 1.0.69",+ "tracing",+ "yoke 0.7.5",+]++[[package]]+name = "ug-cuda"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f0a1fa748f26166778c33b8498255ebb7c6bffb472bcc0a72839e07ebb1d9b5"+dependencies = [+ "cudarc 0.17.8",+ "half",+ "serde",+ "thiserror 1.0.69",+ "ug",+]++[[package]]+name = "ug-metal"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7adf545a99a086d362efc739e7cf4317c18cbeda22706000fd434d70ea3d95"+dependencies = [+ "half",+ "metal",+ "objc",+ "serde",+ "thiserror 1.0.69",+ "ug",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-normalization-alignments"+version = "0.1.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"+dependencies = [+ "smallvec",+]++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "unicode_categories"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"++[[package]]+name = "unit-prefix"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "81e544489bf3d8ef66c953931f56617f423cd4b5494be343d9b9d3dda037b9a3"++[[package]]+name = "unsafe-libyaml"+version = "0.2.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "3.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"+dependencies = [+ "base64 0.22.1",+ "cookie_store",+ "der",+ "flate2",+ "log",+ "native-tls",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "socks",+ "ureq-proto",+ "utf8-zero",+ "webpki-root-certs",+ "webpki-roots",+]++[[package]]+name = "ureq-proto"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"+dependencies = [+ "base64 0.22.1",+ "http",+ "httparse",+ "log",+]++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8-zero"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "utf8parse"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"++[[package]]+name = "uuid"+version = "1.23.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasip2"+version = "1.0.4+wasi-0.2.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"+dependencies = [+ "wit-bindgen",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.76"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "web-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-root-certs"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "webpki-roots"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "which"+version = "7.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"+dependencies = [+ "either",+ "env_home",+ "rustix",+ "winsafe",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.52.0",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winsafe"+version = "0.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"++[[package]]+name = "wit-bindgen"+version = "0.57.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"++[[package]]+name = "writeable"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"++[[package]]+name = "yoke"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40"+dependencies = [+ "serde",+ "stable_deref_trait",+ "yoke-derive 0.7.5",+ "zerofrom",+]++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive 0.8.2",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"++[[package]]+name = "zerotrie"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+dependencies = [+ "displaydoc",+ "yoke 0.8.3",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+dependencies = [+ "yoke 0.8.3",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zip"+version = "7.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c42e33efc22a0650c311c2ef19115ce232583abbe80850bc8b66509ebef02de0"+dependencies = [+ "crc32fast",+ "indexmap",+ "memchr",+ "typed-path",+]++[[package]]+name = "zmij"+version = "1.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"diff --git a/packages/sie_server_rust/Cargo.toml b/packages/sie_server_rust/Cargo.tomlnew file mode 100644index 000000000..b7402f424--- /dev/null+++ b/packages/sie_server_rust/Cargo.toml@@ -0,0 +1,93 @@+[package]+name = "sie-server-rust"+version = "0.4.2"+edition = "2021"+description = "Rust inference-engine integrations for SIE server workers."+publish = false++[workspace]+exclude = [+ "vendor/candle-cublaslt",+ "vendor/candle-gated-activation",+ "vendor/candle-layer-norm",+ "vendor/candle-rotary",+ "vendor/candle-splade-pool",+]++[lib]+name = "sie_server_rust"+path = "src/lib.rs"++[[bin]]+name = "sie-server-rust"+path = "src/main.rs"++[dependencies]+anyhow = "1"+blake3 = "1"+candle = { package = "candle-core", version = "0.10.2" }+candle-cublaslt = { path = "vendor/candle-cublaslt", optional = true }+candle-flash-attn = { version = "0.10.2", optional = true }+candle-gated-activation = { path = "vendor/candle-gated-activation", optional = true }+candle-index-select-cu = { version = "0.0.1", default-features = false, features = ["cuda-12"], optional = true }+candle-layer-norm = { path = "vendor/candle-layer-norm", optional = true }+candle-nn = "0.10.2"+candle-rotary = { path = "vendor/candle-rotary", optional = true }+candle-splade-pool = { path = "vendor/candle-splade-pool", optional = true }+candle-transformers = "0.10.2"+clap = { version = "4", features = ["derive", "env"] }+hf-hub = { version = "0.5.0", features = ["tokio"] }+half = "2"+opentelemetry = "0.32"+# Keep the blocking HTTP client deliberately. OTel 0.32 BatchSpanProcessor and+# PeriodicReader export from dedicated std threads via futures_executor::block_on,+# where an async reqwest client has no Tokio reactor and panics. This blocks only+# those exporter threads, never the worker runtime or inference path.+opentelemetry-otlp = { version = "0.32", default-features = false, features = [+ "grpc-tonic",+ "http-proto",+ "metrics",+ "reqwest-blocking-client",+ "reqwest-rustls",+ "tls-ring",+ "trace",+] }+opentelemetry_sdk = { version = "0.32", features = ["rt-tokio"] }+# Shared OTLP transport/proxy/resource/propagation plumbing (#2339).+sie-telemetry = { path = "../sie_telemetry" }+reqwest = { version = "0.13", default-features = false, features = ["blocking", "rustls"] }+rustls = { version = "0.23", default-features = false, features = ["ring"] }+serde = { version = "1", features = ["derive"] }+serde_bytes = "0.11"+serde_json = { version = "1", features = ["float_roundtrip"] }+serde_yaml = "0.9"+sha2 = "0.10"+thiserror = "2"+tokio = { version = "1", features = ["full"] }+tokenizers = { version = "0.22.0", default-features = false, features = ["onig"] }+tracing = "0.1"+tracing-opentelemetry = "0.33"+tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }+rmp-serde = "1"+uuid = { version = "1", features = ["v4"] }++[dev-dependencies]+opentelemetry_sdk = { version = "0.32", features = ["testing"] }+tempfile = "3"++[features]+default = []+accelerate = ["candle/accelerate", "candle-nn/accelerate", "candle-transformers/accelerate"]+cuda = [+ "candle/cuda",+ "dep:candle-cublaslt",+ "dep:candle-flash-attn",+ "dep:candle-gated-activation",+ "dep:candle-index-select-cu",+ "dep:candle-layer-norm",+ "dep:candle-rotary",+ "dep:candle-splade-pool",+ "candle-nn/cuda",+ "candle-transformers/cuda",+]+metal = ["candle/metal", "candle-nn/metal"]diff --git a/packages/sie_server_rust/Dockerfile b/packages/sie_server_rust/Dockerfilenew file mode 100644index 000000000..217ef371d--- /dev/null+++ b/packages/sie_server_rust/Dockerfile@@ -0,0 +1,80 @@+# syntax=docker/dockerfile:1+#+# SIE Rust Server Image+#+# Build from repo root:+# docker build -f packages/sie_server_rust/Dockerfile -t sie-server-rust:latest .+#+# This image runs the Rust adapter process and exposes the existing UDS IPC+# contract to the worker-sidecar. Native engines such as Candle run inside this+# process rather than through a sibling Python adapter process.++ARG RUST_VERSION=1.97.0+ARG CARGO_FEATURES=""++FROM rust:${RUST_VERSION}-slim-bookworm AS chef+RUN cargo install cargo-chef --locked --version 0.1.77+WORKDIR /build++FROM chef AS planner+COPY packages/sie_server_rust/Cargo.toml packages/sie_server_rust/Cargo.lock ./+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+COPY packages/sie_server_rust/src/ src/+RUN cargo chef prepare --recipe-path recipe.json++FROM chef AS builder+ARG CARGO_FEATURES=""+RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \+ apt-get update && apt-get install -y --no-install-recommends \+ pkg-config \+ libssl-dev \+ ca-certificates \+ build-essential \+ && rm -rf /var/lib/apt/lists/*++COPY --from=planner /build/recipe.json recipe.json+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+RUN --mount=type=cache,target=/usr/local/cargo/registry \+ --mount=type=cache,target=/build/target \+ if [ -n "$CARGO_FEATURES" ]; then \+ cargo chef cook --release --features "$CARGO_FEATURES" --recipe-path recipe.json; \+ else \+ cargo chef cook --release --recipe-path recipe.json; \+ fi++COPY packages/sie_server_rust/Cargo.toml packages/sie_server_rust/Cargo.lock ./+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+COPY packages/sie_server_rust/src/ src/++RUN --mount=type=cache,target=/usr/local/cargo/registry \+ --mount=type=cache,target=/build/target \+ if [ -n "$CARGO_FEATURES" ]; then \+ cargo build --locked --release --features "$CARGO_FEATURES" --bin sie-server-rust; \+ else \+ cargo build --locked --release --bin sie-server-rust; \+ fi \+ && ls -lh target/release/sie-server-rust \+ && test "$(wc -c < target/release/sie-server-rust)" -gt 1000000 \+ && cp target/release/sie-server-rust /usr/local/bin/sie-server-rust++FROM gcr.io/distroless/cc-debian12:nonroot AS runtime++COPY --from=builder /usr/local/bin/sie-server-rust /sie-server-rust++ENV SIE_IPC_SOCKET_PATH=/var/run/sie/ipc.sock \+ SIE_BUNDLE=candle \+ SIE_SERVER_HOST=0.0.0.0 \+ SIE_SERVER_PORT=8080 \+ RUST_LOG=info++EXPOSE 8080++USER nonroot:nonroot+ENTRYPOINT ["/sie-server-rust"]++LABEL org.opencontainers.image.title="sie-server-rust" \+ org.opencontainers.image.description="SIE Rust worker process backed by native inference engines." \+ org.opencontainers.image.source="https://github.com/superlinked/sie"diff --git a/packages/sie_server_rust/Dockerfile.candle b/packages/sie_server_rust/Dockerfile.candlenew file mode 100644index 000000000..07606d4f9--- /dev/null+++ b/packages/sie_server_rust/Dockerfile.candle@@ -0,0 +1,114 @@+# syntax=docker/dockerfile:1+#+# SIE Rust Candle Worker Image (CUDA)+#+# Build from repo root:+# docker build -f packages/sie_server_rust/Dockerfile.candle -t sie-server-rust:latest .+#+# This is the production Candle worker image. It builds sie-server-rust with+# Candle CUDA kernels linked into the Rust binary and runs the IPC worker used+# by the sidecar for engine=candle pools.++ARG CUDA_VERSION=12.4.1+ARG RUST_VERSION=1.97.0+# Candle CUDA kernels cannot detect compute capability during Docker builds.+# Local builds default to the currently supported L4 target, and releases publish+# sie-server-rust:<version>-cuda12-sm89. Override for ad-hoc target GPUs when+# needed, e.g. A100=80, H100=90.+ARG CUDA_COMPUTE_CAP=89++FROM nvidia/cuda:${CUDA_VERSION}-cudnn-devel-ubuntu22.04 AS chef++ARG CUDA_COMPUTE_CAP+ARG CUDAFORGE_THREADS=2+ARG CARGO_BUILD_JOBS=2+# A cold candle-flash-attn build compiles many large CUDA translation units.+# Bound both its inner nvcc pool and Cargo's outer job pool so 16 GiB builders+# do not nondeterministically OOM. Operators can still override either arg.+ENV DEBIAN_FRONTEND=noninteractive \+ CARGO_HOME=/usr/local/cargo \+ CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS} \+ CUDAFORGE_THREADS=${CUDAFORGE_THREADS} \+ RUSTUP_HOME=/usr/local/rustup \+ CUDA_COMPUTE_CAP=${CUDA_COMPUTE_CAP} \+ PATH=/usr/local/cargo/bin:$PATH++RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \+ --mount=type=cache,target=/var/lib/apt/lists,sharing=locked \+ apt-get update && apt-get install -y --no-install-recommends \+ build-essential \+ ca-certificates \+ curl \+ git \+ libssl-dev \+ pkg-config++ARG RUST_VERSION+RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \+ | sh -s -- -y --profile minimal --default-toolchain "${RUST_VERSION}" \+ && cargo install cargo-chef --locked --version 0.1.77++WORKDIR /build++FROM chef AS planner+COPY packages/sie_server_rust/Cargo.toml packages/sie_server_rust/Cargo.lock ./+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+COPY packages/sie_server_rust/src/ src/+RUN cargo chef prepare --recipe-path recipe.json++FROM chef AS builder+COPY --from=planner /build/recipe.json recipe.json+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+RUN --mount=type=cache,id=sie-server-rust-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \+ --mount=type=cache,id=sie-server-rust-target-${CUDA_COMPUTE_CAP},target=/build/target,sharing=locked \+ cargo chef cook --release --features cuda --recipe-path recipe.json++COPY packages/sie_server_rust/Cargo.toml packages/sie_server_rust/Cargo.lock ./+COPY packages/sie_server_rust/vendor/ vendor/+COPY packages/sie_telemetry/ /sie_telemetry/+COPY packages/sie_server_rust/src/ src/++RUN --mount=type=cache,id=sie-server-rust-cargo-registry,target=/usr/local/cargo/registry,sharing=locked \+ --mount=type=cache,id=sie-server-rust-target-${CUDA_COMPUTE_CAP},target=/build/target,sharing=locked \+ cargo build --locked --release --features cuda --bin sie-server-rust \+ && ls -lh target/release/sie-server-rust \+ && test "$(wc -c < target/release/sie-server-rust)" -gt 1000000 \+ && cp target/release/sie-server-rust /usr/local/bin/sie-server-rust++FROM nvidia/cuda:${CUDA_VERSION}-runtime-ubuntu22.04 AS runtime++ARG CUDA_COMPUTE_CAP++ENV DEBIAN_FRONTEND=noninteractive++RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \+ --mount=type=cache,target=/var/lib/apt/lists,sharing=locked \+ apt-get update && apt-get install -y --no-install-recommends \+ ca-certificates \+ libssl3 \+ && groupadd -g 1000 sie \+ && useradd -u 1000 -g sie -m sie++COPY --from=builder /usr/local/bin/sie-server-rust /sie-server-rust++ENV CUDA_HOME=/usr/local/cuda \+ CUDA_COMPUTE_CAP=${CUDA_COMPUTE_CAP} \+ LD_LIBRARY_PATH=/usr/local/cuda/lib64:${LD_LIBRARY_PATH} \+ NVIDIA_VISIBLE_DEVICES=all \+ NVIDIA_DRIVER_CAPABILITIES=compute,utility \+ SIE_IPC_SOCKET_PATH=/var/run/sie/ipc.sock \+ SIE_BUNDLE=candle \+ SIE_SERVER_HOST=0.0.0.0 \+ SIE_SERVER_PORT=8080 \+ RUST_LOG=info++EXPOSE 8080++USER sie:sie+ENTRYPOINT ["/sie-server-rust"]++LABEL org.opencontainers.image.title="sie-server-rust" \+ org.opencontainers.image.description="SIE Rust worker process backed by native Candle CUDA inference." \+ org.opencontainers.image.source="https://github.com/superlinked/sie"diff --git a/packages/sie_server_rust/src/candle_backend.rs b/packages/sie_server_rust/src/candle_backend.rsnew file mode 100644index 000000000..6e6aa13ad--- /dev/null+++ b/packages/sie_server_rust/src/candle_backend.rs@@ -0,0 +1,7288 @@+//! SIE-shaped native Candle executor for the Rust worker process.++use std::collections::{BTreeMap, HashMap, HashSet};+use std::env;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex, OnceLock, RwLock};+use std::time::{Duration, Instant};++use anyhow::{Context, Result};+use serde::Deserialize;+use serde_json::Value as Json;+use tokio::sync::{OwnedSemaphorePermit, Semaphore};+use tracing::{error, info, warn};++use crate::candle_embedding::{+ CandleEmbeddingModel, CandleEmbeddingModelConfig, CandleEncodeRequest, CandleEncodeResult,+ CandleEncodeStageTimings, CandleF16MultivectorBatch, CandleForwardProfile,+ CandleMultivectorEmbedding, CandlePreparedEncodeRequest, CandleScoreResult,+};+use crate::candle_residency::{CandleResidency, ResidencyPolicy, ResidencyUseGuard};+use crate::candle_splade::CandleSparseEmbedding;+use crate::ipc_types::{+ ApplyModelConfigRequest, BatchOutcome, BatchedF16MultivectorItem, BatchedF16MultivectorOutput,+ DenseOutput, Disposition, EncodeBatchItem, EnsureModelReadyResponse, F16Values, ItemOutcome,+ ModelDescriptor, MultivectorOutput, PreparedTokens, ProcessEncodeBatchRequest,+ ProcessScoreBatchRequest, RawOutput, ReadinessState, ReplaceModelConfigsRequest,+ RunBatchRequest, ScoreBatchItem, ScoreOutputRaw, SetPinnedModelsRequest,+ SetPinnedModelsResponse, SparseOutput, UnitCounts,+};+use crate::observability::metrics::{+ self as managed_metrics, ForwardCompleted, ForwardInputSource, ForwardOutcome,+ ForwardOutputPath, ForwardStage, ForwardState, ModelEvictionReason, ModelLoadOutcome,+ ModelLoadStage, OomOutcome, OomStrategy,+};+use crate::text_prep::TextPrep;++const MODEL_LOAD_WAIT_INTERVAL: Duration = Duration::from_millis(50);+const DEFAULT_SLOW_FORWARD_LOG_MS: f64 = 1_000.0;+const OOM_ERROR_INDICATORS: &[&str] = &[+ "out of memory",+ "cannot allocate memory",+ "failed to allocate",+];++#[derive(Debug, Clone)]+pub struct CandleBackendConfig {+ pub batch_budget: u32,+ pub normalize: bool,+ pub max_concurrent_forwards: usize,+ pub idle_evict_s: Option<Duration>,+ pub oom_recovery: CandleOomRecoveryConfig,+}++impl CandleBackendConfig {+ pub fn new(batch_budget: u32, normalize: bool, max_concurrent_forwards: usize) -> Self {+ Self {+ batch_budget: batch_budget.max(1),+ normalize,+ max_concurrent_forwards: max_concurrent_forwards.max(1),+ idle_evict_s: None,+ oom_recovery: CandleOomRecoveryConfig::default(),+ }+ }++ pub fn with_idle_evict_s(mut self, idle_evict_s: Option<Duration>) -> Self {+ self.idle_evict_s = idle_evict_s;+ self+ }++ pub fn with_oom_recovery(mut self, oom_recovery: CandleOomRecoveryConfig) -> Self {+ self.oom_recovery = oom_recovery;+ self+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CandleOomRecoveryAction {+ CacheClear,+ EvictLru,+ SplitBatch,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CandleOomRecoveryConfig {+ enabled: bool,+ strategy: Vec<CandleOomRecoveryAction>,+ max_split_depth: usize,+ nak_delay_ms: u64,+}++impl Default for CandleOomRecoveryConfig {+ fn default() -> Self {+ Self {+ enabled: true,+ strategy: vec![+ CandleOomRecoveryAction::CacheClear,+ CandleOomRecoveryAction::EvictLru,+ CandleOomRecoveryAction::SplitBatch,+ ],+ max_split_depth: 4,+ nak_delay_ms: 10_000,+ }+ }+}++impl CandleOomRecoveryConfig {+ pub fn from_env() -> Result<Self> {+ let mut config = Self::default();+ if let Some(raw) = env_var("SIE_OOM_RECOVERY__ENABLED") {+ config.enabled = parse_env_bool("SIE_OOM_RECOVERY__ENABLED", &raw)?;+ }+ if let Some(raw) = env_var("SIE_OOM_RECOVERY__STRATEGY") {+ config.strategy = parse_oom_recovery_strategy(&raw)?;+ }+ if let Some(raw) = env_var("SIE_OOM_RECOVERY__MAX_SPLIT_DEPTH") {+ config.max_split_depth = parse_oom_max_split_depth(&raw)?;+ }+ if let Some(raw) = env_var("SIE_OOM_NAK_DELAY_S") {+ config.nak_delay_ms = parse_oom_nak_delay_ms(&raw)?;+ }+ let kill_switch = env_var("SIE_DISABLE_OOM_RECOVERY");+ apply_oom_recovery_kill_switch(&mut config, kill_switch.as_deref());+ Ok(config)+ }+}++#[derive(Clone)]+pub struct CandleBackend {+ config: CandleBackendConfig,+ catalog: Arc<RwLock<HashMap<String, ModelRuntimeConfig>>>,+ loaded_embeddings: Arc<Mutex<CandleResidency<LoadedEmbeddingModel>>>,+ loading_embeddings: Arc<Mutex<HashSet<String>>>,+ preload_models: Arc<RwLock<HashSet<String>>>,+ pinned_models: Arc<RwLock<HashSet<String>>>,+ idle_evictor: Arc<Mutex<Option<IdleEvictorState>>>,+}++struct IdleEvictorState {+ abort_handle: tokio::task::AbortHandle,+ finished: Arc<AtomicBool>,+ stop_requested: Arc<AtomicBool>,+}++impl IdleEvictorState {+ fn is_running(&self) -> bool {+ !self.finished.load(Ordering::Relaxed)+ }++ fn abort(self) -> bool {+ let was_running = self.is_running();+ self.stop_requested.store(true, Ordering::Relaxed);+ self.abort_handle.abort();+ was_running+ }+}++struct LoadedEmbeddingModel {+ model: Arc<CandleEmbeddingModel>,+ forward_permits: Arc<Semaphore>,+}++struct ModelExecution<T> {+ lock_wait_ms: f64,+ result: T,+}++struct ForwardSlot {+ _permit: OwnedSemaphorePermit,+ wait_ms: f64,+}++impl LoadedEmbeddingModel {+ fn new(model: CandleEmbeddingModel, max_concurrent_forwards: usize) -> Self {+ Self {+ model: Arc::new(model),+ forward_permits: Arc::new(Semaphore::new(max_concurrent_forwards.max(1))),+ }+ }++ async fn acquire_forward_slot(&self) -> Result<ForwardSlot> {+ let wait_start = Instant::now();+ let permit = Arc::clone(&self.forward_permits)+ .acquire_owned()+ .await+ .map_err(|_| anyhow::anyhow!("Candle forward semaphore closed"))?;+ let wait_ms = elapsed_ms(wait_start);+ Ok(ForwardSlot {+ _permit: permit,+ wait_ms,+ })+ }++ fn with_model<T>(+ &self,+ slot: ForwardSlot,+ f: impl FnOnce(&CandleEmbeddingModel) -> T,+ ) -> ModelExecution<T> {+ let result = f(&self.model);+ drop(slot._permit);+ ModelExecution {+ lock_wait_ms: slot.wait_ms,+ result,+ }+ }++ fn first(&self) -> Arc<CandleEmbeddingModel> {+ Arc::clone(&self.model)+ }+}++struct LoadedEmbeddingModelUse {+ model_id: String,+ model: Arc<LoadedEmbeddingModel>,+ _residency_use: ResidencyUseGuard<LoadedEmbeddingModel>,+}++struct EncodeGroupExecution {+ encoded: Result<CandleEncodeResult>,+ stats: EncodeGroupStats,+ lock_wait_ms: f64,+ encode_elapsed_ms: f64,+ encode_source: &'static str,+}++#[derive(Debug, Clone)]+struct PreparedScoreItem {+ query: CandleEncodeRequest,+ docs: Vec<CandleEncodeRequest>,+ item_ids: Vec<String>,+ normalize: bool,+ work_budget: usize,+ prepared_tokens: Option<PreparedTokens>,+ allow_prepared_tokens: bool,+}++struct ScoreItemExecution {+ scored: Result<CandleScoreResult>,+ lock_wait_ms: f64,+ wall_ms: f64,+}++#[derive(Debug, Clone)]+struct EncodeItemIdentity {+ position: usize,+ work_item_id: String,+ request_id: String,+ item_index: u32,+}++type PreparedEncodeGroup = Vec<(usize, PreparedEncodeItem)>;+type EncodeGroupKey = (EncodeOutputKind, String, bool, bool, String);++#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum EncodeOutputKind {+ Dense,+ Sparse,+ Multivector,+}++fn default_normalize(output_kind: EncodeOutputKind, configured_default: bool) -> bool {+ match output_kind {+ EncodeOutputKind::Sparse => false,+ EncodeOutputKind::Dense | EncodeOutputKind::Multivector => configured_default,+ }+}++#[derive(Clone, Copy)]+struct EncodeGroupContext<'a> {+ model_id: &'a str,+ output_kind: EncodeOutputKind,+ pooling: &'a str,+ normalize: bool,+ is_query: bool,+ output_dtype: &'a str,+ accepts_batched_f16_multivectors: bool,+}++struct EncodeGroupRecoveryContext<'a> {+ model_id: &'a str,+ telemetry_model_id: &'a str,+ active_model_id: &'a str,+ output_kind: EncodeOutputKind,+ pooling: String,+ normalize: bool,+ is_query: bool,+ output_dtype: String,+ accepts_batched_f16_multivectors: bool,+}++enum EncodeGroupAttempt {+ Executed {+ group: PreparedEncodeGroup,+ execution: Box<EncodeGroupExecution>,+ },+ FailedBeforeExecution {+ identities: Vec<EncodeItemIdentity>,+ message: String,+ },+}++enum EncodeGroupOutcome {+ Success {+ items: usize,+ },+ Oom {+ group: PreparedEncodeGroup,+ error: anyhow::Error,+ },+ Failed,+}++#[derive(Debug, PartialEq, Eq)]+enum OomRecoveryStep {+ RetryAfterCacheClear,+ RetryAfterEviction(String),+ SplitBatch,+ Terminal,+}++struct SlowEncodeLogContext<'a> {+ model_id: &'a str,+ pooling: &'a str,+ normalize: bool,+ stats: &'a EncodeGroupStats,+ first_item: Option<&'a PreparedEncodeItem>,+ ok: bool,+ lock_wait_ms: f64,+ encode_elapsed_ms: f64,+ encode_source: &'static str,+}++struct EncodeGroupModelContext {+ loaded: Arc<LoadedEmbeddingModel>,+ slot: ForwardSlot,+ output_kind: EncodeOutputKind,+ pooling: String,+ normalize: bool,+ is_query: bool,+ output_dtype: String,+}++fn maybe_log_slow_encode_group(ctx: SlowEncodeLogContext<'_>) {+ let Some(threshold_ms) = candle_slow_forward_log_threshold_ms() else {+ return;+ };+ let slow_encode = ctx.encode_elapsed_ms >= threshold_ms;+ let slow_lock = ctx.lock_wait_ms >= threshold_ms;+ if !(slow_encode || slow_lock) {+ return;+ }++ let first_work_item_id = ctx+ .first_item+ .map(|item| item.work_item_id.as_str())+ .unwrap_or("");+ let first_request_id = ctx+ .first_item+ .map(|item| item.request_id.as_str())+ .unwrap_or("");+ let first_item_index = ctx+ .first_item+ .map(|item| item.item_index)+ .unwrap_or_default();+ let first_item_is_query = ctx.first_item.is_some_and(|item| item.is_query);+ warn!(+ model_id = ctx.model_id,+ group_items = ctx.stats.items,+ pooling = ctx.pooling,+ normalize = ctx.normalize,+ ok = ctx.ok,+ threshold_ms,+ slow_encode,+ slow_lock,+ lock_wait_ms = ctx.lock_wait_ms,+ encode_elapsed_ms = ctx.encode_elapsed_ms,+ encode_source = ctx.encode_source,+ prepared_items = ctx.stats.prepared_items,+ prepared_sequences = ctx.stats.prepared_sequences,+ prepared_tokens_total = ctx.stats.prepared_tokens_total,+ prepared_tokens_min = ctx.stats.prepared_tokens_min,+ prepared_tokens_max = ctx.stats.prepared_tokens_max,+ prepared_max_seq_len = ctx.stats.prepared_max_seq_len,+ text_chars_total = ctx.stats.text_chars_total,+ text_chars_min = ctx.stats.text_chars_min,+ text_chars_max = ctx.stats.text_chars_max,+ first_work_item_id,+ first_request_id,+ first_item_index,+ first_item_is_query,+ "Slow Candle embedding encode group"+ );+}++fn encode_group_on_model(+ ctx: EncodeGroupModelContext,+ group: PreparedEncodeGroup,+) -> (PreparedEncodeGroup, EncodeGroupExecution) {+ let stats = EncodeGroupStats::from_group(&group);+ let requests: Vec<CandleEncodeRequest> = group+ .iter()+ .map(|(_, item)| CandleEncodeRequest {+ text: item.text.clone(),+ })+ .collect();+ let encode_start = Instant::now();+ let mut encode_source = "raw";+ let execution = ctx.loaded.with_model(ctx.slot, |model| {+ if let Some(prepared_requests) = prepared_requests_for_group(model, &group) {+ encode_source = "prepared";+ match ctx.output_kind {+ EncodeOutputKind::Dense => {+ model.encode_prepared(&prepared_requests, &ctx.pooling, ctx.normalize)+ }+ EncodeOutputKind::Sparse => model.encode_prepared_sparse(&prepared_requests),+ EncodeOutputKind::Multivector => model+ .encode_prepared_multivector_intermediate(+ &prepared_requests,+ ctx.normalize,+ ctx.is_query,+ &ctx.output_dtype,+ )+ .and_then(|intermediate| intermediate.finish()),+ }+ } else {+ match ctx.output_kind {+ EncodeOutputKind::Dense => model.encode(&requests, &ctx.pooling, ctx.normalize),+ EncodeOutputKind::Sparse => model.encode_sparse(&requests),+ EncodeOutputKind::Multivector => model+ .encode_multivector_intermediate(+ &requests,+ ctx.normalize,+ ctx.is_query,+ &ctx.output_dtype,+ )+ .and_then(|intermediate| intermediate.finish()),+ }+ }+ });+ let encoded = execution.result;+ let encode_elapsed_ms = elapsed_ms(encode_start);+ let execution = EncodeGroupExecution {+ encoded,+ stats,+ lock_wait_ms: execution.lock_wait_ms,+ encode_elapsed_ms,+ encode_source,+ };+ (group, execution)+}++fn forward_output_path(context: EncodeGroupContext<'_>) -> ForwardOutputPath {+ match context.output_kind {+ EncodeOutputKind::Dense => ForwardOutputPath::Dense,+ EncodeOutputKind::Sparse => ForwardOutputPath::Sparse,+ EncodeOutputKind::Multivector if context.output_dtype == "float32" => {+ ForwardOutputPath::MultivectorF32+ }+ EncodeOutputKind::Multivector if context.accepts_batched_f16_multivectors => {+ ForwardOutputPath::MultivectorF16Batched+ }+ EncodeOutputKind::Multivector => ForwardOutputPath::MultivectorF16Individual,+ }+}++fn forward_input_source(source: &str) -> ForwardInputSource {+ match source {+ "prepared" => ForwardInputSource::Prepared,+ "raw" => ForwardInputSource::Raw,+ _ => ForwardInputSource::Other,+ }+}++fn forward_stage_durations(+ stages: CandleEncodeStageTimings,+ profile: Option<CandleForwardProfile>,+) -> Vec<(ForwardStage, f64)> {+ let mut values = vec![+ (ForwardStage::Forward, stages.forward_ms / 1_000.0),+ (ForwardStage::Pool, stages.pool_ms / 1_000.0),+ (ForwardStage::Normalize, stages.normalize_ms / 1_000.0),+ (ForwardStage::Conversion, stages.conversion_ms / 1_000.0),+ (+ ForwardStage::ConversionTensorReadback,+ stages.conversion_tensor_readback_ms / 1_000.0,+ ),+ (+ ForwardStage::ConversionHostPack,+ stages.conversion_host_pack_ms / 1_000.0,+ ),+ (ForwardStage::Inference, stages.inference_ms / 1_000.0),+ ];+ match profile {+ Some(CandleForwardProfile::XlmRoberta(profile)) => values.extend([+ (+ ForwardStage::XlmRobertaEmbedding,+ profile.embedding_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaAttention,+ profile.attention_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaAttentionQkv,+ profile.attention_qkv_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaAttentionFlash,+ profile.attention_flash_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaAttentionOutputDense,+ profile.attention_output_dense_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaAttentionOutputLayernorm,+ profile.attention_output_layernorm_ms / 1_000.0,+ ),+ (ForwardStage::XlmRobertaFfn, profile.ffn_ms / 1_000.0),+ (+ ForwardStage::XlmRobertaFfnIntermediateDense,+ profile.ffn_intermediate_dense_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaFfnActivation,+ profile.ffn_activation_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaFfnOutputDense,+ profile.ffn_output_dense_ms / 1_000.0,+ ),+ (+ ForwardStage::XlmRobertaFfnOutputLayernorm,+ profile.ffn_output_layernorm_ms / 1_000.0,+ ),+ ]),+ Some(CandleForwardProfile::GteRope(profile)) => values.extend([+ (+ ForwardStage::GteRopeEmbedding,+ profile.embedding_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeRopeSelect,+ profile.rope_select_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttention,+ profile.attention_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttentionQkv,+ profile.attention_qkv_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttentionRotary,+ profile.attention_rotary_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttentionFlash,+ profile.attention_flash_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttentionOutputDense,+ profile.attention_output_dense_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeAttentionOutputLayernorm,+ profile.attention_output_layernorm_ms / 1_000.0,+ ),+ (ForwardStage::GteRopeFfn, profile.ffn_ms / 1_000.0),+ (+ ForwardStage::GteRopeFfnUpGate,+ profile.ffn_up_gate_ms / 1_000.0,+ ),+ (+ ForwardStage::GteRopeFfnActivation,+ profile.ffn_activation_ms / 1_000.0,+ ),+ (ForwardStage::GteRopeFfnDown, profile.ffn_down_ms / 1_000.0),+ (+ ForwardStage::GteRopeFfnOutputLayernorm,+ profile.ffn_output_layernorm_ms / 1_000.0,+ ),+ ]),+ Some(CandleForwardProfile::ModernBert(profile)) => values.extend([+ (+ ForwardStage::ModernBertEmbedding,+ profile.embedding_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertEmbeddingNorm,+ profile.embedding_norm_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertRopeSelect,+ profile.rope_select_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttention,+ profile.attention_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttentionNorm,+ profile.attention_norm_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttentionQkv,+ profile.attention_qkv_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttentionRotary,+ profile.attention_rotary_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttentionFlash,+ profile.attention_flash_ms / 1_000.0,+ ),+ (+ ForwardStage::ModernBertAttentionOutputDense,+ profile.attention_output_dense_ms / 1_000.0,+ ),+ (ForwardStage::ModernBertMlp, profile.mlp_ms / 1_000.0),+ (+ ForwardStage::ModernBertMlpNorm,+ profile.mlp_norm_ms / 1_000.0,+ ),+ (ForwardStage::ModernBertMlpWi, profile.mlp_wi_ms / 1_000.0),+ (+ ForwardStage::ModernBertMlpActivation,+ profile.mlp_activation_ms / 1_000.0,+ ),+ (ForwardStage::ModernBertMlpWo, profile.mlp_wo_ms / 1_000.0),+ (+ ForwardStage::ModernBertFinalNorm,+ profile.final_norm_ms / 1_000.0,+ ),+ ]),+ None => {}+ }+ values+}++fn elapsed_ms(start: Instant) -> f64 {+ start.elapsed().as_secs_f64() * 1000.0+}++fn idle_evict_check_interval(threshold: Duration) -> Duration {+ let secs = threshold.as_secs().saturating_div(2).clamp(1, 60);+ Duration::from_secs(secs)+}++fn env_var(name: &str) -> Option<String> {+ env::var(name)+ .ok()+ .map(|value| value.trim().to_string())+ .filter(|value| !value.is_empty())+}++fn parse_env_bool(name: &str, raw: &str) -> Result<bool> {+ match raw.trim().to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => Ok(true),+ "0" | "false" | "no" | "off" => Ok(false),+ _ => anyhow::bail!("{name} must be a boolean; got {raw:?}"),+ }+}++fn parse_oom_recovery_strategy(raw: &str) -> Result<Vec<CandleOomRecoveryAction>> {+ let trimmed = raw.trim().trim_start_matches('[').trim_end_matches(']');+ let mut strategy = Vec::new();+ for value in trimmed.split(',') {+ let value = value.trim().trim_matches('"').trim_matches('\'').trim();+ if value.is_empty() {+ continue;+ }+ let action = match value {+ "cache_clear" => CandleOomRecoveryAction::CacheClear,+ "evict_lru" => CandleOomRecoveryAction::EvictLru,+ "split_batch" => CandleOomRecoveryAction::SplitBatch,+ _ => anyhow::bail!("unknown SIE_OOM_RECOVERY__STRATEGY action {value:?}"),+ };+ if !strategy.contains(&action) {+ strategy.push(action);+ }+ }+ if strategy.is_empty() {+ anyhow::bail!("SIE_OOM_RECOVERY__STRATEGY must include at least one action");+ }+ Ok(strategy)+}++fn parse_oom_max_split_depth(raw: &str) -> Result<usize> {+ let depth: usize = raw.trim().parse().with_context(|| {+ format!("SIE_OOM_RECOVERY__MAX_SPLIT_DEPTH must be an integer; got {raw:?}")+ })?;+ if depth > 8 {+ anyhow::bail!("SIE_OOM_RECOVERY__MAX_SPLIT_DEPTH must be <= 8; got {depth}");+ }+ Ok(depth)+}++fn parse_oom_nak_delay_ms(raw: &str) -> Result<u64> {+ let seconds: f64 = raw+ .trim()+ .parse()+ .with_context(|| format!("SIE_OOM_NAK_DELAY_S must be a number; got {raw:?}"))?;+ if !seconds.is_finite() || seconds <= 0.0 {+ anyhow::bail!("SIE_OOM_NAK_DELAY_S must be a positive finite number; got {raw:?}");+ }+ Ok((seconds * 1000.0).round() as u64)+}++fn apply_oom_recovery_kill_switch(config: &mut CandleOomRecoveryConfig, raw: Option<&str>) {+ if raw+ .map(|value| {+ matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "1" | "true" | "yes"+ )+ })+ .unwrap_or(false)+ {+ config.enabled = false;+ }+}++fn next_oom_recovery_step(+ strategy: &[CandleOomRecoveryAction],+ cursor: &mut usize,+ mut evict_lru: impl FnMut() -> Option<String>,+) -> OomRecoveryStep {+ while *cursor < strategy.len() {+ let action = strategy[*cursor];+ *cursor += 1;+ match action {+ CandleOomRecoveryAction::CacheClear => {+ clear_candle_allocator_cache();+ return OomRecoveryStep::RetryAfterCacheClear;+ }+ CandleOomRecoveryAction::EvictLru => {+ if let Some(evicted_model_id) = evict_lru() {+ return OomRecoveryStep::RetryAfterEviction(evicted_model_id);+ }+ }+ CandleOomRecoveryAction::SplitBatch => return OomRecoveryStep::SplitBatch,+ }+ }+ OomRecoveryStep::Terminal+}++fn clear_candle_allocator_cache() {+ // Candle does not currently expose a Torch-style allocator cache clear.+}++fn split_encode_group(+ mut group: PreparedEncodeGroup,+) -> (PreparedEncodeGroup, PreparedEncodeGroup) {+ let right = group.split_off(group.len() / 2);+ (group, right)+}++#[derive(Debug, Clone, Default, PartialEq, Eq)]+struct RuntimeDefaults {+ query_template: Option<String>,+ doc_template: Option<String>,+ default_instruction: Option<String>,+ normalize: Option<bool>,+ pooling: Option<String>,+ output_dtype: Option<String>,+ max_batch_tokens: Option<usize>,+ score_strategy: Option<CandleScoreStrategy>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct ModelRuntimeConfig {+ hf_id: String,+ hf_revision: Option<String>,+ max_sequence_length: Option<usize>,+ query_max_length: Option<usize>,+ dense_dim: Option<usize>,+ sparse_dim: Option<usize>,+ multivector_dim: Option<usize>,+ compute_precision: Option<String>,+ profiles: HashMap<String, RuntimeDefaults>,+ routable_model_ids: Vec<String>,+ task_kind: CandleTaskKind,+}++impl ModelRuntimeConfig {+ fn native_sparse_dim(&self) -> Option<usize> {+ (self.dense_dim.is_none() && self.multivector_dim.is_none())+ .then_some(self.sparse_dim)+ .flatten()+ }++ fn native_multivector_dim(&self) -> Option<usize> {+ self.dense_dim+ .is_none()+ .then_some(self.multivector_dim)+ .flatten()+ }++ fn output_types(&self, model_id: &str, requested_profile: Option<&str>) -> Vec<String> {+ let mut outputs = Vec::new();+ if self.task_kind.supports_embedding() {+ if self.dense_dim.is_some() {+ outputs.push("dense".to_string());+ } else if self.native_sparse_dim().is_some() {+ outputs.push("sparse".to_string());+ } else if self.native_multivector_dim().is_some() {+ outputs.push("multivector".to_string());+ } else {+ outputs.push("dense".to_string());+ }+ }+ if self.supports_native_score(model_id, requested_profile) {+ outputs.push("score".to_string());+ }+ outputs+ }++ fn supports_native_score(&self, model_id: &str, requested_profile: Option<&str>) -> bool {+ self.task_kind.supports_score()+ && self.native_multivector_dim().is_some()+ && selected_runtime_defaults(model_id, requested_profile, &self.profiles).score_strategy+ == Some(CandleScoreStrategy::ColbertMaxsim)+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CandleScoreStrategy {+ ColbertMaxsim,+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+enum CandleTaskKind {+ #[default]+ Embedding,+ Rerank,+ EmbeddingAndRerank,+}++impl CandleTaskKind {+ fn supports_embedding(self) -> bool {+ matches!(self, Self::Embedding | Self::EmbeddingAndRerank)+ }++ fn supports_score(self) -> bool {+ matches!(self, Self::Rerank | Self::EmbeddingAndRerank)+ }+}++#[derive(Debug, Deserialize)]+struct ModelConfigYaml {+ sie_id: String,+ #[serde(default)]+ hf_id: Option<String>,+ #[serde(default)]+ hf_revision: Option<String>,+ #[serde(default)]+ max_sequence_length: Option<usize>,+ #[serde(default)]+ tasks: TasksYaml,+ #[serde(default)]+ profiles: BTreeMap<String, ProfileConfigYaml>,+}++#[derive(Debug, Default, Deserialize)]+struct TasksYaml {+ #[serde(default)]+ encode: Option<Json>,+ #[serde(default)]+ score: Option<Json>,+}++#[derive(Debug, Default, Deserialize)]+struct ProfileConfigYaml {+ #[serde(default)]+ extends: Option<String>,+ #[serde(default)]+ max_batch_tokens: Option<usize>,+ #[serde(default)]+ compute_precision: Option<String>,+ #[serde(default)]+ adapter_path: Option<String>,+ #[serde(default)]+ adapter_options: AdapterOptionsYaml,+}++#[derive(Debug, Default, Deserialize)]+struct AdapterOptionsYaml {+ #[serde(default)]+ loadtime: BTreeMap<String, Json>,+ #[serde(default)]+ runtime: BTreeMap<String, Json>,+}++impl CandleBackend {+ pub fn new(config: CandleBackendConfig) -> Self {+ Self {+ config,+ catalog: Arc::new(RwLock::new(HashMap::new())),+ loaded_embeddings: Arc::new(Mutex::new(CandleResidency::default())),+ loading_embeddings: Arc::new(Mutex::new(HashSet::new())),+ preload_models: Arc::new(RwLock::new(HashSet::new())),+ pinned_models: Arc::new(RwLock::new(HashSet::new())),+ idle_evictor: Arc::new(Mutex::new(None)),+ }+ }++ pub fn supports(&self, model_id: &str) -> bool {+ let Some(model_id) = canonical_pinned_model_id(model_id) else {+ return false;+ };+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ self.catalog_config_for(&model_id, &guard)+ .is_some_and(|config| config.routable_model_ids.contains(&model_id))+ }++ /// Resolve request-supplied routing values through the loaded release+ /// catalog before they may become metric attributes.+ pub(crate) fn telemetry_dimensions(+ &self,+ model_id: &str,+ requested_profile: Option<&str>,+ ) -> (String, String) {+ let Some(route) = effective_model_id(model_id, requested_profile) else {+ return ("other".to_string(), "other".to_string());+ };+ let catalog = self.catalog.read().expect("Candle catalog lock poisoned");+ telemetry_dimensions_for_route(&route, &catalog)+ .unwrap_or_else(|| ("other".to_string(), "other".to_string()))+ }++ fn record_model_residency_for_base(+ &self,+ base_model_id: &str,+ loaded: bool,+ eviction_reason: Option<ModelEvictionReason>,+ ) {+ if !managed_metrics::metrics_enabled() {+ return;+ }+ let dimensions = {+ let catalog = self.catalog.read().expect("Candle catalog lock poisoned");+ telemetry_dimensions_for_base_model(base_model_id, &catalog)+ };+ for (model, profile) in dimensions {+ managed_metrics::record_model_residency_changed(+ &model, &profile, loaded,+ // Candle does not expose authoritative resident bytes.+ None,+ );+ if let Some(reason) = eviction_reason {+ managed_metrics::record_model_evicted(&model, &profile, reason);+ }+ }+ }++ fn record_oom_recovery(&self, model_id: &str, strategy: OomStrategy, outcome: OomOutcome) {+ if !managed_metrics::metrics_enabled() {+ return;+ }+ let (model, profile) = self.telemetry_dimensions(model_id, None);+ managed_metrics::record_oom_recovery_completed(&model, &profile, strategy, outcome);+ }++ pub fn supported_models(&self) -> Vec<String> {+ let mut models: Vec<String> = self+ .catalog+ .read()+ .expect("Candle catalog lock poisoned")+ .values()+ .flat_map(|config| config.routable_model_ids.iter().cloned())+ .collect();+ models.sort();+ models.dedup();+ models+ }++ pub fn loaded_models(&self) -> Vec<String> {+ let loaded_model_ids: Vec<String> = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .keys();+ let catalog = self.catalog.read().expect("Candle catalog lock poisoned");+ loaded_model_routes_for_catalog(&loaded_model_ids, &catalog)+ }++ pub fn set_preload_models(&self, models: &[String]) -> u32 {+ let next = normalize_pinned_model_ids(models);+ let preload_count = u32::try_from(next.len()).unwrap_or(u32::MAX);+ {+ let mut preload = self+ .preload_models+ .write()+ .expect("Candle preload-model lock poisoned");+ *preload = next;+ }++ if preload_count > 0 {+ info!(preload_count, "Candle preload model set configured");+ }+ self.refresh_residency_policies();+ self.reconcile_warm_models();+ preload_count+ }++ pub fn set_pinned_models(&self, req: &SetPinnedModelsRequest) -> SetPinnedModelsResponse {+ let next = normalize_pinned_model_ids(&req.models);+ let pinned_count = u32::try_from(next.len()).unwrap_or(u32::MAX);+ let changed = {+ let mut pinned = self+ .pinned_models+ .write()+ .expect("Candle pinned-model lock poisoned");+ if *pinned == next {+ false+ } else {+ *pinned = next;+ true+ }+ };++ if changed {+ info!(pinned_count, "Candle pinned model set updated from sidecar");+ }+ self.refresh_residency_policies();+ self.reconcile_warm_models();+ SetPinnedModelsResponse {+ applied: true,+ pinned_count,+ }+ }++ pub async fn health_ready(&self) -> bool {+ let catalog = self.catalog.read().expect("Candle catalog lock poisoned");+ !catalog.is_empty()+ }++ pub fn start_idle_evictor(&self) -> bool {+ let Some(threshold) = self.config.idle_evict_s else {+ return false;+ };+ let mut idle_evictor = self+ .idle_evictor+ .lock()+ .expect("Candle idle-evictor lock poisoned");+ if idle_evictor+ .as_ref()+ .is_some_and(IdleEvictorState::is_running)+ {+ return false;+ }+ let interval = idle_evict_check_interval(threshold);+ let backend = self.clone();+ let finished = Arc::new(AtomicBool::new(false));+ let stop_requested = Arc::new(AtomicBool::new(false));+ let task_finished = Arc::clone(&finished);+ let task_stop_requested = Arc::clone(&stop_requested);+ let handle = tokio::spawn(async move {+ info!(+ idle_threshold_s = threshold.as_secs(),+ check_interval_s = interval.as_secs_f64(),+ "Candle idle evictor started"+ );+ loop {+ tokio::time::sleep(interval).await;+ if let Some(evicted_model_id) = backend.evict_idle_embedding_model(threshold) {+ info!(+ model_id = %evicted_model_id,+ idle_threshold_s = threshold.as_secs(),+ "Candle idle eviction unloaded resident embedding model"+ );+ }+ }+ });+ let abort_handle = handle.abort_handle();+ tokio::spawn(async move {+ let result = handle.await;+ task_finished.store(true, Ordering::Relaxed);+ let stop_requested = task_stop_requested.load(Ordering::Relaxed);+ match result {+ Ok(()) if stop_requested => {}+ Ok(()) => error!("Candle idle evictor task exited unexpectedly"),+ Err(error) if stop_requested && error.is_cancelled() => {}+ Err(error) => error!(error = %error, "Candle idle evictor task terminated"),+ }+ });+ *idle_evictor = Some(IdleEvictorState {+ abort_handle,+ finished,+ stop_requested,+ });+ true+ }++ pub fn stop_idle_evictor(&self) -> bool {+ let handle = self+ .idle_evictor+ .lock()+ .expect("Candle idle-evictor lock poisoned")+ .take();+ if let Some(handle) = handle {+ return handle.abort();+ }+ false+ }++ pub fn apply_model_config(&self, req: &ApplyModelConfigRequest) -> Result<()> {+ if req.bundle_id.trim().is_empty() {+ anyhow::bail!("bundle_id is required");+ }+ let (sie_id, runtime_config) = parse_runtime_config(&req.model_id, &req.model_config)?;++ let config_changed = self+ .catalog+ .read()+ .expect("Candle catalog lock poisoned")+ .get(&sie_id)+ .is_some_and(|current| current != &runtime_config);+ if config_changed {+ self.evict_embedding_model(&sie_id, ModelEvictionReason::ConfigChange);+ }+ self.catalog+ .write()+ .expect("Candle catalog lock poisoned")+ .insert(sie_id, runtime_config);+ self.refresh_residency_policies();+ self.reconcile_warm_models();+ Ok(())+ }++ pub fn replace_model_configs(&self, req: &ReplaceModelConfigsRequest) -> Result<Vec<String>> {+ if req.bundle_id.trim().is_empty() {+ anyhow::bail!("bundle_id is required");+ }++ let mut next_catalog = HashMap::new();+ let mut applied_models = Vec::new();+ for entry in &req.models {+ let (sie_id, runtime_config) =+ parse_runtime_config(&entry.model_id, &entry.model_config)?;+ applied_models.extend(runtime_config.routable_model_ids.iter().cloned());+ next_catalog.insert(sie_id, runtime_config);+ }+ applied_models.sort();+ applied_models.dedup();++ let current_catalog = self+ .catalog+ .read()+ .expect("Candle catalog lock poisoned")+ .clone();+ let loaded_before = managed_metrics::metrics_enabled().then(|| {+ self.loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .keys()+ });+ self.loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .retain(|model_id| {+ catalog_config_unchanged_for_model(model_id, ¤t_catalog, &next_catalog)+ });+ self.loading_embeddings+ .lock()+ .expect("Candle model loading lock poisoned")+ .retain(|model_id| {+ catalog_config_unchanged_for_model(model_id, ¤t_catalog, &next_catalog)+ });+ if let Some(loaded_before) = loaded_before {+ let loaded_after: HashSet<_> = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .keys()+ .into_iter()+ .collect();+ for evicted_model_id in loaded_before {+ if !loaded_after.contains(&evicted_model_id) {+ self.record_model_residency_for_base(+ &evicted_model_id,+ false,+ Some(ModelEvictionReason::ConfigChange),+ );+ }+ }+ }+ *self.catalog.write().expect("Candle catalog lock poisoned") = next_catalog;+ self.refresh_residency_policies();+ self.reconcile_warm_models();+ Ok(applied_models)+ }++ pub async fn ensure_model_ready(&self, model_id: &str) -> EnsureModelReadyResponse {+ if !self.supports(model_id) {+ return EnsureModelReadyResponse {+ state: ReadinessState::RetryLater,+ batch_budget: None,+ descriptor: None,+ };+ }++ let runtime_config = {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ self.catalog_config_for(model_id, &guard).cloned()+ };+ let Some(runtime_config) = runtime_config else {+ return EnsureModelReadyResponse {+ state: ReadinessState::RetryLater,+ batch_budget: Some(self.config.batch_budget),+ descriptor: None,+ };+ };++ let defaults = self.runtime_defaults_for(model_id, None);+ let task_kind = runtime_config.task_kind;+ if !task_kind.supports_embedding() {+ return EnsureModelReadyResponse {+ state: ReadinessState::RetryLater,+ batch_budget: None,+ descriptor: None,+ };+ }++ match self.embedding_load_state(model_id) {+ Ok(ReadinessState::Ready) => {}+ Ok(state) => {+ return EnsureModelReadyResponse {+ state,+ batch_budget: None,+ descriptor: None,+ };+ }+ Err(error) => {+ warn!(+ model = %model_id,+ error = %error_chain(&error),+ "Candle model readiness failed to start embedding load"+ );+ return EnsureModelReadyResponse {+ state: ReadinessState::RetryLater,+ batch_budget: None,+ descriptor: None,+ };+ }+ }++ let tokenizer_descriptor = self.loaded_tokenizer_descriptor(model_id);+ let Some((tokenizer_path, tokenizer_id, max_seq_len)) = tokenizer_descriptor else {+ return EnsureModelReadyResponse {+ state: ReadinessState::LoadingInProgress,+ batch_budget: None,+ descriptor: None,+ };+ };++ EnsureModelReadyResponse {+ state: ReadinessState::Ready,+ batch_budget: Some(self.config.batch_budget),+ descriptor: Some(ModelDescriptor {+ tokenizer_path: Some(tokenizer_path),+ tokenizer_id: Some(tokenizer_id),+ output_types: runtime_config.output_types(model_id, None),+ supports_run_batch: true,+ // The loaded model has already clamped the catalog request to+ // the checkpoint's positional-embedding capacity.+ max_seq_len: u32::try_from(max_seq_len).ok(),+ default_query_template: if task_kind.supports_embedding() {+ defaults.query_template+ } else {+ None+ },+ default_doc_template: if task_kind.supports_embedding() {+ defaults.doc_template+ } else {+ None+ },+ }),+ }+ }++ pub async fn process_encode_batch(&self, req: ProcessEncodeBatchRequest) -> BatchOutcome {+ let ProcessEncodeBatchRequest {+ model_id,+ items,+ accepts_batched_f16_multivectors,+ } = req;+ self.encode_items(&model_id, items, accepts_batched_f16_multivectors)+ .await+ }++ pub async fn process_score_batch(&self, req: ProcessScoreBatchRequest) -> BatchOutcome {+ self.score_items(&req.model_id, req.items).await+ }++ pub async fn run_batch(&self, req: RunBatchRequest) -> BatchOutcome {+ let model_id = req.model_id;+ let accepts_batched_f16_multivectors = req.accepts_batched_f16_multivectors;+ let mut encode_items = Vec::with_capacity(req.items.len());+ let mut encode_positions = Vec::with_capacity(req.items.len());+ let mut score_items = Vec::with_capacity(req.items.len());+ let mut score_positions = Vec::with_capacity(req.items.len());+ let mut outcomes: Vec<Option<ItemOutcome>> = vec![None; req.items.len()];++ for (position, item) in req.items.into_iter().enumerate() {+ match item.op.as_str() {+ "encode" => match item.encode {+ Some(encode) => {+ encode_items.push(encode);+ encode_positions.push(position);+ }+ None => {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_invalid_batch_item",+ "RunBatch encode item is missing encode payload",+ ))+ }+ },+ "score" => match item.score {+ Some(score) => {+ score_items.push(score);+ score_positions.push(position);+ }+ None => {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_invalid_batch_item",+ "RunBatch score item is missing score payload",+ ))+ }+ },+ _ => {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_unsupported_operation",+ "Candle Rust worker supports encode and score batches",+ ))+ }+ }+ }++ let mut batched_f16_multivectors = Vec::new();+ if !encode_items.is_empty() {+ let encoded = self+ .encode_items(&model_id, encode_items, accepts_batched_f16_multivectors)+ .await;+ batched_f16_multivectors = encoded.batched_f16_multivectors;+ for (position, outcome) in encode_positions.into_iter().zip(encoded.outcomes) {+ outcomes[position] = Some(outcome);+ }+ }+ if !score_items.is_empty() {+ let scored = self.score_items(&model_id, score_items).await.outcomes;+ for (position, outcome) in score_positions.into_iter().zip(scored) {+ outcomes[position] = Some(outcome);+ }+ }++ BatchOutcome {+ outcomes: outcomes+ .into_iter()+ .enumerate()+ .map(|(idx, outcome)| {+ outcome.unwrap_or_else(|| {+ identity_error_outcome(+ "",+ "",+ idx as u32,+ "candle_internal_error",+ "missing Candle run_batch outcome",+ )+ })+ })+ .collect(),+ batched_f16_multivectors,+ }+ }++ async fn encode_items(+ &self,+ model_id: &str,+ items: Vec<EncodeBatchItem>,+ accepts_batched_f16_multivectors: bool,+ ) -> BatchOutcome {+ let mut outcomes: Vec<Option<ItemOutcome>> = vec![None; items.len()];+ let mut batched_f16_multivectors = Vec::new();+ let mut groups: BTreeMap<EncodeGroupKey, PreparedEncodeGroup> = BTreeMap::new();+ let mut load_model_id: Option<String> = None;+ for (position, item) in items.iter().enumerate() {+ if let Some(message) = profile_option_error(item.options.as_ref()) {+ outcomes[position] =+ Some(error_outcome(item, "candle_unsupported_request", &message));+ continue;+ }+ let requested_profile =+ requested_item_profile(item.options.as_ref(), item.profile_id.as_deref());+ let Some(effective_model_id) = effective_model_id(model_id, requested_profile)+ .filter(|model_id| self.supports(model_id))+ else {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_model",+ "model is not supported by this Rust Candle worker",+ ));+ continue;+ };+ let options = item.options.as_ref();+ if let Some(message) = output_dtype_type_error(options) {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_output_dtype",+ &message,+ ));+ continue;+ }+ let option_output_types = option_output_types(options);+ let requested_output_types = option_output_types+ .as_deref()+ .or(item.output_types.as_deref());+ let Some(output_kind) =+ self.encode_output_kind(&effective_model_id, requested_output_types)+ else {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_request",+ "Candle Rust worker supports native dense, sparse SPLADE, or ColBERT multivector text encode with SIE text-prep options only",+ ));+ continue;+ };+ let defaults = self.runtime_defaults_for(&effective_model_id, requested_profile);+ let output_dtype = option_str(options, "output_dtype")+ .map(str::to_string)+ .or(defaults.output_dtype.clone());+ if let Some(message) = output_dtype_error_for_kind(output_dtype.as_deref(), output_kind)+ {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_output_dtype",+ &message,+ ));+ continue;+ }+ if !self.supports_encode_options(&effective_model_id, item) {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_request",+ "Candle Rust worker supports native text encode with SIE text-prep options only",+ ));+ continue;+ }+ if let Err(message) = item_id(&item.item) {+ outcomes[position] = Some(error_outcome(item, "candle_invalid_item", message));+ continue;+ }+ let raw_text = match extract_text(&item.item) {+ Ok(text) => text,+ Err(message) => {+ outcomes[position] = Some(error_outcome(item, "candle_invalid_item", message));+ continue;+ }+ };++ let default_instruction = defaults.default_instruction.as_deref();+ let instruction =+ resolve_instruction(item.instruction.as_deref(), options, default_instruction);+ let query_template = option_str(options, "query_template")+ .map(str::to_string)+ .or(defaults.query_template);+ let doc_template = option_str(options, "doc_template")+ .map(str::to_string)+ .or(defaults.doc_template);+ let prepared_tokens = if instruction.is_none() {+ item.prepared_tokens.clone()+ } else {+ None+ };+ let pooling = option_str(options, "pooling")+ .map(str::to_string)+ .or(defaults.pooling)+ .unwrap_or_else(|| match output_kind {+ EncodeOutputKind::Sparse => "splade".to_string(),+ EncodeOutputKind::Dense | EncodeOutputKind::Multivector => "mean".to_string(),+ });+ let normalize = option_bool(options, "normalize")+ .or(defaults.normalize)+ .unwrap_or_else(|| default_normalize(output_kind, self.config.normalize));+ match output_kind {+ EncodeOutputKind::Sparse if pooling != "splade" => {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_pooling",+ "Candle Rust worker requires splade pooling for native sparse embeddings",+ ));+ continue;+ }+ EncodeOutputKind::Sparse if normalize => {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_request",+ "Candle Rust worker requires normalize=false for native sparse embeddings",+ ));+ continue;+ }+ EncodeOutputKind::Dense | EncodeOutputKind::Multivector+ if !matches!(pooling.as_str(), "mean" | "cls") =>+ {+ outcomes[position] = Some(error_outcome(+ item,+ "candle_unsupported_pooling",+ "Candle Rust worker supports mean and cls pooling for native dense and multivector embeddings",+ ));+ continue;+ }+ _ => {}+ }++ load_model_id.get_or_insert(effective_model_id);+ let output_wire_dtype = match output_kind {+ EncodeOutputKind::Dense | EncodeOutputKind::Sparse => "float32",+ EncodeOutputKind::Multivector => multivector_wire_dtype(output_dtype.as_deref()),+ }+ .to_string();+ let text = TextPrep {+ instruction,+ is_query: item.is_query,+ query_template: query_template.as_deref(),+ doc_template: doc_template.as_deref(),+ }+ .apply(raw_text);++ groups+ .entry((+ output_kind,+ pooling,+ normalize,+ item.is_query,+ output_wire_dtype,+ ))+ .or_default()+ .push((+ position,+ PreparedEncodeItem {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ text,+ is_query: item.is_query,+ output_dtype,+ prepared_tokens,+ },+ ));+ }++ let loaded_model = if groups.is_empty() {+ None+ } else {+ let load_model_id = load_model_id+ .as_deref()+ .expect("load_model_id is set when encode groups are non-empty");+ match self.embedding_model(load_model_id) {+ Ok(loaded_model) => Some(loaded_model),+ Err(error) => {+ self.mark_model_load_error_outcomes(+ load_model_id,+ &groups,+ &error,+ &mut outcomes,+ );+ None+ }+ }+ };++ let Some(loaded_model_use) = loaded_model else {+ return BatchOutcome {+ outcomes: outcomes+ .into_iter()+ .enumerate()+ .map(|(idx, outcome)| {+ outcome.unwrap_or_else(|| {+ identity_error_outcome(+ "",+ "",+ idx as u32,+ "candle_internal_error",+ "missing Candle encode outcome",+ )+ })+ })+ .collect(),+ batched_f16_multivectors,+ };+ };+ let active_model_id = loaded_model_use.model_id.clone();+ let loaded_model = Arc::clone(&loaded_model_use.model);+ let telemetry_model_id = load_model_id.as_deref().unwrap_or(model_id);++ for ((output_kind, pooling, normalize, is_query, output_dtype), group) in groups {+ self.encode_group_with_oom_recovery(+ EncodeGroupRecoveryContext {+ model_id,+ telemetry_model_id,+ active_model_id: &active_model_id,+ output_kind,+ pooling,+ normalize,+ is_query,+ output_dtype,+ accepts_batched_f16_multivectors,+ },+ Arc::clone(&loaded_model),+ group,+ &mut outcomes,+ &mut batched_f16_multivectors,+ )+ .await;+ }++ BatchOutcome {+ outcomes: outcomes+ .into_iter()+ .enumerate()+ .map(|(idx, outcome)| {+ outcome.unwrap_or_else(|| {+ identity_error_outcome(+ "",+ "",+ idx as u32,+ "candle_internal_error",+ "missing Candle encode outcome",+ )+ })+ })+ .collect(),+ batched_f16_multivectors,+ }+ }++ fn mark_model_load_error_outcomes(+ &self,+ load_model_id: &str,+ groups: &BTreeMap<EncodeGroupKey, PreparedEncodeGroup>,+ error: &anyhow::Error,+ outcomes: &mut [Option<ItemOutcome>],+ ) {+ if is_oom_error(error) {+ let retry_outcomes = groups.values().map(Vec::len).sum::<usize>();+ warn!(+ model_id = load_model_id,+ retry_outcomes,+ nak_delay_ms = self.config.oom_recovery.nak_delay_ms,+ error = %error_chain(error),+ "Candle embedding model load exhausted OOM recovery; marking encode items for retry"+ );+ }+ for group in groups.values() {+ for (position, item) in group {+ outcomes[*position] = Some(model_load_error_outcome(+ item,+ error,+ self.config.oom_recovery.nak_delay_ms,+ ));+ }+ }+ }++ async fn encode_group_with_oom_recovery(+ &self,+ recovery_context: EncodeGroupRecoveryContext<'_>,+ loaded_model: Arc<LoadedEmbeddingModel>,+ group: PreparedEncodeGroup,+ outcomes: &mut [Option<ItemOutcome>],+ batched_f16_multivectors: &mut Vec<BatchedF16MultivectorOutput>,+ ) {+ let context = EncodeGroupContext {+ model_id: recovery_context.model_id,+ output_kind: recovery_context.output_kind,+ pooling: &recovery_context.pooling,+ normalize: recovery_context.normalize,+ is_query: recovery_context.is_query,+ output_dtype: &recovery_context.output_dtype,+ accepts_batched_f16_multivectors: recovery_context.accepts_batched_f16_multivectors,+ };+ let (mut pending_group, mut last_error, recovery_config) = match self+ .run_and_apply_encode_group(+ context,+ Arc::clone(&loaded_model),+ group,+ outcomes,+ batched_f16_multivectors,+ )+ .await+ {+ EncodeGroupOutcome::Success { .. } | EncodeGroupOutcome::Failed => return,+ EncodeGroupOutcome::Oom { group, error } => {+ let config = self.config.oom_recovery.clone();+ if !config.enabled {+ self.mark_oom_group_retry(context, group, error, config.nak_delay_ms, outcomes);+ return;+ }++ warn!(+ model_id = context.model_id,+ group_items = group.len(),+ pooling = context.pooling,+ normalize = context.normalize,+ is_query = context.is_query,+ error = %error_chain(&error),+ "Candle embedding inference hit OOM; attempting recovery"+ );+ (group, error, config)+ }+ };++ let mut recovery_action_cursor = 0usize;+ let mut pending_oom_strategy: Option<OomStrategy> = None;+ loop {+ let strategy = match next_oom_recovery_step(+ &recovery_config.strategy,+ &mut recovery_action_cursor,+ || {+ let evicted = self.evict_lru_embedding_model_excluding_with_reason(+ recovery_context.active_model_id,+ ModelEvictionReason::OomRecovery,+ );+ if evicted.is_none() {+ info!(+ model_id = context.model_id,+ active_model_id = recovery_context.active_model_id,+ "Candle OOM recovery found no LRU sibling model to evict"+ );+ }+ evicted+ },+ ) {+ OomRecoveryStep::RetryAfterCacheClear => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ previous,+ OomOutcome::Failed,+ );+ }+ OomStrategy::CacheClear+ }+ OomRecoveryStep::RetryAfterEviction(evicted_model_id) => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ previous,+ OomOutcome::Failed,+ );+ }+ warn!(+ model_id = context.model_id,+ active_model_id = recovery_context.active_model_id,+ evicted_model_id = %evicted_model_id,+ error = %error_chain(&last_error),+ "Candle OOM recovery evicted LRU sibling model and retrying"+ );+ OomStrategy::EvictLru+ }+ OomRecoveryStep::SplitBatch => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ previous,+ OomOutcome::Failed,+ );+ }+ let (succeeded, oom_failed) = self+ .encode_group_split_recovery(+ context,+ Arc::clone(&loaded_model),+ pending_group,+ &recovery_config,+ outcomes,+ batched_f16_multivectors,+ )+ .await;+ let outcome = if oom_failed > 0 {+ OomOutcome::Terminal+ } else if succeeded > 0 {+ OomOutcome::Success+ } else {+ OomOutcome::Failed+ };+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ OomStrategy::SplitBatch,+ outcome,+ );+ return;+ }+ OomRecoveryStep::Terminal => {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ pending_oom_strategy.unwrap_or(OomStrategy::Other),+ OomOutcome::Terminal,+ );+ self.mark_oom_group_retry(+ context,+ pending_group,+ last_error,+ recovery_config.nak_delay_ms,+ outcomes,+ );+ return;+ }+ };++ match self+ .run_and_apply_encode_group(+ context,+ Arc::clone(&loaded_model),+ pending_group,+ outcomes,+ batched_f16_multivectors,+ )+ .await+ {+ EncodeGroupOutcome::Success { .. } => {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ strategy,+ OomOutcome::Success,+ );+ return;+ }+ EncodeGroupOutcome::Failed => {+ self.record_oom_recovery(+ recovery_context.telemetry_model_id,+ strategy,+ OomOutcome::Failed,+ );+ return;+ }+ EncodeGroupOutcome::Oom { group, error } => {+ pending_group = group;+ last_error = error;+ pending_oom_strategy = Some(strategy);+ }+ };+ }+ }++ async fn encode_group_split_recovery(+ &self,+ context: EncodeGroupContext<'_>,+ loaded_model: Arc<LoadedEmbeddingModel>,+ group: PreparedEncodeGroup,+ config: &CandleOomRecoveryConfig,+ outcomes: &mut [Option<ItemOutcome>],+ batched_f16_multivectors: &mut Vec<BatchedF16MultivectorOutput>,+ ) -> (usize, usize) {+ let mut stack = vec![(group, 0usize)];+ let mut succeeded = 0usize;+ let mut oom_failed = 0usize;++ while let Some((group, depth)) = stack.pop() {+ let group_items = group.len();+ match self+ .run_and_apply_encode_group(+ context,+ Arc::clone(&loaded_model),+ group,+ outcomes,+ batched_f16_multivectors,+ )+ .await+ {+ EncodeGroupOutcome::Success { items } => {+ succeeded += items;+ }+ EncodeGroupOutcome::Failed => {}+ EncodeGroupOutcome::Oom { group, error } => {+ if group_items <= 1 || depth >= config.max_split_depth {+ oom_failed += group_items;+ self.mark_oom_group_retry(+ context,+ group,+ error,+ config.nak_delay_ms,+ outcomes,+ );+ continue;+ }++ let (left, right) = split_encode_group(group);+ stack.push((right, depth + 1));+ stack.push((left, depth + 1));+ }+ }+ }++ (succeeded, oom_failed)+ }++ async fn run_and_apply_encode_group(+ &self,+ context: EncodeGroupContext<'_>,+ loaded_model: Arc<LoadedEmbeddingModel>,+ group: PreparedEncodeGroup,+ outcomes: &mut [Option<ItemOutcome>],+ batched_f16_multivectors: &mut Vec<BatchedF16MultivectorOutput>,+ ) -> EncodeGroupOutcome {+ match self+ .run_encode_group_attempt(context, loaded_model, group)+ .await+ {+ EncodeGroupAttempt::Executed { group, execution } => self.apply_encode_group_execution(+ context,+ group,+ *execution,+ outcomes,+ batched_f16_multivectors,+ ),+ EncodeGroupAttempt::FailedBeforeExecution {+ identities,+ message,+ } => {+ for item in identities {+ outcomes[item.position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ &message,+ ));+ }+ EncodeGroupOutcome::Failed+ }+ }+ }++ async fn run_encode_group_attempt(+ &self,+ context: EncodeGroupContext<'_>,+ loaded_model: Arc<LoadedEmbeddingModel>,+ group: PreparedEncodeGroup,+ ) -> EncodeGroupAttempt {+ let fallback_items = encode_item_identities(&group);+ let output_path = forward_output_path(context);+ let telemetry_dimensions = managed_metrics::metrics_enabled()+ .then(|| self.telemetry_dimensions(context.model_id, None));+ let permit_started = telemetry_dimensions.as_ref().map(|_| Instant::now());+ let waiting_guard = telemetry_dimensions.as_ref().map(|(model, profile)| {+ managed_metrics::begin_forward_activity(+ model,+ profile,+ ForwardState::Waiting,+ self.config.max_concurrent_forwards,+ )+ });+ let slot_result = loaded_model.acquire_forward_slot().await;+ drop(waiting_guard);+ if let (Some((model, profile)), Some(started)) =+ (telemetry_dimensions.as_ref(), permit_started)+ {+ managed_metrics::record_forward_permit_wait(+ model,+ profile,+ output_path,+ started.elapsed().as_secs_f64(),+ );+ }+ let slot = match slot_result {+ Ok(slot) => slot,+ Err(error) => {+ error!(+ model_id = context.model_id,+ pooling = context.pooling,+ normalize = context.normalize,+ error = %error,+ "Candle embedding forward permit acquisition failed"+ );+ return EncodeGroupAttempt::FailedBeforeExecution {+ identities: fallback_items,+ message: format!("Candle embedding forward permit acquisition failed: {error}"),+ };+ }+ };+ let model_for_task = Arc::clone(&loaded_model);+ let task_context = EncodeGroupModelContext {+ loaded: model_for_task,+ slot,+ output_kind: context.output_kind,+ pooling: context.pooling.to_string(),+ normalize: context.normalize,+ is_query: context.is_query,+ output_dtype: context.output_dtype.to_string(),+ };+ let active_guard = telemetry_dimensions.as_ref().map(|(model, profile)| {+ managed_metrics::begin_forward_activity(+ model,+ profile,+ ForwardState::Active,+ self.config.max_concurrent_forwards,+ )+ });+ let joined =+ tokio::task::spawn_blocking(move || encode_group_on_model(task_context, group)).await;+ drop(active_guard);++ match joined {+ Ok((group, execution)) => EncodeGroupAttempt::Executed {+ group,+ execution: Box::new(execution),+ },+ Err(error) => {+ error!(+ model_id = context.model_id,+ pooling = context.pooling,+ normalize = context.normalize,+ error = %error,+ "Candle embedding worker task failed"+ );+ EncodeGroupAttempt::FailedBeforeExecution {+ identities: fallback_items,+ message: format!("Candle embedding worker task failed: {error}"),+ }+ }+ }+ }++ fn apply_encode_group_execution(+ &self,+ context: EncodeGroupContext<'_>,+ group: PreparedEncodeGroup,+ execution: EncodeGroupExecution,+ outcomes: &mut [Option<ItemOutcome>],+ batched_f16_multivectors: &mut Vec<BatchedF16MultivectorOutput>,+ ) -> EncodeGroupOutcome {+ let group_stats = execution.stats;+ maybe_log_slow_encode_group(SlowEncodeLogContext {+ model_id: context.model_id,+ pooling: context.pooling,+ normalize: context.normalize,+ stats: &group_stats,+ first_item: group.first().map(|(_, item)| item),+ ok: execution.encoded.is_ok(),+ lock_wait_ms: execution.lock_wait_ms,+ encode_elapsed_ms: execution.encode_elapsed_ms,+ encode_source: execution.encode_source,+ });+ if candle_backend_diagnostics_enabled() {+ info!(+ model_id = context.model_id,+ group_items = group_stats.items,+ pooling = context.pooling,+ normalize = context.normalize,+ lock_wait_ms = execution.lock_wait_ms,+ encode_elapsed_ms = execution.encode_elapsed_ms,+ encode_source = execution.encode_source,+ prepared_items = group_stats.prepared_items,+ prepared_sequences = group_stats.prepared_sequences,+ prepared_tokens_total = group_stats.prepared_tokens_total,+ prepared_tokens_min = group_stats.prepared_tokens_min,+ prepared_tokens_max = group_stats.prepared_tokens_max,+ prepared_max_seq_len = group_stats.prepared_max_seq_len,+ text_chars_total = group_stats.text_chars_total,+ text_chars_min = group_stats.text_chars_min,+ text_chars_max = group_stats.text_chars_max,+ "Candle embedding backend diagnostics"+ );+ }+ if managed_metrics::metrics_enabled() {+ let (model, profile) = self.telemetry_dimensions(context.model_id, None);+ let outcome = if execution.encoded.is_ok() {+ ForwardOutcome::Success+ } else {+ ForwardOutcome::Error+ };+ let stages = execution+ .encoded+ .as_ref()+ .map(|encoded| {+ forward_stage_durations(+ encoded.stages,+ encoded.forward_profile.as_deref().copied(),+ )+ })+ .unwrap_or_default();+ managed_metrics::record_forward_completed(ForwardCompleted {+ model: &model,+ profile: &profile,+ outcome,+ input_source: forward_input_source(execution.encode_source),+ output_path: forward_output_path(context),+ duration_s: execution.encode_elapsed_ms / 1_000.0,+ stages: &stages,+ });+ }+ match execution.encoded {+ Ok(encoded) => {+ let items = group.len();+ let CandleEncodeResult {+ embeddings,+ sparse_embeddings,+ multivectors,+ multivectors_f16,+ dim,+ tokenization_ms,+ inference_ms,+ ..+ } = encoded;+ match context.output_kind {+ EncodeOutputKind::Dense => {+ for ((position, item), values) in group.into_iter().zip(embeddings) {+ outcomes[position] = Some(success_dense_outcome(+ &item,+ values,+ dim,+ context.normalize,+ inference_ms,+ tokenization_ms,+ ));+ }+ }+ EncodeOutputKind::Sparse => {+ let Some(sparse_embeddings) = sparse_embeddings else {+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle sparse encode returned no sparse embeddings",+ ));+ }+ return EncodeGroupOutcome::Failed;+ };+ if sparse_embeddings.len() != group.len() {+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle sparse item count did not match encode group",+ ));+ }+ return EncodeGroupOutcome::Failed;+ }+ for ((position, item), sparse) in group.into_iter().zip(sparse_embeddings) {+ outcomes[position] = Some(success_sparse_outcome(+ &item,+ sparse,+ dim,+ inference_ms,+ tokenization_ms,+ ));+ }+ }+ EncodeOutputKind::Multivector => {+ if let Some(batch) = multivectors_f16 {+ let CandleF16MultivectorBatch {+ values_f16,+ items: f16_items,+ } = batch;+ if f16_items.len() != group.len() {+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle f16 multivector item count did not match encode group",+ ));+ }+ return EncodeGroupOutcome::Failed;+ }++ if context.accepts_batched_f16_multivectors {+ let mut wire_items = Vec::with_capacity(f16_items.len());+ for ((position, item), f16_item) in group.into_iter().zip(f16_items)+ {+ outcomes[position] =+ Some(success_batched_f16_multivector_outcome(+ &item,+ inference_ms,+ tokenization_ms,+ ));+ let Ok(byte_offset) = u64::try_from(f16_item.byte_offset)+ else {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle f16 multivector offset exceeded wire range",+ ));+ continue;+ };+ let Ok(byte_len) = u64::try_from(f16_item.byte_len) else {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle f16 multivector length exceeded wire range",+ ));+ continue;+ };+ wire_items.push(BatchedF16MultivectorItem {+ work_item_id: item.work_item_id,+ byte_offset,+ byte_len,+ num_tokens: f16_item.num_tokens,+ token_dims: f16_item.token_dims,+ });+ }+ batched_f16_multivectors.push(BatchedF16MultivectorOutput {+ values_f16: F16Values(values_f16),+ items: wire_items,+ });+ } else {+ let batch = CandleF16MultivectorBatch {+ values_f16,+ items: f16_items,+ };+ let legacy = match batch.into_individual() {+ Ok(legacy) => legacy,+ Err(error) => {+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ &format!("Candle f16 multivector conversion failed: {error}"),+ ));+ }+ return EncodeGroupOutcome::Failed;+ }+ };+ for ((position, item), multivector) in group.into_iter().zip(legacy)+ {+ outcomes[position] = Some(success_multivector_outcome(+ &item,+ multivector,+ item.output_dtype.as_deref(),+ inference_ms,+ tokenization_ms,+ ));+ }+ }+ return EncodeGroupOutcome::Success { items };+ }++ let Some(multivectors) = multivectors else {+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ "Candle multivector encode returned no multivectors",+ ));+ }+ return EncodeGroupOutcome::Failed;+ };+ for ((position, item), multivector) in group.into_iter().zip(multivectors) {+ outcomes[position] = Some(success_multivector_outcome(+ &item,+ multivector,+ item.output_dtype.as_deref(),+ inference_ms,+ tokenization_ms,+ ));+ }+ }+ }+ EncodeGroupOutcome::Success { items }+ }+ Err(error) if is_oom_error(&error) => EncodeGroupOutcome::Oom { group, error },+ Err(error) => {+ error!(+ model_id = context.model_id,+ group_items = group_stats.items,+ pooling = context.pooling,+ normalize = context.normalize,+ lock_wait_ms = execution.lock_wait_ms,+ encode_elapsed_ms = execution.encode_elapsed_ms,+ encode_source = execution.encode_source,+ prepared_items = group_stats.prepared_items,+ prepared_sequences = group_stats.prepared_sequences,+ prepared_tokens_total = group_stats.prepared_tokens_total,+ prepared_tokens_min = group_stats.prepared_tokens_min,+ prepared_tokens_max = group_stats.prepared_tokens_max,+ prepared_max_seq_len = group_stats.prepared_max_seq_len,+ text_chars_total = group_stats.text_chars_total,+ text_chars_min = group_stats.text_chars_min,+ text_chars_max = group_stats.text_chars_max,+ error = %error_chain(&error),+ "Candle embedding inference failed"+ );+ for (position, item) in group {+ outcomes[position] = Some(identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_inference_failed",+ &format!("Candle embedding inference failed: {error}"),+ ));+ }+ EncodeGroupOutcome::Failed+ }+ }+ }++ fn mark_oom_group_retry(+ &self,+ context: EncodeGroupContext<'_>,+ group: PreparedEncodeGroup,+ error: anyhow::Error,+ nak_delay_ms: u64,+ outcomes: &mut [Option<ItemOutcome>],+ ) {+ warn!(+ model_id = context.model_id,+ group_items = group.len(),+ pooling = context.pooling,+ normalize = context.normalize,+ nak_delay_ms,+ error = %error_chain(&error),+ "Candle OOM recovery exhausted; marking encode items for retry"+ );+ for (position, item) in group {+ outcomes[position] = Some(oom_nak_outcome(&item, nak_delay_ms));+ }+ }++ async fn score_items(&self, model_id: &str, items: Vec<ScoreBatchItem>) -> BatchOutcome {+ let mut outcomes = Vec::with_capacity(items.len());+ for item in items {+ if let Some(message) = profile_option_error(item.options.as_ref()) {+ outcomes.push(score_error_outcome(+ &item,+ "candle_unsupported_request",+ &message,+ ));+ continue;+ }+ let requested_profile =+ requested_item_profile(item.options.as_ref(), item.profile_id.as_deref());+ let Some(effective_model_id) = effective_model_id(model_id, requested_profile)+ .filter(|model_id| self.supports(model_id))+ else {+ outcomes.push(score_error_outcome(+ &item,+ "candle_unsupported_model",+ "model is not supported by this Rust Candle worker",+ ));+ continue;+ };+ if !self.supports_score_item(&effective_model_id, &item) {+ outcomes.push(score_error_outcome(+ &item,+ "candle_unsupported_request",+ "Candle Rust worker supports explicitly configured ColBERT MaxSim text score with Python-compatible encode runtime options",+ ));+ continue;+ }+ if let Err(message) = item_id(&item.query_item) {+ outcomes.push(score_error_outcome(+ &item,+ "candle_invalid_item",+ &format!("Candle Rust worker score query {message}"),+ ));+ continue;+ }+ let query_text = match extract_text(&item.query_item) {+ Ok(text) => text,+ Err(message) => {+ outcomes.push(score_error_outcome(+ &item,+ "candle_invalid_item",+ &format!("Candle Rust worker score query {message}"),+ ));+ continue;+ }+ };+ let mut raw_docs = Vec::with_capacity(item.score_items.len());+ let mut item_ids = Vec::with_capacity(item.score_items.len());+ let mut invalid_doc = None;+ for (index, doc) in item.score_items.iter().enumerate() {+ let text = match extract_text(doc) {+ Ok(text) => text,+ Err(message) => {+ invalid_doc = Some((index, message));+ break;+ }+ };+ let id = match score_item_id(doc, index) {+ Ok(id) => id,+ Err(message) => {+ invalid_doc = Some((index, message));+ break;+ }+ };+ raw_docs.push(text);+ item_ids.push(id);+ }+ if let Some((index, message)) = invalid_doc {+ outcomes.push(score_error_outcome(+ &item,+ "candle_invalid_item",+ &format!("Candle Rust worker score document {index} {message}"),+ ));+ continue;+ }++ let defaults = self.runtime_defaults_for(&effective_model_id, requested_profile);+ // Score ingress has already canonicalized request instruction+ // precedence into `ScoreBatchItem.instruction`. All encode-time+ // options, including a duplicate `options.instruction`, remain+ // accepted for rolling compatibility but are ignored here.+ let (query, docs, allow_prepared_tokens) =+ prepare_colbert_score_texts(query_text, &raw_docs, item.instruction.as_deref());+ // Late-interaction score is cosine MaxSim. Keep score-time+ // projection normalization invariant even if an encode caller+ // selects a profile that exposes raw multivectors.+ let normalize = true;+ let work_budget = defaults.max_batch_tokens.unwrap_or_else(|| {+ self.catalog+ .read()+ .expect("Candle catalog lock poisoned")+ .get(base_model_id_for_residency(&effective_model_id))+ .and_then(|config| config.max_sequence_length)+ .unwrap_or(8192)+ });+ let prepared = Arc::new(PreparedScoreItem {+ query,+ docs,+ item_ids,+ normalize,+ work_budget: work_budget.max(1),+ prepared_tokens: item.prepared_tokens.clone(),+ allow_prepared_tokens,+ });++ if prepared.docs.is_empty() {+ outcomes.push(success_score_outcome(+ &item,+ &prepared.item_ids,+ CandleScoreResult {+ scores: Vec::new(),+ query_tokens: 0,+ doc_tokens: Vec::new(),+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ maxsim_ms: None,+ },+ ));+ continue;+ }++ let loaded_model_use = match self.embedding_model(&effective_model_id) {+ Ok(loaded) => loaded,+ Err(error) => {+ outcomes.push(score_model_load_error_outcome(+ &item,+ &error,+ self.config.oom_recovery.nak_delay_ms,+ ));+ continue;+ }+ };+ outcomes.push(+ self.score_item_with_oom_recovery(+ &effective_model_id,+ &loaded_model_use.model_id,+ &item,+ Arc::clone(&loaded_model_use.model),+ prepared,+ )+ .await,+ );+ }++ BatchOutcome {+ outcomes,+ batched_f16_multivectors: Vec::new(),+ }+ }++ async fn score_item_with_oom_recovery(+ &self,+ model_id: &str,+ active_model_id: &str,+ item: &ScoreBatchItem,+ loaded_model: Arc<LoadedEmbeddingModel>,+ prepared: Arc<PreparedScoreItem>,+ ) -> ItemOutcome {+ let mut work_budget = prepared.work_budget;+ let mut execution = match self+ .run_score_item_attempt(+ model_id,+ Arc::clone(&loaded_model),+ Arc::clone(&prepared),+ work_budget,+ )+ .await+ {+ Ok(execution) => execution,+ Err(error) => {+ return score_error_outcome(+ item,+ "candle_inference_failed",+ &format!("Candle MaxSim worker task failed: {error}"),+ );+ }+ };+ if !execution.scored.as_ref().err().is_some_and(is_oom_error) {+ return score_execution_outcome(item, &prepared.item_ids, execution);+ }++ let recovery = self.config.oom_recovery.clone();+ if !recovery.enabled {+ return score_oom_nak_outcome(item, recovery.nak_delay_ms);+ }+ warn!(+ model_id,+ documents = prepared.docs.len(),+ work_budget,+ error = %execution.scored.as_ref().unwrap_err(),+ "Candle MaxSim score hit OOM; attempting recovery"+ );++ let mut recovery_action_cursor = 0usize;+ let mut pending_oom_strategy: Option<OomStrategy> = None;+ loop {+ let strategy = match next_oom_recovery_step(+ &recovery.strategy,+ &mut recovery_action_cursor,+ || {+ self.evict_lru_embedding_model_excluding_with_reason(+ active_model_id,+ ModelEvictionReason::OomRecovery,+ )+ },+ ) {+ OomRecoveryStep::RetryAfterCacheClear => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(model_id, previous, OomOutcome::Failed);+ }+ OomStrategy::CacheClear+ }+ OomRecoveryStep::RetryAfterEviction(evicted_model_id) => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(model_id, previous, OomOutcome::Failed);+ }+ warn!(+ model_id,+ active_model_id,+ evicted_model_id = %evicted_model_id,+ "Candle MaxSim OOM recovery evicted LRU sibling model"+ );+ OomStrategy::EvictLru+ }+ OomRecoveryStep::SplitBatch => {+ if let Some(previous) = pending_oom_strategy.take() {+ self.record_oom_recovery(model_id, previous, OomOutcome::Failed);+ }+ let mut split_depth = 0usize;+ while split_depth < recovery.max_split_depth && work_budget > 1 {+ split_depth += 1;+ work_budget = (work_budget / 2).max(1);+ execution = match self+ .run_score_item_attempt(+ model_id,+ Arc::clone(&loaded_model),+ Arc::clone(&prepared),+ work_budget,+ )+ .await+ {+ Ok(execution) => execution,+ Err(error) => {+ self.record_oom_recovery(+ model_id,+ OomStrategy::SplitBatch,+ OomOutcome::Failed,+ );+ return score_error_outcome(+ item,+ "candle_inference_failed",+ &format!("Candle MaxSim worker task failed: {error}"),+ );+ }+ };+ match &execution.scored {+ Ok(_) => {+ self.record_oom_recovery(+ model_id,+ OomStrategy::SplitBatch,+ OomOutcome::Success,+ );+ return score_execution_outcome(+ item,+ &prepared.item_ids,+ execution,+ );+ }+ Err(error) if is_oom_error(error) => continue,+ Err(_) => {+ self.record_oom_recovery(+ model_id,+ OomStrategy::SplitBatch,+ OomOutcome::Failed,+ );+ return score_execution_outcome(+ item,+ &prepared.item_ids,+ execution,+ );+ }+ }+ }+ self.record_oom_recovery(+ model_id,+ OomStrategy::SplitBatch,+ OomOutcome::Terminal,+ );+ return score_oom_nak_outcome(item, recovery.nak_delay_ms);+ }+ OomRecoveryStep::Terminal => {+ self.record_oom_recovery(+ model_id,+ pending_oom_strategy.unwrap_or(OomStrategy::Other),+ OomOutcome::Terminal,+ );+ return score_oom_nak_outcome(item, recovery.nak_delay_ms);+ }+ };++ execution = match self+ .run_score_item_attempt(+ model_id,+ Arc::clone(&loaded_model),+ Arc::clone(&prepared),+ work_budget,+ )+ .await+ {+ Ok(execution) => execution,+ Err(error) => {+ self.record_oom_recovery(model_id, strategy, OomOutcome::Failed);+ return score_error_outcome(+ item,+ "candle_inference_failed",+ &format!("Candle MaxSim worker task failed: {error}"),+ );+ }+ };+ match &execution.scored {+ Ok(_) => {+ self.record_oom_recovery(model_id, strategy, OomOutcome::Success);+ return score_execution_outcome(item, &prepared.item_ids, execution);+ }+ Err(error) if is_oom_error(error) => {+ pending_oom_strategy = Some(strategy);+ }+ Err(_) => {+ self.record_oom_recovery(model_id, strategy, OomOutcome::Failed);+ return score_execution_outcome(item, &prepared.item_ids, execution);+ }+ }+ }+ }++ async fn run_score_item_attempt(+ &self,+ model_id: &str,+ loaded_model: Arc<LoadedEmbeddingModel>,+ prepared: Arc<PreparedScoreItem>,+ work_budget: usize,+ ) -> Result<ScoreItemExecution> {+ let output_path = ForwardOutputPath::Other;+ let telemetry_dimensions =+ managed_metrics::metrics_enabled().then(|| self.telemetry_dimensions(model_id, None));+ let permit_started = telemetry_dimensions.as_ref().map(|_| Instant::now());+ let waiting_guard = telemetry_dimensions.as_ref().map(|(model, profile)| {+ managed_metrics::begin_forward_activity(+ model,+ profile,+ ForwardState::Waiting,+ self.config.max_concurrent_forwards,+ )+ });+ let slot_result = loaded_model.acquire_forward_slot().await;+ drop(waiting_guard);+ if let (Some((model, profile)), Some(started)) =+ (telemetry_dimensions.as_ref(), permit_started)+ {+ managed_metrics::record_forward_permit_wait(+ model,+ profile,+ output_path,+ started.elapsed().as_secs_f64(),+ );+ }+ let slot = slot_result?;+ let active_guard = telemetry_dimensions.as_ref().map(|(model, profile)| {+ managed_metrics::begin_forward_activity(+ model,+ profile,+ ForwardState::Active,+ self.config.max_concurrent_forwards,+ )+ });+ let wall_start = Instant::now();+ let execution = tokio::task::spawn_blocking(move || {+ loaded_model.with_model(slot, |model| {+ score_prepared_item_on_model(model, &prepared, work_budget)+ })+ })+ .await+ .context("join Candle MaxSim worker task")?;+ drop(active_guard);+ let wall_ms = elapsed_ms(wall_start);+ if let Some((model, profile)) = telemetry_dimensions {+ let outcome = if execution.result.is_ok() {+ ForwardOutcome::Success+ } else {+ ForwardOutcome::Error+ };+ managed_metrics::record_forward_completed(ForwardCompleted {+ model: &model,+ profile: &profile,+ outcome,+ input_source: ForwardInputSource::Other,+ output_path,+ duration_s: wall_ms / 1_000.0,+ stages: &[],+ });+ }+ Ok(ScoreItemExecution {+ scored: execution.result,+ lock_wait_ms: execution.lock_wait_ms,+ wall_ms,+ })+ }++ fn embedding_model(&self, model_id: &str) -> Result<LoadedEmbeddingModelUse> {+ let base_model_id = self+ .base_model_for_supported_route(model_id)+ .with_context(|| format!("model {model_id:?} is not supported by this Candle worker"))?+ .to_string();+ let runtime_config = {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ self.catalog_config_for(model_id, &guard)+ .cloned()+ .unwrap_or_else(|| ModelRuntimeConfig {+ hf_id: base_model_id.clone(),+ hf_revision: None,+ max_sequence_length: None,+ query_max_length: None,+ dense_dim: None,+ sparse_dim: None,+ multivector_dim: None,+ compute_precision: None,+ profiles: HashMap::new(),+ routable_model_ids: vec![base_model_id.clone()],+ task_kind: CandleTaskKind::Embedding,+ })+ };+ if !runtime_config.task_kind.supports_embedding() {+ anyhow::bail!("model {base_model_id:?} is not a Candle embedding model");+ }++ if let Some(model) = self.checkout_loaded_embedding_model(&base_model_id) {+ return Ok(model);+ }++ loop {+ if let Some(model) = self.checkout_loaded_embedding_model(&base_model_id) {+ return Ok(model);+ }+ if self.mark_embedding_loading(&base_model_id) {+ break;+ }+ std::thread::sleep(MODEL_LOAD_WAIT_INTERVAL);+ }+ let load_telemetry = managed_metrics::metrics_enabled().then(|| {+ let (model, profile) = self.telemetry_dimensions(model_id, None);+ (Instant::now(), model, profile)+ });++ let model_config = CandleEmbeddingModelConfig {+ model_id: base_model_id.clone(),+ hf_id: runtime_config.hf_id.clone(),+ hf_revision: runtime_config.hf_revision.clone(),+ max_seq_length: runtime_config.max_sequence_length.unwrap_or(512),+ query_max_length: runtime_config.query_max_length,+ dense_dim: runtime_config.dense_dim,+ sparse_dim: runtime_config.native_sparse_dim(),+ multivector_dim: runtime_config.native_multivector_dim(),+ compute_precision: runtime_config.compute_precision.clone(),+ };+ let load_once = || {+ let model = CandleEmbeddingModel::load(&model_config)+ .with_context(|| format!("load Candle embedding model {base_model_id:?}"))?;+ let loaded_model = Arc::new(LoadedEmbeddingModel::new(+ model,+ self.config.max_concurrent_forwards,+ ));+ {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ match self.catalog_config_for(&base_model_id, &guard) {+ Some(current_config) if current_config == &runtime_config => {}+ Some(_) => {+ anyhow::bail!("model {base_model_id:?} changed while loading");+ }+ None => {+ anyhow::bail!("model {base_model_id:?} was removed while loading");+ }+ }+ }+ let policy = self.residency_policy_for_base_model(&base_model_id);+ let mut loaded = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned");+ if let Some(model) = loaded.get_for_use(&base_model_id, Instant::now()) {+ return Ok(self.loaded_embedding_model_use(&base_model_id, model));+ }++ info!(+ model_id = %base_model_id,+ max_concurrent_forwards = self.config.max_concurrent_forwards,+ "loaded Candle embedding model"+ );+ loaded.insert(+ base_model_id.clone(),+ Arc::clone(&loaded_model),+ policy,+ Instant::now(),+ );+ let model = loaded+ .get_for_use(&base_model_id, Instant::now())+ .expect("loaded Candle embedding model was just inserted");+ Ok(self.loaded_embedding_model_use(&base_model_id, model))+ };+ let load_result = match load_once() {+ Ok(model) => Ok(model),+ Err(error) if is_oom_error(&error) => {+ if let Some(evicted_model_id) = self+ .evict_lru_embedding_model_excluding_with_reason(+ &base_model_id,+ ModelEvictionReason::LoadOom,+ )+ {+ warn!(+ model_id = %base_model_id,+ evicted_model_id = %evicted_model_id,+ error = %error_chain(&error),+ "Candle embedding model load hit OOM; evicted LRU resident model and retrying"+ );+ load_once()+ } else {+ Err(error)+ }+ }+ Err(error) => Err(error),+ };+ self.unmark_embedding_loading(&base_model_id);+ if let Some((started, model, profile)) = load_telemetry {+ let outcome = if load_result.is_ok() {+ ModelLoadOutcome::Success+ } else {+ ModelLoadOutcome::Error+ };+ managed_metrics::record_model_load_completed(+ &model,+ &profile,+ outcome,+ ModelLoadStage::Total,+ started.elapsed().as_secs_f64(),+ );+ if load_result.is_ok() {+ self.record_model_residency_for_base(&base_model_id, true, None);+ }+ }+ load_result+ }++ fn reconcile_warm_models(&self) {+ let mut warm_models: Vec<String> = self+ .preload_models+ .read()+ .expect("Candle preload-model lock poisoned")+ .iter()+ .cloned()+ .collect();+ warm_models.extend(+ self.pinned_models+ .read()+ .expect("Candle pinned-model lock poisoned")+ .iter()+ .cloned(),+ );+ warm_models.sort();+ warm_models.dedup();+ if warm_models.is_empty() {+ return;+ }++ let mut load_started = 0_u32;+ let mut already_resident_or_loading = 0_u32;+ let mut skipped = 0_u32;+ for model_id in warm_models {+ let task_kind = {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ self.catalog_config_for(&model_id, &guard)+ .map(|config| config.task_kind)+ };+ if !task_kind.is_some_and(CandleTaskKind::supports_embedding) {+ skipped += 1;+ continue;+ }++ match self.embedding_load_state(&model_id) {+ Ok(ReadinessState::LoadingStarted) => {+ load_started += 1;+ }+ Ok(ReadinessState::Ready | ReadinessState::LoadingInProgress) => {+ already_resident_or_loading += 1;+ }+ // `RetryLater` (unknown/not-ready) and `Failed` (terminal+ // load failure) are both "don't eager-load now": a terminally+ // failed model must not be re-driven by the warm reconcile.+ Ok(ReadinessState::RetryLater | ReadinessState::Failed) => {+ skipped += 1;+ }+ Err(error) => {+ skipped += 1;+ warn!(+ model_id = %model_id,+ error = %error_chain(&error),+ "Candle warm model eager-load reconcile failed"+ );+ }+ }+ }++ if load_started > 0 || skipped > 0 {+ info!(+ load_started,+ already_resident_or_loading, skipped, "Candle warm model reconcile complete"+ );+ }+ }++ fn loaded_embedding_model(&self, base_model_id: &str) -> Option<Arc<LoadedEmbeddingModel>> {+ self.loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .get(base_model_id)+ }++ fn checkout_loaded_embedding_model(+ &self,+ base_model_id: &str,+ ) -> Option<LoadedEmbeddingModelUse> {+ let model = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .get_for_use(base_model_id, Instant::now())?;+ Some(self.loaded_embedding_model_use(base_model_id, model))+ }++ fn loaded_embedding_model_use(+ &self,+ base_model_id: &str,+ model: Arc<LoadedEmbeddingModel>,+ ) -> LoadedEmbeddingModelUse {+ LoadedEmbeddingModelUse {+ model_id: base_model_id.to_string(),+ model,+ _residency_use: ResidencyUseGuard::active(+ Arc::clone(&self.loaded_embeddings),+ base_model_id.to_string(),+ ),+ }+ }++ pub fn evict_lru_embedding_model_excluding(&self, exclude_model_id: &str) -> Option<String> {+ self.evict_lru_embedding_model_excluding_with_reason(+ exclude_model_id,+ ModelEvictionReason::Lru,+ )+ }++ fn evict_lru_embedding_model_excluding_with_reason(+ &self,+ exclude_model_id: &str,+ reason: ModelEvictionReason,+ ) -> Option<String> {+ let exclude_base_model_id = canonical_pinned_model_id(exclude_model_id)+ .map(|model_id| base_model_id_for_residency(&model_id).to_string())+ .unwrap_or_else(|| base_model_id_for_residency(exclude_model_id).to_string());+ let evicted = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .evict_lru_excluding(Some(&exclude_base_model_id));+ if let Some(evicted_model_id) = evicted.as_deref() {+ self.record_model_residency_for_base(evicted_model_id, false, Some(reason));+ }+ evicted+ }++ fn evict_idle_embedding_model(&self, idle_threshold: Duration) -> Option<String> {+ let evicted = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .evict_idle(idle_threshold, Instant::now());+ if let Some(evicted_model_id) = evicted.as_deref() {+ self.record_model_residency_for_base(+ evicted_model_id,+ false,+ Some(ModelEvictionReason::Idle),+ );+ }+ evicted+ }++ fn refresh_residency_policies(&self) {+ let preload = self+ .preload_models+ .read()+ .expect("Candle preload-model lock poisoned")+ .clone();+ let pinned = self+ .pinned_models+ .read()+ .expect("Candle pinned-model lock poisoned")+ .clone();+ self.loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .update_policies(|base_model_id| {+ residency_policy_for_base_model(base_model_id, &preload, &pinned)+ });+ }++ fn residency_policy_for_base_model(&self, base_model_id: &str) -> ResidencyPolicy {+ let preload = self+ .preload_models+ .read()+ .expect("Candle preload-model lock poisoned");+ let pinned = self+ .pinned_models+ .read()+ .expect("Candle pinned-model lock poisoned");+ residency_policy_for_base_model(base_model_id, &preload, &pinned)+ }++ fn embedding_load_route(&self, model_id: &str) -> Result<(String, String)> {+ let load_model_id = canonical_pinned_model_id(model_id).with_context(|| {+ format!("model {model_id:?} is not supported by this Candle worker")+ })?;+ let base_model_id = self+ .base_model_for_supported_route(&load_model_id)+ .with_context(|| format!("model {model_id:?} is not supported by this Candle worker"))?+ .to_string();+ Ok((load_model_id, base_model_id))+ }++ fn embedding_load_state(&self, model_id: &str) -> Result<ReadinessState> {+ let (load_model_id, base_model_id) = self.embedding_load_route(model_id)?;++ if self.loaded_embedding_model(&base_model_id).is_some() {+ return Ok(ReadinessState::Ready);+ }++ if self.is_embedding_loading(&base_model_id) {+ return Ok(ReadinessState::LoadingInProgress);+ }++ let backend = self.clone();+ tokio::task::spawn_blocking(move || {+ let result = backend.embedding_model(&load_model_id);+ match result {+ Ok(_) => {+ info!(+ model_id = %load_model_id,+ "Candle background embedding load completed"+ );+ }+ Err(error) => {+ warn!(+ model_id = %load_model_id,+ error = %error_chain(&error),+ "Candle background embedding load failed"+ );+ }+ }+ });++ Ok(ReadinessState::LoadingStarted)+ }++ fn is_embedding_loading(&self, base_model_id: &str) -> bool {+ self.loading_embeddings+ .lock()+ .expect("Candle model loading lock poisoned")+ .contains(base_model_id)+ }++ fn mark_embedding_loading(&self, base_model_id: &str) -> bool {+ self.loading_embeddings+ .lock()+ .expect("Candle model loading lock poisoned")+ .insert(base_model_id.to_string())+ }++ fn unmark_embedding_loading(&self, base_model_id: &str) {+ self.loading_embeddings+ .lock()+ .expect("Candle model loading lock poisoned")+ .remove(base_model_id);+ }++ fn evict_embedding_model(&self, base_model_id: &str, reason: ModelEvictionReason) {+ let removed = self+ .loaded_embeddings+ .lock()+ .expect("Candle model lock poisoned")+ .remove(base_model_id)+ .is_some();+ self.loading_embeddings+ .lock()+ .expect("Candle model loading lock poisoned")+ .remove(base_model_id);+ if removed {+ self.record_model_residency_for_base(base_model_id, false, Some(reason));+ }+ }++ fn loaded_tokenizer_descriptor(&self, model_id: &str) -> Option<(String, String, usize)> {+ let base_model_id = self.base_model_for_supported_route(model_id)?;+ let model = self+ .loaded_embeddings+ .lock()+ .ok()?+ .get(base_model_id)?+ .first();+ Some((+ model.tokenizer_path().display().to_string(),+ model.tokenizer_id().to_string(),+ model.max_seq_length(),+ ))+ }++ fn supports_encode_options(&self, model_id: &str, item: &EncodeBatchItem) -> bool {+ let requested_profile =+ requested_item_profile(item.options.as_ref(), item.profile_id.as_deref());+ if !self.supports_operation(model_id, CandleTaskKind::Embedding)+ || !supported_options(item.options.as_ref(), ENCODE_OPTION_KEYS)+ || profile_option_error(item.options.as_ref()).is_some()+ || output_dtype_type_error(item.options.as_ref()).is_some()+ || !self.supports_pooling_override(model_id, requested_profile, item.options.as_ref())+ {+ return false;+ }++ let defaults = self.runtime_defaults_for(model_id, requested_profile);+ let output_dtype = option_str(item.options.as_ref(), "output_dtype")+ .map(str::to_string)+ .or(defaults.output_dtype);+ let option_output_types = option_output_types(item.options.as_ref());+ let requested_output_types = option_output_types+ .as_deref()+ .or(item.output_types.as_deref());+ self.encode_output_kind(model_id, requested_output_types)+ .map(|kind| output_dtype_error_for_kind(output_dtype.as_deref(), kind).is_none())+ .unwrap_or(false)+ }++ fn encode_output_kind(+ &self,+ model_id: &str,+ output_types: Option<&[String]>,+ ) -> Option<EncodeOutputKind> {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ let config = self.catalog_config_for(model_id, &guard);+ let supports_dense = config+ .map(|config| config.dense_dim.is_some())+ .unwrap_or(true);+ let supports_sparse = config+ .and_then(ModelRuntimeConfig::native_sparse_dim)+ .is_some();+ let supports_multivector = config+ .and_then(ModelRuntimeConfig::native_multivector_dim)+ .is_some();+ match output_types {+ None | Some([]) if supports_dense => Some(EncodeOutputKind::Dense),+ None | Some([]) if supports_multivector => Some(EncodeOutputKind::Multivector),+ None | Some([]) if supports_sparse => Some(EncodeOutputKind::Sparse),+ Some(types) if types.iter().all(|ty| ty == "dense") && supports_dense => {+ Some(EncodeOutputKind::Dense)+ }+ Some(types) if types.iter().all(|ty| ty == "multivector") && supports_multivector => {+ Some(EncodeOutputKind::Multivector)+ }+ Some(types) if types.iter().all(|ty| ty == "sparse") && supports_sparse => {+ Some(EncodeOutputKind::Sparse)+ }+ _ => None,+ }+ }++ fn supports_score_item(&self, model_id: &str, item: &ScoreBatchItem) -> bool {+ if !self.supports_operation(model_id, CandleTaskKind::Rerank)+ || !supported_options(item.options.as_ref(), SCORE_OPTION_KEYS)+ || profile_option_error(item.options.as_ref()).is_some()+ {+ return false;+ }+ let requested_profile =+ requested_item_profile(item.options.as_ref(), item.profile_id.as_deref());+ self.catalog+ .read()+ .expect("Candle catalog lock poisoned")+ .get(base_model_id_for_residency(model_id))+ .is_some_and(|config| config.supports_native_score(model_id, requested_profile))+ }++ fn runtime_defaults_for(+ &self,+ model_id: &str,+ requested_profile: Option<&str>,+ ) -> RuntimeDefaults {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ let Some(config) = self.catalog_config_for(model_id, &guard) else {+ return RuntimeDefaults::default();+ };++ selected_runtime_defaults(model_id, requested_profile, &config.profiles)+ }++ fn supports_pooling_override(+ &self,+ model_id: &str,+ requested_profile: Option<&str>,+ options: Option<&Json>,+ ) -> bool {+ let Some(pooling) = option_str(options, "pooling") else {+ return true;+ };+ self.runtime_defaults_for(model_id, requested_profile)+ .pooling+ .as_deref()+ == Some(pooling)+ }++ fn base_model_for_supported_route<'a>(&self, model_id: &'a str) -> Option<&'a str> {+ if !self.supports(model_id) {+ return None;+ }+ Some(+ synthetic_model_parts(model_id)+ .map(|(base, _)| base)+ .unwrap_or(model_id),+ )+ }++ fn catalog_config_for<'a>(+ &self,+ model_id: &'a str,+ catalog: &'a HashMap<String, ModelRuntimeConfig>,+ ) -> Option<&'a ModelRuntimeConfig> {+ catalog.get(model_id).or_else(|| {+ synthetic_model_parts(model_id)+ .map(|(base, _)| base)+ .and_then(|base| catalog.get(base))+ })+ }++ fn task_kind_for(&self, model_id: &str) -> CandleTaskKind {+ let guard = self.catalog.read().expect("Candle catalog lock poisoned");+ self.catalog_config_for(model_id, &guard)+ .map(|config| config.task_kind)+ .unwrap_or_default()+ }++ fn supports_operation(&self, model_id: &str, task_kind: CandleTaskKind) -> bool {+ if !self.supports(model_id) {+ return false;+ }+ let configured = self.task_kind_for(model_id);+ match task_kind {+ CandleTaskKind::Embedding => configured.supports_embedding(),+ CandleTaskKind::Rerank => configured.supports_score(),+ CandleTaskKind::EmbeddingAndRerank => {+ configured.supports_embedding() && configured.supports_score()+ }+ }+ }+}++const ENCODE_OPTION_KEYS: &[&str] = &[+ "default_instruction",+ "doc_template",+ "instruction",+ "is_query",+ "normalize",+ "output_dtype",+ "output_types",+ "pooling",+ "profile",+ "query_template",+];+// The Python ColBERT score path accepts and ignores encode-only runtime+// options. Keep those benign keys wire-compatible while continuing to reject+// unknown execution-changing options (for example LoRA).+const SCORE_OPTION_KEYS: &[&str] = &[+ "default_instruction",+ "doc_template",+ "instruction",+ "is_query",+ "muvera",+ "normalize",+ "output_dtype",+ "output_similarity",+ "output_types",+ "pooling",+ "profile",+ "query_template",+];+const CANDLE_ADAPTER_MODULE: &str = "sie_server_rust.adapters.candle";++struct PreparedEncodeItem {+ work_item_id: String,+ request_id: String,+ item_index: u32,+ text: String,+ is_query: bool,+ output_dtype: Option<String>,+ prepared_tokens: Option<PreparedTokens>,+}++#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]+struct EncodeGroupStats {+ items: usize,+ prepared_items: usize,+ prepared_sequences: usize,+ prepared_tokens_total: usize,+ prepared_tokens_min: usize,+ prepared_tokens_max: usize,+ prepared_max_seq_len: u32,+ text_chars_total: usize,+ text_chars_min: usize,+ text_chars_max: usize,+}++impl EncodeGroupStats {+ fn from_group(group: &[(usize, PreparedEncodeItem)]) -> Self {+ let mut stats = Self {+ items: group.len(),+ prepared_tokens_min: usize::MAX,+ text_chars_min: usize::MAX,+ ..Self::default()+ };++ for (_, item) in group {+ let text_chars = item.text.chars().count();+ stats.text_chars_total += text_chars;+ stats.text_chars_min = stats.text_chars_min.min(text_chars);+ stats.text_chars_max = stats.text_chars_max.max(text_chars);++ if let Some(prepared) = item.prepared_tokens.as_ref() {+ stats.prepared_items += 1;+ stats.prepared_sequences += prepared.input_ids.len();+ stats.prepared_max_seq_len = stats.prepared_max_seq_len.max(prepared.max_seq_len);+ let item_tokens = prepared.input_ids.iter().map(Vec::len).sum();+ stats.prepared_tokens_total += item_tokens;+ stats.prepared_tokens_min = stats.prepared_tokens_min.min(item_tokens);+ stats.prepared_tokens_max = stats.prepared_tokens_max.max(item_tokens);+ }+ }++ if group.is_empty() {+ stats.text_chars_min = 0;+ }+ if stats.prepared_items == 0 {+ stats.prepared_tokens_min = 0;+ }++ stats+ }+}++fn encode_item_identities(group: &[(usize, PreparedEncodeItem)]) -> Vec<EncodeItemIdentity> {+ group+ .iter()+ .map(|(position, item)| EncodeItemIdentity {+ position: *position,+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ })+ .collect()+}++fn prepared_requests_for_group(+ model: &CandleEmbeddingModel,+ group: &[(usize, PreparedEncodeItem)],+) -> Option<Vec<CandlePreparedEncodeRequest>> {+ let mut prepared_requests = Vec::with_capacity(group.len());+ for (_, item) in group {+ let prepared = item.prepared_tokens.as_ref()?;+ if prepared.tokenizer_id != model.tokenizer_id() {+ return None;+ }+ let input_ids = single_required_row(&prepared.input_ids)?;+ if input_ids.is_empty() {+ return None;+ }+ prepared_requests.push(CandlePreparedEncodeRequest {+ input_ids,+ attention_mask: single_optional_row(&prepared.attention_mask)?,+ token_type_ids: single_optional_row(&prepared.token_type_ids)?,+ });+ }+ Some(prepared_requests)+}++fn score_prepared_item_on_model(+ model: &CandleEmbeddingModel,+ item: &PreparedScoreItem,+ work_budget: usize,+) -> Result<CandleScoreResult> {+ if item.allow_prepared_tokens {+ if let Some((query, docs)) = prepared_score_requests(model, item) {+ return model.score_prepared_multivector(&query, &docs, item.normalize, work_budget);+ }+ }+ model.score_multivector(&item.query, &item.docs, item.normalize, work_budget)+}++fn prepared_score_requests(+ model: &CandleEmbeddingModel,+ item: &PreparedScoreItem,+) -> Option<(+ CandlePreparedEncodeRequest,+ Vec<CandlePreparedEncodeRequest>,+)> {+ let prepared = item.prepared_tokens.as_ref()?;+ if prepared.tokenizer_id != model.tokenizer_id() {+ return None;+ }+ let expected_rows = item.docs.len().checked_add(1)?;+ if prepared.input_ids.len() != expected_rows+ || prepared.input_ids.iter().any(Vec::is_empty)+ || !(prepared.attention_mask.is_empty() || prepared.attention_mask.len() == expected_rows)+ || !(prepared.token_type_ids.is_empty() || prepared.token_type_ids.len() == expected_rows)+ {+ return None;+ }+ let mut requests = Vec::with_capacity(expected_rows);+ for index in 0..expected_rows {+ requests.push(CandlePreparedEncodeRequest {+ input_ids: prepared.input_ids[index].clone(),+ attention_mask: (!prepared.attention_mask.is_empty())+ .then(|| prepared.attention_mask[index].clone()),+ token_type_ids: (!prepared.token_type_ids.is_empty())+ .then(|| prepared.token_type_ids[index].clone()),+ });+ }+ let query = requests.remove(0);+ Some((query, requests))+}++fn single_required_row(rows: &[Vec<u32>]) -> Option<Vec<u32>> {+ match rows {+ [row] => Some(row.clone()),+ _ => None,+ }+}++fn single_optional_row(rows: &[Vec<u32>]) -> Option<Option<Vec<u32>>> {+ match rows {+ [] => Some(None),+ [row] => Some(Some(row.clone())),+ _ => None,+ }+}++fn supported_options(options: Option<&Json>, allowed_keys: &[&str]) -> bool {+ match options {+ None | Some(Json::Null) => true,+ Some(Json::Object(map)) => map.keys().all(|key| allowed_keys.contains(&key.as_str())),+ _ => false,+ }+}++fn raw_output_dtype<'a>(options: Option<&'a Json>, key: &str) -> Option<&'a Json> {+ options+ .and_then(Json::as_object)+ .and_then(|map| map.get(key))+ .filter(|value| !value.is_null())+}++fn output_dtype_error_for_kind(+ output_dtype: Option<&str>,+ output_kind: EncodeOutputKind,+) -> Option<String> {+ match (output_kind, output_dtype) {+ (_, None) | (_, Some("float32")) => None,+ (EncodeOutputKind::Multivector, Some("float16")) => None,+ (EncodeOutputKind::Dense, Some(dtype)) => Some(format!(+ "Candle Rust worker currently returns dense float32 only; requested output_dtype={dtype:?}"+ )),+ (EncodeOutputKind::Sparse, Some(dtype)) => Some(format!(+ "Candle Rust worker currently returns sparse float32 only; requested output_dtype={dtype:?}"+ )),+ (EncodeOutputKind::Multivector, Some(dtype)) => Some(format!(+ "Candle Rust worker currently returns multivector float16 or float32 only; requested output_dtype={dtype:?}"+ )),+ }+}++fn output_dtype_type_error(options: Option<&Json>) -> Option<String> {+ let value = raw_output_dtype(options, "output_dtype")?;+ match value {+ Json::String(_) => None,+ other => Some(format!(+ "Candle Rust worker output_dtype must be a string when provided; got {other}"+ )),+ }+}++fn profile_option_error(options: Option<&Json>) -> Option<String> {+ let value = options+ .and_then(Json::as_object)+ .and_then(|map| map.get("profile"))?;+ match value {+ Json::Null => None,+ Json::String(profile) if !profile.trim().is_empty() => None,+ Json::String(_) => {+ Some("Candle Rust worker profile must be a non-empty string when provided".to_string())+ }+ other => Some(format!(+ "Candle Rust worker profile must be a string when provided; got {other}"+ )),+ }+}++fn multivector_wire_dtype(output_dtype: Option<&str>) -> &'static str {+ match output_dtype {+ Some("float16") => "float16",+ _ => "float32",+ }+}++fn non_empty_str(value: &str) -> Option<&str> {+ (!value.is_empty()).then_some(value)+}++fn synthetic_model_parts(model_id: &str) -> Option<(&str, &str)> {+ model_id+ .rsplit_once(':')+ .filter(|(base, profile)| !base.is_empty() && !profile.is_empty())+}++fn synthetic_profile_id(model_id: &str) -> Option<&str> {+ synthetic_model_parts(model_id).map(|(_, profile)| profile)+}++fn canonical_pinned_model_id(raw: &str) -> Option<String> {+ let raw = raw.trim();+ if raw.is_empty() {+ return None;+ }+ let (base, profile) = match raw.split_once(':') {+ Some((base, profile)) => (base.trim(), profile.trim()),+ None => (raw, ""),+ };+ if base.is_empty() {+ return None;+ }+ if profile.is_empty() || profile.eq_ignore_ascii_case("default") {+ return Some(base.to_string());+ }+ Some(format!("{}:{}", base, profile.to_ascii_lowercase()))+}++fn base_model_id_for_residency(model_id: &str) -> &str {+ synthetic_model_parts(model_id)+ .map(|(base, _)| base)+ .unwrap_or(model_id)+}++fn warm_set_contains_base_model(models: &HashSet<String>, base_model_id: &str) -> bool {+ models+ .iter()+ .any(|model_id| base_model_id_for_residency(model_id) == base_model_id)+}++fn residency_policy_for_base_model(+ base_model_id: &str,+ preload: &HashSet<String>,+ pinned: &HashSet<String>,+) -> ResidencyPolicy {+ ResidencyPolicy {+ pinned: warm_set_contains_base_model(pinned, base_model_id),+ preload: warm_set_contains_base_model(preload, base_model_id),+ }+}++fn effective_model_id(model_id: &str, requested_profile: Option<&str>) -> Option<String> {+ let model_id = canonical_pinned_model_id(model_id)?;+ let Some(requested_profile) = requested_profile.and_then(non_empty_str) else {+ return Some(model_id);+ };+ if requested_profile.eq_ignore_ascii_case("default") {+ return Some(model_id);+ }+ if let Some((_, synthetic_profile)) = synthetic_model_parts(&model_id) {+ return synthetic_profile+ .eq_ignore_ascii_case(requested_profile)+ .then_some(model_id);+ }+ canonical_pinned_model_id(&format!("{model_id}:{requested_profile}"))+}++fn telemetry_dimensions_for_route(+ route: &str,+ catalog: &HashMap<String, ModelRuntimeConfig>,+) -> Option<(String, String)> {+ let canonical_route = canonical_pinned_model_id(route)?;+ let model = base_model_id_for_residency(&canonical_route);+ let config = catalog.get(model)?;+ if !config.routable_model_ids.contains(&canonical_route) {+ return None;+ }+ let profile = synthetic_profile_id(&canonical_route).unwrap_or("default");+ config+ .profiles+ .contains_key(profile)+ .then(|| (model.to_string(), profile.to_string()))+}++fn telemetry_dimensions_for_base_model(+ base_model_id: &str,+ catalog: &HashMap<String, ModelRuntimeConfig>,+) -> Vec<(String, String)> {+ let Some(config) = catalog.get(base_model_id) else {+ return Vec::new();+ };+ config+ .routable_model_ids+ .iter()+ .filter_map(|route| telemetry_dimensions_for_route(route, catalog))+ .collect()+}++fn catalog_config_unchanged_for_model(+ model_id: &str,+ current: &HashMap<String, ModelRuntimeConfig>,+ next: &HashMap<String, ModelRuntimeConfig>,+) -> bool {+ let base_model_id = synthetic_model_parts(model_id)+ .map(|(base, _)| base)+ .unwrap_or(model_id);+ match (current.get(base_model_id), next.get(base_model_id)) {+ (Some(current_config), Some(next_config)) => current_config == next_config,+ _ => false,+ }+}++fn loaded_model_routes_for_catalog(+ loaded_model_ids: &[String],+ catalog: &HashMap<String, ModelRuntimeConfig>,+) -> Vec<String> {+ let mut models: Vec<String> = loaded_model_ids+ .iter()+ .flat_map(|model_id| {+ catalog+ .get(model_id)+ .or_else(|| {+ synthetic_model_parts(model_id)+ .map(|(base, _)| base)+ .and_then(|base| catalog.get(base))+ })+ .map(|config| config.routable_model_ids.clone())+ .unwrap_or_else(|| {+ canonical_pinned_model_id(model_id)+ .map(|id| vec![id])+ .unwrap_or_default()+ })+ })+ .collect();+ models.sort();+ models.dedup();+ models+}++fn normalize_pinned_model_ids(raw_ids: &[String]) -> HashSet<String> {+ raw_ids+ .iter()+ .filter_map(|raw| canonical_pinned_model_id(raw))+ .collect()+}++fn error_chain(error: &anyhow::Error) -> String {+ error+ .chain()+ .map(ToString::to_string)+ .collect::<Vec<_>>()+ .join(": ")+}++fn is_oom_error(error: &anyhow::Error) -> bool {+ let error = error_chain(error).to_ascii_lowercase();+ OOM_ERROR_INDICATORS+ .iter()+ .any(|indicator| error.contains(indicator))+}++fn option_str<'a>(options: Option<&'a Json>, key: &str) -> Option<&'a str> {+ option_string(options, key).and_then(non_empty_str)+}++fn requested_item_profile<'a>(+ options: Option<&'a Json>,+ profile_id: Option<&'a str>,+) -> Option<&'a str> {+ option_str(options, "profile").or_else(|| profile_id.and_then(non_empty_str))+}++fn option_string<'a>(options: Option<&'a Json>, key: &str) -> Option<&'a str> {+ options+ .and_then(Json::as_object)+ .and_then(|map| map.get(key))+ .and_then(Json::as_str)+}++fn option_bool(options: Option<&Json>, key: &str) -> Option<bool> {+ options+ .and_then(Json::as_object)+ .and_then(|map| map.get(key))+ .and_then(Json::as_bool)+}++fn option_output_types(options: Option<&Json>) -> Option<Vec<String>> {+ options+ .and_then(Json::as_object)+ .and_then(|map| map.get("output_types"))+ .and_then(Json::as_array)+ .map(|values| {+ values+ .iter()+ .filter_map(Json::as_str)+ .filter_map(non_empty_str)+ .map(str::to_string)+ .collect::<Vec<_>>()+ })+ .filter(|values| !values.is_empty())+}++fn candle_backend_diagnostics_enabled() -> bool {+ std::env::var("SIE_CANDLE_DIAGNOSTICS")+ .ok()+ .or_else(|| std::env::var("SIE_CANDLE_DEBUG_KERNELS").ok())+ .map(|value| {+ !matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "" | "0" | "false" | "no" | "off"+ )+ })+ .unwrap_or(false)+}++fn candle_slow_forward_log_threshold_ms() -> Option<f64> {+ static THRESHOLD: OnceLock<Option<f64>> = OnceLock::new();+ *THRESHOLD.get_or_init(|| {+ let Ok(raw) = std::env::var("SIE_CANDLE_SLOW_FORWARD_LOG_MS") else {+ return Some(DEFAULT_SLOW_FORWARD_LOG_MS);+ };+ let trimmed = raw.trim();+ if matches!(+ trimmed.to_ascii_lowercase().as_str(),+ "" | "0" | "false" | "no" | "off"+ ) {+ return None;+ }+ match trimmed.parse::<f64>() {+ Ok(value) if value.is_finite() && value > 0.0 => Some(value),+ Err(_) | Ok(_) => Some(DEFAULT_SLOW_FORWARD_LOG_MS),+ }+ })+}++fn selected_runtime_defaults(+ model_id: &str,+ requested_profile: Option<&str>,+ profiles: &HashMap<String, RuntimeDefaults>,+) -> RuntimeDefaults {+ let requested_profile = requested_profile.and_then(non_empty_str);+ let synthetic_profile = synthetic_profile_id(model_id);+ for profile in [+ requested_profile.filter(|profile| *profile != "default"),+ synthetic_profile,+ requested_profile.filter(|profile| *profile == "default"),+ Some("default"),+ ]+ .into_iter()+ .flatten()+ {+ if let Some(defaults) = profiles.get(profile) {+ return defaults.clone();+ }+ }++ RuntimeDefaults::default()+}++fn parse_runtime_config(+ expected_model_id: &str,+ model_config: &str,+) -> Result<(String, ModelRuntimeConfig)> {+ if model_config.trim().is_empty() {+ anyhow::bail!("model_config is required");+ }+ let model_config: ModelConfigYaml = serde_yaml::from_str(model_config)+ .with_context(|| format!("invalid model_config for {expected_model_id}"))?;+ if !expected_model_id.is_empty() && model_config.sie_id != expected_model_id {+ anyhow::bail!(+ "model_id mismatch: notification={:?} config={:?}",+ expected_model_id,+ model_config.sie_id+ );+ }+ let routable_model_ids = candle_routable_model_ids(&model_config);+ if routable_model_ids.is_empty() {+ anyhow::bail!(+ "Candle model {} has no profiles using adapter module {CANDLE_ADAPTER_MODULE}",+ model_config.sie_id+ );+ }+ validate_candle_profile_loadtime(&model_config)?;+ let candle_profile_id = selected_candle_profile_id(&model_config)?;+ let compute_precision =+ effective_compute_precision(&candle_profile_id, &model_config.profiles, &mut Vec::new());+ let loadtime = resolved_loadtime(&candle_profile_id, &model_config.profiles, &mut Vec::new());+ let max_sequence_length =+ runtime_usize(&loadtime, "max_seq_length").or(model_config.max_sequence_length);+ let query_max_length = runtime_usize(&loadtime, "query_max_length");++ let mut profiles = HashMap::new();+ for profile_id in model_config.profiles.keys() {+ let runtime = resolved_runtime(profile_id, &model_config.profiles, &mut Vec::new());+ let mut defaults = RuntimeDefaults::from_runtime(&runtime);+ defaults.max_batch_tokens =+ effective_max_batch_tokens(profile_id, &model_config.profiles, &mut Vec::new());+ if candle_profile_uses_candle_adapter(profile_id, &model_config.profiles) {+ let loadtime = resolved_loadtime(profile_id, &model_config.profiles, &mut Vec::new());+ defaults.score_strategy = candle_score_strategy(loadtime.get("score_strategy"))?;+ }+ profiles.insert(profile_id.clone(), defaults);+ }+ let task_kind = CandleTaskKind::from_tasks(&model_config.tasks);+ let dense_dim = dense_dim_from_tasks(&model_config.tasks);+ let sparse_dim = sparse_dim_from_tasks(&model_config.tasks);+ let multivector_dim = multivector_dim_from_tasks(&model_config.tasks);+ let sie_id = model_config.sie_id;+ let hf_id = model_config+ .hf_id+ .filter(|value| !value.trim().is_empty())+ .unwrap_or_else(|| sie_id.clone());+ let hf_revision = model_config+ .hf_revision+ .filter(|value| !value.trim().is_empty());+ Ok((+ sie_id,+ ModelRuntimeConfig {+ hf_id,+ hf_revision,+ max_sequence_length,+ query_max_length,+ dense_dim,+ sparse_dim,+ multivector_dim,+ compute_precision,+ profiles,+ routable_model_ids,+ task_kind,+ },+ ))+}++fn validate_candle_profile_loadtime(model_config: &ModelConfigYaml) -> Result<()> {+ let task_token_dim = multivector_dim_from_tasks(&model_config.tasks);+ for profile_id in model_config+ .profiles+ .keys()+ .filter(|profile_id| candle_profile_uses_candle_adapter(profile_id, &model_config.profiles))+ {+ let loadtime = resolved_loadtime(profile_id, &model_config.profiles, &mut Vec::new());+ for key in loadtime.keys() {+ if !matches!(+ key.as_str(),+ "max_seq_length"+ | "query_max_length"+ | "token_dim"+ | "normalize"+ | "score_strategy"+ | "skip_special_tokens"+ | "trust_remote_code"+ ) {+ anyhow::bail!(+ "Candle model {} profile {profile_id} has unsupported loadtime option {key}",+ model_config.sie_id+ );+ }+ }+ for key in ["max_seq_length", "query_max_length"] {+ if let Some(value) = loadtime.get(key) {+ let value = value.as_u64().with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime {key} must be a positive integer",+ model_config.sie_id+ )+ })?;+ if value == 0 || usize::try_from(value).is_err() {+ anyhow::bail!(+ "Candle model {} profile {profile_id} loadtime {key} must fit usize and be positive",+ model_config.sie_id+ );+ }+ }+ }+ if let Some(token_dim) = loadtime.get("token_dim") {+ let token_dim = token_dim.as_u64().with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime token_dim must be a positive integer",+ model_config.sie_id+ )+ })?;+ let token_dim = usize::try_from(token_dim).context("token_dim does not fit usize")?;+ if token_dim == 0 || Some(token_dim) != task_token_dim {+ anyhow::bail!(+ "Candle model {} profile {profile_id} loadtime token_dim {token_dim} must equal tasks.encode.multivector.dim {:?}",+ model_config.sie_id,+ task_token_dim+ );+ }+ }+ let score_strategy =+ candle_score_strategy(loadtime.get("score_strategy")).with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime score_strategy is invalid",+ model_config.sie_id+ )+ })?;+ let loadtime_normalize = loadtime+ .get("normalize")+ .map(|loadtime_normalize| {+ loadtime_normalize.as_bool().with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime normalize must be a boolean",+ model_config.sie_id+ )+ })+ })+ .transpose()?;+ let runtime = resolved_runtime(profile_id, &model_config.profiles, &mut Vec::new());+ let runtime_normalize = runtime.get("normalize").and_then(Json::as_bool);+ if let Some(loadtime_normalize) = loadtime_normalize {+ if runtime_normalize != Some(loadtime_normalize) {+ anyhow::bail!(+ "Candle model {} profile {profile_id} loadtime normalize={loadtime_normalize} must match explicit runtime normalize={runtime_normalize:?}",+ model_config.sie_id+ );+ }+ }+ if score_strategy == Some(CandleScoreStrategy::ColbertMaxsim)+ && (loadtime_normalize != Some(true) || runtime_normalize != Some(true))+ {+ anyhow::bail!(+ "Candle model {} profile {profile_id} score_strategy=colbert_maxsim requires resolved loadtime normalize=true and runtime normalize=true",+ model_config.sie_id+ );+ }+ if let Some(skip_special_tokens) = loadtime.get("skip_special_tokens") {+ let skip_special_tokens = skip_special_tokens.as_bool().with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime skip_special_tokens must be a boolean",+ model_config.sie_id+ )+ })?;+ if skip_special_tokens {+ anyhow::bail!(+ "Candle model {} profile {profile_id} requests skip_special_tokens=true, which the native Candle path does not support",+ model_config.sie_id+ );+ }+ }+ if let Some(trust_remote_code) = loadtime.get("trust_remote_code") {+ let trust_remote_code = trust_remote_code.as_bool().with_context(|| {+ format!(+ "Candle model {} profile {profile_id} loadtime trust_remote_code must be a boolean",+ model_config.sie_id+ )+ })?;+ if trust_remote_code {+ anyhow::bail!(+ "Candle model {} profile {profile_id} requests trust_remote_code=true, which the native Candle path does not support",+ model_config.sie_id+ );+ }+ }+ }+ Ok(())+}++fn selected_candle_profile_id(model_config: &ModelConfigYaml) -> Result<String> {+ for profile_id in ["candle", "default"] {+ if candle_profile_uses_candle_adapter(profile_id, &model_config.profiles) {+ return Ok(profile_id.to_string());+ }+ }+ model_config+ .profiles+ .keys()+ .find(|profile_id| candle_profile_uses_candle_adapter(profile_id, &model_config.profiles))+ .cloned()+ .with_context(|| {+ format!(+ "Candle model {} has no profiles using adapter module {CANDLE_ADAPTER_MODULE}",+ model_config.sie_id+ )+ })+}++fn candle_routable_model_ids(model_config: &ModelConfigYaml) -> Vec<String> {+ let mut model_ids: Vec<String> = model_config+ .profiles+ .keys()+ .filter(|profile_id| candle_profile_uses_candle_adapter(profile_id, &model_config.profiles))+ .filter_map(|profile_id| model_id_for_profile(&model_config.sie_id, profile_id))+ .collect();+ model_ids.sort();+ model_ids.dedup();+ model_ids+}++fn candle_profile_uses_candle_adapter(+ profile_id: &str,+ profiles: &BTreeMap<String, ProfileConfigYaml>,+) -> bool {+ effective_adapter_path(profile_id, profiles, &mut Vec::new())+ .map(adapter_module_from_path)+ .is_some_and(|module| module == CANDLE_ADAPTER_MODULE)+}++fn model_id_for_profile(base_model_id: &str, profile_id: &str) -> Option<String> {+ if profile_id.eq_ignore_ascii_case("default") {+ return canonical_pinned_model_id(base_model_id);+ }+ canonical_pinned_model_id(&format!("{base_model_id}:{profile_id}"))+}++fn effective_adapter_path<'a>(+ profile_id: &str,+ profiles: &'a BTreeMap<String, ProfileConfigYaml>,+ stack: &mut Vec<String>,+) -> Option<&'a str> {+ if stack.iter().any(|seen| seen == profile_id) {+ return None;+ }+ let profile = profiles.get(profile_id)?;+ if let Some(adapter_path) = profile.adapter_path.as_deref().and_then(non_empty_str) {+ return Some(adapter_path);+ }+ stack.push(profile_id.to_string());+ let adapter_path = profile+ .extends+ .as_deref()+ .and_then(|parent| effective_adapter_path(parent, profiles, stack));+ stack.pop();+ adapter_path+}++fn effective_compute_precision(+ profile_id: &str,+ profiles: &BTreeMap<String, ProfileConfigYaml>,+ stack: &mut Vec<String>,+) -> Option<String> {+ if stack.iter().any(|seen| seen == profile_id) {+ return None;+ }+ let profile = profiles.get(profile_id)?;+ if let Some(compute_precision) = profile+ .compute_precision+ .as_deref()+ .and_then(non_empty_str)+ .map(str::to_string)+ {+ return Some(compute_precision);+ }+ stack.push(profile_id.to_string());+ let compute_precision = profile+ .extends+ .as_deref()+ .and_then(|parent| effective_compute_precision(parent, profiles, stack));+ stack.pop();+ compute_precision+}++fn effective_max_batch_tokens(+ profile_id: &str,+ profiles: &BTreeMap<String, ProfileConfigYaml>,+ stack: &mut Vec<String>,+) -> Option<usize> {+ if stack.iter().any(|seen| seen == profile_id) {+ return None;+ }+ let profile = profiles.get(profile_id)?;+ if let Some(max_batch_tokens) = profile.max_batch_tokens.filter(|value| *value > 0) {+ return Some(max_batch_tokens);+ }+ stack.push(profile_id.to_string());+ let max_batch_tokens = profile+ .extends+ .as_deref()+ .and_then(|parent| effective_max_batch_tokens(parent, profiles, stack));+ stack.pop();+ max_batch_tokens+}++fn adapter_module_from_path(adapter_path: &str) -> &str {+ adapter_path+ .split_once(':')+ .map(|(module, _)| module)+ .unwrap_or(adapter_path)+}++impl RuntimeDefaults {+ fn from_runtime(runtime: &BTreeMap<String, Json>) -> Self {+ Self {+ query_template: runtime_string(runtime, "query_template"),+ doc_template: runtime_string(runtime, "doc_template"),+ default_instruction: runtime_string(runtime, "default_instruction")+ .or_else(|| runtime_string(runtime, "instruction")),+ normalize: runtime_bool(runtime, "normalize"),+ pooling: runtime_string(runtime, "pooling"),+ output_dtype: runtime_string(runtime, "output_dtype"),+ max_batch_tokens: None,+ // Load-time and profile-specific; populated by+ // `parse_runtime_config` only for native Candle profiles.+ score_strategy: None,+ }+ }+}++impl CandleTaskKind {+ fn from_tasks(tasks: &TasksYaml) -> Self {+ let encode_dense = tasks.encode.as_ref().is_some_and(encode_has_dense);+ let encode_sparse = tasks.encode.as_ref().is_some_and(encode_has_sparse);+ let encode_multivector = tasks.encode.as_ref().is_some_and(encode_has_multivector);+ let score = tasks.score.is_some();+ match (encode_dense || encode_sparse || encode_multivector, score) {+ (true, true) if encode_multivector && !encode_dense => Self::EmbeddingAndRerank,+ (true, _) => Self::Embedding,+ (false, true) => Self::Rerank,+ (false, false) => Self::Embedding,+ }+ }+}++fn encode_has_dense(value: &Json) -> bool {+ value+ .as_object()+ .and_then(|map| map.get("dense"))+ .is_some_and(|dense| !dense.is_null())+}++fn encode_has_sparse(value: &Json) -> bool {+ value+ .as_object()+ .and_then(|map| map.get("sparse"))+ .is_some_and(|sparse| !sparse.is_null())+}++fn encode_has_multivector(value: &Json) -> bool {+ value+ .as_object()+ .and_then(|map| map.get("multivector"))+ .is_some_and(|multivector| !multivector.is_null())+}++fn dense_dim_from_tasks(tasks: &TasksYaml) -> Option<usize> {+ tasks+ .encode+ .as_ref()?+ .as_object()?+ .get("dense")?+ .as_object()?+ .get("dim")?+ .as_u64()+ .map(|dim| dim as usize)+}++fn sparse_dim_from_tasks(tasks: &TasksYaml) -> Option<usize> {+ tasks+ .encode+ .as_ref()?+ .as_object()?+ .get("sparse")?+ .as_object()?+ .get("dim")?+ .as_u64()+ .map(|dim| dim as usize)+}++fn multivector_dim_from_tasks(tasks: &TasksYaml) -> Option<usize> {+ tasks+ .encode+ .as_ref()?+ .as_object()?+ .get("multivector")?+ .as_object()?+ .get("dim")?+ .as_u64()+ .map(|dim| dim as usize)+}++fn resolved_runtime(+ profile_id: &str,+ profiles: &BTreeMap<String, ProfileConfigYaml>,+ stack: &mut Vec<String>,+) -> BTreeMap<String, Json> {+ if stack.iter().any(|seen| seen == profile_id) {+ return BTreeMap::new();+ }+ let Some(profile) = profiles.get(profile_id) else {+ return BTreeMap::new();+ };+ stack.push(profile_id.to_string());+ let inherited = profile+ .extends+ .as_deref()+ .map(|parent| resolved_runtime(parent, profiles, stack))+ .unwrap_or_default();+ let runtime = if profile.adapter_options.runtime.is_empty() {+ inherited+ } else {+ profile.adapter_options.runtime.clone()+ };+ stack.pop();+ runtime+}++fn resolved_loadtime(+ profile_id: &str,+ profiles: &BTreeMap<String, ProfileConfigYaml>,+ stack: &mut Vec<String>,+) -> BTreeMap<String, Json> {+ if stack.iter().any(|seen| seen == profile_id) {+ return BTreeMap::new();+ }+ let Some(profile) = profiles.get(profile_id) else {+ return BTreeMap::new();+ };+ stack.push(profile_id.to_string());+ let inherited = profile+ .extends+ .as_deref()+ .map(|parent| resolved_loadtime(parent, profiles, stack))+ .unwrap_or_default();+ let loadtime = if profile.adapter_options.loadtime.is_empty() {+ inherited+ } else {+ profile.adapter_options.loadtime.clone()+ };+ stack.pop();+ loadtime+}++fn runtime_string(runtime: &BTreeMap<String, Json>, key: &str) -> Option<String> {+ runtime+ .get(key)+ .and_then(Json::as_str)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+}++fn runtime_usize(runtime: &BTreeMap<String, Json>, key: &str) -> Option<usize> {+ runtime.get(key)?.as_u64().map(|value| value as usize)+}++fn runtime_bool(runtime: &BTreeMap<String, Json>, key: &str) -> Option<bool> {+ runtime.get(key).and_then(Json::as_bool)+}++fn candle_score_strategy(value: Option<&Json>) -> Result<Option<CandleScoreStrategy>> {+ let Some(value) = value else {+ return Ok(None);+ };+ match value.as_str() {+ Some("colbert_maxsim") => Ok(Some(CandleScoreStrategy::ColbertMaxsim)),+ Some(other) => anyhow::bail!("score_strategy must be 'colbert_maxsim'; got {other:?}"),+ None => anyhow::bail!("score_strategy must be a string"),+ }+}++fn resolve_instruction<'a>(+ request_instruction: Option<&'a str>,+ options: Option<&'a Json>,+ default_instruction: Option<&'a str>,+) -> Option<&'a str> {+ request_instruction+ .or_else(|| option_string(options, "instruction"))+ .or_else(|| option_string(options, "default_instruction"))+ .or(default_instruction)+}++/// Match the Python ColBERT score entrypoint rather than encode-time text+/// preparation. Queue ingress owns instruction precedence and supplies the+/// canonical value here; profile defaults and encode-time options remain+/// benign but do not modify score text.+fn prepare_colbert_score_texts(+ query_text: &str,+ raw_docs: &[&str],+ request_instruction: Option<&str>,+) -> (CandleEncodeRequest, Vec<CandleEncodeRequest>, bool) {+ let instruction = request_instruction;+ let query = CandleEncodeRequest {+ text: TextPrep {+ instruction,+ is_query: true,+ query_template: None,+ doc_template: None,+ }+ .apply(query_text),+ };+ let docs = raw_docs+ .iter()+ .map(|text| CandleEncodeRequest {+ text: (*text).to_string(),+ })+ .collect();+ (query, docs, instruction.is_none())+}++fn extract_text(item: &Json) -> std::result::Result<&str, &'static str> {+ let object = item+ .as_object()+ .ok_or("item must be a map containing text")?;+ match object.get("text") {+ Some(Json::String(text)) => Ok(text),+ Some(Json::Null) => Err("item requires a non-null string 'text' field"),+ Some(_) => Err("item field 'text' must be a string or null"),+ None => match object.get("content") {+ Some(Json::String(content)) => Ok(content),+ Some(Json::Null) => Err("item requires a non-null string 'content' field"),+ Some(_) => Err("item field 'content' must be a string or null"),+ None => Err("item must contain a string 'text' or 'content' field"),+ },+ }+}++fn item_id(item: &Json) -> std::result::Result<Option<&str>, &'static str> {+ let object = item+ .as_object()+ .ok_or("item must be a map containing text")?;+ match object.get("id") {+ None | Some(Json::Null) => Ok(None),+ Some(Json::String(id)) => Ok(Some(id)),+ Some(_) => Err("item field 'id' must be a string or null"),+ }+}++fn score_item_id(item: &Json, index: usize) -> std::result::Result<String, &'static str> {+ Ok(item_id(item)?+ .map(str::to_string)+ .unwrap_or_else(|| format!("item-{index}")))+}++fn error_outcome(item: &EncodeBatchItem, code: &str, message: &str) -> ItemOutcome {+ identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ code,+ message,+ )+}++fn score_error_outcome(item: &ScoreBatchItem, code: &str, message: &str) -> ItemOutcome {+ identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ code,+ message,+ )+}++fn checked_score_input_tokens(query_tokens: u64, doc_tokens: &[u64]) -> Option<u64> {+ let document_tokens = doc_tokens+ .iter()+ .try_fold(0_u64, |total, tokens| total.checked_add(*tokens))?;+ let query_uses = query_tokens.checked_mul(u64::try_from(doc_tokens.len()).ok()?)?;+ document_tokens.checked_add(query_uses)+}++fn score_input_tokens(query_tokens: usize, doc_tokens: &[usize]) -> Option<u64> {+ let query_tokens = u64::try_from(query_tokens).ok()?;+ let doc_tokens = doc_tokens+ .iter()+ .map(|tokens| u64::try_from(*tokens))+ .collect::<std::result::Result<Vec<_>, _>>()+ .ok()?;+ checked_score_input_tokens(query_tokens, &doc_tokens)+}++fn success_score_outcome(+ item: &ScoreBatchItem,+ item_ids: &[String],+ result: CandleScoreResult,+) -> ItemOutcome {+ let Some(input_tokens) = score_input_tokens(result.query_tokens, &result.doc_tokens) else {+ return score_error_outcome(+ item,+ "candle_metering_overflow",+ "Candle score token count overflowed the authoritative unit counter",+ );+ };+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::PublishAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: Some(result.inference_ms),+ tokenization_ms: Some(result.tokenization_ms),+ // The inclusive inference duration already contains MaxSim. Publishing+ // it as postprocessing as well would make the sidecar double-count it.+ postprocessing_ms: None,+ raw_output: Some(RawOutput {+ dense: None,+ score: Some(ScoreOutputRaw {+ scores: result.scores,+ item_ids: item_ids.to_vec(),+ }),+ sparse: None,+ multivector: None,+ }),+ units: Some(UnitCounts {+ input_tokens: Some(input_tokens),+ pages: None,+ images: None,+ }),+ }+}++fn score_execution_outcome(+ item: &ScoreBatchItem,+ item_ids: &[String],+ execution: ScoreItemExecution,+) -> ItemOutcome {+ let ScoreItemExecution {+ scored,+ lock_wait_ms,+ wall_ms,+ } = execution;+ match scored {+ Ok(result) => {+ if candle_backend_diagnostics_enabled() {+ info!(+ work_item_id = item.work_item_id,+ documents = result.doc_tokens.len(),+ query_tokens = result.query_tokens,+ document_tokens = result.doc_tokens.iter().sum::<usize>(),+ tokenization_ms = result.tokenization_ms,+ inference_ms = result.inference_ms,+ maxsim_ms = result.maxsim_ms,+ wall_ms,+ lock_wait_ms,+ "Candle MaxSim score diagnostics"+ );+ }+ success_score_outcome(item, item_ids, result)+ }+ Err(error) => {+ error!(+ work_item_id = item.work_item_id,+ documents = item_ids.len(),+ wall_ms,+ lock_wait_ms,+ error = %error_chain(&error),+ "Candle MaxSim score failed"+ );+ score_error_outcome(+ item,+ "candle_inference_failed",+ &format!("Candle MaxSim score failed: {error}"),+ )+ }+ }+}++fn score_oom_nak_outcome(item: &ScoreBatchItem, nak_delay_ms: u64) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::NakRetry,+ nak_delay_ms: Some(nak_delay_ms),+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ raw_output: None,+ units: None,+ }+}++fn score_model_load_error_outcome(+ item: &ScoreBatchItem,+ error: &anyhow::Error,+ nak_delay_ms: u64,+) -> ItemOutcome {+ if is_oom_error(error) {+ score_oom_nak_outcome(item, nak_delay_ms)+ } else {+ score_error_outcome(+ item,+ "candle_model_load_failed",+ &format!("Candle model load failed: {error}"),+ )+ }+}++fn success_dense_outcome(+ item: &PreparedEncodeItem,+ values: Vec<f32>,+ dim: u32,+ normalize: bool,+ inference_ms: f64,+ tokenization_ms: f64,+) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::PublishAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: Some(inference_ms),+ tokenization_ms: Some(tokenization_ms),+ postprocessing_ms: None,+ raw_output: Some(RawOutput {+ dense: Some(DenseOutput {+ values,+ dim,+ normalize,+ }),+ score: None,+ sparse: None,+ multivector: None,+ }),+ units: None,+ }+}++fn success_sparse_outcome(+ item: &PreparedEncodeItem,+ sparse: CandleSparseEmbedding,+ dim: u32,+ inference_ms: f64,+ tokenization_ms: f64,+) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::PublishAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: Some(inference_ms),+ tokenization_ms: Some(tokenization_ms),+ postprocessing_ms: None,+ raw_output: Some(RawOutput {+ dense: None,+ score: None,+ sparse: Some(SparseOutput {+ indices: sparse.indices,+ values: sparse.values,+ dims: Some(dim),+ }),+ multivector: None,+ }),+ units: None,+ }+}++fn success_multivector_outcome(+ item: &PreparedEncodeItem,+ multivector: CandleMultivectorEmbedding,+ output_dtype: Option<&str>,+ inference_ms: f64,+ tokenization_ms: f64,+) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::PublishAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: Some(inference_ms),+ tokenization_ms: Some(tokenization_ms),+ postprocessing_ms: None,+ raw_output: Some(RawOutput {+ dense: None,+ score: None,+ sparse: None,+ multivector: Some(MultivectorOutput {+ values: multivector.values,+ values_f16: multivector.values_f16,+ num_tokens: multivector.num_tokens,+ token_dims: multivector.token_dims,+ dtype: Some(multivector_wire_dtype(output_dtype).to_string()),+ }),+ }),+ units: None,+ }+}++fn success_batched_f16_multivector_outcome(+ item: &PreparedEncodeItem,+ inference_ms: f64,+ tokenization_ms: f64,+) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::PublishAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: Some(inference_ms),+ tokenization_ms: Some(tokenization_ms),+ postprocessing_ms: None,+ // The batch-level buffer is authoritative for this outcome. The+ // sidecar validates its offset before producing the public payload.+ raw_output: None,+ units: None,+ }+}++fn identity_error_outcome(+ work_item_id: &str,+ request_id: &str,+ item_index: u32,+ code: &str,+ message: &str,+) -> ItemOutcome {+ ItemOutcome {+ work_item_id: work_item_id.to_string(),+ request_id: request_id.to_string(),+ item_index,+ disposition: Disposition::PublishErrorAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: Some(message.to_string()),+ error_code: Some(code.to_string()),+ inference_ms: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ raw_output: None::<RawOutput>,+ units: None,+ }+}++fn model_load_error_outcome(+ item: &PreparedEncodeItem,+ error: &anyhow::Error,+ nak_delay_ms: u64,+) -> ItemOutcome {+ if is_oom_error(error) {+ return oom_nak_outcome(item, nak_delay_ms);+ }++ identity_error_outcome(+ &item.work_item_id,+ &item.request_id,+ item.item_index,+ "candle_model_load_failed",+ &format!(+ "failed to load Candle embedding model: {}",+ error_chain(error)+ ),+ )+}++fn oom_nak_outcome(item: &PreparedEncodeItem, nak_delay_ms: u64) -> ItemOutcome {+ ItemOutcome {+ work_item_id: item.work_item_id.clone(),+ request_id: item.request_id.clone(),+ item_index: item.item_index,+ disposition: Disposition::NakRetry,+ nak_delay_ms: Some(nak_delay_ms),+ result_msgpack: Vec::new(),+ error: None,+ error_code: None,+ inference_ms: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ raw_output: None::<RawOutput>,+ units: None,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn prepared_encode_item(position: usize) -> PreparedEncodeItem {+ PreparedEncodeItem {+ work_item_id: format!("work-{position}"),+ request_id: "request".to_string(),+ item_index: position as u32,+ text: format!("text-{position}"),+ is_query: false,+ output_dtype: None,+ prepared_tokens: None,+ }+ }++ fn score_batch_item(options: Option<Json>) -> ScoreBatchItem {+ ScoreBatchItem {+ work_item_id: "work".to_string(),+ request_id: "request".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ query_item: serde_json::json!({"text": "query"}),+ score_items: Vec::new(),+ instruction: None,+ options,+ profile_id: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }+ }++ #[test]+ fn instruction_precedence_is_request_then_options_then_default() {+ let options = serde_json::json!({"instruction": "option"});++ assert_eq!(+ resolve_instruction(Some("request"), Some(&options), Some("default")),+ Some("request")+ );+ assert_eq!(+ resolve_instruction(None, Some(&options), Some("default")),+ Some("option")+ );+ assert_eq!(+ resolve_instruction(None, None, Some("default")),+ Some("default")+ );+ assert_eq!(+ resolve_instruction(Some(""), Some(&options), Some("default")),+ Some("")+ );+ let empty_option = serde_json::json!({"instruction": ""});+ assert_eq!(+ resolve_instruction(None, Some(&empty_option), Some("default")),+ Some("")+ );+ let request_default = serde_json::json!({"default_instruction": "request-default"});+ assert_eq!(+ resolve_instruction(None, Some(&request_default), Some("profile-default")),+ Some("request-default")+ );+ }++ #[test]+ fn colbert_score_uses_canonical_instruction_and_preserves_empty_override() {+ let (query, docs, allow_prepared) =+ prepare_colbert_score_texts("query", &["document"], Some("canonical"));+ assert_eq!(query.text, "canonical query");+ assert_eq!(docs[0].text, "document");+ assert!(!allow_prepared);++ let (query, docs, allow_prepared) =+ prepare_colbert_score_texts("query", &["document"], Some(""));+ assert_eq!(query.text, "query");+ assert_eq!(docs[0].text, "document");+ assert!(!allow_prepared);+ }++ #[test]+ fn colbert_score_options_remain_benign_but_do_not_prepare_text() {+ let options = serde_json::json!({+ "instruction": "ignored-option",+ "default_instruction": "ignored-default",+ "query_template": "ignored-query: {text}",+ "doc_template": "ignored-doc: {text}",+ });++ assert!(supported_options(Some(&options), SCORE_OPTION_KEYS));+ let (query, docs, allow_prepared) =+ prepare_colbert_score_texts("query", &["document"], None);+ assert_eq!(query.text, "query");+ assert_eq!(docs[0].text, "document");+ assert!(allow_prepared);+ }++ #[test]+ fn text_items_match_python_content_alias_and_id_contract() {+ assert_eq!(extract_text(&serde_json::json!({"text": ""})), Ok(""));+ assert_eq!(+ extract_text(&serde_json::json!({"content": "alias"})),+ Ok("alias")+ );+ assert_eq!(+ extract_text(&serde_json::json!({"text": "kept", "content": 42})),+ Ok("kept")+ );+ assert!(extract_text(&serde_json::json!({})).is_err());+ assert!(extract_text(&serde_json::json!({"text": null})).is_err());+ assert!(extract_text(&serde_json::json!({"content": null})).is_err());+ assert!(extract_text(&serde_json::json!({"text": 42})).is_err());+ assert!(extract_text(&serde_json::json!("not-a-map")).is_err());++ assert_eq!(item_id(&serde_json::json!({"id": ""})), Ok(Some("")));+ assert_eq!(item_id(&serde_json::json!({"id": null})), Ok(None));+ assert_eq!(item_id(&serde_json::json!({})), Ok(None));+ assert!(item_id(&serde_json::json!({"id": 42})).is_err());+ }++ #[test]+ fn score_options_accept_python_benign_encode_keys_but_reject_unknowns() {+ let benign = serde_json::json!({+ "muvera": {},+ "output_types": ["dense"],+ "output_similarity": {"dense": "dot"},+ "normalize": true,+ "pooling": "mean",+ "query_template": "query: {text}",+ "doc_template": "passage: {text}",+ });+ assert!(supported_options(Some(&benign), SCORE_OPTION_KEYS));+ assert!(!supported_options(+ Some(&serde_json::json!({"lora": "adapter"})),+ SCORE_OPTION_KEYS+ ));+ assert!(!supported_options(+ Some(&serde_json::json!({"unknown": true})),+ SCORE_OPTION_KEYS+ ));+ }++ #[test]+ fn score_unit_count_duplicates_query_work_per_document_and_checks_overflow() {+ assert_eq!(checked_score_input_tokens(3, &[5, 7]), Some(18));+ assert_eq!(checked_score_input_tokens(32, &[]), Some(0));+ assert_eq!(checked_score_input_tokens(u64::MAX, &[1]), None);+ assert_eq!(checked_score_input_tokens(1, &[u64::MAX]), None);+ }++ #[test]+ fn score_oom_outcome_retries_without_publishing_or_metering() {+ let outcome = score_oom_nak_outcome(&score_batch_item(None), 12_345);++ assert_eq!(outcome.disposition, Disposition::NakRetry);+ assert_eq!(outcome.nak_delay_ms, Some(12_345));+ assert!(outcome.error.is_none());+ assert!(outcome.error_code.is_none());+ assert!(outcome.raw_output.is_none());+ assert!(outcome.units.is_none());+ }++ #[test]+ fn config_normalizes_bounds() {+ let cfg = CandleBackendConfig::new(0, true, 1);+ assert_eq!(cfg.batch_budget, 1);+ assert!(cfg.normalize);+ assert_eq!(cfg.max_concurrent_forwards, 1);+ }++ #[test]+ fn oom_recovery_defaults_match_python_worker_contract() {+ let cfg = CandleOomRecoveryConfig::default();++ assert!(cfg.enabled);+ assert_eq!(+ cfg.strategy,+ vec![+ CandleOomRecoveryAction::CacheClear,+ CandleOomRecoveryAction::EvictLru,+ CandleOomRecoveryAction::SplitBatch,+ ]+ );+ assert_eq!(cfg.max_split_depth, 4);+ assert_eq!(cfg.nak_delay_ms, 10_000);+ }++ #[test]+ fn oom_recovery_kill_switch_matches_python_override() {+ let mut config = CandleOomRecoveryConfig {+ enabled: true,+ ..CandleOomRecoveryConfig::default()+ };++ apply_oom_recovery_kill_switch(&mut config, Some("true"));++ assert!(!config.enabled);++ let mut config = CandleOomRecoveryConfig {+ enabled: true,+ ..CandleOomRecoveryConfig::default()+ };++ apply_oom_recovery_kill_switch(&mut config, Some("false"));++ assert!(config.enabled);+ }++ #[test]+ fn oom_recovery_strategy_parse_dedups_and_accepts_jsonish_list() {+ let parsed = parse_oom_recovery_strategy(+ r#"["cache_clear", "evict_lru", "evict_lru", "split_batch"]"#,+ )+ .unwrap();++ assert_eq!(+ parsed,+ vec![+ CandleOomRecoveryAction::CacheClear,+ CandleOomRecoveryAction::EvictLru,+ CandleOomRecoveryAction::SplitBatch,+ ]+ );+ }++ #[test]+ fn oom_recovery_strategy_rejects_empty_or_unknown_actions() {+ assert!(parse_oom_recovery_strategy(" ").is_err());+ assert!(parse_oom_recovery_strategy("cache_clear,unknown").is_err());+ }++ #[test]+ fn oom_recovery_env_value_parsers_match_python_bounds() {+ assert!(parse_env_bool("TEST", "true").unwrap());+ assert!(!parse_env_bool("TEST", "off").unwrap());+ assert!(parse_env_bool("TEST", "wat").is_err());+ assert_eq!(parse_oom_max_split_depth("8").unwrap(), 8);+ assert!(parse_oom_max_split_depth("9").is_err());+ assert_eq!(parse_oom_nak_delay_ms("2.5").unwrap(), 2500);+ assert!(parse_oom_nak_delay_ms("0").is_err());+ }++ #[test]+ fn oom_recovery_steps_retry_before_eviction_and_split() {+ let strategy = vec![+ CandleOomRecoveryAction::CacheClear,+ CandleOomRecoveryAction::EvictLru,+ CandleOomRecoveryAction::SplitBatch,+ ];+ let mut cursor = 0usize;++ let cache_step = next_oom_recovery_step(&strategy, &mut cursor, || {+ panic!("cache_clear must not invoke LRU eviction")+ });+ let evict_step =+ next_oom_recovery_step(&strategy, &mut cursor, || Some("sibling".to_string()));+ let split_step = next_oom_recovery_step(&strategy, &mut cursor, || None);++ assert_eq!(cache_step, OomRecoveryStep::RetryAfterCacheClear);+ assert_eq!(+ evict_step,+ OomRecoveryStep::RetryAfterEviction("sibling".to_string())+ );+ assert_eq!(split_step, OomRecoveryStep::SplitBatch);+ }++ #[test]+ fn oom_recovery_steps_skip_empty_eviction_and_eventually_terminal() {+ let strategy = vec![+ CandleOomRecoveryAction::EvictLru,+ CandleOomRecoveryAction::SplitBatch,+ ];+ let mut cursor = 0usize;++ let split_step = next_oom_recovery_step(&strategy, &mut cursor, || None);+ let terminal_step = next_oom_recovery_step(&strategy, &mut cursor, || {+ panic!("terminal strategy must not keep evicting")+ });++ assert_eq!(split_step, OomRecoveryStep::SplitBatch);+ assert_eq!(terminal_step, OomRecoveryStep::Terminal);+ }++ #[test]+ fn output_dtype_policy_is_kind_aware() {+ assert!(output_dtype_error_for_kind(Some("float16"), EncodeOutputKind::Dense).is_some());+ assert!(+ output_dtype_error_for_kind(Some("float16"), EncodeOutputKind::Multivector).is_none()+ );+ assert_eq!(multivector_wire_dtype(None), "float32");+ assert_eq!(multivector_wire_dtype(Some("float16")), "float16");+ assert_eq!(multivector_wire_dtype(Some("float32")), "float32");+ }++ #[test]+ fn forward_output_path_is_closed_and_preserves_f16_wire_choice() {+ fn context(+ output_kind: EncodeOutputKind,+ output_dtype: &str,+ accepts_batched_f16_multivectors: bool,+ ) -> EncodeGroupContext<'_> {+ EncodeGroupContext {+ model_id: "test/model",+ output_kind,+ pooling: "mean",+ normalize: true,+ is_query: false,+ output_dtype,+ accepts_batched_f16_multivectors,+ }+ }++ assert_eq!(+ forward_output_path(context(EncodeOutputKind::Dense, "float32", false)),+ ForwardOutputPath::Dense+ );+ assert_eq!(+ forward_output_path(context(EncodeOutputKind::Multivector, "float32", false)),+ ForwardOutputPath::MultivectorF32+ );+ assert_eq!(+ forward_output_path(context(EncodeOutputKind::Multivector, "float16", true)),+ ForwardOutputPath::MultivectorF16Batched+ );+ assert_eq!(+ forward_output_path(context(EncodeOutputKind::Multivector, "float16", false)),+ ForwardOutputPath::MultivectorF16Individual+ );+ }++ #[test]+ fn oom_nak_outcome_matches_queue_retry_contract() {+ let item = PreparedEncodeItem {+ work_item_id: "work".to_string(),+ request_id: "request".to_string(),+ item_index: 7,+ text: "hello".to_string(),+ is_query: false,+ output_dtype: None,+ prepared_tokens: None,+ };++ let outcome = oom_nak_outcome(&item, 12_345);++ assert_eq!(outcome.work_item_id, "work");+ assert_eq!(outcome.request_id, "request");+ assert_eq!(outcome.item_index, 7);+ assert_eq!(outcome.disposition, Disposition::NakRetry);+ assert_eq!(outcome.nak_delay_ms, Some(12_345));+ assert!(outcome.error.is_none());+ assert!(outcome.error_code.is_none());+ assert!(outcome.raw_output.is_none());+ }++ #[test]+ fn model_load_oom_outcome_naks_without_publishing_error() {+ let item = PreparedEncodeItem {+ work_item_id: "work".to_string(),+ request_id: "request".to_string(),+ item_index: 7,+ text: "hello".to_string(),+ is_query: false,+ output_dtype: None,+ prepared_tokens: None,+ };+ let oom_error = anyhow::anyhow!("failed to allocate tensor");+ let non_oom_error = anyhow::anyhow!("missing config");++ let oom_outcome = model_load_error_outcome(&item, &oom_error, 12_345);+ assert_eq!(oom_outcome.disposition, Disposition::NakRetry);+ assert_eq!(oom_outcome.nak_delay_ms, Some(12_345));+ assert!(oom_outcome.error.is_none());+ assert!(oom_outcome.error_code.is_none());++ let non_oom_outcome = model_load_error_outcome(&item, &non_oom_error, 12_345);+ assert_eq!(non_oom_outcome.disposition, Disposition::PublishErrorAndAck);+ assert_eq!(+ non_oom_outcome.error_code.as_deref(),+ Some("candle_model_load_failed")+ );+ assert!(non_oom_outcome.nak_delay_ms.is_none());+ }++ #[test]+ fn model_load_error_fanout_naks_oom_groups() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1).with_oom_recovery(+ CandleOomRecoveryConfig {+ nak_delay_ms: 12_345,+ ..CandleOomRecoveryConfig::default()+ },+ ));+ let mut groups = BTreeMap::new();+ groups.insert(+ (+ EncodeOutputKind::Dense,+ "mean".to_string(),+ true,+ false,+ "float32".to_string(),+ ),+ vec![(2, prepared_encode_item(2)), (0, prepared_encode_item(0))],+ );+ groups.insert(+ (+ EncodeOutputKind::Dense,+ "cls".to_string(),+ false,+ false,+ "float32".to_string(),+ ),+ vec![(1, prepared_encode_item(1))],+ );+ let mut outcomes = vec![None, None, None];+ let oom_error = anyhow::anyhow!("CUDA out of memory");++ backend.mark_model_load_error_outcomes("test/model", &groups, &oom_error, &mut outcomes);++ for (position, outcome) in outcomes.iter().enumerate() {+ let outcome = outcome.as_ref().expect("outcome should be populated");+ assert_eq!(outcome.work_item_id, format!("work-{position}"));+ assert_eq!(outcome.request_id, "request");+ assert_eq!(outcome.item_index, position as u32);+ assert_eq!(outcome.disposition, Disposition::NakRetry);+ assert_eq!(outcome.nak_delay_ms, Some(12_345));+ assert!(outcome.error.is_none());+ assert!(outcome.error_code.is_none());+ }+ }++ #[test]+ fn split_encode_group_halves_without_reordering() {+ let group: Vec<(usize, PreparedEncodeItem)> = (0..5)+ .map(|position| {+ (+ position,+ PreparedEncodeItem {+ work_item_id: format!("work-{position}"),+ request_id: "request".to_string(),+ item_index: position as u32,+ text: format!("text-{position}"),+ is_query: false,+ output_dtype: None,+ prepared_tokens: None,+ },+ )+ })+ .collect();++ let (left, right) = split_encode_group(group);++ assert_eq!(+ left.iter()+ .map(|(position, _)| *position)+ .collect::<Vec<_>>(),+ vec![0, 1]+ );+ assert_eq!(+ right+ .iter()+ .map(|(position, _)| *position)+ .collect::<Vec<_>>(),+ vec![2, 3, 4]+ );+ }++ #[test]+ fn pinned_model_normalization_preserves_hf_case_and_folds_default() {+ let normalized = normalize_pinned_model_ids(&[+ " BAAI/bge-m3:default ".to_string(),+ "BAAI/bge-m3:CANDLE".to_string(),+ "Other/Model:Custom".to_string(),+ "".to_string(),+ ]);++ assert_eq!(normalized.len(), 3);+ assert!(normalized.contains("BAAI/bge-m3"));+ assert!(normalized.contains("BAAI/bge-m3:candle"));+ assert!(normalized.contains("Other/Model:custom"));+ }++ #[test]+ fn effective_model_id_merges_queue_profile_with_base_model() {+ assert_eq!(+ effective_model_id("BAAI/bge-m3", Some("CANDLE")).as_deref(),+ Some("BAAI/bge-m3:candle")+ );+ assert_eq!(+ effective_model_id("BAAI/bge-m3:candle", Some("candle")).as_deref(),+ Some("BAAI/bge-m3:candle")+ );+ assert_eq!(+ effective_model_id("BAAI/bge-m3:candle", Some("other")),+ None+ );+ }++ #[test]+ fn request_options_profile_overrides_queue_profile_placeholder() {+ let options = serde_json::json!({"profile": "candle"});++ assert_eq!(+ requested_item_profile(Some(&options), Some("default")),+ Some("candle")+ );+ assert_eq!(requested_item_profile(None, Some("candle")), Some("candle"));+ }++ #[test]+ fn profile_option_validation_rejects_ambiguous_values() {+ assert!(profile_option_error(Some(&serde_json::json!({"profile": 123}))).is_some());+ assert!(profile_option_error(Some(&serde_json::json!({"profile": " "}))).is_some());+ assert!(profile_option_error(Some(&serde_json::json!({"profile": "unknown"}))).is_none());+ assert!(profile_option_error(Some(&serde_json::json!({"profile": null}))).is_none());+ }++ #[test]+ fn residency_policy_matches_profile_qualified_warm_sets_by_base_model() {+ let preload = normalize_pinned_model_ids(&["BAAI/bge-m3:CANDLE".to_string()]);+ let pinned = normalize_pinned_model_ids(&["Other/Model:default".to_string()]);++ assert_eq!(+ residency_policy_for_base_model("BAAI/bge-m3", &preload, &pinned),+ ResidencyPolicy {+ pinned: false,+ preload: true,+ }+ );+ assert_eq!(+ residency_policy_for_base_model("Other/Model", &preload, &pinned),+ ResidencyPolicy {+ pinned: true,+ preload: false,+ }+ );+ }++ #[test]+ fn idle_evict_check_interval_is_bounded() {+ assert_eq!(+ idle_evict_check_interval(Duration::from_secs(10)),+ Duration::from_secs(5)+ );+ assert_eq!(+ idle_evict_check_interval(Duration::from_secs(300)),+ Duration::from_secs(60)+ );+ }++ #[test]+ fn idle_evictor_start_is_disabled_without_ttl() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ assert!(!backend.start_idle_evictor());+ assert!(!backend.stop_idle_evictor());+ }++ #[tokio::test]+ async fn idle_evictor_start_is_idempotent_and_stoppable() {+ let backend = CandleBackend::new(+ CandleBackendConfig::new(64, true, 1).with_idle_evict_s(Some(Duration::from_secs(10))),+ );++ assert!(backend.start_idle_evictor());+ assert!(!backend.start_idle_evictor());+ assert!(backend.stop_idle_evictor());+ assert!(!backend.stop_idle_evictor());+ assert!(backend.start_idle_evictor());+ assert!(backend.stop_idle_evictor());+ }++ #[test]+ fn oom_error_detector_matches_python_indicators() {+ assert!(is_oom_error(&anyhow::anyhow!("CUDA out of memory")));+ let nested = Err::<(), anyhow::Error>(anyhow::anyhow!("failed to allocate tensor"))+ .context("load Candle embedding model")+ .unwrap_err();+ assert!(is_oom_error(&nested));+ assert!(!is_oom_error(&anyhow::anyhow!(+ "failed to load oom-classifier"+ )));+ }++ #[test]+ fn catalog_config_unchanged_requires_identical_base_config() {+ let (_, current_config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+hf_id: old/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse current config");+ let (_, unchanged_config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+hf_id: old/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse unchanged config");+ let (_, changed_config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+hf_id: new/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse changed config");++ let current = HashMap::from([("test/model".to_string(), current_config)]);+ let unchanged = HashMap::from([("test/model".to_string(), unchanged_config)]);+ let changed = HashMap::from([("test/model".to_string(), changed_config)]);++ assert!(catalog_config_unchanged_for_model(+ "test/model",+ ¤t,+ &unchanged+ ));+ assert!(catalog_config_unchanged_for_model(+ "test/model:candle",+ ¤t,+ &unchanged+ ));+ assert!(!catalog_config_unchanged_for_model(+ "test/model",+ ¤t,+ &changed+ ));+ assert!(!catalog_config_unchanged_for_model(+ "missing/model",+ ¤t,+ &unchanged+ ));+ }++ #[test]+ fn loaded_model_routes_expand_resident_base_to_catalog_profiles() {+ let (_, runtime_config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ pytorch:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+"#,+ )+ .expect("parse Candle config");+ let catalog = HashMap::from([("test/model".to_string(), runtime_config)]);++ let routes = loaded_model_routes_for_catalog(&["test/model".to_string()], &catalog);++ assert_eq!(+ routes,+ vec!["test/model".to_string(), "test/model:candle".to_string()]+ );+ assert_eq!(+ telemetry_dimensions_for_route("test/model:candle", &catalog),+ Some(("test/model".to_string(), "candle".to_string()))+ );+ assert_eq!(+ telemetry_dimensions_for_base_model("test/model", &catalog),+ vec![+ ("test/model".to_string(), "default".to_string()),+ ("test/model".to_string(), "candle".to_string()),+ ]+ );+ assert_eq!(+ telemetry_dimensions_for_route("request/supplied", &catalog),+ None+ );+ }++ #[test]+ fn native_worker_advertises_applied_catalog_models() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ assert!(backend.supported_models().is_empty());+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply first Candle model config");+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "other/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: other/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply second Candle model config");++ assert_eq!(+ backend.supported_models(),+ vec!["other/model:candle", "test/model:candle"]+ );+ assert!(backend.supports("test/model:candle"));+ assert!(backend.supports("other/model:candle"));+ assert!(!backend.supports("test/model"));+ assert!(!backend.supports("missing/model:candle"));+ }++ #[test]+ fn set_pinned_models_stores_set_without_missing_catalog_load() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let resp = backend.set_pinned_models(&SetPinnedModelsRequest {+ models: vec![+ " BAAI/bge-m3:default ".to_string(),+ "BAAI/bge-m3:CANDLE".to_string(),+ "".to_string(),+ ],+ });++ assert!(resp.applied);+ assert_eq!(resp.pinned_count, 2);+ let pinned = backend.pinned_models.read().expect("pinned lock");+ assert!(pinned.contains("BAAI/bge-m3"));+ assert!(pinned.contains("BAAI/bge-m3:candle"));+ assert!(backend.loading_embeddings.lock().unwrap().is_empty());+ assert!(backend.loaded_models().is_empty());+ }++ #[test]+ fn set_preload_models_keeps_startup_warm_set_separate_from_pins() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let preload_count = backend.set_preload_models(&[" BAAI/bge-m3:CANDLE ".to_string()]);+ let resp = backend.set_pinned_models(&SetPinnedModelsRequest { models: vec![] });++ assert_eq!(preload_count, 1);+ assert!(resp.applied);+ assert_eq!(resp.pinned_count, 0);+ assert!(backend+ .pinned_models+ .read()+ .expect("pinned lock")+ .is_empty());+ let preload = backend.preload_models.read().expect("preload lock");+ assert!(preload.contains("BAAI/bge-m3:candle"));+ assert!(backend.loading_embeddings.lock().unwrap().is_empty());+ assert!(backend.loaded_models().is_empty());+ }++ #[test]+ fn f16_multivector_output_paths_preserve_wire_behavior() {+ fn group_and_execution() -> (PreparedEncodeGroup, EncodeGroupExecution) {+ let mut item = prepared_encode_item(0);+ item.output_dtype = Some("float16".to_string());+ let group = vec![(0, item)];+ let stats = EncodeGroupStats::from_group(&group);+ let execution = EncodeGroupExecution {+ encoded: Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors: None,+ multivectors_f16: Some(CandleF16MultivectorBatch {+ values_f16: vec![half::f16::from_f32(1.0), half::f16::from_f32(2.0)],+ items: vec![crate::candle_embedding::CandleF16MultivectorItem {+ byte_offset: 0,+ byte_len: 2 * std::mem::size_of::<half::f16>(),+ num_tokens: 1,+ token_dims: 2,+ }],+ }),+ dim: 2,+ tokenization_ms: 0.0,+ inference_ms: 1.0,+ stages: crate::candle_embedding::CandleEncodeStageTimings::default(),+ forward_profile: None,+ }),+ stats,+ lock_wait_ms: 0.0,+ encode_elapsed_ms: 1.0,+ encode_source: "prepared",+ };+ (group, execution)+ }++ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ let mut outcomes = vec![None];+ let mut batched_outputs = Vec::new();+ let (group, execution) = group_and_execution();+ let result = backend.apply_encode_group_execution(+ EncodeGroupContext {+ model_id: "test/model",+ output_kind: EncodeOutputKind::Multivector,+ pooling: "mean",+ normalize: true,+ is_query: false,+ output_dtype: "float16",+ accepts_batched_f16_multivectors: true,+ },+ group,+ execution,+ &mut outcomes,+ &mut batched_outputs,+ );+ assert!(matches!(result, EncodeGroupOutcome::Success { items: 1 }));+ assert_eq!(batched_outputs.len(), 1);+ assert!(outcomes[0]+ .as_ref()+ .expect("batched outcome")+ .raw_output+ .is_none());++ let (group, execution) = group_and_execution();+ let result = backend.apply_encode_group_execution(+ EncodeGroupContext {+ model_id: "test/model",+ output_kind: EncodeOutputKind::Multivector,+ pooling: "mean",+ normalize: true,+ is_query: false,+ output_dtype: "float16",+ accepts_batched_f16_multivectors: false,+ },+ group,+ execution,+ &mut outcomes,+ &mut batched_outputs,+ );+ assert!(matches!(result, EncodeGroupOutcome::Success { items: 1 }));+ assert_eq!(batched_outputs.len(), 1);+ assert!(outcomes[0]+ .as_ref()+ .and_then(|outcome| outcome.raw_output.as_ref())+ .and_then(|output| output.multivector.as_ref())+ .is_some());+ }++ #[test]+ fn apply_model_config_uses_catalog_candle_profile_route() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ adapter_options:+ runtime:+ pooling: mean+ query_template: "default: {text}"+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ query_template: "candle: {text}"+"#+ .to_string(),+ })+ .expect("apply model config");++ assert!(backend.supports("test/model:candle"));+ assert!(!backend.supports("test/model"));+ let defaults = backend.runtime_defaults_for("test/model:candle", None);+ assert_eq!(defaults.query_template.as_deref(), Some("candle: {text}"));+ assert_eq!(defaults.pooling.as_deref(), Some("cls"));+ }++ #[test]+ fn embedding_load_route_keeps_profile_qualified_candle_id() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply model config");++ let (load_model_id, base_model_id) = backend+ .embedding_load_route(" test/model:CANDLE ")+ .expect("profile-qualified Candle route should resolve");++ assert_eq!(load_model_id, "test/model:candle");+ assert_eq!(base_model_id, "test/model");+ assert!(backend.embedding_load_route("test/model").is_err());+ }++ #[test]+ fn candle_profile_nonempty_runtime_replaces_parent_defaults() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: "query: {text}"+ doc_template: "passage: {text}"+ output_dtype: float16+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+"#+ .to_string(),+ })+ .expect("apply model config");++ let defaults = backend.runtime_defaults_for("test/model:candle", None);+ assert_eq!(defaults.pooling.as_deref(), Some("cls"));+ assert_eq!(defaults.query_template, None);+ assert_eq!(defaults.doc_template, None);+ assert_eq!(defaults.normalize, None);+ assert_eq!(defaults.output_dtype, None);+ }++ #[test]+ fn parse_runtime_config_inherits_compute_precision_for_candle_profile() {+ let (_, config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+profiles:+ default:+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse Candle runtime config");++ assert_eq!(config.compute_precision.as_deref(), Some("bfloat16"));+ }++ #[test]+ fn bge_m3_candle_profile_inherits_bfloat16_precision() {+ let (_, config) = parse_runtime_config(+ "BAAI/bge-m3",+ include_str!("../../sie_server/models/BAAI__bge-m3.yaml"),+ )+ .expect("parse BGE-M3 Candle runtime config");++ assert_eq!(config.compute_precision.as_deref(), Some("bfloat16"));+ }++ #[test]+ fn snowflake_arctic_candle_profile_uses_float16_precision() {+ let (_, config) = parse_runtime_config(+ "Snowflake/snowflake-arctic-embed-l-v2.0",+ include_str!("../../sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml"),+ )+ .expect("parse Snowflake Arctic Candle runtime config");++ assert_eq!(config.compute_precision.as_deref(), Some("float16"));+ }++ #[test]+ fn parse_runtime_config_prefers_candle_compute_precision_override() {+ let (_, config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+profiles:+ default:+ compute_precision: bfloat16+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ extends: default+ compute_precision: float16+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse Candle runtime config");++ assert_eq!(config.compute_precision.as_deref(), Some("float16"));+ }++ #[test]+ fn runtime_defaults_accept_instruction_alias() {+ let runtime = serde_json::json!({+ "query_template": "Instruct: {instruction}\nQuery: {text}",+ "instruction": "retrieve relevant passages",+ });+ let runtime = runtime.as_object().unwrap().clone().into_iter().collect();++ let defaults = RuntimeDefaults::from_runtime(&runtime);++ assert_eq!(+ defaults.default_instruction.as_deref(),+ Some("retrieve relevant passages")+ );+ }++ #[test]+ fn apply_model_config_rejects_non_candle_adapter_profile() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let error = backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ extends: default+"#+ .to_string(),+ })+ .expect_err("non-Candle profile should be rejected");++ assert!(+ error+ .to_string()+ .contains("has no profiles using adapter module sie_server_rust.adapters.candle"),+ "{error:#}"+ );+ }++ #[tokio::test]+ async fn health_ready_waits_for_catalog_config() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ assert!(!backend.health_ready().await);++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ assert!(backend.health_ready().await);+ }++ #[tokio::test]+ async fn health_ready_resolves_profile_variant_from_base_catalog() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ assert!(backend.health_ready().await);+ }++ #[tokio::test]+ async fn health_ready_accepts_applied_catalog_model() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ assert!(!backend.health_ready().await);+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ assert!(backend.health_ready().await);+ }++ #[test]+ fn apply_model_config_registers_catalog_without_loading_weights() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+hf_id: not-a-real-hf-model-for-config-ack+max_sequence_length: 8192+tasks:+ encode:+ dense:+ dim: 1024+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ assert!(backend.supports("test/model:candle"));+ assert_eq!(backend.supported_models(), vec!["test/model:candle"]);+ assert!(backend.loading_embeddings.lock().unwrap().is_empty());+ assert!(backend.loaded_models().is_empty());+ }++ #[tokio::test]+ async fn ensure_model_ready_requires_catalog_before_loading_weights() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+hf_id: not-a-real-hf-model-for-readiness+max_sequence_length: 8192+tasks:+ encode:+ dense:+ dim: 1024+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ query_template: "query: {text}"+ doc_template: "passage: {text}"+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ let resp = backend.ensure_model_ready("other/model:candle").await;+ assert_eq!(resp.state, ReadinessState::RetryLater);+ assert_eq!(resp.batch_budget, None);+ assert!(resp.descriptor.is_none());+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn ensure_model_ready_reports_loading_in_progress_without_descriptor() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+hf_id: not-a-real-hf-model-for-readiness+max_sequence_length: 8192+tasks:+ encode:+ dense:+ dim: 1024+profiles:+ default:+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ backend+ .loading_embeddings+ .lock()+ .unwrap()+ .insert("test/model".to_string());++ let resp = backend.ensure_model_ready("test/model:candle").await;+ assert_eq!(resp.state, ReadinessState::LoadingInProgress);+ assert_eq!(resp.batch_budget, None);+ assert!(resp.descriptor.is_none());+ assert!(backend.loaded_models().is_empty());+ }++ #[tokio::test]+ async fn ensure_model_ready_uses_applied_catalog() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+hf_id: not-a-real-hf-model-for-readiness+max_sequence_length: 8192+tasks:+ encode:+ dense:+ dim: 1024+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ backend+ .loading_embeddings+ .lock()+ .unwrap()+ .insert("test/model".to_string());++ let resp = backend.ensure_model_ready("test/model:candle").await;+ assert_eq!(resp.state, ReadinessState::LoadingInProgress);+ assert_eq!(resp.batch_budget, None);+ assert!(resp.descriptor.is_none());+ }++ #[tokio::test]+ async fn apply_model_config_accepts_default_only_candle_model() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["default".to_string()],+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+"#+ .to_string(),+ })+ .expect("default-only Candle model should be accepted");++ assert!(backend.health_ready().await);+ }++ #[tokio::test]+ async fn replace_model_configs_refreshes_catalog_and_reports_applied_models() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let applied = backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 2,+ bundle_config_hash: "hash-2".to_string(),+ models: vec![+ crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "test/model".to_string(),+ model_config: r#"+sie_id: test/model+profiles:+ default:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ },+ crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "other/model".to_string(),+ model_config: r#"+sie_id: other/model+profiles:+ default:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ },+ ],+ })+ .expect("replace Candle model configs");++ assert_eq!(+ applied,+ vec!["other/model".to_string(), "test/model".to_string()]+ );+ assert!(backend.health_ready().await);+ assert!(backend+ .catalog+ .read()+ .expect("catalog lock")+ .contains_key("other/model"));++ let cleared = backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 3,+ bundle_config_hash: "hash-3".to_string(),+ models: vec![],+ })+ .expect("replace with empty snapshot");++ assert!(cleared.is_empty());+ assert!(!backend.health_ready().await);+ assert!(backend.catalog.read().expect("catalog lock").is_empty());+ }++ #[tokio::test]+ async fn replace_model_configs_reports_all_applied_models() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let applied = backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 2,+ bundle_config_hash: "hash-2".to_string(),+ models: vec![+ crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "test/model".to_string(),+ model_config: r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ },+ crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "other/model".to_string(),+ model_config: r#"+sie_id: other/model+profiles:+ default:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ },+ ],+ })+ .expect("replace Candle model configs");++ assert_eq!(+ applied,+ vec!["other/model".to_string(), "test/model:candle".to_string()]+ );+ assert!(backend.health_ready().await);+ }++ #[tokio::test]+ async fn replace_model_configs_drops_loading_model_when_config_changes() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ let old_config = r#"+sie_id: test/model+hf_id: old/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#;+ backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 1,+ bundle_config_hash: "hash-1".to_string(),+ models: vec![crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "test/model".to_string(),+ model_config: old_config.to_string(),+ }],+ })+ .expect("replace initial Candle model config");+ backend+ .loading_embeddings+ .lock()+ .expect("loading lock")+ .insert("test/model".to_string());++ backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 2,+ bundle_config_hash: "hash-2".to_string(),+ models: vec![crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "test/model".to_string(),+ model_config: old_config.to_string(),+ }],+ })+ .expect("replace unchanged Candle model config");+ assert!(+ backend+ .loading_embeddings+ .lock()+ .expect("loading lock")+ .contains("test/model"),+ "unchanged config should keep an in-flight load"+ );++ let applied = backend+ .replace_model_configs(&ReplaceModelConfigsRequest {+ bundle_id: "candle".to_string(),+ epoch: 3,+ bundle_config_hash: "hash-3".to_string(),+ models: vec![crate::ipc_types::ReplaceModelConfigEntry {+ model_id: "test/model".to_string(),+ model_config: r#"+sie_id: test/model+hf_id: new/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ }],+ })+ .expect("replace changed Candle model config");++ assert_eq!(applied, vec!["test/model:candle".to_string()]);+ assert!(+ !backend+ .loading_embeddings+ .lock()+ .expect("loading lock")+ .contains("test/model"),+ "changed config must invalidate an in-flight load"+ );+ }++ #[tokio::test]+ async fn encode_rejects_non_float32_output_dtype_before_loading() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+tasks:+ encode:+ dense:+ dim: 384+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ let result = backend+ .process_encode_batch(ProcessEncodeBatchRequest {+ model_id: "test/model:candle".to_string(),+ items: vec![EncodeBatchItem {+ work_item_id: "work".to_string(),+ request_id: "req".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: serde_json::json!({"text": "hello"}),+ output_types: None,+ instruction: None,+ is_query: false,+ options: Some(serde_json::json!({"output_dtype": "float16"})),+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }],+ accepts_batched_f16_multivectors: false,+ })+ .await;++ assert_eq!(result.outcomes.len(), 1);+ assert_eq!(+ result.outcomes[0].error_code.as_deref(),+ Some("candle_unsupported_output_dtype")+ );+ assert!(result.outcomes[0]+ .error+ .as_deref()+ .is_some_and(|message| message.contains("dense float32 only")));+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn sparse_encode_rejects_normalization_before_loading() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "prithivida/Splade_PP_en_v2".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!(+ "../../sie_server/models/prithivida__Splade_PP_en_v2.yaml"+ )+ .to_string(),+ })+ .expect("apply SPLADE Candle model config");++ let result = backend+ .process_encode_batch(ProcessEncodeBatchRequest {+ model_id: "prithivida/Splade_PP_en_v2:candle".to_string(),+ items: vec![EncodeBatchItem {+ work_item_id: "work".to_string(),+ request_id: "req".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: serde_json::json!({"text": "hello"}),+ output_types: None,+ instruction: None,+ is_query: false,+ options: Some(serde_json::json!({"normalize": true})),+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }],+ accepts_batched_f16_multivectors: false,+ })+ .await;++ assert_eq!(result.outcomes.len(), 1);+ assert_eq!(+ result.outcomes[0].error_code.as_deref(),+ Some("candle_unsupported_request")+ );+ assert!(result.outcomes[0]+ .error+ .as_deref()+ .is_some_and(|message| message.contains("normalize=false")));+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn encode_accepts_queue_profile_id_without_process_profile_env() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+tasks:+ encode:+ dense:+ dim: 384+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ let result = backend+ .process_encode_batch(ProcessEncodeBatchRequest {+ model_id: "test/model".to_string(),+ items: vec![EncodeBatchItem {+ work_item_id: "work".to_string(),+ request_id: "req".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: serde_json::json!({"text": "hello"}),+ output_types: None,+ instruction: None,+ is_query: false,+ options: Some(serde_json::json!({"output_dtype": "float16"})),+ profile_id: Some("candle".to_string()),+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }],+ accepts_batched_f16_multivectors: false,+ })+ .await;++ assert_eq!(result.outcomes.len(), 1);+ assert_eq!(+ result.outcomes[0].error_code.as_deref(),+ Some("candle_unsupported_output_dtype")+ );+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn encode_prefers_options_profile_over_queue_placeholder() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));++ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+tasks:+ encode:+ dense:+ dim: 384+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#+ .to_string(),+ })+ .expect("apply Candle model config");++ let result = backend+ .process_encode_batch(ProcessEncodeBatchRequest {+ model_id: "test/model".to_string(),+ items: vec![EncodeBatchItem {+ work_item_id: "work".to_string(),+ request_id: "req".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: serde_json::json!({"text": "hello"}),+ output_types: None,+ instruction: None,+ is_query: false,+ options: Some(serde_json::json!({+ "profile": "candle",+ "output_dtype": "float16"+ })),+ profile_id: Some("default".to_string()),+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }],+ accepts_batched_f16_multivectors: false,+ })+ .await;++ assert_eq!(result.outcomes.len(), 1);+ assert_eq!(+ result.outcomes[0].error_code.as_deref(),+ Some("candle_unsupported_output_dtype")+ );+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[test]+ fn parse_runtime_config_supports_multivector_encode_and_score_together() {+ let (_, config) = parse_runtime_config(+ "topk-io/Iso-ModernColBERT",+ include_str!("../../sie_server/models/topk-io__Iso-ModernColBERT.yaml"),+ )+ .expect("parse Iso-ModernColBERT Candle runtime config");++ assert_eq!(config.task_kind, CandleTaskKind::EmbeddingAndRerank);+ assert_eq!(config.dense_dim, None);+ assert_eq!(config.native_multivector_dim(), Some(128));+ assert_eq!(+ config.profiles["candle"].score_strategy,+ Some(CandleScoreStrategy::ColbertMaxsim)+ );+ assert_eq!(+ config.output_types("topk-io/Iso-ModernColBERT:candle", None),+ vec!["multivector".to_string(), "score".to_string()]+ );+ assert_eq!(config.compute_precision.as_deref(), Some("bfloat16"));+ assert_eq!(+ config.hf_revision.as_deref(),+ Some("a43b93e62b11ff205b7f935c1ce2207bfed2d283")+ );+ assert_eq!(config.max_sequence_length, Some(8192));+ assert_eq!(config.query_max_length, Some(32));+ assert_eq!(config.profiles["candle"].max_batch_tokens, Some(16384));+ }++ #[test]+ fn score_is_not_advertised_without_explicit_colbert_maxsim_strategy() {+ let (_, config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+"#,+ )+ .expect("parse score-capable multivector model without a native strategy");++ assert_eq!(config.profiles["candle"].score_strategy, None);+ assert_eq!(+ config.output_types("test/model:candle", None),+ vec!["multivector".to_string()]+ );+ assert!(!config.supports_native_score("test/model:candle", None));+ }++ #[test]+ fn parse_runtime_config_rejects_unknown_score_strategy() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ score_strategy: arbitrary+"#,+ )+ .unwrap_err();++ assert!(error.to_string().contains("score_strategy"));+ assert!(format!("{error:#}").contains("colbert_maxsim"));+ }++ #[test]+ fn colbert_score_strategy_scopes_descriptor_and_request_to_effective_profile() {+ let model_config = r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: true+ score_strategy: colbert_maxsim+ runtime:+ normalize: true+ candle_plain:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: true+ runtime:+ normalize: true+"#;+ let (_, config) =+ parse_runtime_config("test/model", model_config).expect("parse two Candle profiles");++ assert_eq!(+ config.output_types("test/model:candle", None),+ vec!["multivector".to_string(), "score".to_string()]+ );+ assert_eq!(+ config.output_types("test/model:candle_plain", None),+ vec!["multivector".to_string()]+ );++ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string(), "candle_plain".to_string()],+ model_config: model_config.to_string(),+ })+ .expect("apply two Candle profiles");+ assert!(backend.supports_score_item("test/model:candle", &score_batch_item(None)));+ assert!(!backend.supports_score_item("test/model:candle_plain", &score_batch_item(None)));+ }++ #[test]+ fn candle_adapter_option_blocks_inherit_only_when_child_block_is_empty() {+ let model_config = r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: true+ score_strategy: colbert_maxsim+ runtime:+ normalize: true+ output_dtype: float16+ candle_empty:+ extends: candle+ adapter_options:+ loadtime: {}+ runtime: {}+ candle_replaced:+ extends: candle+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: true+ runtime:+ normalize: true+"#;+ let (_, config) = parse_runtime_config("test/model", model_config)+ .expect("parse parent, empty child, and replacing child profiles");++ let parent = &config.profiles["candle"];+ let empty_child = &config.profiles["candle_empty"];+ let replaced_child = &config.profiles["candle_replaced"];+ assert_eq!(+ parent.score_strategy,+ Some(CandleScoreStrategy::ColbertMaxsim)+ );+ assert_eq!(+ empty_child.score_strategy,+ Some(CandleScoreStrategy::ColbertMaxsim)+ );+ assert_eq!(replaced_child.score_strategy, None);+ assert_eq!(parent.output_dtype.as_deref(), Some("float16"));+ assert_eq!(empty_child.output_dtype.as_deref(), Some("float16"));+ assert_eq!(replaced_child.output_dtype, None);++ assert_eq!(+ config.output_types("test/model:candle_empty", None),+ vec!["multivector".to_string(), "score".to_string()]+ );+ assert_eq!(+ config.output_types("test/model:candle_replaced", None),+ vec!["multivector".to_string()]+ );++ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec![+ "candle".to_string(),+ "candle_empty".to_string(),+ "candle_replaced".to_string(),+ ],+ model_config: model_config.to_string(),+ })+ .expect("apply inherited and replaced Candle profiles");+ assert!(backend.supports_score_item("test/model:candle", &score_batch_item(None)));+ assert!(backend.supports_score_item("test/model:candle_empty", &score_batch_item(None)));+ assert!(!backend.supports_score_item("test/model:candle_replaced", &score_batch_item(None)));+ }++ #[test]+ fn colbert_score_strategy_requires_explicit_true_loadtime_normalize() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ score_strategy: colbert_maxsim+ runtime:+ normalize: true+"#,+ )+ .unwrap_err();++ assert!(format!("{error:#}").contains("requires resolved loadtime normalize=true"));+ }++ #[test]+ fn colbert_score_strategy_rejects_false_normalization() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: false+ score_strategy: colbert_maxsim+ runtime:+ normalize: false+"#,+ )+ .unwrap_err();++ assert!(format!("{error:#}").contains("normalize=true"));+ }++ #[test]+ fn colbert_score_strategy_rejects_runtime_normalize_mismatch() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+ normalize: true+ score_strategy: colbert_maxsim+ runtime:+ normalize: false+"#,+ )+ .unwrap_err();++ assert!(format!("{error:#}").contains("must match explicit runtime normalize"));+ }++ #[test]+ fn score_request_is_rejected_without_explicit_colbert_maxsim_strategy() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "test/model".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+ score: {}+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ token_dim: 128+"#+ .to_string(),+ })+ .expect("apply multivector model without native score strategy");++ assert!(!backend.supports_score_item("test/model:candle", &score_batch_item(None)));+ }++ #[test]+ fn parse_runtime_config_rejects_unsupported_special_token_filtering() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ skip_special_tokens: true+"#,+ )+ .unwrap_err();++ assert!(error.to_string().contains("skip_special_tokens=true"));+ }++ #[test]+ fn parse_runtime_config_rejects_special_token_filtering_on_any_candle_profile() {+ let error = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ skip_special_tokens: false+ candle_without_special_tokens:+ extends: candle+ adapter_options:+ loadtime:+ skip_special_tokens: true+"#,+ )+ .unwrap_err();++ let message = error.to_string();+ assert!(message.contains("candle_without_special_tokens"));+ assert!(message.contains("skip_special_tokens=true"));+ }++ #[test]+ fn parse_runtime_config_rejects_inconsistent_candle_loadtime_semantics() {+ for (loadtime, runtime, expected) in [+ ("token_dim: 64", "normalize: true", "token_dim 64"),+ ("normalize: true", "normalize: false", "must match"),+ ("query_prefix: '[Q] '", "normalize: true", "unsupported"),+ (+ "max_seq_length: zero",+ "normalize: true",+ "positive integer",+ ),+ ] {+ let yaml = format!(+ r#"+sie_id: test/model+tasks:+ encode:+ multivector:+ dim: 128+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ loadtime:+ {loadtime}+ runtime:+ {runtime}+"#+ );+ let error = parse_runtime_config("test/model", &yaml).unwrap_err();+ assert!(error.to_string().contains(expected), "{error}");+ }+ }++ #[test]+ fn parse_runtime_config_accepts_existing_candle_false_remote_code_policy() {+ parse_runtime_config(+ "sentence-transformers/all-MiniLM-L6-v2",+ include_str!("../../sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml"),+ )+ .expect("parse existing MiniLM Candle profile");+ }++ #[test]+ fn parse_runtime_config_threads_hugging_face_revision() {+ let (_, config) = parse_runtime_config(+ "test/model",+ r#"+sie_id: test/model+hf_id: upstream/model+hf_revision: 0123456789abcdef+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ )+ .expect("parse pinned Candle model");++ assert_eq!(config.hf_id, "upstream/model");+ assert_eq!(config.hf_revision.as_deref(), Some("0123456789abcdef"));+ }++ #[test]+ fn candle_output_kind_keeps_bge_m3_dense_only() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "BAAI/bge-m3".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!("../../sie_server/models/BAAI__bge-m3.yaml").to_string(),+ })+ .expect("apply BGE-M3 Candle model config");++ let dense = vec!["dense".to_string()];+ let multivector = vec!["multivector".to_string()];++ assert_eq!(+ backend.encode_output_kind("BAAI/bge-m3:candle", Some(&dense)),+ Some(EncodeOutputKind::Dense)+ );+ assert_eq!(+ backend.encode_output_kind("BAAI/bge-m3:candle", Some(&multivector)),+ None+ );+ assert!(!backend.supports_operation("BAAI/bge-m3:candle", CandleTaskKind::Rerank));+ }++ #[test]+ fn candle_output_kind_accepts_iso_multivector_profile_default() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "topk-io/Iso-ModernColBERT".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!(+ "../../sie_server/models/topk-io__Iso-ModernColBERT.yaml"+ )+ .to_string(),+ })+ .expect("apply Iso-ModernColBERT Candle model config");++ let multivector = vec!["multivector".to_string()];+ let dense = vec!["dense".to_string()];++ assert_eq!(+ backend.encode_output_kind("topk-io/Iso-ModernColBERT:candle", None),+ Some(EncodeOutputKind::Multivector)+ );+ assert_eq!(+ backend.encode_output_kind("topk-io/Iso-ModernColBERT:candle", Some(&multivector)),+ Some(EncodeOutputKind::Multivector)+ );+ assert_eq!(+ backend.encode_output_kind("topk-io/Iso-ModernColBERT:candle", Some(&dense)),+ None+ );+ assert_eq!(+ backend+ .runtime_defaults_for("topk-io/Iso-ModernColBERT:candle", None)+ .output_dtype+ .as_deref(),+ Some("float16")+ );+ assert!(backend.supports_operation(+ "topk-io/Iso-ModernColBERT:candle",+ CandleTaskKind::Embedding+ ));+ assert!(+ backend.supports_operation("topk-io/Iso-ModernColBERT:candle", CandleTaskKind::Rerank)+ );+ assert!(backend+ .supports_score_item("topk-io/Iso-ModernColBERT:candle", &score_batch_item(None)));+ assert_eq!(+ backend+ .runtime_defaults_for("topk-io/Iso-ModernColBERT:candle", None)+ .max_batch_tokens,+ Some(16384)+ );+ }++ #[test]+ fn candle_output_kind_accepts_splade_sparse_profile_default() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "prithivida/Splade_PP_en_v2".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!(+ "../../sie_server/models/prithivida__Splade_PP_en_v2.yaml"+ )+ .to_string(),+ })+ .expect("apply SPLADE Candle model config");++ let sparse = vec!["sparse".to_string()];+ let dense = vec!["dense".to_string()];+ let multivector = vec!["multivector".to_string()];++ assert_eq!(+ backend.encode_output_kind("prithivida/Splade_PP_en_v2:candle", None),+ Some(EncodeOutputKind::Sparse)+ );+ assert_eq!(+ backend.encode_output_kind("prithivida/Splade_PP_en_v2:candle", Some(&sparse)),+ Some(EncodeOutputKind::Sparse)+ );+ assert_eq!(+ backend.encode_output_kind("prithivida/Splade_PP_en_v2:candle", Some(&dense)),+ None+ );+ assert_eq!(+ backend.encode_output_kind("prithivida/Splade_PP_en_v2:candle", Some(&multivector)),+ None+ );+ let defaults = backend.runtime_defaults_for("prithivida/Splade_PP_en_v2:candle", None);+ assert_eq!(defaults.pooling.as_deref(), Some("splade"));+ assert_eq!(defaults.normalize, Some(false));+ }++ #[test]+ fn encode_normalize_fallback_is_output_kind_aware() {+ assert!(!default_normalize(EncodeOutputKind::Sparse, true));+ assert!(default_normalize(EncodeOutputKind::Dense, true));+ assert!(default_normalize(EncodeOutputKind::Multivector, true));+ assert!(!default_normalize(EncodeOutputKind::Dense, false));+ }++ #[test]+ fn score_item_ids_preserve_strings_and_generate_stable_fallbacks() {+ assert_eq!(+ score_item_id(&serde_json::json!({"id": "doc-a"}), 0),+ Ok("doc-a".to_string())+ );+ assert_eq!(+ score_item_id(&serde_json::json!({}), 1),+ Ok("item-1".to_string())+ );+ assert!(score_item_id(&serde_json::json!({"id": 42}), 2).is_err());+ assert_eq!(+ score_item_id(&serde_json::json!({"id": ""}), 3),+ Ok(String::new())+ );+ }++ #[test]+ fn score_raw_output_preserves_document_order_for_sidecar_ranking() {+ let item = ScoreBatchItem {+ work_item_id: "work".to_string(),+ request_id: "request".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ query_item: serde_json::json!({"text": "query"}),+ score_items: Vec::new(),+ instruction: None,+ options: None,+ profile_id: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ };+ let outcome = success_score_outcome(+ &item,+ &["doc-b".to_string(), "doc-a".to_string()],+ CandleScoreResult {+ scores: vec![0.1, 0.9],+ query_tokens: 2,+ doc_tokens: vec![3, 4],+ tokenization_ms: 1.0,+ inference_ms: 2.0,+ maxsim_ms: Some(0.5),+ },+ );++ assert_eq!(outcome.inference_ms, Some(2.0));+ assert_eq!(outcome.postprocessing_ms, None);+ assert_eq!(+ outcome.units,+ Some(UnitCounts {+ input_tokens: Some(11),+ pages: None,+ images: None,+ })+ );++ let score = outcome+ .raw_output+ .and_then(|raw| raw.score)+ .expect("raw score output");+ assert_eq!(score.item_ids, vec!["doc-b", "doc-a"]);+ assert_eq!(score.scores, vec![0.1, 0.9]);+ }++ #[test]+ fn sparse_raw_output_is_exclusive_and_preserves_ascending_indices() {+ let item = prepared_encode_item(0);+ let outcome = success_sparse_outcome(+ &item,+ CandleSparseEmbedding {+ indices: vec![7, 19, 30521],+ values: vec![0.25, 1.5, 0.75],+ },+ 30522,+ 2.0,+ 1.0,+ );++ let raw = outcome.raw_output.expect("raw sparse output");+ assert!(raw.dense.is_none());+ assert!(raw.score.is_none());+ assert!(raw.multivector.is_none());+ let sparse = raw.sparse.expect("sparse payload");+ assert_eq!(sparse.indices, vec![7, 19, 30521]);+ assert_eq!(sparse.values, vec![0.25, 1.5, 0.75]);+ assert_eq!(sparse.dims, Some(30522));+ }++ #[tokio::test]+ async fn score_accepts_benign_python_encode_options_for_empty_document_set() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "topk-io/Iso-ModernColBERT".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!(+ "../../sie_server/models/topk-io__Iso-ModernColBERT.yaml"+ )+ .to_string(),+ })+ .expect("apply Iso-ModernColBERT Candle model config");++ let result = backend+ .process_score_batch(ProcessScoreBatchRequest {+ model_id: "topk-io/Iso-ModernColBERT".to_string(),+ items: vec![ScoreBatchItem {+ work_item_id: "work".to_string(),+ request_id: "request".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ query_item: serde_json::json!({"content": "query", "id": null}),+ score_items: Vec::new(),+ instruction: None,+ options: Some(serde_json::json!({+ "profile": "candle",+ "output_dtype": "float16",+ "muvera": {},+ "output_types": ["dense"],+ "output_similarity": {"dense": "dot"},+ })),+ profile_id: Some("default".to_string()),+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ }],+ })+ .await;++ assert_eq!(result.outcomes.len(), 1);+ let outcome = &result.outcomes[0];+ assert_eq!(outcome.disposition, Disposition::PublishAndAck);+ let score = outcome+ .raw_output+ .as_ref()+ .and_then(|raw| raw.score.as_ref())+ .expect("empty score output");+ assert!(score.scores.is_empty());+ assert!(score.item_ids.is_empty());+ assert_eq!(+ outcome.units.as_ref().and_then(|units| units.input_tokens),+ Some(0)+ );+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn score_validates_missing_null_empty_and_malformed_text_items_before_load() {+ let backend = CandleBackend::new(CandleBackendConfig::new(64, true, 1));+ backend+ .apply_model_config(&ApplyModelConfigRequest {+ bundle_id: "candle".to_string(),+ model_id: "topk-io/Iso-ModernColBERT".to_string(),+ epoch: 1,+ bundle_config_hash: "hash".to_string(),+ profiles_added: vec!["candle".to_string()],+ model_config: include_str!(+ "../../sie_server/models/topk-io__Iso-ModernColBERT.yaml"+ )+ .to_string(),+ })+ .expect("apply Iso-ModernColBERT Candle model config");++ let make_item = |index: u32, query_item: Json, score_items: Vec<Json>| ScoreBatchItem {+ work_item_id: format!("work-{index}"),+ request_id: "request".to_string(),+ item_index: index,+ total_items: 5,+ timestamp: 0.0,+ query_item,+ score_items,+ instruction: None,+ options: None,+ profile_id: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ };+ let result = backend+ .process_score_batch(ProcessScoreBatchRequest {+ model_id: "topk-io/Iso-ModernColBERT:candle".to_string(),+ items: vec![+ make_item(0, serde_json::json!({}), Vec::new()),+ make_item(1, serde_json::json!({"text": null}), Vec::new()),+ make_item(2, serde_json::json!({"text": ""}), Vec::new()),+ make_item(+ 3,+ serde_json::json!({"text": "query", "id": 42}),+ Vec::new(),+ ),+ make_item(+ 4,+ serde_json::json!({"text": "query"}),+ vec![serde_json::json!({"text": "doc", "id": 42})],+ ),+ ],+ })+ .await;++ assert_eq!(result.outcomes.len(), 5);+ for index in [0_usize, 1, 3, 4] {+ assert_eq!(+ result.outcomes[index].error_code.as_deref(),+ Some("candle_invalid_item")+ );+ }+ assert_eq!(result.outcomes[2].disposition, Disposition::PublishAndAck);+ assert_eq!(+ result.outcomes[2]+ .units+ .as_ref()+ .and_then(|units| units.input_tokens),+ Some(0)+ );+ assert!(backend.loaded_embeddings.lock().unwrap().is_empty());+ }+}diff --git a/packages/sie_server_rust/src/candle_bert_flash.rs b/packages/sie_server_rust/src/candle_bert_flash.rsnew file mode 100644index 000000000..ed3108506--- /dev/null+++ b/packages/sie_server_rust/src/candle_bert_flash.rs@@ -0,0 +1,482 @@+//! Packed BERT encoder with variable-length FlashAttention for Candle.+//!+//! This path is intentionally narrower than the generic Candle BERT model: it+//! serves standard post-layer-norm BERT checkpoints with absolute learned+//! positions. The caller keeps the generic padded model as the correctness+//! fallback for unsupported devices, dtypes, and attention-mask shapes.++use crate::candle_layers::{FastLayerNorm, FastLinear, HiddenAct};+use candle::{Result, Tensor};+use candle_nn::{embedding, Embedding, Module, VarBuilder};+use candle_transformers::models::bert::{+ Config as BertConfig, HiddenAct as BertHiddenAct, PositionEmbeddingType,+};++#[derive(Debug)]+struct BertEmbeddings {+ word_embeddings: Embedding,+ position_embeddings: Embedding,+ token_type_embeddings: Embedding,+ layer_norm: FastLayerNorm,+}++impl BertEmbeddings {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let word_embeddings = embedding(+ config.vocab_size,+ config.hidden_size,+ vb.pp("word_embeddings"),+ )?;+ let position_embeddings = embedding(+ config.max_position_embeddings,+ config.hidden_size,+ vb.pp("position_embeddings"),+ )?;+ let token_type_embeddings = embedding(+ config.type_vocab_size,+ config.hidden_size,+ vb.pp("token_type_embeddings"),+ )?;+ let layer_norm = FastLayerNorm::load(+ vb.pp("LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )?;+ Ok(Self {+ word_embeddings,+ position_embeddings,+ token_type_embeddings,+ layer_norm,+ })+ }++ fn forward_packed(+ &self,+ input_ids: &Tensor,+ token_type_ids: &Tensor,+ position_ids: &Tensor,+ ) -> Result<Tensor> {+ let word_embeddings = self.word_embeddings.forward(input_ids)?;+ let token_type_embeddings = self.token_type_embeddings.forward(token_type_ids)?;+ let position_embeddings = self.position_embeddings.forward(position_ids)?;+ let word_and_type = (&word_embeddings + token_type_embeddings)?;+ self.layer_norm+ .forward(&word_and_type, Some(&position_embeddings))+ }+}++#[derive(Debug)]+struct BertAttention {+ qkv: FastLinear,+ output: FastLinear,+ output_layer_norm: FastLayerNorm,+ num_attention_heads: usize,+ attention_head_size: usize,+ all_head_size: usize,+}++impl BertAttention {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let attention_head_size = config.hidden_size / config.num_attention_heads;+ let all_head_size = config.num_attention_heads * attention_head_size;+ let qkv = FastLinear::load_qkv(config.hidden_size, all_head_size, vb.pp("self"))?;+ let output = FastLinear::load(+ all_head_size,+ config.hidden_size,+ vb.pp("output.dense"),+ None,+ )?;+ let output_layer_norm = FastLayerNorm::load(+ vb.pp("output.LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )?;+ Ok(Self {+ qkv,+ output,+ output_layer_norm,+ num_attention_heads: config.num_attention_heads,+ attention_head_size,+ all_head_size,+ })+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;+ let qkv = self.qkv.forward(hidden_states)?.reshape((+ total_tokens,+ self.num_attention_heads * 3,+ self.attention_head_size,+ ))?;+ let qkv = qkv.chunk(3, 1)?;+ let attention_output = flash_attn_varlen(+ &qkv[0],+ &qkv[1],+ &qkv[2],+ seqlens,+ max_seqlen,+ self.attention_head_size,+ )?+ .reshape((total_tokens, self.all_head_size))?;+ let attention_output = self.output.forward(&attention_output)?;+ self.output_layer_norm+ .forward(&attention_output, Some(hidden_states))+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum BertIntermediateActivation {+ ExactGelu,+ Fused(HiddenAct),+}++impl BertIntermediateActivation {+ fn from_config(value: BertHiddenAct) -> Self {+ match value {+ // Candle's generic BERT model and Hugging Face both interpret+ // `gelu` as the erf formulation. TEI intentionally approximates+ // it for fusion, but this path preserves checkpoint semantics.+ BertHiddenAct::Gelu => Self::ExactGelu,+ BertHiddenAct::GeluApproximate => Self::Fused(HiddenAct::Gelu),+ BertHiddenAct::Relu => Self::Fused(HiddenAct::Relu),+ }+ }++ fn fused_activation(self) -> Option<HiddenAct> {+ match self {+ Self::ExactGelu => None,+ Self::Fused(activation) => Some(activation),+ }+ }++ fn finish(self, hidden_states: Tensor) -> Result<Tensor> {+ match self {+ Self::ExactGelu => hidden_states.gelu_erf(),+ Self::Fused(_) => Ok(hidden_states),+ }+ }+}++#[derive(Debug)]+struct BertIntermediate {+ dense: FastLinear,+ activation: BertIntermediateActivation,+}++impl BertIntermediate {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let activation = BertIntermediateActivation::from_config(config.hidden_act);+ let dense = FastLinear::load(+ config.hidden_size,+ config.intermediate_size,+ vb.pp("dense"),+ activation.fused_activation(),+ )?;+ Ok(Self { dense, activation })+ }++ fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> {+ self.activation.finish(self.dense.forward(hidden_states)?)+ }+}++#[derive(Debug)]+struct BertOutput {+ dense: FastLinear,+ layer_norm: FastLayerNorm,+}++impl BertOutput {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let dense = FastLinear::load(+ config.intermediate_size,+ config.hidden_size,+ vb.pp("dense"),+ None,+ )?;+ let layer_norm = FastLayerNorm::load(+ vb.pp("LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )?;+ Ok(Self { dense, layer_norm })+ }++ fn forward(&self, hidden_states: &Tensor, residual: &Tensor) -> Result<Tensor> {+ let hidden_states = self.dense.forward(hidden_states)?;+ self.layer_norm.forward(&hidden_states, Some(residual))+ }+}++#[derive(Debug)]+struct BertLayer {+ attention: BertAttention,+ intermediate: BertIntermediate,+ output: BertOutput,+}++impl BertLayer {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ Ok(Self {+ attention: BertAttention::load(vb.pp("attention"), config)?,+ intermediate: BertIntermediate::load(vb.pp("intermediate"), config)?,+ output: BertOutput::load(vb.pp("output"), config)?,+ })+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let attention_output = self+ .attention+ .forward_packed(hidden_states, seqlens, max_seqlen)?;+ let intermediate_output = self.intermediate.forward(&attention_output)?;+ self.output.forward(&intermediate_output, &attention_output)+ }+}++#[derive(Debug)]+struct BertEncoder {+ layers: Vec<BertLayer>,+}++impl BertEncoder {+ fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let layers = (0..config.num_hidden_layers)+ .map(|index| BertLayer::load(vb.pp(format!("layer.{index}")), config))+ .collect::<Result<Vec<_>>>()?;+ Ok(Self { layers })+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let mut hidden_states = hidden_states.clone();+ for layer in &self.layers {+ hidden_states = layer.forward_packed(&hidden_states, seqlens, max_seqlen)?;+ }+ Ok(hidden_states)+ }+}++/// Standard post-LN BERT backbone evaluated over unpadded token rows.+#[derive(Debug)]+pub(crate) struct PackedBertModel {+ embeddings: BertEmbeddings,+ encoder: BertEncoder,+}++impl PackedBertModel {+ pub(crate) fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ validate_config(config)?;+ let vb = if vb.contains_tensor("bert.embeddings.word_embeddings.weight") {+ vb.pp("bert")+ } else {+ vb+ };+ Ok(Self {+ embeddings: BertEmbeddings::load(vb.pp("embeddings"), config)?,+ encoder: BertEncoder::load(vb.pp("encoder"), config)?,+ })+ }++ pub(crate) fn forward_packed(+ &self,+ input_ids: &Tensor,+ token_type_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let hidden_states =+ self.embeddings+ .forward_packed(input_ids, token_type_ids, position_ids)?;+ self.encoder+ .forward_packed(&hidden_states, seqlens, max_seqlen)+ }+}++fn validate_config(config: &BertConfig) -> Result<()> {+ if config.position_embedding_type != PositionEmbeddingType::Absolute {+ candle::bail!("packed BERT supports only absolute position embeddings")+ }+ if config.num_attention_heads == 0+ || !config+ .hidden_size+ .is_multiple_of(config.num_attention_heads)+ {+ candle::bail!(+ "packed BERT hidden_size {} must be divisible by non-zero num_attention_heads {}",+ config.hidden_size,+ config.num_attention_heads+ )+ }+ if config.num_hidden_layers == 0 {+ candle::bail!("packed BERT requires at least one encoder layer")+ }+ if config.type_vocab_size == 0 {+ candle::bail!("packed BERT type_vocab_size must be greater than zero")+ }+ Ok(())+}++#[cfg(feature = "cuda")]+fn flash_attn_varlen(+ query: &Tensor,+ key: &Tensor,+ value: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ head_size: usize,+) -> Result<Tensor> {+ candle_flash_attn::flash_attn_varlen(+ query,+ key,+ value,+ seqlens,+ seqlens,+ max_seqlen,+ max_seqlen,+ 1f32 / f32::sqrt(head_size as f32),+ false,+ )+}++#[cfg(not(feature = "cuda"))]+fn flash_attn_varlen(+ _query: &Tensor,+ _key: &Tensor,+ _value: &Tensor,+ _seqlens: &Tensor,+ _max_seqlen: usize,+ _head_size: usize,+) -> Result<Tensor> {+ candle::bail!("packed BERT FlashAttention requires the cuda feature")+}++#[cfg(test)]+mod tests {+ use super::*;+ use candle::{DType, Device};++ #[test]+ fn bert_activation_preserves_exact_gelu_semantics() -> Result<()> {+ assert_eq!(+ BertIntermediateActivation::from_config(BertHiddenAct::Gelu),+ BertIntermediateActivation::ExactGelu+ );+ assert_eq!(+ BertIntermediateActivation::from_config(BertHiddenAct::GeluApproximate),+ BertIntermediateActivation::Fused(HiddenAct::Gelu)+ );+ assert_eq!(+ BertIntermediateActivation::from_config(BertHiddenAct::Relu),+ BertIntermediateActivation::Fused(HiddenAct::Relu)+ );++ let input = Tensor::new(&[-2.0f32, -0.5, 0.5, 2.0], &Device::Cpu)?;+ let exact = BertIntermediateActivation::ExactGelu+ .finish(input.clone())?+ .to_vec1::<f32>()?;+ let approximate = input.gelu()?.to_vec1::<f32>()?;+ assert!(exact+ .iter()+ .zip(approximate)+ .any(|(exact, approximate)| (exact - approximate).abs() > 1e-6));+ Ok(())+ }++ #[test]+ fn embedding_forward_uses_supplied_positions_and_token_types() -> Result<()> {+ let hidden_size = 4;+ let tensors = std::collections::HashMap::from([+ (+ "word_embeddings.weight".to_string(),+ Tensor::new(+ &[+ [0.1f32, 0.2, 0.3, 0.4],+ [0.5, 0.6, 0.7, 0.8],+ [0.9, 1.0, 1.1, 1.2],+ ],+ &Device::Cpu,+ )?,+ ),+ (+ "position_embeddings.weight".to_string(),+ Tensor::new(+ &[+ [0.0f32, 0.1, 0.2, 0.3],+ [0.4, 0.3, 0.2, 0.1],+ [0.8, 0.7, 0.6, 0.5],+ ],+ &Device::Cpu,+ )?,+ ),+ (+ "token_type_embeddings.weight".to_string(),+ Tensor::new(+ &[[0.0f32, 0.0, 0.0, 0.0], [0.3, -0.2, 0.1, -0.4]],+ &Device::Cpu,+ )?,+ ),+ (+ "LayerNorm.weight".to_string(),+ Tensor::ones(hidden_size, DType::F32, &Device::Cpu)?,+ ),+ (+ "LayerNorm.bias".to_string(),+ Tensor::zeros(hidden_size, DType::F32, &Device::Cpu)?,+ ),+ ]);+ let vb = VarBuilder::from_tensors(tensors, DType::F32, &Device::Cpu);+ let config = BertConfig {+ vocab_size: 3,+ hidden_size,+ num_hidden_layers: 1,+ num_attention_heads: 2,+ intermediate_size: 8,+ hidden_act: BertHiddenAct::Gelu,+ hidden_dropout_prob: 0.0,+ max_position_embeddings: 3,+ type_vocab_size: 2,+ initializer_range: 0.02,+ layer_norm_eps: 1e-5,+ pad_token_id: 0,+ position_embedding_type: PositionEmbeddingType::Absolute,+ use_cache: false,+ classifier_dropout: None,+ model_type: Some("bert".to_string()),+ };+ let embeddings = BertEmbeddings::load(vb, &config)?;+ let input_ids = Tensor::new(&[1u32, 2], &Device::Cpu)?;+ let zero_types = Tensor::new(&[0u32, 0], &Device::Cpu)?;+ let mixed_types = Tensor::new(&[0u32, 1], &Device::Cpu)?;+ let forward_positions = Tensor::new(&[0u32, 1], &Device::Cpu)?;+ let reverse_positions = Tensor::new(&[1u32, 0], &Device::Cpu)?;++ let baseline = embeddings+ .forward_packed(&input_ids, &zero_types, &forward_positions)?+ .to_vec2::<f32>()?;+ let typed = embeddings+ .forward_packed(&input_ids, &mixed_types, &forward_positions)?+ .to_vec2::<f32>()?;+ let repositioned = embeddings+ .forward_packed(&input_ids, &zero_types, &reverse_positions)?+ .to_vec2::<f32>()?;++ assert_ne!(baseline[1], typed[1]);+ assert_ne!(baseline, repositioned);+ Ok(())+ }+}diff --git a/packages/sie_server_rust/src/candle_embedding.rs b/packages/sie_server_rust/src/candle_embedding.rsnew file mode 100644index 000000000..b9b5a6649--- /dev/null+++ b/packages/sie_server_rust/src/candle_embedding.rs@@ -0,0 +1,4798 @@+//! Candle-backed dense embedding kernels for native text encoders.++use std::fs;+use std::mem::size_of;+use std::ops::Range;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::time::Instant;++use crate::candle_bert_flash::PackedBertModel;+use crate::candle_gte_rope::{Config as GteRopeConfig, GteRopeForwardProfile, GteRopeModel};+use crate::candle_layers;+use crate::candle_modernbert::{Config as ModernBertConfig, ModernBert, ModernBertForwardProfile};+use crate::candle_splade::{+ pool_packed_splade_activations_dispatch, pool_splade_activations, sparse_embeddings_from_dense,+ CandleBertSpladeHead, CandleSparseEmbedding,+};+use crate::candle_xlm_roberta::{+ Config as XlmRobertaConfig, XlmRobertaForwardProfile, XlmRobertaModel,+};+use anyhow::{Context, Result};+use candle::{DType, Device, Tensor};+use candle_nn::{Module, VarBuilder};+use candle_transformers::models::{+ bert::{BertModel, Config as BertConfig},+ jina_bert::{BertModel as JinaBertModel, Config as JinaBertConfig},+ nomic_bert::{Config as NomicBertConfig, NomicBertModel},+};+use half::f16;+#[cfg(test)]+use hf_hub::Cache;+use hf_hub::{+ api::sync::{Api, ApiBuilder},+ Repo, RepoType,+};+use serde::Deserialize;+use tokenizers::{PaddingParams, PaddingStrategy, Tokenizer, TruncationParams};+use tracing::{info, warn};++#[derive(Debug, Clone)]+pub struct CandleEmbeddingModelConfig {+ pub model_id: String,+ pub hf_id: String,+ pub hf_revision: Option<String>,+ pub max_seq_length: usize,+ pub query_max_length: Option<usize>,+ pub dense_dim: Option<usize>,+ pub sparse_dim: Option<usize>,+ pub multivector_dim: Option<usize>,+ pub compute_precision: Option<String>,+}++#[derive(Debug, Clone)]+pub struct CandleEncodeRequest {+ pub text: String,+}++#[derive(Debug, Clone)]+pub struct CandlePreparedEncodeRequest {+ pub input_ids: Vec<u32>,+ pub attention_mask: Option<Vec<u32>>,+ pub token_type_ids: Option<Vec<u32>>,+}++struct PreparedPackedTensors {+ input_ids: Tensor,+ token_type_ids: Tensor,+ position_ids: Tensor,+ seqlens: Tensor,+ seq_lengths: Vec<usize>,+ max_seqlen: usize,+}++#[derive(Debug, Clone)]+pub struct CandleEncodeResult {+ pub embeddings: Vec<Vec<f32>>,+ pub(crate) sparse_embeddings: Option<Vec<CandleSparseEmbedding>>,+ pub multivectors: Option<Vec<CandleMultivectorEmbedding>>,+ pub multivectors_f16: Option<CandleF16MultivectorBatch>,+ pub dim: u32,+ pub tokenization_ms: f64,+ pub inference_ms: f64,+ pub stages: CandleEncodeStageTimings,+ pub forward_profile: Option<Box<CandleForwardProfile>>,+}++#[derive(Debug, Clone)]+pub struct CandleScoreResult {+ pub scores: Vec<f32>,+ pub query_tokens: usize,+ pub doc_tokens: Vec<usize>,+ pub tokenization_ms: f64,+ pub inference_ms: f64,+ /// MaxSim-only timing is available when synchronized diagnostic timings+ /// are enabled. It is diagnostic metadata, not response postprocessing:+ /// `inference_ms` already covers query/doc forward plus MaxSim.+ pub maxsim_ms: Option<f64>,+}++#[derive(Debug, Clone)]+pub struct CandleMultivectorEmbedding {+ pub values: Vec<f32>,+ pub values_f16: Vec<u8>,+ pub num_tokens: u32,+ pub token_dims: u32,+}++/// A single device-to-host f16 buffer with the layout of each multivector.+///+/// Keeping the offsets alongside the one buffer avoids allocating and copying+/// a separate buffer for every request in a packed ColBERT batch.+#[derive(Debug, Clone)]+pub struct CandleF16MultivectorBatch {+ pub values_f16: Vec<f16>,+ pub items: Vec<CandleF16MultivectorItem>,+}++#[derive(Debug, Clone)]+pub struct CandleF16MultivectorItem {+ pub byte_offset: usize,+ pub byte_len: usize,+ pub num_tokens: u32,+ pub token_dims: u32,+}++impl CandleF16MultivectorBatch {+ /// Legacy per-item representation used only when talking to an older+ /// sidecar that did not opt into the shared-buffer response.+ pub fn into_individual(self) -> Result<Vec<CandleMultivectorEmbedding>> {+ self.items+ .into_iter()+ .map(|item| {+ if !item.byte_offset.is_multiple_of(size_of::<f16>())+ || !item.byte_len.is_multiple_of(size_of::<f16>())+ {+ anyhow::bail!("f16 multivector byte range is not f16-aligned");+ }+ let value_offset = item.byte_offset / size_of::<f16>();+ let value_len = item.byte_len / size_of::<f16>();+ let end = item+ .byte_offset+ .checked_add(item.byte_len)+ .context("f16 multivector byte range overflow")?;+ let value_end = value_offset+ .checked_add(value_len)+ .context("f16 multivector value range overflow")?;+ if end / size_of::<f16>() != value_end {+ anyhow::bail!("f16 multivector byte range is not f16-aligned");+ }+ let values_f16: &[f16] = self+ .values_f16+ .get(value_offset..value_end)+ .context("f16 multivector byte range exceeds batch buffer")?;+ Ok(CandleMultivectorEmbedding {+ values: Vec::new(),+ values_f16: f16_values_to_le_bytes(values_f16),+ num_tokens: item.num_tokens,+ token_dims: item.token_dims,+ })+ })+ .collect()+ }+}++#[derive(Debug, Clone, Copy, Default)]+struct F16MultivectorConversionTimings {+ tensor_readback_ms: f64,+ host_pack_ms: f64,+}++pub struct CandleMultivectorEncodeIntermediate {+ projected: Tensor,+ split: CandleMultivectorSplit,+ output_dtype: String,+ token_dim: usize,+ tokenization_ms: f64,+ inference_start: Instant,+ forward_ms: f64,+ pool_ms: f64,+ normalize_ms: f64,+ sync_timings: bool,+ forward_profile: Option<CandleForwardProfile>,+}++enum CandleMultivectorSplit {+ Masked { attention_mask: Tensor },+ Packed { seq_lengths: Vec<usize> },+}++impl CandleMultivectorEncodeIntermediate {+ pub fn finish(self) -> Result<CandleEncodeResult> {+ let conversion_start = Instant::now();+ let (multivectors, multivectors_f16, conversion_detail) = match self.split {+ CandleMultivectorSplit::Masked { attention_mask } => {+ if self.output_dtype == "float16" {+ let (batch, detail) =+ split_multivectors_f16(&self.projected, &attention_mask, self.token_dim)?;+ (None, Some(batch), detail)+ } else {+ (+ Some(split_multivectors(+ &self.projected,+ &attention_mask,+ self.token_dim,+ )?),+ None,+ F16MultivectorConversionTimings::default(),+ )+ }+ }+ CandleMultivectorSplit::Packed { seq_lengths } => {+ if self.output_dtype == "float16" {+ let (batch, detail) = split_packed_multivectors_f16(+ &self.projected,+ &seq_lengths,+ self.token_dim,+ )?;+ (None, Some(batch), detail)+ } else {+ (+ Some(split_packed_multivectors(+ &self.projected,+ &seq_lengths,+ self.token_dim,+ )?),+ None,+ F16MultivectorConversionTimings::default(),+ )+ }+ }+ };+ if self.sync_timings {+ self.projected.device().synchronize()?;+ }+ let conversion_ms = elapsed_ms(conversion_start);+ let inference_ms = self.inference_start.elapsed().as_secs_f64() * 1000.0;++ Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors,+ multivectors_f16,+ dim: self.token_dim as u32,+ tokenization_ms: self.tokenization_ms,+ inference_ms,+ stages: CandleEncodeStageTimings {+ forward_ms: self.forward_ms,+ pool_ms: self.pool_ms,+ normalize_ms: self.normalize_ms,+ conversion_ms,+ conversion_tensor_readback_ms: conversion_detail.tensor_readback_ms,+ conversion_host_pack_ms: conversion_detail.host_pack_ms,+ inference_ms,+ },+ forward_profile: self.forward_profile.map(Box::new),+ })+ }++ /// Split projected token matrices without copying their values to the+ /// host. Only a padded attention mask may be read back to identify valid+ /// rows; projected multivectors remain on their original device.+ fn into_device_multivectors(self) -> Result<Vec<Tensor>> {+ match self.split {+ CandleMultivectorSplit::Packed { seq_lengths } => {+ let mut cursor = 0usize;+ let mut outputs = Vec::with_capacity(seq_lengths.len());+ for len in seq_lengths {+ outputs.push(self.projected.narrow(0, cursor, len)?);+ cursor = cursor+ .checked_add(len)+ .context("packed multivector device split overflow")?;+ }+ if cursor != self.projected.dim(0)? {+ anyhow::bail!(+ "packed multivector device split consumed {cursor} rows but projected has {}",+ self.projected.dim(0)?+ );+ }+ Ok(outputs)+ }+ CandleMultivectorSplit::Masked { attention_mask } => {+ let (batch_size, sequence_length, token_dim) = self.projected.dims3()?;+ let masks = attention_mask.to_vec2::<u32>()?;+ if masks.len() != batch_size {+ anyhow::bail!(+ "masked multivector batch mismatch: projected={batch_size} masks={}",+ masks.len()+ );+ }+ let mut outputs = Vec::with_capacity(batch_size);+ for (batch_index, mask) in masks.into_iter().enumerate() {+ if mask.len() != sequence_length {+ anyhow::bail!(+ "masked multivector sequence mismatch: projected={sequence_length} mask={}",+ mask.len()+ );+ }+ let rows = self+ .projected+ .narrow(0, batch_index, 1)?+ .reshape((sequence_length, token_dim))?;+ let indices = mask+ .into_iter()+ .enumerate()+ .filter_map(|(index, keep)| (keep != 0).then_some(index as u32))+ .collect::<Vec<_>>();+ if indices.is_empty() {+ outputs.push(Tensor::zeros(+ (0, token_dim),+ self.projected.dtype(),+ self.projected.device(),+ )?);+ } else {+ let indices = Tensor::new(indices.as_slice(), self.projected.device())?;+ outputs.push(candle_layers::index_select(&rows, &indices, 0)?);+ }+ }+ Ok(outputs)+ }+ }+ }+}++pub struct CandleEmbeddingModel {+ model_id: String,+ hf_id: String,+ architecture: CandleEmbeddingArchitecture,+ model: CandleEmbeddingInner,+ tokenizer: Tokenizer,+ device: Device,+ dtype: DType,+ max_seq_length: usize,+ query_max_length: Option<usize>,+ dense_dim: usize,+ sparse_dim: Option<usize>,+ splade_head: Option<CandleBertSpladeHead>,+ packed_bert: Option<PackedBertModel>,+ multivector_dim: Option<usize>,+ pylate_dense_chain: Option<PylateDenseChain>,+ pad_id: u32,+ tokenizer_path: PathBuf,+ tokenizer_id: String,+ diagnostics: CandleDiagnosticsConfig,+ diagnostic_batches: AtomicU64,+}++enum CandleEmbeddingInner {+ Bert(BertModel),+ JinaBert(JinaBertModel),+ XlmRoberta(XlmRobertaModel),+ GteRope(GteRopeModel),+ ModernBert(ModernBert),+ NomicBert(NomicBertModel),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CandleEmbeddingArchitecture {+ Bert,+ JinaBert,+ XlmRoberta,+ GteRope,+ ModernBert,+ NomicBert,+}++#[derive(Debug, Deserialize)]+struct ModelTypeProbe {+ #[serde(default)]+ model_type: Option<String>,+ #[serde(default)]+ architectures: Vec<String>,+ #[serde(default)]+ position_embedding_type: Option<String>,+ #[serde(default)]+ feed_forward_type: Option<String>,+}++struct LoadedCandleEmbedding {+ model: CandleEmbeddingInner,+ hidden_size: usize,+ max_position_embeddings: usize,+}++fn modernbert_rope_theta(config: &serde_json::Value, attention_kind: &str) -> Option<f64> {+ config+ .get("rope_parameters")+ .and_then(|params| params.get(attention_kind))+ .and_then(|params| params.get("rope_theta"))+ .and_then(serde_json::Value::as_f64)+}++fn parse_modernbert_config(raw_config: &str) -> Result<ModernBertConfig> {+ let mut config: serde_json::Value = serde_json::from_str(raw_config)?;+ if let (Some(norm_eps), Some(layer_norm_eps)) = (+ config.get("norm_eps").and_then(serde_json::Value::as_f64),+ config+ .get("layer_norm_eps")+ .and_then(serde_json::Value::as_f64),+ ) {+ if norm_eps != layer_norm_eps {+ anyhow::bail!(+ "ModernBERT norm_eps {norm_eps} conflicts with layer_norm_eps {layer_norm_eps}"+ );+ }+ }+ if config.get("norm_eps").is_none() {+ if let Some(layer_norm_eps) = config.get("layer_norm_eps").cloned() {+ config["norm_eps"] = layer_norm_eps;+ }+ }+ if config.get("global_rope_theta").is_none() {+ if let Some(theta) = modernbert_rope_theta(&config, "full_attention") {+ config["global_rope_theta"] = serde_json::Value::from(theta);+ }+ }+ if config.get("local_rope_theta").is_none() {+ if let Some(theta) = modernbert_rope_theta(&config, "sliding_attention") {+ config["local_rope_theta"] = serde_json::Value::from(theta);+ }+ }+ let config: ModernBertConfig =+ serde_json::from_value(config).context("deserialize normalized ModernBERT config")?;+ config.validate()?;+ Ok(config)+}++fn modernbert_var_builder<'a>(vb: VarBuilder<'a>) -> VarBuilder<'a> {+ if vb.contains_tensor("model.embeddings.tok_embeddings.weight")+ || !vb.contains_tensor("embeddings.tok_embeddings.weight")+ {+ return vb;+ }++ vb.rename_f(|name| name.strip_prefix("model.").unwrap_or(name).to_string())+}++#[derive(Debug)]+struct PylateDenseChain {+ weights: Vec<Tensor>,+ output_dim: usize,+}++enum CandleWeightFile {+ Safetensors(PathBuf),+ Pytorch(PathBuf),+}++#[derive(Debug, Clone)]+struct CandleDiagnosticsConfig {+ enabled: bool,+ sync_timings: bool,+ every_n: u64,+}++#[derive(Debug, Deserialize)]+struct SentenceTransformersModule {+ idx: usize,+ path: String,+ #[serde(rename = "type")]+ module_type: String,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+struct PylateDenseConfig {+ in_features: usize,+ out_features: usize,+ bias: bool,+ use_residual: bool,+ activation_function: String,+}++#[derive(Debug, Clone, Copy)]+struct BatchTokenStats {+ items: usize,+ total_tokens: usize,+ squared_tokens: usize,+ min_tokens: usize,+ max_tokens: usize,+}++#[derive(Debug, Clone, Copy, Default)]+pub struct CandleEncodeStageTimings {+ pub forward_ms: f64,+ pub pool_ms: f64,+ pub normalize_ms: f64,+ pub conversion_ms: f64,+ /// CUDA conversion plus the blocking tensor readback to host. It avoids+ /// claiming that either cast or PCIe transfer alone owns this time.+ pub conversion_tensor_readback_ms: f64,+ /// CPU packing from downloaded f16 values into the shared output buffer.+ pub conversion_host_pack_ms: f64,+ pub inference_ms: f64,+}++#[derive(Debug, Clone, Copy)]+pub enum CandleForwardProfile {+ XlmRoberta(XlmRobertaForwardProfile),+ GteRope(GteRopeForwardProfile),+ ModernBert(ModernBertForwardProfile),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum PackedPositionIdPolicy {+ ZeroBased,+ PaddingOffset,+}++#[derive(Debug, Clone, Copy)]+struct CandleGemmPrecisionConfig {+ f32: bool,+ f16: bool,+ bf16: bool,+}++impl CandleDiagnosticsConfig {+ fn from_env() -> Self {+ Self {+ enabled: env_bool_any(+ &["SIE_CANDLE_DIAGNOSTICS", "SIE_CANDLE_DEBUG_KERNELS"],+ false,+ ),+ sync_timings: env_bool_any(+ &["SIE_CANDLE_SYNC_DIAGNOSTICS", "SIE_CANDLE_DIAGNOSTICS_SYNC"],+ false,+ ),+ every_n: env_u64("SIE_CANDLE_DIAGNOSTICS_EVERY_N", 1).max(1),+ }+ }+}++impl CandleGemmPrecisionConfig {+ fn applies_to_dtype(self, dtype: DType) -> bool {+ match dtype {+ DType::F32 => self.f32,+ DType::F16 => self.f16,+ DType::BF16 => self.bf16,+ _ => false,+ }+ }++ fn from_env_for_device(device: &Device) -> Self {+ let config = Self {+ f32: env_bool_any(&["SIE_CANDLE_GEMM_REDUCED_PRECISION_F32"], false),+ f16: env_bool_any(&["SIE_CANDLE_GEMM_REDUCED_PRECISION_F16"], true),+ bf16: env_bool_any(+ &[+ "SIE_CANDLE_GEMM_REDUCED_PRECISION_BF16",+ "SIE_CANDLE_FAST_BF16_GEMM",+ ],+ true,+ ),+ };++ if device.is_cuda() {+ candle::cuda::set_gemm_reduced_precision_f32(config.f32);+ candle::cuda::set_gemm_reduced_precision_f16(config.f16);+ candle::cuda::set_gemm_reduced_precision_bf16(config.bf16);+ }++ config+ }+}++impl BatchTokenStats {+ fn from_lengths(lengths: impl IntoIterator<Item = usize>) -> Self {+ let mut items = 0usize;+ let mut total_tokens = 0usize;+ let mut squared_tokens = 0usize;+ let mut min_tokens = usize::MAX;+ let mut max_tokens = 0usize;++ for len in lengths {+ items += 1;+ total_tokens += len;+ squared_tokens = squared_tokens.saturating_add(len.saturating_mul(len));+ min_tokens = min_tokens.min(len);+ max_tokens = max_tokens.max(len);+ }++ if items == 0 {+ min_tokens = 0;+ }++ Self {+ items,+ total_tokens,+ squared_tokens,+ min_tokens,+ max_tokens,+ }+ }++ fn avg_tokens(self) -> f64 {+ if self.items == 0 {+ 0.0+ } else {+ self.total_tokens as f64 / self.items as f64+ }+ }+}++fn attention_gflops(squared_tokens: usize, hidden_size: usize, layers: usize) -> f64 {+ 4.0 * squared_tokens as f64 * hidden_size as f64 * layers as f64 / 1_000_000_000.0+}++fn tflops_per_second(gflops: f64, elapsed_ms: f64) -> f64 {+ if elapsed_ms <= 0.0 {+ 0.0+ } else {+ gflops / elapsed_ms+ }+}++impl CandleEmbeddingArchitecture {+ fn from_probe(probe: &ModelTypeProbe) -> Result<Self> {+ let normalized = probe+ .model_type+ .as_deref()+ .unwrap_or("bert")+ .to_ascii_lowercase()+ .replace('-', "_");+ match normalized.as_str() {+ "bert" if probe.looks_like_jina_bert() => Ok(Self::JinaBert),+ "bert" => Ok(Self::Bert),+ "jina_bert" => Ok(Self::JinaBert),+ "xlm_roberta" => Ok(Self::XlmRoberta),+ "new" | "gte" if probe.uses_rope_position_embeddings() => Ok(Self::GteRope),+ "new" | "gte" => anyhow::bail!(+ "CandleEmbeddingAdapter supports model_type={normalized:?} only when position_embedding_type=rope"+ ),+ "modernbert" | "modern_bert" => Ok(Self::ModernBert),+ "nomic_bert" => Ok(Self::NomicBert),+ _ => anyhow::bail!(+ "CandleEmbeddingAdapter does not support model_type={:?}; supported model types are bert, jina-bert, xlm-roberta, new/gte rope, modernbert, and nomic_bert",+ probe.model_type+ ),+ }+ }++ fn name(self) -> &'static str {+ match self {+ Self::Bert => "BERT",+ Self::JinaBert => "JinaBERT",+ Self::XlmRoberta => "XLM-RoBERTa",+ Self::GteRope => "GTE-RoPE",+ Self::ModernBert => "ModernBERT",+ Self::NomicBert => "NomicBERT",+ }+ }+}++impl ModelTypeProbe {+ fn looks_like_jina_bert(&self) -> bool {+ self.architectures+ .iter()+ .any(|architecture| architecture.to_ascii_lowercase().contains("jinabert"))+ || matches!(self.position_embedding_type.as_deref(), Some("alibi"))+ && matches!(self.feed_forward_type.as_deref(), Some("geglu"))+ }++ fn uses_rope_position_embeddings(&self) -> bool {+ self.position_embedding_type+ .as_deref()+ .is_some_and(|value| value.eq_ignore_ascii_case("rope"))+ }+}++impl CandleEmbeddingInner {+ fn load(+ architecture: CandleEmbeddingArchitecture,+ raw_config: &str,+ vb: VarBuilder,+ hf_id: &str,+ ) -> Result<LoadedCandleEmbedding> {+ match architecture {+ CandleEmbeddingArchitecture::Bert => {+ let model_config: BertConfig = serde_json::from_str(raw_config)+ .with_context(|| format!("parse BERT config for {hf_id}"))?;+ let hidden_size = model_config.hidden_size;+ let max_position_embeddings = model_config.max_position_embeddings;+ let model = BertModel::load(vb, &model_config)+ .with_context(|| format!("load Candle BERT model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::Bert(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ CandleEmbeddingArchitecture::JinaBert => {+ let model_config: JinaBertConfig = serde_json::from_str(raw_config)+ .with_context(|| format!("parse JinaBERT config for {hf_id}"))?;+ let hidden_size = model_config.hidden_size;+ let max_position_embeddings = model_config.max_position_embeddings;+ let model = JinaBertModel::new(vb, &model_config)+ .with_context(|| format!("load Candle JinaBERT model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::JinaBert(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ CandleEmbeddingArchitecture::XlmRoberta => {+ let model_config: XlmRobertaConfig = serde_json::from_str(raw_config)+ .with_context(|| format!("parse XLM-RoBERTa config for {hf_id}"))?;+ let hidden_size = model_config.hidden_size;+ let max_position_embeddings = model_config.max_position_embeddings;+ let model = XlmRobertaModel::new(&model_config, vb)+ .with_context(|| format!("load Candle XLM-RoBERTa model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::XlmRoberta(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ CandleEmbeddingArchitecture::GteRope => {+ let model_config: GteRopeConfig = serde_json::from_str(raw_config)+ .with_context(|| format!("parse GTE-RoPE config for {hf_id}"))?;+ let hidden_size = model_config.hidden_size;+ let max_position_embeddings = model_config.max_position_embeddings;+ let model = GteRopeModel::load(&model_config, vb)+ .with_context(|| format!("load Candle GTE-RoPE model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::GteRope(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ CandleEmbeddingArchitecture::ModernBert => {+ let model_config = parse_modernbert_config(raw_config)+ .with_context(|| format!("parse ModernBERT config for {hf_id}"))?;+ let hidden_size = model_config.hidden_size;+ let max_position_embeddings = model_config.max_position_embeddings;+ let vb = modernbert_var_builder(vb);+ let model = ModernBert::load(vb, &model_config)+ .with_context(|| format!("load Candle ModernBERT model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::ModernBert(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ CandleEmbeddingArchitecture::NomicBert => {+ let model_config: NomicBertConfig = serde_json::from_str(raw_config)+ .with_context(|| format!("parse NomicBERT config for {hf_id}"))?;+ let hidden_size = model_config.n_embd;+ let max_position_embeddings = model_config.n_positions;+ let model = NomicBertModel::load(vb, &model_config)+ .with_context(|| format!("load Candle NomicBERT model for {hf_id}"))?;+ Ok(LoadedCandleEmbedding {+ model: Self::NomicBert(model),+ hidden_size,+ max_position_embeddings,+ })+ }+ }+ }++ fn forward(+ &self,+ token_ids: &Tensor,+ attention_mask: &Tensor,+ token_type_ids: &Tensor,+ ) -> candle::Result<Tensor> {+ match self {+ Self::Bert(model) => model.forward(token_ids, token_type_ids, Some(attention_mask)),+ Self::JinaBert(model) => model.forward(token_ids),+ Self::XlmRoberta(model) => model.forward(token_ids, attention_mask, token_type_ids),+ Self::GteRope(_) => {+ candle::bail!("Candle GTE-RoPE model requires packed FlashAttention forward")+ }+ Self::ModernBert(model) => model.forward(token_ids, attention_mask),+ Self::NomicBert(model) => {+ model.forward(token_ids, Some(token_type_ids), Some(attention_mask))+ }+ }+ }++ fn forward_packed(&self, packed: &PreparedPackedTensors) -> Option<candle::Result<Tensor>> {+ match self {+ Self::XlmRoberta(model) => Some(model.forward_packed(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )),+ Self::GteRope(model) => Some(model.forward_packed(+ &packed.input_ids,+ &packed.token_type_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )),+ Self::ModernBert(model) => Some(model.forward_packed(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )),+ _ => None,+ }+ }+}++impl CandleEmbeddingModel {+ pub fn load(config: &CandleEmbeddingModelConfig) -> Result<Self> {+ let device = candle_device()?;+ let gemm_precision = CandleGemmPrecisionConfig::from_env_for_device(&device);+ let api = hugging_face_api_from_env()?;+ let revision = config+ .hf_revision+ .clone()+ .unwrap_or_else(|| "main".to_string());+ let repo = api.repo(Repo::with_revision(+ config.hf_id.clone(),+ RepoType::Model,+ revision,+ ));+ let config_filename = repo+ .get("config.json")+ .with_context(|| format!("download config.json for {}", config.hf_id))?;+ let tokenizer_filename = repo+ .get("tokenizer.json")+ .with_context(|| format!("download tokenizer.json for {}", config.hf_id))?;+ let weights_file = download_weight_file(&repo, &config.hf_id)?;++ let raw_config = std::fs::read_to_string(&config_filename)+ .with_context(|| format!("read {}", config_filename.display()))?;+ let model_type_probe: ModelTypeProbe = serde_json::from_str(&raw_config)+ .with_context(|| format!("read model_type from config for {}", config.hf_id))?;+ let architecture = CandleEmbeddingArchitecture::from_probe(&model_type_probe)?;++ let dtype = dtype_from_compute_precision(config.compute_precision.as_deref(), &device)?;+ let vb = var_builder_from_weight_file(weights_file, &config.hf_id, &device, dtype)?;+ let (splade_head, packed_bert) = match config.sparse_dim {+ Some(sparse_dim) => {+ if architecture != CandleEmbeddingArchitecture::Bert {+ anyhow::bail!(+ "Candle sparse encode for {} requires a BERT masked-language-model checkpoint, got {}",+ config.model_id,+ architecture.name()+ );+ }+ let bert_config: BertConfig = serde_json::from_str(&raw_config)+ .with_context(|| format!("parse BERT SPLADE config for {}", config.hf_id))?;+ let head = CandleBertSpladeHead::load(vb.clone(), &bert_config)+ .with_context(|| format!("load Candle SPLADE head for {}", config.hf_id))?;+ if head.vocab_size() != sparse_dim {+ anyhow::bail!(+ "Candle sparse dimension mismatch for {}: catalog sparse_dim={} model vocab_size={}",+ config.model_id,+ sparse_dim,+ head.vocab_size()+ );+ }+ let packed_bert = if device.is_cuda() && dtype == DType::F16 {+ match PackedBertModel::load(vb.clone(), &bert_config) {+ Ok(model) => Some(model),+ Err(error) => {+ warn!(+ model_id = %config.model_id,+ hf_id = %config.hf_id,+ error = %error,+ "packed BERT load failed; using padded SPLADE fallback"+ );+ None+ }+ }+ } else {+ None+ };+ (Some(head), packed_bert)+ }+ None => (None, None),+ };+ let loaded = CandleEmbeddingInner::load(architecture, &raw_config, vb, &config.hf_id)?;+ if let Some(expected_dim) = config.dense_dim {+ if loaded.hidden_size != expected_dim {+ anyhow::bail!(+ "Candle embedding dimension mismatch for {}: catalog dense_dim={} model hidden_size={}",+ config.model_id,+ expected_dim,+ loaded.hidden_size+ );+ }+ }+ let pylate_dense_chain = match config.multivector_dim {+ Some(token_dim) => Some(load_pylate_dense_chain(+ &repo,+ &config.hf_id,+ loaded.hidden_size,+ token_dim,+ &device,+ dtype,+ )?),+ None => None,+ };++ let tokenizer_for_hash = Tokenizer::from_file(&tokenizer_filename)+ .map_err(anyhow::Error::msg)+ .with_context(|| format!("load tokenizer for {}", config.hf_id))?;+ let tokenizer_id = tokenizer_content_hash(&tokenizer_for_hash)+ .with_context(|| format!("hash tokenizer for {}", config.hf_id))?;+ let tokenizer_path =+ materialize_tokenizer(&config.model_id, &tokenizer_filename, &tokenizer_id)?;++ let mut tokenizer = tokenizer_for_hash;+ let pad_id = tokenizer+ .get_padding()+ .map(|padding| padding.pad_id)+ .unwrap_or(0);+ let max_seq_length = config+ .max_seq_length+ .max(1)+ .min(loaded.max_position_embeddings);+ tokenizer+ .with_truncation(Some(TruncationParams {+ max_length: max_seq_length,+ ..Default::default()+ }))+ .map_err(anyhow::Error::msg)+ .with_context(|| format!("configure tokenizer truncation for {}", config.hf_id))?;+ if let Some(existing) = tokenizer.get_padding_mut() {+ existing.strategy = PaddingStrategy::BatchLongest;+ } else {+ tokenizer.with_padding(Some(PaddingParams {+ strategy: PaddingStrategy::BatchLongest,+ ..Default::default()+ }));+ }+ let diagnostics = CandleDiagnosticsConfig::from_env();++ info!(+ model_id = %config.model_id,+ hf_id = %config.hf_id,+ architecture = architecture.name(),+ device = ?device,+ configured_compute_precision = config.compute_precision.as_deref().unwrap_or("auto"),+ compute_dtype = ?dtype,+ dtype = ?dtype,+ hidden_size = loaded.hidden_size,+ sparse_dim = config.sparse_dim,+ packed_bert = packed_bert.is_some(),+ max_seq_length,+ gemm_reduced_precision_f32 = gemm_precision.f32,+ gemm_reduced_precision_f16 = gemm_precision.f16,+ gemm_reduced_precision_bf16 = gemm_precision.bf16,+ gemm_reduced_precision_applies_to_compute_dtype = gemm_precision.applies_to_dtype(dtype),+ tokenizer_id = %tokenizer_id,+ tokenizer_path = %tokenizer_path.display(),+ "loaded Candle embedding model"+ );+ if diagnostics.enabled {+ info!(+ model_id = %config.model_id,+ sync_timings = diagnostics.sync_timings,+ every_n = diagnostics.every_n,+ "Candle embedding diagnostics enabled"+ );+ }++ Ok(Self {+ model_id: config.model_id.clone(),+ hf_id: config.hf_id.clone(),+ architecture,+ model: loaded.model,+ tokenizer,+ device,+ dtype,+ max_seq_length,+ query_max_length: config+ .query_max_length+ .map(|max_length| max_length.max(1).min(max_seq_length)),+ dense_dim: loaded.hidden_size,+ sparse_dim: config.sparse_dim,+ splade_head,+ packed_bert,+ multivector_dim: config.multivector_dim,+ pylate_dense_chain,+ pad_id,+ tokenizer_path,+ tokenizer_id,+ diagnostics,+ diagnostic_batches: AtomicU64::new(0),+ })+ }++ pub fn encode(+ &self,+ requests: &[CandleEncodeRequest],+ pooling: &str,+ normalize: bool,+ ) -> Result<CandleEncodeResult> {+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors: None,+ multivectors_f16: None,+ dim: self.dense_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }+ if !matches!(pooling, "mean" | "cls") {+ anyhow::bail!("unsupported Candle pooling strategy {pooling:?}; expected mean or cls");+ }++ let tokenization_start = Instant::now();+ let texts: Vec<&str> = requests+ .iter()+ .map(|request| request.text.as_str())+ .collect();+ if self.should_use_packed_forward() {+ let prepared_requests = texts+ .iter()+ .map(|text| {+ self.tokenizer+ .encode(*text, true)+ .map_err(anyhow::Error::msg)+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let tokenization_ms = tokenization_start.elapsed().as_secs_f64() * 1000.0;+ let pack_start = Instant::now();+ let packed = self.prepared_packed_tensors(&prepared_requests)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed(+ &packed,+ pooling,+ normalize,+ tokenization_ms,+ pack_ms,+ "raw",+ );+ }++ let encodings = self+ .tokenizer+ .encode_batch(texts, true)+ .map_err(anyhow::Error::msg)+ .context("tokenize Candle embedding batch")?;+ let token_stats = BatchTokenStats::from_lengths(encodings.iter().map(|encoding| {+ encoding+ .get_attention_mask()+ .iter()+ .filter(|&&mask| mask != 0)+ .count()+ }));+ let tensorize_start = Instant::now();+ let token_ids = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_ids(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let attention_mask = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_attention_mask(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let token_ids = Tensor::stack(&token_ids, 0)?;+ let attention_mask = Tensor::stack(&attention_mask, 0)?;+ let token_type_ids = token_ids.zeros_like()?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ let tokenization_ms = tokenization_start.elapsed().as_secs_f64() * 1000.0;++ self.encode_tensors(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ pooling,+ normalize,+ tokenization_ms,+ token_stats,+ tensorize_ms,+ "raw",+ )+ }++ pub fn encode_prepared(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ pooling: &str,+ normalize: bool,+ ) -> Result<CandleEncodeResult> {+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors: None,+ multivectors_f16: None,+ dim: self.dense_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }+ if !matches!(pooling, "mean" | "cls") {+ anyhow::bail!("unsupported Candle pooling strategy {pooling:?}; expected mean or cls");+ }++ if self.should_use_packed_forward() {+ let pack_start = Instant::now();+ let packed = self.prepared_packed_tensors(requests)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed(&packed, pooling, normalize, 0.0, pack_ms, "prepared");+ }++ let token_stats = self.prepared_token_stats(requests);+ let tensorize_start = Instant::now();+ let (token_ids, attention_mask, token_type_ids) = self.prepared_tensors(requests)?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ self.encode_tensors(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ pooling,+ normalize,+ 0.0,+ token_stats,+ tensorize_ms,+ "prepared",+ )+ }++ pub fn encode_sparse(&self, requests: &[CandleEncodeRequest]) -> Result<CandleEncodeResult> {+ let sparse_dim = self+ .sparse_dim+ .context("Candle sparse encode requested for model without sparse_dim")?;+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: Some(Vec::new()),+ multivectors: None,+ multivectors_f16: None,+ dim: sparse_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }++ let tokenization_start = Instant::now();+ let texts = requests+ .iter()+ .map(|request| request.text.as_str())+ .collect::<Vec<_>>();+ if self.should_use_packed_splade() {+ let prepared_requests = texts+ .iter()+ .map(|text| {+ self.tokenizer+ .encode(*text, true)+ .map_err(anyhow::Error::msg)+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let tokenization_ms = elapsed_ms(tokenization_start);+ let pack_start = Instant::now();+ let packed = self.prepared_packed_tensors(&prepared_requests)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed_sparse(&packed, tokenization_ms, pack_ms, "raw");+ }+ let encodings = self+ .tokenizer+ .encode_batch(texts, true)+ .map_err(anyhow::Error::msg)+ .context("tokenize Candle SPLADE batch")?;+ let token_stats = BatchTokenStats::from_lengths(encodings.iter().map(|encoding| {+ encoding+ .get_attention_mask()+ .iter()+ .filter(|&&mask| mask != 0)+ .count()+ }));+ let tensorize_start = Instant::now();+ let token_ids = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_ids(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let attention_mask = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_attention_mask(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let token_type_ids = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_type_ids(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let token_ids = Tensor::stack(&token_ids, 0)?;+ let attention_mask = Tensor::stack(&attention_mask, 0)?;+ let token_type_ids = Tensor::stack(&token_type_ids, 0)?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ let tokenization_ms = elapsed_ms(tokenization_start);++ self.encode_sparse_tensors(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ tokenization_ms,+ token_stats,+ tensorize_ms,+ "raw",+ )+ }++ pub fn encode_prepared_sparse(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ ) -> Result<CandleEncodeResult> {+ let sparse_dim = self+ .sparse_dim+ .context("Candle sparse encode requested for model without sparse_dim")?;+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: Some(Vec::new()),+ multivectors: None,+ multivectors_f16: None,+ dim: sparse_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }++ if self.should_use_packed_splade()+ && Self::prepared_attention_masks_are_prefix(requests, self.max_seq_length)+ {+ let pack_start = Instant::now();+ let packed = self.prepared_packed_tensors(requests)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed_sparse(&packed, 0.0, pack_ms, "prepared");+ }++ let token_stats = self.prepared_token_stats(requests);+ let tensorize_start = Instant::now();+ let (token_ids, attention_mask, token_type_ids) = self.prepared_tensors(requests)?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ self.encode_sparse_tensors(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ 0.0,+ token_stats,+ tensorize_ms,+ "prepared",+ )+ }++ pub fn encode_multivector(+ &self,+ requests: &[CandleEncodeRequest],+ normalize: bool,+ is_query: bool,+ output_dtype: &str,+ ) -> Result<CandleEncodeResult> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors: Some(Vec::new()),+ multivectors_f16: None,+ dim: token_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }+ self.encode_multivector_intermediate(requests, normalize, is_query, output_dtype)?+ .finish()+ }++ pub fn encode_multivector_intermediate(+ &self,+ requests: &[CandleEncodeRequest],+ normalize: bool,+ is_query: bool,+ output_dtype: &str,+ ) -> Result<CandleMultivectorEncodeIntermediate> {+ if requests.is_empty() {+ anyhow::bail!("Candle multivector requests are empty");+ }++ let tokenization_start = Instant::now();+ let texts: Vec<&str> = requests+ .iter()+ .map(|request| request.text.as_str())+ .collect();+ let max_seq_length = self.multivector_raw_max_seq_length(is_query);+ if self.should_use_packed_forward() {+ let tokenizer = tokenizer_for_max_seq_length_without_padding(+ &self.tokenizer,+ max_seq_length,+ &self.hf_id,+ )?;+ let prepared_requests = tokenizer+ .encode_batch(texts, true)+ .map_err(anyhow::Error::msg)+ .context("tokenize Candle packed multivector batch")?+ .into_iter()+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ .collect::<Vec<_>>();+ let tokenization_ms = tokenization_start.elapsed().as_secs_f64() * 1000.0;+ let pack_start = Instant::now();+ let packed =+ self.prepared_packed_tensors_with_max(&prepared_requests, max_seq_length)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed_multivector_intermediate(+ &packed,+ normalize,+ output_dtype,+ tokenization_ms,+ pack_ms,+ "raw",+ );+ }+ let tokenizer = tokenizer_for_max_seq_length(&self.tokenizer, max_seq_length, &self.hf_id)?;+ let encodings = tokenizer+ .encode_batch(texts, true)+ .map_err(anyhow::Error::msg)+ .context("tokenize Candle multivector batch")?;+ let token_stats = BatchTokenStats::from_lengths(encodings.iter().map(|encoding| {+ encoding+ .get_attention_mask()+ .iter()+ .filter(|&&mask| mask != 0)+ .count()+ }));+ let tensorize_start = Instant::now();+ let token_ids = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_ids(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let attention_mask = encodings+ .iter()+ .map(|encoding| Tensor::new(encoding.get_attention_mask(), &self.device))+ .collect::<candle::Result<Vec<_>>>()?;+ let token_ids = Tensor::stack(&token_ids, 0)?;+ let attention_mask = Tensor::stack(&attention_mask, 0)?;+ let token_type_ids = token_ids.zeros_like()?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ let tokenization_ms = tokenization_start.elapsed().as_secs_f64() * 1000.0;++ self.encode_multivector_tensors_intermediate(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ normalize,+ output_dtype,+ tokenization_ms,+ token_stats,+ tensorize_ms,+ "raw",+ )+ }++ pub fn encode_prepared_multivector(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ normalize: bool,+ is_query: bool,+ output_dtype: &str,+ ) -> Result<CandleEncodeResult> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ if requests.is_empty() {+ return Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: None,+ multivectors: Some(Vec::new()),+ multivectors_f16: None,+ dim: token_dim as u32,+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ stages: CandleEncodeStageTimings::default(),+ forward_profile: None,+ });+ }+ self.encode_prepared_multivector_intermediate(requests, normalize, is_query, output_dtype)?+ .finish()+ }++ pub fn encode_prepared_multivector_intermediate(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ normalize: bool,+ is_query: bool,+ output_dtype: &str,+ ) -> Result<CandleMultivectorEncodeIntermediate> {+ if requests.is_empty() {+ anyhow::bail!("prepared Candle multivector tokens are empty");+ }++ let max_seq_length = self.multivector_raw_max_seq_length(is_query);+ if self.should_use_packed_forward() {+ let pack_start = Instant::now();+ let packed = self.prepared_packed_tensors_with_max(requests, max_seq_length)?;+ let pack_ms = elapsed_ms(pack_start);+ return self.encode_packed_multivector_intermediate(+ &packed,+ normalize,+ output_dtype,+ 0.0,+ pack_ms,+ "prepared",+ );+ }+ let token_stats = self.prepared_token_stats_with_max(requests, max_seq_length);+ let tensorize_start = Instant::now();+ let (token_ids, attention_mask, token_type_ids) =+ self.prepared_tensors_with_max(requests, max_seq_length)?;+ let tensorize_ms = elapsed_ms(tensorize_start);+ self.encode_multivector_tensors_intermediate(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ normalize,+ output_dtype,+ 0.0,+ token_stats,+ tensorize_ms,+ "prepared",+ )+ }++ /// Score one query against documents with late-interaction MaxSim.+ ///+ /// Query and document text are tokenized with their independent caps. The+ /// projected, normalized multivectors never leave the model device; only+ /// the final f32 score vector is copied to the host.+ pub fn score_multivector(+ &self,+ query: &CandleEncodeRequest,+ docs: &[CandleEncodeRequest],+ normalize: bool,+ doc_work_budget: usize,+ ) -> Result<CandleScoreResult> {+ if docs.is_empty() {+ return Ok(CandleScoreResult {+ scores: Vec::new(),+ query_tokens: 0,+ doc_tokens: Vec::new(),+ tokenization_ms: 0.0,+ inference_ms: 0.0,+ maxsim_ms: None,+ });+ }++ let tokenization_start = Instant::now();+ let mut query = self.tokenize_multivector_requests(std::slice::from_ref(query), true)?;+ let docs = self.tokenize_multivector_requests(docs, false)?;+ let tokenization_ms = elapsed_ms(tokenization_start);+ let query = query+ .pop()+ .context("Candle score query tokenization returned no query")?;+ self.score_prepared_multivector_impl(+ &query,+ &docs,+ normalize,+ doc_work_budget,+ tokenization_ms,+ )+ }++ /// Prepared-token form of [`Self::score_multivector`]. The rows must be+ /// supplied separately so query and document truncation caps remain+ /// distinct.+ pub fn score_prepared_multivector(+ &self,+ query: &CandlePreparedEncodeRequest,+ docs: &[CandlePreparedEncodeRequest],+ normalize: bool,+ doc_work_budget: usize,+ ) -> Result<CandleScoreResult> {+ self.score_prepared_multivector_impl(query, docs, normalize, doc_work_budget, 0.0)+ }++ fn score_prepared_multivector_impl(+ &self,+ query: &CandlePreparedEncodeRequest,+ docs: &[CandlePreparedEncodeRequest],+ normalize: bool,+ doc_work_budget: usize,+ tokenization_ms: f64,+ ) -> Result<CandleScoreResult> {+ self.multivector_dim+ .context("Candle MaxSim score requested for model without multivector_dim")?;+ if docs.is_empty() {+ return Ok(CandleScoreResult {+ scores: Vec::new(),+ query_tokens: 0,+ doc_tokens: Vec::new(),+ tokenization_ms,+ inference_ms: 0.0,+ maxsim_ms: None,+ });+ }++ let query_tokens =+ Self::prepared_effective_len(self.multivector_raw_max_seq_length(true), query);+ if query_tokens == 0 {+ anyhow::bail!("Candle MaxSim score query tokens are empty");+ }+ let doc_tokens = docs+ .iter()+ .map(|doc| {+ Self::prepared_effective_len(self.multivector_raw_max_seq_length(false), doc)+ })+ .collect::<Vec<_>>();+ if doc_tokens.contains(&0) {+ anyhow::bail!("Candle MaxSim score document tokens are empty");+ }++ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let mut query_vectors = self+ .encode_prepared_multivector_intermediate(+ std::slice::from_ref(query),+ normalize,+ true,+ "float32",+ )?+ .into_device_multivectors()?;+ if query_vectors.len() != 1 {+ anyhow::bail!(+ "Candle MaxSim query encode returned {} vectors",+ query_vectors.len()+ );+ }+ let query_vectors = query_vectors+ .pop()+ .context("Candle MaxSim query encode returned no vector")?;++ let mut scores = Vec::with_capacity(docs.len());+ let mut maxsim_ms = self.diagnostics.sync_timings.then_some(0.0);+ for range in score_document_chunks(&doc_tokens, doc_work_budget.max(1)) {+ let doc_vectors = self+ .encode_prepared_multivector_intermediate(+ &docs[range.clone()],+ normalize,+ false,+ "float32",+ )?+ .into_device_multivectors()?;+ // Synchronize the document forward only for explicitly requested+ // diagnostic timings. The regular hot path keeps its existing+ // asynchronous execution and exposes only the inclusive inference+ // duration below.+ let score_start = if maxsim_ms.is_some() {+ self.synchronize_for_timing()?;+ Some(Instant::now())+ } else {+ None+ };+ scores.extend(maxsim_scores_device(&query_vectors, &doc_vectors)?);+ if let (Some(total), Some(start)) = (&mut maxsim_ms, score_start) {+ *total += elapsed_ms(start);+ }+ }+ self.synchronize_for_timing()?;+ let inference_ms = elapsed_ms(inference_start);+ if scores.len() != docs.len() {+ anyhow::bail!(+ "Candle MaxSim returned {} scores for {} documents",+ scores.len(),+ docs.len()+ );+ }++ Ok(CandleScoreResult {+ scores,+ query_tokens,+ doc_tokens,+ tokenization_ms,+ inference_ms,+ maxsim_ms,+ })+ }++ fn tokenize_multivector_requests(+ &self,+ requests: &[CandleEncodeRequest],+ is_query: bool,+ ) -> Result<Vec<CandlePreparedEncodeRequest>> {+ let tokenizer = tokenizer_for_max_seq_length_without_padding(+ &self.tokenizer,+ self.multivector_raw_max_seq_length(is_query),+ &self.hf_id,+ )?;+ let texts = requests+ .iter()+ .map(|request| request.text.as_str())+ .collect::<Vec<_>>();+ tokenizer+ .encode_batch(texts, true)+ .map_err(anyhow::Error::msg)+ .context("tokenize Candle MaxSim inputs")+ .map(|encodings| {+ encodings+ .into_iter()+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ .collect()+ })+ }++ #[allow(clippy::too_many_arguments)]+ fn encode_packed_sparse(+ &self,+ packed: &PreparedPackedTensors,+ tokenization_ms: f64,+ pack_ms: f64,+ source: &'static str,+ ) -> Result<CandleEncodeResult> {+ let sparse_dim = self+ .sparse_dim+ .context("Candle sparse encode requested for model without sparse_dim")?;+ let splade_head = self+ .splade_head+ .as_ref()+ .context("Candle sparse encode requested for model without a SPLADE head")?;+ let packed_bert = self+ .packed_bert+ .as_ref()+ .context("packed SPLADE encode requested without a packed BERT backbone")?;+ let token_stats = BatchTokenStats::from_lengths(packed.seq_lengths.iter().copied());++ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let sequence_output = packed_bert+ .forward_packed(+ &packed.input_ids,+ &packed.token_type_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )+ .context("run packed Candle SPLADE BERT forward pass")?;+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let pool_start = Instant::now();+ let activated = splade_head+ .forward_activated(&sequence_output)+ .context("run packed Candle SPLADE MLM head")?;+ let max_weights = pool_packed_splade_activations_dispatch(+ &activated,+ &packed.seqlens,+ &packed.seq_lengths,+ )?;+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(pool_start);++ let conversion_start = Instant::now();+ let sparse_embeddings = sparse_embeddings_from_dense(&max_weights)?;+ self.synchronize_for_timing()?;+ let conversion_ms = elapsed_ms(conversion_start);+ let inference_ms = elapsed_ms(inference_start);+ let stages = CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms: 0.0,+ conversion_ms,+ inference_ms,+ ..Default::default()+ };+ self.log_encode_diagnostics(+ "packed_bert_splade",+ source,+ token_stats,+ "splade",+ false,+ tokenization_ms,+ pack_ms,+ stages,+ None,+ );++ Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: Some(sparse_embeddings),+ multivectors: None,+ multivectors_f16: None,+ dim: sparse_dim as u32,+ tokenization_ms,+ inference_ms,+ stages,+ forward_profile: None,+ })+ }++ #[allow(clippy::too_many_arguments)]+ fn encode_sparse_tensors(+ &self,+ token_ids: &Tensor,+ attention_mask: &Tensor,+ token_type_ids: &Tensor,+ tokenization_ms: f64,+ token_stats: BatchTokenStats,+ prepare_ms: f64,+ source: &'static str,+ ) -> Result<CandleEncodeResult> {+ let sparse_dim = self+ .sparse_dim+ .context("Candle sparse encode requested for model without sparse_dim")?;+ let splade_head = self+ .splade_head+ .as_ref()+ .context("Candle sparse encode requested for model without a SPLADE head")?;++ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let sequence_output = self+ .model+ .forward(token_ids, attention_mask, token_type_ids)+ .context("run Candle SPLADE BERT forward pass")?;+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let pool_start = Instant::now();+ let activated = splade_head+ .forward_activated(&sequence_output)+ .context("run Candle SPLADE MLM head")?;+ let max_weights = pool_splade_activations(&activated, attention_mask)?;+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(pool_start);++ let conversion_start = Instant::now();+ let sparse_embeddings = sparse_embeddings_from_dense(&max_weights)?;+ self.synchronize_for_timing()?;+ let conversion_ms = elapsed_ms(conversion_start);+ let inference_ms = elapsed_ms(inference_start);+ let stages = CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms: 0.0,+ conversion_ms,+ inference_ms,+ ..Default::default()+ };+ self.log_encode_diagnostics(+ "padded",+ source,+ token_stats,+ "splade",+ false,+ tokenization_ms,+ prepare_ms,+ stages,+ None,+ );++ Ok(CandleEncodeResult {+ embeddings: Vec::new(),+ sparse_embeddings: Some(sparse_embeddings),+ multivectors: None,+ multivectors_f16: None,+ dim: sparse_dim as u32,+ tokenization_ms,+ inference_ms,+ stages,+ forward_profile: None,+ })+ }++ #[allow(clippy::too_many_arguments)]+ fn encode_tensors(+ &self,+ token_ids: &Tensor,+ attention_mask: &Tensor,+ token_type_ids: &Tensor,+ pooling: &str,+ normalize: bool,+ tokenization_ms: f64,+ token_stats: BatchTokenStats,+ prepare_ms: f64,+ source: &'static str,+ ) -> Result<CandleEncodeResult> {+ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let sequence_output = self+ .model+ .forward(token_ids, attention_mask, token_type_ids)+ .context("run Candle embedding forward pass")?;+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let pool_start = Instant::now();+ let pooled = pool_embeddings(&sequence_output, attention_mask, pooling)?;+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(pool_start);++ let normalize_start = Instant::now();+ let pooled = if normalize {+ normalize_l2(&pooled)?+ } else {+ pooled+ };+ self.synchronize_for_timing()?;+ let normalize_ms = elapsed_ms(normalize_start);++ let conversion_start = Instant::now();+ let embeddings = pooled.to_dtype(DType::F32)?.to_vec2::<f32>()?;+ self.synchronize_for_timing()?;+ let conversion_ms = elapsed_ms(conversion_start);+ let inference_ms = inference_start.elapsed().as_secs_f64() * 1000.0;+ self.log_encode_diagnostics(+ "padded",+ source,+ token_stats,+ pooling,+ normalize,+ tokenization_ms,+ prepare_ms,+ CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms,+ conversion_ms,+ inference_ms,+ ..Default::default()+ },+ None,+ );++ Ok(CandleEncodeResult {+ embeddings,+ sparse_embeddings: None,+ multivectors: None,+ multivectors_f16: None,+ dim: self.dense_dim as u32,+ tokenization_ms,+ inference_ms,+ stages: CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms,+ conversion_ms,+ inference_ms,+ ..Default::default()+ },+ forward_profile: None,+ })+ }++ #[allow(clippy::too_many_arguments)]+ fn encode_multivector_tensors_intermediate(+ &self,+ token_ids: &Tensor,+ attention_mask: &Tensor,+ token_type_ids: &Tensor,+ normalize: bool,+ output_dtype: &str,+ tokenization_ms: f64,+ _token_stats: BatchTokenStats,+ _prepare_ms: f64,+ _source: &'static str,+ ) -> Result<CandleMultivectorEncodeIntermediate> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let sequence_output = self+ .model+ .forward(token_ids, attention_mask, token_type_ids)+ .context("run Candle multivector forward pass")?;+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let project_start = Instant::now();+ let projected = self.project_multivector_tokens(&sequence_output)?;+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(project_start);++ let normalize_start = Instant::now();+ let projected = if normalize {+ normalize_l2_last_dim(&projected)?+ } else {+ projected+ };+ self.synchronize_for_timing()?;+ let normalize_ms = elapsed_ms(normalize_start);++ Ok(CandleMultivectorEncodeIntermediate {+ projected,+ split: CandleMultivectorSplit::Masked {+ attention_mask: attention_mask.clone(),+ },+ output_dtype: output_dtype.to_string(),+ token_dim,+ tokenization_ms,+ inference_start,+ forward_ms,+ pool_ms,+ normalize_ms,+ sync_timings: self.diagnostics.sync_timings,+ forward_profile: None,+ })+ }++ fn encode_packed_multivector_intermediate(+ &self,+ packed: &PreparedPackedTensors,+ normalize: bool,+ output_dtype: &str,+ tokenization_ms: f64,+ _pack_ms: f64,+ _source: &'static str,+ ) -> Result<CandleMultivectorEncodeIntermediate> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let (sequence_output, forward_profile) = if self.diagnostics.enabled {+ match &self.model {+ CandleEmbeddingInner::ModernBert(model) => {+ let (output, profile) = model.forward_packed_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?;+ (output, Some(CandleForwardProfile::ModernBert(profile)))+ }+ CandleEmbeddingInner::XlmRoberta(model) => {+ let (output, profile) = model.forward_packed_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?;+ (output, Some(CandleForwardProfile::XlmRoberta(profile)))+ }+ CandleEmbeddingInner::GteRope(model) => {+ let (output, profile) = model.forward_packed_profiled(+ &packed.input_ids,+ &packed.token_type_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?;+ (output, Some(CandleForwardProfile::GteRope(profile)))+ }+ _ => (+ self.model+ .forward_packed(packed)+ .transpose()+ .context("run packed Candle multivector forward pass")?+ .context(+ "packed Candle forward selected for model without packed support",+ )?,+ None,+ ),+ }+ } else {+ (+ self.model+ .forward_packed(packed)+ .transpose()+ .context("run packed Candle multivector forward pass")?+ .context("packed Candle forward selected for model without packed support")?,+ None,+ )+ };+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let project_start = Instant::now();+ let projected = self.project_multivector_tokens_packed(&sequence_output)?;+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(project_start);++ let normalize_start = Instant::now();+ let projected = if normalize {+ normalize_l2(&projected)?+ } else {+ projected+ };+ self.synchronize_for_timing()?;+ let normalize_ms = elapsed_ms(normalize_start);++ Ok(CandleMultivectorEncodeIntermediate {+ projected,+ split: CandleMultivectorSplit::Packed {+ seq_lengths: packed.seq_lengths.clone(),+ },+ output_dtype: output_dtype.to_string(),+ token_dim,+ tokenization_ms,+ inference_start,+ forward_ms,+ pool_ms,+ normalize_ms,+ sync_timings: self.diagnostics.sync_timings,+ forward_profile,+ })+ }++ fn encode_packed(+ &self,+ packed: &PreparedPackedTensors,+ pooling: &str,+ normalize: bool,+ tokenization_ms: f64,+ pack_ms: f64,+ source: &'static str,+ ) -> Result<CandleEncodeResult> {+ let token_stats = BatchTokenStats::from_lengths(packed.seq_lengths.iter().copied());+ self.synchronize_for_timing()?;+ let inference_start = Instant::now();+ let forward_start = Instant::now();+ let (sequence_output, forward_profile, output_is_pooled) = if self.diagnostics.enabled {+ match &self.model {+ CandleEmbeddingInner::XlmRoberta(model) => {+ let (output, profile) = if pooling == "cls" {+ model.forward_packed_cls_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?+ } else {+ model.forward_packed_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?+ };+ (+ output,+ Some(CandleForwardProfile::XlmRoberta(profile)),+ pooling == "cls",+ )+ }+ CandleEmbeddingInner::GteRope(model) => {+ let (output, profile) = model.forward_packed_profiled(+ &packed.input_ids,+ &packed.token_type_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?;+ (output, Some(CandleForwardProfile::GteRope(profile)), false)+ }+ CandleEmbeddingInner::ModernBert(model) => {+ let (output, profile) = model.forward_packed_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ self.diagnostics.sync_timings,+ )?;+ (+ output,+ Some(CandleForwardProfile::ModernBert(profile)),+ false,+ )+ }+ _ => (+ self.model+ .forward_packed(packed)+ .transpose()+ .context("run packed Candle embedding forward pass")?+ .context(+ "packed Candle forward selected for model without packed support",+ )?,+ None,+ false,+ ),+ }+ } else {+ match &self.model {+ CandleEmbeddingInner::XlmRoberta(model) if pooling == "cls" => (+ model.forward_packed_cls(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )?,+ None,+ true,+ ),+ _ => (+ self.model+ .forward_packed(packed)+ .transpose()+ .context("run packed Candle embedding forward pass")?+ .context(+ "packed Candle forward selected for model without packed support",+ )?,+ None,+ false,+ ),+ }+ };+ self.synchronize_for_timing()?;+ let forward_ms = elapsed_ms(forward_start);++ let pool_start = Instant::now();+ let pooled = if output_is_pooled {+ sequence_output+ } else {+ pool_packed_embeddings(+ &sequence_output,+ &packed.seqlens,+ &packed.seq_lengths,+ pooling,+ )?+ };+ self.synchronize_for_timing()?;+ let pool_ms = elapsed_ms(pool_start);++ let normalize_start = Instant::now();+ let pooled = if normalize {+ normalize_l2(&pooled)?+ } else {+ pooled+ };+ self.synchronize_for_timing()?;+ let normalize_ms = elapsed_ms(normalize_start);++ let conversion_start = Instant::now();+ let embeddings = pooled.to_dtype(DType::F32)?.to_vec2::<f32>()?;+ self.synchronize_for_timing()?;+ let conversion_ms = elapsed_ms(conversion_start);+ let inference_ms = inference_start.elapsed().as_secs_f64() * 1000.0;+ self.log_encode_diagnostics(+ self.packed_path_name(),+ source,+ token_stats,+ pooling,+ normalize,+ tokenization_ms,+ pack_ms,+ CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms,+ conversion_ms,+ inference_ms,+ ..Default::default()+ },+ forward_profile,+ );++ Ok(CandleEncodeResult {+ embeddings,+ sparse_embeddings: None,+ multivectors: None,+ multivectors_f16: None,+ dim: self.dense_dim as u32,+ tokenization_ms,+ inference_ms,+ stages: CandleEncodeStageTimings {+ forward_ms,+ pool_ms,+ normalize_ms,+ conversion_ms,+ inference_ms,+ ..Default::default()+ },+ forward_profile: forward_profile.map(Box::new),+ })+ }++ fn should_use_packed_forward(&self) -> bool {+ if !self.device.is_cuda() {+ return false;+ }+ match &self.model {+ CandleEmbeddingInner::XlmRoberta(_) => matches!(self.dtype, DType::F16 | DType::BF16),+ CandleEmbeddingInner::GteRope(_) => matches!(self.dtype, DType::F16),+ CandleEmbeddingInner::ModernBert(_) => matches!(self.dtype, DType::F16 | DType::BF16),+ _ => false,+ }+ }++ fn should_use_packed_splade(&self) -> bool {+ self.packed_bert.is_some() && self.device.is_cuda() && self.dtype == DType::F16+ }++ fn packed_path_name(&self) -> &'static str {+ match &self.model {+ CandleEmbeddingInner::XlmRoberta(_) => "packed_xlm_roberta",+ CandleEmbeddingInner::GteRope(_) => "packed_gte_rope",+ CandleEmbeddingInner::ModernBert(_) => "packed_modernbert",+ _ => "packed",+ }+ }++ fn packed_position_id(&self, idx: usize) -> u32 {+ packed_position_id(self.packed_position_id_policy(), self.pad_id, idx)+ }++ fn packed_position_id_policy(&self) -> PackedPositionIdPolicy {+ match &self.model {+ CandleEmbeddingInner::XlmRoberta(_) => PackedPositionIdPolicy::PaddingOffset,+ _ => PackedPositionIdPolicy::ZeroBased,+ }+ }++ fn packed_token_type_ids_ignored(&self) -> bool {+ match &self.model {+ CandleEmbeddingInner::GteRope(model) => model.ignores_token_type_ids(),+ _ => false,+ }+ }++ fn prepared_token_stats(&self, requests: &[CandlePreparedEncodeRequest]) -> BatchTokenStats {+ self.prepared_token_stats_with_max(requests, self.max_seq_length)+ }++ fn prepared_token_stats_with_max(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ max_seq_length: usize,+ ) -> BatchTokenStats {+ BatchTokenStats::from_lengths(+ requests+ .iter()+ .map(|request| Self::prepared_effective_len(max_seq_length, request)),+ )+ }++ fn synchronize_for_timing(&self) -> Result<()> {+ if self.diagnostics.sync_timings {+ self.device.synchronize()?;+ }+ Ok(())+ }++ fn should_log_diagnostics(&self) -> bool {+ if !self.diagnostics.enabled {+ return false;+ }+ let batch = self.diagnostic_batches.fetch_add(1, Ordering::Relaxed) + 1;+ batch.is_multiple_of(self.diagnostics.every_n)+ }++ #[allow(clippy::too_many_arguments)]+ fn log_encode_diagnostics(+ &self,+ path: &'static str,+ source: &'static str,+ token_stats: BatchTokenStats,+ pooling: &str,+ normalize: bool,+ tokenization_ms: f64,+ prepare_ms: f64,+ timings: CandleEncodeStageTimings,+ forward_profile: Option<CandleForwardProfile>,+ ) {+ if !self.should_log_diagnostics() {+ return;+ }++ let cuda_compute_cap =+ std::env::var("CUDA_COMPUTE_CAP").unwrap_or_else(|_| "unset".to_string());+ let (xlm_profile, gte_profile, modernbert_profile) = match forward_profile {+ Some(CandleForwardProfile::XlmRoberta(profile)) => (+ profile,+ GteRopeForwardProfile::default(),+ ModernBertForwardProfile::default(),+ ),+ Some(CandleForwardProfile::GteRope(profile)) => (+ XlmRobertaForwardProfile::default(),+ profile,+ ModernBertForwardProfile::default(),+ ),+ Some(CandleForwardProfile::ModernBert(profile)) => (+ XlmRobertaForwardProfile::default(),+ GteRopeForwardProfile::default(),+ profile,+ ),+ None => (+ XlmRobertaForwardProfile::default(),+ GteRopeForwardProfile::default(),+ ModernBertForwardProfile::default(),+ ),+ };+ let (+ xlm_roberta_linear_backend,+ xlm_roberta_layernorm_backend,+ xlm_roberta_qkv_fused,+ xlm_roberta_ffn_activation_fused,+ ) = match &self.model {+ CandleEmbeddingInner::XlmRoberta(model) => model.kernel_backend(),+ _ => ("candle_transformers", "candle_transformers", false, false),+ };+ let (+ gte_rope_linear_backend,+ gte_rope_layernorm_backend,+ gte_rope_qkv_fused,+ gte_rope_rotary_inplace,+ gte_rope_ffn_activation_fused,+ ) = match &self.model {+ CandleEmbeddingInner::GteRope(model) => model.kernel_backend(),+ _ => (+ "candle_transformers",+ "candle_transformers",+ false,+ false,+ false,+ ),+ };+ let (modernbert_linear_backend, modernbert_layernorm_backend) = match &self.model {+ CandleEmbeddingInner::ModernBert(model) => model.kernel_backend(),+ _ => ("candle_transformers", "candle_transformers"),+ };+ let gemm_precision = candle_gemm_reduced_precision_state(&self.device);+ let xlm_roberta_attention_gflops = attention_gflops(+ token_stats.squared_tokens,+ xlm_profile.hidden_size,+ xlm_profile.layers,+ );+ let xlm_roberta_total_gflops = xlm_profile.linear_gflops + xlm_roberta_attention_gflops;+ let gte_rope_attention_gflops = attention_gflops(+ token_stats.squared_tokens,+ gte_profile.hidden_size,+ gte_profile.layers,+ );+ let gte_rope_total_gflops = gte_profile.linear_gflops + gte_rope_attention_gflops;+ let modernbert_attention_gflops = attention_gflops(+ token_stats.squared_tokens,+ modernbert_profile.hidden_size,+ modernbert_profile.layers,+ );+ let modernbert_total_gflops =+ modernbert_profile.linear_gflops + modernbert_attention_gflops;+ info!(+ model_id = %self.model_id,+ hf_id = %self.hf_id,+ architecture = self.architecture.name(),+ device = ?self.device,+ compute_dtype = ?self.dtype,+ dtype = ?self.dtype,+ cuda_compute_cap = %cuda_compute_cap,+ path,+ source,+ items = token_stats.items,+ total_tokens = token_stats.total_tokens,+ squared_tokens = token_stats.squared_tokens,+ avg_tokens = token_stats.avg_tokens(),+ min_tokens = token_stats.min_tokens,+ max_tokens = token_stats.max_tokens,+ max_seq_length = self.max_seq_length,+ pooling,+ normalize,+ sync_timings = self.diagnostics.sync_timings,+ gemm_reduced_precision_f32 = gemm_precision.f32,+ gemm_reduced_precision_f16 = gemm_precision.f16,+ gemm_reduced_precision_bf16 = gemm_precision.bf16,+ gemm_reduced_precision_applies_to_compute_dtype = gemm_precision.applies_to_dtype(self.dtype),+ tokenization_ms,+ prepare_ms,+ forward_ms = timings.forward_ms,+ pool_ms = timings.pool_ms,+ normalize_ms = timings.normalize_ms,+ conversion_ms = timings.conversion_ms,+ inference_ms = timings.inference_ms,+ xlm_roberta_embedding_ms = xlm_profile.embedding_ms,+ xlm_roberta_total_tokens = xlm_profile.total_tokens,+ xlm_roberta_max_seqlen = xlm_profile.max_seqlen,+ xlm_roberta_hidden_size = xlm_profile.hidden_size,+ xlm_roberta_intermediate_size = xlm_profile.intermediate_size,+ xlm_roberta_attention_heads = xlm_profile.attention_heads,+ xlm_roberta_attention_head_size = xlm_profile.attention_head_size,+ xlm_roberta_linear_gflops = xlm_profile.linear_gflops,+ xlm_roberta_attention_gflops,+ xlm_roberta_total_gflops,+ xlm_roberta_linear_tflops_s = tflops_per_second(xlm_profile.linear_gflops, timings.forward_ms),+ xlm_roberta_total_tflops_s = tflops_per_second(xlm_roberta_total_gflops, timings.forward_ms),+ xlm_roberta_attention_ms = xlm_profile.attention_ms,+ xlm_roberta_attention_qkv_ms = xlm_profile.attention_qkv_ms,+ xlm_roberta_attention_flash_ms = xlm_profile.attention_flash_ms,+ xlm_roberta_attention_output_dense_ms = xlm_profile.attention_output_dense_ms,+ xlm_roberta_attention_output_layernorm_ms = xlm_profile.attention_output_layernorm_ms,+ xlm_roberta_ffn_ms = xlm_profile.ffn_ms,+ xlm_roberta_ffn_intermediate_dense_ms = xlm_profile.ffn_intermediate_dense_ms,+ xlm_roberta_ffn_activation_ms = xlm_profile.ffn_activation_ms,+ xlm_roberta_ffn_output_dense_ms = xlm_profile.ffn_output_dense_ms,+ xlm_roberta_ffn_output_layernorm_ms = xlm_profile.ffn_output_layernorm_ms,+ xlm_roberta_layers = xlm_profile.layers,+ xlm_roberta_linear_backend,+ xlm_roberta_layernorm_backend,+ xlm_roberta_qkv_fused,+ xlm_roberta_ffn_activation_fused,+ gte_rope_embedding_ms = gte_profile.embedding_ms,+ gte_rope_select_ms = gte_profile.rope_select_ms,+ gte_rope_total_tokens = gte_profile.total_tokens,+ gte_rope_max_seqlen = gte_profile.max_seqlen,+ gte_rope_hidden_size = gte_profile.hidden_size,+ gte_rope_intermediate_size = gte_profile.intermediate_size,+ gte_rope_attention_heads = gte_profile.attention_heads,+ gte_rope_attention_head_size = gte_profile.attention_head_size,+ gte_rope_linear_gflops = gte_profile.linear_gflops,+ gte_rope_attention_gflops,+ gte_rope_total_gflops,+ gte_rope_linear_tflops_s = tflops_per_second(gte_profile.linear_gflops, timings.forward_ms),+ gte_rope_total_tflops_s = tflops_per_second(gte_rope_total_gflops, timings.forward_ms),+ gte_rope_attention_ms = gte_profile.attention_ms,+ gte_rope_attention_qkv_ms = gte_profile.attention_qkv_ms,+ gte_rope_attention_rotary_ms = gte_profile.attention_rotary_ms,+ gte_rope_attention_flash_ms = gte_profile.attention_flash_ms,+ gte_rope_attention_output_dense_ms = gte_profile.attention_output_dense_ms,+ gte_rope_attention_output_layernorm_ms = gte_profile.attention_output_layernorm_ms,+ gte_rope_ffn_ms = gte_profile.ffn_ms,+ gte_rope_ffn_up_gate_ms = gte_profile.ffn_up_gate_ms,+ gte_rope_ffn_activation_ms = gte_profile.ffn_activation_ms,+ gte_rope_ffn_down_ms = gte_profile.ffn_down_ms,+ gte_rope_ffn_output_layernorm_ms = gte_profile.ffn_output_layernorm_ms,+ gte_rope_layers = gte_profile.layers,+ gte_rope_linear_backend,+ gte_rope_layernorm_backend,+ gte_rope_qkv_fused,+ gte_rope_rotary_inplace,+ gte_rope_ffn_activation_fused,+ modernbert_embedding_ms = modernbert_profile.embedding_ms,+ modernbert_embedding_norm_ms = modernbert_profile.embedding_norm_ms,+ modernbert_rope_select_ms = modernbert_profile.rope_select_ms,+ modernbert_total_tokens = modernbert_profile.total_tokens,+ modernbert_max_seqlen = modernbert_profile.max_seqlen,+ modernbert_hidden_size = modernbert_profile.hidden_size,+ modernbert_intermediate_size = modernbert_profile.intermediate_size,+ modernbert_attention_heads = modernbert_profile.attention_heads,+ modernbert_attention_head_size = modernbert_profile.attention_head_size,+ modernbert_linear_gflops = modernbert_profile.linear_gflops,+ modernbert_attention_gflops,+ modernbert_total_gflops,+ modernbert_linear_tflops_s = tflops_per_second(modernbert_profile.linear_gflops, timings.forward_ms),+ modernbert_total_tflops_s = tflops_per_second(modernbert_total_gflops, timings.forward_ms),+ modernbert_attention_ms = modernbert_profile.attention_ms,+ modernbert_attention_norm_ms = modernbert_profile.attention_norm_ms,+ modernbert_attention_qkv_ms = modernbert_profile.attention_qkv_ms,+ modernbert_attention_rotary_ms = modernbert_profile.attention_rotary_ms,+ modernbert_attention_flash_ms = modernbert_profile.attention_flash_ms,+ modernbert_attention_output_dense_ms = modernbert_profile.attention_output_dense_ms,+ modernbert_mlp_ms = modernbert_profile.mlp_ms,+ modernbert_mlp_norm_ms = modernbert_profile.mlp_norm_ms,+ modernbert_mlp_wi_ms = modernbert_profile.mlp_wi_ms,+ modernbert_mlp_activation_ms = modernbert_profile.mlp_activation_ms,+ modernbert_mlp_wo_ms = modernbert_profile.mlp_wo_ms,+ modernbert_final_norm_ms = modernbert_profile.final_norm_ms,+ modernbert_layers = modernbert_profile.layers,+ modernbert_linear_backend,+ modernbert_layernorm_backend,+ "Candle embedding encode diagnostics"+ );+ }++ fn prepared_tensors(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ ) -> Result<(Tensor, Tensor, Tensor)> {+ self.prepared_tensors_with_max(requests, self.max_seq_length)+ }++ fn prepared_tensors_with_max(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ max_seq_length: usize,+ ) -> Result<(Tensor, Tensor, Tensor)> {+ let seq_len = requests+ .iter()+ .map(|request| request.input_ids.len().min(max_seq_length))+ .max()+ .unwrap_or(0);+ if seq_len == 0 {+ anyhow::bail!("prepared Candle tokens are empty");+ }++ let token_ids = requests+ .iter()+ .map(|request| {+ let len = request.input_ids.len().min(seq_len);+ let mut row = vec![self.pad_id; seq_len];+ row[..len].copy_from_slice(&request.input_ids[..len]);+ Tensor::new(row.as_slice(), &self.device)+ })+ .collect::<candle::Result<Vec<_>>>()?;+ let attention_mask = requests+ .iter()+ .map(|request| {+ let len = request.input_ids.len().min(seq_len);+ let mut row = vec![0u32; seq_len];+ match request.attention_mask.as_ref() {+ Some(mask) if mask.len() >= len => row[..len].copy_from_slice(&mask[..len]),+ Some(mask) => {+ candle::bail!(+ "prepared attention_mask length {} is shorter than input_ids length {}",+ mask.len(),+ len+ );+ }+ None => row[..len].fill(1),+ }+ Tensor::new(row.as_slice(), &self.device)+ })+ .collect::<candle::Result<Vec<_>>>()?;+ let token_type_ids = requests+ .iter()+ .map(|request| {+ let len = request.input_ids.len().min(seq_len);+ let mut row = vec![0u32; seq_len];+ if let Some(types) = request.token_type_ids.as_ref() {+ if types.len() < len {+ candle::bail!(+ "prepared token_type_ids length {} is shorter than input_ids length {}",+ types.len(),+ len+ );+ }+ row[..len].copy_from_slice(&types[..len]);+ }+ Tensor::new(row.as_slice(), &self.device)+ })+ .collect::<candle::Result<Vec<_>>>()?;++ Ok((+ Tensor::stack(&token_ids, 0)?,+ Tensor::stack(&attention_mask, 0)?,+ Tensor::stack(&token_type_ids, 0)?,+ ))+ }++ fn prepared_packed_tensors(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ ) -> Result<PreparedPackedTensors> {+ self.prepared_packed_tensors_with_max(requests, self.max_seq_length)+ }++ fn prepared_packed_tensors_with_max(+ &self,+ requests: &[CandlePreparedEncodeRequest],+ max_seq_length: usize,+ ) -> Result<PreparedPackedTensors> {+ let seq_lengths = requests+ .iter()+ .map(|request| Self::prepared_effective_len(max_seq_length, request))+ .collect::<Vec<_>>();+ if seq_lengths.contains(&0) {+ anyhow::bail!("prepared Candle tokens are empty");+ }++ let total_tokens = seq_lengths.iter().sum::<usize>();+ let max_seqlen = seq_lengths.iter().copied().max().unwrap_or(0);+ let mut input_ids = Vec::with_capacity(total_tokens);+ let mut token_type_ids = Vec::with_capacity(total_tokens);+ let mut position_ids = Vec::with_capacity(total_tokens);+ let mut seqlens = Vec::with_capacity(requests.len() + 1);+ let mut cursor = 0u32;+ seqlens.push(cursor);+ for (request, len) in requests.iter().zip(seq_lengths.iter().copied()) {+ Self::validate_prepared_attention_mask_len(max_seq_length, request)?;+ input_ids.extend_from_slice(&request.input_ids[..len]);+ Self::append_packed_token_type_ids(+ request,+ len,+ self.packed_token_type_ids_ignored(),+ &mut token_type_ids,+ )?;+ position_ids.extend((0..len).map(|idx| self.packed_position_id(idx)));+ cursor += len as u32;+ seqlens.push(cursor);+ }++ Ok(PreparedPackedTensors {+ input_ids: Tensor::new(input_ids.as_slice(), &self.device)?,+ token_type_ids: Tensor::new(token_type_ids.as_slice(), &self.device)?,+ position_ids: Tensor::new(position_ids.as_slice(), &self.device)?,+ seqlens: Tensor::new(seqlens.as_slice(), &self.device)?,+ seq_lengths,+ max_seqlen,+ })+ }++ fn validate_prepared_attention_mask_len(+ max_seq_length: usize,+ request: &CandlePreparedEncodeRequest,+ ) -> Result<()> {+ let input_len = request.input_ids.len().min(max_seq_length);+ if let Some(mask) = request.attention_mask.as_ref() {+ if mask.len() < input_len {+ anyhow::bail!(+ "prepared attention_mask length {} is shorter than input_ids length {}",+ mask.len(),+ input_len+ );+ }+ }+ Ok(())+ }++ fn append_packed_token_type_ids(+ request: &CandlePreparedEncodeRequest,+ len: usize,+ ignore_token_type_ids: bool,+ out: &mut Vec<u32>,+ ) -> Result<()> {+ if let Some(types) = request.token_type_ids.as_ref() {+ if types.len() < len {+ anyhow::bail!(+ "prepared token_type_ids length {} is shorter than packed input length {}",+ types.len(),+ len+ );+ }+ if ignore_token_type_ids {+ out.extend(std::iter::repeat_n(0, len));+ } else {+ out.extend_from_slice(&types[..len]);+ }+ } else {+ out.extend(std::iter::repeat_n(0, len));+ }+ Ok(())+ }++ fn project_multivector_flat(&self, sequence_output: &Tensor) -> Result<Tensor> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ let (_, hidden_size) = sequence_output.dims2()?;+ let mut projected = sequence_output.reshape(((), hidden_size))?;+ let chain = self.pylate_dense_chain.as_ref().with_context(|| {+ format!(+ "Candle multivector model {} has no supported PyLate Dense projection",+ self.model_id+ )+ })?;+ for weight in &chain.weights {+ projected = projected.matmul(&weight.t()?)?;+ }+ let (_, projected_dim) = projected.dims2()?;+ validate_multivector_projection_dim(&self.model_id, projected_dim, token_dim)?;+ if chain.output_dim != token_dim {+ anyhow::bail!(+ "Candle PyLate Dense chain for {} ended at dim {} but requested token_dim {}",+ self.model_id,+ chain.output_dim,+ token_dim+ );+ }+ Ok(projected)+ }++ fn project_multivector_tokens(&self, sequence_output: &Tensor) -> Result<Tensor> {+ let token_dim = self+ .multivector_dim+ .context("Candle multivector encode requested for model without multivector_dim")?;+ let (batch_size, seq_len, hidden_size) = sequence_output.dims3()?;+ let projected = self.project_multivector_flat(+ &sequence_output.reshape((batch_size * seq_len, hidden_size))?,+ )?;+ Ok(projected.reshape((batch_size, seq_len, token_dim))?)+ }++ fn project_multivector_tokens_packed(&self, sequence_output: &Tensor) -> Result<Tensor> {+ self.project_multivector_flat(sequence_output)+ }++ fn prepared_effective_len(+ max_seq_length: usize,+ request: &CandlePreparedEncodeRequest,+ ) -> usize {+ let mut len = request.input_ids.len().min(max_seq_length);+ if let Some(mask) = request.attention_mask.as_ref() {+ len = len.min(mask.len());+ while len > 0 && mask[len - 1] == 0 {+ len -= 1;+ }+ }+ len+ }++ /// FlashAttention represents padding solely through cumulative sequence+ /// lengths, so only a contiguous `1...10...0` mask can be packed without+ /// changing semantics. Arbitrary masks stay on the padded fallback.+ fn prepared_attention_masks_are_prefix(+ requests: &[CandlePreparedEncodeRequest],+ max_seq_length: usize,+ ) -> bool {+ requests.iter().all(|request| {+ let input_len = request.input_ids.len().min(max_seq_length);+ if input_len == 0 {+ return false;+ }+ let Some(mask) = request.attention_mask.as_ref() else {+ return true;+ };+ if mask.len() < input_len {+ return false;+ }+ let mut saw_padding = false;+ for value in &mask[..input_len] {+ match (*value, saw_padding) {+ (1, false) => {}+ (0, _) => saw_padding = true,+ _ => return false,+ }+ }+ !mask[..input_len].iter().all(|value| *value == 0)+ })+ }++ pub fn max_seq_length(&self) -> usize {+ self.max_seq_length+ }++ fn multivector_raw_max_seq_length(&self, is_query: bool) -> usize {+ multivector_raw_max_seq_length(self.max_seq_length, self.query_max_length, is_query)+ }++ pub fn tokenizer_path(&self) -> &Path {+ &self.tokenizer_path+ }++ pub fn tokenizer_id(&self) -> &str {+ &self.tokenizer_id+ }++ pub fn dtype(&self) -> DType {+ self.dtype+ }+}++fn validate_multivector_projection_dim(+ model_id: &str,+ projected_dim: usize,+ token_dim: usize,+) -> Result<()> {+ if projected_dim != token_dim {+ anyhow::bail!(+ "Candle multivector projection for {model_id} produced dim {projected_dim} but requested token_dim {token_dim}"+ );+ }+ Ok(())+}++fn tokenizer_for_max_seq_length(+ tokenizer: &Tokenizer,+ max_seq_length: usize,+ hf_id: &str,+) -> Result<Tokenizer> {+ let mut tokenizer = tokenizer.clone();+ tokenizer+ .with_truncation(Some(TruncationParams {+ max_length: max_seq_length.max(1),+ ..Default::default()+ }))+ .map_err(anyhow::Error::msg)+ .with_context(|| format!("configure tokenizer truncation for {hf_id}"))?;+ if let Some(existing) = tokenizer.get_padding_mut() {+ existing.strategy = PaddingStrategy::BatchLongest;+ } else {+ tokenizer.with_padding(Some(PaddingParams {+ strategy: PaddingStrategy::BatchLongest,+ ..Default::default()+ }));+ }+ Ok(tokenizer)+}++fn tokenizer_for_max_seq_length_without_padding(+ tokenizer: &Tokenizer,+ max_seq_length: usize,+ hf_id: &str,+) -> Result<Tokenizer> {+ let mut tokenizer = tokenizer.clone();+ tokenizer+ .with_truncation(Some(TruncationParams {+ max_length: max_seq_length.max(1),+ ..Default::default()+ }))+ .map_err(anyhow::Error::msg)+ .with_context(|| format!("configure tokenizer truncation for {hf_id}"))?;+ tokenizer.with_padding(None);+ Ok(tokenizer)+}++fn download_weight_file(+ repo: &hf_hub::api::sync::ApiRepo,+ hf_id: &str,+) -> Result<CandleWeightFile> {+ match repo.get("model.safetensors") {+ Ok(path) => Ok(CandleWeightFile::Safetensors(path)),+ Err(safetensors_error) => match repo.get("pytorch_model.bin") {+ Ok(path) => Ok(CandleWeightFile::Pytorch(path)),+ Err(pytorch_error) => anyhow::bail!(+ "download model.safetensors or pytorch_model.bin for {hf_id}: safetensors error: {safetensors_error}; pytorch error: {pytorch_error}"+ ),+ },+ }+}++fn hugging_face_api_from_env() -> Result<Api> {+ let mut builder = ApiBuilder::from_env();+ if let Some(token) = hugging_face_token_from_env_value(std::env::var("HF_TOKEN").ok()) {+ builder = builder.with_token(Some(token));+ }+ builder.build().context("create Hugging Face API client")+}++fn hugging_face_token_from_env_value(value: Option<String>) -> Option<String> {+ value.and_then(|token| {+ let token = token.trim();+ (!token.is_empty()).then(|| token.to_owned())+ })+}++#[cfg(test)]+fn hugging_face_cache_path_from_env() -> PathBuf {+ Cache::from_env().path().clone()+}++fn var_builder_from_weight_file(+ weights_file: CandleWeightFile,+ hf_id: &str,+ device: &Device,+ dtype: DType,+) -> Result<VarBuilder<'static>> {+ match weights_file {+ CandleWeightFile::Safetensors(path) => {+ // The safetensors file is downloaded into the HF cache and treated+ // as immutable while this process maps it.+ unsafe {+ VarBuilder::from_mmaped_safetensors(&[path], dtype, device)+ .with_context(|| format!("mmap safetensors for {hf_id}"))+ }+ }+ CandleWeightFile::Pytorch(path) => VarBuilder::from_pth(path, dtype, device)+ .with_context(|| format!("load PyTorch checkpoint for {hf_id}")),+ }+}++fn load_pylate_dense_chain(+ repo: &hf_hub::api::sync::ApiRepo,+ hf_id: &str,+ hidden_size: usize,+ token_dim: usize,+ device: &Device,+ dtype: DType,+) -> Result<PylateDenseChain> {+ if hidden_size == 0 || token_dim == 0 {+ anyhow::bail!(+ "Candle multivector model {hf_id} requires positive hidden_size and token_dim"+ );+ }+ let modules_path = match repo.get("modules.json") {+ Ok(path) => path,+ Err(error) => {+ anyhow::bail!(+ "Candle multivector model {hf_id} requires explicit supported PyLate projection metadata, but modules.json could not be loaded: {error}"+ );+ }+ };+ let raw_modules = fs::read_to_string(&modules_path)+ .with_context(|| format!("read {}", modules_path.display()))?;+ let mut modules: Vec<SentenceTransformersModule> = serde_json::from_str(&raw_modules)+ .with_context(|| format!("parse PyLate modules.json for {hf_id}"))?;+ let dense_modules = validate_pylate_modules(hf_id, &mut modules)?;+ if dense_modules.is_empty() {+ if hidden_size == token_dim {+ info!(+ hf_id,+ token_dim,+ "PyLate metadata declares no Dense modules; using exact-dimension identity projection"+ );+ return Ok(PylateDenseChain {+ weights: Vec::new(),+ output_dim: token_dim,+ });+ }+ anyhow::bail!(+ "PyLate modules.json for {hf_id} has no explicit Dense projection from hidden_size {hidden_size} to token_dim {token_dim}"+ );+ }++ let mut expected_in = hidden_size;+ let mut weights = Vec::with_capacity(dense_modules.len());+ for module in dense_modules {+ let config_rel = format!("{}/config.json", module.path);+ let config_path = repo+ .get(&config_rel)+ .with_context(|| format!("download PyLate Dense config {config_rel} for {hf_id}"))?;+ let raw_config = fs::read_to_string(&config_path)+ .with_context(|| format!("read {}", config_path.display()))?;+ let dense_config: PylateDenseConfig = serde_json::from_str(&raw_config)+ .with_context(|| format!("parse PyLate Dense config {config_rel} for {hf_id}"))?;+ validate_pylate_dense_config(hf_id, &module.path, &dense_config, expected_in)?;++ let safetensors_rel = format!("{}/model.safetensors", module.path);+ let pytorch_rel = format!("{}/pytorch_model.bin", module.path);+ let dense_vb = match repo.get(&safetensors_rel) {+ Ok(path) => unsafe {+ VarBuilder::from_mmaped_safetensors(&[path], dtype, device)+ .with_context(|| format!("mmap {safetensors_rel} for {hf_id}"))?+ },+ Err(safetensors_error) => match repo.get(&pytorch_rel) {+ Ok(path) => VarBuilder::from_pth(path, dtype, device)+ .with_context(|| format!("load {pytorch_rel} for {hf_id}"))?,+ Err(pytorch_error) => anyhow::bail!(+ "download PyLate Dense weights for {hf_id} at {}: safetensors error: {safetensors_error}; pytorch error: {pytorch_error}",+ module.path+ ),+ },+ };+ validate_pylate_dense_weights(hf_id, &module.path, &dense_vb)?;+ let weight = dense_vb+ .get(+ (dense_config.out_features, dense_config.in_features),+ "linear.weight",+ )+ .with_context(|| {+ format!(+ "load PyLate Dense linear.weight for {hf_id} at {}",+ module.path+ )+ })?;+ weights.push(weight);+ expected_in = dense_config.out_features;+ }++ if expected_in != token_dim {+ anyhow::bail!(+ "PyLate Dense chain for {hf_id} ended at dim {expected_in}, but requested token_dim is {token_dim}"+ );+ }++ info!(+ hf_id,+ token_dim,+ layers = weights.len(),+ "Loaded PyLate Dense chain for Candle multivector model"+ );+ Ok(PylateDenseChain {+ weights,+ output_dim: token_dim,+ })+}++fn validate_pylate_dense_config(+ hf_id: &str,+ path: &str,+ config: &PylateDenseConfig,+ expected_in: usize,+) -> Result<()> {+ if config.in_features == 0 || config.out_features == 0 {+ anyhow::bail!(+ "PyLate Dense config for {hf_id} at {path} requires positive in_features and out_features"+ );+ }+ if config.bias || config.use_residual {+ anyhow::bail!(+ "Unsupported PyLate Dense config for {hf_id} at {path}: bias={} use_residual={}; Candle supports only biasless, residualless projections",+ config.bias,+ config.use_residual+ );+ }+ if config.activation_function.rsplit('.').next() != Some("Identity") {+ anyhow::bail!(+ "Unsupported PyLate Dense activation {} for {hf_id} at {path}; Candle supports only Identity",+ config.activation_function+ );+ }+ if config.in_features != expected_in {+ anyhow::bail!(+ "PyLate Dense chain for {hf_id} is discontinuous at {path}: in_features={} expected={expected_in}",+ config.in_features+ );+ }+ Ok(())+}++fn validate_pylate_dense_weights(hf_id: &str, path: &str, vb: &VarBuilder<'_>) -> Result<()> {+ if vb.contains_tensor("linear.bias") {+ anyhow::bail!(+ "PyLate Dense weights for {hf_id} at {path} contain linear.bias although the supported projection is biasless"+ );+ }+ Ok(())+}++fn validate_pylate_modules<'a>(+ hf_id: &str,+ modules: &'a mut [SentenceTransformersModule],+) -> Result<Vec<&'a SentenceTransformersModule>> {+ if modules.is_empty() {+ anyhow::bail!("PyLate modules.json for {hf_id} is empty");+ }+ modules.sort_by_key(|module| module.idx);+ for (expected_idx, module) in modules.iter().enumerate() {+ if module.idx != expected_idx {+ anyhow::bail!(+ "PyLate modules.json for {hf_id} must have contiguous indices starting at zero; expected {expected_idx}, got {}",+ module.idx+ );+ }+ }++ let transformer = &modules[0];+ if transformer.module_type != "sentence_transformers.models.Transformer" {+ anyhow::bail!(+ "PyLate modules.json for {hf_id} must start with a Transformer, got {}",+ transformer.module_type+ );+ }+ if !transformer.path.is_empty() {+ anyhow::bail!(+ "PyLate Transformer for {hf_id} must use the repository root, got path {}",+ transformer.path+ );+ }++ let dense_modules = modules.iter().skip(1).collect::<Vec<_>>();+ for module in &dense_modules {+ if module.module_type != "pylate.models.Dense.Dense" {+ anyhow::bail!(+ "Unsupported PyLate module {} after Transformer for {hf_id}; Candle supports only biasless, residualless Identity Dense chains",+ module.module_type+ );+ }+ let path = Path::new(&module.path);+ if module.path.is_empty()+ || path.is_absolute()+ || path+ .components()+ .any(|component| !matches!(component, std::path::Component::Normal(_)))+ {+ anyhow::bail!(+ "PyLate Dense module path {:?} is not a safe repository-relative path for {hf_id}",+ module.path+ );+ }+ }+ Ok(dense_modules)+}++fn dtype_from_compute_precision(value: Option<&str>, device: &Device) -> Result<DType> {+ let dtype = match value+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_ascii_lowercase)+ .as_deref()+ {+ None | Some("auto") | Some("float32") | Some("fp32") | Some("f32") => DType::F32,+ Some("bfloat16") | Some("bf16") => DType::BF16,+ Some("float16") | Some("fp16") | Some("f16") | Some("half") => DType::F16,+ Some(other) => anyhow::bail!(+ "unsupported Candle compute_precision {other:?}; expected float32, float16, bfloat16, or auto"+ ),+ };++ if matches!(device, Device::Cpu) && matches!(dtype, DType::BF16 | DType::F16) {+ warn!(+ requested_dtype = ?dtype,+ "Candle CPU backend does not reliably support reduced precision; using F32"+ );+ return Ok(DType::F32);+ }++ Ok(dtype)+}++fn tokenizer_content_hash(tokenizer: &Tokenizer) -> Result<String> {+ let canonical = tokenizer+ .to_string(false)+ .map_err(anyhow::Error::msg)+ .context("serialize tokenizer for content hash")?;+ let digest = blake3::hash(canonical.as_bytes());+ Ok(digest.to_hex().as_str()[..32].to_string())+}++fn materialize_tokenizer(model_id: &str, source: &Path, tokenizer_id: &str) -> Result<PathBuf> {+ let Some(root) =+ std::env::var_os("SIE_TOKENIZER_STAGING_DIR").filter(|value| !value.is_empty())+ else {+ return Ok(source.to_path_buf());+ };+ let root = PathBuf::from(root);+ fs::create_dir_all(&root)+ .with_context(|| format!("create tokenizer staging dir {}", root.display()))?;+ let filename = format!("{}-{tokenizer_id}.json", safe_filename(model_id));+ let staged = root.join(filename);+ if !staged.is_file() {+ fs::copy(source, &staged).with_context(|| {+ format!(+ "copy tokenizer {} to staged path {}",+ source.display(),+ staged.display()+ )+ })?;+ }+ Ok(staged)+}++fn safe_filename(value: &str) -> String {+ value+ .chars()+ .map(|ch| {+ if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.') {+ ch+ } else {+ '_'+ }+ })+ .collect()+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum CandleDeviceSpec {+ Cpu,+ Cuda(usize),+ Metal(usize),+}++fn parse_candle_device_spec(raw: &str) -> Result<Option<CandleDeviceSpec>> {+ let value = raw.trim();+ if value.is_empty() {+ return Ok(None);+ }+ let (family, index) = value+ .split_once(':')+ .map_or((value, None), |(family, index)| (family, Some(index)));+ let index = index+ .map(|raw_index| {+ raw_index+ .parse::<usize>()+ .with_context(|| format!("invalid device index in {value:?}"))+ })+ .transpose()?+ .unwrap_or(0);+ match family.to_ascii_lowercase().as_str() {+ "cpu" => Ok(Some(CandleDeviceSpec::Cpu)),+ "cuda" => Ok(Some(CandleDeviceSpec::Cuda(index))),+ "metal" | "mps" => Ok(Some(CandleDeviceSpec::Metal(index))),+ other => anyhow::bail!("unsupported SIE device family {other:?} in {value:?}"),+ }+}++fn configured_candle_device_spec() -> Result<Option<CandleDeviceSpec>> {+ if let Ok(devices) = std::env::var("SIE_DEVICES") {+ if let Some(first) = devices+ .split(',')+ .map(str::trim)+ .find(|item| !item.is_empty())+ {+ return parse_candle_device_spec(first);+ }+ }+ if let Ok(device) = std::env::var("SIE_DEVICE") {+ return parse_candle_device_spec(&device);+ }+ Ok(None)+}++fn device_from_spec(spec: CandleDeviceSpec) -> Result<Device> {+ match spec {+ CandleDeviceSpec::Cpu => Ok(Device::Cpu),+ CandleDeviceSpec::Cuda(index) => Ok(Device::new_cuda(index)?),+ CandleDeviceSpec::Metal(index) => Ok(Device::new_metal(index)?),+ }+}++fn candle_device() -> Result<Device> {+ if let Some(spec) = configured_candle_device_spec()? {+ return device_from_spec(spec);+ }+ if candle::utils::cuda_is_available() {+ Ok(Device::new_cuda(0)?)+ } else if candle::utils::metal_is_available() {+ Ok(Device::new_metal(0)?)+ } else {+ Ok(Device::Cpu)+ }+}++fn pool_embeddings(+ sequence_output: &Tensor,+ attention_mask: &Tensor,+ pooling: &str,+) -> Result<Tensor> {+ match pooling {+ "cls" => {+ let (batch_size, _seq_len, hidden_size) = sequence_output.dims3()?;+ Ok(sequence_output+ .narrow(1, 0, 1)?+ .reshape((batch_size, hidden_size))?)+ }+ "mean" => {+ let attention_mask = attention_mask+ .to_dtype(sequence_output.dtype())?+ .unsqueeze(2)?;+ let sum_mask = attention_mask.sum(1)?;+ let embeddings = sequence_output+ .broadcast_mul(&attention_mask)?+ .sum(1)?+ .broadcast_div(&sum_mask)?;+ Ok(embeddings)+ }+ _ => anyhow::bail!("unsupported Candle pooling strategy {pooling:?}; expected mean or cls"),+ }+}++fn pool_packed_embeddings(+ sequence_output: &Tensor,+ seqlens: &Tensor,+ seq_lengths: &[usize],+ pooling: &str,+) -> Result<Tensor> {+ if pooling == "cls" {+ let indices = seqlens.narrow(0, 0, seq_lengths.len())?;+ return Ok(candle_layers::index_select(sequence_output, &indices, 0)?);+ }++ let mut cursor = 0usize;+ let mut rows = Vec::with_capacity(seq_lengths.len());+ for len in seq_lengths {+ match pooling {+ "mean" => {+ let sum = sequence_output.narrow(0, cursor, *len)?.sum(0)?;+ rows.push((&sum / *len as f64)?);+ }+ _ => anyhow::bail!(+ "unsupported Candle pooling strategy {pooling:?}; expected mean or cls"+ ),+ }+ cursor += *len;+ }+ Ok(Tensor::stack(&rows, 0)?)+}++fn normalize_l2(v: &Tensor) -> Result<Tensor> {+ Ok(v.broadcast_div(&v.sqr()?.sum_keepdim(1)?.sqrt()?)?)+}++fn normalize_l2_last_dim(v: &Tensor) -> Result<Tensor> {+ Ok(v.broadcast_div(&v.sqr()?.sum_keepdim(2)?.sqrt()?)?)+}++/// Split documents into stable contiguous chunks bounded by token work. A+/// single long document is never truncated to satisfy the budget; it occupies+/// a chunk by itself and remains governed by the model's sequence cap.+fn score_document_chunks(doc_tokens: &[usize], work_budget: usize) -> Vec<Range<usize>> {+ let work_budget = work_budget.max(1);+ let mut chunks = Vec::new();+ let mut start = 0usize;+ let mut work = 0usize;+ for (index, tokens) in doc_tokens.iter().copied().enumerate() {+ if index > start && work.saturating_add(tokens) > work_budget {+ chunks.push(start..index);+ start = index;+ work = 0;+ }+ work = work.saturating_add(tokens);+ }+ if start < doc_tokens.len() {+ chunks.push(start..doc_tokens.len());+ }+ chunks+}++/// ColBERT late-interaction MaxSim in f32. Both query and documents stay on+/// their source device; only the stacked scalar scores are read back.+fn maxsim_scores_device(query: &Tensor, docs: &[Tensor]) -> Result<Vec<f32>> {+ if docs.is_empty() {+ return Ok(Vec::new());+ }+ let (query_tokens, query_dim) = query.dims2()?;+ if query_tokens == 0 {+ return Ok(vec![0.0; docs.len()]);+ }+ let query = query.to_dtype(DType::F32)?;+ let mut scores = Vec::with_capacity(docs.len());+ for doc in docs {+ let (doc_tokens, doc_dim) = doc.dims2()?;+ if doc_dim != query_dim {+ anyhow::bail!("MaxSim dimension mismatch: query={query_dim} document={doc_dim}");+ }+ if doc_tokens == 0 {+ scores.push(Tensor::new(f32::NEG_INFINITY, query.device())?);+ continue;+ }+ let doc = doc.to_dtype(DType::F32)?;+ let score = query.matmul(&doc.t()?)?.max(1)?.sum_all()?;+ scores.push(score);+ }+ Ok(Tensor::stack(&scores, 0)?.to_vec1::<f32>()?)+}++fn multivector_raw_max_seq_length(+ max_seq_length: usize,+ query_max_length: Option<usize>,+ is_query: bool,+) -> usize {+ if is_query {+ query_max_length.unwrap_or(max_seq_length)+ } else {+ max_seq_length+ }+}++fn packed_position_id(policy: PackedPositionIdPolicy, pad_id: u32, idx: usize) -> u32 {+ match policy {+ PackedPositionIdPolicy::ZeroBased => idx as u32,+ PackedPositionIdPolicy::PaddingOffset => pad_id + 1 + idx as u32,+ }+}++fn split_multivectors(+ projected: &Tensor,+ attention_mask: &Tensor,+ token_dim: usize,+) -> Result<Vec<CandleMultivectorEmbedding>> {+ let projected = projected.to_dtype(DType::F32)?.to_vec3::<f32>()?;+ let attention_mask = attention_mask.to_vec2::<u32>()?;+ let mut outputs = Vec::with_capacity(projected.len());+ for (rows, mask) in projected.into_iter().zip(attention_mask) {+ let mut values = Vec::with_capacity(rows.len() * token_dim);+ for (row, keep) in rows.into_iter().zip(mask) {+ if keep != 0 {+ values.extend_from_slice(&row);+ }+ }+ let num_tokens = values.len() / token_dim;+ outputs.push(CandleMultivectorEmbedding {+ values,+ values_f16: Vec::new(),+ num_tokens: num_tokens as u32,+ token_dims: token_dim as u32,+ });+ }+ Ok(outputs)+}++fn split_multivectors_f16(+ projected: &Tensor,+ attention_mask: &Tensor,+ token_dim: usize,+) -> Result<(CandleF16MultivectorBatch, F16MultivectorConversionTimings)> {+ if token_dim == 0 {+ anyhow::bail!("multivector token_dim must be positive");+ }+ let shape = projected.dims();+ let [batch_size, sequence_length, projected_dim] = shape else {+ anyhow::bail!("expected rank-3 masked multivector projection, got shape {shape:?}");+ };+ if *projected_dim != token_dim {+ anyhow::bail!(+ "multivector projected dim {projected_dim} does not match token_dim {token_dim}"+ );+ }++ let tensor_readback_start = Instant::now();+ let projected = projected+ .to_dtype(DType::F16)?+ .flatten_all()?+ .to_vec1::<f16>()?;+ let attention_mask = attention_mask.flatten_all()?.to_vec1::<u32>()?;+ let tensor_readback_ms = elapsed_ms(tensor_readback_start);+ let expected_mask_values = batch_size+ .checked_mul(*sequence_length)+ .context("masked multivector attention-mask size overflow")?;+ let expected_projected_values = expected_mask_values+ .checked_mul(token_dim)+ .context("masked multivector projection size overflow")?;+ if attention_mask.len() != expected_mask_values || projected.len() != expected_projected_values+ {+ anyhow::bail!(+ "masked multivector tensors do not match expected shape [{batch_size}, {sequence_length}, {token_dim}]"+ );+ }++ let host_pack_start = Instant::now();+ let mut values_f16 = Vec::with_capacity(projected.len());+ let mut items = Vec::with_capacity(*batch_size);+ for batch_idx in 0..*batch_size {+ let row_start = batch_idx * *sequence_length;+ let rows = &attention_mask[row_start..row_start + *sequence_length];+ let value_offset = values_f16.len();+ for (row_idx, keep) in rows.iter().enumerate() {+ if *keep != 0 {+ let value_start = (row_start + row_idx) * token_dim;+ let value_end = value_start + token_dim;+ let row = &projected[value_start..value_end];+ if row.len() != token_dim {+ anyhow::bail!(+ "multivector row dim {} does not match token_dim {}",+ row.len(),+ token_dim+ );+ }+ values_f16.extend_from_slice(row);+ }+ }+ let value_len = values_f16+ .len()+ .checked_sub(value_offset)+ .context("masked f16 multivector value range underflow")?;+ let byte_offset = value_offset+ .checked_mul(size_of::<f16>())+ .context("masked f16 multivector byte offset overflow")?;+ let byte_len = value_len+ .checked_mul(size_of::<f16>())+ .context("masked f16 multivector byte length overflow")?;+ let num_tokens = value_len / token_dim;+ items.push(CandleF16MultivectorItem {+ byte_offset,+ byte_len,+ num_tokens: num_tokens as u32,+ token_dims: token_dim as u32,+ });+ }+ Ok((+ CandleF16MultivectorBatch { values_f16, items },+ F16MultivectorConversionTimings {+ tensor_readback_ms,+ host_pack_ms: elapsed_ms(host_pack_start),+ },+ ))+}++fn split_packed_multivectors(+ projected: &Tensor,+ seq_lengths: &[usize],+ token_dim: usize,+) -> Result<Vec<CandleMultivectorEmbedding>> {+ let projected = projected.to_dtype(DType::F32)?.to_vec2::<f32>()?;+ let mut outputs = Vec::with_capacity(seq_lengths.len());+ let mut cursor = 0usize;+ for len in seq_lengths {+ let end = cursor + *len;+ if end > projected.len() {+ anyhow::bail!(+ "packed multivector split exceeded projected rows: end={} rows={}",+ end,+ projected.len()+ );+ }+ let mut values = Vec::with_capacity(*len * token_dim);+ for row in &projected[cursor..end] {+ if row.len() != token_dim {+ anyhow::bail!(+ "packed multivector row dim {} does not match token_dim {}",+ row.len(),+ token_dim+ );+ }+ values.extend_from_slice(row);+ }+ outputs.push(CandleMultivectorEmbedding {+ values,+ values_f16: Vec::new(),+ num_tokens: *len as u32,+ token_dims: token_dim as u32,+ });+ cursor = end;+ }+ if cursor != projected.len() {+ anyhow::bail!(+ "packed multivector split consumed {} rows but projected has {} rows",+ cursor,+ projected.len()+ );+ }+ Ok(outputs)+}++fn split_packed_multivectors_f16(+ projected: &Tensor,+ seq_lengths: &[usize],+ token_dim: usize,+) -> Result<(CandleF16MultivectorBatch, F16MultivectorConversionTimings)> {+ if token_dim == 0 {+ anyhow::bail!("multivector token_dim must be positive");+ }+ let tensor_readback_start = Instant::now();+ let projected = projected+ .to_dtype(DType::F16)?+ .flatten_all()?+ .to_vec1::<f16>()?;+ let tensor_readback_ms = elapsed_ms(tensor_readback_start);+ let host_pack_start = Instant::now();+ let mut items = Vec::with_capacity(seq_lengths.len());+ let mut cursor = 0usize;+ for len in seq_lengths {+ let values_len = len+ .checked_mul(token_dim)+ .context("packed multivector f16 size overflow")?;+ let end = cursor+ .checked_add(values_len)+ .context("packed multivector f16 cursor overflow")?;+ if end > projected.len() {+ anyhow::bail!(+ "packed multivector split exceeded projected values: end={} values={}",+ end,+ projected.len()+ );+ }+ let byte_offset = cursor+ .checked_mul(size_of::<f16>())+ .context("packed multivector f16 byte offset overflow")?;+ let byte_len = values_len+ .checked_mul(size_of::<f16>())+ .context("packed multivector f16 byte length overflow")?;+ items.push(CandleF16MultivectorItem {+ byte_offset,+ byte_len,+ num_tokens: *len as u32,+ token_dims: token_dim as u32,+ });+ cursor = end;+ }+ if cursor != projected.len() {+ anyhow::bail!(+ "packed multivector split consumed {} rows but projected has {} rows",+ cursor,+ projected.len()+ );+ }+ Ok((+ CandleF16MultivectorBatch {+ values_f16: projected,+ items,+ },+ F16MultivectorConversionTimings {+ tensor_readback_ms,+ host_pack_ms: elapsed_ms(host_pack_start),+ },+ ))+}++fn extend_f16_le_bytes(out: &mut Vec<u8>, values: &[f16]) {+ #[cfg(target_endian = "little")]+ {+ // SAFETY: f16 is repr(transparent) over u16, and a u8 view has no alignment requirement.+ // On little-endian targets its native representation is the required wire format.+ let bytes = unsafe {+ std::slice::from_raw_parts(values.as_ptr().cast::<u8>(), std::mem::size_of_val(values))+ };+ out.extend_from_slice(bytes);+ }+ #[cfg(target_endian = "big")]+ for value in values {+ out.extend_from_slice(&value.to_bits().to_le_bytes());+ }+}++fn f16_values_to_le_bytes(values: &[f16]) -> Vec<u8> {+ let mut bytes = Vec::with_capacity(std::mem::size_of_val(values));+ extend_f16_le_bytes(&mut bytes, values);+ bytes+}++fn elapsed_ms(start: Instant) -> f64 {+ start.elapsed().as_secs_f64() * 1000.0+}++fn env_bool_any(names: &[&str], default: bool) -> bool {+ for name in names {+ if let Ok(value) = std::env::var(name) {+ return env_bool_value(&value, default);+ }+ }+ default+}++fn env_bool_value(raw: &str, default: bool) -> bool {+ let trimmed = raw.trim().to_ascii_lowercase();+ if trimmed.is_empty() {+ return default;+ }+ !matches!(trimmed.as_str(), "0" | "false" | "no" | "off")+}++fn env_u64(name: &str, default: u64) -> u64 {+ std::env::var(name)+ .ok()+ .and_then(|value| value.trim().parse::<u64>().ok())+ .unwrap_or(default)+}++fn candle_gemm_reduced_precision_state(device: &Device) -> CandleGemmPrecisionConfig {+ if !device.is_cuda() {+ return CandleGemmPrecisionConfig {+ f32: false,+ f16: false,+ bf16: false,+ };+ }++ CandleGemmPrecisionConfig {+ f32: candle::cuda::gemm_reduced_precision_f32(),+ f16: candle::cuda::gemm_reduced_precision_f16(),+ bf16: candle::cuda::gemm_reduced_precision_bf16(),+ }+}++#[cfg(test)]+mod tests {+ use std::ffi::OsString;+ use std::sync::{Mutex, MutexGuard};++ use super::*;++ static ENV_LOCK: Mutex<()> = Mutex::new(());++ fn env_lock() -> MutexGuard<'static, ()> {+ ENV_LOCK.lock().expect("env lock poisoned")+ }++ struct EnvVarGuard {+ key: &'static str,+ original: Option<OsString>,+ }++ impl EnvVarGuard {+ fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {+ let original = std::env::var_os(key);+ std::env::set_var(key, value);+ Self { key, original }+ }++ fn unset(key: &'static str) -> Self {+ let original = std::env::var_os(key);+ std::env::remove_var(key);+ Self { key, original }+ }+ }++ impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ match &self.original {+ Some(value) => std::env::set_var(self.key, value),+ None => std::env::remove_var(self.key),+ }+ }+ }++ #[test]+ fn hf_home_configures_hugging_face_cache_path() {+ let _env_lock = env_lock();+ let tempdir = tempfile::tempdir().unwrap();+ let _guard = EnvVarGuard::set("HF_HOME", tempdir.path());++ assert_eq!(+ hugging_face_cache_path_from_env(),+ tempdir.path().join("hub")+ );+ }++ #[test]+ fn parses_configured_candle_device_specs() {+ assert_eq!(+ parse_candle_device_spec("cuda:2").unwrap(),+ Some(CandleDeviceSpec::Cuda(2))+ );+ assert_eq!(+ parse_candle_device_spec("mps").unwrap(),+ Some(CandleDeviceSpec::Metal(0))+ );+ assert_eq!(+ parse_candle_device_spec("cpu").unwrap(),+ Some(CandleDeviceSpec::Cpu)+ );+ assert!(parse_candle_device_spec("cuda:nope").is_err());+ }++ #[test]+ fn sie_devices_overrides_scalar_device_for_candle() {+ let _env_lock = env_lock();+ let _devices = EnvVarGuard::set("SIE_DEVICES", " cuda:1, cuda:2 ");+ let _device = EnvVarGuard::set("SIE_DEVICE", "cpu");++ assert_eq!(+ configured_candle_device_spec().unwrap(),+ Some(CandleDeviceSpec::Cuda(1))+ );+ }++ #[test]+ fn scalar_device_is_used_when_sie_devices_is_empty() {+ let _env_lock = env_lock();+ let _devices = EnvVarGuard::set("SIE_DEVICES", " , ");+ let _device = EnvVarGuard::set("SIE_DEVICE", "mps:3");++ assert_eq!(+ configured_candle_device_spec().unwrap(),+ Some(CandleDeviceSpec::Metal(3))+ );+ }++ #[test]+ fn missing_device_env_leaves_candle_auto_detect_enabled() {+ let _env_lock = env_lock();+ let _devices = EnvVarGuard::unset("SIE_DEVICES");+ let _device = EnvVarGuard::unset("SIE_DEVICE");++ assert_eq!(configured_candle_device_spec().unwrap(), None);+ }++ #[test]+ fn parses_modernbert_transformers5_rope_parameters() {+ let config = parse_modernbert_config(+ r#"{+ "vocab_size": 50370,+ "hidden_size": 768,+ "num_hidden_layers": 22,+ "num_attention_heads": 12,+ "intermediate_size": 1152,+ "max_position_embeddings": 8192,+ "layer_norm_eps": 1e-5,+ "pad_token_id": 50283,+ "global_attn_every_n_layers": 3,+ "local_attention": 128,+ "rope_parameters": {+ "full_attention": {"rope_theta": 160000.0},+ "sliding_attention": {"rope_theta": 10000.0}+ }+ }"#,+ )+ .unwrap();++ assert_eq!(config.global_rope_theta, 160000.0);+ assert_eq!(config.local_rope_theta, 10000.0);+ }++ #[test]+ fn modernbert_var_builder_preserves_prefixed_checkpoint_layout() {+ let tensors = std::collections::HashMap::from([(+ "model.embeddings.tok_embeddings.weight".to_string(),+ Tensor::zeros((2, 3), DType::F32, &Device::Cpu).unwrap(),+ )]);+ let vb = VarBuilder::from_tensors(tensors, DType::F32, &Device::Cpu);+ let vb = modernbert_var_builder(vb);++ assert!(vb.contains_tensor("model.embeddings.tok_embeddings.weight"));+ assert!(!vb.contains_tensor("embeddings.tok_embeddings.weight"));+ }++ #[test]+ fn modernbert_var_builder_accepts_unprefixed_checkpoint_layout() {+ let tensors = std::collections::HashMap::from([(+ "embeddings.tok_embeddings.weight".to_string(),+ Tensor::zeros((2, 3), DType::F32, &Device::Cpu).unwrap(),+ )]);+ let vb = VarBuilder::from_tensors(tensors, DType::F32, &Device::Cpu);+ let vb = modernbert_var_builder(vb);++ assert!(vb.contains_tensor("model.embeddings.tok_embeddings.weight"));+ assert!(vb.contains_tensor("embeddings.tok_embeddings.weight"));+ }++ #[test]+ fn selects_supported_architectures_from_model_type() {+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&ModelTypeProbe {+ model_type: None,+ architectures: Vec::new(),+ position_embedding_type: None,+ feed_forward_type: None,+ })+ .unwrap(),+ CandleEmbeddingArchitecture::Bert+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("bert")).unwrap(),+ CandleEmbeddingArchitecture::Bert+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("jina-bert")).unwrap(),+ CandleEmbeddingArchitecture::JinaBert+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("xlm-roberta")).unwrap(),+ CandleEmbeddingArchitecture::XlmRoberta+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_rope_model_type("new")).unwrap(),+ CandleEmbeddingArchitecture::GteRope+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_rope_model_type("gte")).unwrap(),+ CandleEmbeddingArchitecture::GteRope+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("modernbert")).unwrap(),+ CandleEmbeddingArchitecture::ModernBert+ );+ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("nomic_bert")).unwrap(),+ CandleEmbeddingArchitecture::NomicBert+ );+ }++ #[test]+ fn selects_jina_bert_when_model_type_is_bert_but_architecture_is_jina() {+ let probe = ModelTypeProbe {+ model_type: Some("bert".to_string()),+ architectures: vec!["JinaBertForMaskedLM".to_string()],+ position_embedding_type: Some("alibi".to_string()),+ feed_forward_type: Some("geglu".to_string()),+ };++ assert_eq!(+ CandleEmbeddingArchitecture::from_probe(&probe).unwrap(),+ CandleEmbeddingArchitecture::JinaBert+ );+ }++ #[test]+ fn batch_token_stats_counts_each_sequence_once() {+ let stats = BatchTokenStats::from_lengths([2usize, 3, 5]);++ assert_eq!(stats.items, 3);+ assert_eq!(stats.total_tokens, 10);+ assert_eq!(stats.squared_tokens, 38);+ assert_eq!(stats.min_tokens, 2);+ assert_eq!(stats.max_tokens, 5);+ }++ #[test]+ fn multivector_raw_max_seq_length_uses_query_cap_only_for_queries() {+ assert_eq!(multivector_raw_max_seq_length(8192, Some(32), true), 32);+ assert_eq!(multivector_raw_max_seq_length(8192, Some(32), false), 8192);+ assert_eq!(multivector_raw_max_seq_length(8192, None, true), 8192);+ }++ #[test]+ fn score_document_chunks_respect_budget_without_truncating_long_docs() {+ assert_eq!(+ score_document_chunks(&[4, 5, 20, 3], 10),+ vec![0..2, 2..3, 3..4]+ );+ assert_eq!(score_document_chunks(&[20], 10), vec![0..1]);+ assert_eq!(score_document_chunks(&[512, 512], 16384), vec![0..2]);+ assert!(score_document_chunks(&[], 10).is_empty());+ }++ #[test]+ fn maxsim_scores_device_accumulates_in_f32_and_handles_empty_docs() -> Result<()> {+ let query =+ Tensor::new(&[[1.0f32, 0.0], [0.0, 1.0]], &Device::Cpu)?.to_dtype(DType::F16)?;+ let exact =+ Tensor::new(&[[1.0f32, 0.0], [0.0, 1.0]], &Device::Cpu)?.to_dtype(DType::F16)?;+ let opposite =+ Tensor::new(&[[-1.0f32, 0.0], [0.0, -1.0]], &Device::Cpu)?.to_dtype(DType::F16)?;+ let empty = Tensor::zeros((0, 2), DType::F16, &Device::Cpu)?;++ let scores = maxsim_scores_device(&query, &[exact, opposite, empty])?;++ assert_eq!(scores.len(), 3);+ assert!((scores[0] - 2.0).abs() < 1e-6);+ assert!(scores[1].abs() < 1e-6);+ assert_eq!(scores[2], f32::NEG_INFINITY);+ Ok(())+ }++ #[test]+ fn maxsim_scores_device_empty_query_is_zero_per_document() -> Result<()> {+ let query = Tensor::zeros((0, 2), DType::F32, &Device::Cpu)?;+ let doc = Tensor::new(&[[1.0f32, 0.0]], &Device::Cpu)?;+ assert_eq!(maxsim_scores_device(&query, &[doc])?, vec![0.0]);+ Ok(())+ }++ #[test]+ fn multivector_projection_dimension_must_match_without_truncation() {+ validate_multivector_projection_dim("test/model", 128, 128).unwrap();+ let error = validate_multivector_projection_dim("test/model", 768, 128).unwrap_err();+ assert!(error.to_string().contains("produced dim 768"));+ }++ #[test]+ fn pylate_modules_require_root_transformer_and_contiguous_dense_chain() {+ let mut valid = vec![+ SentenceTransformersModule {+ idx: 1,+ path: "1_Dense".to_string(),+ module_type: "pylate.models.Dense.Dense".to_string(),+ },+ SentenceTransformersModule {+ idx: 0,+ path: String::new(),+ module_type: "sentence_transformers.models.Transformer".to_string(),+ },+ ];+ let dense = validate_pylate_modules("test/model", &mut valid).unwrap();+ assert_eq!(dense.len(), 1);+ assert_eq!(dense[0].path, "1_Dense");++ let mut non_root = vec![SentenceTransformersModule {+ idx: 0,+ path: "0_Transformer".to_string(),+ module_type: "sentence_transformers.models.Transformer".to_string(),+ }];+ assert!(validate_pylate_modules("test/model", &mut non_root)+ .unwrap_err()+ .to_string()+ .contains("repository root"));++ let mut non_contiguous = vec![+ SentenceTransformersModule {+ idx: 0,+ path: String::new(),+ module_type: "sentence_transformers.models.Transformer".to_string(),+ },+ SentenceTransformersModule {+ idx: 2,+ path: "2_Dense".to_string(),+ module_type: "pylate.models.Dense.Dense".to_string(),+ },+ ];+ assert!(validate_pylate_modules("test/model", &mut non_contiguous)+ .unwrap_err()+ .to_string()+ .contains("contiguous indices"));+ }++ #[test]+ fn pylate_modules_reject_unsafe_dense_paths() {+ for path in ["", "../Dense", "/tmp/Dense", "nested/../Dense"] {+ let mut modules = vec![+ SentenceTransformersModule {+ idx: 0,+ path: String::new(),+ module_type: "sentence_transformers.models.Transformer".to_string(),+ },+ SentenceTransformersModule {+ idx: 1,+ path: path.to_string(),+ module_type: "pylate.models.Dense.Dense".to_string(),+ },+ ];+ assert!(validate_pylate_modules("test/model", &mut modules).is_err());+ }+ }++ #[test]+ fn pylate_dense_config_is_explicit_biasless_identity_projection() {+ let valid = PylateDenseConfig {+ in_features: 768,+ out_features: 128,+ bias: false,+ use_residual: false,+ activation_function: "torch.nn.modules.linear.Identity".to_string(),+ };+ validate_pylate_dense_config("test/model", "1_Dense", &valid, 768).unwrap();++ for (invalid, expected) in [+ (+ {+ let mut config = valid.clone();+ config.in_features = 0;+ config+ },+ "positive",+ ),+ (+ {+ let mut config = valid.clone();+ config.out_features = 0;+ config+ },+ "positive",+ ),+ (+ {+ let mut config = valid.clone();+ config.bias = true;+ config+ },+ "bias=true",+ ),+ (+ {+ let mut config = valid.clone();+ config.use_residual = true;+ config+ },+ "use_residual=true",+ ),+ (+ {+ let mut config = valid.clone();+ config.activation_function = "torch.nn.GELU".to_string();+ config+ },+ "only Identity",+ ),+ (+ {+ let mut config = valid.clone();+ config.in_features = 384;+ config+ },+ "discontinuous",+ ),+ ] {+ let error =+ validate_pylate_dense_config("test/model", "1_Dense", &invalid, 768).unwrap_err();+ assert!(error.to_string().contains(expected), "{error}");+ }+ }++ #[test]+ fn pylate_modules_require_explicit_index_path_and_type() {+ for raw in [+ r#"[{"path":"","type":"sentence_transformers.models.Transformer"}]"#,+ r#"[{"idx":0,"type":"sentence_transformers.models.Transformer"}]"#,+ r#"[{"idx":0,"path":""}]"#,+ ] {+ assert!(serde_json::from_str::<Vec<SentenceTransformersModule>>(raw).is_err());+ }++ let unknown_dense = r#"{+ "in_features": 768,+ "out_features": 128,+ "bias": false,+ "use_residual": false,+ "activation_function": "torch.nn.modules.linear.Identity",+ "scale": 0.5+ }"#;+ assert!(serde_json::from_str::<PylateDenseConfig>(unknown_dense).is_err());+ }++ #[test]+ fn pylate_modules_reject_unrelated_terminal_class_names() {+ let mut modules = vec![+ SentenceTransformersModule {+ idx: 0,+ path: String::new(),+ module_type: "other.models.Transformer".to_string(),+ },+ SentenceTransformersModule {+ idx: 1,+ path: "1_Dense".to_string(),+ module_type: "other.models.Dense".to_string(),+ },+ ];+ assert!(validate_pylate_modules("test/model", &mut modules).is_err());+ }++ #[test]+ fn pylate_dense_weights_reject_unconfigured_bias_tensor() {+ let tensors = std::collections::HashMap::from([+ (+ "linear.weight".to_string(),+ Tensor::zeros((2, 3), DType::F32, &Device::Cpu).unwrap(),+ ),+ (+ "linear.bias".to_string(),+ Tensor::zeros(2, DType::F32, &Device::Cpu).unwrap(),+ ),+ ]);+ let vb = VarBuilder::from_tensors(tensors, DType::F32, &Device::Cpu);+ assert!(validate_pylate_dense_weights("test/model", "1_Dense", &vb)+ .unwrap_err()+ .to_string()+ .contains("linear.bias"));+ }++ #[test]+ fn rejects_unsupported_architecture_model_type() {+ let err = CandleEmbeddingArchitecture::from_probe(&probe_for_model_type("qwen2"))+ .unwrap_err()+ .to_string();+ assert!(err.contains("does not support model_type"));+ assert!(err.contains("qwen2"));+ }++ fn probe_for_model_type(model_type: &str) -> ModelTypeProbe {+ ModelTypeProbe {+ model_type: Some(model_type.to_string()),+ architectures: Vec::new(),+ position_embedding_type: None,+ feed_forward_type: None,+ }+ }++ fn probe_for_rope_model_type(model_type: &str) -> ModelTypeProbe {+ ModelTypeProbe {+ model_type: Some(model_type.to_string()),+ architectures: Vec::new(),+ position_embedding_type: Some("rope".to_string()),+ feed_forward_type: None,+ }+ }++ #[test]+ fn rejects_unknown_pooling_without_loading_model() {+ let err = pool_embeddings(+ &Tensor::zeros((1, 1, 1), DType::F32, &Device::Cpu).unwrap(),+ &Tensor::zeros((1, 1), DType::F32, &Device::Cpu).unwrap(),+ "last_token",+ )+ .unwrap_err()+ .to_string();+ assert!(err.contains("unsupported Candle pooling strategy"));+ }++ #[test]+ fn prepared_effective_len_strips_trailing_padding_mask() {+ let request = CandlePreparedEncodeRequest {+ input_ids: vec![0, 11, 12, 1, 1],+ attention_mask: Some(vec![1, 1, 1, 0, 0]),+ token_type_ids: None,+ };++ assert_eq!(+ CandleEmbeddingModel::prepared_effective_len(8192, &request),+ 3+ );+ assert_eq!(CandleEmbeddingModel::prepared_effective_len(2, &request), 2);+ }++ #[test]+ fn packed_prepared_tokens_reject_short_attention_mask() {+ let request = CandlePreparedEncodeRequest {+ input_ids: vec![0, 11, 12],+ attention_mask: Some(vec![1, 1]),+ token_type_ids: None,+ };++ let err = CandleEmbeddingModel::validate_prepared_attention_mask_len(8192, &request)+ .unwrap_err()+ .to_string();+ assert!(err.contains("prepared attention_mask length 2 is shorter than input_ids length 3"));+ }++ #[test]+ fn packed_splade_accepts_only_prefix_attention_masks() {+ let prefix = CandlePreparedEncodeRequest {+ input_ids: vec![101, 11, 12, 0, 0],+ attention_mask: Some(vec![1, 1, 1, 0, 0]),+ token_type_ids: None,+ };+ let implicit = CandlePreparedEncodeRequest {+ input_ids: vec![101, 13, 102],+ attention_mask: None,+ token_type_ids: None,+ };+ assert!(CandleEmbeddingModel::prepared_attention_masks_are_prefix(+ &[prefix, implicit],+ 512+ ));++ for mask in [vec![1, 0, 1], vec![0, 0, 0], vec![1, 2, 0], vec![1, 1]] {+ let request = CandlePreparedEncodeRequest {+ input_ids: vec![101, 11, 102],+ attention_mask: Some(mask),+ token_type_ids: None,+ };+ assert!(!CandleEmbeddingModel::prepared_attention_masks_are_prefix(+ &[request],+ 512+ ));+ }+ }++ #[test]+ fn packed_prepared_tokens_zero_ignored_token_type_ids() {+ let request = CandlePreparedEncodeRequest {+ input_ids: vec![0, 11, 12],+ attention_mask: Some(vec![1, 1, 1]),+ token_type_ids: Some(vec![0, 1, 2]),+ };+ let mut out = Vec::new();++ CandleEmbeddingModel::append_packed_token_type_ids(&request, 3, true, &mut out).unwrap();++ assert_eq!(out, vec![0, 0, 0]);+ }++ #[test]+ fn packed_prepared_tokens_preserve_supported_token_type_ids() {+ let request = CandlePreparedEncodeRequest {+ input_ids: vec![0, 11, 12],+ attention_mask: Some(vec![1, 1, 1]),+ token_type_ids: Some(vec![0, 1, 0]),+ };+ let mut out = Vec::new();++ CandleEmbeddingModel::append_packed_token_type_ids(&request, 3, false, &mut out).unwrap();++ assert_eq!(out, vec![0, 1, 0]);+ }++ #[test]+ fn packed_position_ids_match_model_family_semantics() {+ assert_eq!(+ packed_position_id(PackedPositionIdPolicy::ZeroBased, 42, 7),+ 7,+ "RoPE packed paths such as ModernBERT restart positions at zero"+ );+ assert_eq!(+ packed_position_id(PackedPositionIdPolicy::PaddingOffset, 1, 7),+ 9,+ "XLM-R packed positions mirror padding_idx + 1 offset"+ );+ }++ #[test]+ fn pool_packed_embeddings_matches_cls_and_mean_semantics() -> Result<()> {+ let sequence_output = Tensor::new(+ &[[1f32, 2.], [3., 4.], [5., 6.], [7., 8.], [9., 10.]],+ &Device::Cpu,+ )?;+ let seqlens = Tensor::new(&[0u32, 2, 5], &Device::Cpu)?;++ let cls = pool_packed_embeddings(&sequence_output, &seqlens, &[2, 3], "cls")?;+ assert_eq!(cls.to_vec2::<f32>()?, vec![vec![1., 2.], vec![5., 6.]]);++ let mean = pool_packed_embeddings(&sequence_output, &seqlens, &[2, 3], "mean")?;+ assert_eq!(mean.to_vec2::<f32>()?, vec![vec![2., 3.], vec![7., 8.]]);+ Ok(())+ }++ #[test]+ fn compute_precision_parser_uses_safe_cpu_fallback() {+ assert_eq!(+ dtype_from_compute_precision(Some("float32"), &Device::Cpu).unwrap(),+ DType::F32+ );+ assert_eq!(+ dtype_from_compute_precision(Some("bfloat16"), &Device::Cpu).unwrap(),+ DType::F32+ );+ assert!(dtype_from_compute_precision(Some("int8"), &Device::Cpu).is_err());+ }++ #[test]+ fn f16_wire_bytes_are_little_endian() {+ let values = [f16::from_bits(0x3c00), f16::from_bits(0x8001)];++ assert_eq!(+ f16_values_to_le_bytes(&values),+ vec![0x00, 0x3c, 0x01, 0x80]+ );+ }++ #[test]+ fn split_packed_multivectors_f16_uses_contiguous_item_slices() -> Result<()> {+ let projected = Tensor::new(&[[1f32, 2.], [3., 4.], [5., 6.]], &Device::Cpu)?;++ let (batch, timings) = split_packed_multivectors_f16(&projected, &[2, 1], 2)?;++ assert_eq!(batch.items.len(), 2);+ assert_eq!(batch.items[0].byte_offset, 0);+ assert_eq!(batch.items[0].byte_len, 8);+ assert_eq!(batch.items[0].num_tokens, 2);+ assert_eq!(batch.items[0].token_dims, 2);+ assert_eq!(+ f16_values_to_le_bytes(&batch.values_f16[0..4]),+ f16_values_to_le_bytes(&[+ f16::from_f32(1.),+ f16::from_f32(2.),+ f16::from_f32(3.),+ f16::from_f32(4.),+ ])+ );+ assert_eq!(batch.items[1].byte_offset, 8);+ assert_eq!(batch.items[1].byte_len, 4);+ assert_eq!(batch.items[1].num_tokens, 1);+ assert_eq!(+ f16_values_to_le_bytes(&batch.values_f16[4..6]),+ f16_values_to_le_bytes(&[f16::from_f32(5.), f16::from_f32(6.)])+ );+ let legacy = batch.clone().into_individual()?;+ assert_eq!(legacy.len(), 2);+ assert_eq!(+ legacy[0].values_f16,+ f16_values_to_le_bytes(&[+ f16::from_f32(1.),+ f16::from_f32(2.),+ f16::from_f32(3.),+ f16::from_f32(4.),+ ])+ );+ assert!(timings.tensor_readback_ms >= 0.0);+ assert!(timings.host_pack_ms >= 0.0);+ Ok(())+ }++ #[test]+ fn split_masked_multivectors_f16_preserves_selected_rows() -> Result<()> {+ let projected = Tensor::new(+ &[+ [[1f32, 2.], [3., 4.], [5., 6.]],+ [[7., 8.], [9., 10.], [11., 12.]],+ ],+ &Device::Cpu,+ )?;+ let attention_mask = Tensor::new(&[[1u32, 0, 1], [0, 1, 0]], &Device::Cpu)?;++ let (batch, timings) = split_multivectors_f16(&projected, &attention_mask, 2)?;++ assert_eq!(batch.items.len(), 2);+ assert_eq!(batch.items[0].byte_offset, 0);+ assert_eq!(batch.items[0].byte_len, 8);+ assert_eq!(batch.items[0].num_tokens, 2);+ assert_eq!(+ f16_values_to_le_bytes(&batch.values_f16[0..4]),+ f16_values_to_le_bytes(&[+ f16::from_f32(1.),+ f16::from_f32(2.),+ f16::from_f32(5.),+ f16::from_f32(6.),+ ])+ );+ assert_eq!(batch.items[1].byte_offset, 8);+ assert_eq!(batch.items[1].byte_len, 4);+ assert_eq!(batch.items[1].num_tokens, 1);+ assert_eq!(+ f16_values_to_le_bytes(&batch.values_f16[4..6]),+ f16_values_to_le_bytes(&[f16::from_f32(9.), f16::from_f32(10.)])+ );+ assert!(timings.tensor_readback_ms >= 0.0);+ assert!(timings.host_pack_ms >= 0.0);+ Ok(())+ }++ #[test]+ fn gemm_precision_flags_apply_only_to_matching_compute_dtype() {+ let config = CandleGemmPrecisionConfig {+ f32: false,+ f16: true,+ bf16: false,+ };++ assert!(config.applies_to_dtype(DType::F16));+ assert!(!config.applies_to_dtype(DType::BF16));+ assert!(!config.applies_to_dtype(DType::F32));+ }++ #[test]+ fn hugging_face_token_from_env_value_uses_only_nonempty_tokens() {+ assert_eq!(+ hugging_face_token_from_env_value(Some(" hf_read_token ".to_string())),+ Some("hf_read_token".to_string())+ );+ assert_eq!(+ hugging_face_token_from_env_value(Some(" \n\t ".to_string())),+ None+ );+ assert_eq!(hugging_face_token_from_env_value(None), None);+ }++ #[test]+ #[ignore = "downloads a Hugging Face model and runs Candle inference"]+ fn live_encodes_all_minilm() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "sentence-transformers/all-MiniLM-L6-v2".to_string(),+ hf_id: "sentence-transformers/all-MiniLM-L6-v2".to_string(),+ hf_revision: None,+ max_seq_length: 256,+ query_max_length: None,+ dense_dim: Some(384),+ sparse_dim: None,+ multivector_dim: None,+ compute_precision: None,+ })?;+ let encoded = model.encode(+ &[CandleEncodeRequest {+ text: "query: what is candle?".to_string(),+ }],+ "mean",+ true,+ )?;+ assert_eq!(encoded.dim, 384);+ assert_eq!(encoded.embeddings.len(), 1);+ assert_eq!(encoded.embeddings[0].len(), 384);+ assert!(encoded.embeddings[0].iter().all(|value| value.is_finite()));+ Ok(())+ }++ #[test]+ #[ignore = "downloads pinned prithivida/Splade_PP_en_v2 PyTorch weights and runs Candle inference"]+ fn live_encodes_splade_pytorch_checkpoint() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "prithivida/Splade_PP_en_v2".to_string(),+ hf_id: "prithivida/Splade_PP_en_v2".to_string(),+ hf_revision: Some("f0d4aa214dcb60c274052a52c0497535e3aec64c".to_string()),+ max_seq_length: 512,+ query_max_length: None,+ dense_dim: None,+ sparse_dim: Some(30522),+ multivector_dim: None,+ compute_precision: Some("float32".to_string()),+ })?;+ let encoded = model.encode_sparse(&[+ CandleEncodeRequest {+ text: "test".to_string(),+ },+ CandleEncodeRequest {+ text: "A longer sentence keeps sparse batch ordering honest.".to_string(),+ },+ ])?;++ assert_eq!(encoded.dim, 30522);+ let sparse = encoded+ .sparse_embeddings+ .expect("SPLADE encode returns sparse rows");+ assert_eq!(sparse.len(), 2);+ let first = &sparse[0];+ assert!(first.indices.len() >= 3);+ assert_eq!(&first.indices[..3], &[2668, 2671, 2674]);+ for (actual, expected) in first.values[..3].iter().copied().map(f64::from).zip([+ 0.1822509765625,+ 0.1221923828125,+ 0.061126708984375,+ ]) {+ assert!(+ (actual - expected).abs() <= 0.05,+ "SPLADE golden weight mismatch: actual={actual} expected={expected}"+ );+ }+ for row in sparse {+ assert!(!row.indices.is_empty());+ assert_eq!(row.indices.len(), row.values.len());+ assert!(row.indices.windows(2).all(|pair| pair[0] < pair[1]));+ assert!(row+ .values+ .iter()+ .all(|value| value.is_finite() && *value > 0.0));+ }+ Ok(())+ }++ #[test]+ #[ignore = "downloads pinned SPLADE weights and compares CUDA F16 packed/padded forwards"]+ fn live_packed_splade_matches_padded_f16() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "prithivida/Splade_PP_en_v2".to_string(),+ hf_id: "prithivida/Splade_PP_en_v2".to_string(),+ hf_revision: Some("f0d4aa214dcb60c274052a52c0497535e3aec64c".to_string()),+ max_seq_length: 512,+ query_max_length: None,+ dense_dim: None,+ sparse_dim: Some(30522),+ multivector_dim: None,+ compute_precision: Some("float16".to_string()),+ })?;+ if !model.should_use_packed_splade() {+ anyhow::bail!("packed SPLADE parity test requires a CUDA F16 runtime")+ }++ let texts = [+ "how to sort a list in python",+ "segfault when freeing a pointer twice in C",+ "SPLADE max-pools lexical term weights over a mixed-length token batch.",+ ];+ let mut prepared = texts+ .iter()+ .map(|text| {+ model+ .tokenizer+ .encode(*text, true)+ .map_err(anyhow::Error::msg)+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ if let Some(token_types) = prepared[1].token_type_ids.as_mut() {+ let midpoint = token_types.len() / 2;+ token_types[midpoint..].fill(1);+ }++ let token_stats = model.prepared_token_stats(&prepared);+ let (token_ids, attention_mask, token_type_ids) = model.prepared_tensors(&prepared)?;+ let padded = model.encode_sparse_tensors(+ &token_ids,+ &attention_mask,+ &token_type_ids,+ 0.0,+ token_stats,+ 0.0,+ "prepared",+ )?;+ let packed_tensors = model.prepared_packed_tensors(&prepared)?;+ let packed = model.encode_packed_sparse(&packed_tensors, 0.0, 0.0, "prepared")?;+ let padded = padded+ .sparse_embeddings+ .context("padded SPLADE parity output is missing")?;+ let packed = packed+ .sparse_embeddings+ .context("packed SPLADE parity output is missing")?;+ assert_eq!(packed.len(), padded.len());++ let densify = |row: &CandleSparseEmbedding| {+ let mut dense = vec![0.0f32; 30522];+ for (&index, &value) in row.indices.iter().zip(&row.values) {+ dense[index as usize] = value;+ }+ dense+ };+ for (packed, padded) in packed.iter().zip(&padded) {+ let packed = densify(packed);+ let padded = densify(padded);+ let max_diff = packed+ .iter()+ .zip(&padded)+ .map(|(packed, padded)| (packed - padded).abs())+ .fold(0.0f32, f32::max);+ assert!(+ max_diff < 0.05,+ "packed/padded SPLADE max sparse-weight difference {max_diff} exceeds tolerance"+ );++ let top_indices = |values: &[f32]| {+ let mut indices = (0..values.len()).collect::<Vec<_>>();+ indices.sort_unstable_by(|left, right| values[*right].total_cmp(&values[*left]));+ indices+ .into_iter()+ .take(20)+ .collect::<std::collections::HashSet<_>>()+ };+ let packed_top = top_indices(&packed);+ let padded_top = top_indices(&padded);+ let overlap = packed_top.intersection(&padded_top).count();+ assert!(+ overlap >= 18,+ "packed/padded SPLADE top-20 overlap {overlap}/20 is below tolerance"+ );+ }+ Ok(())+ }++ #[test]+ #[ignore = "downloads BAAI/bge-m3 and runs Candle XLM-R dense inference"]+ fn live_encodes_bge_m3_dense() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "BAAI/bge-m3".to_string(),+ hf_id: "BAAI/bge-m3".to_string(),+ hf_revision: None,+ max_seq_length: 8192,+ query_max_length: None,+ dense_dim: Some(1024),+ sparse_dim: None,+ multivector_dim: None,+ compute_precision: Some("bfloat16".to_string()),+ })?;+ let encoded = model.encode(+ &[CandleEncodeRequest {+ text: "Represent this sentence for searching relevant passages.".to_string(),+ }],+ "cls",+ true,+ )?;+ assert_eq!(encoded.dim, 1024);+ assert_eq!(encoded.embeddings.len(), 1);+ assert_eq!(encoded.embeddings[0].len(), 1024);+ assert!(encoded.embeddings[0].iter().all(|value| value.is_finite()));+ Ok(())+ }++ #[test]+ #[ignore = "downloads Snowflake Arctic Embed L v2.0 and runs CUDA XLM-R FP16 inference"]+ fn live_encodes_snowflake_arctic_dense() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "Snowflake/snowflake-arctic-embed-l-v2.0".to_string(),+ hf_id: "Snowflake/snowflake-arctic-embed-l-v2.0".to_string(),+ hf_revision: Some("ac6544c8a46e00af67e330e85a9028c66b8cfd9a".to_string()),+ max_seq_length: 8192,+ query_max_length: None,+ dense_dim: Some(1024),+ sparse_dim: None,+ multivector_dim: None,+ compute_precision: Some("float16".to_string()),+ })?;+ let texts = [+ "query: what is Snowflake Arctic Embed?",+ "Snowflake Arctic Embed is a multilingual retrieval model.",+ "query: Wo findet man die besten Tacos?",+ "Die besten Tacos findet man in Mexiko-Stadt.",+ ];+ let requests = texts+ .iter()+ .map(|text| CandleEncodeRequest {+ text: (*text).to_string(),+ })+ .collect::<Vec<_>>();+ let encoded = model.encode(&requests, "cls", true)?;++ assert_eq!(encoded.dim, 1024);+ assert_eq!(encoded.embeddings.len(), texts.len());+ for embedding in &encoded.embeddings {+ assert_eq!(embedding.len(), 1024);+ assert!(embedding.iter().all(|value| value.is_finite()));+ let norm = embedding+ .iter()+ .map(|value| value * value)+ .sum::<f32>()+ .sqrt();+ assert!(+ (norm - 1.0).abs() < 1e-3,+ "embedding norm {norm} is not unit length"+ );+ }++ let prepared = texts+ .iter()+ .map(|text| {+ model+ .tokenizer+ .encode(*text, true)+ .map_err(anyhow::Error::msg)+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let packed = model.prepared_packed_tensors(&prepared)?;+ let xlm_roberta = match &model.model {+ CandleEmbeddingInner::XlmRoberta(model) => model,+ _ => anyhow::bail!("Snowflake Arctic did not load through XLM-R"),+ };+ let full_output = xlm_roberta.forward_packed(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )?;+ let full_cls =+ pool_packed_embeddings(&full_output, &packed.seqlens, &packed.seq_lengths, "cls")?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ let fast_cls = xlm_roberta+ .forward_packed_cls(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ )?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ let (profiled_cls, profile) = xlm_roberta.forward_packed_cls_profiled(+ &packed.input_ids,+ &packed.position_ids,+ &packed.seqlens,+ packed.max_seqlen,+ false,+ )?;+ let profiled_cls = profiled_cls.to_dtype(DType::F32)?.to_vec2::<f32>()?;+ assert_eq!(full_cls.len(), texts.len());+ assert_eq!(fast_cls.len(), full_cls.len());+ assert_eq!(profiled_cls.len(), full_cls.len());+ assert_eq!(profile.layers, 24);+ assert_eq!(+ profile.total_tokens,+ packed.seq_lengths.iter().sum::<usize>()+ );+ for ((full, fast), profiled) in full_cls.iter().zip(&fast_cls).zip(&profiled_cls) {+ assert!(+ cosine_similarity(full, fast) > 0.9999,+ "full and CLS-tail Snowflake Arctic forwards diverged"+ );+ assert!(+ cosine_similarity(fast, profiled) > 0.9999,+ "profiled and unprofiled CLS-tail Snowflake Arctic forwards diverged"+ );+ }++ for (text, batched) in texts.iter().zip(&encoded.embeddings) {+ let singleton = model.encode(+ &[CandleEncodeRequest {+ text: (*text).to_string(),+ }],+ "cls",+ true,+ )?;+ assert!(+ cosine_similarity(batched, &singleton.embeddings[0]) > 0.999,+ "batched and singleton Snowflake Arctic embeddings diverged"+ );+ }++ Ok(())+ }++ #[test]+ #[ignore = "downloads Alibaba-NLP/gte-multilingual-base and runs CUDA GTE-RoPE dense inference"]+ fn live_encodes_gte_multilingual_base_rope_dense() -> Result<()> {+ let model = CandleEmbeddingModel::load(&CandleEmbeddingModelConfig {+ model_id: "Alibaba-NLP/gte-multilingual-base".to_string(),+ hf_id: "Alibaba-NLP/gte-multilingual-base".to_string(),+ hf_revision: None,+ max_seq_length: 8192,+ query_max_length: None,+ dense_dim: Some(768),+ sparse_dim: None,+ multivector_dim: None,+ compute_precision: Some("float16".to_string()),+ })?;+ let texts = [+ "Represent this sentence for searching relevant passages.",+ "A second sentence keeps the packed batch path honest.",+ ];+ let requests = texts+ .iter()+ .map(|text| CandleEncodeRequest {+ text: (*text).to_string(),+ })+ .collect::<Vec<_>>();+ let encoded = model.encode(&requests, "cls", true)?;+ assert_eq!(encoded.dim, 768);+ assert_eq!(encoded.embeddings.len(), texts.len());+ assert!(encoded+ .embeddings+ .iter()+ .all(|embedding| embedding.len() == 768+ && embedding.iter().all(|value| value.is_finite())));++ let prepared = texts+ .iter()+ .map(|text| {+ model+ .tokenizer+ .encode(*text, true)+ .map_err(anyhow::Error::msg)+ .map(|encoding| CandlePreparedEncodeRequest {+ input_ids: encoding.get_ids().to_vec(),+ attention_mask: Some(encoding.get_attention_mask().to_vec()),+ token_type_ids: Some(encoding.get_type_ids().to_vec()),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let prepared_encoded = model.encode_prepared(&prepared, "cls", true)?;+ assert_eq!(prepared_encoded.dim, encoded.dim);+ assert_eq!(prepared_encoded.embeddings.len(), encoded.embeddings.len());+ for (raw, prepared) in encoded+ .embeddings+ .iter()+ .zip(prepared_encoded.embeddings.iter())+ {+ assert!(+ cosine_similarity(raw, prepared) > 0.999,+ "prepared and raw packed GTE embeddings diverged"+ );+ }+ Ok(())+ }++ fn cosine_similarity(left: &[f32], right: &[f32]) -> f32 {+ let mut dot = 0.0f32;+ let mut left_norm = 0.0f32;+ let mut right_norm = 0.0f32;+ for (left, right) in left.iter().zip(right.iter()) {+ dot += left * right;+ left_norm += left * left;+ right_norm += right * right;+ }+ dot / (left_norm.sqrt() * right_norm.sqrt())+ }+}diff --git a/packages/sie_server_rust/src/candle_gte_rope.rs b/packages/sie_server_rust/src/candle_gte_rope.rsnew file mode 100644index 000000000..b26317505--- /dev/null+++ b/packages/sie_server_rust/src/candle_gte_rope.rs@@ -0,0 +1,732 @@+//! GTE/NewModel encoder with packed RoPE FlashAttention for Candle.++#[cfg(feature = "cuda")]+use std::sync::OnceLock;+use std::time::Instant;++use crate::candle_layers::{index_select, FastLayerNorm, FastLinear, HiddenAct};+use crate::candle_rope::{+ apply_rotary_packed_inplace, cos_sin, inv_freqs as build_inv_freqs, RopeScaling,+};+use candle::{DType, Device, Result, Tensor, D};+use candle_nn::{embedding, Embedding, Module, VarBuilder};+use serde::Deserialize;++#[derive(Debug, Clone, Deserialize)]+pub struct Config {+ pub vocab_size: usize,+ pub hidden_size: usize,+ pub num_hidden_layers: usize,+ pub num_attention_heads: usize,+ pub intermediate_size: usize,+ pub hidden_act: HiddenAct,+ pub max_position_embeddings: usize,+ pub type_vocab_size: usize,+ pub layer_norm_eps: f64,+ #[serde(default)]+ pub layer_norm_type: Option<String>,+ #[serde(default)]+ pub pack_qkv: Option<bool>,+ #[serde(default)]+ pub position_embedding_type: Option<String>,+ #[serde(default)]+ pub rope_theta: Option<f32>,+ #[serde(default)]+ pub rope_parameters: Option<RopeParameters>,+ #[serde(default)]+ pub rope_scaling: Option<RopeScaling>,+ #[serde(default)]+ pub logn_attention_scale: bool,+ #[serde(default)]+ pub logn_attention_clip1: bool,+}++#[derive(Debug, Clone, Deserialize)]+pub struct RopeParameters {+ pub rope_theta: f32,+}++#[derive(Debug, Clone, Copy, Default)]+pub struct GteRopeForwardProfile {+ pub total_tokens: usize,+ pub max_seqlen: usize,+ pub hidden_size: usize,+ pub intermediate_size: usize,+ pub attention_heads: usize,+ pub attention_head_size: usize,+ pub linear_gflops: f64,+ pub embedding_ms: f64,+ pub rope_select_ms: f64,+ pub attention_ms: f64,+ pub attention_qkv_ms: f64,+ pub attention_rotary_ms: f64,+ pub attention_flash_ms: f64,+ pub attention_output_dense_ms: f64,+ pub attention_output_layernorm_ms: f64,+ pub ffn_ms: f64,+ pub ffn_up_gate_ms: f64,+ pub ffn_activation_ms: f64,+ pub ffn_down_ms: f64,+ pub ffn_output_layernorm_ms: f64,+ pub layers: usize,+}++struct GteRopeEmbeddings {+ word_embeddings: Embedding,+ token_type_embeddings: Option<Embedding>,+ layer_norm: FastLayerNorm,+}++impl GteRopeEmbeddings {+ fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ let word_embeddings = embedding(+ config.vocab_size,+ config.hidden_size,+ vb.pp("word_embeddings"),+ )?;+ let token_type_embeddings = if config.type_vocab_size > 0 {+ Some(embedding(+ config.type_vocab_size,+ config.hidden_size,+ vb.pp("token_type_embeddings"),+ )?)+ } else {+ None+ };+ let layer_norm = FastLayerNorm::load(+ vb.pp("LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )?;+ Ok(Self {+ word_embeddings,+ token_type_embeddings,+ layer_norm,+ })+ }++ fn forward_packed(&self, input_ids: &Tensor, token_type_ids: &Tensor) -> Result<Tensor> {+ let word_embeddings = self.word_embeddings.forward(input_ids)?;+ let token_type_embeddings = self+ .token_type_embeddings+ .as_ref()+ .map(|embeddings| embeddings.forward(token_type_ids))+ .transpose()?;+ self.layer_norm+ .forward(&word_embeddings, token_type_embeddings.as_ref())+ }+}++struct GteRopeAttention {+ qkv: FastLinear,+ output: FastLinear,+ num_attention_heads: usize,+ attention_head_size: usize,+ all_head_size: usize,+}++impl GteRopeAttention {+ fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ let num_attention_heads = config.num_attention_heads;+ let attention_head_size = config.hidden_size / config.num_attention_heads;+ let all_head_size = num_attention_heads * attention_head_size;+ let qkv_weight = vb+ .pp("qkv_proj")+ .get((config.hidden_size * 3, config.hidden_size), "weight")?;+ let qkv_bias = vb.pp("qkv_proj").get(config.hidden_size * 3, "bias")?;+ let output_weight = vb+ .pp("o_proj")+ .get((config.hidden_size, config.hidden_size), "weight")?;+ let output_bias = vb.pp("o_proj").get(config.hidden_size, "bias")?;++ Ok(Self {+ qkv: FastLinear::new(qkv_weight, Some(qkv_bias), None),+ output: FastLinear::new(output_weight, Some(output_bias), None),+ num_attention_heads,+ attention_head_size,+ all_head_size,+ })+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;+ let qkv = self.qkv.forward(hidden_states)?;+ let qkv = qkv.reshape((+ total_tokens,+ self.num_attention_heads * 3,+ self.attention_head_size,+ ))?;++ let query = qkv.narrow(1, 0, self.num_attention_heads)?;+ let key = qkv.narrow(1, self.num_attention_heads, self.num_attention_heads)?;+ let value = qkv.narrow(1, self.num_attention_heads * 2, self.num_attention_heads)?;++ apply_rotary_packed_inplace(&query, &key, cos, sin)?;+ let attention_output = flash_attn_varlen(+ &query,+ &key,+ &value,+ seqlens,+ max_seqlen,+ self.attention_head_size,+ )?;+ let attention_output = attention_output.reshape((total_tokens, self.all_head_size))?;+ self.output.forward(&attention_output)+ }++ #[allow(clippy::too_many_arguments)]+ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ profile: &mut GteRopeForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;++ synchronize_if(hidden_states.device(), sync_timings)?;+ let qkv_start = Instant::now();+ let qkv = self.qkv.forward(hidden_states)?;+ let qkv = qkv.reshape((+ total_tokens,+ self.num_attention_heads * 3,+ self.attention_head_size,+ ))?;+ let query = qkv.narrow(1, 0, self.num_attention_heads)?;+ let key = qkv.narrow(1, self.num_attention_heads, self.num_attention_heads)?;+ let value = qkv.narrow(1, self.num_attention_heads * 2, self.num_attention_heads)?;+ synchronize_if(query.device(), sync_timings)?;+ profile.attention_qkv_ms += elapsed_ms(qkv_start);++ let rotary_start = Instant::now();+ apply_rotary_packed_inplace(&query, &key, cos, sin)?;+ synchronize_if(query.device(), sync_timings)?;+ profile.attention_rotary_ms += elapsed_ms(rotary_start);++ let flash_start = Instant::now();+ let attention_output = flash_attn_varlen(+ &query,+ &key,+ &value,+ seqlens,+ max_seqlen,+ self.attention_head_size,+ )?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_flash_ms += elapsed_ms(flash_start);++ let dense_start = Instant::now();+ let attention_output = attention_output.reshape((total_tokens, self.all_head_size))?;+ let attention_output = self.output.forward(&attention_output)?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_output_dense_ms += elapsed_ms(dense_start);+ Ok(attention_output)+ }+}++struct GteRopeMlp {+ up_gate: FastLinear,+ down: FastLinear,+ act: HiddenAct,+ intermediate_size: usize,+}++impl GteRopeMlp {+ fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ let up_gate_weight = vb+ .pp("up_gate_proj")+ .get((config.intermediate_size * 2, config.hidden_size), "weight")?;+ let down_weight = vb+ .pp("down_proj")+ .get((config.hidden_size, config.intermediate_size), "weight")?;+ let down_bias = vb.pp("down_proj").get(config.hidden_size, "bias")?;+ Ok(Self {+ up_gate: FastLinear::new(up_gate_weight, None, None),+ down: FastLinear::new(down_weight, Some(down_bias), None),+ act: config.hidden_act,+ intermediate_size: config.intermediate_size,+ })+ }++ fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> {+ let up_gate = self.up_gate.forward(hidden_states)?;+ let gated = self.gated_activation(&up_gate)?;+ self.down.forward(&gated)+ }++ fn forward_profiled(+ &self,+ hidden_states: &Tensor,+ profile: &mut GteRopeForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let up_gate_start = Instant::now();+ let up_gate = self.up_gate.forward(hidden_states)?;+ synchronize_if(up_gate.device(), sync_timings)?;+ profile.ffn_up_gate_ms += elapsed_ms(up_gate_start);++ let activation_start = Instant::now();+ let gated = self.gated_activation(&up_gate)?;+ synchronize_if(gated.device(), sync_timings)?;+ profile.ffn_activation_ms += elapsed_ms(activation_start);++ let down_start = Instant::now();+ let output = self.down.forward(&gated)?;+ synchronize_if(output.device(), sync_timings)?;+ profile.ffn_down_ms += elapsed_ms(down_start);+ Ok(output)+ }++ fn gated_activation(&self, up_gate: &Tensor) -> Result<Tensor> {+ if self.can_use_fused_gated_activation(up_gate) {+ #[cfg(feature = "cuda")]+ {+ return candle_gated_activation::gelu_gate(up_gate, self.intermediate_size);+ }+ }++ let up = up_gate.narrow(D::Minus1, 0, self.intermediate_size)?;+ let gate = up_gate.narrow(D::Minus1, self.intermediate_size, self.intermediate_size)?;+ let gate = self.act.forward(&gate)?;+ gate * up+ }++ fn can_use_fused_gated_activation(&self, up_gate: &Tensor) -> bool {+ if !self.gated_activation_fused() {+ return false;+ }+ if !matches!(up_gate.device(), Device::Cuda(_)) || !up_gate.is_contiguous() {+ return false;+ }+ if !matches!(up_gate.dtype(), DType::F16 | DType::BF16 | DType::F32) {+ return false;+ }+ up_gate+ .dims()+ .last()+ .is_some_and(|last_dim| *last_dim == self.intermediate_size * 2)+ }++ fn gated_activation_fused(&self) -> bool {+ matches!(self.act, HiddenAct::Gelu) && fused_gated_gelu_enabled()+ }+}++struct GteRopeLayer {+ attention: GteRopeAttention,+ mlp: GteRopeMlp,+ attention_layer_norm: FastLayerNorm,+ mlp_layer_norm: FastLayerNorm,+}++impl GteRopeLayer {+ fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ let attention = GteRopeAttention::load(vb.pp("attention"), config)?;+ let mlp = GteRopeMlp::load(vb.pp("mlp"), config)?;+ let attention_layer_norm =+ FastLayerNorm::load(vb.pp("attn_ln"), config.hidden_size, config.layer_norm_eps)?;+ let mlp_layer_norm =+ FastLayerNorm::load(vb.pp("mlp_ln"), config.hidden_size, config.layer_norm_eps)?;+ Ok(Self {+ attention,+ mlp,+ attention_layer_norm,+ mlp_layer_norm,+ })+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let attention_output =+ self.attention+ .forward_packed(hidden_states, seqlens, cos, sin, max_seqlen)?;+ let attention_output = self+ .attention_layer_norm+ .forward(&attention_output, Some(hidden_states))?;+ let mlp_output = self.mlp.forward(&attention_output)?;+ self.mlp_layer_norm+ .forward(&mlp_output, Some(&attention_output))+ }++ #[allow(clippy::too_many_arguments)]+ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ profile: &mut GteRopeForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let attention_start = Instant::now();+ let attention_output = self.attention.forward_packed_profiled(+ hidden_states,+ seqlens,+ cos,+ sin,+ max_seqlen,+ profile,+ sync_timings,+ )?;++ let layernorm_start = Instant::now();+ let attention_output = self+ .attention_layer_norm+ .forward(&attention_output, Some(hidden_states))?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_output_layernorm_ms += elapsed_ms(layernorm_start);+ profile.attention_ms += elapsed_ms(attention_start);++ let ffn_start = Instant::now();+ let mlp_output = self+ .mlp+ .forward_profiled(&attention_output, profile, sync_timings)?;++ let layernorm_start = Instant::now();+ let output = self+ .mlp_layer_norm+ .forward(&mlp_output, Some(&attention_output))?;+ synchronize_if(output.device(), sync_timings)?;+ profile.ffn_output_layernorm_ms += elapsed_ms(layernorm_start);+ profile.ffn_ms += elapsed_ms(ffn_start);+ profile.layers += 1;+ Ok(output)+ }+}++pub struct GteRopeModel {+ embeddings: GteRopeEmbeddings,+ layers: Vec<GteRopeLayer>,+ cos_cache: Tensor,+ sin_cache: Tensor,+ config: Config,+}++impl GteRopeModel {+ pub fn load(config: &Config, vb: VarBuilder) -> Result<Self> {+ if !matches!(vb.device(), Device::Cuda(_)) {+ candle::bail!("GTE-RoPE packed Candle path requires CUDA");+ }+ if vb.dtype() != DType::F16 {+ candle::bail!("GTE-RoPE packed Candle path requires float16 compute_precision");+ }+ if config.logn_attention_clip1 {+ candle::bail!("GTE-RoPE logn_attention_clip1 is not supported");+ }+ if config.logn_attention_scale {+ candle::bail!("GTE-RoPE logn_attention_scale is not supported");+ }+ if !matches!(+ config.position_embedding_type.as_deref(),+ Some(value) if value.eq_ignore_ascii_case("rope")+ ) {+ candle::bail!("GTE-RoPE requires position_embedding_type=rope");+ }+ if matches!(config.pack_qkv, Some(false)) {+ candle::bail!("GTE-RoPE requires packed qkv_proj weights");+ }+ if let Some(layer_norm_type) = config.layer_norm_type.as_deref() {+ if !layer_norm_type.eq_ignore_ascii_case("layer_norm") {+ candle::bail!("GTE-RoPE requires layer_norm_type=layer_norm");+ }+ }+ if config.num_attention_heads == 0 {+ candle::bail!("GTE-RoPE num_attention_heads must be greater than zero");+ }+ if !config+ .hidden_size+ .is_multiple_of(config.num_attention_heads)+ {+ candle::bail!(+ "GTE-RoPE hidden_size={} must be divisible by num_attention_heads={}",+ config.hidden_size,+ config.num_attention_heads+ );+ }++ let (embeddings, layers) = Self::inner_load(vb.pp("new"), config)+ .or_else(|_| Self::inner_load(vb.clone(), config))?;+ let attention_head_size = config.hidden_size / config.num_attention_heads;+ if !attention_head_size.is_multiple_of(2) {+ candle::bail!("GTE-RoPE attention_head_size must be even");+ }+ let rope_theta = config+ .rope_theta+ .or_else(|| {+ config+ .rope_parameters+ .as_ref()+ .map(|params| params.rope_theta)+ })+ .ok_or_else(|| candle::Error::msg("GTE-RoPE requires rope_theta"))?;+ let inv_freqs = build_inv_freqs(+ attention_head_size,+ rope_theta,+ vb.device(),+ config.rope_scaling.as_ref(),+ )?;+ let (cos_cache, sin_cache) = cos_sin(+ config.max_position_embeddings,+ &inv_freqs,+ vb.dtype(),+ false,+ )?;+ Ok(Self {+ embeddings,+ layers,+ cos_cache,+ sin_cache,+ config: config.clone(),+ })+ }++ fn inner_load(+ vb: VarBuilder,+ config: &Config,+ ) -> Result<(GteRopeEmbeddings, Vec<GteRopeLayer>)> {+ let embeddings = GteRopeEmbeddings::load(vb.pp("embeddings"), config)?;+ let layers = (0..config.num_hidden_layers)+ .map(|index| GteRopeLayer::load(vb.pp(format!("encoder.layer.{index}")), config))+ .collect::<Result<Vec<_>>>()?;+ Ok((embeddings, layers))+ }++ pub fn kernel_backend(&self) -> (&'static str, &'static str, bool, bool, bool) {+ let linear_backend = self+ .layers+ .first()+ .map(|layer| layer.mlp.up_gate.backend())+ .unwrap_or("candle_matmul");+ let layernorm_backend = self.embeddings.layer_norm.backend();+ let ffn_activation_fused = self+ .layers+ .first()+ .map(|layer| layer.mlp.gated_activation_fused())+ .unwrap_or(false);+ (+ linear_backend,+ layernorm_backend,+ true,+ cfg!(feature = "cuda"),+ ffn_activation_fused,+ )+ }++ pub fn ignores_token_type_ids(&self) -> bool {+ self.config.type_vocab_size < 2+ }++ pub fn forward_packed(+ &self,+ input_ids: &Tensor,+ token_type_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let mut hidden_states = self.embeddings.forward_packed(input_ids, token_type_ids)?;+ let cos = index_select(&self.cos_cache, position_ids, 0)?;+ let sin = index_select(&self.sin_cache, position_ids, 0)?;+ for layer in self.layers.iter() {+ hidden_states =+ layer.forward_packed(&hidden_states, seqlens, &cos, &sin, max_seqlen)?;+ }+ Ok(hidden_states)+ }++ pub fn forward_packed_profiled(+ &self,+ input_ids: &Tensor,+ token_type_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ sync_timings: bool,+ ) -> Result<(Tensor, GteRopeForwardProfile)> {+ synchronize_if(input_ids.device(), sync_timings)?;+ let embedding_start = Instant::now();+ let mut hidden_states = self.embeddings.forward_packed(input_ids, token_type_ids)?;+ synchronize_if(hidden_states.device(), sync_timings)?;++ let rope_select_start = Instant::now();+ let cos = index_select(&self.cos_cache, position_ids, 0)?;+ let sin = index_select(&self.sin_cache, position_ids, 0)?;+ synchronize_if(cos.device(), sync_timings)?;++ let total_tokens = input_ids.dim(0)?;+ let mut profile = GteRopeForwardProfile {+ total_tokens,+ max_seqlen,+ hidden_size: self.config.hidden_size,+ intermediate_size: self.config.intermediate_size,+ attention_heads: self.config.num_attention_heads,+ attention_head_size: self.config.hidden_size / self.config.num_attention_heads,+ linear_gflops: linear_gflops(+ total_tokens,+ self.config.hidden_size,+ self.config.intermediate_size,+ self.config.num_hidden_layers,+ ),+ embedding_ms: elapsed_ms(embedding_start),+ rope_select_ms: elapsed_ms(rope_select_start),+ ..Default::default()+ };+ for layer in self.layers.iter() {+ hidden_states = layer.forward_packed_profiled(+ &hidden_states,+ seqlens,+ &cos,+ &sin,+ max_seqlen,+ &mut profile,+ sync_timings,+ )?;+ }+ Ok((hidden_states, profile))+ }+}++#[cfg(feature = "cuda")]+fn fused_gated_gelu_enabled() -> bool {+ static ENABLED: OnceLock<bool> = OnceLock::new();+ *ENABLED.get_or_init(|| {+ let disabled = env_bool_any(&["SIE_CANDLE_DISABLE_FUSED_GATED_GELU"], false);+ let enabled = env_bool_any(&["SIE_CANDLE_ENABLE_FUSED_GATED_GELU"], true);+ enabled && !disabled+ })+}++#[cfg(not(feature = "cuda"))]+fn fused_gated_gelu_enabled() -> bool {+ false+}++#[cfg(feature = "cuda")]+fn env_bool_any(names: &[&str], default: bool) -> bool {+ names+ .iter()+ .find_map(|name| std::env::var(name).ok())+ .map(|value| {+ matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "1" | "true" | "yes" | "on"+ )+ })+ .unwrap_or(default)+}++#[cfg(feature = "cuda")]+fn flash_attn_varlen(+ query: &Tensor,+ key: &Tensor,+ value: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ head_size: usize,+) -> Result<Tensor> {+ let softmax_scale = 1f32 / f32::sqrt(head_size as f32);+ candle_flash_attn::flash_attn_varlen(+ query,+ key,+ value,+ seqlens,+ seqlens,+ max_seqlen,+ max_seqlen,+ softmax_scale,+ false,+ )+}++#[cfg(not(feature = "cuda"))]+fn flash_attn_varlen(+ _query: &Tensor,+ _key: &Tensor,+ _value: &Tensor,+ _seqlens: &Tensor,+ _max_seqlen: usize,+ _head_size: usize,+) -> Result<Tensor> {+ candle::bail!("packed GTE-RoPE FlashAttention requires the cuda feature")+}++fn synchronize_if(device: &Device, enabled: bool) -> Result<()> {+ if enabled {+ device.synchronize()?;+ }+ Ok(())+}++fn elapsed_ms(start: Instant) -> f64 {+ start.elapsed().as_secs_f64() * 1000.0+}++fn linear_gflops(+ tokens: usize,+ hidden_size: usize,+ intermediate_size: usize,+ layers: usize,+) -> f64 {+ let qkv = hidden_size * 3 * hidden_size;+ let attention_output = hidden_size * hidden_size;+ let ffn_up_gate = hidden_size * intermediate_size * 2;+ let ffn_down = intermediate_size * hidden_size;+ 2.0 * tokens as f64 * layers as f64 * (qkv + attention_output + ffn_up_gate + ffn_down) as f64+ / 1_000_000_000.0+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_new_model_rope_ntk_config() {+ let config: Config = serde_json::from_str(+ r#"{+ "vocab_size": 250048,+ "hidden_size": 768,+ "num_hidden_layers": 12,+ "num_attention_heads": 12,+ "intermediate_size": 3072,+ "hidden_act": "gelu",+ "max_position_embeddings": 8192,+ "type_vocab_size": 1,+ "layer_norm_eps": 1e-12,+ "layer_norm_type": "layer_norm",+ "model_type": "new",+ "pack_qkv": true,+ "position_embedding_type": "rope",+ "rope_theta": 20000,+ "rope_scaling": {"factor": 8.0, "type": "ntk"}+ }"#,+ )+ .unwrap();++ assert_eq!(config.hidden_size, 768);+ assert_eq!(config.position_embedding_type.as_deref(), Some("rope"));+ assert_eq!(config.rope_theta, Some(20000.0));+ match config.rope_scaling {+ Some(RopeScaling::Ntk { factor, .. }) => assert_eq!(factor, 8.0),+ other => panic!("expected NTK RoPE scaling, got {other:?}"),+ }+ }+}diff --git a/packages/sie_server_rust/src/candle_layers.rs b/packages/sie_server_rust/src/candle_layers.rsnew file mode 100644index 000000000..7d7a1f9c1--- /dev/null+++ b/packages/sie_server_rust/src/candle_layers.rs@@ -0,0 +1,770 @@+//! Small optimized layer wrappers used by the custom Candle XLM-R path.++#[cfg(feature = "cuda")]+use self::cublaslt::CublasLtExt;+#[cfg(feature = "cuda")]+use std::sync::{Once, OnceLock};++use candle::{DType, Device, Result, Tensor, D};+use candle_nn::{init, ops, Init, VarBuilder};+use serde::Deserialize;+#[cfg(feature = "cuda")]+use tracing::warn;++#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub(crate) enum HiddenAct {+ #[serde(alias = "gelu_new", alias = "gelu_pytorch_tanh")]+ Gelu,+ Relu,+ Silu,+ Swiglu,+ Tanh,+}++impl HiddenAct {+ pub(crate) fn forward(self, x: &Tensor) -> Result<Tensor> {+ match self {+ // Matches TEI's fast path: cuBLASLt supports the tanh GELU epilogue.+ Self::Gelu => x.gelu(),+ Self::Relu => x.relu(),+ Self::Silu => x.silu(),+ Self::Swiglu => ops::swiglu(x),+ Self::Tanh => x.tanh(),+ }+ }+}++#[derive(Debug, Clone)]+pub(crate) struct FastLinear {+ weight: Tensor,+ bias: Option<Tensor>,+ act: Option<HiddenAct>,+}++impl FastLinear {+ pub(crate) fn new(weight: Tensor, bias: Option<Tensor>, act: Option<HiddenAct>) -> Self {+ Self { weight, bias, act }+ }++ pub(crate) fn load(+ in_dim: usize,+ out_dim: usize,+ vb: VarBuilder,+ act: Option<HiddenAct>,+ ) -> Result<Self> {+ let weight =+ vb.get_with_hints((out_dim, in_dim), "weight", init::DEFAULT_KAIMING_NORMAL)?;+ let bound = 1. / (in_dim as f64).sqrt();+ let bias = vb.get_with_hints(+ out_dim,+ "bias",+ Init::Uniform {+ lo: -bound,+ up: bound,+ },+ )?;+ Ok(Self {+ weight,+ bias: Some(bias),+ act,+ })+ }++ pub(crate) fn load_no_bias(+ in_dim: usize,+ out_dim: usize,+ vb: VarBuilder,+ act: Option<HiddenAct>,+ ) -> Result<Self> {+ let weight =+ vb.get_with_hints((out_dim, in_dim), "weight", init::DEFAULT_KAIMING_NORMAL)?;+ Ok(Self::new(weight, None, act))+ }++ pub(crate) fn load_qkv(in_dim: usize, out_dim: usize, vb: VarBuilder) -> Result<Self> {+ let query = Self::load(in_dim, out_dim, vb.pp("query"), None)?;+ let key = Self::load(in_dim, out_dim, vb.pp("key"), None)?;+ let value = Self::load(in_dim, out_dim, vb.pp("value"), None)?;+ let weight = Tensor::cat(&[&query.weight, &key.weight, &value.weight], 0)?;+ let bias = match (&query.bias, &key.bias, &value.bias) {+ (Some(query), Some(key), Some(value)) => Some(Tensor::cat(&[query, key, value], 0)?),+ _ => None,+ };+ Ok(Self::new(weight, bias, None))+ }++ pub(crate) fn forward(&self, x: &Tensor) -> Result<Tensor> {+ if let Some(output) = self.forward_cublaslt(x)? {+ return Ok(output);+ }++ let x = match *x.dims() {+ [b1, b2, m, k] if x.is_contiguous() => {+ let w = self.weight.t()?;+ x.reshape((b1 * b2 * m, k))?+ .matmul(&w)?+ .reshape((b1, b2, m, ()))?+ }+ [b1, b2, _, _] => {+ let w = self.weight.broadcast_left((b1, b2))?.t()?;+ x.matmul(&w)?+ }+ [bsize, m, k] if x.is_contiguous() => {+ let w = self.weight.t()?;+ x.reshape((bsize * m, k))?+ .matmul(&w)?+ .reshape((bsize, m, ()))?+ }+ [bsize, _, _] => {+ let w = self.weight.broadcast_left(bsize)?.t()?;+ x.matmul(&w)?+ }+ _ => {+ let w = self.weight.t()?;+ x.matmul(&w)?+ }+ };+ let x = match &self.bias {+ Some(bias) => x.broadcast_add(bias)?,+ None => x,+ };+ self.forward_activation(x)+ }++ fn forward_activation(&self, x: Tensor) -> Result<Tensor> {+ match self.act {+ Some(act) => act.forward(&x),+ None => Ok(x),+ }+ }++ #[cfg(feature = "cuda")]+ fn forward_cublaslt(&self, x: &Tensor) -> Result<Option<Tensor>> {+ if !matches!(x.device(), Device::Cuda(_)) {+ return Ok(None);+ }+ if !x.is_contiguous() {+ return Ok(None);+ }+ if !cublaslt_enabled() {+ return Ok(None);+ }+ let Some(cublaslt) = cublaslt::get(x.device()) else {+ return Ok(None);+ };+ let (fused_act, activation_fused) = cublaslt_activation(self.act);+ let mut output = match *x.dims() {+ // Broadcasting the weight creates a stride-zero view that cuBLASLt rejects.+ // Flatten the batch into the row dimension and reuse the contiguous rank-two path.+ [bsize, rows, columns] => {+ let flattened_rows = bsize.checked_mul(rows).ok_or_else(|| {+ candle::Error::msg("FastLinear rank-three row count overflow")+ })?;+ cublaslt+ .matmul(+ &self.weight,+ &x.reshape((flattened_rows, columns))?,+ self.bias.as_ref(),+ fused_act,+ )?+ .reshape((bsize, rows, ()))?+ }+ [_, _] => cublaslt.matmul(&self.weight, x, self.bias.as_ref(), fused_act)?,+ _ => return Ok(None),+ };+ if !activation_fused {+ output = self.forward_activation(output)?;+ }+ Ok(Some(output))+ }++ #[cfg(not(feature = "cuda"))]+ fn forward_cublaslt(&self, _x: &Tensor) -> Result<Option<Tensor>> {+ Ok(None)+ }++ pub(crate) fn backend(&self) -> &'static str {+ if self.uses_cublaslt() {+ "cuda_cublaslt"+ } else {+ "candle_matmul"+ }+ }++ pub(crate) fn uses_cublaslt(&self) -> bool {+ cublaslt_available(self.weight.device())+ }++ pub(crate) fn activation_kernel_fused(&self) -> bool {+ self.uses_cublaslt() && matches!(self.act, Some(HiddenAct::Gelu | HiddenAct::Relu))+ }+}++#[derive(Debug, Clone)]+pub(crate) struct FastLayerNorm {+ weight: Tensor,+ bias: Option<Tensor>,+ epsilon: f32,+}++impl FastLayerNorm {+ pub(crate) fn load(vb: VarBuilder, hidden_size: usize, epsilon: f64) -> Result<Self> {+ let weight = vb.get_with_hints(hidden_size, "weight", Init::Const(1.))?;+ let bias = vb.get_with_hints(hidden_size, "bias", Init::Const(0.))?;+ Ok(Self {+ weight,+ bias: Some(bias),+ epsilon: epsilon as f32,+ })+ }++ pub(crate) fn load_no_bias(vb: VarBuilder, hidden_size: usize, epsilon: f64) -> Result<Self> {+ let weight = vb.get_with_hints(hidden_size, "weight", Init::Const(1.))?;+ Ok(Self {+ weight,+ bias: None,+ epsilon: epsilon as f32,+ })+ }++ pub(crate) fn forward(+ &self,+ hidden_states: &Tensor,+ residual: Option<&Tensor>,+ ) -> Result<Tensor> {+ if let Some(output) = self.forward_cuda(hidden_states, residual)? {+ return Ok(output);+ }++ let hidden_states = match residual {+ Some(residual) => hidden_states.add(residual)?,+ None => hidden_states.clone(),+ };+ self.forward_fallback(&hidden_states)+ }++ fn forward_fallback(&self, hidden_states: &Tensor) -> Result<Tensor> {+ if hidden_states.is_contiguous() {+ if let Some(bias) = &self.bias {+ return ops::layer_norm(hidden_states, &self.weight, bias, self.epsilon);+ }+ }++ let hidden_states_dtype = hidden_states.dtype();+ let internal_dtype = match hidden_states_dtype {+ DType::F16 | DType::BF16 => DType::F32,+ dtype => dtype,+ };+ let hidden_size = hidden_states.dim(D::Minus1)?;+ let hidden_states = hidden_states.to_dtype(internal_dtype)?;+ let mean_hidden_states = (hidden_states.sum_keepdim(D::Minus1)? / hidden_size as f64)?;+ let hidden_states = hidden_states.broadcast_sub(&mean_hidden_states)?;+ let norm_hidden_states =+ (hidden_states.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?;+ let hidden_states = hidden_states+ .broadcast_div(&(norm_hidden_states + self.epsilon as f64)?.sqrt()?)?+ .to_dtype(hidden_states_dtype)?+ .broadcast_mul(&self.weight)?;+ match &self.bias {+ Some(bias) => hidden_states.broadcast_add(bias),+ None => Ok(hidden_states),+ }+ }++ #[cfg(feature = "cuda")]+ fn forward_cuda(+ &self,+ hidden_states: &Tensor,+ residual: Option<&Tensor>,+ ) -> Result<Option<Tensor>> {+ if !matches!(hidden_states.device(), Device::Cuda(_)) {+ return Ok(None);+ }+ let original_shape = hidden_states.shape();+ let hidden_size = hidden_states.dim(D::Minus1)?;+ if hidden_size % 8 != 0 || hidden_size > 8192 {+ return Ok(None);+ }+ let hidden_states = hidden_states.flatten_to(D::Minus2)?;+ let output_only = layer_norm_output_only_enabled();+ let output = match residual {+ Some(residual) => {+ let residual = residual.flatten_to(D::Minus2)?;+ if output_only {+ candle_layer_norm::fused_add_layer_norm_output_only(+ &hidden_states,+ &residual,+ &self.weight,+ self.bias.as_ref(),+ self.epsilon,+ )?+ } else {+ candle_layer_norm::fused_add_layer_norm(+ &hidden_states,+ &residual,+ &self.weight,+ self.bias.as_ref(),+ self.epsilon,+ )?+ .0+ }+ }+ None => {+ if output_only {+ candle_layer_norm::layer_norm_output_only(+ &hidden_states,+ &self.weight,+ self.bias.as_ref(),+ self.epsilon,+ )?+ } else {+ candle_layer_norm::layer_norm(+ &hidden_states,+ &self.weight,+ self.bias.as_ref(),+ self.epsilon,+ )?+ }+ }+ };+ Ok(Some(output.reshape(original_shape)?))+ }++ #[cfg(not(feature = "cuda"))]+ fn forward_cuda(+ &self,+ _hidden_states: &Tensor,+ _residual: Option<&Tensor>,+ ) -> Result<Option<Tensor>> {+ Ok(None)+ }++ pub(crate) fn backend(&self) -> &'static str {+ #[cfg(feature = "cuda")]+ if matches!(self.weight.device(), Device::Cuda(_)) {+ return if layer_norm_output_only_enabled() {+ "cuda_fused_layer_norm_output_only"+ } else {+ "cuda_fused_layer_norm"+ };+ }+ "candle_layer_norm"+ }+}++pub(crate) fn cublaslt_available(device: &Device) -> bool {+ matches!(device, Device::Cuda(_)) && cublaslt_available_inner(device)+}++pub(crate) fn index_select(tensor: &Tensor, indices: &Tensor, dim: usize) -> Result<Tensor> {+ #[cfg(feature = "cuda")]+ {+ if matches!(tensor.device(), Device::Cuda(_)) && matches!(indices.device(), Device::Cuda(_))+ {+ candle_index_select_cu::index_select(tensor, indices, dim)+ } else {+ tensor.index_select(indices, dim)+ }+ }+ #[cfg(not(feature = "cuda"))]+ {+ tensor.index_select(indices, dim)+ }+}++#[cfg(feature = "cuda")]+fn cublaslt_available_inner(device: &Device) -> bool {+ cublaslt_enabled() && cublaslt::get(device).is_some()+}++#[cfg(not(feature = "cuda"))]+fn cublaslt_available_inner(_device: &Device) -> bool {+ false+}++#[cfg(feature = "cuda")]+fn cublaslt_activation(act: Option<HiddenAct>) -> (Option<candle_cublaslt::Activation>, bool) {+ match act {+ Some(HiddenAct::Gelu) => (Some(candle_cublaslt::Activation::Gelu), true),+ Some(HiddenAct::Relu) => (Some(candle_cublaslt::Activation::Relu), true),+ _ => (None, act.is_none()),+ }+}++#[cfg(feature = "cuda")]+fn cublaslt_enabled() -> bool {+ static ENABLED: OnceLock<bool> = OnceLock::new();+ *ENABLED.get_or_init(|| {+ let disabled = env_bool_any(&["SIE_CANDLE_DISABLE_CUBLASLT"], false);+ let enabled = env_bool_any(&["SIE_CANDLE_ENABLE_CUBLASLT"], true);+ enabled && !disabled+ })+}++#[cfg(feature = "cuda")]+fn layer_norm_output_only_enabled() -> bool {+ static ENABLED: OnceLock<bool> = OnceLock::new();+ *ENABLED.get_or_init(|| {+ let disabled = std::env::var("SIE_CANDLE_DISABLE_LAYER_NORM_OUTPUT_ONLY").ok();+ layer_norm_output_only_enabled_from(disabled.as_deref())+ })+}++#[cfg(any(feature = "cuda", test))]+fn layer_norm_output_only_enabled_from(disabled: Option<&str>) -> bool {+ !env_bool_value(disabled, false)+}++#[cfg(feature = "cuda")]+fn env_bool_any(names: &[&str], default: bool) -> bool {+ let value = names.iter().find_map(|name| std::env::var(name).ok());+ env_bool_value(value.as_deref(), default)+}++#[cfg(any(feature = "cuda", test))]+fn env_bool_value(value: Option<&str>, default: bool) -> bool {+ value+ .map(|value| {+ matches!(+ value.trim().to_ascii_lowercase().as_str(),+ "1" | "true" | "yes" | "on"+ )+ })+ .unwrap_or(default)+}++#[cfg(feature = "cuda")]+mod cublaslt {+ use super::*;+ use candle_cublaslt::{fused_matmul, Activation, CublasLt};++ static INIT: Once = Once::new();+ static mut CUBLASLT: Option<CublasLt> = None;++ pub(super) fn get(device: &Device) -> Option<CublasLt> {+ unsafe {+ INIT.call_once(|| {+ CUBLASLT = match CublasLt::new(device) {+ Ok(cublaslt) => Some(cublaslt),+ Err(error) => {+ warn!(?error, "failed to initialize Candle cuBLASLt wrapper");+ None+ }+ };+ });+ #[allow(static_mut_refs)]+ CUBLASLT.clone()+ }+ }++ pub(super) trait CublasLtExt {+ fn matmul(+ &self,+ weight: &Tensor,+ input: &Tensor,+ bias: Option<&Tensor>,+ act: Option<Activation>,+ ) -> Result<Tensor>;+ }++ impl CublasLtExt for CublasLt {+ fn matmul(+ &self,+ weight: &Tensor,+ input: &Tensor,+ bias: Option<&Tensor>,+ act: Option<Activation>,+ ) -> Result<Tensor> {+ fused_matmul(weight, input, None, None, None, bias, act, self.clone())+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use candle::Device;++ #[test]+ fn hidden_act_gelu_uses_tanh_approximation() -> Result<()> {+ let xs = Tensor::new(&[-1f32, 0., 1.], &Device::Cpu)?;+ let fast = HiddenAct::Gelu.forward(&xs)?;+ let expected = xs.gelu()?;+ assert_eq!(fast.to_vec1::<f32>()?, expected.to_vec1::<f32>()?);+ Ok(())+ }++ #[test]+ fn fast_linear_matches_stock_linear_on_cpu() -> Result<()> {+ let device = Device::Cpu;+ let weight = Tensor::new(&[[1f32, 2.], [3., 4.], [5., 6.]], &device)?;+ let bias = Tensor::new(&[0.5f32, -0.5, 1.], &device)?;+ let layer = FastLinear {+ weight: weight.clone(),+ bias: Some(bias.clone()),+ act: None,+ };+ let xs = Tensor::new(&[[10f32, 100.], [1., 2.]], &device)?;+ let actual = layer.forward(&xs)?;+ let expected = xs.matmul(&weight.t()?)?.broadcast_add(&bias)?;+ assert_close_2d(&actual.to_vec2::<f32>()?, &expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn fast_linear_rank_three_matches_flattened_projection_on_cpu() -> Result<()> {+ let device = Device::Cpu;+ let weight = Tensor::new(&[[1f32, 2.], [3., 4.], [5., 6.]], &device)?;+ let bias = Tensor::new(&[0.5f32, -0.5, 1.], &device)?;+ let layer = FastLinear::new(weight.clone(), Some(bias.clone()), None);+ let xs = Tensor::new(+ &[+ [[1f32, 2.], [3., 4.], [5., 6.]],+ [[7., 8.], [9., 10.], [11., 12.]],+ ],+ &device,+ )?;++ let actual = layer.forward(&xs)?;+ let expected = xs+ .reshape((6, 2))?+ .matmul(&weight.t()?)?+ .broadcast_add(&bias)?+ .reshape((2, 3, 3))?;++ assert_eq!(actual.dims(), &[2, 3, 3]);+ assert_close_3d(&actual.to_vec3::<f32>()?, &expected.to_vec3::<f32>()?);+ Ok(())+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn fast_linear_rank_three_cublaslt_matches_flattened_projection_on_cuda() -> Result<()> {+ let device = Device::new_cuda(0)?;+ let weight_values = [[1f32, 2.], [3., 4.], [5., 6.]];+ let bias_values = [0.5f32, -0.5, 1.];+ let input_values = [+ [[1f32, 2.], [3., 4.], [5., 6.]],+ [[7., 8.], [9., 10.], [11., 12.]],+ ];++ for (dtype, tolerance) in [+ (DType::F32, 1e-5f32),+ (DType::F16, 0.02f32),+ (DType::BF16, 0.15f32),+ ] {+ let weight = Tensor::new(&weight_values, &device)?.to_dtype(dtype)?;+ let bias = Tensor::new(&bias_values, &device)?.to_dtype(dtype)?;+ let xs = Tensor::new(&input_values, &device)?.to_dtype(dtype)?;+ let layer = FastLinear::new(weight.clone(), Some(bias.clone()), Some(HiddenAct::Silu));++ let actual = layer+ .forward_cublaslt(&xs)?+ .expect("cuBLASLt should handle contiguous rank-three CUDA input");+ let expected = xs+ .reshape((6, 2))?+ .matmul(&weight.t()?)?+ .broadcast_add(&bias)?+ .silu()?+ .reshape((2, 3, 3))?;++ assert_eq!(actual.dims(), &[2, 3, 3]);+ let actual = actual.to_dtype(DType::F32)?.to_vec3::<f32>()?;+ let expected = expected.to_dtype(DType::F32)?.to_vec3::<f32>()?;+ assert_close_3d_with_tolerance(&actual, &expected, tolerance);+ }+ Ok(())+ }++ #[test]+ fn fast_linear_qkv_projection_preserves_projection_order() -> Result<()> {+ let device = Device::Cpu;+ let query = Tensor::new(&[[1f32, 2.]], &device)?;+ let key = Tensor::new(&[[3f32, 4.]], &device)?;+ let value = Tensor::new(&[[5f32, 6.]], &device)?;+ let qkv_weight = Tensor::cat(&[&query, &key, &value], 0)?;+ let qkv_bias = Tensor::new(&[0f32, 10., 100.], &device)?;+ let layer = FastLinear::new(qkv_weight, Some(qkv_bias), None);+ let output = layer.forward(&Tensor::new(&[[7f32, 11.]], &device)?)?;+ assert_eq!(output.to_vec2::<f32>()?, vec![vec![29., 75., 201.]]);+ Ok(())+ }++ #[test]+ fn fast_layer_norm_fuses_residual_semantics_on_cpu() -> Result<()> {+ let device = Device::Cpu;+ let hidden_states = Tensor::new(&[[1f32, 2., 3.], [4., 5., 6.]], &device)?;+ let residual = Tensor::new(&[[0.5f32, -1., 2.], [1., 0., -2.]], &device)?;+ let weight = Tensor::new(&[1f32, 0.5, 2.], &device)?;+ let bias = Tensor::new(&[0.1f32, -0.2, 0.3], &device)?;+ let layer_norm = FastLayerNorm {+ weight: weight.clone(),+ bias: Some(bias.clone()),+ epsilon: 1e-5,+ };+ let actual = layer_norm.forward(&hidden_states, Some(&residual))?;+ let expected = ops::layer_norm(&(hidden_states + residual)?, &weight, &bias, 1e-5)?;+ assert_close_2d(&actual.to_vec2::<f32>()?, &expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn layer_norm_output_only_kill_switch_parses_boolean_values() {+ assert!(layer_norm_output_only_enabled_from(None));+ assert!(!layer_norm_output_only_enabled_from(Some("1")));+ assert!(!layer_norm_output_only_enabled_from(Some(" YeS ")));+ assert!(layer_norm_output_only_enabled_from(Some("0")));+ assert!(layer_norm_output_only_enabled_from(Some("false")));+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn layer_norm_output_only_matches_reference_on_default_cuda_stream() -> Result<()> {+ assert_layer_norm_output_only_matches_reference(&Device::new_cuda(0)?)+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn layer_norm_output_only_matches_reference_on_non_default_cuda_stream() -> Result<()> {+ assert_layer_norm_output_only_matches_reference(&Device::new_cuda_with_stream(0)?)+ }++ #[cfg(feature = "cuda")]+ fn assert_layer_norm_output_only_matches_reference(device: &Device) -> Result<()> {+ let input_values = (0..24)+ .map(|value| (value as f32 - 12.) / 7.)+ .collect::<Vec<_>>();+ let residual_values = (0..24)+ .map(|value| (11. - value as f32) / 13.)+ .collect::<Vec<_>>();+ let gamma_values = (0..8)+ .map(|value| 0.75 + value as f32 / 16.)+ .collect::<Vec<_>>();+ let beta_values = (0..8)+ .map(|value| (value as f32 - 4.) / 20.)+ .collect::<Vec<_>>();++ for (dtype, tolerance) in [+ (DType::F32, 1e-3f32),+ (DType::F16, 0.02f32),+ (DType::BF16, 0.15f32),+ ] {+ let input = Tensor::from_vec(input_values.clone(), (3, 8), device)?.to_dtype(dtype)?;+ let residual =+ Tensor::from_vec(residual_values.clone(), (3, 8), device)?.to_dtype(dtype)?;+ let gamma = Tensor::from_vec(gamma_values.clone(), 8, device)?.to_dtype(dtype)?;+ let beta = Tensor::from_vec(beta_values.clone(), 8, device)?.to_dtype(dtype)?;++ let expected = ops::layer_norm(&input, &gamma, &beta, 1e-5)?;+ let output_only =+ candle_layer_norm::layer_norm_output_only(&input, &gamma, Some(&beta), 1e-5)?;+ assert_close_2d_with_tolerance(+ &output_only.to_dtype(DType::F32)?.to_vec2::<f32>()?,+ &expected.to_dtype(DType::F32)?.to_vec2::<f32>()?,+ tolerance,+ );++ let expected =+ ops::layer_norm(&(input.clone() + residual.clone())?, &gamma, &beta, 1e-5)?;+ let output_only = candle_layer_norm::fused_add_layer_norm_output_only(+ &input,+ &residual,+ &gamma,+ Some(&beta),+ 1e-5,+ )?;+ assert_close_2d_with_tolerance(+ &output_only.to_dtype(DType::F32)?.to_vec2::<f32>()?,+ &expected.to_dtype(DType::F32)?.to_vec2::<f32>()?,+ tolerance,+ );+ }+ Ok(())+ }++ #[test]+ fn fast_linear_no_bias_loader_matches_stock_linear_on_cpu() -> Result<()> {+ let device = Device::Cpu;+ let weight = Tensor::new(&[[1f32, 2.], [3., 4.], [5., 6.]], &device)?;+ let vb = VarBuilder::from_tensors(+ std::collections::HashMap::from([("weight".to_string(), weight.clone())]),+ DType::F32,+ &device,+ );+ let layer = FastLinear::load_no_bias(2, 3, vb, None)?;+ let xs = Tensor::new(&[[10f32, 100.], [1., 2.]], &device)?;++ let actual = layer.forward(&xs)?;+ let expected = xs.matmul(&weight.t()?)?;++ assert!(layer.bias.is_none());+ assert_close_2d(&actual.to_vec2::<f32>()?, &expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn fast_layer_norm_no_bias_loader_matches_stock_layer_norm_on_cpu() -> Result<()> {+ let device = Device::Cpu;+ let weight = Tensor::new(&[1f32, 0.5, 2.], &device)?;+ let vb = VarBuilder::from_tensors(+ std::collections::HashMap::from([("weight".to_string(), weight.clone())]),+ DType::F32,+ &device,+ );+ let layer_norm = FastLayerNorm::load_no_bias(vb, 3, 1e-5)?;+ let xs = Tensor::new(&[[1f32, 2., 3.], [4., 5., 7.]], &device)?;++ let actual = layer_norm.forward(&xs, None)?;+ let expected = xs.apply(&candle_nn::LayerNorm::new_no_bias(weight, 1e-5))?;++ assert!(layer_norm.bias.is_none());+ assert_eq!(layer_norm.backend(), "candle_layer_norm");+ assert_close_2d(&actual.to_vec2::<f32>()?, &expected.to_vec2::<f32>()?);+ Ok(())+ }++ fn assert_close_2d(actual: &[Vec<f32>], expected: &[Vec<f32>]) {+ assert_close_2d_with_tolerance(actual, expected, 1e-5);+ }++ fn assert_close_2d_with_tolerance(actual: &[Vec<f32>], expected: &[Vec<f32>], tolerance: f32) {+ assert_eq!(actual.len(), expected.len());+ for (actual_row, expected_row) in actual.iter().zip(expected) {+ assert_eq!(actual_row.len(), expected_row.len());+ for (&actual, &expected) in actual_row.iter().zip(expected_row) {+ assert!(+ (actual - expected).abs() < tolerance,+ "actual={actual} expected={expected} tolerance={tolerance}"+ );+ }+ }+ }++ fn assert_close_3d(actual: &[Vec<Vec<f32>>], expected: &[Vec<Vec<f32>>]) {+ assert_close_3d_with_tolerance(actual, expected, 1e-5);+ }++ fn assert_close_3d_with_tolerance(+ actual: &[Vec<Vec<f32>>],+ expected: &[Vec<Vec<f32>>],+ tolerance: f32,+ ) {+ assert_eq!(actual.len(), expected.len());+ for (actual_matrix, expected_matrix) in actual.iter().zip(expected) {+ assert_eq!(actual_matrix.len(), expected_matrix.len());+ for (actual_row, expected_row) in actual_matrix.iter().zip(expected_matrix) {+ assert_eq!(actual_row.len(), expected_row.len());+ for (&actual, &expected) in actual_row.iter().zip(expected_row) {+ assert!(+ (actual - expected).abs() <= tolerance,+ "actual={actual} expected={expected} tolerance={tolerance}"+ );+ }+ }+ }+ }+}diff --git a/packages/sie_server_rust/src/candle_modernbert.rs b/packages/sie_server_rust/src/candle_modernbert.rsnew file mode 100644index 000000000..8e15afdad--- /dev/null+++ b/packages/sie_server_rust/src/candle_modernbert.rs@@ -0,0 +1,1309 @@+//! Local ModernBERT backbone wrapper for Candle embedding models.+//!+//! This mirrors `candle_transformers::models::modernbert::ModernBert`+//! closely, but keeps the attention mask dtype aligned with the attention+//! logits before adding it. The upstream implementation builds the mask in+//! F32, which fails on BF16 ModernBERT checkpoints on CUDA.++use std::collections::HashMap;+use std::sync::Arc;+use std::time::Instant;++use crate::candle_layers::{index_select, FastLayerNorm, FastLinear};+use crate::candle_rope::apply_rotary_packed_inplace;+use candle::{DType, Device, Result, Tensor, D};+use candle_nn::{embedding, ops::softmax, Embedding, Module, VarBuilder};+use serde::Deserialize;++#[derive(Debug, Clone, PartialEq, Deserialize)]+pub struct Config {+ pub vocab_size: usize,+ pub hidden_size: usize,+ pub num_hidden_layers: usize,+ pub num_attention_heads: usize,+ pub intermediate_size: usize,+ pub max_position_embeddings: usize,+ #[serde(default = "default_norm_eps")]+ pub norm_eps: f64,+ #[serde(default)]+ pub norm_bias: bool,+ #[serde(default)]+ pub attention_bias: bool,+ #[serde(default)]+ pub mlp_bias: bool,+ #[serde(default = "default_hidden_activation")]+ pub hidden_activation: String,+ pub pad_token_id: u32,+ pub global_attn_every_n_layers: usize,+ pub global_rope_theta: f64,+ pub local_attention: usize,+ pub local_rope_theta: f64,+ #[serde(default)]+ pub rope_scaling: Option<serde_json::Value>,+ #[serde(default)]+ pub rope_parameters: Option<serde_json::Value>,+ #[serde(default)]+ #[serde(flatten)]+ pub classifier_config: Option<ClassifierConfig>,+}++fn default_norm_eps() -> f64 {+ 1e-5+}++fn default_hidden_activation() -> String {+ "gelu".to_string()+}++#[derive(Debug, Clone, Deserialize, PartialEq, Copy, Default)]+#[serde(rename_all = "lowercase")]+pub enum ClassifierPooling {+ #[default]+ Cls,+ Mean,+}++#[derive(Debug, Clone, PartialEq, Deserialize)]+pub struct ClassifierConfig {+ pub id2label: HashMap<String, String>,+ pub label2id: HashMap<String, String>,+ pub classifier_pooling: ClassifierPooling,+}++impl Config {+ pub(crate) fn validate(&self) -> Result<()> {+ if self.vocab_size == 0 {+ candle::bail!("ModernBERT vocab_size must be greater than zero");+ }+ if self.pad_token_id as usize >= self.vocab_size {+ candle::bail!(+ "ModernBERT pad_token_id {} must be below vocab_size {}",+ self.pad_token_id,+ self.vocab_size+ );+ }+ if self.hidden_size == 0 {+ candle::bail!("ModernBERT hidden_size must be greater than zero");+ }+ if self.num_hidden_layers == 0 {+ candle::bail!("ModernBERT num_hidden_layers must be greater than zero");+ }+ if self.num_attention_heads == 0 {+ candle::bail!("ModernBERT num_attention_heads must be greater than zero");+ }+ if !self.hidden_size.is_multiple_of(self.num_attention_heads) {+ candle::bail!(+ "ModernBERT hidden_size {} must be divisible by num_attention_heads {}",+ self.hidden_size,+ self.num_attention_heads+ );+ }+ if self.hidden_size.checked_mul(3).is_none() {+ candle::bail!("ModernBERT hidden_size is too large");+ }+ let head_size = self.hidden_size / self.num_attention_heads;+ if !head_size.is_multiple_of(2) {+ candle::bail!("ModernBERT attention head size {head_size} must be even for RoPE");+ }+ if self.global_attn_every_n_layers == 0 {+ candle::bail!("ModernBERT global_attn_every_n_layers must be greater than zero");+ }+ if self.intermediate_size == 0 {+ candle::bail!("ModernBERT intermediate_size must be greater than zero");+ }+ if self.intermediate_size > i32::MAX as usize+ || self.intermediate_size.checked_mul(2).is_none()+ {+ candle::bail!("ModernBERT intermediate_size must fit the CUDA gated-activation ABI");+ }+ if self.max_position_embeddings == 0 || self.max_position_embeddings > i32::MAX as usize {+ candle::bail!("ModernBERT max_position_embeddings must be in 1..=i32::MAX");+ }+ if !self.norm_eps.is_finite() || self.norm_eps <= 0.0 {+ candle::bail!("ModernBERT norm_eps must be finite and greater than zero");+ }+ let uses_local_attention =+ (0..self.num_hidden_layers).any(|layer| layer % self.global_attn_every_n_layers != 0);+ if uses_local_attention+ && (self.local_attention == 0 || self.local_attention / 2 > i32::MAX as usize)+ {+ candle::bail!(+ "ModernBERT local_attention must be positive and its half-window must fit i32 when local-attention layers are present"+ );+ }+ if self.norm_bias || self.attention_bias || self.mlp_bias {+ candle::bail!(+ "ModernBERT Candle supports only norm_bias=false, attention_bias=false, and mlp_bias=false"+ );+ }+ if self.hidden_activation != "gelu" {+ candle::bail!(+ "ModernBERT Candle supports only hidden_activation=gelu, got {}",+ self.hidden_activation+ );+ }+ for (name, theta) in [+ ("global_rope_theta", self.global_rope_theta),+ ("local_rope_theta", self.local_rope_theta),+ ] {+ if !theta.is_finite() || theta <= 0.0 {+ candle::bail!("ModernBERT {name} must be finite and greater than zero");+ }+ }+ self.validate_rope_configuration()?;+ Ok(())+ }++ fn validate_rope_configuration(&self) -> Result<()> {+ if let Some(rope_scaling) = self.rope_scaling.as_ref() {+ let params = rope_scaling.as_object().ok_or_else(|| {+ candle::Error::msg("ModernBERT rope_scaling must be an object when present")+ })?;+ let rope_type = validated_rope_type(params, "rope_scaling")?;+ if rope_type != "default"+ || params.keys().any(|key| key != "rope_type" && key != "type")+ {+ candle::bail!(+ "ModernBERT Candle supports only default, unscaled rope_scaling metadata"+ );+ }+ }++ let Some(rope_parameters) = self.rope_parameters.as_ref() else {+ return Ok(());+ };+ let attention_parameters = rope_parameters.as_object().ok_or_else(|| {+ candle::Error::msg("ModernBERT rope_parameters must be an object when present")+ })?;+ if attention_parameters.len() != 2 {+ candle::bail!(+ "ModernBERT rope_parameters must contain exactly full_attention and sliding_attention"+ );+ }+ for (attention_kind, expected_theta) in [+ ("full_attention", self.global_rope_theta),+ ("sliding_attention", self.local_rope_theta),+ ] {+ let params = attention_parameters+ .get(attention_kind)+ .and_then(serde_json::Value::as_object)+ .ok_or_else(|| {+ candle::Error::msg(format!(+ "ModernBERT rope_parameters is missing object {attention_kind}"+ ))+ })?;+ let rope_type =+ validated_rope_type(params, &format!("rope_parameters.{attention_kind}"))?;+ let theta = params+ .get("rope_theta")+ .and_then(serde_json::Value::as_f64)+ .ok_or_else(|| {+ candle::Error::msg(format!(+ "ModernBERT rope_parameters.{attention_kind}.rope_theta must be numeric"+ ))+ })?;+ if rope_type != "default"+ || params+ .keys()+ .any(|key| key != "rope_theta" && key != "rope_type" && key != "type")+ || theta != expected_theta+ {+ candle::bail!(+ "ModernBERT Candle supports only matching default {attention_kind} RoPE parameters"+ );+ }+ }+ Ok(())+ }+}++fn validated_rope_type<'a>(+ params: &'a serde_json::Map<String, serde_json::Value>,+ context: &str,+) -> Result<&'a str> {+ let rope_type = params+ .get("rope_type")+ .map(|value| {+ value.as_str().ok_or_else(|| {+ candle::Error::msg(format!("ModernBERT {context}.rope_type must be a string"))+ })+ })+ .transpose()?;+ let legacy_type = params+ .get("type")+ .map(|value| {+ value.as_str().ok_or_else(|| {+ candle::Error::msg(format!("ModernBERT {context}.type must be a string"))+ })+ })+ .transpose()?;+ if let (Some(rope_type), Some(legacy_type)) = (rope_type, legacy_type) {+ if rope_type != legacy_type {+ candle::bail!(+ "ModernBERT {context}.rope_type={rope_type} conflicts with type={legacy_type}"+ );+ }+ }+ Ok(rope_type.or(legacy_type).unwrap_or("default"))+}++#[derive(Debug, Clone, Copy, Default)]+pub struct ModernBertForwardProfile {+ pub total_tokens: usize,+ pub max_seqlen: usize,+ pub hidden_size: usize,+ pub intermediate_size: usize,+ pub attention_heads: usize,+ pub attention_head_size: usize,+ pub linear_gflops: f64,+ pub embedding_ms: f64,+ pub embedding_norm_ms: f64,+ pub rope_select_ms: f64,+ pub attention_ms: f64,+ pub attention_norm_ms: f64,+ pub attention_qkv_ms: f64,+ pub attention_rotary_ms: f64,+ pub attention_flash_ms: f64,+ pub attention_output_dense_ms: f64,+ pub mlp_ms: f64,+ pub mlp_norm_ms: f64,+ pub mlp_wi_ms: f64,+ pub mlp_activation_ms: f64,+ pub mlp_wo_ms: f64,+ pub final_norm_ms: f64,+ pub layers: usize,+}++#[derive(Clone, Copy)]+struct ModernBertPackedForward<'a> {+ seqlens: &'a Tensor,+ cos: &'a Tensor,+ sin: &'a Tensor,+ max_seqlen: usize,+ window_size: Option<usize>,+}++struct PackedRotaryEmbeddings {+ global: (Tensor, Tensor),+ local: Option<(Tensor, Tensor)>,+}++impl PackedRotaryEmbeddings {+ fn new(+ global: &RotaryEmbedding,+ local: &RotaryEmbedding,+ position_ids: &Tensor,+ has_local_layers: bool,+ ) -> Result<Self> {+ Ok(Self {+ global: global.packed_cos_sin(position_ids)?,+ local: has_local_layers+ .then(|| local.packed_cos_sin(position_ids))+ .transpose()?,+ })+ }++ fn for_layer(&self, uses_local_attention: bool) -> (&Tensor, &Tensor) {+ if uses_local_attention {+ let (cos, sin) = self+ .local+ .as_ref()+ .expect("local RoPE is precomputed when a local-attention layer exists");+ (cos, sin)+ } else {+ (&self.global.0, &self.global.1)+ }+ }+}++#[derive(Debug, Clone)]+struct RotaryEmbedding {+ sin: Tensor,+ cos: Tensor,+}++impl RotaryEmbedding {+ fn new(dtype: DType, config: &Config, rope_theta: f64, dev: &Device) -> Result<Self> {+ let dim = config.hidden_size / config.num_attention_heads;+ let inv_freq: Vec<_> = (0..dim)+ .step_by(2)+ .map(|i| 1f32 / rope_theta.powf(i as f64 / dim as f64) as f32)+ .collect();+ let inv_freq_len = inv_freq.len();+ let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?;+ let max_seq_len = config.max_position_embeddings;+ let t = Tensor::arange(0u32, max_seq_len as u32, dev)?+ .to_dtype(dtype)?+ .reshape((max_seq_len, 1))?;+ let freqs = t.matmul(&inv_freq)?;+ Ok(Self {+ sin: freqs.sin()?,+ cos: freqs.cos()?,+ })+ }++ fn apply_rotary_emb_qkv(&self, q: &Tensor, k: &Tensor) -> Result<(Tensor, Tensor)> {+ let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &self.cos, &self.sin)?;+ let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &self.cos, &self.sin)?;+ Ok((q_embed, k_embed))+ }++ fn packed_cos_sin(&self, position_ids: &Tensor) -> Result<(Tensor, Tensor)> {+ Ok((+ index_select(&self.cos, position_ids, 0)?,+ index_select(&self.sin, position_ids, 0)?,+ ))+ }+}++#[derive(Clone)]+struct ModernBertAttention {+ qkv: FastLinear,+ proj: FastLinear,+ num_attention_heads: usize,+ attention_head_size: usize,+ rotary_emb: Arc<RotaryEmbedding>,+}++impl ModernBertAttention {+ fn load(vb: VarBuilder, config: &Config, rotary_emb: Arc<RotaryEmbedding>) -> Result<Self> {+ let num_attention_heads = config.num_attention_heads;+ let attention_head_size = config.hidden_size / config.num_attention_heads;++ let qkv = FastLinear::load_no_bias(+ config.hidden_size,+ config.hidden_size * 3,+ vb.pp("Wqkv"),+ None,+ )?;+ let proj =+ FastLinear::load_no_bias(config.hidden_size, config.hidden_size, vb.pp("Wo"), None)?;++ Ok(Self {+ qkv,+ proj,+ num_attention_heads,+ attention_head_size,+ rotary_emb,+ })+ }++ fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> {+ let xs = hidden_states.clone();+ let (b, seq_len, d) = xs.dims3()?;+ let qkv = self+ .qkv+ .forward(&xs)?+ .reshape((+ b,+ seq_len,+ 3,+ self.num_attention_heads,+ self.attention_head_size,+ ))?+ .permute((2, 0, 3, 1, 4))?;++ let q = qkv.get(0)?;+ let k = qkv.get(1)?;+ let v = qkv.get(2)?;++ let (q, k) = self.rotary_emb.apply_rotary_emb_qkv(&q, &k)?;++ let scale = (self.attention_head_size as f64).powf(-0.5);+ let q = (q * scale)?;++ let att = q.matmul(&k.transpose(D::Minus2, D::Minus1)?)?;+ let attention_mask = if attention_mask.dtype() == att.dtype() {+ attention_mask.clone()+ } else {+ attention_mask.to_dtype(att.dtype())?+ };+ let att = att.broadcast_add(&attention_mask)?;+ let att = softmax(&att, D::Minus1)?;++ let xs = att.matmul(&v)?;++ let xs = xs.transpose(1, 2)?.reshape((b, seq_len, d))?;+ let xs = self.proj.forward(&xs)?;+ let xs = xs.reshape((b, seq_len, d))?;++ Ok(xs)+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ window_size: Option<usize>,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;+ let qkv = self.qkv.forward(hidden_states)?.reshape((+ total_tokens,+ self.num_attention_heads * 3,+ self.attention_head_size,+ ))?;++ let query = qkv.narrow(1, 0, self.num_attention_heads)?;+ let key = qkv.narrow(1, self.num_attention_heads, self.num_attention_heads)?;+ let value = qkv.narrow(1, self.num_attention_heads * 2, self.num_attention_heads)?;++ apply_rotary_packed_inplace(&query, &key, cos, sin)?;++ let attention_output = flash_attn_varlen_windowed(+ &query,+ &key,+ &value,+ seqlens,+ max_seqlen,+ self.attention_head_size,+ window_size,+ )?;+ let attention_output = attention_output.reshape((+ total_tokens,+ self.num_attention_heads * self.attention_head_size,+ ))?;+ self.proj.forward(&attention_output)+ }++ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ ctx: ModernBertPackedForward<'_>,+ profile: &mut ModernBertForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let attention_start = Instant::now();+ let total_tokens = hidden_states.dim(0)?;+ let qkv_start = Instant::now();+ let qkv = self.qkv.forward(hidden_states)?.reshape((+ total_tokens,+ self.num_attention_heads * 3,+ self.attention_head_size,+ ))?;+ let query = qkv.narrow(1, 0, self.num_attention_heads)?;+ let key = qkv.narrow(1, self.num_attention_heads, self.num_attention_heads)?;+ let value = qkv.narrow(1, self.num_attention_heads * 2, self.num_attention_heads)?;+ synchronize_if(hidden_states.device(), sync_timings)?;+ profile.attention_qkv_ms += elapsed_ms(qkv_start);++ let rotary_start = Instant::now();+ apply_rotary_packed_inplace(&query, &key, ctx.cos, ctx.sin)?;+ synchronize_if(hidden_states.device(), sync_timings)?;+ profile.attention_rotary_ms += elapsed_ms(rotary_start);++ let flash_start = Instant::now();+ let attention_output = flash_attn_varlen_windowed(+ &query,+ &key,+ &value,+ ctx.seqlens,+ ctx.max_seqlen,+ self.attention_head_size,+ ctx.window_size,+ )?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_flash_ms += elapsed_ms(flash_start);++ let output_start = Instant::now();+ let attention_output = attention_output.reshape((+ total_tokens,+ self.num_attention_heads * self.attention_head_size,+ ))?;+ let output = self.proj.forward(&attention_output)?;+ synchronize_if(output.device(), sync_timings)?;+ profile.attention_output_dense_ms += elapsed_ms(output_start);+ profile.attention_ms += elapsed_ms(attention_start);+ Ok(output)+ }+}++#[derive(Clone)]+struct ModernBertGatedActivation {+ intermediate_size: usize,+ #[cfg(feature = "cuda")]+ cuda: candle_gated_activation::GeluErfGate,+}++impl ModernBertGatedActivation {+ fn new(intermediate_size: usize) -> Result<Self> {+ if intermediate_size == 0 {+ candle::bail!("ModernBERT intermediate_size must be greater than zero");+ }+ Ok(Self {+ intermediate_size,+ #[cfg(feature = "cuda")]+ cuda: candle_gated_activation::GeluErfGate::new(intermediate_size)?,+ })+ }++ fn forward(&self, xs: &Tensor) -> Result<Tensor> {+ let width = xs.dim(D::Minus1)?;+ let expected_width = self+ .intermediate_size+ .checked_mul(2)+ .ok_or_else(|| candle::Error::msg("ModernBERT MLP activation width overflow"))?;+ if width != expected_width {+ candle::bail!("ModernBERT MLP activation expected width {expected_width}, got {width}");+ }++ #[cfg(feature = "cuda")]+ if matches!(xs.device(), Device::Cuda(_)) && xs.is_contiguous() {+ return self.cuda.forward(xs);+ }++ let xs = xs.chunk(2, D::Minus1)?;+ &xs[0].gelu_erf()? * &xs[1]+ }+}++#[derive(Clone)]+struct ModernBertMLP {+ wi: FastLinear,+ wo: FastLinear,+ activation: ModernBertGatedActivation,+}++impl ModernBertMLP {+ fn load(+ vb: VarBuilder,+ config: &Config,+ activation: ModernBertGatedActivation,+ ) -> Result<Self> {+ let wi = FastLinear::load_no_bias(+ config.hidden_size,+ config.intermediate_size * 2,+ vb.pp("Wi"),+ None,+ )?;+ let wo = FastLinear::load_no_bias(+ config.intermediate_size,+ config.hidden_size,+ vb.pp("Wo"),+ None,+ )?;+ Ok(Self { wi, wo, activation })+ }++ fn activate(&self, xs: &Tensor) -> Result<Tensor> {+ self.activation.forward(xs)+ }+}++impl Module for ModernBertMLP {+ fn forward(&self, xs: &Tensor) -> Result<Tensor> {+ let xs = self.wi.forward(xs)?;+ self.wo.forward(&self.activate(&xs)?)+ }+}++impl ModernBertMLP {+ fn forward_profiled(+ &self,+ xs: &Tensor,+ profile: &mut ModernBertForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let mlp_start = Instant::now();+ let wi_start = Instant::now();+ let xs = self.wi.forward(xs)?;+ synchronize_if(xs.device(), sync_timings)?;+ profile.mlp_wi_ms += elapsed_ms(wi_start);++ let activation_start = Instant::now();+ let xs = self.activate(&xs)?;+ synchronize_if(xs.device(), sync_timings)?;+ profile.mlp_activation_ms += elapsed_ms(activation_start);++ let wo_start = Instant::now();+ let xs = self.wo.forward(&xs)?;+ synchronize_if(xs.device(), sync_timings)?;+ profile.mlp_wo_ms += elapsed_ms(wo_start);+ profile.mlp_ms += elapsed_ms(mlp_start);+ Ok(xs)+ }+}++#[derive(Clone)]+struct ModernBertLayer {+ attn: ModernBertAttention,+ mlp: ModernBertMLP,+ attn_norm: Option<FastLayerNorm>,+ mlp_norm: FastLayerNorm,+ uses_local_attention: bool,+}++impl ModernBertLayer {+ fn load(+ vb: VarBuilder,+ config: &Config,+ rotary_emb: Arc<RotaryEmbedding>,+ layer_id: usize,+ uses_local_attention: bool,+ activation: ModernBertGatedActivation,+ ) -> Result<Self> {+ let attn = ModernBertAttention::load(vb.pp("attn"), config, rotary_emb)?;+ let mlp = ModernBertMLP::load(vb.pp("mlp"), config, activation)?;+ let attn_norm = if layer_id == 0 {+ None+ } else {+ Some(FastLayerNorm::load_no_bias(+ vb.pp("attn_norm"),+ config.hidden_size,+ config.norm_eps,+ )?)+ };+ let mlp_norm =+ FastLayerNorm::load_no_bias(vb.pp("mlp_norm"), config.hidden_size, config.norm_eps)?;+ Ok(Self {+ attn,+ mlp,+ attn_norm,+ mlp_norm,+ uses_local_attention,+ })+ }++ fn forward(+ &self,+ xs: &Tensor,+ global_attention_mask: &Tensor,+ local_attention_mask: &Tensor,+ ) -> Result<Tensor> {+ let residual = xs.clone();+ let mut xs = xs.clone();+ if let Some(norm) = &self.attn_norm {+ xs = norm.forward(&xs, None)?;+ }++ let attention_mask = if self.uses_local_attention {+ global_attention_mask.broadcast_add(local_attention_mask)?+ } else {+ global_attention_mask.clone()+ };+ let xs = self.attn.forward(&xs, &attention_mask)?;+ let xs = (xs + residual)?;+ let mlp_out = self.mlp.forward(&self.mlp_norm.forward(&xs, None)?)?;+ let xs = (xs + mlp_out)?;+ Ok(xs)+ }++ fn forward_packed(+ &self,+ xs: &Tensor,+ seqlens: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+ max_seqlen: usize,+ local_window_size: Option<usize>,+ ) -> Result<Tensor> {+ let residual = xs.clone();+ let mut xs = xs.clone();+ if let Some(norm) = &self.attn_norm {+ xs = norm.forward(&xs, None)?;+ }++ let window_size = if self.uses_local_attention {+ local_window_size+ } else {+ None+ };+ let xs = self+ .attn+ .forward_packed(&xs, seqlens, cos, sin, max_seqlen, window_size)?;+ let xs = (xs + residual)?;+ let mlp_out = self.mlp.forward(&self.mlp_norm.forward(&xs, None)?)?;+ let xs = (xs + mlp_out)?;+ Ok(xs)+ }++ fn forward_packed_profiled(+ &self,+ xs: &Tensor,+ ctx: ModernBertPackedForward<'_>,+ profile: &mut ModernBertForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let residual = xs.clone();+ let mut xs = xs.clone();+ if let Some(norm) = &self.attn_norm {+ let norm_start = Instant::now();+ xs = norm.forward(&xs, None)?;+ synchronize_if(xs.device(), sync_timings)?;+ profile.attention_norm_ms += elapsed_ms(norm_start);+ }++ let window_size = if self.uses_local_attention {+ ctx.window_size+ } else {+ None+ };+ let attention_ctx = ModernBertPackedForward { window_size, ..ctx };+ let xs = self+ .attn+ .forward_packed_profiled(&xs, attention_ctx, profile, sync_timings)?;+ let xs = (xs + residual)?;++ let mlp_norm_start = Instant::now();+ let mlp_input = self.mlp_norm.forward(&xs, None)?;+ synchronize_if(mlp_input.device(), sync_timings)?;+ profile.mlp_norm_ms += elapsed_ms(mlp_norm_start);++ let mlp_out = self+ .mlp+ .forward_profiled(&mlp_input, profile, sync_timings)?;+ let xs = (xs + mlp_out)?;+ profile.layers += 1;+ Ok(xs)+ }+}++#[derive(Clone)]+pub struct ModernBert {+ word_embeddings: Embedding,+ norm: FastLayerNorm,+ global_rotary_emb: Arc<RotaryEmbedding>,+ local_rotary_emb: Arc<RotaryEmbedding>,+ layers: Vec<ModernBertLayer>,+ final_norm: FastLayerNorm,+ local_attention_size: usize,+ hidden_size: usize,+ intermediate_size: usize,+ num_hidden_layers: usize,+ num_attention_heads: usize,+}++impl ModernBert {+ pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ config.validate()?;+ let word_embeddings = embedding(+ config.vocab_size,+ config.hidden_size,+ vb.pp("model.embeddings.tok_embeddings"),+ )?;+ let norm = FastLayerNorm::load_no_bias(+ vb.pp("model.embeddings.norm"),+ config.hidden_size,+ config.norm_eps,+ )?;+ let global_rotary_emb = Arc::new(RotaryEmbedding::new(+ vb.dtype(),+ config,+ config.global_rope_theta,+ vb.device(),+ )?);+ let local_rotary_emb = Arc::new(RotaryEmbedding::new(+ vb.dtype(),+ config,+ config.local_rope_theta,+ vb.device(),+ )?);++ let activation = ModernBertGatedActivation::new(config.intermediate_size)?;+ let mut layers = Vec::with_capacity(config.num_hidden_layers);+ for layer_id in 0..config.num_hidden_layers {+ let layer_uses_local_attention = layer_id % config.global_attn_every_n_layers != 0;+ layers.push(ModernBertLayer::load(+ vb.pp(format!("model.layers.{layer_id}")),+ config,+ if layer_uses_local_attention {+ local_rotary_emb.clone()+ } else {+ global_rotary_emb.clone()+ },+ layer_id,+ layer_uses_local_attention,+ activation.clone(),+ )?);+ }++ let final_norm = FastLayerNorm::load_no_bias(+ vb.pp("model.final_norm"),+ config.hidden_size,+ config.norm_eps,+ )?;++ Ok(Self {+ word_embeddings,+ norm,+ global_rotary_emb,+ local_rotary_emb,+ layers,+ final_norm,+ local_attention_size: config.local_attention,+ hidden_size: config.hidden_size,+ intermediate_size: config.intermediate_size,+ num_hidden_layers: config.num_hidden_layers,+ num_attention_heads: config.num_attention_heads,+ })+ }++ pub fn kernel_backend(&self) -> (&'static str, &'static str) {+ let linear_backend = self+ .layers+ .first()+ .map(|layer| layer.attn.qkv.backend())+ .unwrap_or("candle_matmul");+ (linear_backend, self.norm.backend())+ }++ pub fn forward(&self, xs: &Tensor, mask: &Tensor) -> Result<Tensor> {+ let seq_len = xs.shape().dims()[1];+ let global_attention_mask =+ prepare_4d_attention_mask(mask, DType::F32, None)?.to_device(xs.device())?;+ let local_attention_mask =+ get_local_attention_mask(seq_len, self.local_attention_size / 2, xs.device())?;+ let embeddings = xs.apply(&self.word_embeddings)?;+ let mut xs = self.norm.forward(&embeddings, None)?;+ for layer in self.layers.iter() {+ xs = layer.forward(&xs, &global_attention_mask, &local_attention_mask)?;+ }+ let xs = self.final_norm.forward(&xs, None)?;+ Ok(xs)+ }++ pub fn forward_packed(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let embeddings = input_ids.apply(&self.word_embeddings)?;+ let mut xs = self.norm.forward(&embeddings, None)?;+ let rope = PackedRotaryEmbeddings::new(+ &self.global_rotary_emb,+ &self.local_rotary_emb,+ position_ids,+ self.layers.iter().any(|layer| layer.uses_local_attention),+ )?;+ let local_window_size =+ (self.local_attention_size > 0).then_some(self.local_attention_size / 2);+ for layer in self.layers.iter() {+ let (cos, sin) = rope.for_layer(layer.uses_local_attention);+ xs = layer.forward_packed(&xs, seqlens, cos, sin, max_seqlen, local_window_size)?;+ }+ self.final_norm.forward(&xs, None)+ }++ pub fn forward_packed_profiled(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ sync_timings: bool,+ ) -> Result<(Tensor, ModernBertForwardProfile)> {+ synchronize_if(input_ids.device(), sync_timings)?;+ let embedding_start = Instant::now();+ let mut xs = input_ids.apply(&self.word_embeddings)?;+ synchronize_if(xs.device(), sync_timings)?;+ let embedding_ms = elapsed_ms(embedding_start);++ let norm_start = Instant::now();+ xs = self.norm.forward(&xs, None)?;+ synchronize_if(xs.device(), sync_timings)?;+ let embedding_norm_ms = elapsed_ms(norm_start);++ let rope_select_start = Instant::now();+ let rope = PackedRotaryEmbeddings::new(+ &self.global_rotary_emb,+ &self.local_rotary_emb,+ position_ids,+ self.layers.iter().any(|layer| layer.uses_local_attention),+ )?;+ synchronize_if(input_ids.device(), sync_timings)?;+ let rope_select_ms = elapsed_ms(rope_select_start);++ let total_tokens = input_ids.dim(0)?;+ let mut profile = ModernBertForwardProfile {+ total_tokens,+ max_seqlen,+ hidden_size: self.hidden_size,+ intermediate_size: self.intermediate_size,+ attention_heads: self.num_attention_heads,+ attention_head_size: self.hidden_size / self.num_attention_heads,+ linear_gflops: linear_gflops(+ total_tokens,+ self.hidden_size,+ self.intermediate_size,+ self.num_hidden_layers,+ ),+ embedding_ms,+ embedding_norm_ms,+ rope_select_ms,+ ..Default::default()+ };++ let local_window_size =+ (self.local_attention_size > 0).then_some(self.local_attention_size / 2);+ for layer in self.layers.iter() {+ let (cos, sin) = rope.for_layer(layer.uses_local_attention);+ let ctx = ModernBertPackedForward {+ seqlens,+ cos,+ sin,+ max_seqlen,+ window_size: local_window_size,+ };+ xs = layer.forward_packed_profiled(&xs, ctx, &mut profile, sync_timings)?;+ }++ let final_norm_start = Instant::now();+ let xs = self.final_norm.forward(&xs, None)?;+ synchronize_if(xs.device(), sync_timings)?;+ profile.final_norm_ms = elapsed_ms(final_norm_start);+ Ok((xs, profile))+ }+}++fn prepare_4d_attention_mask(+ mask: &Tensor,+ dtype: DType,+ tgt_len: Option<usize>,+) -> Result<Tensor> {+ let bsz = mask.dim(0)?;+ let src_len = mask.dim(1)?;+ let tgt_len = tgt_len.unwrap_or(src_len);++ let expanded_mask = mask+ .unsqueeze(1)?+ .unsqueeze(2)?+ .expand((bsz, 1, tgt_len, src_len))?+ .to_dtype(dtype)?;++ let inverted_mask = (1.0 - expanded_mask)?;++ (inverted_mask * f32::MIN as f64)?.to_dtype(dtype)+}++fn get_local_attention_mask(+ seq_len: usize,+ max_distance: usize,+ device: &Device,+) -> Result<Tensor> {+ let mask: Vec<_> = (0..seq_len)+ .flat_map(|i| {+ (0..seq_len).map(move |j| {+ if (j as i32 - i as i32).abs() > max_distance as i32 {+ f32::NEG_INFINITY+ } else {+ 0.+ }+ })+ })+ .collect();+ Tensor::from_slice(&mask, (seq_len, seq_len), device)+}++fn synchronize_if(device: &Device, enabled: bool) -> Result<()> {+ if enabled {+ device.synchronize()?;+ }+ Ok(())+}++fn elapsed_ms(start: Instant) -> f64 {+ start.elapsed().as_secs_f64() * 1000.0+}++fn linear_gflops(+ total_tokens: usize,+ hidden_size: usize,+ intermediate_size: usize,+ layers: usize,+) -> f64 {+ let tokens = total_tokens as f64;+ let hidden = hidden_size as f64;+ let intermediate = intermediate_size as f64;+ let layers = layers as f64;+ let attention_qkv = 2.0 * tokens * hidden * (3.0 * hidden);+ let attention_output = 2.0 * tokens * hidden * hidden;+ let mlp_wi = 2.0 * tokens * hidden * (2.0 * intermediate);+ let mlp_wo = 2.0 * tokens * intermediate * hidden;+ (attention_qkv + attention_output + mlp_wi + mlp_wo) * layers / 1e9+}++#[cfg(feature = "cuda")]+fn flash_attn_varlen_windowed(+ query: &Tensor,+ key: &Tensor,+ value: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ head_size: usize,+ window_size: Option<usize>,+) -> Result<Tensor> {+ let softmax_scale = 1f32 / f32::sqrt(head_size as f32);+ candle_flash_attn::flash_attn_varlen_windowed(+ query,+ key,+ value,+ seqlens,+ seqlens,+ max_seqlen,+ max_seqlen,+ softmax_scale,+ window_size,+ window_size,+ )+}++#[cfg(not(feature = "cuda"))]+fn flash_attn_varlen_windowed(+ _query: &Tensor,+ _key: &Tensor,+ _value: &Tensor,+ _seqlens: &Tensor,+ _max_seqlen: usize,+ _head_size: usize,+ _window_size: Option<usize>,+) -> Result<Tensor> {+ candle::bail!("packed ModernBERT FlashAttention requires the cuda feature")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn prepares_attention_mask_with_requested_dtype() {+ let mask = Tensor::from_vec(vec![1u32, 0], (1, 2), &Device::Cpu).unwrap();+ let prepared = prepare_4d_attention_mask(&mask, DType::F32, None).unwrap();+ assert_eq!(prepared.dtype(), DType::F32);+ assert_eq!(prepared.dims(), &[1, 1, 2, 2]);+ }++ #[test]+ fn local_attention_window_matches_pytorch_adapter() {+ let local_attention_size = 128usize;+ assert_eq!(local_attention_size / 2, 64);+ }++ #[test]+ fn modernbert_mlp_activation_uses_exact_gelu_on_first_half() -> Result<()> {+ let device = Device::Cpu;+ let unused_weight = Tensor::zeros((1, 1), DType::F32, &device)?;+ let mlp = ModernBertMLP {+ wi: FastLinear::new(unused_weight.clone(), None, None),+ wo: FastLinear::new(unused_weight, None, None),+ activation: ModernBertGatedActivation::new(2)?,+ };+ let xs = Tensor::new(&[[-1f32, 2., 3., 4.]], &device)?;++ let actual = mlp.activate(&xs)?;+ let halves = xs.chunk(2, D::Minus1)?;+ let expected = (&halves[0].gelu_erf()? * &halves[1])?;++ assert_eq!(actual.to_vec2::<f32>()?, expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn modernbert_config_rejects_invalid_attention_geometry() {+ let mut config = test_config();+ config.num_attention_heads = 0;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("num_attention_heads"));++ let mut config = test_config();+ config.hidden_size = 10;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("must be divisible"));++ let mut config = test_config();+ config.global_attn_every_n_layers = 0;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("global_attn_every_n_layers"));++ let mut config = test_config();+ config.local_attention = 0;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("half-window"));++ let mut config = test_config();+ config.norm_eps = f64::NAN;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("norm_eps"));++ let mut config = test_config();+ config.attention_bias = true;+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("attention_bias=false"));++ let mut config = test_config();+ config.hidden_activation = "silu".to_string();+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("hidden_activation=gelu"));++ let mut config = test_config();+ config.rope_scaling = Some(serde_json::json!({+ "rope_type": "linear",+ "factor": 2.0+ }));+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("unscaled rope_scaling"));++ let mut config = test_config();+ config.rope_scaling = Some(serde_json::json!({"rope_type": 7}));+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("must be a string"));++ let mut config = test_config();+ config.rope_scaling = Some(serde_json::json!({+ "rope_type": "default",+ "type": "linear"+ }));+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("conflicts"));++ let mut config = test_config();+ config.rope_parameters = Some(serde_json::json!({+ "full_attention": {"rope_theta": 10_000.0, "rope_type": "default"},+ "sliding_attention": {"rope_theta": 20_000.0, "rope_type": "default"}+ }));+ assert!(config+ .validate()+ .unwrap_err()+ .to_string()+ .contains("sliding_attention"));+ }++ #[cfg(feature = "cuda")]+ #[test]+ fn fused_modernbert_mlp_activation_matches_unfused_bf16_cuda() -> Result<()> {+ let device = Device::new_cuda(0)?;+ let xs = Tensor::new(+ &[+ [-3f32, -1., 0.5, 2., 7., -4., 3., 0.25],+ [1.5, -0.25, 4., -2., -3., 6., 0.5, 8.],+ ],+ &device,+ )?+ .to_dtype(DType::BF16)?;++ let actual = candle_gated_activation::GeluErfGate::new(4)?.forward(&xs)?;+ let halves = xs.chunk(2, D::Minus1)?;+ let expected = (&halves[0].gelu_erf()? * &halves[1])?;++ assert_eq!(+ actual.to_vec2::<half::bf16>()?,+ expected.to_vec2::<half::bf16>()?+ );+ Ok(())+ }++ #[test]+ fn packed_rotary_embeddings_gather_global_and_local_positions() -> Result<()> {+ let device = Device::Cpu;+ let global = RotaryEmbedding {+ cos: Tensor::new(&[[1f32, 2.], [3., 4.], [5., 6.]], &device)?,+ sin: Tensor::new(&[[11f32, 12.], [13., 14.], [15., 16.]], &device)?,+ };+ let local = RotaryEmbedding {+ cos: Tensor::new(&[[21f32, 22.], [23., 24.], [25., 26.]], &device)?,+ sin: Tensor::new(&[[31f32, 32.], [33., 34.], [35., 36.]], &device)?,+ };+ let position_ids = Tensor::new(&[2u32, 0], &device)?;++ let packed = PackedRotaryEmbeddings::new(&global, &local, &position_ids, true)?;+ let (global_cos, global_sin) = packed.for_layer(false);+ let (local_cos, local_sin) = packed.for_layer(true);++ assert_eq!(+ global_cos.to_vec2::<f32>()?,+ vec![vec![5., 6.], vec![1., 2.]]+ );+ assert_eq!(+ global_sin.to_vec2::<f32>()?,+ vec![vec![15., 16.], vec![11., 12.]]+ );+ assert_eq!(+ local_cos.to_vec2::<f32>()?,+ vec![vec![25., 26.], vec![21., 22.]]+ );+ assert_eq!(+ local_sin.to_vec2::<f32>()?,+ vec![vec![35., 36.], vec![31., 32.]]+ );+ Ok(())+ }++ #[test]+ fn packed_rotary_embeddings_skip_unused_local_cache() -> Result<()> {+ let device = Device::Cpu;+ let global = RotaryEmbedding {+ cos: Tensor::new(&[[1f32], [2.]], &device)?,+ sin: Tensor::new(&[[3f32], [4.]], &device)?,+ };+ // Position 1 is deliberately out of range for the local cache. This+ // succeeds only if a global-only model does not gather local RoPE.+ let local = RotaryEmbedding {+ cos: Tensor::new(&[[5f32]], &device)?,+ sin: Tensor::new(&[[6f32]], &device)?,+ };+ let position_ids = Tensor::new(&[1u32], &device)?;++ let packed = PackedRotaryEmbeddings::new(&global, &local, &position_ids, false)?;++ assert!(packed.local.is_none());+ assert_eq!(packed.for_layer(false).0.to_vec2::<f32>()?, vec![vec![2.]]);+ Ok(())+ }++ fn test_config() -> Config {+ Config {+ vocab_size: 128,+ hidden_size: 12,+ num_hidden_layers: 2,+ num_attention_heads: 3,+ intermediate_size: 16,+ max_position_embeddings: 64,+ norm_eps: 1e-5,+ norm_bias: false,+ attention_bias: false,+ mlp_bias: false,+ hidden_activation: "gelu".to_string(),+ pad_token_id: 0,+ global_attn_every_n_layers: 2,+ global_rope_theta: 10_000.0,+ local_attention: 8,+ local_rope_theta: 10_000.0,+ rope_scaling: None,+ rope_parameters: None,+ classifier_config: None,+ }+ }+}diff --git a/packages/sie_server_rust/src/candle_residency.rs b/packages/sie_server_rust/src/candle_residency.rsnew file mode 100644index 000000000..359f8e668--- /dev/null+++ b/packages/sie_server_rust/src/candle_residency.rs@@ -0,0 +1,338 @@+use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub(crate) struct ResidencyPolicy {+ pub pinned: bool,+ pub preload: bool,+}++#[derive(Debug)]+pub(crate) struct CandleResidency<T> {+ entries: HashMap<String, ResidentEntry<T>>,+}++#[derive(Debug)]+struct ResidentEntry<T> {+ model: Arc<T>,+ loaded_at: Instant,+ last_used_at: Instant,+ active_forwards: usize,+ policy: ResidencyPolicy,+}++pub(crate) struct ResidencyUseGuard<T> {+ residency: Arc<Mutex<CandleResidency<T>>>,+ model_id: String,+}++impl<T> Drop for ResidencyUseGuard<T> {+ fn drop(&mut self) {+ if let Ok(mut residency) = self.residency.lock() {+ residency.end_use(&self.model_id, Instant::now());+ }+ }+}++impl<T> ResidencyUseGuard<T> {+ pub(crate) fn active(residency: Arc<Mutex<CandleResidency<T>>>, model_id: String) -> Self {+ Self {+ residency,+ model_id,+ }+ }+}++impl<T> Default for CandleResidency<T> {+ fn default() -> Self {+ Self {+ entries: HashMap::new(),+ }+ }+}++impl<T> CandleResidency<T> {+ #[cfg(test)]+ pub(crate) fn is_empty(&self) -> bool {+ self.entries.is_empty()+ }++ pub(crate) fn keys(&self) -> Vec<String> {+ self.entries.keys().cloned().collect()+ }++ pub(crate) fn get(&self, model_id: &str) -> Option<Arc<T>> {+ self.entries+ .get(model_id)+ .map(|entry| Arc::clone(&entry.model))+ }++ pub(crate) fn get_for_use(&mut self, model_id: &str, now: Instant) -> Option<Arc<T>> {+ let entry = self.entries.get_mut(model_id)?;+ entry.active_forwards += 1;+ entry.last_used_at = now;+ Some(Arc::clone(&entry.model))+ }++ pub(crate) fn insert(+ &mut self,+ model_id: String,+ model: Arc<T>,+ policy: ResidencyPolicy,+ now: Instant,+ ) {+ self.entries.insert(+ model_id,+ ResidentEntry {+ model,+ loaded_at: now,+ last_used_at: now,+ active_forwards: 0,+ policy,+ },+ );+ }++ pub(crate) fn remove(&mut self, model_id: &str) -> Option<Arc<T>> {+ self.entries.remove(model_id).map(|entry| entry.model)+ }++ pub(crate) fn retain<F>(&mut self, mut keep: F) -> usize+ where+ F: FnMut(&str) -> bool,+ {+ let before = self.entries.len();+ self.entries.retain(|model_id, _| keep(model_id));+ before.saturating_sub(self.entries.len())+ }++ pub(crate) fn update_policies<F>(&mut self, mut policy_for: F)+ where+ F: FnMut(&str) -> ResidencyPolicy,+ {+ for (model_id, entry) in &mut self.entries {+ entry.policy = policy_for(model_id);+ }+ }++ fn end_use(&mut self, model_id: &str, now: Instant) {+ let Some(entry) = self.entries.get_mut(model_id) else {+ return;+ };+ if entry.active_forwards > 0 {+ entry.active_forwards -= 1;+ entry.last_used_at = now;+ }+ }++ pub(crate) fn evict_lru_excluding(&mut self, exclude: Option<&str>) -> Option<String> {+ let candidate = self+ .entries+ .iter()+ .filter(|(model_id, entry)| {+ Some(model_id.as_str()) != exclude && entry.is_policy_evictable()+ })+ .min_by_key(|(_, entry)| (entry.last_used_at, entry.loaded_at))+ .map(|(model_id, _)| model_id.clone())?;+ self.entries.remove(&candidate);+ Some(candidate)+ }++ pub(crate) fn evict_idle(&mut self, idle_threshold: Duration, now: Instant) -> Option<String> {+ let candidate = self+ .entries+ .iter()+ .filter(|(_, entry)| entry.is_policy_evictable())+ .filter(|(_, entry)| now.duration_since(entry.last_used_at) >= idle_threshold)+ .min_by_key(|(_, entry)| (entry.last_used_at, entry.loaded_at))+ .map(|(model_id, _)| model_id.clone())?;+ self.entries.remove(&candidate);+ Some(candidate)+ }+}++impl<T> ResidentEntry<T> {+ fn is_policy_evictable(&self) -> bool {+ !self.policy.pinned && self.active_forwards == 0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lru_eviction_skips_pinned_active_and_excluded_models() {+ let now = Instant::now();+ let mut residency = CandleResidency::default();+ residency.insert(+ "old".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(30),+ );+ residency.insert(+ "pinned".to_string(),+ Arc::new(()),+ ResidencyPolicy {+ pinned: true,+ preload: false,+ },+ now - Duration::from_secs(20),+ );+ residency.insert(+ "active".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(10),+ );+ residency.insert(+ "new".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now,+ );+ let _active_model = residency.get_for_use("active", now).expect("mark active");++ assert_eq!(+ residency.evict_lru_excluding(Some("old")),+ Some("new".to_string())+ );+ assert!(residency.get("old").is_some());+ assert!(residency.get("pinned").is_some());+ assert!(residency.get("active").is_some());+ assert!(residency.get("new").is_none());+ }++ #[test]+ fn idle_eviction_removes_only_cold_evictable_models() {+ let now = Instant::now();+ let mut residency = CandleResidency::default();+ residency.insert(+ "cold".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(120),+ );+ residency.insert(+ "warm".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(10),+ );+ residency.insert(+ "pinned-cold".to_string(),+ Arc::new(()),+ ResidencyPolicy {+ pinned: true,+ preload: false,+ },+ now - Duration::from_secs(180),+ );++ assert_eq!(+ residency.evict_idle(Duration::from_secs(60), now),+ Some("cold".to_string())+ );+ assert!(residency.get("warm").is_some());+ assert!(residency.get("pinned-cold").is_some());+ assert_eq!(residency.evict_idle(Duration::from_secs(60), now), None);+ }++ #[test]+ fn use_guard_releases_active_marker_on_drop() {+ let now = Instant::now();+ let residency = Arc::new(Mutex::new(CandleResidency::default()));+ residency.lock().unwrap().insert(+ "model".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(120),+ );++ let model = residency+ .lock()+ .unwrap()+ .get_for_use("model", now)+ .expect("model should be resident");+ drop(model);+ let guard = ResidencyUseGuard::active(Arc::clone(&residency), "model".to_string());+ assert_eq!(residency.lock().unwrap().evict_lru_excluding(None), None);+ drop(guard);+ assert_eq!(+ residency.lock().unwrap().evict_lru_excluding(None),+ Some("model".to_string())+ );+ }++ #[test]+ fn get_for_use_marks_model_active_before_returning() {+ let now = Instant::now();+ let mut residency = CandleResidency::default();+ residency.insert(+ "model".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now - Duration::from_secs(120),+ );++ let model = residency+ .get_for_use("model", now)+ .expect("model should be resident");++ assert_eq!(residency.evict_lru_excluding(None), None);+ drop(model);+ residency.end_use("model", now);+ assert_eq!(+ residency.evict_lru_excluding(None),+ Some("model".to_string())+ );+ }++ #[test]+ fn end_use_refreshes_idle_timestamp_after_long_forward() {+ let now = Instant::now();+ let mut residency = CandleResidency::default();+ let request_start = now - Duration::from_secs(120);+ residency.insert(+ "model".to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ request_start,+ );+ let model = residency+ .get_for_use("model", request_start)+ .expect("model should be resident");+ drop(model);++ residency.end_use("model", now);++ assert_eq!(residency.evict_idle(Duration::from_secs(60), now), None);+ assert_eq!(+ residency.evict_idle(Duration::from_secs(60), now + Duration::from_secs(60)),+ Some("model".to_string())+ );+ }++ #[test]+ fn retain_reports_removed_entry_count() {+ let now = Instant::now();+ let mut residency = CandleResidency::default();+ for model_id in ["keep", "drop-a", "drop-b"] {+ residency.insert(+ model_id.to_string(),+ Arc::new(()),+ ResidencyPolicy::default(),+ now,+ );+ }++ let removed = residency.retain(|model_id| model_id == "keep");++ assert_eq!(removed, 2);+ assert!(residency.get("keep").is_some());+ assert!(residency.get("drop-a").is_none());+ assert!(residency.get("drop-b").is_none());+ }+}diff --git a/packages/sie_server_rust/src/candle_rope.rs b/packages/sie_server_rust/src/candle_rope.rsnew file mode 100644index 000000000..49890ac66--- /dev/null+++ b/packages/sie_server_rust/src/candle_rope.rs@@ -0,0 +1,212 @@+//! Shared RoPE helpers for Candle model kernels.++use candle::{DType, Device, Result, Tensor};+#[cfg(feature = "cuda")]+use candle_rotary::apply_rotary_inplace;+use serde::{de, Deserialize, Deserializer};++#[derive(Debug, Clone)]+pub enum RopeScaling {+ Llama3 {+ #[allow(dead_code)]+ rope_type: String,+ factor: f32,+ high_freq_factor: f32,+ low_freq_factor: f32,+ original_max_position_embeddings: usize,+ },+ Ntk {+ #[allow(dead_code)]+ rope_type: String,+ factor: f32,+ },+}++#[derive(Deserialize)]+struct RawRopeScaling {+ #[serde(alias = "type")]+ rope_type: String,+ factor: f32,+ #[serde(default)]+ high_freq_factor: Option<f32>,+ #[serde(default)]+ low_freq_factor: Option<f32>,+ #[serde(default)]+ original_max_position_embeddings: Option<usize>,+}++impl<'de> Deserialize<'de> for RopeScaling {+ fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>+ where+ D: Deserializer<'de>,+ {+ let raw = RawRopeScaling::deserialize(deserializer)?;+ let rope_type = raw.rope_type;+ if rope_type == "llama3" {+ Ok(Self::Llama3 {+ rope_type,+ factor: raw.factor,+ high_freq_factor: raw+ .high_freq_factor+ .ok_or_else(|| de::Error::missing_field("high_freq_factor"))?,+ low_freq_factor: raw+ .low_freq_factor+ .ok_or_else(|| de::Error::missing_field("low_freq_factor"))?,+ original_max_position_embeddings: raw+ .original_max_position_embeddings+ .ok_or_else(|| de::Error::missing_field("original_max_position_embeddings"))?,+ })+ } else if rope_type == "ntk" {+ Ok(Self::Ntk {+ rope_type,+ factor: raw.factor,+ })+ } else {+ Err(de::Error::unknown_variant(&rope_type, &["llama3", "ntk"]))+ }+ }+}++pub fn inv_freqs(+ dim: usize,+ base: f32,+ device: &Device,+ rope_scaling: Option<&RopeScaling>,+) -> Result<Tensor> {+ if let Some(rope_scaling) = rope_scaling {+ match rope_scaling {+ RopeScaling::Llama3 {+ factor,+ high_freq_factor,+ low_freq_factor,+ original_max_position_embeddings,+ ..+ } => {+ let old_context_len = *original_max_position_embeddings as f32;+ let low_freq_wavelen = old_context_len / *low_freq_factor;+ let high_freq_wavelen = old_context_len / *high_freq_factor;+ let inv_freq = (0..dim)+ .step_by(2)+ .map(|idx| {+ let freq_idx = idx as f32 / dim as f32;+ let inv_freq_base = 1.0 / base.powf(freq_idx);+ let wavelen = 2.0 * std::f32::consts::PI / inv_freq_base;+ if wavelen < high_freq_wavelen {+ inv_freq_base+ } else if wavelen > low_freq_wavelen {+ inv_freq_base / *factor+ } else {+ let smooth_factor = (old_context_len / wavelen - *low_freq_factor)+ / (*high_freq_factor - *low_freq_factor);+ let inv_freq_llama = inv_freq_base / *factor;+ (1.0 - smooth_factor) * inv_freq_llama + smooth_factor * inv_freq_base+ }+ })+ .collect::<Vec<_>>();+ return Tensor::from_vec(inv_freq, (1, dim / 2), device);+ }+ RopeScaling::Ntk { factor, .. } => {+ let inv_freqs = base_inv_freqs(dim, base * *factor, device)?;+ let scale = factor.powf(2.0 / dim as f32) as f64;+ return inv_freqs / scale;+ }+ }+ }+ base_inv_freqs(dim, base, device)+}++fn base_inv_freqs(dim: usize, base: f32, device: &Device) -> Result<Tensor> {+ let inv_freq = (0..dim)+ .step_by(2)+ .map(|idx| 1f32 / base.powf(idx as f32 / dim as f32))+ .collect::<Vec<_>>();+ Tensor::from_vec(inv_freq, (1, dim / 2), device)+}++pub fn cos_sin(+ length: usize,+ inv_freqs: &Tensor,+ dtype: DType,+ repeat_freqs: bool,+) -> Result<(Tensor, Tensor)> {+ let positions = Tensor::arange(0u32, length as u32, inv_freqs.device())?+ .to_dtype(DType::F32)?+ .reshape((length, 1))?;+ let mut freqs = positions.matmul(inv_freqs)?;+ if repeat_freqs {+ freqs = Tensor::cat(&[&freqs, &freqs], 1)?;+ }+ Ok((freqs.cos()?.to_dtype(dtype)?, freqs.sin()?.to_dtype(dtype)?))+}++#[cfg(feature = "cuda")]+pub fn apply_rotary_packed_inplace(+ query: &Tensor,+ key: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+) -> Result<()> {+ apply_rotary_inplace(query, key, cos, sin, true)+}++#[cfg(not(feature = "cuda"))]+pub fn apply_rotary_packed_inplace(+ _query: &Tensor,+ _key: &Tensor,+ _cos: &Tensor,+ _sin: &Tensor,+) -> Result<()> {+ candle::bail!("packed RoPE rotary requires the cuda feature")+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rope_scaling_accepts_supported_ntk_type() {+ let scaling: RopeScaling = serde_json::from_str(r#"{"type":"ntk","factor":8.0}"#).unwrap();+ match scaling {+ RopeScaling::Ntk { factor, .. } => assert_eq!(factor, 8.0),+ other => panic!("expected NTK RoPE scaling, got {other:?}"),+ }+ }++ #[test]+ fn rope_scaling_accepts_supported_llama3_type() {+ let scaling: RopeScaling = serde_json::from_str(+ r#"{+ "rope_type":"llama3",+ "factor":8.0,+ "high_freq_factor":4.0,+ "low_freq_factor":1.0,+ "original_max_position_embeddings":8192+ }"#,+ )+ .unwrap();+ match scaling {+ RopeScaling::Llama3 {+ factor,+ high_freq_factor,+ low_freq_factor,+ original_max_position_embeddings,+ ..+ } => {+ assert_eq!(factor, 8.0);+ assert_eq!(high_freq_factor, 4.0);+ assert_eq!(low_freq_factor, 1.0);+ assert_eq!(original_max_position_embeddings, 8192);+ }+ other => panic!("expected Llama 3 RoPE scaling, got {other:?}"),+ }+ }++ #[test]+ fn rope_scaling_rejects_unsupported_type() {+ let err = serde_json::from_str::<RopeScaling>(r#"{"type":"linear","factor":8.0}"#)+ .unwrap_err()+ .to_string();+ assert!(err.contains("unknown variant"));+ assert!(err.contains("linear"));+ }+}diff --git a/packages/sie_server_rust/src/candle_splade.rs b/packages/sie_server_rust/src/candle_splade.rsnew file mode 100644index 000000000..55c89fcc6--- /dev/null+++ b/packages/sie_server_rust/src/candle_splade.rs@@ -0,0 +1,865 @@+//! SPLADE masked-language-model head and sparse output conversion.++use anyhow::{Context, Result};+use candle::{CpuStorage, DType, Device, Storage, Tensor};+use candle_nn::VarBuilder;+use candle_transformers::models::bert::{Config as BertConfig, HiddenAct as BertHiddenAct};+use half::{bf16, f16};++use crate::candle_layers::{FastLayerNorm, FastLinear, HiddenAct};++#[derive(Debug, Clone, PartialEq)]+pub(crate) struct CandleSparseEmbedding {+ pub indices: Vec<i32>,+ pub values: Vec<f32>,+}++#[derive(Debug)]+pub(crate) struct CandleBertSpladeHead {+ transform: FastLinear,+ transform_activation: BertHiddenAct,+ transform_layer_norm: FastLayerNorm,+ decoder: FastLinear,+ vocab_size: usize,+}++impl CandleBertSpladeHead {+ pub(crate) fn load(vb: VarBuilder<'_>, config: &BertConfig) -> Result<Self> {+ let transform = FastLinear::load(+ config.hidden_size,+ config.hidden_size,+ vb.pp("cls.predictions.transform.dense"),+ None,+ )+ .context("load BERT SPLADE prediction transform")?;+ let transform_layer_norm = FastLayerNorm::load(+ vb.pp("cls.predictions.transform.LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )+ .context("load BERT SPLADE prediction layer norm")?;++ // PyTorch-to-safetensors conversion may omit either alias of a tied+ // tensor. Accept both canonical BERT MLM layouts without synthesizing+ // weights or changing checkpoint semantics.+ let decoder_weight = if vb.contains_tensor("cls.predictions.decoder.weight") {+ vb.pp("cls.predictions.decoder")+ .get((config.vocab_size, config.hidden_size), "weight")?+ } else {+ vb.pp("bert.embeddings.word_embeddings")+ .get((config.vocab_size, config.hidden_size), "weight")?+ };+ let decoder_bias = if vb.contains_tensor("cls.predictions.bias") {+ vb.pp("cls.predictions").get(config.vocab_size, "bias")?+ } else {+ vb.pp("cls.predictions.decoder")+ .get(config.vocab_size, "bias")?+ };+ let decoder = FastLinear::new(decoder_weight, Some(decoder_bias), Some(HiddenAct::Relu));++ Ok(Self {+ transform,+ transform_activation: config.hidden_act,+ transform_layer_norm,+ decoder,+ vocab_size: config.vocab_size,+ })+ }++ pub(crate) fn vocab_size(&self) -> usize {+ self.vocab_size+ }++ /// Apply the BERT MLM head through its ReLU to+ /// `[batch, tokens, hidden]` states. The caller applies `log1p` after+ /// sequence max-pooling: `log1p(relu(x))` is monotone, so moving the log+ /// after max is exact and avoids a vocabulary-wide token-level kernel.+ pub(crate) fn forward_activated(&self, hidden_states: &Tensor) -> Result<Tensor> {+ let transformed = self.transform.forward(hidden_states)?;+ let transformed = match self.transform_activation {+ BertHiddenAct::Gelu => transformed.gelu_erf()?,+ BertHiddenAct::GeluApproximate => transformed.gelu()?,+ BertHiddenAct::Relu => transformed.relu()?,+ };+ let transformed = self.transform_layer_norm.forward(&transformed, None)?;+ Ok(self.decoder.forward(&transformed)?)+ }+}++pub(crate) fn sparse_embeddings_from_dense(+ dense_embeddings: &Tensor,+) -> Result<Vec<CandleSparseEmbedding>> {+ let (batch_size, vocab_size) = dense_embeddings+ .dims2()+ .context("SPLADE pooled vocabulary weights must have shape [batch, vocab]")?;+ // Preserve the pooled compute dtype across the device-to-host transfer.+ // F16 and BF16 widen exactly to F32, so scanning their CPU storage avoids+ // a vocabulary-wide GPU cast and halves the readback bytes.+ let host_embeddings = dense_embeddings.to_device(&Device::Cpu)?;+ if let Some((start, end)) = host_embeddings+ .is_contiguous()+ .then(|| host_embeddings.layout().contiguous_offsets())+ .flatten()+ {+ let (storage, _) = host_embeddings.storage_and_layout();+ match &*storage {+ Storage::Cpu(CpuStorage::F16(values)) => {+ return sparse_embeddings_from_contiguous_values(+ values+ .get(start..end)+ .context("read contiguous F16 SPLADE vocabulary weights")?,+ batch_size,+ vocab_size,+ f16::to_f32,+ );+ }+ Storage::Cpu(CpuStorage::BF16(values)) => {+ return sparse_embeddings_from_contiguous_values(+ values+ .get(start..end)+ .context("read contiguous BF16 SPLADE vocabulary weights")?,+ batch_size,+ vocab_size,+ bf16::to_f32,+ );+ }+ Storage::Cpu(CpuStorage::F32(values)) => {+ return sparse_embeddings_from_contiguous_values(+ values+ .get(start..end)+ .context("read contiguous F32 SPLADE vocabulary weights")?,+ batch_size,+ vocab_size,+ |value| value,+ );+ }+ _ => {}+ }+ }++ let rows = host_embeddings+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()+ .context("read SPLADE pooled vocabulary weights")?;+ rows.into_iter()+ .map(sparse_embedding_from_f32_values)+ .collect()+}++fn sparse_embeddings_from_contiguous_values<T: Copy>(+ values: &[T],+ batch_size: usize,+ vocab_size: usize,+ to_f32: impl Fn(T) -> f32,+) -> Result<Vec<CandleSparseEmbedding>> {+ let expected_values = batch_size+ .checked_mul(vocab_size)+ .context("SPLADE pooled vocabulary size overflow")?;+ if values.len() != expected_values {+ anyhow::bail!(+ "SPLADE pooled vocabulary storage mismatch: values={} expected={expected_values}",+ values.len()+ )+ }++ let mut sparse_embeddings = Vec::with_capacity(batch_size);+ for row_index in 0..batch_size {+ let start = row_index * vocab_size;+ let end = start + vocab_size;+ sparse_embeddings.push(sparse_embedding_from_f32_values(+ values[start..end].iter().copied().map(&to_f32),+ )?);+ }+ Ok(sparse_embeddings)+}++fn sparse_embedding_from_f32_values(+ values: impl IntoIterator<Item = f32>,+) -> Result<CandleSparseEmbedding> {+ let mut indices = Vec::new();+ let mut sparse_values = Vec::new();+ for (index, value) in values.into_iter().enumerate() {+ if !value.is_finite() {+ anyhow::bail!("SPLADE produced a non-finite vocabulary weight at {index}");+ }+ if value > 0.0 {+ indices.push(i32::try_from(index).context("SPLADE vocabulary exceeds i32")?);+ sparse_values.push(value);+ }+ }+ Ok(CandleSparseEmbedding {+ indices,+ values: sparse_values,+ })+}++/// Apply true `log1p` semantics to non-negative pooled SPLADE weights.+///+/// Candle does not expose a tensor `log1p` operation. Computing `(x + 1).log()`+/// in F16/BF16 first rounds small positive weights away. Widen the epilogue and+/// use the compensated identity `log(u) * x / (u - 1)`, with the `u == 1`+/// limit selected explicitly. The infinity branch preserves the existing+/// non-finite validation behavior without turning positive infinity into NaN.+fn splade_log1p_nonnegative(pooled: &Tensor) -> Result<Tensor> {+ let output_dtype = pooled.dtype();+ let compute_dtype = match output_dtype {+ DType::F16 | DType::BF16 => DType::F32,+ dtype => dtype,+ };+ let x = pooled.to_dtype(compute_dtype)?;+ let one_plus_x = (&x + 1.0)?;+ let denominator = (&one_plus_x - 1.0)?;+ let compensated = ((one_plus_x.log()? * &x)? / &denominator)?;+ let stable = one_plus_x.eq(1.0)?.where_cond(&x, &compensated)?;+ let stable = x.eq(f64::INFINITY)?.where_cond(&x, &stable)?;+ Ok(stable.to_dtype(output_dtype)?)+}++/// Pool non-negative MLM activations across the sequence dimension.+///+/// Padding is zeroed before max-pooling. Applying `log1p` after the max is+/// exactly equivalent to applying it token-wise first because the activation+/// is monotone, and avoids a token-by-vocabulary elementwise kernel.+pub(crate) fn pool_splade_activations(+ activated: &Tensor,+ attention_mask: &Tensor,+) -> Result<Tensor> {+ let mask = attention_mask.unsqueeze(2)?.to_dtype(activated.dtype())?;+ let masked = activated.broadcast_mul(&mask)?;+ let max_weights = masked.max(1)?;+ splade_log1p_nonnegative(&max_weights)+}++/// Max-pool non-negative packed MLM activations using host-side sequence+/// lengths, then apply `log1p` once per pooled vocabulary row.+pub(crate) fn pool_packed_splade_activations(+ activated: &Tensor,+ seq_lengths: &[usize],+) -> Result<Tensor> {+ let (_, vocab_size) = validate_packed_splade_activations(activated, seq_lengths)?;++ let max_weights = if seq_lengths+ .first()+ .is_some_and(|first| seq_lengths.iter().all(|length| length == first))+ {+ activated+ .reshape((seq_lengths.len(), seq_lengths[0], vocab_size))?+ .max(1)?+ } else {+ let mut cursor = 0usize;+ let mut rows = Vec::with_capacity(seq_lengths.len());+ for length in seq_lengths {+ rows.push(activated.narrow(0, cursor, *length)?.max_keepdim(0)?);+ cursor += *length;+ }+ Tensor::cat(&rows, 0)?+ };+ splade_log1p_nonnegative(&max_weights)+}++fn validate_packed_splade_activations(+ activated: &Tensor,+ seq_lengths: &[usize],+) -> Result<(usize, usize)> {+ let (total_tokens, vocab_size) = activated+ .dims2()+ .context("packed SPLADE activations must have shape [tokens, vocab]")?;+ if seq_lengths.is_empty() {+ anyhow::bail!("packed SPLADE sequence lengths are empty")+ }+ if seq_lengths.contains(&0) {+ anyhow::bail!("packed SPLADE sequence lengths must be positive")+ }+ let expected_tokens = seq_lengths.iter().try_fold(0usize, |total, length| {+ total+ .checked_add(*length)+ .context("packed SPLADE token count overflow")+ })?;+ if expected_tokens != total_tokens {+ anyhow::bail!(+ "packed SPLADE token count mismatch: activations={total_tokens} lengths={expected_tokens}"+ )+ }+ if vocab_size == 0 {+ anyhow::bail!("packed SPLADE vocabulary is empty")+ }++ Ok((total_tokens, vocab_size))+}++fn validate_packed_splade_offsets(+ activated: &Tensor,+ seqlens: &Tensor,+ seq_lengths: &[usize],+) -> Result<()> {+ let offset_count = seqlens+ .dims1()+ .context("packed SPLADE cumulative offsets must have shape [batch + 1]")?;+ let expected_offsets = seq_lengths+ .len()+ .checked_add(1)+ .context("packed SPLADE cumulative offset count overflow")?;+ if offset_count != expected_offsets {+ anyhow::bail!(+ "packed SPLADE cumulative offset count mismatch: offsets={offset_count} expected={expected_offsets}"+ )+ }+ if seqlens.dtype() != DType::U32 {+ anyhow::bail!(+ "packed SPLADE cumulative offsets must use U32, got {:?}",+ seqlens.dtype()+ )+ }+ if !activated.device().same_device(seqlens.device()) {+ anyhow::bail!("packed SPLADE activations and cumulative offsets must use the same device")+ }++ Ok(())+}++#[cfg(feature = "cuda")]+fn can_use_fused_packed_splade_pool(+ activated: &Tensor,+ seqlens: &Tensor,+ seq_lengths: &[usize],+) -> bool {+ let Ok((total_tokens, vocab_size)) = activated.dims2() else {+ return false;+ };+ activated.device().is_cuda()+ && activated.dtype() == DType::F16+ && activated.is_contiguous()+ && seqlens.is_contiguous()+ && total_tokens <= u32::MAX as usize+ && vocab_size <= i32::MAX as usize+ // CUDA grid.y is capped at 65,535 for the supported deployment GPUs.+ && seq_lengths.len() <= 65_535+}++/// Dispatch packed SPLADE pooling to the coalesced CUDA kernel when its strict+/// contract is met. CPU, non-F16, and non-contiguous inputs retain the generic+/// Candle implementation as a correctness fallback.+pub(crate) fn pool_packed_splade_activations_dispatch(+ activated: &Tensor,+ seqlens: &Tensor,+ seq_lengths: &[usize],+) -> Result<Tensor> {+ validate_packed_splade_activations(activated, seq_lengths)?;+ validate_packed_splade_offsets(activated, seqlens, seq_lengths)?;++ #[cfg(feature = "cuda")]+ if can_use_fused_packed_splade_pool(activated, seqlens, seq_lengths) {+ return candle_splade_pool::segmented_max_log1p(activated, seqlens)+ .context("run fused packed SPLADE pooling");+ }++ pool_packed_splade_activations(activated, seq_lengths)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn assert_native_sparse_conversion<T: candle::WithDType + Copy>(+ values: Vec<T>,+ expected_values: [Vec<f32>; 2],+ ) -> Result<()> {+ let dense = Tensor::from_vec(values, (2, 7), &Device::Cpu)?;+ let sparse = sparse_embeddings_from_dense(&dense)?;++ assert_eq!(sparse.len(), 2);+ assert_eq!(sparse[0].indices, vec![3, 4, 6]);+ assert_eq!(sparse[1].indices, vec![0, 5, 6]);+ for (actual, expected) in sparse.iter().zip(expected_values) {+ assert_eq!(+ actual+ .values+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>(),+ expected+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>()+ );+ }+ Ok(())+ }++ fn assert_non_finite_rejected<T: candle::WithDType + Copy>(+ zero: T,+ non_finite: T,+ ) -> Result<()> {+ let dense = Tensor::from_vec(vec![zero, non_finite], (1, 2), &Device::Cpu)?;+ let error = sparse_embeddings_from_dense(&dense).unwrap_err();+ assert!(error+ .to_string()+ .contains("non-finite vocabulary weight at 1"));+ Ok(())+ }++ #[test]+ fn sparse_conversion_keeps_positive_finite_weights() -> Result<()> {+ let dense = Tensor::new(+ &[[0.0_f32, 1.5, -0.0, 2.25], [3.0, 0.0, 0.5, 0.0]],+ &Device::Cpu,+ )?;++ let sparse = sparse_embeddings_from_dense(&dense)?;++ assert_eq!(+ sparse,+ vec![+ CandleSparseEmbedding {+ indices: vec![1, 3],+ values: vec![1.5, 2.25],+ },+ CandleSparseEmbedding {+ indices: vec![0, 2],+ values: vec![3.0, 0.5],+ },+ ]+ );+ Ok(())+ }++ #[test]+ fn sparse_conversion_rejects_non_finite_weights() -> Result<()> {+ let dense = Tensor::new(&[[0.0_f32, f32::NAN]], &Device::Cpu)?;++ let error = sparse_embeddings_from_dense(&dense).unwrap_err();++ assert!(error.to_string().contains("non-finite"));+ Ok(())+ }++ #[test]+ fn sparse_conversion_preserves_native_float_bits_and_order() -> Result<()> {+ let f32_subnormal = f32::from_bits(1);+ assert_native_sparse_conversion(+ vec![+ 0.0,+ -0.0,+ -1.0,+ f32_subnormal,+ 1.5,+ -f32_subnormal,+ 2.0,+ 3.0,+ 0.0,+ -2.0,+ -0.0,+ -f32_subnormal,+ f32_subnormal,+ 4.0,+ ],+ [vec![f32_subnormal, 1.5, 2.0], vec![3.0, f32_subnormal, 4.0]],+ )?;++ let f16_subnormal = f16::from_bits(1);+ assert_native_sparse_conversion(+ vec![+ f16::ZERO,+ f16::NEG_ZERO,+ f16::from_f32(-1.0),+ f16_subnormal,+ f16::from_f32(1.5),+ -f16_subnormal,+ f16::from_f32(2.0),+ f16::from_f32(3.0),+ f16::ZERO,+ f16::from_f32(-2.0),+ f16::NEG_ZERO,+ -f16_subnormal,+ f16_subnormal,+ f16::from_f32(4.0),+ ],+ [+ vec![f16_subnormal.to_f32(), 1.5, 2.0],+ vec![3.0, f16_subnormal.to_f32(), 4.0],+ ],+ )?;++ let bf16_subnormal = bf16::from_bits(1);+ assert_native_sparse_conversion(+ vec![+ bf16::ZERO,+ bf16::NEG_ZERO,+ bf16::from_f32(-1.0),+ bf16_subnormal,+ bf16::from_f32(1.5),+ -bf16_subnormal,+ bf16::from_f32(2.0),+ bf16::from_f32(3.0),+ bf16::ZERO,+ bf16::from_f32(-2.0),+ bf16::NEG_ZERO,+ -bf16_subnormal,+ bf16_subnormal,+ bf16::from_f32(4.0),+ ],+ [+ vec![bf16_subnormal.to_f32(), 1.5, 2.0],+ vec![3.0, bf16_subnormal.to_f32(), 4.0],+ ],+ )?;++ Ok(())+ }++ #[test]+ fn sparse_conversion_rejects_all_native_non_finite_values() -> Result<()> {+ for non_finite in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ assert_non_finite_rejected(0.0f32, non_finite)?;+ }+ for non_finite in [f16::NAN, f16::INFINITY, f16::NEG_INFINITY] {+ assert_non_finite_rejected(f16::ZERO, non_finite)?;+ }+ for non_finite in [bf16::NAN, bf16::INFINITY, bf16::NEG_INFINITY] {+ assert_non_finite_rejected(bf16::ZERO, non_finite)?;+ }+ Ok(())+ }++ #[test]+ fn sparse_conversion_preserves_non_contiguous_row_order() -> Result<()> {+ let base = Tensor::from_vec(+ vec![+ f16::ZERO,+ f16::from_f32(3.0),+ f16::from_f32(1.0),+ f16::ZERO,+ f16::from_f32(-1.0),+ f16::from_f32(4.0),+ f16::from_f32(2.0),+ f16::NEG_ZERO,+ ],+ (4, 2),+ &Device::Cpu,+ )?;+ let dense = base.t()?;+ assert!(!dense.is_contiguous());++ assert_eq!(+ sparse_embeddings_from_dense(&dense)?,+ vec![+ CandleSparseEmbedding {+ indices: vec![1, 3],+ values: vec![1.0, 2.0],+ },+ CandleSparseEmbedding {+ indices: vec![0, 2],+ values: vec![3.0, 4.0],+ },+ ]+ );+ Ok(())+ }++ #[test]+ fn pooling_masks_padding_and_matches_tokenwise_log1p() -> Result<()> {+ let activated = Tensor::new(+ &[+ [[0.0_f32, 2.0, 1.0], [4.0, 1.0, 3.0], [99.0, 99.0, 99.0]],+ [[1.0, 0.0, 5.0], [9.0, 9.0, 9.0], [8.0, 8.0, 8.0]],+ ],+ &Device::Cpu,+ )?;+ let mask = Tensor::new(&[[1_u32, 1, 0], [1, 0, 0]], &Device::Cpu)?;++ let optimized = pool_splade_activations(&activated, &mask)?;+ let direct = (activated + 1.0)?+ .log()?+ .broadcast_mul(&mask.unsqueeze(2)?.to_dtype(DType::F32)?)?+ .max(1)?;++ assert_eq!(optimized.to_vec2::<f32>()?, direct.to_vec2::<f32>()?);+ let pooled = optimized.to_vec2::<f32>()?;+ assert!((pooled[0][0] - 4.0_f32.ln_1p()).abs() < 1e-6);+ assert!((pooled[1][2] - 5.0_f32.ln_1p()).abs() < 1e-6);+ Ok(())+ }++ #[test]+ fn packed_pooling_matches_per_sequence_tokenwise_log1p() -> Result<()> {+ let activated = Tensor::new(+ &[+ [0.0f32, 2.0, 1.0],+ [4.0, 1.0, 3.0],+ [1.0, 0.0, 5.0],+ [7.0, 3.0, 2.0],+ [2.0, 8.0, 4.0],+ ],+ &Device::Cpu,+ )?;++ let optimized = pool_packed_splade_activations(&activated, &[2, 3])?;+ let tokenwise = (activated + 1.0)?.log()?;+ let expected = Tensor::cat(+ &[+ tokenwise.narrow(0, 0, 2)?.max_keepdim(0)?,+ tokenwise.narrow(0, 2, 3)?.max_keepdim(0)?,+ ],+ 0,+ )?;++ assert_eq!(optimized.to_vec2::<f32>()?, expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn packed_pooling_preserves_true_log1p_for_tiny_f16_weights() -> Result<()> {+ let values = vec![+ f16::from_bits(1),+ f16::from_f32(2.0f32.powi(-14)),+ f16::from_f32(2.0f32.powi(-12)),+ f16::from_f32(2.0f32.powi(-11)),+ f16::from_f32(2.0f32.powi(-10)),+ ];+ let activated = Tensor::from_vec(values.clone(), (1, values.len()), &Device::Cpu)?;++ let actual = pool_packed_splade_activations(&activated, &[1])?+ .to_vec2::<f16>()?+ .remove(0);++ for (index, (actual, input)) in actual.iter().zip(values).enumerate() {+ let expected = f16::from_f32(input.to_f32().ln_1p());+ assert_eq!(+ actual.to_bits(),+ expected.to_bits(),+ "tiny log1p mismatch at index {index}: input={}",+ input.to_f32()+ );+ assert!(*actual > f16::ZERO);+ }+ Ok(())+ }++ #[test]+ fn packed_pooling_uses_uniform_length_fast_path() -> Result<()> {+ let activated = Tensor::new(+ &[[0.0f32, 2.0], [4.0, 1.0], [1.0, 5.0], [7.0, 3.0]],+ &Device::Cpu,+ )?;++ let optimized = pool_packed_splade_activations(&activated, &[2, 2])?;+ let expected = activated.reshape((2, 2, 2))?.max(1)?;+ let expected = (expected + 1.0)?.log()?;++ assert_eq!(optimized.to_vec2::<f32>()?, expected.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn packed_pooling_rejects_mismatched_lengths() -> Result<()> {+ let activated = Tensor::zeros((3, 2), DType::F32, &Device::Cpu)?;++ let error = pool_packed_splade_activations(&activated, &[1, 1])+ .unwrap_err()+ .to_string();++ assert!(error.contains("token count mismatch"));+ Ok(())+ }++ #[test]+ fn packed_pooling_dispatch_falls_back_on_cpu() -> Result<()> {+ let activated = Tensor::new(+ &[+ [0.0f32, 2.0, 1.0],+ [4.0, 1.0, 3.0],+ [1.0, 0.0, 5.0],+ [7.0, 3.0, 2.0],+ [2.0, 8.0, 4.0],+ ],+ &Device::Cpu,+ )?;+ let seqlens = Tensor::new(&[0u32, 2, 5], &Device::Cpu)?;++ let dispatched = pool_packed_splade_activations_dispatch(&activated, &seqlens, &[2, 3])?;+ let reference = pool_packed_splade_activations(&activated, &[2, 3])?;++ assert_eq!(dispatched.dims(), &[2, 3]);+ assert_eq!(dispatched.to_vec2::<f32>()?, reference.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn packed_pooling_dispatch_validates_offsets() -> Result<()> {+ let activated = Tensor::zeros((3, 2), DType::F32, &Device::Cpu)?;+ let short_offsets = Tensor::new(&[0u32, 3], &Device::Cpu)?;+ let float_offsets = Tensor::new(&[0.0f32, 1.0, 3.0], &Device::Cpu)?;+ let matrix_offsets = Tensor::new(&[[0u32, 1, 3]], &Device::Cpu)?;++ let error = pool_packed_splade_activations_dispatch(&activated, &short_offsets, &[1, 2])+ .unwrap_err()+ .to_string();+ assert!(error.contains("offset count mismatch"));++ let error = pool_packed_splade_activations_dispatch(&activated, &float_offsets, &[1, 2])+ .unwrap_err()+ .to_string();+ assert!(error.contains("must use U32"));++ let error = pool_packed_splade_activations_dispatch(&activated, &matrix_offsets, &[1, 2])+ .unwrap_err()+ .to_string();+ assert!(error.contains("shape [batch + 1]"));+ Ok(())+ }++ #[test]+ fn packed_pooling_preserves_full_vocabulary_tail_without_normalizing() -> Result<()> {+ const VOCAB_SIZE: usize = 30_522;+ let mut values = vec![0.0f32; 2 * VOCAB_SIZE];+ values[VOCAB_SIZE - 1] = 2.0;+ values[2 * VOCAB_SIZE - 1] = 5.0;+ values[VOCAB_SIZE] = 3.0;+ let activated = Tensor::from_vec(values, (2, VOCAB_SIZE), &Device::Cpu)?;++ let pooled = pool_packed_splade_activations(&activated, &[2])?;+ let row = pooled.to_vec2::<f32>()?.remove(0);++ assert_eq!(pooled.dims(), &[1, VOCAB_SIZE]);+ assert!((row[0] - 3.0f32.ln_1p()).abs() < 1e-6);+ assert!((row[VOCAB_SIZE - 1] - 5.0f32.ln_1p()).abs() < 1e-6);+ assert!(row.iter().map(|value| value * value).sum::<f32>() > 1.0);+ Ok(())+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn fused_packed_pooling_matches_host_reference_and_handles_vocab_tail() -> Result<()> {+ use half::f16;++ const TOKENS: usize = 5;+ const VOCAB_SIZE: usize = 30_522;+ let device = Device::new_cuda(0)?;+ let values = (0..TOKENS)+ .flat_map(|token| {+ (0..VOCAB_SIZE)+ .map(move |vocab| f16::from_f32(((token * 11 + vocab % 23) % 31) as f32 / 8.0))+ })+ .collect::<Vec<_>>();+ let activated = Tensor::from_vec(values, (TOKENS, VOCAB_SIZE), &device)?;+ let seqlens = Tensor::new(&[0u32, 2, 5], &device)?;++ let reference = pool_packed_splade_activations(&activated, &[2, 3])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ let fused = pool_packed_splade_activations_dispatch(&activated, &seqlens, &[2, 3])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;++ assert_eq!(fused.len(), 2);+ assert_eq!(fused[0].len(), VOCAB_SIZE);+ for batch in 0..fused.len() {+ for vocab in 0..VOCAB_SIZE {+ assert_eq!(+ fused[batch][vocab], reference[batch][vocab],+ "batch={batch} vocab={vocab}"+ );+ }+ }+ Ok(())+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn fused_packed_pooling_preserves_true_log1p_for_tiny_f16_weights() -> Result<()> {+ let device = Device::new_cuda(0)?;+ let values = vec![+ f16::from_bits(1),+ f16::from_f32(2.0f32.powi(-14)),+ f16::from_f32(2.0f32.powi(-12)),+ f16::from_f32(2.0f32.powi(-11)),+ f16::from_f32(2.0f32.powi(-10)),+ ];+ let activated = Tensor::from_vec(values.clone(), (1, values.len()), &device)?;+ let seqlens = Tensor::new(&[0u32, 1], &device)?;++ let actual = pool_packed_splade_activations_dispatch(&activated, &seqlens, &[1])?+ .to_device(&Device::Cpu)?+ .to_vec2::<f16>()?+ .remove(0);++ for (index, (actual, input)) in actual.iter().zip(values).enumerate() {+ let expected = f16::from_f32(input.to_f32().ln_1p());+ assert_eq!(+ actual.to_bits(),+ expected.to_bits(),+ "fused tiny log1p mismatch at index {index}: input={}",+ input.to_f32()+ );+ assert!(*actual > f16::ZERO);+ }+ Ok(())+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn fused_packed_pooling_preserves_batch_one_extrema_nan_and_infinity() -> Result<()> {+ use half::f16;++ let device = Device::new_cuda(0)?;+ let values = vec![+ f16::from_f32(5.0),+ f16::from_f32(1.0),+ f16::NAN,+ f16::INFINITY,+ f16::from_f32(0.0),+ f16::from_f32(2.0),+ f16::from_f32(3.0),+ f16::from_f32(2.0),+ f16::from_f32(4.0),+ f16::from_f32(1.0),+ f16::from_f32(1.0),+ f16::from_f32(7.0),+ f16::from_f32(3.0),+ f16::from_f32(2.0),+ f16::from_f32(6.0),+ ];+ let activated = Tensor::from_vec(values, (3, 5), &device)?;+ let seqlens = Tensor::new(&[0u32, 3], &device)?;++ let reference = pool_packed_splade_activations(&activated, &[3])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ let fused = pool_packed_splade_activations_dispatch(&activated, &seqlens, &[3])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;++ assert_eq!(fused[0][0], reference[0][0]);+ assert_eq!(fused[0][1], reference[0][1]);+ assert!(fused[0][2].is_nan() && reference[0][2].is_nan());+ assert!(fused[0][3].is_infinite() && reference[0][3].is_infinite());+ assert_eq!(fused[0][4], reference[0][4]);+ Ok(())+ }++ #[cfg(feature = "cuda")]+ #[test]+ #[ignore = "requires a CUDA GPU"]+ fn fused_packed_pooling_rejects_invalid_device_offsets_without_oob_reads() -> Result<()> {+ let device = Device::new_cuda(0)?;+ let activated = Tensor::zeros((4, 3), DType::F16, &device)?;++ for offsets in [[1u32, 4], [0, 3], [0, 0], [0, 5]] {+ let seqlens = Tensor::new(&offsets, &device)?;+ let pooled = pool_packed_splade_activations_dispatch(&activated, &seqlens, &[4])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ assert!(pooled[0].iter().all(|value| value.is_nan()));+ }++ let decreasing = Tensor::new(&[0u32, 3, 2], &device)?;+ let pooled = pool_packed_splade_activations_dispatch(&activated, &decreasing, &[2, 2])?+ .to_dtype(DType::F32)?+ .to_vec2::<f32>()?;+ assert!(pooled[1].iter().all(|value| value.is_nan()));+ Ok(())+ }+}diff --git a/packages/sie_server_rust/src/candle_xlm_roberta.rs b/packages/sie_server_rust/src/candle_xlm_roberta.rsnew file mode 100644index 000000000..6a9ab3dd7--- /dev/null+++ b/packages/sie_server_rust/src/candle_xlm_roberta.rs@@ -0,0 +1,1111 @@+//! XLM-RoBERTa encoder with a packed FlashAttention path for Candle.++use std::time::Instant;++use crate::candle_layers::{index_select, FastLayerNorm, FastLinear, HiddenAct};+use candle::{DType, Device, Result, Tensor};+use candle_nn::{embedding, ops::softmax_last_dim, Embedding, Module, VarBuilder};+use serde::Deserialize;++#[derive(Debug, Clone, Deserialize)]+pub struct Config {+ pub hidden_size: usize,+ pub layer_norm_eps: f64,+ pub num_attention_heads: usize,+ pub intermediate_size: usize,+ pub hidden_act: HiddenAct,+ pub num_hidden_layers: usize,+ pub vocab_size: usize,+ pub max_position_embeddings: usize,+ pub type_vocab_size: usize,+ pub pad_token_id: u32,+}++#[derive(Debug, Clone, Copy, Default)]+pub struct XlmRobertaForwardProfile {+ pub total_tokens: usize,+ pub max_seqlen: usize,+ pub hidden_size: usize,+ pub intermediate_size: usize,+ pub attention_heads: usize,+ pub attention_head_size: usize,+ pub linear_gflops: f64,+ pub embedding_ms: f64,+ pub attention_ms: f64,+ pub attention_qkv_ms: f64,+ pub attention_flash_ms: f64,+ pub attention_output_dense_ms: f64,+ pub attention_output_layernorm_ms: f64,+ pub ffn_ms: f64,+ pub ffn_intermediate_dense_ms: f64,+ pub ffn_activation_ms: f64,+ pub ffn_output_dense_ms: f64,+ pub ffn_output_layernorm_ms: f64,+ pub layers: usize,+}++struct XlmRobertaEmbeddings {+ word_embeddings: Embedding,+ position_embeddings: Embedding,+ token_type_embeddings: Embedding,+ layer_norm: FastLayerNorm,+ padding_idx: u32,+}++impl XlmRobertaEmbeddings {+ fn load(vb: VarBuilder, config: &Config) -> Result<Self> {+ let word_embeddings = embedding(+ config.vocab_size,+ config.hidden_size,+ vb.pp("word_embeddings"),+ )?;+ let position_embeddings = embedding(+ config.max_position_embeddings,+ config.hidden_size,+ vb.pp("position_embeddings"),+ )?;+ let token_type_embeddings = embedding(+ config.type_vocab_size,+ config.hidden_size,+ vb.pp("token_type_embeddings"),+ )?;+ let layer_norm = FastLayerNorm::load(+ vb.pp("LayerNorm"),+ config.hidden_size,+ config.layer_norm_eps,+ )?;+ Ok(Self {+ word_embeddings,+ position_embeddings,+ token_type_embeddings,+ layer_norm,+ padding_idx: config.pad_token_id,+ })+ }++ fn forward(&self, input_ids: &Tensor, token_type_ids: &Tensor) -> Result<Tensor> {+ let input_embeddings = self.word_embeddings.forward(input_ids)?;+ let token_type_embeddings = self.token_type_embeddings.forward(token_type_ids)?;+ let embeddings = (&input_embeddings + token_type_embeddings)?;+ let mask = input_ids+ .ne(self.padding_idx)?+ .to_dtype(input_embeddings.dtype())?;+ let cumsum = mask.cumsum(1)?;+ let position_ids = (cumsum * mask)?+ .broadcast_add(+ &Tensor::try_from(self.padding_idx)?+ .to_dtype(input_embeddings.dtype())?+ .to_device(input_embeddings.device())?,+ )?+ .to_dtype(DType::U32)?;+ let position_embeddings = self.position_embeddings.forward(&position_ids)?;+ self.layer_norm+ .forward(&embeddings, Some(&position_embeddings))+ }++ fn forward_packed(&self, input_ids: &Tensor, position_ids: &Tensor) -> Result<Tensor> {+ let input_embeddings = self.word_embeddings.forward(input_ids)?;+ let position_embeddings = self.position_embeddings.forward(position_ids)?;+ // Packed XLM-R always uses token type zero. Broadcast that single row instead of+ // allocating zero ids and gathering the same embedding for every token.+ let token_type_embedding = packed_token_type_embedding(&self.token_type_embeddings)?;+ let embeddings = input_embeddings.broadcast_add(&token_type_embedding)?;+ self.layer_norm+ .forward(&embeddings, Some(&position_embeddings))+ }+}++fn packed_token_type_embedding(token_type_embeddings: &Embedding) -> Result<Tensor> {+ token_type_embeddings.embeddings().narrow(0, 0, 1)+}++fn packed_cls_indices(seqlens: &Tensor) -> Result<Tensor> {+ let offset_count = seqlens.dim(0)?;+ if offset_count == 0 {+ candle::bail!("packed XLM-R sequence offsets are empty")+ }+ seqlens.narrow(0, 0, offset_count - 1)+}++fn select_packed_cls_rows(+ self_outputs: &Tensor,+ hidden_states: &Tensor,+ seqlens: &Tensor,+) -> Result<(Tensor, Tensor)> {+ let indices = packed_cls_indices(seqlens)?;+ Ok((+ index_select(self_outputs, &indices, 0)?,+ index_select(hidden_states, &indices, 0)?,+ ))+}++struct XlmRobertaSelfAttention {+ num_attention_heads: usize,+ attention_head_size: usize,+ all_head_size: usize,+ qkv: FastLinear,+}++impl XlmRobertaSelfAttention {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let attention_head_size = cfg.hidden_size / cfg.num_attention_heads;+ let all_head_size = cfg.num_attention_heads * attention_head_size;+ Ok(Self {+ num_attention_heads: cfg.num_attention_heads,+ attention_head_size,+ all_head_size,+ qkv: FastLinear::load_qkv(cfg.hidden_size, all_head_size, vb)?,+ })+ }++ fn qkv(&self, hidden_states: &Tensor) -> Result<Vec<Tensor>> {+ let qkv = self.qkv.forward(hidden_states)?;+ let mut qkv_shape = qkv.dims().to_vec();+ qkv_shape.pop();+ qkv_shape.push(self.num_attention_heads * 3);+ qkv_shape.push(self.attention_head_size);+ let qkv = qkv.reshape(qkv_shape)?;+ qkv.chunk(3, qkv.rank() - 2)+ }++ fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> {+ let qkv = self.qkv(hidden_states)?;+ let query_layer = qkv[0].permute((0, 2, 1, 3))?.contiguous()?;+ let key_layer = qkv[1].permute((0, 2, 1, 3))?.contiguous()?;+ let value_layer = qkv[2].permute((0, 2, 1, 3))?.contiguous()?;+ let mut attention_scores = query_layer.matmul(&key_layer.transpose(2, 3)?)?;+ let scale = 1f64 / f64::sqrt(self.attention_head_size as f64);++ attention_scores = (attention_scores * scale)?;+ attention_scores =+ attention_scores.broadcast_add(&attention_mask.to_dtype(attention_scores.dtype())?)?;+ let attention_probs = softmax_last_dim(&attention_scores)?;++ let context_layer = attention_probs+ .matmul(&value_layer)?+ .permute((0, 2, 1, 3))?+ .contiguous()?;+ let mut new_context_layer_shape =+ context_layer.dims()[..context_layer.dims().len() - 2].to_vec();+ new_context_layer_shape.push(self.all_head_size);+ context_layer.reshape(new_context_layer_shape)+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;+ let qkv = self.qkv(hidden_states)?;+ let query = qkv[0].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ let key = qkv[1].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ let value = qkv[2].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ let attention_output = flash_attn_varlen(+ &query,+ &key,+ &value,+ seqlens,+ max_seqlen,+ self.attention_head_size,+ )?;+ attention_output.reshape((total_tokens, self.all_head_size))+ }++ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let total_tokens = hidden_states.dim(0)?;++ synchronize_if(hidden_states.device(), sync_timings)?;+ let qkv_start = Instant::now();+ let qkv = self.qkv(hidden_states)?;+ let query = qkv[0].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ let key = qkv[1].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ let value = qkv[2].reshape((+ total_tokens,+ self.num_attention_heads,+ self.attention_head_size,+ ))?;+ synchronize_if(query.device(), sync_timings)?;+ profile.attention_qkv_ms += elapsed_ms(qkv_start);++ let flash_start = Instant::now();+ let attention_output = flash_attn_varlen(+ &query,+ &key,+ &value,+ seqlens,+ max_seqlen,+ self.attention_head_size,+ )?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_flash_ms += elapsed_ms(flash_start);++ attention_output.reshape((total_tokens, self.all_head_size))+ }+}++struct XlmRobertaSelfOutput {+ dense: FastLinear,+ layernorm: FastLayerNorm,+}++impl XlmRobertaSelfOutput {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let dense = FastLinear::load(cfg.hidden_size, cfg.hidden_size, vb.pp("dense"), None)?;+ let layernorm =+ FastLayerNorm::load(vb.pp("LayerNorm"), cfg.hidden_size, cfg.layer_norm_eps)?;+ Ok(Self { dense, layernorm })+ }++ fn forward(&self, hidden_states: &Tensor, input_tensor: &Tensor) -> Result<Tensor> {+ let hidden_states = self.dense.forward(hidden_states)?;+ self.layernorm.forward(&hidden_states, Some(input_tensor))+ }++ fn forward_profiled(+ &self,+ hidden_states: &Tensor,+ input_tensor: &Tensor,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let dense_start = Instant::now();+ let hidden_states = self.dense.forward(hidden_states)?;+ synchronize_if(hidden_states.device(), sync_timings)?;+ profile.attention_output_dense_ms += elapsed_ms(dense_start);++ let layernorm_start = Instant::now();+ let output = self.layernorm.forward(&hidden_states, Some(input_tensor))?;+ synchronize_if(output.device(), sync_timings)?;+ profile.attention_output_layernorm_ms += elapsed_ms(layernorm_start);+ Ok(output)+ }+}++struct XlmRobertaAttention {+ output: XlmRobertaSelfOutput,+ self_attention: XlmRobertaSelfAttention,+}++impl XlmRobertaAttention {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let output = XlmRobertaSelfOutput::new(cfg, vb.pp("output"))?;+ let self_attention = XlmRobertaSelfAttention::new(cfg, vb.pp("self"))?;+ Ok(Self {+ output,+ self_attention,+ })+ }++ fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> {+ let self_outputs = self.self_attention.forward(hidden_states, attention_mask)?;+ self.output.forward(&self_outputs, hidden_states)+ }++ fn forward_packed_cls(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let self_outputs =+ self.self_attention+ .forward_packed(hidden_states, seqlens, max_seqlen)?;+ let (self_outputs, hidden_states) =+ select_packed_cls_rows(&self_outputs, hidden_states, seqlens)?;+ self.output.forward(&self_outputs, &hidden_states)+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let self_outputs =+ self.self_attention+ .forward_packed(hidden_states, seqlens, max_seqlen)?;+ self.output.forward(&self_outputs, hidden_states)+ }++ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let self_outputs = self.self_attention.forward_packed_profiled(+ hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ self.output+ .forward_profiled(&self_outputs, hidden_states, profile, sync_timings)+ }++ fn forward_packed_cls_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let self_outputs = self.self_attention.forward_packed_profiled(+ hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ let (self_outputs, hidden_states) =+ select_packed_cls_rows(&self_outputs, hidden_states, seqlens)?;+ self.output+ .forward_profiled(&self_outputs, &hidden_states, profile, sync_timings)+ }+}++struct XlmRobertaOutput {+ dense: FastLinear,+ layernorm: FastLayerNorm,+}++impl XlmRobertaOutput {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let dense = FastLinear::load(cfg.intermediate_size, cfg.hidden_size, vb.pp("dense"), None)?;+ let layernorm =+ FastLayerNorm::load(vb.pp("LayerNorm"), cfg.hidden_size, cfg.layer_norm_eps)?;+ Ok(Self { dense, layernorm })+ }++ fn forward(&self, hidden_states: &Tensor, input_tensor: &Tensor) -> Result<Tensor> {+ let hidden_states = self.dense.forward(hidden_states)?;+ self.layernorm.forward(&hidden_states, Some(input_tensor))+ }++ fn forward_profiled(+ &self,+ hidden_states: &Tensor,+ input_tensor: &Tensor,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let dense_start = Instant::now();+ let hidden_states = self.dense.forward(hidden_states)?;+ synchronize_if(hidden_states.device(), sync_timings)?;+ profile.ffn_output_dense_ms += elapsed_ms(dense_start);++ let layernorm_start = Instant::now();+ let output = self.layernorm.forward(&hidden_states, Some(input_tensor))?;+ synchronize_if(output.device(), sync_timings)?;+ profile.ffn_output_layernorm_ms += elapsed_ms(layernorm_start);+ Ok(output)+ }+}++struct XlmRobertaIntermediate {+ dense: FastLinear,+}++impl XlmRobertaIntermediate {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let dense = FastLinear::load(+ cfg.hidden_size,+ cfg.intermediate_size,+ vb.pp("dense"),+ Some(cfg.hidden_act),+ )?;+ Ok(Self { dense })+ }++ fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> {+ self.dense.forward(hidden_states)+ }++ fn forward_profiled(+ &self,+ hidden_states: &Tensor,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let dense_start = Instant::now();+ let hidden_states = self.dense.forward(hidden_states)?;+ synchronize_if(hidden_states.device(), sync_timings)?;+ profile.ffn_intermediate_dense_ms += elapsed_ms(dense_start);++ Ok(hidden_states)+ }+}++struct XlmRobertaLayer {+ attention: XlmRobertaAttention,+ intermediate: XlmRobertaIntermediate,+ output: XlmRobertaOutput,+}++impl XlmRobertaLayer {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let attention = XlmRobertaAttention::new(cfg, vb.pp("attention"))?;+ let intermediate = XlmRobertaIntermediate::new(cfg, vb.pp("intermediate"))?;+ let output = XlmRobertaOutput::new(cfg, vb.pp("output"))?;+ Ok(Self {+ attention,+ intermediate,+ output,+ })+ }++ fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> {+ let attention_output = self.attention.forward(hidden_states, attention_mask)?;+ let intermediate_output = self.intermediate.forward(&attention_output)?;+ self.output.forward(&intermediate_output, &attention_output)+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let attention_output = self+ .attention+ .forward_packed(hidden_states, seqlens, max_seqlen)?;+ let intermediate_output = self.intermediate.forward(&attention_output)?;+ self.output.forward(&intermediate_output, &attention_output)+ }++ fn forward_packed_cls(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let attention_output =+ self.attention+ .forward_packed_cls(hidden_states, seqlens, max_seqlen)?;+ let intermediate_output = self.intermediate.forward(&attention_output)?;+ self.output.forward(&intermediate_output, &attention_output)+ }++ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let attention_start = Instant::now();+ let attention_output = self.attention.forward_packed_profiled(+ hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_ms += elapsed_ms(attention_start);++ let ffn_start = Instant::now();+ let intermediate_output =+ self.intermediate+ .forward_profiled(&attention_output, profile, sync_timings)?;+ let output = self.output.forward_profiled(+ &intermediate_output,+ &attention_output,+ profile,+ sync_timings,+ )?;+ synchronize_if(output.device(), sync_timings)?;+ profile.ffn_ms += elapsed_ms(ffn_start);+ profile.layers += 1;+ Ok(output)+ }++ fn forward_packed_cls_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ synchronize_if(hidden_states.device(), sync_timings)?;+ let attention_start = Instant::now();+ let attention_output = self.attention.forward_packed_cls_profiled(+ hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ synchronize_if(attention_output.device(), sync_timings)?;+ profile.attention_ms += elapsed_ms(attention_start);++ let ffn_start = Instant::now();+ let intermediate_output =+ self.intermediate+ .forward_profiled(&attention_output, profile, sync_timings)?;+ let output = self.output.forward_profiled(+ &intermediate_output,+ &attention_output,+ profile,+ sync_timings,+ )?;+ synchronize_if(output.device(), sync_timings)?;+ profile.ffn_ms += elapsed_ms(ffn_start);+ profile.layers += 1;+ Ok(output)+ }+}++struct XlmRobertaEncoder {+ layers: Vec<XlmRobertaLayer>,+}++impl XlmRobertaEncoder {+ fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let layers = (0..cfg.num_hidden_layers)+ .map(|i| XlmRobertaLayer::new(cfg, vb.pp(format!("layer.{i}"))))+ .collect::<Result<Vec<_>>>()?;+ Ok(Self { layers })+ }++ fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> {+ let mut hidden_states = hidden_states.clone();+ for layer_module in self.layers.iter() {+ hidden_states = layer_module.forward(&hidden_states, attention_mask)?;+ }+ Ok(hidden_states)+ }++ fn forward_packed(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let mut hidden_states = hidden_states.clone();+ for layer_module in self.layers.iter() {+ hidden_states = layer_module.forward_packed(&hidden_states, seqlens, max_seqlen)?;+ }+ Ok(hidden_states)+ }++ fn forward_packed_cls(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let Some((last_layer, prefix_layers)) = self.layers.split_last() else {+ candle::bail!("packed XLM-R CLS forward requires at least one encoder layer")+ };+ let mut hidden_states = hidden_states.clone();+ for layer_module in prefix_layers {+ hidden_states = layer_module.forward_packed(&hidden_states, seqlens, max_seqlen)?;+ }+ last_layer.forward_packed_cls(&hidden_states, seqlens, max_seqlen)+ }++ fn forward_packed_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let mut hidden_states = hidden_states.clone();+ for layer_module in self.layers.iter() {+ hidden_states = layer_module.forward_packed_profiled(+ &hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ }+ Ok(hidden_states)+ }++ fn forward_packed_cls_profiled(+ &self,+ hidden_states: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ profile: &mut XlmRobertaForwardProfile,+ sync_timings: bool,+ ) -> Result<Tensor> {+ let Some((last_layer, prefix_layers)) = self.layers.split_last() else {+ candle::bail!("packed XLM-R CLS forward requires at least one encoder layer")+ };+ let mut hidden_states = hidden_states.clone();+ for layer_module in prefix_layers {+ hidden_states = layer_module.forward_packed_profiled(+ &hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )?;+ }+ last_layer.forward_packed_cls_profiled(+ &hidden_states,+ seqlens,+ max_seqlen,+ profile,+ sync_timings,+ )+ }+}++pub struct XlmRobertaModel {+ encoder: XlmRobertaEncoder,+ embeddings: XlmRobertaEmbeddings,+ config: Config,+}++impl XlmRobertaModel {+ pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> {+ let encoder = XlmRobertaEncoder::new(cfg, vb.pp("encoder"))?;+ let embeddings = XlmRobertaEmbeddings::load(vb.pp("embeddings"), cfg)?;+ Ok(Self {+ encoder,+ embeddings,+ config: cfg.clone(),+ })+ }++ pub fn kernel_backend(&self) -> (&'static str, &'static str, bool, bool) {+ let linear_backend = self+ .encoder+ .layers+ .first()+ .map(|layer| layer.intermediate.dense.backend())+ .unwrap_or("candle_matmul");+ let ffn_activation_fused = self+ .encoder+ .layers+ .first()+ .map(|layer| layer.intermediate.dense.activation_kernel_fused())+ .unwrap_or(false);+ let layernorm_backend = self.embeddings.layer_norm.backend();+ (+ linear_backend,+ layernorm_backend,+ true,+ ffn_activation_fused,+ )+ }++ pub fn forward(+ &self,+ input_ids: &Tensor,+ attention_mask: &Tensor,+ token_type_ids: &Tensor,+ ) -> Result<Tensor> {+ let hidden_states = self.embeddings.forward(input_ids, token_type_ids)?;+ let attention_mask = prepare_4d_attention_mask(attention_mask, DType::F32, None)?+ .to_device(hidden_states.device())?;+ self.encoder.forward(&hidden_states, &attention_mask)+ }++ pub fn forward_packed(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let hidden_states = self.embeddings.forward_packed(input_ids, position_ids)?;+ self.encoder+ .forward_packed(&hidden_states, seqlens, max_seqlen)+ }++ /// Returns only the final CLS row for each packed sequence as `[batch, hidden]`.+ pub fn forward_packed_cls(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ ) -> Result<Tensor> {+ let hidden_states = self.embeddings.forward_packed(input_ids, position_ids)?;+ self.encoder+ .forward_packed_cls(&hidden_states, seqlens, max_seqlen)+ }++ pub fn forward_packed_profiled(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ sync_timings: bool,+ ) -> Result<(Tensor, XlmRobertaForwardProfile)> {+ synchronize_if(input_ids.device(), sync_timings)?;+ let embedding_start = Instant::now();+ let hidden_states = self.embeddings.forward_packed(input_ids, position_ids)?;+ synchronize_if(hidden_states.device(), sync_timings)?;++ let total_tokens = input_ids.dim(0)?;+ let mut profile = XlmRobertaForwardProfile {+ total_tokens,+ max_seqlen,+ hidden_size: self.config.hidden_size,+ intermediate_size: self.config.intermediate_size,+ attention_heads: self.config.num_attention_heads,+ attention_head_size: self.config.hidden_size / self.config.num_attention_heads,+ linear_gflops: linear_gflops(+ total_tokens,+ self.config.hidden_size,+ self.config.intermediate_size,+ self.config.num_hidden_layers,+ ),+ embedding_ms: elapsed_ms(embedding_start),+ ..Default::default()+ };+ let hidden_states = self.encoder.forward_packed_profiled(+ &hidden_states,+ seqlens,+ max_seqlen,+ &mut profile,+ sync_timings,+ )?;+ Ok((hidden_states, profile))+ }++ /// Profiled variant of [`Self::forward_packed_cls`].+ pub fn forward_packed_cls_profiled(+ &self,+ input_ids: &Tensor,+ position_ids: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ sync_timings: bool,+ ) -> Result<(Tensor, XlmRobertaForwardProfile)> {+ synchronize_if(input_ids.device(), sync_timings)?;+ let embedding_start = Instant::now();+ let hidden_states = self.embeddings.forward_packed(input_ids, position_ids)?;+ synchronize_if(hidden_states.device(), sync_timings)?;++ let total_tokens = input_ids.dim(0)?;+ let batch_size = seqlens.dim(0)?.saturating_sub(1);+ let mut profile = XlmRobertaForwardProfile {+ total_tokens,+ max_seqlen,+ hidden_size: self.config.hidden_size,+ intermediate_size: self.config.intermediate_size,+ attention_heads: self.config.num_attention_heads,+ attention_head_size: self.config.hidden_size / self.config.num_attention_heads,+ linear_gflops: cls_linear_gflops(+ total_tokens,+ batch_size,+ self.config.hidden_size,+ self.config.intermediate_size,+ self.config.num_hidden_layers,+ ),+ embedding_ms: elapsed_ms(embedding_start),+ ..Default::default()+ };+ let hidden_states = self.encoder.forward_packed_cls_profiled(+ &hidden_states,+ seqlens,+ max_seqlen,+ &mut profile,+ sync_timings,+ )?;+ Ok((hidden_states, profile))+ }+}++#[cfg(feature = "cuda")]+fn flash_attn_varlen(+ query: &Tensor,+ key: &Tensor,+ value: &Tensor,+ seqlens: &Tensor,+ max_seqlen: usize,+ head_size: usize,+) -> Result<Tensor> {+ let softmax_scale = 1f32 / f32::sqrt(head_size as f32);+ candle_flash_attn::flash_attn_varlen(+ query,+ key,+ value,+ seqlens,+ seqlens,+ max_seqlen,+ max_seqlen,+ softmax_scale,+ false,+ )+}++#[cfg(not(feature = "cuda"))]+fn flash_attn_varlen(+ _query: &Tensor,+ _key: &Tensor,+ _value: &Tensor,+ _seqlens: &Tensor,+ _max_seqlen: usize,+ _head_size: usize,+) -> Result<Tensor> {+ candle::bail!("packed XLM-R FlashAttention requires the cuda feature")+}++fn prepare_4d_attention_mask(+ mask: &Tensor,+ dtype: DType,+ tgt_len: Option<usize>,+) -> Result<Tensor> {+ let bsz = mask.dim(0)?;+ let src_len = mask.dim(1)?;+ let tgt_len = tgt_len.unwrap_or(src_len);++ let expanded_mask = mask+ .unsqueeze(1)?+ .unsqueeze(2)?+ .expand((bsz, 1, tgt_len, src_len))?+ .to_dtype(dtype)?;++ let inverted_mask = (1.0 - expanded_mask)?;+ (inverted_mask * get_dtype_min_val(dtype))?.to_dtype(dtype)+}++fn get_dtype_min_val(dtype: DType) -> f64 {+ match dtype {+ DType::F32 => f32::MIN as f64,+ DType::F64 => f64::MIN,+ _ => panic!("unsupported attention mask dtype"),+ }+}++fn synchronize_if(device: &Device, enabled: bool) -> Result<()> {+ if enabled {+ device.synchronize()?;+ }+ Ok(())+}++fn elapsed_ms(start: Instant) -> f64 {+ start.elapsed().as_secs_f64() * 1000.0+}++fn linear_gflops(+ tokens: usize,+ hidden_size: usize,+ intermediate_size: usize,+ layers: usize,+) -> f64 {+ let qkv = hidden_size * 3 * hidden_size;+ let attention_output = hidden_size * hidden_size;+ let ffn_intermediate = hidden_size * intermediate_size;+ let ffn_output = intermediate_size * hidden_size;+ 2.0 * tokens as f64+ * layers as f64+ * (qkv + attention_output + ffn_intermediate + ffn_output) as f64+ / 1_000_000_000.0+}++fn cls_linear_gflops(+ tokens: usize,+ batch_size: usize,+ hidden_size: usize,+ intermediate_size: usize,+ layers: usize,+) -> f64 {+ let qkv = hidden_size * 3 * hidden_size;+ let token_local = hidden_size * hidden_size+ + hidden_size * intermediate_size+ + intermediate_size * hidden_size;+ let prefix_rows = tokens * layers.saturating_sub(1);+ 2.0 * (tokens * layers * qkv + (prefix_rows + batch_size) * token_local) as f64+ / 1_000_000_000.0+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn packed_cls_selection_uses_sequence_starts() -> Result<()> {+ let device = Device::Cpu;+ let self_outputs = Tensor::new(+ &[[1f32, 2.], [3., 4.], [5., 6.], [7., 8.], [9., 10.]],+ &device,+ )?;+ let hidden_states = (&self_outputs + 100.0)?;+ let seqlens = Tensor::new(&[0u32, 2, 5], &device)?;++ let (selected_outputs, selected_residuals) =+ select_packed_cls_rows(&self_outputs, &hidden_states, &seqlens)?;++ assert_eq!(+ selected_outputs.to_vec2::<f32>()?,+ vec![vec![1., 2.], vec![5., 6.]]+ );+ assert_eq!(+ selected_residuals.to_vec2::<f32>()?,+ vec![vec![101., 102.], vec![105., 106.]]+ );+ Ok(())+ }++ #[test]+ fn last_layer_cls_tail_matches_full_token_local_tail() -> Result<()> {+ let device = Device::Cpu;+ let config = Config {+ hidden_size: 4,+ layer_norm_eps: 1e-5,+ num_attention_heads: 2,+ intermediate_size: 6,+ hidden_act: HiddenAct::Gelu,+ num_hidden_layers: 1,+ vocab_size: 8,+ max_position_embeddings: 8,+ type_vocab_size: 1,+ pad_token_id: 1,+ };+ let matrix = |rows, columns, offset: f32| {+ Tensor::from_vec(+ (0..rows * columns)+ .map(|index| offset + (index as f32 - 7.0) / 19.0)+ .collect::<Vec<_>>(),+ (rows, columns),+ &device,+ )+ };+ let tensors = std::collections::HashMap::from([+ (+ "attention.output.dense.weight".to_string(),+ matrix(4, 4, -0.2)?,+ ),+ (+ "attention.output.dense.bias".to_string(),+ Tensor::new(&[0.1f32, -0.2, 0.3, -0.4], &device)?,+ ),+ (+ "attention.output.LayerNorm.weight".to_string(),+ Tensor::new(&[0.8f32, 1.1, 0.9, 1.2], &device)?,+ ),+ (+ "attention.output.LayerNorm.bias".to_string(),+ Tensor::new(&[-0.1f32, 0.2, -0.3, 0.4], &device)?,+ ),+ ("intermediate.dense.weight".to_string(), matrix(6, 4, 0.15)?),+ (+ "intermediate.dense.bias".to_string(),+ Tensor::new(&[0.05f32, -0.1, 0.15, -0.2, 0.25, -0.3], &device)?,+ ),+ ("output.dense.weight".to_string(), matrix(4, 6, -0.1)?),+ (+ "output.dense.bias".to_string(),+ Tensor::new(&[-0.05f32, 0.1, -0.15, 0.2], &device)?,+ ),+ (+ "output.LayerNorm.weight".to_string(),+ Tensor::new(&[1.2f32, 0.7, 1.1, 0.9], &device)?,+ ),+ (+ "output.LayerNorm.bias".to_string(),+ Tensor::new(&[0.2f32, -0.1, 0.05, -0.15], &device)?,+ ),+ ]);+ let vb = VarBuilder::from_tensors(tensors, DType::F32, &device);+ let attention_output = XlmRobertaSelfOutput::new(&config, vb.pp("attention.output"))?;+ let intermediate = XlmRobertaIntermediate::new(&config, vb.pp("intermediate"))?;+ let output = XlmRobertaOutput::new(&config, vb.pp("output"))?;+ let self_outputs = matrix(5, 4, -0.35)?;+ let hidden_states = matrix(5, 4, 0.45)?;+ let seqlens = Tensor::new(&[0u32, 2, 5], &device)?;++ let full_attention = attention_output.forward(&self_outputs, &hidden_states)?;+ let full_intermediate = intermediate.forward(&full_attention)?;+ let full_tail = output.forward(&full_intermediate, &full_attention)?;+ let expected = index_select(&full_tail, &packed_cls_indices(&seqlens)?, 0)?;++ let (selected_outputs, selected_residuals) =+ select_packed_cls_rows(&self_outputs, &hidden_states, &seqlens)?;+ let selected_attention =+ attention_output.forward(&selected_outputs, &selected_residuals)?;+ let selected_intermediate = intermediate.forward(&selected_attention)?;+ let actual = output.forward(&selected_intermediate, &selected_attention)?;++ let expected = expected.to_vec2::<f32>()?;+ let actual = actual.to_vec2::<f32>()?;+ assert_eq!(actual.len(), expected.len());+ for (actual_row, expected_row) in actual.iter().zip(&expected) {+ assert_eq!(actual_row.len(), expected_row.len());+ for (&actual, &expected) in actual_row.iter().zip(expected_row) {+ assert!(+ (actual - expected).abs() < 1e-5,+ "CLS tail diverged: actual={actual}, expected={expected}"+ );+ }+ }+ Ok(())+ }++ #[test]+ fn packed_token_type_row_matches_zero_id_gather() -> Result<()> {+ let device = Device::Cpu;+ let table = Tensor::new(&[[1f32, 2., 3.], [4., 5., 6.]], &device)?;+ let embeddings = Embedding::new(table, 3);+ let zero_ids = Tensor::new(&[0u32, 0, 0], &device)?;+ let gathered = embeddings.forward(&zero_ids)?;+ let input = Tensor::zeros((3, 3), DType::F32, &device)?;+ let broadcast = input.broadcast_add(&packed_token_type_embedding(&embeddings)?)?;++ assert_eq!(broadcast.to_vec2::<f32>()?, gathered.to_vec2::<f32>()?);+ Ok(())+ }++ #[test]+ fn cls_linear_gflops_reduces_only_final_token_local_work() {+ let full = linear_gflops(10, 4, 8, 3);+ let cls = cls_linear_gflops(10, 2, 4, 8, 3);+ let one_layer_saved_rows = 10 - 2;+ let token_local = 4 * 4 + 4 * 8 + 8 * 4;+ let expected_saved = 2.0 * (one_layer_saved_rows * token_local) as f64 / 1_000_000_000.0;++ assert!((full - cls - expected_saved).abs() < f64::EPSILON);+ }+}diff --git a/packages/sie_server_rust/src/ipc.rs b/packages/sie_server_rust/src/ipc.rsnew file mode 100644index 000000000..acf1d64a0--- /dev/null+++ b/packages/sie_server_rust/src/ipc.rs@@ -0,0 +1,1076 @@+//! UDS IPC server for the Rust worker process.++use std::collections::HashSet;+use std::path::{Path, PathBuf};+use std::sync::{Arc, RwLock};++use serde::de::DeserializeOwned;+use serde::Serialize;+use sha2::{Digest, Sha256};+use thiserror::Error;+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::{TcpListener, UnixListener, UnixStream};+use tokio::task::JoinSet;+use tracing::{debug, error, info, warn, Instrument};+use tracing_opentelemetry::OpenTelemetrySpanExt;++use crate::ipc_types::{+ ApplyModelConfigRequest, ApplyModelConfigResponse, BatchOutcome, DrainRequest, DrainResponse,+ EnsureModelReadyRequest, ProcessEncodeBatchRequest, ProcessExtractBatchRequest,+ ProcessScoreBatchRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,+ RequestEnvelope, ResponseEnvelope, SetPinnedModelsRequest, SignalGenerateCancelResponse,+ WorkerCapabilitiesResponse, IPC_VERSION, METHOD_APPLY_MODEL_CONFIG, METHOD_DRAIN,+ METHOD_ENSURE_MODEL_READY, METHOD_PING, METHOD_PROCESS_ENCODE_BATCH,+ METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE, METHOD_PROCESS_SCORE_BATCH,+ METHOD_REPLACE_MODEL_CONFIGS, METHOD_RUN_BATCH, METHOD_SET_PINNED_MODELS,+ METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,+};+use crate::native_backend::NativeBackend;+use crate::observability::propagation::{extract_context_from_w3c, remote_span_context};++const MAX_FRAME_BYTES: usize = 32 * 1024 * 1024;+const IPC_RESPONSE_CHUNK_PAYLOAD_BYTES: usize = 4 * 1024 * 1024;+const MAX_CHUNKED_IPC_RESPONSE_BYTES: usize = 128 * 1024 * 1024;+const MAX_IPC_RESPONSE_CHUNKS: u32 = 64;+const IPC_RESPONSE_CHUNK_KIND_V1: &str = "ipc_response_chunk_v1";++#[derive(Debug, Clone)]+pub struct IpcServerConfig {+ pub socket_path: PathBuf,+ pub worker_id: String,+ pub bundle: String,+ pub http_host: String,+ pub http_port: u16,+}++#[derive(Debug, Error)]+pub enum IpcServerError {+ #[error("io: {0}")]+ Io(#[from] std::io::Error),+ #[error("msgpack decode: {0}")]+ Decode(#[from] rmp_serde::decode::Error),+ #[error("msgpack encode: {0}")]+ Encode(#[from] rmp_serde::encode::Error),+ #[error("json conversion: {0}")]+ Json(#[from] serde_json::Error),+ #[error("frame too large: {0} > {MAX_FRAME_BYTES}")]+ FrameTooLarge(u32),+}++#[derive(Clone)]+pub struct IpcServer {+ config: IpcServerConfig,+ backend: Arc<NativeBackend>,+ bundle_config_hash: Arc<RwLock<String>>,+}++impl IpcServer {+ pub fn new(config: IpcServerConfig, backend: NativeBackend) -> Self {+ Self {+ config,+ backend: Arc::new(backend),+ bundle_config_hash: Arc::new(RwLock::new(String::new())),+ }+ }++ pub async fn run(self) -> Result<(), IpcServerError> {+ if let Some(parent) = self.config.socket_path.parent() {+ tokio::fs::create_dir_all(parent).await?;+ }+ unlink_stale_socket(&self.config.socket_path).await?;+ let listener = UnixListener::bind(&self.config.socket_path)?;+ let http_server = self.clone();+ let mut tasks = JoinSet::new();+ tasks.spawn(async move {+ if let Err(e) = http_server.run_http().await {+ error!(error = %e, "rust worker HTTP server stopped");+ }+ });++ info!(+ path = %self.config.socket_path.display(),+ worker_id = %self.config.worker_id,+ bundle = %self.config.bundle,+ "sie-server-rust IPC server listening"+ );++ let shutdown = shutdown_signal();+ tokio::pin!(shutdown);+ loop {+ tokio::select! {+ accepted = listener.accept() => {+ let (stream, _) = accepted?;+ let server = self.clone();+ tasks.spawn(async move {+ if let Err(e) = server.handle_connection(stream).await {+ debug!(error = %e, "IPC connection closed with error");+ }+ });+ }+ _ = &mut shutdown => {+ info!("shutdown signal received");+ break;+ }+ Some(joined) = tasks.join_next() => {+ if let Err(e) = joined {+ warn!(error = %e, "background task failed");+ }+ }+ }+ }++ Ok(())+ }++ async fn handle_connection(&self, mut stream: UnixStream) -> Result<(), IpcServerError> {+ loop {+ let frame = match read_frame(&mut stream).await {+ Ok(frame) => frame,+ Err(IpcServerError::Io(e))+ if matches!(+ e.kind(),+ std::io::ErrorKind::UnexpectedEof+ | std::io::ErrorKind::ConnectionReset+ | std::io::ErrorKind::BrokenPipe+ ) =>+ {+ return Ok(());+ }+ Err(e) => return Err(e),+ };++ let response = self.handle_request_frame(&frame).await?;+ write_response(&mut stream, response).await?;+ }+ }++ async fn handle_request_frame(&self, frame: &[u8]) -> Result<HandledResponse, IpcServerError> {+ let envelope: RequestEnvelope = rmp_serde::from_slice(frame)?;+ let request_id = envelope.request_id.clone();+ let accepts_response_chunks_v1 =+ envelope.version == IPC_VERSION && envelope.accepts_ipc_response_chunks_v1;+ if envelope.version != IPC_VERSION {+ return Ok(HandledResponse {+ payload: response_error(+ &envelope.request_id,+ format!(+ "IPC version mismatch: got {}, expected {}",+ envelope.version, IPC_VERSION+ ),+ )?,+ request_id,+ accepts_response_chunks_v1: false,+ });+ }++ let payload = match envelope.method.as_str() {+ METHOD_PING => {+ let req = body_as::<crate::ipc_types::PingRequest>(envelope.body)?;+ let ready = self.backend.health_ready().await;+ let bundle_config_hash = self+ .bundle_config_hash+ .read()+ .expect("bundle hash lock poisoned")+ .clone();+ response_ok(+ &envelope.request_id,+ crate::ipc_types::PingResponse {+ timestamp_ms: req.timestamp_ms,+ worker_id: self.config.worker_id.clone(),+ ready,+ bundle_config_hash,+ loaded_models: self.backend.loaded_models(),+ },+ )+ }+ METHOD_WORKER_CAPABILITIES => response_ok(&envelope.request_id, {+ let supported_models = self.backend.supported_models();+ let loaded_models = self.backend.loaded_models();+ WorkerCapabilitiesResponse {+ has_generation_models: false,+ generation_models: Vec::new(),+ supported_models: supported_models.clone(),+ loaded_models,+ }+ }),+ METHOD_ENSURE_MODEL_READY => {+ let req = body_as::<EnsureModelReadyRequest>(envelope.body)?;+ let resp = self.backend.ensure_model_ready(&req.model_id).await;+ response_ok(&envelope.request_id, resp)+ }+ METHOD_PROCESS_ENCODE_BATCH => {+ let req = body_as::<ProcessEncodeBatchRequest>(envelope.body)?;+ let resp = self.backend.process_encode_batch(req).await;+ response_ok(&envelope.request_id, resp)+ }+ METHOD_PROCESS_SCORE_BATCH => {+ let req = body_as::<ProcessScoreBatchRequest>(envelope.body)?;+ let resp = self.backend.process_score_batch(req).await;+ response_ok(&envelope.request_id, resp)+ }+ METHOD_PROCESS_EXTRACT_BATCH => {+ let req = body_as::<ProcessExtractBatchRequest>(envelope.body)?;+ response_ok(&envelope.request_id, unsupported_extract(req))+ }+ METHOD_RUN_BATCH => {+ let req = body_as::<crate::ipc_types::RunBatchRequest>(envelope.body)?;+ let op_label = req+ .items+ .first()+ .map(|item| item.op.clone())+ .unwrap_or_default();+ let model_id = req.model_id.clone();+ let batch_id = req.batch_id;+ let batch_size = req.items.len();+ let span = tracing::info_span!(+ "worker.run_batch",+ otel.name = "worker.run_batch",+ sie.op = %op_label,+ sie.model = %model_id,+ sie.batch_id = batch_id,+ sie.batch_size = batch_size,+ );+ {+ let mut linked: HashSet<&str> = HashSet::new();+ if let Some(parent) = req.items.iter().find(|item| {+ remote_span_context(item.traceparent.as_deref(), item.tracestate.as_deref())+ .is_some()+ }) {+ let tp = parent.traceparent.as_deref();+ let ts = parent.tracestate.as_deref();+ let _ = span.set_parent(extract_context_from_w3c(tp, ts));+ if let Some(tp) = tp {+ linked.insert(tp);+ }+ }+ for item in &req.items {+ let Some(tp) = item.traceparent.as_deref() else {+ continue;+ };+ if !linked.insert(tp) {+ continue;+ }+ if let Some(sc) = remote_span_context(Some(tp), item.tracestate.as_deref())+ {+ span.add_link(sc);+ }+ }+ }+ let resp = self.backend.run_batch(req).instrument(span).await;+ response_ok(&envelope.request_id, resp)+ }+ METHOD_APPLY_MODEL_CONFIG => {+ let req = body_as::<ApplyModelConfigRequest>(envelope.body)?;+ if let Err(error) = self.backend.apply_model_config(&req) {+ return Ok(HandledResponse {+ payload: response_error(&envelope.request_id, error.to_string())?,+ request_id,+ accepts_response_chunks_v1,+ });+ }+ {+ let mut hash = self+ .bundle_config_hash+ .write()+ .expect("bundle hash lock poisoned");+ *hash = req.bundle_config_hash.clone();+ }+ response_ok(+ &envelope.request_id,+ ApplyModelConfigResponse {+ applied: true,+ bundle_config_hash: req.bundle_config_hash,+ config_version: req.epoch,+ },+ )+ }+ METHOD_REPLACE_MODEL_CONFIGS => {+ let req = body_as::<ReplaceModelConfigsRequest>(envelope.body)?;+ let applied_models = match self.backend.replace_model_configs(&req) {+ Ok(models) => models,+ Err(error) => {+ return Ok(HandledResponse {+ payload: response_error(&envelope.request_id, error.to_string())?,+ request_id,+ accepts_response_chunks_v1,+ });+ }+ };+ let applied_profiles = applied_profiles(&applied_models);+ {+ let mut hash = self+ .bundle_config_hash+ .write()+ .expect("bundle hash lock poisoned");+ *hash = req.bundle_config_hash.clone();+ }+ response_ok(+ &envelope.request_id,+ ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: req.bundle_config_hash,+ config_version: req.epoch,+ applied_models,+ applied_profiles,+ },+ )+ }+ METHOD_SET_PINNED_MODELS => {+ let req = body_as::<SetPinnedModelsRequest>(envelope.body)?;+ let resp = self.backend.set_pinned_models(&req);+ response_ok(&envelope.request_id, resp)+ }+ METHOD_DRAIN => {+ let _req = body_as::<DrainRequest>(envelope.body)?;+ response_ok(&envelope.request_id, DrainResponse { acknowledged: true })+ }+ METHOD_SIGNAL_GENERATE_CANCEL => response_ok(+ &envelope.request_id,+ SignalGenerateCancelResponse { matched: false },+ ),+ METHOD_PROCESS_GENERATE => response_error(+ &envelope.request_id,+ "sie-server-rust does not support generation".to_string(),+ ),+ other => response_error(&envelope.request_id, format!("unknown IPC method {other}")),+ }?;+ Ok(HandledResponse {+ payload,+ request_id,+ accepts_response_chunks_v1,+ })+ }++ #[cfg(test)]+ async fn handle_frame(&self, frame: &[u8]) -> Result<Vec<u8>, IpcServerError> {+ Ok(self.handle_request_frame(frame).await?.payload)+ }++ async fn run_http(self) -> Result<(), IpcServerError> {+ let listener =+ TcpListener::bind((self.config.http_host.as_str(), self.config.http_port)).await?;+ let addr = listener.local_addr()?;+ info!(addr = %addr, "sie-server-rust HTTP health server listening");++ loop {+ let (mut socket, _) = listener.accept().await?;+ let server = self.clone();+ tokio::spawn(async move {+ let mut buf = [0u8; 1024];+ let n = match socket.read(&mut buf).await {+ Ok(n) => n,+ Err(_) => return,+ };+ let request = String::from_utf8_lossy(&buf[..n]);+ let path = request+ .lines()+ .next()+ .and_then(|line| line.split_whitespace().nth(1))+ .unwrap_or("/");++ let (status, content_type, body) = match path {+ "/healthz" | "/livez" => ("200 OK", "text/plain", "ok".to_string()),+ "/readyz" => {+ if server.backend.health_ready().await {+ ("200 OK", "text/plain", "ready".to_string())+ } else {+ (+ "503 Service Unavailable",+ "text/plain",+ "not ready".to_string(),+ )+ }+ }+ _ => ("404 Not Found", "text/plain", "not found".to_string()),+ };+ let response = format!(+ "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",+ body.len()+ );+ let _ = socket.write_all(response.as_bytes()).await;+ });+ }+ }+}++struct HandledResponse {+ payload: Vec<u8>,+ request_id: String,+ accepts_response_chunks_v1: bool,+}++enum ResponsePlan {+ Legacy(Vec<u8>),+ Chunked {+ payload: Vec<u8>,+ request_id: String,+ transfer_digest: [u8; 32],+ chunk_count: u32,+ chunk_payload_bytes: usize,+ },+}++/// Serialize-only response-chunk view. Borrowing the complete response slice+/// avoids allocating a second `Vec<u8>` for every physical chunk before+/// `rmp_serde` writes the UDS frame.+#[derive(Serialize)]+struct IpcResponseChunkV1Ref<'a> {+ version: u32,+ request_id: &'a str,+ #[serde(with = "serde_bytes")]+ transfer_digest: &'a [u8],+ chunk_index: u32,+ chunk_count: u32,+ total_bytes: u64,+ #[serde(with = "serde_bytes")]+ payload: &'a [u8],+ kind: &'a str,+}++fn plan_response(response: HandledResponse) -> Result<ResponsePlan, IpcServerError> {+ plan_response_with_limits(+ response,+ MAX_FRAME_BYTES,+ IPC_RESPONSE_CHUNK_PAYLOAD_BYTES,+ MAX_CHUNKED_IPC_RESPONSE_BYTES,+ MAX_IPC_RESPONSE_CHUNKS,+ )+}++fn plan_response_with_limits(+ response: HandledResponse,+ max_frame_bytes: usize,+ chunk_payload_bytes: usize,+ max_chunked_bytes: usize,+ max_chunks: u32,+) -> Result<ResponsePlan, IpcServerError> {+ if response.payload.len() <= max_frame_bytes {+ return Ok(ResponsePlan::Legacy(response.payload));+ }+ if !response.accepts_response_chunks_v1 {+ return Ok(ResponsePlan::Legacy(response_error(+ &response.request_id,+ "IPC response exceeds the legacy frame limit; response chunking v1 was not negotiated"+ .to_string(),+ )?));+ }++ if chunk_payload_bytes == 0 || max_chunks == 0 {+ return Ok(ResponsePlan::Legacy(response_error(+ &response.request_id,+ "IPC response exceeds the negotiated response chunking v1 bounds".to_string(),+ )?));+ }++ let chunk_count = response.payload.len().div_ceil(chunk_payload_bytes);+ if response.payload.len() > max_chunked_bytes || chunk_count > max_chunks as usize {+ return Ok(ResponsePlan::Legacy(response_error(+ &response.request_id,+ "IPC response exceeds the negotiated response chunking v1 bounds".to_string(),+ )?));+ }++ Ok(ResponsePlan::Chunked {+ transfer_digest: Sha256::digest(&response.payload).into(),+ payload: response.payload,+ request_id: response.request_id,+ chunk_count: chunk_count as u32,+ chunk_payload_bytes,+ })+}++fn encode_response_chunk(+ payload: &[u8],+ request_id: &str,+ transfer_digest: &[u8; 32],+ chunk_index: u32,+ chunk_count: u32,+ chunk_payload_bytes: usize,+) -> Result<Vec<u8>, IpcServerError> {+ let start = chunk_index as usize * chunk_payload_bytes;+ let end = (start + chunk_payload_bytes).min(payload.len());+ Ok(rmp_serde::to_vec_named(&IpcResponseChunkV1Ref {+ version: IPC_VERSION,+ request_id,+ transfer_digest,+ chunk_index,+ chunk_count,+ total_bytes: payload.len() as u64,+ payload: &payload[start..end],+ kind: IPC_RESPONSE_CHUNK_KIND_V1,+ })?)+}++async fn write_response(+ stream: &mut UnixStream,+ response: HandledResponse,+) -> Result<(), IpcServerError> {+ match plan_response(response)? {+ ResponsePlan::Legacy(payload) => write_frame(stream, &payload).await,+ ResponsePlan::Chunked {+ payload,+ request_id,+ transfer_digest,+ chunk_count,+ chunk_payload_bytes,+ } => {+ for chunk_index in 0..chunk_count {+ let frame = encode_response_chunk(+ &payload,+ &request_id,+ &transfer_digest,+ chunk_index,+ chunk_count,+ chunk_payload_bytes,+ )?;+ write_frame(stream, &frame).await?;+ }+ Ok(())+ }+ }+}++fn body_as<T: DeserializeOwned>(body: serde_json::Value) -> Result<T, IpcServerError> {+ Ok(serde_json::from_value(body)?)+}++fn applied_profiles(applied_models: &[String]) -> Vec<String> {+ let mut profiles = applied_models+ .iter()+ .map(|model_id| {+ model_id+ .rsplit_once(':')+ .map_or("default", |(_, profile)| profile)+ .to_string()+ })+ .collect::<HashSet<_>>()+ .into_iter()+ .collect::<Vec<_>>();+ profiles.sort();+ profiles+}++fn response_ok<T: Serialize>(request_id: &str, body: T) -> Result<Vec<u8>, IpcServerError> {+ let envelope = ResponseEnvelope {+ version: IPC_VERSION,+ request_id: request_id.to_string(),+ ok: true,+ body: Some(body),+ error: None,+ };+ Ok(rmp_serde::to_vec_named(&envelope)?)+}++fn response_error(request_id: &str, error: String) -> Result<Vec<u8>, IpcServerError> {+ let envelope: ResponseEnvelope<serde_json::Value> = ResponseEnvelope {+ version: IPC_VERSION,+ request_id: request_id.to_string(),+ ok: false,+ body: None,+ error: Some(error),+ };+ Ok(rmp_serde::to_vec_named(&envelope)?)+}++async fn read_frame(stream: &mut UnixStream) -> Result<Vec<u8>, IpcServerError> {+ let mut len_buf = [0u8; 4];+ stream.read_exact(&mut len_buf).await?;+ let len = u32::from_be_bytes(len_buf);+ if len as usize > MAX_FRAME_BYTES {+ return Err(IpcServerError::FrameTooLarge(len));+ }+ let mut buf = vec![0u8; len as usize];+ stream.read_exact(&mut buf).await?;+ Ok(buf)+}++async fn write_frame(stream: &mut UnixStream, payload: &[u8]) -> Result<(), IpcServerError> {+ if payload.len() > MAX_FRAME_BYTES {+ return Err(IpcServerError::FrameTooLarge(+ u32::try_from(payload.len()).unwrap_or(u32::MAX),+ ));+ }+ let len = u32::try_from(payload.len()).map_err(|_| IpcServerError::FrameTooLarge(u32::MAX))?;+ stream.write_all(&len.to_be_bytes()).await?;+ stream.write_all(payload).await?;+ Ok(())+}++async fn unlink_stale_socket(path: &Path) -> Result<(), std::io::Error> {+ match tokio::fs::remove_file(path).await {+ Ok(()) => Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(e) => Err(e),+ }+}++#[cfg(unix)]+async fn shutdown_signal() {+ use tokio::signal::unix::{signal, SignalKind};++ let mut terminate = signal(SignalKind::terminate()).expect("install SIGTERM handler");+ tokio::select! {+ _ = tokio::signal::ctrl_c() => {}+ _ = terminate.recv() => {}+ }+}++#[cfg(not(unix))]+async fn shutdown_signal() {+ let _ = tokio::signal::ctrl_c().await;+}++fn unsupported_extract(req: ProcessExtractBatchRequest) -> BatchOutcome {+ BatchOutcome {+ outcomes: req+ .items+ .into_iter()+ .map(|item| crate::ipc_types::ItemOutcome {+ work_item_id: item.work_item_id,+ request_id: item.request_id,+ item_index: item.item_index,+ disposition: crate::ipc_types::Disposition::PublishErrorAndAck,+ nak_delay_ms: None,+ result_msgpack: Vec::new(),+ error: Some("sie-server-rust native backend does not support extract".to_string()),+ error_code: Some("native_unsupported_operation".to_string()),+ inference_ms: None,+ tokenization_ms: None,+ postprocessing_ms: None,+ raw_output: None,+ units: None,+ })+ .collect(),+ batched_f16_multivectors: Vec::new(),+ }+}++#[cfg(test)]+mod tests {+ use std::path::PathBuf;++ use serde::Serialize;+ use serde_json::json;++ use super::*;+ use crate::candle_backend::{CandleBackend, CandleBackendConfig};+ use crate::ipc_types::{+ IpcResponseChunkV1, METHOD_APPLY_MODEL_CONFIG, METHOD_PING, METHOD_REPLACE_MODEL_CONFIGS,+ METHOD_SET_PINNED_MODELS, METHOD_WORKER_CAPABILITIES,+ };++ #[derive(Serialize)]+ struct TestRequestEnvelope {+ version: u32,+ method: String,+ request_id: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ accepts_ipc_response_chunks_v1: Option<bool>,+ body: serde_json::Value,+ }++ fn test_server() -> IpcServer {+ IpcServer::new(+ IpcServerConfig {+ socket_path: PathBuf::from("/tmp/sie-server-rust-test.sock"),+ worker_id: "worker-test".to_string(),+ bundle: "candle".to_string(),+ http_host: "127.0.0.1".to_string(),+ http_port: 0,+ },+ NativeBackend::Candle(CandleBackend::new(CandleBackendConfig::new(64, true, 1))),+ )+ }++ fn request_frame(method: &str, body: serde_json::Value) -> Vec<u8> {+ rmp_serde::to_vec_named(&TestRequestEnvelope {+ version: IPC_VERSION,+ method: method.to_string(),+ request_id: "req-1".to_string(),+ accepts_ipc_response_chunks_v1: None,+ body,+ })+ .expect("encode request")+ }++ #[test]+ fn applied_profile_ids_are_bounded_to_successful_routes() {+ assert_eq!(+ applied_profiles(&[+ "BAAI/bge-m3".to_string(),+ "Qwen/Qwen3.6-27B:candle".to_string(),+ "other/model:candle".to_string(),+ ]),+ vec!["candle".to_string(), "default".to_string()]+ );+ }++ #[tokio::test]+ async fn replace_model_configs_reports_applied_profiles() {+ let server = test_server();+ let response = server+ .handle_frame(&request_frame(+ METHOD_REPLACE_MODEL_CONFIGS,+ json!({+ "bundle_id": "candle",+ "epoch": 1,+ "bundle_config_hash": "hash-candle",+ "models": [{+ "model_id": "BAAI/bge-m3",+ "model_config": concat!(+ "sie_id: BAAI/bge-m3\n",+ "profiles:\n",+ " candle:\n",+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n",+ ),+ }],+ }),+ ))+ .await+ .expect("replace config");+ let envelope: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&response).expect("decode replace response");+ assert!(envelope.ok, "unexpected IPC error: {:?}", envelope.error);+ let body = envelope.body.expect("replace response body");+ assert_eq!(body.get("applied_profiles"), Some(&json!(["candle"])));+ }++ fn request_frame_with_response_chunks(method: &str, body: serde_json::Value) -> Vec<u8> {+ rmp_serde::to_vec_named(&TestRequestEnvelope {+ version: IPC_VERSION,+ method: method.to_string(),+ request_id: "req-chunked".to_string(),+ accepts_ipc_response_chunks_v1: Some(true),+ body,+ })+ .expect("encode chunk-capable request")+ }++ #[tokio::test]+ async fn request_chunk_capability_is_explicit_and_defaults_false() {+ let server = test_server();+ let legacy = server+ .handle_request_frame(&request_frame(METHOD_PING, json!({"timestamp_ms": 1.0})))+ .await+ .unwrap();+ assert!(!legacy.accepts_response_chunks_v1);++ let negotiated = server+ .handle_request_frame(&request_frame_with_response_chunks(+ METHOD_PING,+ json!({"timestamp_ms": 1.0}),+ ))+ .await+ .unwrap();+ assert!(negotiated.accepts_response_chunks_v1);+ assert_eq!(negotiated.request_id, "req-chunked");+ }++ #[test]+ fn small_negotiated_response_preserves_exact_legacy_bytes() {+ let payload = response_ok("r", json!({"value": [1, 2, 3]})).unwrap();+ let plan = plan_response_with_limits(+ HandledResponse {+ payload: payload.clone(),+ request_id: "r".to_string(),+ accepts_response_chunks_v1: true,+ },+ 512,+ 128,+ 4096,+ 64,+ )+ .unwrap();++ match plan {+ ResponsePlan::Legacy(actual) => assert_eq!(actual, payload),+ ResponsePlan::Chunked { .. } => panic!("small response must remain one legacy frame"),+ }+ }++ #[test]+ fn negotiated_response_chunks_reassemble_exact_serialized_bytes() {+ let payload = response_ok("r", json!({"blob": "x".repeat(1200)})).unwrap();+ let plan = plan_response_with_limits(+ HandledResponse {+ payload: payload.clone(),+ request_id: "r".to_string(),+ accepts_response_chunks_v1: true,+ },+ 512,+ 128,+ 4096,+ 64,+ )+ .unwrap();++ let ResponsePlan::Chunked {+ payload: planned_payload,+ request_id,+ transfer_digest,+ chunk_count,+ chunk_payload_bytes,+ } = plan+ else {+ panic!("oversized negotiated response must be chunked");+ };+ let mut reconstructed = Vec::new();+ for chunk_index in 0..chunk_count {+ let frame = encode_response_chunk(+ &planned_payload,+ &request_id,+ &transfer_digest,+ chunk_index,+ chunk_count,+ chunk_payload_bytes,+ )+ .unwrap();+ assert!(frame.len() <= 512);+ let chunk: IpcResponseChunkV1 = rmp_serde::from_slice(&frame).unwrap();+ assert_eq!(chunk.kind, IPC_RESPONSE_CHUNK_KIND_V1);+ assert_eq!(chunk.request_id, "r");+ assert_eq!(chunk.chunk_index, chunk_index);+ assert_eq!(chunk.chunk_count, chunk_count);+ assert_eq!(chunk.total_bytes, payload.len() as u64);+ assert_eq!(chunk.transfer_digest, transfer_digest);+ reconstructed.extend_from_slice(&chunk.payload);+ }+ assert_eq!(reconstructed, payload);+ let reconstructed_digest: [u8; 32] = Sha256::digest(&reconstructed).into();+ assert_eq!(reconstructed_digest, transfer_digest);+ }++ #[test]+ fn borrowed_response_chunk_encoding_matches_owned_wire_at_bin_boundaries() {+ for payload_len in [255, 256, 65_535, 65_536] {+ let payload = vec![7; payload_len];+ let digest = [9_u8; 32];+ let borrowed = IpcResponseChunkV1Ref {+ version: IPC_VERSION,+ request_id: "r",+ transfer_digest: &digest,+ chunk_index: 0,+ chunk_count: 1,+ total_bytes: payload_len as u64,+ payload: &payload,+ kind: IPC_RESPONSE_CHUNK_KIND_V1,+ };+ let borrowed_bytes = rmp_serde::to_vec_named(&borrowed).unwrap();+ let owned = IpcResponseChunkV1 {+ version: IPC_VERSION,+ request_id: "r".to_string(),+ transfer_digest: digest.to_vec(),+ chunk_index: 0,+ chunk_count: 1,+ total_bytes: payload_len as u64,+ payload,+ kind: IPC_RESPONSE_CHUNK_KIND_V1.to_string(),+ };++ assert_eq!(+ borrowed_bytes,+ rmp_serde::to_vec_named(&owned).unwrap(),+ "payload length {payload_len}"+ );+ }+ }++ #[test]+ fn absent_capability_and_overbound_response_return_compact_legacy_error() {+ for (accepts, max_chunked, max_chunks) in+ [(false, 4096, 64), (true, 800, 64), (true, 4096, 4)]+ {+ let payload = response_ok("r", json!({"blob": "x".repeat(1200)})).unwrap();+ let plan = plan_response_with_limits(+ HandledResponse {+ payload,+ request_id: "r".to_string(),+ accepts_response_chunks_v1: accepts,+ },+ 512,+ 128,+ max_chunked,+ max_chunks,+ )+ .unwrap();+ let ResponsePlan::Legacy(error) = plan else {+ panic!("unsupported/overbound response must be a compact legacy error");+ };+ assert!(error.len() <= 512);+ let error: ResponseEnvelope<serde_json::Value> = rmp_serde::from_slice(&error).unwrap();+ assert!(!error.ok);+ assert_eq!(error.request_id, "r");+ }+ }++ #[test]+ fn invalid_chunk_planning_limits_return_compact_legacy_error() {+ for (chunk_payload_bytes, max_chunks) in [(0, 64), (128, 0)] {+ let payload = response_ok("r", json!({"blob": "x".repeat(1200)})).unwrap();+ let plan = plan_response_with_limits(+ HandledResponse {+ payload,+ request_id: "r".to_string(),+ accepts_response_chunks_v1: true,+ },+ 512,+ chunk_payload_bytes,+ 4096,+ max_chunks,+ )+ .unwrap();+ let ResponsePlan::Legacy(error) = plan else {+ panic!("invalid planning limits must produce a compact legacy error");+ };+ assert!(error.len() <= 512);+ let error: ResponseEnvelope<serde_json::Value> = rmp_serde::from_slice(&error).unwrap();+ assert!(!error.ok);+ assert_eq!(error.request_id, "r");+ }+ }++ #[tokio::test]+ async fn ping_reports_candle_readiness_after_config_apply() {+ let server = test_server();++ let before = server+ .handle_frame(&request_frame(METHOD_PING, json!({"timestamp_ms": 123.0})))+ .await+ .expect("ping before config");+ let before: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&before).expect("decode ping before config");+ assert!(before.ok, "unexpected IPC error: {:?}", before.error);+ let body = before.body.expect("ping body");+ assert_eq!(body.get("worker_id"), Some(&json!("worker-test")));+ assert_eq!(body.get("ready"), Some(&json!(false)));++ let apply = server+ .handle_frame(&request_frame(+ METHOD_APPLY_MODEL_CONFIG,+ json!({+ "bundle_id": "candle",+ "model_id": "BAAI/bge-m3",+ "epoch": 1,+ "bundle_config_hash": "hash-candle",+ "profiles_added": ["candle"],+ "model_config": r#"+sie_id: BAAI/bge-m3+profiles:+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+"#,+ }),+ ))+ .await+ .expect("apply config");+ let apply: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&apply).expect("decode apply response");+ assert!(apply.ok, "unexpected IPC error: {:?}", apply.error);++ let after = server+ .handle_frame(&request_frame(METHOD_PING, json!({"timestamp_ms": 456.0})))+ .await+ .expect("ping after config");+ let after: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&after).expect("decode ping after config");+ assert!(after.ok, "unexpected IPC error: {:?}", after.error);+ let body = after.body.expect("ping body");+ assert_eq!(body.get("ready"), Some(&json!(true)));+ assert_eq!(body.get("bundle_config_hash"), Some(&json!("hash-candle")));+ }++ #[tokio::test]+ async fn set_pinned_models_frame_is_dispatched() {+ let server = test_server();+ let frame = request_frame(+ METHOD_SET_PINNED_MODELS,+ json!({+ "models": [+ " BAAI/bge-m3:default ",+ "BAAI/bge-m3:CANDLE",+ ""+ ]+ }),+ );++ let response = server.handle_frame(&frame).await.expect("handle frame");+ let envelope: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&response).expect("decode response");++ assert!(envelope.ok, "unexpected IPC error: {:?}", envelope.error);+ assert_eq!(envelope.request_id, "req-1");+ let body = envelope.body.expect("response body");+ assert_eq!(+ body.get("applied").and_then(serde_json::Value::as_bool),+ Some(true)+ );+ assert_eq!(+ body.get("pinned_count").and_then(serde_json::Value::as_u64),+ Some(2)+ );+ }++ #[tokio::test]+ async fn worker_capabilities_still_reports_supported_models_after_pinned_rpc() {+ let server = test_server();+ let response = server+ .handle_frame(&request_frame(METHOD_WORKER_CAPABILITIES, json!({})))+ .await+ .expect("worker capabilities before config");+ let envelope: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&response).expect("decode response");++ assert!(envelope.ok, "unexpected IPC error: {:?}", envelope.error);+ let body = envelope.body.expect("response body");+ assert_eq!(body.get("supported_models"), Some(&json!([])));++ let apply_frame = request_frame(+ METHOD_APPLY_MODEL_CONFIG,+ json!({+ "bundle_id": "candle",+ "model_id": "BAAI/bge-m3",+ "epoch": 1,+ "bundle_config_hash": "hash",+ "profiles_added": ["candle"],+ "model_config": concat!(+ "sie_id: BAAI/bge-m3\n",+ "profiles:\n",+ " candle:\n",+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n",+ ),+ }),+ );+ let apply_response = server+ .handle_frame(&apply_frame)+ .await+ .expect("apply catalog config");+ let apply_envelope: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&apply_response).expect("decode apply response");+ assert!(+ apply_envelope.ok,+ "unexpected IPC error: {:?}",+ apply_envelope.error+ );++ let frame = request_frame(+ METHOD_SET_PINNED_MODELS,+ json!({"models": ["not/catalogued:candle"]}),+ );+ let _ = server.handle_frame(&frame).await.expect("set pinned");++ let response = server+ .handle_frame(&request_frame(METHOD_WORKER_CAPABILITIES, json!({})))+ .await+ .expect("worker capabilities");+ let envelope: ResponseEnvelope<serde_json::Value> =+ rmp_serde::from_slice(&response).expect("decode response");++ assert!(envelope.ok, "unexpected IPC error: {:?}", envelope.error);+ let body = envelope.body.expect("response body");+ assert_eq!(+ body.get("supported_models"),+ Some(&json!(["BAAI/bge-m3:candle"]))+ );+ assert_eq!(body.get("loaded_models"), Some(&json!([])));+ }+}diff --git a/packages/sie_server_rust/src/ipc_types.rs b/packages/sie_server_rust/src/ipc_types.rsnew file mode 100644index 000000000..e13fc68f4--- /dev/null+++ b/packages/sie_server_rust/src/ipc_types.rs@@ -0,0 +1,725 @@+//! IPC wire types for the Rust worker.+//!+//! This mirrors the subset of `sie_server_sidecar::protocol::ipc_types`+//! needed by a Rust adapter process. The response-chunk v1 envelope and+//! limits are pinned across the native worker, sidecar, and Python worker by+//! `tools/check_response_chunk_protocol.py`. The wire format is named-map+//! msgpack framed as `[4-byte BE length][msgpack body]`.++use half::f16;+use serde::{Deserialize, Serialize};++pub const IPC_VERSION: u32 = 1;++pub const METHOD_PING: &str = "Ping";+pub const METHOD_ENSURE_MODEL_READY: &str = "EnsureModelReady";+pub const METHOD_PROCESS_ENCODE_BATCH: &str = "ProcessEncodeBatch";+pub const METHOD_PROCESS_SCORE_BATCH: &str = "ProcessScoreBatch";+pub const METHOD_PROCESS_EXTRACT_BATCH: &str = "ProcessExtractBatch";+pub const METHOD_PROCESS_GENERATE: &str = "ProcessGenerate";+pub const METHOD_WORKER_CAPABILITIES: &str = "WorkerCapabilities";+pub const METHOD_SIGNAL_GENERATE_CANCEL: &str = "SignalGenerateCancel";+pub const METHOD_RUN_BATCH: &str = "RunBatch";+pub const METHOD_APPLY_MODEL_CONFIG: &str = "ApplyModelConfig";+pub const METHOD_REPLACE_MODEL_CONFIGS: &str = "ReplaceModelConfigs";+pub const METHOD_SET_PINNED_MODELS: &str = "SetPinnedModels";+pub const METHOD_DRAIN: &str = "Drain";++#[derive(Debug, Clone, Deserialize)]+pub struct RequestEnvelope {+ pub version: u32,+ pub method: String,+ pub request_id: String,+ /// Explicit v1-only negotiation for oversized non-streaming response+ /// chunks. Missing/false preserves the legacy one-frame response.+ #[serde(default)]+ pub accepts_ipc_response_chunks_v1: bool,+ #[serde(default)]+ pub body: serde_json::Value,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResponseEnvelope<B> {+ pub version: u32,+ pub request_id: String,+ pub ok: bool,+ #[serde(default)]+ pub body: Option<B>,+ #[serde(default)]+ pub error: Option<String>,+}++/// One negotiated chunk of an oversized serialized [`ResponseEnvelope`].+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct IpcResponseChunkV1 {+ pub version: u32,+ pub request_id: String,+ #[serde(with = "serde_bytes")]+ pub transfer_digest: Vec<u8>,+ pub chunk_index: u32,+ pub chunk_count: u32,+ pub total_bytes: u64,+ #[serde(with = "serde_bytes")]+ pub payload: Vec<u8>,+ pub kind: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PingRequest {+ pub timestamp_ms: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PingResponse {+ #[serde(default)]+ pub timestamp_ms: f64,+ #[serde(default)]+ pub worker_id: String,+ #[serde(default)]+ pub ready: bool,+ #[serde(default)]+ pub bundle_config_hash: String,+ #[serde(default)]+ pub loaded_models: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EnsureModelReadyRequest {+ pub model_id: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ReadinessState {+ Ready,+ LoadingStarted,+ LoadingInProgress,+ RetryLater,+ /// Terminal, non-retryable load failure (registry recorded a+ /// permanent `LoadFailure`, `cooldown=permanent`). The sidecar+ /// dead-letters the group as `MODEL_LOAD_FAILED` instead of+ /// re-driving `EnsureModelReady` forever. Wire string: `"failed"`.+ Failed,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct ModelDescriptor {+ #[serde(default)]+ pub tokenizer_path: Option<String>,+ #[serde(default)]+ pub tokenizer_id: Option<String>,+ #[serde(default)]+ pub max_seq_len: Option<u32>,+ #[serde(default)]+ pub output_types: Vec<String>,+ #[serde(default)]+ pub supports_run_batch: bool,+ #[serde(default)]+ pub default_query_template: Option<String>,+ #[serde(default)]+ pub default_doc_template: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EnsureModelReadyResponse {+ pub state: ReadinessState,+ #[serde(default)]+ pub batch_budget: Option<u32>,+ #[serde(default)]+ pub descriptor: Option<ModelDescriptor>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApplyModelConfigRequest {+ pub bundle_id: String,+ pub model_id: String,+ pub epoch: u64,+ pub bundle_config_hash: String,+ #[serde(default)]+ pub profiles_added: Vec<String>,+ pub model_config: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApplyModelConfigResponse {+ pub applied: bool,+ pub bundle_config_hash: String,+ #[serde(default)]+ pub config_version: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigEntry {+ pub model_id: String,+ pub model_config: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigsRequest {+ pub bundle_id: String,+ pub epoch: u64,+ pub bundle_config_hash: String,+ pub models: Vec<ReplaceModelConfigEntry>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ReplaceModelConfigsResponse {+ pub applied: bool,+ pub bundle_config_hash: String,+ #[serde(default)]+ pub config_version: u64,+ #[serde(default)]+ pub applied_models: Vec<String>,+ #[serde(default)]+ pub applied_profiles: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SetPinnedModelsRequest {+ #[serde(default)]+ pub models: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SetPinnedModelsResponse {+ pub applied: bool,+ #[serde(default)]+ pub pinned_count: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WorkerCapabilitiesRequest {}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct WorkerCapabilitiesResponse {+ #[serde(default)]+ pub has_generation_models: bool,+ #[serde(default)]+ pub generation_models: Vec<String>,+ #[serde(default)]+ pub supported_models: Vec<String>,+ #[serde(default)]+ pub loaded_models: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SignalGenerateCancelRequest {+ pub request_id: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SignalGenerateCancelResponse {+ #[serde(default)]+ pub matched: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PreparedTokens {+ pub input_ids: Vec<Vec<u32>>,+ #[serde(default)]+ pub attention_mask: Vec<Vec<u32>>,+ #[serde(default)]+ pub token_type_ids: Vec<Vec<u32>>,+ pub tokenizer_id: String,+ #[serde(default)]+ pub max_seq_len: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct EncodeBatchItem {+ pub work_item_id: String,+ pub request_id: String,+ pub item_index: u32,+ pub total_items: u32,+ pub timestamp: f64,+ pub item: serde_json::Value,+ #[serde(default)]+ pub output_types: Option<Vec<String>>,+ #[serde(default)]+ pub instruction: Option<String>,+ #[serde(default)]+ pub is_query: bool,+ #[serde(default)]+ pub options: Option<serde_json::Value>,+ #[serde(default)]+ pub profile_id: Option<String>,+ #[serde(default)]+ pub bundle_config_hash: Option<String>,+ #[serde(default)]+ pub payload_fetch_ms: f64,+ #[serde(default)]+ pub prepared_tokens: Option<PreparedTokens>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ProcessEncodeBatchRequest {+ pub model_id: String,+ pub items: Vec<EncodeBatchItem>,+ /// Opt-in for the additive shared-buffer multivector response. Keeping+ /// this false by default preserves a safe per-item fallback while a+ /// worker and sidecar are rolled independently.+ #[serde(default)]+ pub accepts_batched_f16_multivectors: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ScoreBatchItem {+ pub work_item_id: String,+ pub request_id: String,+ pub item_index: u32,+ pub total_items: u32,+ pub timestamp: f64,+ pub query_item: serde_json::Value,+ pub score_items: Vec<serde_json::Value>,+ #[serde(default)]+ pub instruction: Option<String>,+ #[serde(default)]+ pub options: Option<serde_json::Value>,+ #[serde(default)]+ pub profile_id: Option<String>,+ #[serde(default)]+ pub payload_fetch_ms: f64,+ /// Optional sidecar-prepared tokens ordered as query followed by score+ /// documents. The current sidecar leaves this unset for score requests,+ /// but accepting it keeps the native score path wire-compatible with the+ /// existing prepared-token contract.+ #[serde(default)]+ pub prepared_tokens: Option<PreparedTokens>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ProcessScoreBatchRequest {+ pub model_id: String,+ pub items: Vec<ScoreBatchItem>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ExtractBatchItem {+ pub work_item_id: String,+ pub request_id: String,+ pub item_index: u32,+ pub total_items: u32,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ProcessExtractBatchRequest {+ pub model_id: String,+ pub items: Vec<ExtractBatchItem>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Disposition {+ PublishAndAck,+ PublishErrorAndAck,+ NakRetry,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ItemOutcome {+ pub work_item_id: String,+ pub request_id: String,+ pub item_index: u32,+ pub disposition: Disposition,+ #[serde(default)]+ pub nak_delay_ms: Option<u64>,+ #[serde(default, serialize_with = "serde_bytes::serialize")]+ pub result_msgpack: Vec<u8>,+ #[serde(default)]+ pub error: Option<String>,+ #[serde(default)]+ pub error_code: Option<String>,+ #[serde(default)]+ pub inference_ms: Option<f64>,+ #[serde(default)]+ pub tokenization_ms: Option<f64>,+ #[serde(default)]+ pub postprocessing_ms: Option<f64>,+ #[serde(default)]+ pub raw_output: Option<RawOutput>,+ /// Authoritative billable-unit counts produced by the inference engine.+ /// A field is present only when the engine has an exact count.+ #[serde(default)]+ pub units: Option<UnitCounts>,+}++/// Mirror of `sie_server_sidecar::protocol::ipc_types::UnitCounts`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct UnitCounts {+ #[serde(default)]+ pub input_tokens: Option<u64>,+ #[serde(default)]+ pub pages: Option<u64>,+ #[serde(default)]+ pub images: Option<u64>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BatchOutcome {+ pub outcomes: Vec<ItemOutcome>,+ /// Native Candle f16 multivectors can share one contiguous buffer across+ /// a batch. The sidecar owns slicing and final public wire framing.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub batched_f16_multivectors: Vec<BatchedF16MultivectorOutput>,+}++/// Contiguous f16 values encoded as one MessagePack binary value.+///+/// Native Candle receives this buffer directly from its device-to-host read.+/// Keeping it typed until the IPC serializer removes the otherwise redundant+/// host-side f16-to-byte copy. The wire representation remains byte-identical+/// to Python's `bytes` field: little-endian IEEE-754 binary16 values.+#[derive(Debug, Clone, Default)]+pub struct F16Values(pub Vec<f16>);++impl Serialize for F16Values {+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>+ where+ S: serde::Serializer,+ {+ #[cfg(target_endian = "little")]+ {+ // SAFETY: `f16` is transparent over `u16`; a `u8` view has no+ // alignment requirement and little-endian memory is the wire form.+ let bytes = unsafe {+ std::slice::from_raw_parts(+ self.0.as_ptr().cast::<u8>(),+ std::mem::size_of_val(self.0.as_slice()),+ )+ };+ serializer.serialize_bytes(bytes)+ }++ #[cfg(target_endian = "big")]+ {+ let mut bytes = Vec::with_capacity(std::mem::size_of_val(self.0.as_slice()));+ for value in &self.0 {+ bytes.extend_from_slice(&value.to_bits().to_le_bytes());+ }+ serializer.serialize_bytes(&bytes)+ }+ }+}++impl<'de> Deserialize<'de> for F16Values {+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>+ where+ D: serde::Deserializer<'de>,+ {+ struct F16ValuesVisitor;++ impl<'de> serde::de::Visitor<'de> for F16ValuesVisitor {+ type Value = F16Values;++ fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str("a little-endian f16 byte sequence")+ }++ fn visit_borrowed_bytes<E>(self, bytes: &'de [u8]) -> Result<Self::Value, E>+ where+ E: serde::de::Error,+ {+ f16_values_from_le_bytes(bytes).map_err(E::custom)+ }++ fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E>+ where+ E: serde::de::Error,+ {+ f16_values_from_le_bytes(bytes).map_err(E::custom)+ }++ fn visit_byte_buf<E>(self, bytes: Vec<u8>) -> Result<Self::Value, E>+ where+ E: serde::de::Error,+ {+ f16_values_from_le_bytes(&bytes).map_err(E::custom)+ }+ }++ deserializer.deserialize_bytes(F16ValuesVisitor)+ }+}++fn f16_values_from_le_bytes(bytes: &[u8]) -> Result<F16Values, &'static str> {+ if !bytes.len().is_multiple_of(std::mem::size_of::<f16>()) {+ return Err("f16 byte buffer length must be divisible by two");+ }++ #[cfg(target_endian = "little")]+ {+ let mut values = Vec::<f16>::with_capacity(bytes.len() / std::mem::size_of::<f16>());+ // SAFETY: every f16 bit pattern is valid. The allocation retains f16+ // alignment, unlike reinterpreting a Vec<u8> as an owning Vec<f16>.+ unsafe {+ std::ptr::copy_nonoverlapping(+ bytes.as_ptr(),+ values.as_mut_ptr().cast::<u8>(),+ bytes.len(),+ );+ values.set_len(bytes.len() / std::mem::size_of::<f16>());+ }+ Ok(F16Values(values))+ }++ #[cfg(target_endian = "big")]+ {+ Ok(F16Values(+ bytes+ .chunks_exact(std::mem::size_of::<f16>())+ .map(|chunk| f16::from_bits(u16::from_le_bytes([chunk[0], chunk[1]])))+ .collect(),+ ))+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BatchedF16MultivectorOutput {+ pub values_f16: F16Values,+ pub items: Vec<BatchedF16MultivectorItem>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BatchedF16MultivectorItem {+ pub work_item_id: String,+ pub byte_offset: u64,+ pub byte_len: u64,+ pub num_tokens: u32,+ pub token_dims: u32,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize)]+pub struct RawOutput {+ #[serde(default)]+ pub dense: Option<DenseOutput>,+ #[serde(default)]+ pub score: Option<ScoreOutputRaw>,+ #[serde(default)]+ pub sparse: Option<SparseOutput>,+ #[serde(default)]+ pub multivector: Option<MultivectorOutput>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DenseOutput {+ pub values: Vec<f32>,+ pub dim: u32,+ #[serde(default)]+ pub normalize: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ScoreOutputRaw {+ pub scores: Vec<f32>,+ pub item_ids: Vec<String>,+}++/// Sparse `(indices, values)` payload for one encode item.+///+/// The v1 native wire contract uses i32 indices and f32 values. `dims` is+/// the full sparse vocabulary size when the model exposes one.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SparseOutput {+ pub indices: Vec<i32>,+ pub values: Vec<f32>,+ #[serde(default)]+ pub dims: Option<u32>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MultivectorOutput {+ pub values: Vec<f32>,+ #[serde(+ default,+ skip_serializing_if = "Vec::is_empty",+ serialize_with = "serde_bytes::serialize",+ deserialize_with = "serde_bytes::deserialize"+ )]+ pub values_f16: Vec<u8>,+ pub num_tokens: u32,+ pub token_dims: u32,+ #[serde(default)]+ pub dtype: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RunBatchItem {+ pub op: String,+ #[serde(default)]+ pub work_item_id: String,+ #[serde(default)]+ pub request_id: String,+ #[serde(default)]+ pub item_index: u32,+ #[serde(default)]+ pub encode: Option<EncodeBatchItem>,+ #[serde(default)]+ pub score: Option<ScoreBatchItem>,+ #[serde(default)]+ pub extract: Option<ExtractBatchItem>,+ #[serde(default)]+ pub traceparent: Option<String>,+ #[serde(default)]+ pub tracestate: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct RunBatchRequest {+ pub model_id: String,+ pub batch_id: u64,+ pub lora_key: String,+ pub total_cost: u64,+ pub items: Vec<RunBatchItem>,+ /// Same capability gate as [`ProcessEncodeBatchRequest`], carried by the+ /// scheduler's production RPC path.+ #[serde(default)]+ pub accepts_batched_f16_multivectors: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DrainRequest {+ #[serde(default)]+ pub deadline_ms: u64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DrainResponse {+ #[serde(default)]+ pub acknowledged: bool,+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn f16_values_roundtrip_as_little_endian_msgpack_binary() {+ let values = F16Values(vec![f16::from_bits(0x3c00), f16::from_bits(0x8001)]);++ let encoded = rmp_serde::to_vec_named(&values).unwrap();+ let wire: serde_bytes::ByteBuf = rmp_serde::from_slice(&encoded).unwrap();+ assert_eq!(wire.as_ref(), &[0x00, 0x3c, 0x01, 0x80]);++ let decoded: F16Values = rmp_serde::from_slice(&encoded).unwrap();+ assert_eq!(+ decoded+ .0+ .iter()+ .map(|value| value.to_bits())+ .collect::<Vec<_>>(),+ vec![0x3c00, 0x8001]+ );+ }++ #[test]+ fn run_batch_item_trace_context_roundtrips_msgpack() {+ let item = RunBatchItem {+ op: "encode".to_string(),+ work_item_id: "r.0".to_string(),+ request_id: "r".to_string(),+ item_index: 0,+ encode: None,+ score: None,+ extract: None,+ traceparent: Some(+ "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01".to_string(),+ ),+ tracestate: Some("vendor=opaque".to_string()),+ };++ let bytes = rmp_serde::to_vec_named(&item).unwrap();+ let back: RunBatchItem = rmp_serde::from_slice(&bytes).unwrap();++ assert_eq!(+ back.traceparent.as_deref(),+ Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"),+ );+ assert_eq!(back.tracestate.as_deref(), Some("vendor=opaque"));+ }++ #[test]+ fn score_prepared_tokens_roundtrip_msgpack() {+ let item = ScoreBatchItem {+ work_item_id: "r.0".to_string(),+ request_id: "r".to_string(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ query_item: serde_json::json!({"text": "query"}),+ score_items: vec![serde_json::json!({"text": "document"})],+ instruction: None,+ options: None,+ profile_id: Some("candle".to_string()),+ payload_fetch_ms: 0.0,+ prepared_tokens: Some(PreparedTokens {+ input_ids: vec![vec![1, 2], vec![3, 4, 5]],+ attention_mask: vec![vec![1, 1], vec![1, 1, 1]],+ token_type_ids: Vec::new(),+ tokenizer_id: "tokenizer".to_string(),+ max_seq_len: 8192,+ }),+ };++ let bytes = rmp_serde::to_vec_named(&item).unwrap();+ let back: ScoreBatchItem = rmp_serde::from_slice(&bytes).unwrap();++ let prepared = back.prepared_tokens.expect("prepared score tokens");+ assert_eq!(prepared.input_ids, vec![vec![1, 2], vec![3, 4, 5]]);+ assert_eq!(prepared.tokenizer_id, "tokenizer");+ }++ #[test]+ fn unit_counts_roundtrip_as_named_msgpack_fields() {+ let units = UnitCounts {+ input_tokens: Some(42),+ pages: None,+ images: Some(2),+ };++ let bytes = rmp_serde::to_vec_named(&units).unwrap();+ let map: std::collections::BTreeMap<String, serde_json::Value> =+ rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(map["input_tokens"].as_u64(), Some(42));+ assert!(map["pages"].is_null());++ let back: UnitCounts = rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(back, units);+ }++ #[test]+ fn sparse_raw_output_roundtrips_named_msgpack_fields() {+ let output = RawOutput {+ sparse: Some(SparseOutput {+ indices: vec![7, 29_522],+ values: vec![0.25, 3.5],+ dims: Some(30_522),+ }),+ ..RawOutput::default()+ };++ let bytes = rmp_serde::to_vec_named(&output).unwrap();+ let map: std::collections::BTreeMap<String, serde_json::Value> =+ rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(map["sparse"]["indices"], serde_json::json!([7, 29_522]));+ assert_eq!(map["sparse"]["dims"].as_u64(), Some(30_522));++ let back: RawOutput = rmp_serde::from_slice(&bytes).unwrap();+ let sparse = back.sparse.expect("sparse output");+ assert_eq!(sparse.indices, vec![7, 29_522]);+ assert_eq!(sparse.values, vec![0.25, 3.5]);+ assert_eq!(sparse.dims, Some(30_522));+ }++ #[test]+ fn raw_output_without_sparse_field_remains_compatible() {+ let old_wire = rmp_serde::to_vec_named(&serde_json::json!({+ "dense": null,+ "score": null,+ "multivector": null,+ }))+ .unwrap();++ let output: RawOutput = rmp_serde::from_slice(&old_wire).unwrap();+ assert!(output.sparse.is_none());+ }+}diff --git a/packages/sie_server_rust/src/lib.rs b/packages/sie_server_rust/src/lib.rsnew file mode 100644index 000000000..63c40cd6c--- /dev/null+++ b/packages/sie_server_rust/src/lib.rs@@ -0,0 +1,22 @@+//! Rust inference-engine integrations for SIE server workers.+//!+//! This crate owns engine-specific client/runtime code. Queueing, NATS,+//! SIE work-item routing, and result publishing stay in+//! `sie-server-sidecar`; that crate adapts these clients to the SIE+//! backend trait.++pub mod candle_backend;+mod candle_bert_flash;+pub mod candle_embedding;+mod candle_gte_rope;+mod candle_layers;+mod candle_modernbert;+mod candle_residency;+mod candle_rope;+mod candle_splade;+mod candle_xlm_roberta;+pub mod ipc;+pub mod ipc_types;+pub mod native_backend;+pub mod observability;+pub mod text_prep;diff --git a/packages/sie_server_rust/src/main.rs b/packages/sie_server_rust/src/main.rsnew file mode 100644index 000000000..3ec6d1974--- /dev/null+++ b/packages/sie_server_rust/src/main.rs@@ -0,0 +1,162 @@+use std::path::PathBuf;+use std::time::Duration;++use anyhow::Context;+use clap::Parser;+use sie_server_rust::candle_backend::{+ CandleBackend, CandleBackendConfig, CandleOomRecoveryConfig,+};+use sie_server_rust::ipc::{IpcServer, IpcServerConfig};+use sie_server_rust::ipc_types::SetPinnedModelsRequest;+use sie_server_rust::native_backend::NativeBackend;+use sie_server_rust::observability::{init_observability, shutdown_observability};+use tracing::{error, info};++#[derive(Debug, Parser)]+#[command(author, version, name = "sie-server-rust")]+#[command(about = "Rust SIE worker process backed by native inference engines")]+struct Cli {+ #[arg(long, env = "SIE_IPC_SOCKET_PATH", default_value = "/tmp/sie-ipc.sock")]+ ipc_socket_path: PathBuf,++ #[arg(long, env = "SIE_WORKER_ID", default_value = "sie-server-rust")]+ worker_id: String,++ #[arg(long, env = "SIE_BUNDLE", default_value = "candle")]+ bundle: String,++ #[arg(long, env = "SIE_CANDLE_BATCH_BUDGET", default_value = "64")]+ candle_batch_budget: u32,++ #[arg(long, env = "SIE_CANDLE_MAX_CONCURRENT_FORWARDS", default_value = "1")]+ candle_max_concurrent_forwards: usize,++ #[arg(long, env = "SIE_CANDLE_NORMALIZE")]+ candle_normalize: Option<String>,++ #[arg(long, env = "SIE_IDLE_EVICT_S")]+ idle_evict_s: Option<u64>,++ #[arg(long, env = "SIE_PRELOAD_MODELS")]+ preload_models: Option<String>,++ #[arg(long, env = "SIE_PINNED_MODELS")]+ pinned_models: Option<String>,++ #[arg(long, env = "SIE_SERVER_HOST", default_value = "0.0.0.0")]+ host: String,++ #[arg(long, env = "SIE_SERVER_PORT", default_value = "8080")]+ port: u16,+}++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ init_observability();++ if let Err(e) = run().await {+ error!(error = %e, "sie-server-rust failed");+ shutdown_observability();+ std::process::exit(1);+ }++ shutdown_observability();+ Ok(())+}++async fn run() -> anyhow::Result<()> {+ let cli = Cli::parse();+ let backend = NativeBackend::Candle(CandleBackend::new(+ CandleBackendConfig::new(+ cli.candle_batch_budget,+ env_bool_value(cli.candle_normalize.as_deref(), true),+ cli.candle_max_concurrent_forwards,+ )+ .with_idle_evict_s(idle_evict_duration(cli.idle_evict_s)?)+ .with_oom_recovery(CandleOomRecoveryConfig::from_env()?),+ ));+ if let Some(raw) = cli.preload_models.as_deref() {+ let models = csv_values(raw);+ if !models.is_empty() {+ let preload_count = backend.set_preload_models(&models);+ info!(preload_count, "configured startup preload models");+ }+ }+ if let Some(raw) = cli.pinned_models.as_deref() {+ let models = csv_values(raw);+ if !models.is_empty() {+ let response = backend.set_pinned_models(&SetPinnedModelsRequest { models });+ info!(+ pinned_count = response.pinned_count,+ "configured startup pinned models"+ );+ }+ }+ backend.start_idle_evictor();++ let shutdown_backend = backend.clone();+ let server = IpcServer::new(+ IpcServerConfig {+ socket_path: cli.ipc_socket_path,+ worker_id: cli.worker_id,+ bundle: cli.bundle,+ http_host: cli.host,+ http_port: cli.port,+ },+ backend,+ );++ info!("starting sie-server-rust");+ let result = server.run().await.context("run IPC server");+ shutdown_backend.stop_idle_evictor();+ result+}++fn csv_values(raw: &str) -> Vec<String> {+ raw.split(',')+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(str::to_string)+ .collect()+}++fn env_bool_value(raw: Option<&str>, default: bool) -> bool {+ let Some(raw) = raw else {+ return default;+ };+ let trimmed = raw.trim().to_ascii_lowercase();+ if trimmed.is_empty() {+ return default;+ }+ !matches!(trimmed.as_str(), "0" | "false" | "no" | "off")+}++fn idle_evict_duration(raw: Option<u64>) -> anyhow::Result<Option<Duration>> {+ let Some(seconds) = raw else {+ return Ok(None);+ };+ if seconds == 0 {+ return Ok(None);+ }+ if !(10..=86_400).contains(&seconds) {+ anyhow::bail!("SIE_IDLE_EVICT_S must be 0 or between 10 and 86400 seconds; got {seconds}");+ }+ Ok(Some(Duration::from_secs(seconds)))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn idle_evict_duration_matches_python_bounds() {+ assert_eq!(idle_evict_duration(None).unwrap(), None);+ assert_eq!(idle_evict_duration(Some(0)).unwrap(), None);+ assert_eq!(+ idle_evict_duration(Some(10)).unwrap(),+ Some(Duration::from_secs(10))+ );+ assert!(idle_evict_duration(Some(9)).is_err());+ assert!(idle_evict_duration(Some(86_401)).is_err());+ }+}diff --git a/packages/sie_server_rust/src/native_backend.rs b/packages/sie_server_rust/src/native_backend.rsnew file mode 100644index 000000000..fff0b2080--- /dev/null+++ b/packages/sie_server_rust/src/native_backend.rs@@ -0,0 +1,275 @@+//! Native Rust backend dispatch for the worker IPC server.++use std::time::Instant;++use anyhow::Result;++use crate::candle_backend::CandleBackend;+use crate::ipc_types::{+ ApplyModelConfigRequest, BatchOutcome, Disposition, EnsureModelReadyResponse,+ ProcessEncodeBatchRequest, ProcessScoreBatchRequest, ReplaceModelConfigsRequest,+ RunBatchRequest, SetPinnedModelsRequest, SetPinnedModelsResponse,+};+use crate::observability::metrics::{+ self, AuthoritativeUnits, ItemCompleted, PhaseDurations, WorkerOutcome,+};++#[derive(Clone)]+pub enum NativeBackend {+ Candle(CandleBackend),+}++impl NativeBackend {+ pub fn supported_models(&self) -> Vec<String> {+ match self {+ Self::Candle(backend) => backend.supported_models(),+ }+ }++ pub fn loaded_models(&self) -> Vec<String> {+ match self {+ Self::Candle(backend) => backend.loaded_models(),+ }+ }++ pub async fn health_ready(&self) -> bool {+ match self {+ Self::Candle(backend) => backend.health_ready().await,+ }+ }++ pub fn start_idle_evictor(&self) -> bool {+ match self {+ Self::Candle(backend) => backend.start_idle_evictor(),+ }+ }++ pub fn stop_idle_evictor(&self) -> bool {+ match self {+ Self::Candle(backend) => backend.stop_idle_evictor(),+ }+ }++ pub async fn ensure_model_ready(&self, model_id: &str) -> EnsureModelReadyResponse {+ match self {+ Self::Candle(backend) => backend.ensure_model_ready(model_id).await,+ }+ }++ pub async fn process_encode_batch(&self, req: ProcessEncodeBatchRequest) -> BatchOutcome {+ match self {+ Self::Candle(backend) => {+ let telemetry = BatchTelemetry::for_encode(backend, &req);+ let outcome = backend.process_encode_batch(req).await;+ if let Some(telemetry) = telemetry {+ telemetry.record(&outcome);+ }+ outcome+ }+ }+ }++ pub async fn process_score_batch(&self, req: ProcessScoreBatchRequest) -> BatchOutcome {+ match self {+ Self::Candle(backend) => {+ let telemetry = BatchTelemetry::for_score(backend, &req);+ let outcome = backend.process_score_batch(req).await;+ if let Some(telemetry) = telemetry {+ telemetry.record(&outcome);+ }+ outcome+ }+ }+ }++ pub async fn run_batch(&self, req: RunBatchRequest) -> BatchOutcome {+ match self {+ Self::Candle(backend) => {+ let telemetry = BatchTelemetry::for_run_batch(backend, &req);+ let outcome = backend.run_batch(req).await;+ if let Some(telemetry) = telemetry {+ telemetry.record(&outcome);+ }+ outcome+ }+ }+ }++ pub fn apply_model_config(&self, req: &ApplyModelConfigRequest) -> Result<()> {+ match self {+ Self::Candle(backend) => backend.apply_model_config(req),+ }+ }++ pub fn replace_model_configs(&self, req: &ReplaceModelConfigsRequest) -> Result<Vec<String>> {+ match self {+ Self::Candle(backend) => backend.replace_model_configs(req),+ }+ }++ pub fn set_preload_models(&self, models: &[String]) -> u32 {+ match self {+ Self::Candle(backend) => backend.set_preload_models(models),+ }+ }++ pub fn set_pinned_models(&self, req: &SetPinnedModelsRequest) -> SetPinnedModelsResponse {+ match self {+ Self::Candle(backend) => backend.set_pinned_models(req),+ }+ }+}++struct ItemTelemetryDimensions {+ operation: &'static str,+ model: String,+ profile: String,+}++struct BatchTelemetry {+ started: Instant,+ items: Vec<ItemTelemetryDimensions>,+}++impl BatchTelemetry {+ fn for_encode(backend: &CandleBackend, req: &ProcessEncodeBatchRequest) -> Option<Self> {+ if !metrics::metrics_enabled() {+ return None;+ }+ Some(Self {+ started: Instant::now(),+ items: req+ .items+ .iter()+ .map(|item| {+ let (model, profile) =+ backend.telemetry_dimensions(&req.model_id, item.profile_id.as_deref());+ ItemTelemetryDimensions {+ operation: "encode",+ model,+ profile,+ }+ })+ .collect(),+ })+ }++ fn for_score(backend: &CandleBackend, req: &ProcessScoreBatchRequest) -> Option<Self> {+ if !metrics::metrics_enabled() {+ return None;+ }+ Some(Self {+ started: Instant::now(),+ items: req+ .items+ .iter()+ .map(|item| {+ let (model, profile) =+ backend.telemetry_dimensions(&req.model_id, item.profile_id.as_deref());+ ItemTelemetryDimensions {+ operation: "score",+ model,+ profile,+ }+ })+ .collect(),+ })+ }++ fn for_run_batch(backend: &CandleBackend, req: &RunBatchRequest) -> Option<Self> {+ if !metrics::metrics_enabled() {+ return None;+ }+ Some(Self {+ started: Instant::now(),+ items: req+ .items+ .iter()+ .map(|item| {+ let requested_profile = item+ .encode+ .as_ref()+ .and_then(|encode| encode.profile_id.as_deref())+ .or_else(|| {+ item.score+ .as_ref()+ .and_then(|score| score.profile_id.as_deref())+ });+ let (model, profile) =+ backend.telemetry_dimensions(&req.model_id, requested_profile);+ ItemTelemetryDimensions {+ operation: bounded_operation(&item.op),+ model,+ profile,+ }+ })+ .collect(),+ })+ }++ fn record(self, batch: &BatchOutcome) {+ let duration_s = self.started.elapsed().as_secs_f64();+ for (dimensions, outcome) in self.items.iter().zip(&batch.outcomes) {+ metrics::record_item_completed(ItemCompleted {+ operation: dimensions.operation,+ outcome: worker_outcome(&outcome.disposition),+ model: &dimensions.model,+ profile: &dimensions.profile,+ duration_s,+ phases: PhaseDurations {+ tokenization_s: milliseconds_to_seconds(outcome.tokenization_ms),+ inference_s: milliseconds_to_seconds(outcome.inference_ms),+ postprocessing_s: milliseconds_to_seconds(outcome.postprocessing_ms),+ },+ // Rust/Candle does not yet return authoritative per-item input+ // units for every tokenization path. Never estimate from text.+ units: AuthoritativeUnits::default(),+ });+ }+ }+}++fn bounded_operation(operation: &str) -> &'static str {+ match operation {+ "encode" => "encode",+ "score" => "score",+ "extract" => "extract",+ _ => "other",+ }+}++fn worker_outcome(disposition: &Disposition) -> WorkerOutcome {+ match disposition {+ Disposition::PublishAndAck => WorkerOutcome::Success,+ Disposition::PublishErrorAndAck => WorkerOutcome::Error,+ Disposition::NakRetry => WorkerOutcome::Retry,+ }+}++fn milliseconds_to_seconds(value: Option<f64>) -> Option<f64> {+ value.map(|milliseconds| milliseconds / 1_000.0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn typed_dispositions_map_to_the_bounded_worker_outcomes() {+ assert_eq!(+ worker_outcome(&Disposition::PublishAndAck),+ WorkerOutcome::Success+ );+ assert_eq!(+ worker_outcome(&Disposition::PublishErrorAndAck),+ WorkerOutcome::Error+ );+ assert_eq!(worker_outcome(&Disposition::NakRetry), WorkerOutcome::Retry);+ }++ #[test]+ fn phase_durations_convert_milliseconds_to_contract_seconds() {+ assert_eq!(milliseconds_to_seconds(Some(250.0)), Some(0.25));+ assert_eq!(milliseconds_to_seconds(None), None);+ }+}diff --git a/packages/sie_server_rust/src/observability/metrics.rs b/packages/sie_server_rust/src/observability/metrics.rsnew file mode 100644index 000000000..17bb63c1d--- /dev/null+++ b/packages/sie_server_rust/src/observability/metrics.rs@@ -0,0 +1,2008 @@+//! Canonical single-emission metric facade for the Rust inference engine.+//!+//! Service code reports one typed semantic event here. If the OTLP metrics+//! provider is not enabled, every public recorder returns before allocating+//! attributes or touching an instrument. Prometheus spelling and fan-out are+//! collector concerns; this module never records a second compatibility copy.++use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use opentelemetry::metrics::{Counter, Gauge, Histogram, Meter, MeterProvider as _, UpDownCounter};+use opentelemetry::{global, KeyValue};+use opentelemetry_sdk::metrics::{Instrument, PeriodicReader, SdkMeterProvider, Stream};++use super::resource::{cleaned_env, telemetry_resource};+use super::transport::{build_metric_exporter, endpoint_origin_for_log, metric_export_config};++pub const REQUESTS_METRIC_NAME: &str = "sie.worker.requests";+pub const REQUEST_DURATION_METRIC_NAME: &str = "sie.worker.request.duration";+pub const INFERENCE_DURATION_METRIC_NAME: &str = "sie.worker.inference.duration";+pub const UNITS_METRIC_NAME: &str = "sie.worker.units";+pub const MODEL_LOADED_METRIC_NAME: &str = "sie.worker.model.loaded";+pub const MODEL_LOAD_DURATION_METRIC_NAME: &str = "sie.worker.model.load.duration";+pub const MODEL_MEMORY_METRIC_NAME: &str = "sie.worker.model.memory";+pub const OOM_RECOVERIES_METRIC_NAME: &str = "sie.worker.oom.recoveries";+pub const MODEL_EVICTIONS_METRIC_NAME: &str = "sie.worker.model.evictions";+pub const FORWARD_DURATION_METRIC_NAME: &str = "sie.worker.runtime.forward.duration";+pub const FORWARD_PERMIT_WAIT_METRIC_NAME: &str = "sie.worker.runtime.forward.permit.wait";+pub const FORWARD_CONCURRENT_METRIC_NAME: &str = "sie.worker.runtime.forward.concurrent";+pub const FORWARD_LIMIT_METRIC_NAME: &str = "sie.worker.runtime.forward.limit";++pub const REQUEST_DURATION_BUCKETS_S: &[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, 60.0, 120.0, 300.0,+];+pub const MODEL_LOAD_DURATION_BUCKETS_S: &[f64] = &[+ 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 900.0,+];++const METRICS_EXPORT_INTERVAL_MAX_MS: u64 = 5_000;+const METRICS_SHUTDOWN_TIMEOUT_MS: u64 = 3_000;+const MAX_DIMENSION_LENGTH: usize = 256;+const MAX_CATALOG_MODEL_PROFILE_PAIRS: usize = 256;+const MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS: usize = 32;+const MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS: usize = 4;+const OTHER: &str = "other";+const BACKEND: &str = "candle";++const OPERATION_SERIES: usize = 7;+const WORKER_OUTCOME_SERIES: usize = 5;+const INFERENCE_PHASE_SERIES: usize = 3;+const UNIT_TYPE_SERIES: usize = 3;+const MODEL_LOAD_OUTCOME_SERIES: usize = 4;+const MODEL_LOAD_STAGE_SERIES: usize = 5;+const OOM_STRATEGY_SERIES: usize = 4;+const OOM_OUTCOME_SERIES: usize = 4;+const MODEL_EVICTION_REASON_SERIES: usize = 10;+const FORWARD_OUTCOME_SERIES: usize = 2;+const FORWARD_INPUT_SOURCE_SERIES: usize = 3;+const FORWARD_OUTPUT_PATH_SERIES: usize = 6;+const FORWARD_STATE_SERIES: usize = 2;+const FORWARD_STAGE_SERIES: usize = 47;++pub(crate) const WORKER_CATALOG_PAIR_SERIES: usize = MAX_CATALOG_MODEL_PROFILE_PAIRS + 1;+pub(crate) const WORKER_REQUEST_DETAIL_CATALOG_PAIR_SERIES: usize =+ MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS + 1;+pub(crate) const WORKER_FORWARD_DETAIL_CATALOG_PAIR_SERIES: usize =+ MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS + 1;+pub(crate) const WORKER_REQUEST_CARDINALITY_LIMIT: usize =+ WORKER_REQUEST_DETAIL_CATALOG_PAIR_SERIES * OPERATION_SERIES * WORKER_OUTCOME_SERIES;+pub(crate) const WORKER_PHASE_CARDINALITY_LIMIT: usize =+ WORKER_REQUEST_CARDINALITY_LIMIT * INFERENCE_PHASE_SERIES;+pub(crate) const WORKER_UNITS_CARDINALITY_LIMIT: usize =+ WORKER_REQUEST_DETAIL_CATALOG_PAIR_SERIES * OPERATION_SERIES * UNIT_TYPE_SERIES;+pub(crate) const WORKER_MODEL_LOAD_CARDINALITY_LIMIT: usize =+ WORKER_CATALOG_PAIR_SERIES * MODEL_LOAD_OUTCOME_SERIES * MODEL_LOAD_STAGE_SERIES;+pub(crate) const WORKER_OOM_CARDINALITY_LIMIT: usize =+ WORKER_CATALOG_PAIR_SERIES * OOM_STRATEGY_SERIES * OOM_OUTCOME_SERIES;+pub(crate) const WORKER_EVICTION_CARDINALITY_LIMIT: usize =+ WORKER_CATALOG_PAIR_SERIES * MODEL_EVICTION_REASON_SERIES;+pub(crate) const WORKER_FORWARD_CARDINALITY_LIMIT: usize = WORKER_FORWARD_DETAIL_CATALOG_PAIR_SERIES+ * FORWARD_OUTCOME_SERIES+ * FORWARD_INPUT_SOURCE_SERIES+ * FORWARD_OUTPUT_PATH_SERIES+ * FORWARD_STAGE_SERIES;+pub(crate) const WORKER_FORWARD_PERMIT_CARDINALITY_LIMIT: usize =+ WORKER_CATALOG_PAIR_SERIES * FORWARD_OUTPUT_PATH_SERIES;+pub(crate) const WORKER_FORWARD_CONCURRENT_CARDINALITY_LIMIT: usize =+ WORKER_CATALOG_PAIR_SERIES * FORWARD_STATE_SERIES;++static METER_PROVIDER: OnceLock<SdkMeterProvider> = OnceLock::new();+static WORKER_METRICS: OnceLock<Option<WorkerMetrics>> = OnceLock::new();++/// Return the complete finite-domain ceiling for every Rust-engine metric.+/// Explicit views keep the SDK's 2,000-series default from becoming an+/// accidental second cardinality policy for valid catalog dimensions.+pub(crate) fn worker_metric_cardinality_limit(name: &str) -> Option<usize> {+ match name {+ REQUESTS_METRIC_NAME | REQUEST_DURATION_METRIC_NAME => {+ Some(WORKER_REQUEST_CARDINALITY_LIMIT)+ }+ INFERENCE_DURATION_METRIC_NAME => Some(WORKER_PHASE_CARDINALITY_LIMIT),+ UNITS_METRIC_NAME => Some(WORKER_UNITS_CARDINALITY_LIMIT),+ MODEL_LOADED_METRIC_NAME | MODEL_MEMORY_METRIC_NAME | FORWARD_LIMIT_METRIC_NAME => {+ Some(WORKER_CATALOG_PAIR_SERIES)+ }+ MODEL_LOAD_DURATION_METRIC_NAME => Some(WORKER_MODEL_LOAD_CARDINALITY_LIMIT),+ OOM_RECOVERIES_METRIC_NAME => Some(WORKER_OOM_CARDINALITY_LIMIT),+ MODEL_EVICTIONS_METRIC_NAME => Some(WORKER_EVICTION_CARDINALITY_LIMIT),+ FORWARD_DURATION_METRIC_NAME => Some(WORKER_FORWARD_CARDINALITY_LIMIT),+ FORWARD_PERMIT_WAIT_METRIC_NAME => Some(WORKER_FORWARD_PERMIT_CARDINALITY_LIMIT),+ FORWARD_CONCURRENT_METRIC_NAME => Some(WORKER_FORWARD_CONCURRENT_CARDINALITY_LIMIT),+ _ => None,+ }+}++fn worker_metric_cardinality_view(instrument: &Instrument) -> Option<Stream> {+ let limit = worker_metric_cardinality_limit(instrument.name())?;+ Some(+ Stream::builder()+ .with_cardinality_limit(limit)+ .build()+ .expect("constant worker cardinality limits must be valid"),+ )+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum WorkerOutcome {+ Success,+ Error,+ Retry,+ Cancelled,+ Other,+}++impl WorkerOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Error => "error",+ Self::Retry => "retry",+ Self::Cancelled => "cancelled",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ModelLoadOutcome {+ Success,+ Error,+ Timeout,+ Other,+}++impl ModelLoadOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Error => "error",+ Self::Timeout => "timeout",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ModelLoadStage {+ Total,+ Instantiate,+ Load,+ Resident,+ Other,+}++impl ModelLoadStage {+ fn as_str(self) -> &'static str {+ match self {+ Self::Total => "total",+ Self::Instantiate => "instantiate",+ Self::Load => "load",+ Self::Resident => "resident",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OomStrategy {+ CacheClear,+ EvictLru,+ SplitBatch,+ Other,+}++impl OomStrategy {+ fn as_str(self) -> &'static str {+ match self {+ Self::CacheClear => "cache_clear",+ Self::EvictLru => "evict_lru",+ Self::SplitBatch => "split_batch",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum OomOutcome {+ Success,+ Failed,+ Terminal,+ Other,+}++impl OomOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Failed => "failed",+ Self::Terminal => "terminal",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ModelEvictionReason {+ ConfigChange,+ Idle,+ Lru,+ LoadOom,+ OomRecovery,+ Other,+}++impl ModelEvictionReason {+ fn as_str(self) -> &'static str {+ match self {+ Self::ConfigChange => "config_change",+ Self::Idle => "idle",+ Self::Lru => "lru",+ Self::LoadOom => "load_oom",+ Self::OomRecovery => "oom_recovery",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ForwardState {+ Active,+ Waiting,+}++impl ForwardState {+ fn as_str(self) -> &'static str {+ match self {+ Self::Active => "active",+ Self::Waiting => "waiting",+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ForwardOutcome {+ Success,+ Error,+}++impl ForwardOutcome {+ fn as_str(self) -> &'static str {+ match self {+ Self::Success => "success",+ Self::Error => "error",+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ForwardInputSource {+ Prepared,+ Raw,+ Other,+}++impl ForwardInputSource {+ fn as_str(self) -> &'static str {+ match self {+ Self::Prepared => "prepared",+ Self::Raw => "raw",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ForwardOutputPath {+ Dense,+ Sparse,+ MultivectorF32,+ MultivectorF16Batched,+ MultivectorF16Individual,+ Other,+}++impl ForwardOutputPath {+ fn as_str(self) -> &'static str {+ match self {+ Self::Dense => "dense",+ Self::Sparse => "sparse",+ Self::MultivectorF32 => "multivector_f32",+ Self::MultivectorF16Batched => "multivector_f16_batched",+ Self::MultivectorF16Individual => "multivector_f16_individual",+ Self::Other => OTHER,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ForwardStage {+ Total,+ Forward,+ Pool,+ Normalize,+ Conversion,+ ConversionTensorReadback,+ ConversionHostPack,+ Inference,+ XlmRobertaEmbedding,+ XlmRobertaAttention,+ XlmRobertaAttentionQkv,+ XlmRobertaAttentionFlash,+ XlmRobertaAttentionOutputDense,+ XlmRobertaAttentionOutputLayernorm,+ XlmRobertaFfn,+ XlmRobertaFfnIntermediateDense,+ XlmRobertaFfnActivation,+ XlmRobertaFfnOutputDense,+ XlmRobertaFfnOutputLayernorm,+ GteRopeEmbedding,+ GteRopeRopeSelect,+ GteRopeAttention,+ GteRopeAttentionQkv,+ GteRopeAttentionRotary,+ GteRopeAttentionFlash,+ GteRopeAttentionOutputDense,+ GteRopeAttentionOutputLayernorm,+ GteRopeFfn,+ GteRopeFfnUpGate,+ GteRopeFfnActivation,+ GteRopeFfnDown,+ GteRopeFfnOutputLayernorm,+ ModernBertEmbedding,+ ModernBertEmbeddingNorm,+ ModernBertRopeSelect,+ ModernBertAttention,+ ModernBertAttentionNorm,+ ModernBertAttentionQkv,+ ModernBertAttentionRotary,+ ModernBertAttentionFlash,+ ModernBertAttentionOutputDense,+ ModernBertMlp,+ ModernBertMlpNorm,+ ModernBertMlpWi,+ ModernBertMlpActivation,+ ModernBertMlpWo,+ ModernBertFinalNorm,+}++impl ForwardStage {+ fn as_str(self) -> &'static str {+ match self {+ Self::Total => "total",+ Self::Forward => "forward",+ Self::Pool => "pool",+ Self::Normalize => "normalize",+ Self::Conversion => "conversion",+ Self::ConversionTensorReadback => "conversion_tensor_readback",+ Self::ConversionHostPack => "conversion_host_pack",+ Self::Inference => "inference",+ Self::XlmRobertaEmbedding => "xlm_roberta_embedding",+ Self::XlmRobertaAttention => "xlm_roberta_attention",+ Self::XlmRobertaAttentionQkv => "xlm_roberta_attention_qkv",+ Self::XlmRobertaAttentionFlash => "xlm_roberta_attention_flash",+ Self::XlmRobertaAttentionOutputDense => "xlm_roberta_attention_output_dense",+ Self::XlmRobertaAttentionOutputLayernorm => "xlm_roberta_attention_output_layernorm",+ Self::XlmRobertaFfn => "xlm_roberta_ffn",+ Self::XlmRobertaFfnIntermediateDense => "xlm_roberta_ffn_intermediate_dense",+ Self::XlmRobertaFfnActivation => "xlm_roberta_ffn_activation",+ Self::XlmRobertaFfnOutputDense => "xlm_roberta_ffn_output_dense",+ Self::XlmRobertaFfnOutputLayernorm => "xlm_roberta_ffn_output_layernorm",+ Self::GteRopeEmbedding => "gte_rope_embedding",+ Self::GteRopeRopeSelect => "gte_rope_rope_select",+ Self::GteRopeAttention => "gte_rope_attention",+ Self::GteRopeAttentionQkv => "gte_rope_attention_qkv",+ Self::GteRopeAttentionRotary => "gte_rope_attention_rotary",+ Self::GteRopeAttentionFlash => "gte_rope_attention_flash",+ Self::GteRopeAttentionOutputDense => "gte_rope_attention_output_dense",+ Self::GteRopeAttentionOutputLayernorm => "gte_rope_attention_output_layernorm",+ Self::GteRopeFfn => "gte_rope_ffn",+ Self::GteRopeFfnUpGate => "gte_rope_ffn_up_gate",+ Self::GteRopeFfnActivation => "gte_rope_ffn_activation",+ Self::GteRopeFfnDown => "gte_rope_ffn_down",+ Self::GteRopeFfnOutputLayernorm => "gte_rope_ffn_output_layernorm",+ Self::ModernBertEmbedding => "modernbert_embedding",+ Self::ModernBertEmbeddingNorm => "modernbert_embedding_norm",+ Self::ModernBertRopeSelect => "modernbert_rope_select",+ Self::ModernBertAttention => "modernbert_attention",+ Self::ModernBertAttentionNorm => "modernbert_attention_norm",+ Self::ModernBertAttentionQkv => "modernbert_attention_qkv",+ Self::ModernBertAttentionRotary => "modernbert_attention_rotary",+ Self::ModernBertAttentionFlash => "modernbert_attention_flash",+ Self::ModernBertAttentionOutputDense => "modernbert_attention_output_dense",+ Self::ModernBertMlp => "modernbert_mlp",+ Self::ModernBertMlpNorm => "modernbert_mlp_norm",+ Self::ModernBertMlpWi => "modernbert_mlp_wi",+ Self::ModernBertMlpActivation => "modernbert_mlp_activation",+ Self::ModernBertMlpWo => "modernbert_mlp_wo",+ Self::ModernBertFinalNorm => "modernbert_final_norm",+ }+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct AuthoritativeUnits {+ pub input_tokens: Option<u64>,+ pub pages: Option<u64>,+ pub images: Option<u64>,+}++#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct PhaseDurations {+ pub tokenization_s: Option<f64>,+ pub inference_s: Option<f64>,+ pub postprocessing_s: Option<f64>,+}++pub struct ItemCompleted<'a> {+ pub operation: &'a str,+ pub outcome: WorkerOutcome,+ pub model: &'a str,+ pub profile: &'a str,+ pub duration_s: f64,+ pub phases: PhaseDurations,+ pub units: AuthoritativeUnits,+}++pub struct ForwardCompleted<'a> {+ pub model: &'a str,+ pub profile: &'a str,+ pub outcome: ForwardOutcome,+ pub input_source: ForwardInputSource,+ pub output_path: ForwardOutputPath,+ pub duration_s: f64,+ pub stages: &'a [(ForwardStage, f64)],+}++#[derive(Default)]+struct CatalogPairAdmission {+ // One table keeps the catalog and first-observed detail tiers atomic under+ // one lock; flags never reopen when later catalog pairs appear.+ admitted: HashMap<(String, String), CatalogPairDetailAdmission>,+ request_detail_count: usize,+ forward_detail_count: usize,+}++#[derive(Default)]+struct CatalogPairDetailAdmission {+ request: bool,+ forward: bool,+}++#[derive(Clone, Copy)]+enum CatalogPairScope {+ Catalog,+ RequestDetail,+ ForwardDetail,+}++struct WorkerMetrics {+ requests: Counter<u64>,+ request_duration: Histogram<f64>,+ inference_duration: Histogram<f64>,+ units: Counter<u64>,+ model_loaded: Gauge<u64>,+ model_load_duration: Histogram<f64>,+ model_memory: Gauge<u64>,+ oom_recoveries: Counter<u64>,+ model_evictions: Counter<u64>,+ forward_duration: Histogram<f64>,+ forward_permit_wait: Histogram<f64>,+ forward_concurrent: UpDownCounter<i64>,+ forward_limit: Gauge<u64>,+ lane: String,+ catalog_pairs: Mutex<CatalogPairAdmission>,+ catalog_warning_emitted: AtomicBool,+}++impl WorkerMetrics {+ fn new(meter: &Meter, lane: String) -> Self {+ Self {+ requests: meter+ .u64_counter(REQUESTS_METRIC_NAME)+ .with_description("Inference items completed by the engine.")+ .with_unit("{item}")+ .build(),+ request_duration: meter+ .f64_histogram(REQUEST_DURATION_METRIC_NAME)+ .with_description("End-to-end engine processing time per inference item.")+ .with_unit("s")+ .with_boundaries(REQUEST_DURATION_BUCKETS_S.to_vec())+ .build(),+ inference_duration: meter+ .f64_histogram(INFERENCE_DURATION_METRIC_NAME)+ .with_description("Engine processing time split into bounded phases.")+ .with_unit("s")+ .with_boundaries(REQUEST_DURATION_BUCKETS_S.to_vec())+ .build(),+ units: meter+ .u64_counter(UNITS_METRIC_NAME)+ .with_description("Authoritative non-generation units completed by the engine.")+ .with_unit("{unit}")+ .build(),+ model_loaded: meter+ .u64_gauge(MODEL_LOADED_METRIC_NAME)+ .with_description("Whether a catalog model is resident in the engine.")+ .with_unit("{model}")+ .build(),+ model_load_duration: meter+ .f64_histogram(MODEL_LOAD_DURATION_METRIC_NAME)+ .with_description("Model load duration.")+ .with_unit("s")+ .with_boundaries(MODEL_LOAD_DURATION_BUCKETS_S.to_vec())+ .build(),+ model_memory: meter+ .u64_gauge(MODEL_MEMORY_METRIC_NAME)+ .with_description("Engine-reported resident model memory.")+ .with_unit("By")+ .build(),+ oom_recoveries: meter+ .u64_counter(OOM_RECOVERIES_METRIC_NAME)+ .with_description("OOM recovery strategy outcomes.")+ .with_unit("{recovery}")+ .build(),+ model_evictions: meter+ .u64_counter(MODEL_EVICTIONS_METRIC_NAME)+ .with_description("Resident models evicted from the engine by bounded cause.")+ .with_unit("{model}")+ .build(),+ forward_duration: meter+ .f64_histogram(FORWARD_DURATION_METRIC_NAME)+ .with_description("Candle forward duration split by bounded execution stage.")+ .with_unit("s")+ .with_boundaries(REQUEST_DURATION_BUCKETS_S.to_vec())+ .build(),+ forward_permit_wait: meter+ .f64_histogram(FORWARD_PERMIT_WAIT_METRIC_NAME)+ .with_description("Time spent waiting for a Candle forward permit.")+ .with_unit("s")+ .with_boundaries(REQUEST_DURATION_BUCKETS_S.to_vec())+ .build(),+ forward_concurrent: meter+ .i64_up_down_counter(FORWARD_CONCURRENT_METRIC_NAME)+ .with_description("Candle forwards active or waiting for a permit.")+ .with_unit("{forward}")+ .build(),+ forward_limit: meter+ .u64_gauge(FORWARD_LIMIT_METRIC_NAME)+ .with_description("Configured concurrent Candle forward limit per loaded model.")+ .with_unit("{forward}")+ .build(),+ lane: bounded_release_value(&lane),+ catalog_pairs: Mutex::new(CatalogPairAdmission::default()),+ catalog_warning_emitted: AtomicBool::new(false),+ }+ }++ fn record_item_completed(&self, event: ItemCompleted<'_>) {+ let attributes =+ self.request_attributes(event.operation, event.outcome, event.model, event.profile);+ self.requests.add(1, &attributes);+ if let Some(duration_s) = nonnegative_finite(event.duration_s) {+ self.request_duration.record(duration_s, &attributes);+ }+ for (phase, duration_s) in [+ ("tokenization", event.phases.tokenization_s),+ ("inference", event.phases.inference_s),+ ("postprocessing", event.phases.postprocessing_s),+ ] {+ let Some(duration_s) = duration_s.and_then(nonnegative_finite) else {+ continue;+ };+ let mut phase_attributes = attributes.to_vec();+ phase_attributes.push(KeyValue::new("phase", phase));+ self.inference_duration+ .record(duration_s, &phase_attributes);+ }+ if event.outcome == WorkerOutcome::Success {+ for (unit_type, value) in [+ ("input_tokens", event.units.input_tokens),+ ("pages", event.units.pages),+ ("images", event.units.images),+ ] {+ let Some(value) = value.filter(|value| *value > 0) else {+ continue;+ };+ let mut unit_attributes = vec![+ attributes[0].clone(),+ attributes[2].clone(),+ attributes[3].clone(),+ attributes[4].clone(),+ attributes[5].clone(),+ ];+ unit_attributes.push(KeyValue::new("unit.type", unit_type));+ self.units.add(value, &unit_attributes);+ }+ }+ }++ fn record_model_residency_changed(+ &self,+ model: &str,+ profile: &str,+ loaded: bool,+ memory_bytes: Option<u64>,+ ) {+ let attributes = self.model_attributes(model, profile);+ self.model_loaded.record(u64::from(loaded), &attributes);+ if let Some(memory_bytes) = memory_bytes {+ self.model_memory.record(memory_bytes, &attributes);+ }+ }++ fn record_model_load_completed(+ &self,+ model: &str,+ profile: &str,+ outcome: ModelLoadOutcome,+ stage: ModelLoadStage,+ duration_s: f64,+ ) {+ let Some(duration_s) = nonnegative_finite(duration_s) else {+ return;+ };+ let mut attributes = Vec::with_capacity(6);+ attributes.push(KeyValue::new("outcome", outcome.as_str()));+ attributes.push(KeyValue::new("stage", stage.as_str()));+ attributes.extend(self.model_attributes(model, profile));+ self.model_load_duration.record(duration_s, &attributes);+ }++ fn record_oom_recovery_completed(+ &self,+ model: &str,+ profile: &str,+ strategy: OomStrategy,+ outcome: OomOutcome,+ ) {+ let mut attributes = Vec::with_capacity(6);+ attributes.push(KeyValue::new("strategy", strategy.as_str()));+ attributes.push(KeyValue::new("outcome", outcome.as_str()));+ attributes.extend(self.model_attributes(model, profile));+ self.oom_recoveries.add(1, &attributes);+ }++ fn record_model_evicted(&self, model: &str, profile: &str, reason: ModelEvictionReason) {+ let mut attributes = Vec::with_capacity(5);+ attributes.push(KeyValue::new("reason", reason.as_str()));+ attributes.extend(self.model_attributes(model, profile));+ self.model_evictions.add(1, &attributes);+ }++ fn record_forward_permit_wait(+ &self,+ model: &str,+ profile: &str,+ output_path: ForwardOutputPath,+ duration_s: f64,+ ) {+ let Some(duration_s) = nonnegative_finite(duration_s) else {+ return;+ };+ let mut attributes = Vec::with_capacity(5);+ attributes.push(KeyValue::new("output.path", output_path.as_str()));+ attributes.extend(self.model_attributes(model, profile));+ self.forward_permit_wait.record(duration_s, &attributes);+ }++ fn record_forward_completed(&self, event: ForwardCompleted<'_>) {+ let Some(duration_s) = nonnegative_finite(event.duration_s) else {+ return;+ };+ let base_attributes = self.forward_attributes(+ event.model,+ event.profile,+ event.outcome,+ event.input_source,+ event.output_path,+ );+ self.record_forward_stage(duration_s, ForwardStage::Total, &base_attributes);+ for (stage, raw_duration_s) in event.stages {+ if let Some(stage_duration_s) = nonnegative_finite(*raw_duration_s) {+ self.record_forward_stage(stage_duration_s, *stage, &base_attributes);+ }+ }+ }++ fn record_forward_stage(+ &self,+ duration_s: f64,+ stage: ForwardStage,+ base_attributes: &[KeyValue],+ ) {+ let mut attributes = Vec::with_capacity(base_attributes.len() + 1);+ attributes.extend_from_slice(base_attributes);+ attributes.push(KeyValue::new("stage", stage.as_str()));+ self.forward_duration.record(duration_s, &attributes);+ }++ fn begin_forward_activity(+ &self,+ model: &str,+ profile: &str,+ state: ForwardState,+ limit: usize,+ ) -> ForwardActivityGuard<'_> {+ let model_attributes = self.model_attributes(model, profile);+ let mut attributes = Vec::with_capacity(5);+ attributes.push(KeyValue::new("state", state.as_str()));+ attributes.extend(model_attributes.clone());+ self.forward_concurrent.add(1, &attributes);+ self.forward_limit+ .record(u64::try_from(limit).unwrap_or(u64::MAX), &model_attributes);+ ForwardActivityGuard {+ metrics: Some(self),+ attributes,+ }+ }++ fn request_attributes(+ &self,+ operation: &str,+ outcome: WorkerOutcome,+ model: &str,+ profile: &str,+ ) -> [KeyValue; 6] {+ let (model, profile, backend) = self.admit_request_model_profile(model, profile);+ [+ KeyValue::new("operation", bounded_operation(operation)),+ KeyValue::new("outcome", outcome.as_str()),+ KeyValue::new("backend", backend),+ KeyValue::new("lane", self.lane.clone()),+ KeyValue::new("model", model),+ KeyValue::new("profile", profile),+ ]+ }++ fn model_attributes(&self, model: &str, profile: &str) -> [KeyValue; 4] {+ let (model, profile, backend) = self.admit_model_profile(model, profile);+ [+ KeyValue::new("backend", backend),+ KeyValue::new("lane", self.lane.clone()),+ KeyValue::new("model", model),+ KeyValue::new("profile", profile),+ ]+ }++ /// Admit exact catalog dimensions for the process lifetime. The service+ /// call sites pass already catalog-resolved values; this final facade+ /// boundary prevents sequential catalog churn from retaining unbounded SDK+ /// series. Collapse affects telemetry only and never serving decisions.+ fn admit_model_profile(&self, model: &str, profile: &str) -> (String, String, &'static str) {+ self.admit_model_profile_for(model, profile, CatalogPairScope::Catalog)+ }++ fn admit_request_model_profile(+ &self,+ model: &str,+ profile: &str,+ ) -> (String, String, &'static str) {+ self.admit_model_profile_for(model, profile, CatalogPairScope::RequestDetail)+ }++ fn admit_forward_model_profile(+ &self,+ model: &str,+ profile: &str,+ ) -> (String, String, &'static str) {+ self.admit_model_profile_for(model, profile, CatalogPairScope::ForwardDetail)+ }++ fn admit_model_profile_for(+ &self,+ model: &str,+ profile: &str,+ scope: CatalogPairScope,+ ) -> (String, String, &'static str) {+ let pair = (bounded_release_value(model), bounded_release_value(profile));+ if pair.0 == OTHER || pair.1 == OTHER {+ return (OTHER.to_string(), OTHER.to_string(), OTHER);+ }++ let (exact, exhausted_scope, limit) = {+ let mut admission = self+ .catalog_pairs+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let existing_scope_admitted = admission.admitted.get(&pair).map(|detail| match scope {+ CatalogPairScope::Catalog => true,+ CatalogPairScope::RequestDetail => detail.request,+ CatalogPairScope::ForwardDetail => detail.forward,+ });+ if existing_scope_admitted == Some(true) {+ match scope {+ CatalogPairScope::Catalog => (true, "catalog", MAX_CATALOG_MODEL_PROFILE_PAIRS),+ CatalogPairScope::RequestDetail => (+ true,+ "request_detail",+ MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS,+ ),+ CatalogPairScope::ForwardDetail => (+ true,+ "forward_detail",+ MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS,+ ),+ }+ } else if existing_scope_admitted.is_none()+ && admission.admitted.len() >= MAX_CATALOG_MODEL_PROFILE_PAIRS+ {+ (false, "catalog", MAX_CATALOG_MODEL_PROFILE_PAIRS)+ } else {+ if existing_scope_admitted.is_none() {+ admission.admitted.insert(pair.clone(), Default::default());+ }+ match scope {+ CatalogPairScope::Catalog => (true, "catalog", MAX_CATALOG_MODEL_PROFILE_PAIRS),+ CatalogPairScope::RequestDetail => {+ let exact =+ admission.request_detail_count < MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS;+ if exact {+ admission.request_detail_count += 1;+ admission+ .admitted+ .get_mut(&pair)+ .expect("catalog pair was admitted")+ .request = true;+ }+ (+ exact,+ "request_detail",+ MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS,+ )+ }+ CatalogPairScope::ForwardDetail => {+ let exact =+ admission.forward_detail_count < MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS;+ if exact {+ admission.forward_detail_count += 1;+ admission+ .admitted+ .get_mut(&pair)+ .expect("catalog pair was admitted")+ .forward = true;+ }+ (+ exact,+ "forward_detail",+ MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS,+ )+ }+ }+ }+ };+ if !exact && !self.catalog_warning_emitted.swap(true, Ordering::Relaxed) {+ tracing::warn!(+ admission_scope = exhausted_scope,+ admitted_pairs = limit,+ "Rust worker telemetry model-profile budget exhausted; later pairs collapse to other"+ );+ }+ if exact {+ (pair.0, pair.1, BACKEND)+ } else {+ (OTHER.to_string(), OTHER.to_string(), OTHER)+ }+ }++ fn forward_attributes(+ &self,+ model: &str,+ profile: &str,+ outcome: ForwardOutcome,+ input_source: ForwardInputSource,+ output_path: ForwardOutputPath,+ ) -> Vec<KeyValue> {+ let (model, profile, backend) = self.admit_forward_model_profile(model, profile);+ vec![+ KeyValue::new("outcome", outcome.as_str()),+ KeyValue::new("input.source", input_source.as_str()),+ KeyValue::new("output.path", output_path.as_str()),+ KeyValue::new("backend", backend),+ KeyValue::new("lane", self.lane.clone()),+ KeyValue::new("model", model),+ KeyValue::new("profile", profile),+ ]+ }+}++pub struct ForwardActivityGuard<'a> {+ metrics: Option<&'a WorkerMetrics>,+ attributes: Vec<KeyValue>,+}++impl ForwardActivityGuard<'_> {+ fn disabled() -> Self {+ Self {+ metrics: None,+ attributes: Vec::new(),+ }+ }+}++impl Drop for ForwardActivityGuard<'_> {+ fn drop(&mut self) {+ if let Some(metrics) = self.metrics {+ metrics.forward_concurrent.add(-1, &self.attributes);+ }+ }+}++/// Initialise the sole canonical OTLP metric backend. Failures are fail-open.+pub fn init_metrics() {+ static INIT_GUARD: AtomicBool = AtomicBool::new(false);+ if INIT_GUARD.swap(true, Ordering::SeqCst) {+ return;+ }++ let enabled = positive_flag(cleaned_env("SIE_METRICS_ENABLED").as_deref());+ let export_config = match metric_export_config(enabled) {+ Ok(config) => config,+ Err(_) => {+ let _ = WORKER_METRICS.set(None);+ tracing::warn!("invalid OTLP metric transport configuration; metrics disabled");+ return;+ }+ };+ let Some(export_config) = export_config else {+ let _ = WORKER_METRICS.set(None);+ if enabled {+ tracing::warn!("SIE_METRICS_ENABLED set but no metric OTLP endpoint; metrics disabled");+ }+ return;+ };++ let exporter = match build_metric_exporter(&export_config) {+ Ok(exporter) => exporter,+ Err(_) => {+ let _ = WORKER_METRICS.set(None);+ tracing::warn!("failed to build OTLP metric exporter; metrics disabled");+ return;+ }+ };+ let reader = PeriodicReader::builder(exporter)+ .with_interval(metric_export_interval(+ cleaned_env("OTEL_METRIC_EXPORT_INTERVAL").as_deref(),+ ))+ .build();+ let provider = SdkMeterProvider::builder()+ .with_reader(reader)+ .with_resource(telemetry_resource())+ .with_view(worker_metric_cardinality_view)+ .build();+ let metrics = WorkerMetrics::new(&provider.meter("sie-worker"), lane_from_environment());++ global::set_meter_provider(provider.clone());+ let _ = METER_PROVIDER.set(provider);+ let _ = WORKER_METRICS.set(Some(metrics));+ tracing::info!(endpoint = %endpoint_origin_for_log(&export_config.endpoint), protocol = ?export_config.protocol, "OpenTelemetry worker metrics initialized");+}++pub fn shutdown_metrics() {+ if let Some(provider) = METER_PROVIDER.get() {+ let _ = provider.shutdown_with_timeout(Duration::from_millis(METRICS_SHUTDOWN_TIMEOUT_MS));+ }+}++#[inline]+pub fn metrics_enabled() -> bool {+ WORKER_METRICS.get().is_some_and(Option::is_some)+}++#[inline]+fn enabled_metrics() -> Option<&'static WorkerMetrics> {+ WORKER_METRICS.get().and_then(Option::as_ref)+}++#[inline]+pub fn record_item_completed(event: ItemCompleted<'_>) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_item_completed(event);+}++#[inline]+pub fn record_model_residency_changed(+ model: &str,+ profile: &str,+ loaded: bool,+ memory_bytes: Option<u64>,+) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_model_residency_changed(model, profile, loaded, memory_bytes);+}++#[inline]+pub fn record_model_load_completed(+ model: &str,+ profile: &str,+ outcome: ModelLoadOutcome,+ stage: ModelLoadStage,+ duration_s: f64,+) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_model_load_completed(model, profile, outcome, stage, duration_s);+}++#[inline]+pub fn record_oom_recovery_completed(+ model: &str,+ profile: &str,+ strategy: OomStrategy,+ outcome: OomOutcome,+) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_oom_recovery_completed(model, profile, strategy, outcome);+}++#[inline]+pub fn record_model_evicted(model: &str, profile: &str, reason: ModelEvictionReason) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_model_evicted(model, profile, reason);+}++#[inline]+pub fn record_forward_permit_wait(+ model: &str,+ profile: &str,+ output_path: ForwardOutputPath,+ duration_s: f64,+) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_forward_permit_wait(model, profile, output_path, duration_s);+}++#[inline]+pub fn record_forward_completed(event: ForwardCompleted<'_>) {+ let Some(metrics) = enabled_metrics() else {+ return;+ };+ metrics.record_forward_completed(event);+}++#[inline]+pub fn begin_forward_activity(+ model: &str,+ profile: &str,+ state: ForwardState,+ limit: usize,+) -> ForwardActivityGuard<'static> {+ let Some(metrics) = enabled_metrics() else {+ return ForwardActivityGuard::disabled();+ };+ metrics.begin_forward_activity(model, profile, state, limit)+}++fn positive_flag(raw: Option<&str>) -> bool {+ raw.is_some_and(|value| {+ let value = value.trim();+ value == "1" || value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("yes")+ })+}++fn metric_export_interval(raw: Option<&str>) -> Duration {+ let milliseconds = raw+ .and_then(|value| value.trim().parse::<u64>().ok())+ .filter(|value| *value > 0)+ .unwrap_or(METRICS_EXPORT_INTERVAL_MAX_MS)+ .min(METRICS_EXPORT_INTERVAL_MAX_MS);+ Duration::from_millis(milliseconds)+}++fn lane_from_environment() -> String {+ let pool = bounded_release_value(&cleaned_env("SIE_POOL").unwrap_or_else(|| "default".into()));+ let machine = bounded_release_value(+ &cleaned_env("SIE_MACHINE_PROFILE").unwrap_or_else(|| "default".into()),+ );+ let bundle =+ bounded_release_value(&cleaned_env("SIE_BUNDLE").unwrap_or_else(|| "default".into()));+ if [pool.as_str(), machine.as_str(), bundle.as_str()].contains(&OTHER) {+ OTHER.to_string()+ } else {+ bounded_release_value(&format!("{pool}|{machine}|{bundle}"))+ }+}++fn bounded_operation(value: &str) -> &'static str {+ match value.trim().to_ascii_lowercase().as_str() {+ "encode" => "encode",+ "score" => "score",+ "extract" => "extract",+ "embeddings" => "embeddings",+ "moderations" => "moderations",+ "generate" => "generate",+ _ => OTHER,+ }+}++fn bounded_release_value(value: &str) -> String {+ let value = value.trim();+ if value.is_empty() || value.len() > MAX_DIMENSION_LENGTH || !value.is_ascii() {+ OTHER.to_string()+ } else {+ value.to_string()+ }+}++fn nonnegative_finite(value: f64) -> Option<f64> {+ value.is_finite().then_some(value.max(0.0))+}++#[cfg(test)]+mod tests {+ use std::collections::BTreeSet;++ use opentelemetry::KeyValue;+ use opentelemetry_sdk::metrics::data::{AggregatedMetrics, Metric, MetricData};+ use opentelemetry_sdk::metrics::{+ InMemoryMetricExporter, InMemoryMetricExporterBuilder, Temporality,+ };++ use super::*;++ #[test]+ fn export_interval_cannot_exceed_the_contract_budget() {+ assert_eq!(metric_export_interval(None), Duration::from_secs(5));+ assert_eq!(metric_export_interval(Some("1000")), Duration::from_secs(1));+ assert_eq!(+ metric_export_interval(Some("30000")),+ Duration::from_secs(5)+ );+ assert_eq!(metric_export_interval(Some("0")), Duration::from_secs(5));+ }++ #[test]+ fn cancelled_worker_outcome_is_not_collapsed() {+ assert_eq!(WorkerOutcome::Cancelled.as_str(), "cancelled");+ }++ #[test]+ fn sparse_forward_output_path_has_a_stable_label() {+ assert_eq!(ForwardOutputPath::Sparse.as_str(), "sparse");+ }++ #[test]+ fn low_memory_wire_policy_resets_additive_metrics_but_preserves_state() {+ let exporter = InMemoryMetricExporterBuilder::new()+ .with_temporality(Temporality::LowMemory)+ .build();+ let reader = PeriodicReader::builder(exporter.clone()).build();+ let provider = SdkMeterProvider::builder().with_reader(reader).build();+ let meter = provider.meter("temporality-contract-test");+ let counter = meter.u64_counter("test.counter").build();+ let histogram = meter.f64_histogram("test.histogram").build();+ let up_down = meter.i64_up_down_counter("test.up_down").build();+ let gauge = meter.u64_gauge("test.gauge").build();++ counter.add(1, &[]);+ histogram.record(0.1, &[]);+ up_down.add(2, &[]);+ gauge.record(7, &[]);+ provider.force_flush().expect("flush first interval");++ counter.add(3, &[]);+ histogram.record(0.2, &[]);+ up_down.add(-1, &[]);+ provider.force_flush().expect("flush second interval");++ let finished = exporter+ .get_finished_metrics()+ .expect("read metric intervals");+ assert_eq!(finished.len(), 2);+ let intervals: Vec<HashMap<_, _>> = finished+ .iter()+ .map(|resource| {+ resource+ .scope_metrics()+ .flat_map(|scope| scope.metrics())+ .map(|metric| (metric.name(), metric))+ .collect()+ })+ .collect();++ for (index, expected_counter) in [1, 3].into_iter().enumerate() {+ let AggregatedMetrics::U64(MetricData::Sum(sum)) =+ intervals[index]["test.counter"].data()+ else {+ panic!("counter must be a u64 sum");+ };+ assert_eq!(sum.temporality(), Temporality::Delta);+ assert_eq!(+ sum.data_points().next().expect("counter point").value(),+ expected_counter+ );++ let AggregatedMetrics::F64(MetricData::Histogram(histogram)) =+ intervals[index]["test.histogram"].data()+ else {+ panic!("histogram must be f64");+ };+ assert_eq!(histogram.temporality(), Temporality::Delta);+ assert_eq!(+ histogram+ .data_points()+ .next()+ .expect("histogram point")+ .count(),+ 1+ );+ }++ for (index, expected_value) in [2, 1].into_iter().enumerate() {+ let AggregatedMetrics::I64(MetricData::Sum(sum)) =+ intervals[index]["test.up_down"].data()+ else {+ panic!("up/down counter must be an i64 sum");+ };+ assert_eq!(sum.temporality(), Temporality::Cumulative);+ assert_eq!(+ sum.data_points().next().expect("up/down point").value(),+ expected_value+ );++ let AggregatedMetrics::U64(MetricData::Gauge(gauge)) =+ intervals[index]["test.gauge"].data()+ else {+ panic!("gauge must remain current-value data");+ };+ assert_eq!(gauge.data_points().next().expect("gauge point").value(), 7);+ }+ provider.shutdown().expect("shutdown test provider");+ }++ #[test]+ fn one_facade_event_exports_the_canonical_worker_families_and_attributes() {+ let exporter = InMemoryMetricExporter::default();+ let reader = PeriodicReader::builder(exporter.clone()).build();+ let provider = SdkMeterProvider::builder().with_reader(reader).build();+ let metrics = WorkerMetrics::new(+ &provider.meter("sie-worker-test"),+ "default|gpu-a10|candle".to_string(),+ );++ metrics.record_item_completed(ItemCompleted {+ operation: "encode",+ outcome: WorkerOutcome::Success,+ model: "BAAI/bge-m3",+ profile: "candle",+ duration_s: 0.25,+ phases: PhaseDurations {+ tokenization_s: Some(0.01),+ inference_s: Some(0.2),+ postprocessing_s: Some(0.04),+ },+ units: AuthoritativeUnits {+ input_tokens: Some(17),+ ..AuthoritativeUnits::default()+ },+ });+ metrics.record_model_load_completed(+ "BAAI/bge-m3",+ "candle",+ ModelLoadOutcome::Success,+ ModelLoadStage::Total,+ 2.0,+ );+ metrics.record_model_residency_changed("BAAI/bge-m3", "candle", true, Some(1024));+ metrics.record_oom_recovery_completed(+ "BAAI/bge-m3",+ "candle",+ OomStrategy::SplitBatch,+ OomOutcome::Success,+ );+ metrics.record_model_evicted("BAAI/bge-m3", "candle", ModelEvictionReason::Idle);+ metrics.record_forward_permit_wait("BAAI/bge-m3", "candle", ForwardOutputPath::Dense, 0.01);+ {+ let _waiting =+ metrics.begin_forward_activity("BAAI/bge-m3", "candle", ForwardState::Waiting, 2);+ }+ metrics.record_forward_completed(ForwardCompleted {+ model: "BAAI/bge-m3",+ profile: "candle",+ outcome: ForwardOutcome::Success,+ input_source: ForwardInputSource::Prepared,+ output_path: ForwardOutputPath::Dense,+ duration_s: 0.2,+ stages: &[(ForwardStage::Inference, 0.15)],+ });+ provider.force_flush().expect("flush test metrics");++ let finished = exporter.get_finished_metrics().expect("read test metrics");+ let all_metrics: Vec<_> = finished+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .collect();+ let names: BTreeSet<_> = all_metrics.iter().map(|metric| metric.name()).collect();+ assert_eq!(+ names,+ BTreeSet::from([+ REQUESTS_METRIC_NAME,+ REQUEST_DURATION_METRIC_NAME,+ INFERENCE_DURATION_METRIC_NAME,+ UNITS_METRIC_NAME,+ MODEL_LOADED_METRIC_NAME,+ MODEL_LOAD_DURATION_METRIC_NAME,+ MODEL_MEMORY_METRIC_NAME,+ OOM_RECOVERIES_METRIC_NAME,+ MODEL_EVICTIONS_METRIC_NAME,+ FORWARD_DURATION_METRIC_NAME,+ FORWARD_PERMIT_WAIT_METRIC_NAME,+ FORWARD_CONCURRENT_METRIC_NAME,+ FORWARD_LIMIT_METRIC_NAME,+ ])+ );++ let requests = all_metrics+ .iter()+ .find(|metric| metric.name() == REQUESTS_METRIC_NAME)+ .expect("request counter");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = requests.data() else {+ panic!("requests must be a u64 sum");+ };+ let point = sum.data_points().next().expect("request point");+ assert_eq!(point.value(), 1);+ assert_eq!(+ attribute_key_sets(requests),+ vec![string_set([+ "operation",+ "outcome",+ "backend",+ "lane",+ "model",+ "profile"+ ])]+ );++ let expected_attributes = [+ (+ REQUESTS_METRIC_NAME,+ string_set([+ "operation",+ "outcome",+ "backend",+ "lane",+ "model",+ "profile",+ ]),+ ),+ (+ REQUEST_DURATION_METRIC_NAME,+ string_set([+ "operation",+ "outcome",+ "backend",+ "lane",+ "model",+ "profile",+ ]),+ ),+ (+ INFERENCE_DURATION_METRIC_NAME,+ string_set([+ "operation",+ "outcome",+ "phase",+ "backend",+ "lane",+ "model",+ "profile",+ ]),+ ),+ (+ UNITS_METRIC_NAME,+ string_set([+ "operation",+ "backend",+ "lane",+ "model",+ "profile",+ "unit.type",+ ]),+ ),+ (+ MODEL_LOADED_METRIC_NAME,+ string_set(["backend", "lane", "model", "profile"]),+ ),+ (+ MODEL_LOAD_DURATION_METRIC_NAME,+ string_set(["outcome", "stage", "backend", "lane", "model", "profile"]),+ ),+ (+ MODEL_MEMORY_METRIC_NAME,+ string_set(["backend", "lane", "model", "profile"]),+ ),+ (+ OOM_RECOVERIES_METRIC_NAME,+ string_set(["strategy", "outcome", "backend", "lane", "model", "profile"]),+ ),+ (+ MODEL_EVICTIONS_METRIC_NAME,+ string_set(["reason", "backend", "lane", "model", "profile"]),+ ),+ (+ FORWARD_DURATION_METRIC_NAME,+ string_set([+ "outcome",+ "input.source",+ "output.path",+ "stage",+ "backend",+ "lane",+ "model",+ "profile",+ ]),+ ),+ (+ FORWARD_PERMIT_WAIT_METRIC_NAME,+ string_set(["output.path", "backend", "lane", "model", "profile"]),+ ),+ (+ FORWARD_CONCURRENT_METRIC_NAME,+ string_set(["state", "backend", "lane", "model", "profile"]),+ ),+ (+ FORWARD_LIMIT_METRIC_NAME,+ string_set(["backend", "lane", "model", "profile"]),+ ),+ ];+ for (name, expected) in expected_attributes {+ let metric = all_metrics+ .iter()+ .find(|metric| metric.name() == name)+ .unwrap_or_else(|| panic!("missing {name}"));+ let point_keys = attribute_key_sets(metric);+ assert!(+ !point_keys.is_empty(),+ "{name} must export at least one point"+ );+ assert!(+ point_keys.iter().all(|keys| keys == &expected),+ "{name} attribute set drifted: {point_keys:?}"+ );+ }++ let request_duration = all_metrics+ .iter()+ .find(|metric| metric.name() == REQUEST_DURATION_METRIC_NAME)+ .expect("request duration histogram");+ let AggregatedMetrics::F64(MetricData::Histogram(histogram)) = request_duration.data()+ else {+ panic!("request duration must be an f64 histogram");+ };+ assert_eq!(+ histogram+ .data_points()+ .next()+ .expect("request duration point")+ .bounds()+ .collect::<Vec<_>>(),+ REQUEST_DURATION_BUCKETS_S+ );+ }++ fn string_set<const N: usize>(values: [&str; N]) -> BTreeSet<String> {+ values.into_iter().map(str::to_string).collect()+ }++ fn point_keys<'a>(attributes: impl Iterator<Item = &'a KeyValue>) -> BTreeSet<String> {+ attributes+ .map(|attribute| attribute.key.as_str().to_string())+ .collect()+ }++ fn string_attribute(attributes: &[KeyValue], key: &str) -> String {+ attributes+ .iter()+ .find(|attribute| attribute.key.as_str() == key)+ .unwrap_or_else(|| panic!("missing {key} attribute"))+ .value+ .as_str()+ .into_owned()+ }++ fn attribute_key_sets(metric: &Metric) -> Vec<BTreeSet<String>> {+ match metric.data() {+ AggregatedMetrics::U64(MetricData::Sum(sum)) => sum+ .data_points()+ .map(|point| point_keys(point.attributes()))+ .collect(),+ AggregatedMetrics::U64(MetricData::Gauge(gauge)) => gauge+ .data_points()+ .map(|point| point_keys(point.attributes()))+ .collect(),+ AggregatedMetrics::I64(MetricData::Sum(sum)) => sum+ .data_points()+ .map(|point| point_keys(point.attributes()))+ .collect(),+ AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram+ .data_points()+ .map(|point| point_keys(point.attributes()))+ .collect(),+ other => panic!("unexpected aggregation for {}: {other:?}", metric.name()),+ }+ }++ #[test]+ fn dimensions_and_measurements_are_bounded_before_recording() {+ assert_eq!(bounded_operation("unknown"), OTHER);+ assert_eq!(bounded_release_value(""), OTHER);+ assert_eq!(bounded_release_value("naïve"), OTHER);+ assert_eq!(nonnegative_finite(f64::NAN), None);+ assert_eq!(nonnegative_finite(-1.0), Some(0.0));+ }++ #[test]+ fn catalog_pair_admission_is_process_lifetime_bounded_and_fail_open() {+ let provider = SdkMeterProvider::builder().build();+ let metrics = WorkerMetrics::new(+ &provider.meter("sie-worker-cardinality-admission-test"),+ "default|gpu-a10|candle".to_string(),+ );++ let invalid = metrics.model_attributes("naïve", "candle");+ assert_eq!(string_attribute(&invalid, "backend"), OTHER);+ assert_eq!(string_attribute(&invalid, "model"), OTHER);+ assert_eq!(string_attribute(&invalid, "profile"), OTHER);+ assert!(metrics+ .catalog_pairs+ .lock()+ .expect("catalog admission")+ .admitted+ .is_empty());++ for index in 0..MAX_CATALOG_MODEL_PROFILE_PAIRS {+ let model = format!("catalog/model-{index}");+ let attributes = metrics.model_attributes(&model, "candle");+ assert_eq!(string_attribute(&attributes, "model"), model);+ assert_eq!(string_attribute(&attributes, "profile"), "candle");+ }++ let overflow = metrics.model_attributes("catalog/overflow", "candle");+ assert_eq!(string_attribute(&overflow, "backend"), OTHER);+ assert_eq!(string_attribute(&overflow, "model"), OTHER);+ assert_eq!(string_attribute(&overflow, "profile"), OTHER);++ let retained = metrics.model_attributes("catalog/model-0", "candle");+ assert_eq!(string_attribute(&retained, "model"), "catalog/model-0");+ let admission = metrics+ .catalog_pairs+ .lock()+ .expect("catalog admission after overflow");+ assert_eq!(admission.admitted.len(), MAX_CATALOG_MODEL_PROFILE_PAIRS);+ drop(admission);+ assert!(metrics.catalog_warning_emitted.load(Ordering::Relaxed));+ }++ #[test]+ fn high_product_streams_have_smaller_telemetry_only_pair_admission() {+ let provider = SdkMeterProvider::builder().build();+ let metrics = WorkerMetrics::new(+ &provider.meter("sie-worker-detail-admission-test"),+ "default|gpu-a10|candle".to_string(),+ );++ for index in 0..MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS {+ let model = format!("catalog/request-model-{index}");+ let attributes =+ metrics.request_attributes("encode", WorkerOutcome::Success, &model, "candle");+ assert_eq!(string_attribute(&attributes, "model"), model);+ }+ let request_overflow_model = "catalog/request-overflow";+ let request_overflow = metrics.request_attributes(+ "encode",+ WorkerOutcome::Success,+ request_overflow_model,+ "candle",+ );+ assert_eq!(string_attribute(&request_overflow, "backend"), OTHER);+ assert_eq!(string_attribute(&request_overflow, "model"), OTHER);+ assert_eq!(string_attribute(&request_overflow, "profile"), OTHER);+ assert_eq!(+ string_attribute(+ &metrics.model_attributes(request_overflow_model, "candle"),+ "model"+ ),+ request_overflow_model+ );++ for index in 0..MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS {+ let model = format!("catalog/forward-model-{index}");+ let attributes = metrics.forward_attributes(+ &model,+ "candle",+ ForwardOutcome::Success,+ ForwardInputSource::Prepared,+ ForwardOutputPath::Dense,+ );+ assert_eq!(string_attribute(&attributes, "model"), model);+ }+ let forward_overflow_model = "catalog/forward-overflow";+ let forward_overflow = metrics.forward_attributes(+ forward_overflow_model,+ "candle",+ ForwardOutcome::Success,+ ForwardInputSource::Prepared,+ ForwardOutputPath::Dense,+ );+ assert_eq!(string_attribute(&forward_overflow, "backend"), OTHER);+ assert_eq!(string_attribute(&forward_overflow, "model"), OTHER);+ assert_eq!(string_attribute(&forward_overflow, "profile"), OTHER);+ assert_eq!(+ string_attribute(+ &metrics.model_attributes(forward_overflow_model, "candle"),+ "model"+ ),+ forward_overflow_model+ );++ let admission = metrics.catalog_pairs.lock().expect("detail admission");+ assert_eq!(+ admission.request_detail_count,+ MAX_REQUEST_DETAIL_MODEL_PROFILE_PAIRS+ );+ assert_eq!(+ admission.forward_detail_count,+ MAX_FORWARD_DETAIL_MODEL_PROFILE_PAIRS+ );+ }++ #[test]+ fn worker_cardinality_views_cover_every_owned_instrument() {+ let names = [+ REQUESTS_METRIC_NAME,+ REQUEST_DURATION_METRIC_NAME,+ INFERENCE_DURATION_METRIC_NAME,+ UNITS_METRIC_NAME,+ MODEL_LOADED_METRIC_NAME,+ MODEL_LOAD_DURATION_METRIC_NAME,+ MODEL_MEMORY_METRIC_NAME,+ OOM_RECOVERIES_METRIC_NAME,+ MODEL_EVICTIONS_METRIC_NAME,+ FORWARD_DURATION_METRIC_NAME,+ FORWARD_PERMIT_WAIT_METRIC_NAME,+ FORWARD_CONCURRENT_METRIC_NAME,+ FORWARD_LIMIT_METRIC_NAME,+ ];+ assert!(names+ .iter()+ .all(|name| worker_metric_cardinality_limit(name).is_some()));+ assert!(worker_metric_cardinality_limit("not-a-contract-metric").is_none());+ assert_eq!(WORKER_REQUEST_CARDINALITY_LIMIT, 33 * 7 * 5);+ assert_eq!(WORKER_PHASE_CARDINALITY_LIMIT, 33 * 7 * 5 * 3);+ assert_eq!(WORKER_UNITS_CARDINALITY_LIMIT, 33 * 7 * 3);+ assert_eq!(WORKER_FORWARD_CARDINALITY_LIMIT, 5 * 2 * 3 * 6 * 47);++ let limits: Vec<_> = names+ .iter()+ .map(|name| worker_metric_cardinality_limit(name).expect("owned instrument limit"))+ .collect();+ assert_eq!(limits.iter().sum::<usize>(), 29_577);+ assert_eq!(+ limits.iter().map(|limit| limit + 1).sum::<usize>(),+ 29_590,+ "the pinned SDK requests one plus each view limit as initial tracker-map capacity"+ );++ let histogram_bucket_counter_cells = WORKER_REQUEST_CARDINALITY_LIMIT+ * (REQUEST_DURATION_BUCKETS_S.len() + 1)+ + WORKER_PHASE_CARDINALITY_LIMIT * (REQUEST_DURATION_BUCKETS_S.len() + 1)+ + WORKER_MODEL_LOAD_CARDINALITY_LIMIT * (MODEL_LOAD_DURATION_BUCKETS_S.len() + 1)+ + WORKER_FORWARD_CARDINALITY_LIMIT * (REQUEST_DURATION_BUCKETS_S.len() + 1)+ + WORKER_FORWARD_PERMIT_CARDINALITY_LIMIT * (REQUEST_DURATION_BUCKETS_S.len() + 1);+ assert_eq!(histogram_bucket_counter_cells, 379_022);+ assert_eq!(+ histogram_bucket_counter_cells * std::mem::size_of::<u64>(),+ 3_032_176+ );+ }++ #[test]+ fn valid_worker_request_domain_never_uses_sdk_overflow_series() {+ let exporter = InMemoryMetricExporter::default();+ let reader = PeriodicReader::builder(exporter.clone()).build();+ let provider = SdkMeterProvider::builder()+ .with_reader(reader)+ .with_view(worker_metric_cardinality_view)+ .build();+ let metrics = WorkerMetrics::new(+ &provider.meter("sie-worker-cardinality-view-test"),+ "default|gpu-a10|candle".to_string(),+ );+ let models: Vec<_> = (0..=MAX_CATALOG_MODEL_PROFILE_PAIRS)+ .map(|index| format!("catalog/model-{index}"))+ .collect();+ let operations = [+ "encode",+ "score",+ "extract",+ "embeddings",+ "moderations",+ "generate",+ "unknown-operation",+ ];+ let outcomes = [+ WorkerOutcome::Success,+ WorkerOutcome::Error,+ WorkerOutcome::Retry,+ WorkerOutcome::Cancelled,+ WorkerOutcome::Other,+ ];+ for model in &models {+ for operation in operations {+ for outcome in outcomes {+ metrics.record_item_completed(ItemCompleted {+ operation,+ outcome,+ model,+ profile: "candle",+ duration_s: f64::NAN,+ phases: PhaseDurations::default(),+ units: AuthoritativeUnits::default(),+ });+ }+ }+ }++ provider+ .force_flush()+ .expect("flush cardinality test metrics");+ let finished = exporter+ .get_finished_metrics()+ .expect("read cardinality metrics");+ let requests = finished+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .find(|metric| metric.name() == REQUESTS_METRIC_NAME)+ .expect("request counter");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = requests.data() else {+ panic!("requests must be a u64 sum");+ };+ assert_eq!(sum.data_points().count(), WORKER_REQUEST_CARDINALITY_LIMIT);+ assert!(sum.data_points().all(|point| point+ .attributes()+ .all(|attribute| attribute.key.as_str() != "otel.metric.overflow")));+ }++ /// Reproducible hot-path microbenchmark. One release-mode invocation+ /// collects three independently warmed samples and asserts their median:+ /// `SIE_RUN_TELEMETRY_BENCHMARK=1 cargo test --manifest-path packages/sie_server_rust/Cargo.toml --locked --release --lib benchmark_worker_item_paths -- --ignored --nocapture --test-threads=1`.+ #[cfg(not(debug_assertions))]+ #[test]+ #[ignore = "manual telemetry disabled/enabled microbenchmark"]+ fn benchmark_worker_item_paths() {+ const SAMPLES: usize = 3;+ const WARMUP_ITERATIONS: u32 = 10_000;+ const ITERATIONS: u32 = 200_000;+ assert!(+ !metrics_enabled(),+ "benchmark expects the global noop facade"+ );+ let budget_document: serde_json::Value = serde_json::from_str(include_str!(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/../../telemetry/performance-budgets.json"+ )))+ .expect("parse checked-in telemetry performance budgets");+ let budget = |name: &str| {+ budget_document["budgets"][name]+ .as_f64()+ .unwrap_or_else(|| panic!("missing numeric telemetry performance budget {name}"))+ };++ // Match the largest production stage set: seven common stages plus+ // all fifteen ModernBERT profile stages. `record_forward_completed`+ // adds the `total` observation, so this benchmarks 23 histogram+ // writes rather than a convenient smaller subset.+ let forward_stages = [+ (ForwardStage::Forward, 0.18),+ (ForwardStage::Pool, 0.01),+ (ForwardStage::Normalize, 0.005),+ (ForwardStage::Conversion, 0.005),+ (ForwardStage::ConversionTensorReadback, 0.002),+ (ForwardStage::ConversionHostPack, 0.003),+ (ForwardStage::Inference, 0.2),+ (ForwardStage::ModernBertEmbedding, 0.01),+ (ForwardStage::ModernBertEmbeddingNorm, 0.005),+ (ForwardStage::ModernBertRopeSelect, 0.002),+ (ForwardStage::ModernBertAttention, 0.08),+ (ForwardStage::ModernBertAttentionNorm, 0.005),+ (ForwardStage::ModernBertAttentionQkv, 0.02),+ (ForwardStage::ModernBertAttentionRotary, 0.005),+ (ForwardStage::ModernBertAttentionFlash, 0.04),+ (ForwardStage::ModernBertAttentionOutputDense, 0.01),+ (ForwardStage::ModernBertMlp, 0.06),+ (ForwardStage::ModernBertMlpNorm, 0.005),+ (ForwardStage::ModernBertMlpWi, 0.02),+ (ForwardStage::ModernBertMlpActivation, 0.005),+ (ForwardStage::ModernBertMlpWo, 0.02),+ (ForwardStage::ModernBertFinalNorm, 0.005),+ ];++ let exporter = InMemoryMetricExporterBuilder::new()+ .with_temporality(Temporality::LowMemory)+ .build();+ let reader = PeriodicReader::builder(exporter).build();+ let provider = SdkMeterProvider::builder()+ .with_reader(reader)+ .with_view(worker_metric_cardinality_view)+ .build();+ let metrics = WorkerMetrics::new(+ &provider.meter("sie-worker-benchmark"),+ "default|gpu-a10|candle".to_string(),+ );++ let exercise_disabled_item = |iterations: u32| {+ for _ in 0..iterations {+ record_item_completed(std::hint::black_box(ItemCompleted {+ operation: "encode",+ outcome: WorkerOutcome::Success,+ model: "BAAI/bge-m3",+ profile: "candle",+ duration_s: 0.25,+ phases: PhaseDurations::default(),+ units: AuthoritativeUnits::default(),+ }));+ }+ };+ let exercise_disabled_forward = |iterations: u32| {+ for _ in 0..iterations {+ record_forward_completed(std::hint::black_box(ForwardCompleted {+ model: "BAAI/bge-m3",+ profile: "candle",+ outcome: ForwardOutcome::Success,+ input_source: ForwardInputSource::Prepared,+ output_path: ForwardOutputPath::Dense,+ duration_s: 0.25,+ stages: &forward_stages,+ }));+ }+ };+ let exercise_enabled_item = |iterations: u32| {+ for _ in 0..iterations {+ metrics.record_item_completed(std::hint::black_box(ItemCompleted {+ operation: "encode",+ outcome: WorkerOutcome::Success,+ model: "BAAI/bge-m3",+ profile: "candle",+ duration_s: 0.25,+ phases: PhaseDurations::default(),+ units: AuthoritativeUnits::default(),+ }));+ }+ };+ let exercise_enabled_phases = |iterations: u32| {+ for _ in 0..iterations {+ metrics.record_item_completed(std::hint::black_box(ItemCompleted {+ operation: "encode",+ outcome: WorkerOutcome::Success,+ model: "BAAI/bge-m3",+ profile: "candle",+ duration_s: 0.25,+ phases: PhaseDurations {+ tokenization_s: Some(0.01),+ inference_s: Some(0.2),+ postprocessing_s: None,+ },+ units: AuthoritativeUnits::default(),+ }));+ }+ };+ let exercise_enabled_forward = |iterations: u32| {+ for _ in 0..iterations {+ metrics.record_forward_completed(std::hint::black_box(ForwardCompleted {+ model: "BAAI/bge-m3",+ profile: "candle",+ outcome: ForwardOutcome::Success,+ input_source: ForwardInputSource::Prepared,+ output_path: ForwardOutputPath::Dense,+ duration_s: 0.25,+ stages: &forward_stages,+ }));+ }+ };++ let mut disabled_samples = [0.0; SAMPLES];+ let mut disabled_forward_samples = [0.0; SAMPLES];+ let mut enabled_samples = [0.0; SAMPLES];+ let mut enabled_phases_samples = [0.0; SAMPLES];+ let mut enabled_forward_samples = [0.0; SAMPLES];+ for sample_index in 0..SAMPLES {+ exercise_disabled_item(WARMUP_ITERATIONS);+ let started = std::time::Instant::now();+ exercise_disabled_item(ITERATIONS);+ disabled_samples[sample_index] =+ started.elapsed().as_nanos() as f64 / f64::from(ITERATIONS);++ exercise_disabled_forward(WARMUP_ITERATIONS);+ let started = std::time::Instant::now();+ exercise_disabled_forward(ITERATIONS);+ disabled_forward_samples[sample_index] =+ started.elapsed().as_nanos() as f64 / f64::from(ITERATIONS);++ exercise_enabled_item(WARMUP_ITERATIONS);+ let started = std::time::Instant::now();+ exercise_enabled_item(ITERATIONS);+ enabled_samples[sample_index] =+ started.elapsed().as_nanos() as f64 / f64::from(ITERATIONS);++ exercise_enabled_phases(WARMUP_ITERATIONS);+ let started = std::time::Instant::now();+ exercise_enabled_phases(ITERATIONS);+ enabled_phases_samples[sample_index] =+ started.elapsed().as_nanos() as f64 / f64::from(ITERATIONS);++ exercise_enabled_forward(WARMUP_ITERATIONS);+ let started = std::time::Instant::now();+ exercise_enabled_forward(ITERATIONS);+ enabled_forward_samples[sample_index] =+ started.elapsed().as_nanos() as f64 / f64::from(ITERATIONS);+ }+ provider.force_flush().expect("flush benchmark metrics");++ let median = |mut samples: [f64; SAMPLES]| {+ samples.sort_by(f64::total_cmp);+ samples[SAMPLES / 2]+ };+ let disabled_median_ns = median(disabled_samples);+ let disabled_forward_median_ns = median(disabled_forward_samples);+ let enabled_median_ns = median(enabled_samples);+ let enabled_phases_median_ns = median(enabled_phases_samples);+ let enabled_forward_median_ns = median(enabled_forward_samples);+ let incremental_median_ns = (enabled_median_ns - disabled_median_ns).max(0.0);+ let incremental_phases_median_ns = (enabled_phases_median_ns - disabled_median_ns).max(0.0);+ let incremental_forward_median_ns =+ (enabled_forward_median_ns - disabled_forward_median_ns).max(0.0);++ eprintln!(+ "worker facade: samples={SAMPLES} iterations_per_sample={ITERATIONS} disabled_item={disabled_samples:?} disabled_item_median={disabled_median_ns:.1} ns/event disabled_forward_23_histograms={disabled_forward_samples:?} disabled_forward_23_histograms_median={disabled_forward_median_ns:.1} ns/event enabled_item={enabled_samples:?} enabled_item_median={enabled_median_ns:.1} ns/event enabled_item_two_phases={enabled_phases_samples:?} enabled_item_two_phases_median={enabled_phases_median_ns:.1} ns/event enabled_forward_23_histograms={enabled_forward_samples:?} enabled_forward_23_histograms_median={enabled_forward_median_ns:.1} ns/event incremental_item_median={incremental_median_ns:.1} ns/event incremental_two_phases_median={incremental_phases_median_ns:.1} ns/event incremental_forward_23_histograms_median={incremental_forward_median_ns:.1} ns/event",+ );+ assert!(+ disabled_median_ns <= budget("rust_worker_disabled_ns_per_item"),+ "rust worker telemetry-disabled item median {disabled_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ enabled_median_ns <= budget("rust_worker_enabled_ns_per_item"),+ "rust worker item telemetry median {enabled_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ incremental_median_ns <= budget("rust_worker_incremental_ns_per_item"),+ "rust worker incremental item telemetry median {incremental_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ enabled_phases_median_ns <= budget("rust_worker_two_phase_enabled_ns_per_item"),+ "rust worker two-phase telemetry median {enabled_phases_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ incremental_phases_median_ns+ <= budget("rust_worker_two_phase_incremental_ns_per_item"),+ "rust worker incremental two-phase telemetry median {incremental_phases_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ disabled_forward_median_ns <= budget("rust_worker_forward_disabled_ns_per_event"),+ "rust worker telemetry-disabled forward median {disabled_forward_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ enabled_forward_median_ns <= budget("rust_worker_23_histogram_forward_ns_per_event"),+ "rust worker 23-histogram telemetry median {enabled_forward_median_ns:.1} ns exceeded its checked-in budget"+ );+ assert!(+ incremental_forward_median_ns+ <= budget("rust_worker_23_histogram_forward_incremental_ns_per_event"),+ "rust worker incremental 23-histogram telemetry median {incremental_forward_median_ns:.1} ns exceeded its checked-in budget"+ );+ }+}diff --git a/packages/sie_server_rust/src/observability/mod.rs b/packages/sie_server_rust/src/observability/mod.rsnew file mode 100644index 000000000..a3887e244--- /dev/null+++ b/packages/sie_server_rust/src/observability/mod.rs@@ -0,0 +1,22 @@+//! Rust worker observability: one OTLP metrics/tracing pipeline.+//!+//! The native worker is the leaf process on the queue-mode inference path. It+//! owns provider setup and helpers for extracting `traceparent` / `tracestate`+//! strings carried on IPC `RunBatchItem`s.++pub mod metrics;+pub mod propagation;+mod resource;+pub mod tracing;+mod transport;++pub fn init_observability() {+ transport::install_crypto_provider();+ tracing::init_tracing();+ metrics::init_metrics();+}++pub fn shutdown_observability() {+ metrics::shutdown_metrics();+ tracing::shutdown_tracing();+}diff --git a/packages/sie_server_rust/src/observability/propagation.rs b/packages/sie_server_rust/src/observability/propagation.rsnew file mode 100644index 000000000..22a73bedf--- /dev/null+++ b/packages/sie_server_rust/src/observability/propagation.rs@@ -0,0 +1,9 @@+//! W3C Trace Context extraction helpers for the Rust worker.+//!+//! Shared implementation in `sie-telemetry` (#2339): the worker extracts the+//! W3C `traceparent` / `tracestate` strings it receives on+//! [`crate::ipc_types::RunBatchItem`] via the global propagator installed in+//! [`super::tracing::init_tracing`] so `worker.run_batch` can attach to the+//! inbound trace.++pub use sie_telemetry::propagation::{extract_context_from_w3c, remote_span_context};diff --git a/packages/sie_server_rust/src/observability/resource.rs b/packages/sie_server_rust/src/observability/resource.rsnew file mode 100644index 000000000..f1e815498--- /dev/null+++ b/packages/sie_server_rust/src/observability/resource.rs@@ -0,0 +1,34 @@+//! Resource identity shared by every Rust worker OpenTelemetry signal.+//!+//! Identity composition lives in `sie-telemetry` (#2339); this module keeps+//! the worker's env-precedence chains and service identity.++use opentelemetry_sdk::Resource;++pub(crate) use sie_telemetry::env::cleaned_env;+use sie_telemetry::resource::{+ instance_prefix_env, resource_from_values, service_instance_id, UNKNOWN_RESOURCE_VALUE,+};++pub const SERVICE_NAME: &str = "sie-worker";++/// Build the process resource shared by traces and metrics.+pub fn telemetry_resource() -> Resource {+ let instance_id = service_instance_id(instance_prefix_env().as_deref());+ let deployment_environment = cleaned_env("SIE_OTEL_DEPLOYMENT_ENVIRONMENT")+ .or_else(|| cleaned_env("SIE_DEPLOYMENT_ENV"))+ .unwrap_or_else(|| UNKNOWN_RESOURCE_VALUE.to_string());+ let cloud_region = cleaned_env("SIE_OTEL_CLOUD_REGION")+ .or_else(|| cleaned_env("SIE_CLOUD_REGION"))+ .or_else(|| cleaned_env("AWS_REGION"))+ .or_else(|| cleaned_env("AWS_DEFAULT_REGION"))+ .unwrap_or_else(|| UNKNOWN_RESOURCE_VALUE.to_string());++ resource_from_values(+ SERVICE_NAME,+ &instance_id,+ &deployment_environment,+ &cloud_region,+ Some(env!("CARGO_PKG_VERSION")),+ )+}diff --git a/packages/sie_server_rust/src/observability/tracing.rs b/packages/sie_server_rust/src/observability/tracing.rsnew file mode 100644index 000000000..073627ac7--- /dev/null+++ b/packages/sie_server_rust/src/observability/tracing.rs@@ -0,0 +1,127 @@+//! OpenTelemetry tracer-provider setup for the Rust worker.+//!+//! The OTLP exporter is enabled only when `SIE_TRACING_ENABLED` is truthy and+//! an OTLP endpoint is configured via `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or+//! `OTEL_EXPORTER_OTLP_ENDPOINT`. The W3C propagator is installed globally+//! regardless of that exporter gate so inbound `traceparent` strings on IPC+//! `RunBatchItem`s still extract into an `opentelemetry::Context`.++use std::env;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::OnceLock;+use std::time::Duration;++use opentelemetry::global;+use opentelemetry::trace::TracerProvider as _;+use opentelemetry_sdk::propagation::TraceContextPropagator;+use opentelemetry_sdk::trace::{SdkTracerProvider, Tracer};+use tracing_subscriber::layer::SubscriberExt;+use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::{EnvFilter, Layer};++use sie_telemetry::env::sie_tracing_enabled;++use super::resource::telemetry_resource;+use super::transport::{+ build_span_exporter, endpoint_origin_for_log, trace_export_config, SignalExportConfig,+};++static TRACER_PROVIDER: OnceLock<SdkTracerProvider> = OnceLock::new();++/// Bounded flush deadline (ms) so process exit can't stall on an unreachable collector.+const TRACING_SHUTDOWN_TIMEOUT_MS: u64 = 3_000;++/// Initialise OpenTelemetry + tracing-subscriber for the Rust worker.+pub fn init_tracing() {+ // Idempotency guard. The subscriber's `.init()` panics on a second call.+ static INIT_GUARD: AtomicBool = AtomicBool::new(false);+ if INIT_GUARD.swap(true, Ordering::SeqCst) {+ tracing::debug!("init_tracing called more than once; skipping subsequent init");+ return;+ }++ global::set_text_map_propagator(TraceContextPropagator::new());++ let tracing_enabled = sie_tracing_enabled();+ let (export_config, transport_error) = match trace_export_config(tracing_enabled) {+ Ok(config) => (config, None),+ Err(error) => (None, Some(error)),+ };++ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));+ let json_logs = env_bool_value(env::var("SIE_LOG_JSON").ok().as_deref(), false);++ let tracer = export_config+ .as_ref()+ .and_then(|config| match init_tracer(config) {+ Ok(t) => Some(t),+ Err(_) => {+ eprintln!("warn: failed to init OTLP exporter; continuing without exporter");+ None+ }+ });+ let exporter_enabled = tracer.is_some();++ let mut layers: Vec<Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync>> = Vec::new();+ if let Some(t) = tracer {+ layers.push(Box::new(tracing_opentelemetry::layer().with_tracer(t)));+ }++ let fmt_layer_boxed: Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync> = if json_logs {+ Box::new(tracing_subscriber::fmt::layer().json().with_target(false))+ } else {+ Box::new(tracing_subscriber::fmt::layer().with_target(false))+ };+ layers.push(fmt_layer_boxed);++ tracing_subscriber::registry()+ .with(layers)+ .with(filter)+ .init();++ if exporter_enabled {+ let config = export_config+ .as_ref()+ .expect("exporter_enabled implies export config is set");+ tracing::info!(endpoint = %endpoint_origin_for_log(&config.endpoint), protocol = ?config.protocol, "OpenTelemetry tracing initialized");+ } else if transport_error.is_some() {+ tracing::warn!("invalid OTLP trace transport configuration; tracing disabled");+ } else if export_config.is_none() {+ tracing::debug!(+ "SIE_TRACING_ENABLED not truthy or OTLP endpoint not set; W3C propagator installed (no exporter)"+ );+ } else {+ tracing::warn!("OTLP exporter init failed; W3C propagator installed (no exporter)");+ }+}++fn env_bool_value(raw: Option<&str>, default: bool) -> bool {+ let Some(raw) = raw else {+ return default;+ };+ let trimmed = raw.trim().to_ascii_lowercase();+ if trimmed.is_empty() {+ return default;+ }+ !matches!(trimmed.as_str(), "0" | "false" | "no" | "off")+}++fn init_tracer(config: &SignalExportConfig) -> Result<Tracer, String> {+ let exporter = build_span_exporter(config)?;++ let provider = SdkTracerProvider::builder()+ .with_resource(telemetry_resource())+ .with_batch_exporter(exporter)+ .build();+ let tracer = provider.tracer("sie-worker");+ global::set_tracer_provider(provider.clone());+ let _ = TRACER_PROVIDER.set(provider);+ Ok(tracer)+}++/// Graceful shutdown: flush any pending spans.+pub fn shutdown_tracing() {+ if let Some(provider) = TRACER_PROVIDER.get() {+ let _ = provider.shutdown_with_timeout(Duration::from_millis(TRACING_SHUTDOWN_TIMEOUT_MS));+ }+}diff --git a/packages/sie_server_rust/src/observability/transport.rs b/packages/sie_server_rust/src/observability/transport.rsnew file mode 100644index 000000000..ff04c6961--- /dev/null+++ b/packages/sie_server_rust/src/observability/transport.rs@@ -0,0 +1,30 @@+//! OTLP transport selection for native-worker traces and metrics.+//!+//! The transport/exporter plumbing lives in the shared `sie-telemetry`+//! crate (#2339); this module keeps the worker-local pieces — the rustls+//! crypto-provider install and the `SIE_TRACING_ENABLED`-gated wrappers —+//! and re-exports the shared names its siblings consume.++pub(crate) use sie_telemetry::transport::{+ endpoint_origin_for_log, metric_export_config, trace_export_config, SignalExportConfig,+};++pub(crate) fn install_crypto_provider() {+ let _ = rustls::crypto::ring::default_provider().install_default();+}++pub(crate) fn build_span_exporter(+ config: &SignalExportConfig,+) -> Result<opentelemetry_otlp::SpanExporter, String> {+ // Historical worker posture: (re-)install the ring provider before any+ // exporter build; install_default is a no-op once a provider is set.+ install_crypto_provider();+ sie_telemetry::exporters::build_span_exporter(config)+}++pub(crate) fn build_metric_exporter(+ config: &SignalExportConfig,+) -> Result<opentelemetry_otlp::MetricExporter, String> {+ install_crypto_provider();+ sie_telemetry::exporters::build_metric_exporter(config)+}diff --git a/packages/sie_server_rust/src/text_prep.rs b/packages/sie_server_rust/src/text_prep.rsnew file mode 100644index 000000000..ae6d24af1--- /dev/null+++ b/packages/sie_server_rust/src/text_prep.rs@@ -0,0 +1,152 @@+//! SIE text preparation for Rust-backed inference engines.+//!+//! Mirrors the Python adapter rules for `instruction`, `is_query`,+//! `query_template`, and `doc_template` before the request is sent to an+//! engine such as Candle.++pub struct TextPrep<'a> {+ pub instruction: Option<&'a str>,+ pub is_query: bool,+ pub query_template: Option<&'a str>,+ pub doc_template: Option<&'a str>,+}++impl TextPrep<'_> {+ pub fn apply(&self, text: &str) -> String {+ let template = if self.is_query {+ self.query_template+ } else {+ self.doc_template+ };+ if let Some(template) = template.filter(|value| !value.is_empty()) {+ return format_template(template, text, self.instruction.unwrap_or(""));+ }+ if let Some(instruction) = self.instruction.filter(|value| !value.is_empty()) {+ return format!("{instruction} {text}");+ }+ text.to_string()+ }+}++fn format_template(template: &str, text: &str, instruction: &str) -> String {+ let mut out = String::with_capacity(template.len() + text.len() + instruction.len());+ let mut chars = template.chars().peekable();+ while let Some(c) = chars.next() {+ match c {+ '{' => {+ if chars.peek() == Some(&'{') {+ out.push('{');+ chars.next();+ continue;+ }+ let mut name = String::new();+ let mut closed = false;+ for next in chars.by_ref() {+ if next == '}' {+ closed = true;+ break;+ }+ name.push(next);+ }+ if !closed {+ out.push('{');+ out.push_str(&name);+ continue;+ }+ match name.as_str() {+ "text" => out.push_str(text),+ "instruction" => out.push_str(instruction),+ other => {+ out.push('{');+ out.push_str(other);+ out.push('}');+ }+ }+ }+ '}' => {+ if chars.peek() == Some(&'}') {+ out.push('}');+ chars.next();+ } else {+ out.push('}');+ }+ }+ _ => out.push(c),+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn applies_query_template() {+ let prep = TextPrep {+ instruction: None,+ is_query: true,+ query_template: Some("query: {text}"),+ doc_template: Some("passage: {text}"),+ };+ assert_eq!(prep.apply("cats"), "query: cats");+ }++ #[test]+ fn applies_doc_template() {+ let prep = TextPrep {+ instruction: None,+ is_query: false,+ query_template: Some("query: {text}"),+ doc_template: Some("passage: {text}"),+ };+ assert_eq!(prep.apply("cats"), "passage: cats");+ }++ #[test]+ fn substitutes_instruction() {+ let prep = TextPrep {+ instruction: Some("retrieve relevant passages"),+ is_query: true,+ query_template: Some("Instruct: {instruction}\nQuery: {text}"),+ doc_template: None,+ };+ assert_eq!(+ prep.apply("what is love"),+ "Instruct: retrieve relevant passages\nQuery: what is love"+ );+ }++ #[test]+ fn prepends_bare_instruction_without_template() {+ let prep = TextPrep {+ instruction: Some("Represent this:"),+ is_query: true,+ query_template: None,+ doc_template: None,+ };+ assert_eq!(prep.apply("hello"), "Represent this: hello");+ }++ #[test]+ fn keeps_escaped_braces_literal() {+ let prep = TextPrep {+ instruction: None,+ is_query: true,+ query_template: Some("{{literal}} {text}"),+ doc_template: None,+ };+ assert_eq!(prep.apply("x"), "{literal} x");+ }++ #[test]+ fn preserves_unknown_placeholder() {+ let prep = TextPrep {+ instruction: None,+ is_query: true,+ query_template: Some("{foo}:{text}"),+ doc_template: None,+ };+ assert_eq!(prep.apply("x"), "{foo}:x");+ }+}diff --git a/packages/sie_server_rust/vendor/candle-cublaslt/Cargo.toml b/packages/sie_server_rust/vendor/candle-cublaslt/Cargo.tomlnew file mode 100644index 000000000..07be9874c--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-cublaslt/Cargo.toml@@ -0,0 +1,52 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+name = "candle-cublaslt"+version = "0.0.1"+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "CUBLASLt gemm for the candle ML framework."+homepage = "https://github.com/huggingface/candle-extensions/candle-cublaslt"+documentation = "https://docs.rs/candle-cublaslt"+readme = "README.md"+keywords = [+ "tensor",+ "machine-learning",+]+categories = ["science"]+license = "MIT OR Apache-2.0"+repository = "https://github.com/huggingface/candle-extensions/"++[lib]+name = "candle_cublaslt"+path = "src/lib.rs"++[dependencies.candle]+version = "0.10.2"+features = ["cuda"]+package = "candle-core"++[dependencies.cudarc]+version = "0.19.7"+features = [+ "cublaslt",+ "f16",+]++[dependencies.half]+version = "2.3.1"+features = ["num-traits"]diff --git a/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-APACHE b/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-APACHEnew file mode 100644index 000000000..261eeb9e9--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-APACHE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-MIT b/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-MITnew file mode 100644index 000000000..31aa79387--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-cublaslt/LICENSE-MIT@@ -0,0 +1,23 @@+Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/sie_server_rust/vendor/candle-cublaslt/README.md b/packages/sie_server_rust/vendor/candle-cublaslt/README.mdnew file mode 100644index 000000000..d6f6ce537--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-cublaslt/README.md@@ -0,0 +1,4 @@+# Candle CublasLt Matmul Layer++CublasLt Matmul operation for the Candle ML framework.+Allows for bias and Relu/Gelu fusing.diff --git a/packages/sie_server_rust/vendor/candle-cublaslt/src/lib.rs b/packages/sie_server_rust/vendor/candle-cublaslt/src/lib.rsnew file mode 100644index 000000000..ca57eb204--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-cublaslt/src/lib.rs@@ -0,0 +1,969 @@+pub use cudarc::cublaslt::Activation;+use std::ffi::c_int;++use candle::backend::BackendStorage;+use candle::{CpuStorage, Device, Layout, Result, Shape, Storage, Tensor};+use half::{bf16, f16};+use std::sync::Arc;++use cudarc::cublaslt::{CudaBlasLT, Matmul, MatmulConfig};++fn ensure_dense_layout(layout: &Layout, name: &str) -> Result<()> {+ if layout.contiguous_offsets().is_none() {+ candle::bail!("`{name}` has to be contiguous for cuBLASLt")+ }+ Ok(())+}++#[derive(Debug, Clone)]+pub struct CublasLt(Arc<CudaBlasLT>);++impl CublasLt {+ pub fn new(device: &Device) -> Result<Self> {+ let dev = match &*device {+ Device::Cuda(d) => d,+ _ => candle::bail!("`device` must be a `cuda` device"),+ };++ let inner =+ CudaBlasLT::new(dev.cuda_stream()).map_err(|e| candle::Error::Cuda(Box::new(e)))?;++ Ok(Self(Arc::new(inner)))+ }+}++pub struct CublasLTMatmul {+ pub cublaslt: Arc<CudaBlasLT>,+ pub act: Option<Activation>,+ pub c: Option<Tensor>,+ pub alpha: Option<f32>,+ pub beta: Option<f32>,+}++impl CublasLTMatmul {+ pub fn fwd_f16(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (m, k) = a_l.shape().dims2()?;++ let (n, b_1) = b_l.shape().dims2()?;++ if b_1 != k {+ candle::bail!("This layer only supports TN layout");+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((n, m));++ let a = a.as_cuda_slice::<f16>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<f16>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<f16>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let mut out = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<f16>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };+ if c_l.shape().dims2()? != (n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ c.clone()+ } else {+ // Allocate out tensor+ unsafe { dev.alloc::<f16>(out_shape.elem_count())? }+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: None,+ stride_b: None,+ stride_c: None,+ stride_bias: None,+ batch_size: None,+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }++ pub fn fwd_bf16(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (m, k) = a_l.shape().dims2()?;++ let (n, b_1) = b_l.shape().dims2()?;++ if b_1 != k {+ candle::bail!("This layer only supports TN layout");+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((n, m));++ let a = a.as_cuda_slice::<bf16>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<bf16>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<bf16>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let mut out = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<bf16>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };+ if c_l.shape().dims2()? != (n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ c.clone()+ } else {+ // Allocate out tensor+ unsafe { dev.alloc::<bf16>(out_shape.elem_count())? }+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: None,+ stride_b: None,+ stride_c: None,+ stride_bias: None,+ batch_size: None,+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }++ pub fn fwd_f32(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (m, k) = a_l.shape().dims2()?;++ let (n, b_1) = b_l.shape().dims2()?;++ if b_1 != k {+ candle::bail!("This layer only supports TN layout");+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((n, m));++ let a = a.as_cuda_slice::<f32>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<f32>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<f32>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let mut out = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<f32>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };+ if c_l.shape().dims2()? != (n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ c.clone()+ } else {+ // Allocate out tensor+ unsafe { dev.alloc::<f32>(out_shape.elem_count())? }+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: None,+ stride_b: None,+ stride_c: None,+ stride_bias: None,+ batch_size: None,+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }+}++impl candle::CustomOp2 for CublasLTMatmul {+ fn name(&self) -> &'static str {+ "cublaslt-matmul"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for cublaslt-matmul")+ }++ fn cuda_fwd(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match a.dtype() {+ candle::DType::F16 => self.fwd_f16(a, a_l, b, b_l, None, None),+ candle::DType::BF16 => self.fwd_bf16(a, a_l, b, b_l, None, None),+ candle::DType::F32 => self.fwd_f32(a, a_l, b, b_l, None, None),+ dt => candle::bail!("cublaslt-matmul is only supported for f16/bf16/f32 ({dt:?})"),+ }+ }+}++impl candle::CustomOp3 for CublasLTMatmul {+ fn name(&self) -> &'static str {+ "cublaslt-matmul-add"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for cublaslt-matmul")+ }++ fn cuda_fwd(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: &candle::CudaStorage,+ bias_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match a.dtype() {+ candle::DType::F16 => self.fwd_f16(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ candle::DType::BF16 => self.fwd_bf16(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ candle::DType::F32 => self.fwd_f32(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ dt => candle::bail!("cublaslt-matmul is only supported for f16/bf16/f32 ({dt:?})"),+ }+ }+}++/// Fused matmul + add + Relu/Gelu activation using CublasLt+///+/// # Arguments+///+/// * `a` - Input tensor of size MxK+/// * `b` - Input tensor of size NxK+/// * `out` - Optional Output tensor of size NxM.+/// If set and beta != 0, will be added to the end result of A*B before `act`+/// * `alpha` - Optional scaling factor for A*B+/// * `beta` - Optional scaling factor for C+/// * `bias` - Optional bias tensor of size M+/// * `act` - Optional Gelu or Relu activation. If set, will be added to the end result+/// * `cublaslt` - CublasLt handle+///+/// The resulting tensor is of shape NxM+pub fn fused_matmul(+ a: &Tensor,+ b: &Tensor,+ out: Option<&Tensor>,+ alpha: Option<f32>,+ beta: Option<f32>,+ bias: Option<&Tensor>,+ act: Option<Activation>,+ cublaslt: CublasLt,+) -> Result<Tensor> {+ let op = CublasLTMatmul {+ act,+ cublaslt: cublaslt.0,+ c: out.cloned(),+ alpha,+ beta,+ };++ if let Some(bias) = bias {+ a.apply_op3(&b, &bias, op)+ } else {+ a.apply_op2(&b, op)+ }+}++pub struct CublasLTBatchMatmul {+ pub cublaslt: Arc<CudaBlasLT>,+ pub act: Option<Activation>,+ pub c: Option<Tensor>,+ pub alpha: Option<f32>,+ pub beta: Option<f32>,+}++impl CublasLTBatchMatmul {+ pub fn fwd_f16(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (batch_size, m, k) = a_l.shape().dims3()?;+ let (b_0, n, b_2) = b_l.shape().dims3()?;++ if b_2 != k {+ candle::bail!("This layer only supports TN layout");+ }++ if b_0 != batch_size {+ candle::bail!("`b` must have the same batch size as `a`")+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((batch_size, n, m));++ let a = a.as_cuda_slice::<f16>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<f16>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<f16>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let (mut out, stride_c) = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<f16>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };++ if c_l.shape().dims3()? != (batch_size, n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ // Set beta to 0.0 if it is not set+ (c.clone(), c_l.stride()[0])+ } else {+ // Allocate out tensor+ (+ unsafe { dev.alloc::<f16>(out_shape.elem_count())? },+ (n * m),+ )+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: Some(a_l.stride()[0] as i64),+ stride_b: Some(b_l.stride()[0] as i64),+ stride_c: Some(stride_c as i64),+ stride_bias: None,+ batch_size: Some(batch_size as c_int),+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }++ pub fn fwd_bf16(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (batch_size, m, k) = a_l.shape().dims3()?;+ let (b_0, n, b_2) = b_l.shape().dims3()?;++ if b_2 != k {+ candle::bail!("This layer only supports TN layout");+ }++ if b_0 != batch_size {+ candle::bail!("`b` must have the same batch size as `a`")+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((batch_size, n, m));++ let a = a.as_cuda_slice::<bf16>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<bf16>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<bf16>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let (mut out, stride_c) = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<bf16>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };++ if c_l.shape().dims3()? != (batch_size, n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ // Set beta to 0.0 if it is not set+ (c.clone(), c_l.stride()[0])+ } else {+ // Allocate out tensor+ (+ unsafe { dev.alloc::<bf16>(out_shape.elem_count())? },+ (n * m),+ )+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: Some(a_l.stride()[0] as i64),+ stride_b: Some(b_l.stride()[0] as i64),+ stride_c: Some(stride_c as i64),+ stride_bias: None,+ batch_size: Some(batch_size as c_int),+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }++ pub fn fwd_f32(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: Option<&candle::CudaStorage>,+ bias_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let dev = a.device();++ // Assume TN+ let (batch_size, m, k) = a_l.shape().dims3()?;+ let (b_0, n, b_2) = b_l.shape().dims3()?;++ if b_2 != k {+ candle::bail!("This layer only supports TN layout");+ }++ if b_0 != batch_size {+ candle::bail!("`b` must have the same batch size as `a`")+ }+ ensure_dense_layout(a_l, "a")?;+ ensure_dense_layout(b_l, "b")?;++ let lda = k;+ let ldb = k;+ let ldc = m;++ let out_shape = Shape::from((batch_size, n, m));++ let a = a.as_cuda_slice::<f32>()?.slice(a_l.start_offset()..);+ let b = b.as_cuda_slice::<f32>()?.slice(b_l.start_offset()..);++ let bias = if let (Some(bias), Some(bias_l)) = (bias, bias_l) {+ if bias_l.shape().dims1()? != m {+ candle::bail!("Bias does not have the correct shape");+ }+ ensure_dense_layout(bias_l, "bias")?;++ Some(bias.as_cuda_slice::<f32>()?.slice(bias_l.start_offset()..))+ } else {+ None+ };++ let (mut out, stride_c) = if let Some(c) = &self.c {+ let (c, c_l) = c.storage_and_layout();+ let c = match &*c {+ Storage::Cuda(storage) => storage.as_cuda_slice::<f32>()?,+ _ => candle::bail!("`c` must be a cuda tensor"),+ };+ match c_l.contiguous_offsets() {+ Some((o1, o2)) => {+ if o1 != 0 {+ candle::bail!("`c` start offset must be 0");+ }+ if o2 != out_shape.elem_count() {+ candle::bail!("`c` end offset must be {}", out_shape.elem_count())+ }+ }+ None => candle::bail!("`c` has to be contiguous"),+ };++ if c_l.shape().dims3()? != (batch_size, n, m) {+ candle::bail!("`c` does not have the correct shape");+ }++ // Set beta to 0.0 if it is not set+ (c.clone(), c_l.stride()[0])+ } else {+ // Allocate out tensor+ (+ unsafe { dev.alloc::<f32>(out_shape.elem_count())? },+ (n * m),+ )+ };++ let config = MatmulConfig {+ transa: true,+ transb: false,+ transc: false,+ m: m as u64,+ n: n as u64,+ k: k as u64,+ alpha: self.alpha.unwrap_or(1.0),+ lda: lda as i64,+ ldb: ldb as i64,+ beta: self.beta.unwrap_or(0.0),+ ldc: ldc as i64,+ stride_a: Some(a_l.stride()[0] as i64),+ stride_b: Some(b_l.stride()[0] as i64),+ stride_c: Some(stride_c as i64),+ stride_bias: None,+ batch_size: Some(batch_size as c_int),+ };++ unsafe {+ self.cublaslt+ .matmul(config, &a, &b, &mut out, bias.as_ref(), self.act.as_ref())+ .map_err(|e| candle::Error::Cuda(Box::new(e)))?;+ }++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }+}++impl candle::CustomOp2 for CublasLTBatchMatmul {+ fn name(&self) -> &'static str {+ "cublaslt-batch-matmul"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for cublaslt-batch-matmul")+ }++ fn cuda_fwd(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match a.dtype() {+ candle::DType::F16 => self.fwd_f16(a, a_l, b, b_l, None, None),+ candle::DType::BF16 => self.fwd_bf16(a, a_l, b, b_l, None, None),+ candle::DType::F32 => self.fwd_f32(a, a_l, b, b_l, None, None),+ dt => {+ candle::bail!("cublaslt-batch-matmul is only supported for f16/bf16/f32 ({dt:?})")+ }+ }+ }+}++impl candle::CustomOp3 for CublasLTBatchMatmul {+ fn name(&self) -> &'static str {+ "cublaslt-batch-matmul-add"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for cublaslt-batch-matmul-add")+ }++ fn cuda_fwd(+ &self,+ a: &candle::CudaStorage,+ a_l: &Layout,+ b: &candle::CudaStorage,+ b_l: &Layout,+ bias: &candle::CudaStorage,+ bias_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match a.dtype() {+ candle::DType::F16 => self.fwd_f16(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ candle::DType::BF16 => self.fwd_bf16(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ candle::DType::F32 => self.fwd_f32(a, a_l, b, b_l, Some(bias), Some(bias_l)),+ dt => candle::bail!(+ "cublaslt-batch-matmul-add is only supported for f16/bf16/f32 ({dt:?})"+ ),+ }+ }+}++/// Fused batch matmul + add + Relu/Gelu activation using CublasLt+///+/// # Arguments+///+/// * `a` - Input tensor of size BxMxK+/// * `b` - Input tensor of size BxNxK+/// * `out` - Optional Output tensor of size BxNxM.+/// If set and beta != 0, will be added to the end result of A*B before `act`+/// * `alpha` - Optional scaling factor for A*B+/// * `beta` - Optional scaling factor for C+/// * `bias` - Optional bias tensor of size M+/// * `act` - Optional Gelu or Relu activation. If set, will be added to the end result+/// * `cublaslt` - CublasLt handle+///+/// The resulting tensor is of shape BxNxM+pub fn fused_batch_matmul(+ a: &Tensor,+ b: &Tensor,+ out: Option<&Tensor>,+ alpha: Option<f32>,+ beta: Option<f32>,+ bias: Option<&Tensor>,+ act: Option<Activation>,+ cublaslt: CublasLt,+) -> Result<Tensor> {+ let op = CublasLTBatchMatmul {+ act,+ cublaslt: cublaslt.0,+ c: out.cloned(),+ alpha,+ beta,+ };++ if let Some(bias) = bias {+ a.apply_op3(&b, &bias, op)+ } else {+ a.apply_op2(&b, op)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use candle::{DType, Device};++ // fn to_vec2_round(t: Tensor, digits: i32) -> Result<Vec<Vec<f32>>> {+ // let b = 10f32.powi(digits);+ // let t = t.to_vec2::<f32>()?;+ // let t = t+ // .iter()+ // .map(|t| t.iter().map(|t| f32::round(t * b) / b).collect())+ // .collect();+ // Ok(t)+ // }++ fn to_vec3_round(t: Tensor, digits: i32) -> Result<Vec<Vec<Vec<f32>>>> {+ let b = 10f32.powi(digits);+ let t = t.to_vec3::<f32>()?;+ let t = t+ .iter()+ .map(|t| {+ t.iter()+ .map(|t| t.iter().map(|t| f32::round(t * b) / b).collect())+ .collect()+ })+ .collect();+ Ok(t)+ }++ #[test]+ fn test_fused_matmul() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let a = Tensor::randn(0., 1., (8, 4), &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., (2, 4), &device)?.to_dtype(DType::F32)?;+ let bias = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let cublaslt = CublasLt::new(&device)?;++ let res = fused_matmul(&a, &b, None, None, None, Some(&bias), None, cublaslt)?;+ let expected = (b.matmul(&a.t()?)? + bias.broadcast_left(2)?)?;++ let diff = ((res.clone() - expected.clone())?.abs()? / expected.clone())?+ .sum_all()?+ .to_vec0::<f32>()?;++ assert!(diff < 2e-3, "{res} != {expected}, Diff {diff}");++ Ok(())+ }++ #[test]+ fn test_fused_batch_matmul() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let a = Tensor::randn(0., 1., (3, 8, 4), &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., (3, 2, 4), &device)?.to_dtype(DType::F32)?;+ let c = Tensor::randn(0., 1., (3, 2, 8), &device)?.to_dtype(DType::F32)?;+ let bias = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let cublaslt = CublasLt::new(&device)?;++ let res = fused_batch_matmul(+ &a,+ &b,+ Some(&c),+ None,+ Some(1.0),+ Some(&bias),+ None,+ cublaslt,+ )?;+ let expected = (b.matmul(&a.t()?)?.add(&c)? + bias.broadcast_left((3, 2))?)?;++ assert_eq!(+ to_vec3_round(res.to_dtype(DType::F32)?, 4)?,+ to_vec3_round(expected.to_dtype(DType::F32)?, 4)?+ );+ Ok(())+ }+}diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/Cargo.toml b/packages/sie_server_rust/vendor/candle-gated-activation/Cargo.tomlnew file mode 100644index 000000000..3f2b38910--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/Cargo.toml@@ -0,0 +1,31 @@+[package]+edition = "2021"+name = "candle-gated-activation"+version = "0.0.1"+build = "build.rs"+publish = false+description = "CUDA gated activation kernels for Candle tensors."+license = "MIT OR Apache-2.0"++[lib]+name = "candle_gated_activation"+path = "src/lib.rs"++[dependencies.candle]+version = "0.10.2"+features = ["cuda"]+package = "candle-core"++[dependencies.half]+version = "2.3.1"+features = ["num-traits"]++[build-dependencies.anyhow]+version = "1"+features = ["backtrace"]++[build-dependencies.num_cpus]+version = "1.15.0"++[build-dependencies.rayon]+version = "1.7.0"diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/build.rs b/packages/sie_server_rust/vendor/candle-gated-activation/build.rsnew file mode 100644index 000000000..c808261cb--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/build.rs@@ -0,0 +1,256 @@+use anyhow::{Context, Result};+use rayon::prelude::*;+use std::path::PathBuf;+use std::str::FromStr;++const KERNEL_FILES: [&str; 2] = ["gated_activation.cu", "gelu_erf_gate.cu"];++fn main() -> Result<()> {+ let num_cpus = std::env::var("RAYON_NUM_THREADS").map_or_else(+ |_| num_cpus::get_physical(),+ |s| usize::from_str(&s).unwrap(),+ );+ rayon::ThreadPoolBuilder::new()+ .num_threads(num_cpus)+ .build_global()+ .unwrap();++ println!("cargo:rerun-if-changed=build.rs");+ for kernel_file in KERNEL_FILES.iter() {+ println!("cargo:rerun-if-changed=kernels/{kernel_file}");+ }+ println!("cargo:rerun-if-env-changed=CANDLE_GATED_ACTIVATION_BUILD_DIR");+ println!("cargo:rerun-if-env-changed=CANDLE_NVCC_CCBIN");+ set_cuda_include_dir()?;++ let out_dir = PathBuf::from(std::env::var("OUT_DIR").context("OUT_DIR not set")?);+ let build_dir = match std::env::var("CANDLE_GATED_ACTIVATION_BUILD_DIR") {+ Err(_) => out_dir.clone(),+ Ok(build_dir) => {+ let path = PathBuf::from(build_dir);+ path.canonicalize().unwrap_or_else(|_| {+ panic!(+ "Directory does not exist: {} (the current directory is {})",+ path.display(),+ std::env::current_dir()+ .map(|dir| dir.display().to_string())+ .unwrap_or_else(|_| "<unknown>".to_string())+ )+ })+ }+ };++ let ccbin_env = std::env::var("CANDLE_NVCC_CCBIN");+ let compute_cap = compute_cap()?;+ let out_file = build_dir.join("libgatedactivation.a");+ let stamp_file = build_dir.join("libgatedactivation.stamp");+ let build_stamp = format!(+ "KERNEL_BUILD_VERSION=4\nCUDA_COMPUTE_CAP={compute_cap}\nCANDLE_NVCC_CCBIN={}\n",+ ccbin_env.as_deref().unwrap_or("")+ );++ let kernel_dir = PathBuf::from("kernels");+ let cu_files: Vec<_> = KERNEL_FILES+ .iter()+ .map(|f| {+ let mut obj_file = out_dir.join(f);+ obj_file.set_extension("o");+ (kernel_dir.join(f), obj_file)+ })+ .collect();++ let out_modified: Result<_, _> = out_file.metadata().and_then(|m| m.modified());+ let should_compile = if out_file.exists() {+ std::fs::read_to_string(&stamp_file).ok().as_deref() != Some(build_stamp.as_str())+ || kernel_dir+ .read_dir()+ .expect("kernels folder should exist")+ .any(|entry| {+ if let (Ok(entry), Ok(out_modified)) = (entry, &out_modified) {+ let in_modified = entry.metadata().unwrap().modified().unwrap();+ in_modified.duration_since(*out_modified).is_ok()+ } else {+ true+ }+ })+ } else {+ true+ };++ if should_compile {+ cu_files+ .par_iter()+ .map(|(cu_file, obj_file)| {+ let mut command = std::process::Command::new("nvcc");+ command+ .arg("-std=c++17")+ .arg("-O3")+ .arg("-U__CUDA_NO_HALF_OPERATORS__")+ .arg("-U__CUDA_NO_HALF_CONVERSIONS__")+ .arg("-U__CUDA_NO_BFLOAT16_OPERATORS__")+ .arg("-U__CUDA_NO_BFLOAT16_CONVERSIONS__")+ .arg("-U__CUDA_NO_BFLOAT162_OPERATORS__")+ .arg("-U__CUDA_NO_BFLOAT162_CONVERSIONS__")+ .arg(format!("--gpu-architecture=sm_{compute_cap}"))+ .arg("-c")+ .args(["-o", obj_file.to_str().unwrap()])+ .arg("--expt-relaxed-constexpr")+ .arg("--expt-extended-lambda");+ if cu_file.file_name().and_then(|name| name.to_str()) == Some("gated_activation.cu")+ {+ command.arg("--use_fast_math");+ }+ command.arg("--verbose");+ if let Ok(ccbin_path) = &ccbin_env {+ command+ .arg("-allow-unsupported-compiler")+ .args(["-ccbin", ccbin_path]);+ }+ command.arg(cu_file);+ let output = command+ .spawn()+ .context("failed spawning nvcc")?+ .wait_with_output()?;+ if !output.status.success() {+ anyhow::bail!(+ "nvcc error while compiling {:?}\n\n# stdout\n{}\n\n# stderr\n{}",+ command,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ }+ Ok(())+ })+ .collect::<Result<()>>()?;++ let obj_files = cu_files.iter().map(|c| c.1.clone()).collect::<Vec<_>>();+ let mut command = std::process::Command::new("nvcc");+ command+ .arg("--lib")+ .args(["-o", out_file.to_str().unwrap()])+ .args(obj_files);+ let output = command+ .spawn()+ .context("failed spawning nvcc")?+ .wait_with_output()?;+ if !output.status.success() {+ anyhow::bail!(+ "nvcc error while linking {:?}\n\n# stdout\n{}\n\n# stderr\n{}",+ command,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ }+ std::fs::write(&stamp_file, build_stamp).with_context(|| {+ format!(+ "write gated-activation build stamp {}",+ stamp_file.display()+ )+ })?;+ }++ println!("cargo:rustc-link-search={}", build_dir.display());+ println!("cargo:rustc-link-lib=gatedactivation");+ println!("cargo:rustc-link-lib=dylib=cudart");+ println!("cargo:rustc-link-lib=dylib=stdc++");++ Ok(())+}++fn set_cuda_include_dir() -> Result<()> {+ let env_vars = [+ "CUDA_PATH",+ "CUDA_ROOT",+ "CUDA_TOOLKIT_ROOT_DIR",+ "CUDNN_LIB",+ ];+ let env_vars = env_vars+ .into_iter()+ .map(std::env::var)+ .filter_map(Result::ok)+ .map(Into::<PathBuf>::into);++ let roots = [+ "/usr",+ "/usr/local/cuda",+ "/opt/cuda",+ "/usr/lib/cuda",+ "C:/Program Files/NVIDIA GPU Computing Toolkit",+ "C:/CUDA",+ ];+ let root = env_vars+ .chain(roots.into_iter().map(Into::<PathBuf>::into))+ .find(|path| path.join("include").join("cuda.h").is_file())+ .context("cannot find include/cuda.h")?;+ println!(+ "cargo:rustc-env=CUDA_INCLUDE_DIR={}",+ root.join("include").display()+ );+ Ok(())+}++fn compute_cap() -> Result<usize> {+ println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");++ let compute_cap = if let Ok(compute_cap_str) = std::env::var("CUDA_COMPUTE_CAP") {+ println!("cargo:rustc-env=CUDA_COMPUTE_CAP={compute_cap_str}");+ compute_cap_str+ .parse::<usize>()+ .context("could not parse CUDA_COMPUTE_CAP")?+ } else {+ let out = std::process::Command::new("nvidia-smi")+ .arg("--query-gpu=compute_cap")+ .arg("--format=csv")+ .output()+ .context("`nvidia-smi` failed. Ensure CUDA is installed and nvidia-smi is in PATH.")?;+ let out = std::str::from_utf8(&out.stdout).context("stdout is not utf8")?;+ let mut lines = out.lines();+ assert_eq!(+ lines.next().context("missing line in stdout")?,+ "compute_cap"+ );+ let cap = lines+ .next()+ .context("missing line in stdout")?+ .replace('.', "");+ let cap = cap+ .parse::<usize>()+ .with_context(|| format!("cannot parse as int {cap}"))?;+ println!("cargo:rustc-env=CUDA_COMPUTE_CAP={cap}");+ cap+ };++ let out = std::process::Command::new("nvcc")+ .arg("--list-gpu-code")+ .output()+ .context("`nvcc` failed. Ensure CUDA is installed and nvcc is in PATH.")?;+ let out = std::str::from_utf8(&out.stdout).context("nvcc stdout is not utf8")?;+ let mut supported_nvcc_codes = out+ .lines()+ .filter_map(|line| {+ let parts = line.split('_').collect::<Vec<_>>();+ if !parts.is_empty() && parts.contains(&"sm") {+ parts.get(1).and_then(|value| value.parse::<usize>().ok())+ } else {+ None+ }+ })+ .collect::<Vec<_>>();+ supported_nvcc_codes.sort();+ let max_nvcc_code = *supported_nvcc_codes+ .last()+ .context("nvcc did not report any sm targets")?;++ if !supported_nvcc_codes.contains(&compute_cap) {+ anyhow::bail!(+ "nvcc cannot target gpu arch {compute_cap}. Available nvcc targets are {supported_nvcc_codes:?}."+ );+ }+ if compute_cap > max_nvcc_code {+ anyhow::bail!(+ "CUDA compute cap {compute_cap} is higher than highest nvcc gpu code {max_nvcc_code}"+ );+ }++ Ok(compute_cap)+}diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gated_activation.cu b/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gated_activation.cunew file mode 100644index 000000000..b4cef838f--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gated_activation.cu@@ -0,0 +1,102 @@+#include <cuda_bf16.h>+#include <cuda_fp16.h>+#include <cuda_runtime.h>+#include <stdint.h>++template <typename scalar_t>+__device__ inline float to_float(scalar_t value);++template <>+__device__ inline float to_float<half>(half value) {+ return __half2float(value);+}++template <>+__device__ inline float to_float<__nv_bfloat16>(__nv_bfloat16 value) {+ return __bfloat162float(value);+}++template <>+__device__ inline float to_float<float>(float value) {+ return value;+}++template <typename scalar_t>+__device__ inline scalar_t from_float(float value);++template <>+__device__ inline half from_float<half>(float value) {+ return __float2half(value);+}++template <>+__device__ inline __nv_bfloat16 from_float<__nv_bfloat16>(float value) {+ return __float2bfloat16(value);+}++template <>+__device__ inline float from_float<float>(float value) {+ return value;+}++__device__ inline float gelu_tanh(float x) {+ constexpr float kAlpha = 0.7978845608028654f;+ constexpr float kBeta = 0.044715f;+ return 0.5f * x * (1.0f + tanhf(kAlpha * (x + kBeta * x * x * x)));+}++template <typename scalar_t>+__global__ void gelu_gate_kernel(+ const scalar_t* __restrict__ input,+ scalar_t* __restrict__ output,+ int64_t rows,+ int32_t intermediate_size) {+ const int64_t total = rows * static_cast<int64_t>(intermediate_size);+ for (int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;+ idx < total;+ idx += blockDim.x * gridDim.x) {+ const int64_t row = idx / intermediate_size;+ const int32_t col = idx - row * intermediate_size;+ const int64_t row_offset = row * static_cast<int64_t>(intermediate_size) * 2;+ const float up = to_float(input[row_offset + col]);+ const float gate = to_float(input[row_offset + intermediate_size + col]);+ output[idx] = from_float<scalar_t>(gelu_tanh(gate) * up);+ }+}++#define CALL_GELU_GATE(T) \+ gelu_gate_kernel<T><<<grid, block, 0, stream>>>( \+ reinterpret_cast<const T*>(input), \+ reinterpret_cast<T*>(output), \+ rows, \+ intermediate_size)++extern "C" int gelu_gate(+ const void* input,+ void* output,+ int64_t rows,+ int32_t intermediate_size,+ uint32_t dtype,+ cudaStream_t stream) {+ if (rows <= 0 || intermediate_size <= 0) {+ return 0;+ }++ const int threads = 256;+ const int64_t total = rows * static_cast<int64_t>(intermediate_size);+ const int blocks = static_cast<int>((total + threads - 1) / threads);+ dim3 grid(blocks);+ dim3 block(threads);++ if (dtype == 0) {+ CALL_GELU_GATE(half);+ } else if (dtype == 1) {+ CALL_GELU_GATE(__nv_bfloat16);+ } else if (dtype == 2) {+ CALL_GELU_GATE(float);+ } else {+ return 1;+ }++ return static_cast<int>(cudaGetLastError());+}diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gelu_erf_gate.cu b/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gelu_erf_gate.cunew file mode 100644index 000000000..5f3a881ca--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/kernels/gelu_erf_gate.cu@@ -0,0 +1,204 @@+#include <cuda_bf16.h>+#include <cuda_fp16.h>+#include <cuda_runtime.h>+#include <math.h>+#include <stdint.h>++template <typename scalar_t>+__device__ inline scalar_t gelu_erf(scalar_t x);++template <>+__device__ inline half gelu_erf<half>(half x) {+ return x * __float2half(normcdff(__half2float(x)));+}++template <>+__device__ inline __nv_bfloat16 gelu_erf<__nv_bfloat16>(__nv_bfloat16 x) {+ return x * __float2bfloat16(normcdff(__bfloat162float(x)));+}++template <>+__device__ inline float gelu_erf<float>(float x) {+ return x * normcdff(x);+}++template <typename scalar_t>+__global__ void gelu_erf_gate_kernel(+ const scalar_t* __restrict__ input,+ scalar_t* __restrict__ output,+ int64_t rows,+ int32_t intermediate_size) {+ const int32_t col = blockIdx.x * blockDim.x + threadIdx.x;+ if (col >= intermediate_size) {+ return;+ }+ for (int64_t row = blockIdx.y * blockDim.y + threadIdx.y;+ row < rows;+ row += static_cast<int64_t>(gridDim.y) * blockDim.y) {+ const int64_t row_offset = row * static_cast<int64_t>(intermediate_size) * 2;+ const scalar_t gate = input[row_offset + col];+ const scalar_t up = input[row_offset + intermediate_size + col];+ output[row * static_cast<int64_t>(intermediate_size) + col] =+ gelu_erf(gate) * up;+ }+}++__global__ void init_gelu_erf_bf16_lut_kernel(+ __nv_bfloat16* __restrict__ lut) {+ const uint32_t bits = blockIdx.x * blockDim.x + threadIdx.x;+ if (bits < (1u << 16)) {+ const __nv_bfloat16 value = __ushort_as_bfloat16(+ static_cast<unsigned short>(bits));+ lut[bits] = gelu_erf<__nv_bfloat16>(value);+ }+}++__global__ void gelu_erf_gate_bf16_lut_kernel(+ const __nv_bfloat16* __restrict__ input,+ __nv_bfloat16* __restrict__ output,+ const __nv_bfloat16* __restrict__ lut,+ int64_t rows,+ int32_t intermediate_size) {+ const int32_t col = blockIdx.x * blockDim.x + threadIdx.x;+ if (col >= intermediate_size) {+ return;+ }+ for (int64_t row = blockIdx.y * blockDim.y + threadIdx.y;+ row < rows;+ row += static_cast<int64_t>(gridDim.y) * blockDim.y) {+ const int64_t row_offset = row * static_cast<int64_t>(intermediate_size) * 2;+ const __nv_bfloat16 gate = input[row_offset + col];+ const __nv_bfloat16 up = input[row_offset + intermediate_size + col];+ output[row * static_cast<int64_t>(intermediate_size) + col] =+ lut[__bfloat16_as_ushort(gate)] * up;+ }+}++__global__ void gelu_erf_gate_bf16_lut_vec2_kernel(+ const __nv_bfloat16* __restrict__ input,+ __nv_bfloat16* __restrict__ output,+ const __nv_bfloat16* __restrict__ lut,+ int64_t rows,+ int32_t intermediate_size) {+ const int32_t vec_col = blockIdx.x * blockDim.x + threadIdx.x;+ const int32_t vec_intermediate_size = intermediate_size / 2;+ if (vec_col >= vec_intermediate_size) {+ return;+ }+ for (int64_t row = blockIdx.y * blockDim.y + threadIdx.y;+ row < rows;+ row += static_cast<int64_t>(gridDim.y) * blockDim.y) {+ const int64_t row_offset =+ row * static_cast<int64_t>(vec_intermediate_size) * 2;+ const __nv_bfloat162 gate =+ reinterpret_cast<const __nv_bfloat162*>(input)[row_offset + vec_col];+ const __nv_bfloat162 up =+ reinterpret_cast<const __nv_bfloat162*>(input)[+ row_offset + vec_intermediate_size + vec_col];+ const __nv_bfloat162 activated = __halves2bfloat162(+ lut[__bfloat16_as_ushort(__low2bfloat16(gate))],+ lut[__bfloat16_as_ushort(__high2bfloat16(gate))]);+ reinterpret_cast<__nv_bfloat162*>(output)[+ row * static_cast<int64_t>(vec_intermediate_size) + vec_col] =+ __hmul2_rn(activated, up);+ }+}++#define CALL_GELU_ERF_GATE(T) \+ gelu_erf_gate_kernel<T><<<grid, block, 0, stream>>>( \+ reinterpret_cast<const T*>(input), \+ reinterpret_cast<T*>(output), \+ rows, \+ intermediate_size)++extern "C" int gelu_erf_gate(+ const void* input,+ void* output,+ int64_t rows,+ int32_t intermediate_size,+ uint32_t dtype,+ cudaStream_t stream) {+ if (rows <= 0 || intermediate_size <= 0) {+ return 0;+ }++ constexpr int threads_x = 32;+ constexpr int threads_y = 8;+ const int64_t row_blocks = (rows - 1) / threads_y + 1;+ dim3 grid(+ static_cast<unsigned int>(+ (static_cast<int64_t>(intermediate_size) + threads_x - 1) /+ threads_x),+ static_cast<unsigned int>(row_blocks < 65535 ? row_blocks : 65535));+ dim3 block(threads_x, threads_y);++ if (dtype == 0) {+ CALL_GELU_ERF_GATE(half);+ } else if (dtype == 1) {+ CALL_GELU_ERF_GATE(__nv_bfloat16);+ } else if (dtype == 2) {+ CALL_GELU_ERF_GATE(float);+ } else {+ return 1;+ }++ return static_cast<int>(cudaGetLastError());+}++extern "C" int init_gelu_erf_bf16_lut(+ void* lut,+ cudaStream_t stream) {+ constexpr int threads = 256;+ constexpr int entries = 1 << 16;+ init_gelu_erf_bf16_lut_kernel<<<entries / threads, threads, 0, stream>>>(+ reinterpret_cast<__nv_bfloat16*>(lut));+ return static_cast<int>(cudaGetLastError());+}++extern "C" int gelu_erf_gate_bf16_lut(+ const void* input,+ void* output,+ const void* lut,+ int64_t rows,+ int32_t intermediate_size,+ cudaStream_t stream) {+ if (rows <= 0 || intermediate_size <= 0) {+ return 0;+ }++ constexpr int threads_x = 32;+ constexpr int threads_y = 8;+ const int64_t row_blocks = (rows - 1) / threads_y + 1;+ dim3 block(threads_x, threads_y);+ const bool use_vec2 =+ (reinterpret_cast<uintptr_t>(input) & 0x3u) == 0 &&+ (reinterpret_cast<uintptr_t>(output) & 0x3u) == 0 &&+ intermediate_size % 2 == 0;+ if (use_vec2) {+ const int32_t vec_intermediate_size = intermediate_size / 2;+ dim3 grid(+ static_cast<unsigned int>(+ (static_cast<int64_t>(vec_intermediate_size) + threads_x - 1) /+ threads_x),+ static_cast<unsigned int>(row_blocks < 65535 ? row_blocks : 65535));+ gelu_erf_gate_bf16_lut_vec2_kernel<<<grid, block, 0, stream>>>(+ reinterpret_cast<const __nv_bfloat16*>(input),+ reinterpret_cast<__nv_bfloat16*>(output),+ reinterpret_cast<const __nv_bfloat16*>(lut),+ rows,+ intermediate_size);+ } else {+ dim3 grid(+ static_cast<unsigned int>(+ (static_cast<int64_t>(intermediate_size) + threads_x - 1) /+ threads_x),+ static_cast<unsigned int>(row_blocks < 65535 ? row_blocks : 65535));+ gelu_erf_gate_bf16_lut_kernel<<<grid, block, 0, stream>>>(+ reinterpret_cast<const __nv_bfloat16*>(input),+ reinterpret_cast<__nv_bfloat16*>(output),+ reinterpret_cast<const __nv_bfloat16*>(lut),+ rows,+ intermediate_size);+ }+ return static_cast<int>(cudaGetLastError());+}diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/src/ffi.rs b/packages/sie_server_rust/vendor/candle-gated-activation/src/ffi.rsnew file mode 100644index 000000000..e0d0e2dcf--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/src/ffi.rs@@ -0,0 +1,32 @@+use core::ffi::{c_int, c_long, c_void};++extern "C" {+ pub(crate) fn init_gelu_erf_bf16_lut(lut: *mut c_void, stream: *mut c_void) -> c_int;++ pub(crate) fn gelu_gate(+ input: *const c_void,+ output: *mut c_void,+ rows: c_long,+ intermediate_size: c_int,+ dtype: u32,+ stream: *mut c_void,+ ) -> c_int;++ pub(crate) fn gelu_erf_gate(+ input: *const c_void,+ output: *mut c_void,+ rows: c_long,+ intermediate_size: c_int,+ dtype: u32,+ stream: *mut c_void,+ ) -> c_int;++ pub(crate) fn gelu_erf_gate_bf16_lut(+ input: *const c_void,+ output: *mut c_void,+ lut: *const c_void,+ rows: c_long,+ intermediate_size: c_int,+ stream: *mut c_void,+ ) -> c_int;+}diff --git a/packages/sie_server_rust/vendor/candle-gated-activation/src/lib.rs b/packages/sie_server_rust/vendor/candle-gated-activation/src/lib.rsnew file mode 100644index 000000000..3ad724263--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-gated-activation/src/lib.rs@@ -0,0 +1,503 @@+mod ffi;++use candle::backend::BackendStorage;+use candle::cuda_backend::cudarc::driver::{CudaSlice, DevicePtr, DevicePtrMut};+use candle::cuda_backend::{CudaDevice, DeviceId};+use candle::{CpuStorage, DType, Layout, Result, Shape, Storage, Tensor};+use half::{bf16, f16};+use std::collections::HashMap;+use std::ffi::{c_int, c_long};+use std::sync::{Arc, Mutex};++const BF16_GELU_ERF_LUT_SIZE: usize = 1 << 16;++#[derive(Default)]+struct Bf16GeluErfLutCache {+ luts: Mutex<HashMap<DeviceId, Arc<CudaSlice<bf16>>>>,+}++/// Reusable exact-erf GELU gate whose CUDA lookup tables live as long as its owner.+///+/// Loaded models should retain and clone this value across layers so unloading the+/// model also releases the cached device allocation.+#[derive(Clone)]+pub struct GeluErfGate {+ intermediate_size: usize,+ bf16_luts: Arc<Bf16GeluErfLutCache>,+}++impl GeluErfGate {+ pub fn new(intermediate_size: usize) -> Result<Self> {+ validate_intermediate_size(intermediate_size)?;+ Ok(Self {+ intermediate_size,+ bf16_luts: Arc::new(Bf16GeluErfLutCache::default()),+ })+ }++ pub fn forward(&self, input: &Tensor) -> Result<Tensor> {+ gelu_gate_with_kind(+ input,+ self.intermediate_size,+ GeluGateKind::ErfFirst,+ Some(self.bf16_luts.clone()),+ )+ }+}++#[derive(Clone, Copy)]+enum GeluGateKind {+ TanhSecond,+ ErfFirst,+}++struct GeluGate {+ intermediate_size: usize,+ kind: GeluGateKind,+ bf16_luts: Option<Arc<Bf16GeluErfLutCache>>,+}++impl GeluGate {+ fn output_shape(&self, layout: &Layout) -> Result<(Shape, usize)> {+ let mut dims = layout.shape().dims().to_vec();+ let Some(last_dim) = dims.last_mut() else {+ candle::bail!("gelu-gate expects rank >= 1")+ };+ validate_intermediate_size(self.intermediate_size)?;+ let expected = self+ .intermediate_size+ .checked_mul(2)+ .ok_or_else(|| candle::Error::msg("gelu-gate input width overflow"))?;+ if *last_dim != expected {+ candle::bail!(+ "gelu-gate expected last dim {}, got {}",+ expected,+ *last_dim+ );+ }+ if layout.contiguous_offsets().is_none() {+ candle::bail!("gelu-gate expects a contiguous input tensor");+ }++ *last_dim = self.intermediate_size;+ let rows = layout.shape().elem_count() / expected;+ Ok((Shape::from(dims), rows))+ }+}++impl candle::CustomOp1 for GeluGate {+ fn name(&self) -> &'static str {+ match self.kind {+ GeluGateKind::TanhSecond => "gelu-gate",+ GeluGateKind::ErfFirst => "gelu-erf-gate",+ }+ }++ fn cpu_fwd(&self, _storage: &CpuStorage, _layout: &Layout) -> Result<(CpuStorage, Shape)> {+ candle::bail!("gelu-gate is only supported on CUDA")+ }++ fn cuda_fwd(+ &self,+ storage: &candle::CudaStorage,+ layout: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ let (out_shape, rows) = self.output_shape(layout)?;+ let elem_count = out_shape.elem_count();+ let dev = storage.device();+ let stream = dev.cuda_stream();+ let (start, end) = layout+ .contiguous_offsets()+ .ok_or_else(|| candle::Error::msg("gelu-gate expects a contiguous input tensor"))?;++ match storage.dtype() {+ DType::F16 => launch::<f16>(+ storage,+ start,+ end,+ rows,+ elem_count,+ self.intermediate_size,+ 0,+ self.kind,+ self.bf16_luts.as_deref(),+ out_shape,+ &stream,+ ),+ DType::BF16 => launch::<bf16>(+ storage,+ start,+ end,+ rows,+ elem_count,+ self.intermediate_size,+ 1,+ self.kind,+ self.bf16_luts.as_deref(),+ out_shape,+ &stream,+ ),+ DType::F32 => launch::<f32>(+ storage,+ start,+ end,+ rows,+ elem_count,+ self.intermediate_size,+ 2,+ self.kind,+ self.bf16_luts.as_deref(),+ out_shape,+ &stream,+ ),+ dtype => candle::bail!("gelu-gate only supports f16/bf16/f32, got {dtype:?}"),+ }+ }+}++#[allow(clippy::too_many_arguments)]+fn launch<T>(+ storage: &candle::CudaStorage,+ start: usize,+ end: usize,+ rows: usize,+ elem_count: usize,+ intermediate_size: usize,+ dtype: u32,+ kind: GeluGateKind,+ bf16_luts: Option<&Bf16GeluErfLutCache>,+ out_shape: Shape,+ stream: &std::sync::Arc<candle::cuda_backend::cudarc::driver::CudaStream>,+) -> Result<(candle::CudaStorage, Shape)>+where+ T: candle::cuda_backend::CudaDType + candle::cuda_backend::cudarc::driver::DeviceRepr,+{+ let dev = storage.device();+ let input = storage.as_cuda_slice::<T>()?.slice(start..end);+ let mut output = unsafe { dev.alloc::<T>(elem_count)? };+ if elem_count > 0 {+ let lut = if matches!(kind, GeluGateKind::ErfFirst) && dtype == 1 {+ let cache = bf16_luts.ok_or_else(|| {+ candle::Error::msg("BF16 exact-GELU gate requires an owner-scoped lookup cache")+ })?;+ Some(bf16_gelu_erf_lut(dev, stream, cache)?)+ } else {+ None+ };+ let (input_ptr, input_sync) = input.view_ptr(stream);+ let (output_ptr, output_sync) = output.device_ptr_mut(stream);+ let (lut_ptr, lut_sync) = match lut.as_ref() {+ Some(lut) => {+ let (ptr, sync) = lut.device_ptr(stream);+ (Some(ptr), Some(sync))+ }+ None => (None, None),+ };+ let status = unsafe {+ let input = input_ptr as *const core::ffi::c_void;+ let output = output_ptr as *mut core::ffi::c_void;+ match kind {+ GeluGateKind::TanhSecond => ffi::gelu_gate(+ input,+ output,+ rows as c_long,+ intermediate_size as c_int,+ dtype,+ stream.cu_stream().cast(),+ ),+ GeluGateKind::ErfFirst if dtype == 1 => ffi::gelu_erf_gate_bf16_lut(+ input,+ output,+ lut_ptr.expect("BF16 exact-GELU lookup table must be initialized")+ as *const core::ffi::c_void,+ rows as c_long,+ intermediate_size as c_int,+ stream.cu_stream().cast(),+ ),+ GeluGateKind::ErfFirst => ffi::gelu_erf_gate(+ input,+ output,+ rows as c_long,+ intermediate_size as c_int,+ dtype,+ stream.cu_stream().cast(),+ ),+ }+ };+ drop((input_sync, output_sync, lut_sync));+ if status != 0 {+ candle::bail!("gelu-gate CUDA kernel failed with status {status}");+ }+ }+ let output = candle::CudaStorage::wrap_cuda_slice(output, dev.clone());+ Ok((output, out_shape))+}++fn bf16_gelu_erf_lut(+ dev: &CudaDevice,+ stream: &Arc<candle::cuda_backend::cudarc::driver::CudaStream>,+ cache: &Bf16GeluErfLutCache,+) -> Result<Arc<CudaSlice<bf16>>> {+ let mut luts = cache+ .luts+ .lock()+ .map_err(|_| candle::Error::msg("BF16 exact-GELU lookup-table cache lock poisoned"))?;+ if let Some(lut) = luts.get(&dev.id()) {+ return Ok(lut.clone());+ }++ let mut lut = unsafe { dev.alloc::<bf16>(BF16_GELU_ERF_LUT_SIZE)? };+ let (lut_ptr, lut_sync) = lut.device_ptr_mut(stream);+ let status = unsafe {+ ffi::init_gelu_erf_bf16_lut(lut_ptr as *mut core::ffi::c_void, stream.cu_stream().cast())+ };+ drop(lut_sync);+ if status != 0 {+ candle::bail!("BF16 exact-GELU lookup-table initialization failed with status {status}");+ }++ let lut = Arc::new(lut);+ luts.insert(dev.id(), lut.clone());+ Ok(lut)+}++pub fn gelu_gate(input: &Tensor, intermediate_size: usize) -> Result<Tensor> {+ gelu_gate_with_kind(input, intermediate_size, GeluGateKind::TanhSecond, None)+}++fn gelu_gate_with_kind(+ input: &Tensor,+ intermediate_size: usize,+ kind: GeluGateKind,+ bf16_luts: Option<Arc<Bf16GeluErfLutCache>>,+) -> Result<Tensor> {+ let (storage, _) = input.storage_and_layout();+ match &*storage {+ Storage::Cuda(_) => {}+ _ => candle::bail!("gelu-gate expects a CUDA tensor"),+ }+ input.apply_op1_no_bwd(&GeluGate {+ intermediate_size,+ kind,+ bf16_luts,+ })+}++fn validate_intermediate_size(intermediate_size: usize) -> Result<()> {+ if intermediate_size == 0 || intermediate_size > i32::MAX as usize {+ candle::bail!("gelu-gate intermediate size must be in 1..=i32::MAX");+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use candle::Device;++ fn bf16_bits(tensor: &Tensor) -> Result<Vec<u16>> {+ Ok(tensor+ .flatten_all()?+ .to_vec1::<bf16>()?+ .into_iter()+ .map(bf16::to_bits)+ .collect())+ }++ #[test]+ #[ignore = "requires CUDA"]+ fn bf16_lut_handles_tail_shape_and_repeated_calls() -> Result<()> {+ const ROWS: usize = 9;+ const INTERMEDIATE_SIZE: usize = 33;++ let device = Device::new_cuda(0)?;+ let gates = (0..ROWS * INTERMEDIATE_SIZE)+ .map(|index| bf16::from_f32((index % 29) as f32 / 4.0 - 3.5))+ .collect::<Vec<_>>();+ let ups = (0..ROWS * INTERMEDIATE_SIZE)+ .map(|index| bf16::from_f32((index % 17) as f32 / 5.0 - 1.5))+ .collect::<Vec<_>>();+ let mut input = Vec::with_capacity(ROWS * INTERMEDIATE_SIZE * 2);+ for row in 0..ROWS {+ let start = row * INTERMEDIATE_SIZE;+ let end = start + INTERMEDIATE_SIZE;+ input.extend_from_slice(&gates[start..end]);+ input.extend_from_slice(&ups[start..end]);+ }++ let input = Tensor::from_vec(input, (ROWS, INTERMEDIATE_SIZE * 2), &device)?;+ let gates = Tensor::from_vec(gates, (ROWS, INTERMEDIATE_SIZE), &device)?;+ let ups = Tensor::from_vec(ups, (ROWS, INTERMEDIATE_SIZE), &device)?;+ let expected = (&gates.gelu_erf()? * &ups)?;+ let gate = GeluErfGate::new(INTERMEDIATE_SIZE)?;+ let first = gate.forward(&input)?;+ let second = gate.forward(&input)?;++ let expected = bf16_bits(&expected)?;+ assert_eq!(bf16_bits(&first)?, expected);+ assert_eq!(bf16_bits(&second)?, expected);+ Ok(())+ }++ #[test]+ #[ignore = "requires CUDA"]+ fn bf16_lut_matches_candle_for_all_raw_inputs() -> Result<()> {+ let device = Device::new_cuda(0)?;+ let gates = (u16::MIN..=u16::MAX)+ .map(bf16::from_bits)+ .collect::<Vec<_>>();+ let ups = vec![bf16::from_f32(1.0); BF16_GELU_ERF_LUT_SIZE];+ let input = Tensor::from_vec(+ [gates.as_slice(), ups.as_slice()].concat(),+ (1, BF16_GELU_ERF_LUT_SIZE * 2),+ &device,+ )?;+ let gate_tensor = Tensor::from_vec(gates.clone(), BF16_GELU_ERF_LUT_SIZE, &device)?;+ let up_tensor = Tensor::from_vec(ups, BF16_GELU_ERF_LUT_SIZE, &device)?;+ let expected = (&gate_tensor.gelu_erf()? * &up_tensor)?.to_vec1::<bf16>()?;+ let actual = GeluErfGate::new(BF16_GELU_ERF_LUT_SIZE)?+ .forward(&input)?+ .to_vec2::<bf16>()?+ .remove(0);++ let mut finite_inputs = 0usize;+ let mut nan_inputs = 0usize;+ let mut infinite_inputs = 0usize;+ for (raw_bits, ((gate, actual), expected)) in+ (u16::MIN..=u16::MAX).zip(gates.iter().zip(actual.iter()).zip(expected.iter()))+ {+ if gate.is_finite() {+ finite_inputs += 1;+ assert_eq!(+ actual.to_bits(),+ expected.to_bits(),+ "finite BF16 input 0x{raw_bits:04x}"+ );+ } else if gate.is_nan() {+ nan_inputs += 1;+ assert!(+ actual.is_nan() && expected.is_nan(),+ "NaN BF16 input 0x{raw_bits:04x}"+ );+ } else {+ infinite_inputs += 1;+ if expected.is_nan() {+ assert!(actual.is_nan(), "infinite BF16 input 0x{raw_bits:04x}");+ } else {+ assert_eq!(+ actual.to_bits(),+ expected.to_bits(),+ "infinite BF16 input 0x{raw_bits:04x}"+ );+ }+ }+ }++ assert_eq!(finite_inputs, 65_280);+ assert_eq!(nan_inputs, 254);+ assert_eq!(infinite_inputs, 2);+ Ok(())+ }++ #[test]+ #[ignore = "requires CUDA"]+ fn f16_and_f32_exact_erf_paths_match_candle_for_multiple_rows() -> Result<()> {+ const ROWS: usize = 5;+ const INTERMEDIATE_SIZE: usize = 34;++ let device = Device::new_cuda(0)?;+ let values = (0..ROWS * INTERMEDIATE_SIZE * 2)+ .map(|index| (index % 41) as f32 / 7.0 - 2.5)+ .collect::<Vec<_>>();+ for (dtype, tolerance) in [(DType::F16, 0.004f32), (DType::F32, 1e-6f32)] {+ let input = Tensor::from_vec(values.clone(), (ROWS, INTERMEDIATE_SIZE * 2), &device)?+ .to_dtype(dtype)?;+ let halves = input.chunk(2, candle::D::Minus1)?;+ let expected = (&halves[0].gelu_erf()? * &halves[1])?.to_dtype(DType::F32)?;+ let actual = GeluErfGate::new(INTERMEDIATE_SIZE)?+ .forward(&input)?+ .to_dtype(DType::F32)?;++ for (actual, expected) in actual+ .flatten_all()?+ .to_vec1::<f32>()?+ .iter()+ .zip(expected.flatten_all()?.to_vec1::<f32>()?)+ {+ assert!(+ (actual - expected).abs() <= tolerance,+ "{dtype:?} exact-erf mismatch: actual={actual} expected={expected}"+ );+ }+ }+ Ok(())+ }++ #[test]+ #[ignore = "requires CUDA"]+ fn bf16_lut_scalar_fallback_handles_misaligned_even_width_input() -> Result<()> {+ const ROWS: usize = 3;+ const INTERMEDIATE_SIZE: usize = 32;+ const ELEMENTS: usize = ROWS * INTERMEDIATE_SIZE * 2;++ let device = Device::new_cuda(0)?;+ let values = (0..=ELEMENTS)+ .map(|index| bf16::from_f32((index % 37) as f32 / 8.0 - 2.0))+ .collect::<Vec<_>>();+ let input = Tensor::from_vec(values, ELEMENTS + 1, &device)?+ .narrow(0, 1, ELEMENTS)?+ .reshape((ROWS, INTERMEDIATE_SIZE * 2))?;+ let halves = input.chunk(2, candle::D::Minus1)?;+ let expected = (&halves[0].gelu_erf()? * &halves[1])?;+ let actual = GeluErfGate::new(INTERMEDIATE_SIZE)?.forward(&input)?;++ assert_eq!(bf16_bits(&actual)?, bf16_bits(&expected)?);+ Ok(())+ }++ #[test]+ fn bf16_lut_cache_lifetime_is_bound_to_gate_owners() -> Result<()> {+ let gate = GeluErfGate::new(32)?;+ let cache = Arc::downgrade(&gate.bf16_luts);+ let cloned = gate.clone();++ drop(gate);+ assert!(cache.upgrade().is_some());+ drop(cloned);+ assert!(cache.upgrade().is_none());+ Ok(())+ }++ #[test]+ #[ignore = "requires CUDA"]+ fn populated_bf16_lut_cache_drops_with_all_gate_owners() -> Result<()> {+ const INTERMEDIATE_SIZE: usize = 32;++ let device = Device::new_cuda(0)?;+ let input = Tensor::from_vec(+ vec![bf16::from_f32(1.0); INTERMEDIATE_SIZE * 2],+ (1, INTERMEDIATE_SIZE * 2),+ &device,+ )?;+ let gate = GeluErfGate::new(INTERMEDIATE_SIZE)?;+ let cloned = gate.clone();+ let cache = Arc::downgrade(&gate.bf16_luts);++ let output = gate.forward(&input)?;+ output.to_vec2::<bf16>()?;+ assert_eq!(+ gate.bf16_luts+ .luts+ .lock()+ .map_err(|_| candle::Error::msg("test cache lock poisoned"))?+ .len(),+ 1+ );++ drop(gate);+ assert!(cache.upgrade().is_some());+ drop(cloned);+ assert!(cache.upgrade().is_none());+ Ok(())+ }+}diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/Cargo.toml b/packages/sie_server_rust/vendor/candle-layer-norm/Cargo.tomlnew file mode 100644index 000000000..73a276670--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/Cargo.toml@@ -0,0 +1,49 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+name = "candle-layer-norm"+version = "0.0.1"+build = "build.rs"+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "Layer Norm layer for the candle ML framework."+homepage = "https://github.com/huggingface/candle-extensions/candle-layer-norm/"+documentation = "https://docs.rs/candle-layer-norm"+readme = "README.md"+license = "BSD-3-Clause"++[lib]+name = "candle_layer_norm"+path = "src/lib.rs"++[dependencies.candle]+version = "0.10.2"+features = ["cuda"]+package = "candle-core"++[dependencies.half]+version = "2.3.1"+features = ["num-traits"]++[build-dependencies.anyhow]+version = "1"+features = ["backtrace"]++[build-dependencies.num_cpus]+version = "1.15.0"++[build-dependencies.rayon]+version = "1.7.0"diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSEnew file mode 100644index 000000000..5860e4b33--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE@@ -0,0 +1,29 @@+BSD 3-Clause License++Copyright (c) 2022, the respective contributors, as shown by the AUTHORS file.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-APACHE b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-APACHEnew file mode 100644index 000000000..261eeb9e9--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-APACHE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-MIT b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-MITnew file mode 100644index 000000000..31aa79387--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/LICENSE-MIT@@ -0,0 +1,23 @@+Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/README.md b/packages/sie_server_rust/vendor/candle-layer-norm/README.mdnew file mode 100644index 000000000..e5b3f4ac8--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/README.md@@ -0,0 +1,14 @@+# Candle Cuda Layer Norm++Layer Norm fused operation for the Candle ML framework.++This Layer was adapted from https://github.com/Dao-AILab/flash-attention/tree/main/csrc/layer_norm.++It implements fused dropout + residual + LayerNorm, building on Apex's FastLayerNorm.++Major changes:++- Add residual.+- Make it work for both pre-norm and post-norm architecture.+- Support more hidden dimensions (all dimensions divisible by 8, up to 8192).+- Implement RMSNorm as an option.diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/build.rs b/packages/sie_server_rust/vendor/candle-layer-norm/build.rsnew file mode 100644index 000000000..77705d4b6--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/build.rs@@ -0,0 +1,264 @@+// Build script to run nvcc and generate the C glue code for launching the layer-norm kernel.+// The cuda build time is very long so one can set the CANDLE_LAYER_NORM_BUILD_DIR environment+// variable in order to cache the compiled artifacts and avoid recompiling too often.+use anyhow::{Context, Result};+use rayon::prelude::*;+use std::path::PathBuf;+use std::str::FromStr;++const KERNEL_FILES: [&str; 1] = ["ln_api.cu"];++fn main() -> Result<()> {+ let num_cpus = std::env::var("RAYON_NUM_THREADS").map_or_else(+ |_| num_cpus::get_physical(),+ |s| usize::from_str(&s).unwrap(),+ );++ rayon::ThreadPoolBuilder::new()+ .num_threads(num_cpus)+ .build_global()+ .unwrap();++ println!("cargo:rerun-if-changed=build.rs");+ for kernel_file in KERNEL_FILES.iter() {+ println!("cargo:rerun-if-changed=kernels/{kernel_file}");+ }+ println!("cargo:rerun-if-changed=kernels/ln_fwd_kernels.cuh");+ println!("cargo:rerun-if-changed=kernels/ln_kernel_traits.h");+ println!("cargo:rerun-if-changed=kernels/ln_utils.cuh");+ println!("cargo:rerun-if-changed=kernels/static_switch.h");+ println!("cargo:rerun-if-env-changed=CANDLE_LAYER_NORM_BUILD_DIR");+ let out_dir = PathBuf::from(std::env::var("OUT_DIR").context("OUT_DIR not set")?);+ let build_dir = match std::env::var("CANDLE_LAYER_NORM_BUILD_DIR") {+ Err(_) =>+ {+ #[allow(clippy::redundant_clone)]+ out_dir.clone()+ }+ Ok(build_dir) => {+ let path = PathBuf::from(build_dir);+ path.canonicalize().expect(&format!(+ "Directory doesn't exists: {} (the current directory is {})",+ &path.display(),+ std::env::current_dir()?.display()+ ))+ }+ };+ set_cuda_include_dir()?;++ let ccbin_env = std::env::var("CANDLE_NVCC_CCBIN");+ println!("cargo:rerun-if-env-changed=CANDLE_NVCC_CCBIN");++ let compute_cap = compute_cap()?;++ let out_file = build_dir.join("liblayernorm.a");+ let stamp_file = build_dir.join("liblayernorm.stamp");+ let build_stamp = format!(+ "CUDA_COMPUTE_CAP={compute_cap}\nCANDLE_NVCC_CCBIN={}\n",+ ccbin_env.as_deref().unwrap_or("")+ );++ let kernel_dir = PathBuf::from("kernels");+ let cu_files: Vec<_> = KERNEL_FILES+ .iter()+ .map(|f| {+ let mut obj_file = out_dir.join(f);+ obj_file.set_extension("o");+ (kernel_dir.join(f), obj_file)+ })+ .collect();++ let out_modified: Result<_, _> = out_file.metadata().and_then(|m| m.modified());+ let should_compile = if out_file.exists() {+ std::fs::read_to_string(&stamp_file).ok().as_deref() != Some(build_stamp.as_str())+ || kernel_dir+ .read_dir()+ .expect("kernels folder should exist")+ .any(|entry| {+ if let (Ok(entry), Ok(out_modified)) = (entry, &out_modified) {+ let in_modified = entry.metadata().unwrap().modified().unwrap();+ in_modified.duration_since(*out_modified).is_ok()+ } else {+ true+ }+ })+ } else {+ true+ };+ if should_compile {+ cu_files+ .par_iter()+ .map(|(cu_file, obj_file)| {+ let mut command = std::process::Command::new("nvcc");+ command+ .arg("-std=c++17")+ .arg("-O3")+ .arg("-U__CUDA_NO_HALF_OPERATORS__")+ .arg("-U__CUDA_NO_HALF_CONVERSIONS__")+ .arg("-U__CUDA_NO_BFLOAT16_OPERATORS__")+ .arg("-U__CUDA_NO_BFLOAT16_CONVERSIONS__")+ .arg("-U__CUDA_NO_BFLOAT162_OPERATORS__")+ .arg("-U__CUDA_NO_BFLOAT162_CONVERSIONS__")+ .arg(format!("--gpu-architecture=sm_{compute_cap}"))+ .arg("-c")+ .args(["-o", obj_file.to_str().unwrap()])+ .args(["--default-stream", "per-thread"])+ .arg("--expt-relaxed-constexpr")+ .arg("--expt-extended-lambda")+ .arg("--use_fast_math")+ .arg("--verbose");+ if let Ok(ccbin_path) = &ccbin_env {+ command+ .arg("-allow-unsupported-compiler")+ .args(["-ccbin", ccbin_path]);+ }+ command.arg(cu_file);+ let output = command+ .spawn()+ .context("failed spawning nvcc")?+ .wait_with_output()?;+ if !output.status.success() {+ anyhow::bail!(+ "nvcc error while executing compiling: {:?}\n\n# stdout\n{:#}\n\n# stderr\n{:#}",+ &command,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ }+ Ok(())+ })+ .collect::<Result<()>>()?;+ let obj_files = cu_files.iter().map(|c| c.1.clone()).collect::<Vec<_>>();+ let mut command = std::process::Command::new("nvcc");+ command+ .arg("--lib")+ .args(["-o", out_file.to_str().unwrap()])+ .args(obj_files);+ let output = command+ .spawn()+ .context("failed spawning nvcc")?+ .wait_with_output()?;+ if !output.status.success() {+ anyhow::bail!(+ "nvcc error while linking: {:?}\n\n# stdout\n{:#}\n\n# stderr\n{:#}",+ &command,+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+ }+ std::fs::write(&stamp_file, build_stamp)+ .with_context(|| format!("write layer-norm build stamp {}", stamp_file.display()))?;+ }+ println!("cargo:rustc-link-search={}", build_dir.display());+ println!("cargo:rustc-link-lib=layernorm");+ println!("cargo:rustc-link-lib=dylib=cudart");+ println!("cargo:rustc-link-lib=dylib=stdc++");++ Ok(())+}++fn set_cuda_include_dir() -> Result<()> {+ // NOTE: copied from cudarc build.rs.+ let env_vars = [+ "CUDA_PATH",+ "CUDA_ROOT",+ "CUDA_TOOLKIT_ROOT_DIR",+ "CUDNN_LIB",+ ];+ let env_vars = env_vars+ .into_iter()+ .map(std::env::var)+ .filter_map(Result::ok)+ .map(Into::<PathBuf>::into);++ let roots = [+ "/usr",+ "/usr/local/cuda",+ "/opt/cuda",+ "/usr/lib/cuda",+ "C:/Program Files/NVIDIA GPU Computing Toolkit",+ "C:/CUDA",+ ];+ let roots = roots.into_iter().map(Into::<PathBuf>::into);+ let root = env_vars+ .chain(roots)+ .find(|path| path.join("include").join("cuda.h").is_file())+ .context("cannot find include/cuda.h")?;+ println!(+ "cargo:rustc-env=CUDA_INCLUDE_DIR={}",+ root.join("include").display()+ );+ Ok(())+}++#[allow(unused)]+fn compute_cap() -> Result<usize> {+ println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");++ // Try to parse compute caps from env+ let mut compute_cap = if let Ok(compute_cap_str) = std::env::var("CUDA_COMPUTE_CAP") {+ println!("cargo:rustc-env=CUDA_COMPUTE_CAP={compute_cap_str}");+ compute_cap_str+ .parse::<usize>()+ .context("Could not parse code")?+ } else {+ // Use nvidia-smi to get the current compute cap+ let out = std::process::Command::new("nvidia-smi")+ .arg("--query-gpu=compute_cap")+ .arg("--format=csv")+ .output()+ .context("`nvidia-smi` failed. Ensure that you have CUDA installed and that `nvidia-smi` is in your PATH.")?;+ let out = std::str::from_utf8(&out.stdout).context("stdout is not a utf8 string")?;+ let mut lines = out.lines();+ assert_eq!(+ lines.next().context("missing line in stdout")?,+ "compute_cap"+ );+ let cap = lines+ .next()+ .context("missing line in stdout")?+ .replace('.', "");+ let cap = cap+ .parse::<usize>()+ .with_context(|| format!("cannot parse as int {cap}"))?;+ println!("cargo:rustc-env=CUDA_COMPUTE_CAP={cap}");+ cap+ };++ // Grab available GPU codes from nvcc and select the highest one+ let (supported_nvcc_codes, max_nvcc_code) = {+ let out = std::process::Command::new("nvcc")+ .arg("--list-gpu-code")+ .output()+ .expect("`nvcc` failed. Ensure that you have CUDA installed and that `nvcc` is in your PATH.");+ let out = std::str::from_utf8(&out.stdout).unwrap();++ let out = out.lines().collect::<Vec<&str>>();+ let mut codes = Vec::with_capacity(out.len());+ for code in out {+ let code = code.split('_').collect::<Vec<&str>>();+ if !code.is_empty() && code.contains(&"sm") {+ if let Ok(num) = code[1].parse::<usize>() {+ codes.push(num);+ }+ }+ }+ codes.sort();+ let max_nvcc_code = *codes.last().unwrap();+ (codes, max_nvcc_code)+ };++ // Check that nvcc supports the asked compute cap+ if !supported_nvcc_codes.contains(&compute_cap) {+ anyhow::bail!(+ "nvcc cannot target gpu arch {compute_cap}. Available nvcc targets are {supported_nvcc_codes:?}."+ );+ }+ if compute_cap > max_nvcc_code {+ anyhow::bail!(+ "CUDA compute cap {compute_cap} is higher than the highest gpu code from nvcc {max_nvcc_code}"+ );+ }++ Ok(compute_cap)+}diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln.h b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln.hnew file mode 100644index 000000000..31dae138e--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln.h@@ -0,0 +1,206 @@+#pragma once++#include <functional>+#include <unordered_map>+#include <cuda_runtime_api.h>+#include <cuda_fp16.h>+#include <cuda_bf16.h>++#include <stdint.h>+#include <stdlib.h>+#include <stdio.h>+#include <iostream>+++//#ifdef OLD_GENERATOR_PATH+//#include <ATen/CUDAGeneratorImpl.h>+//#else+//#include <ATen/cuda/CUDAGeneratorImpl.h>+//#endif++namespace layer_norm {++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename Params>+struct LaunchParams{++ size_t elts_per_thread;+ size_t workspace_bytes;+ size_t barrier_size;++ int multi_processor_count;++ cudaStream_t stream;++ Params params;++};++////////////////////////////////////////////////////////////////////////////////////////////////////++struct ParamsBase {+ ParamsBase()+ : ctas_per_col(0)+ , rows(0)+ , cols(0)+ , x(nullptr)+ , mu(nullptr)+ , rs(nullptr)+ , gamma(nullptr)+ , gamma1(nullptr)+ , rowscale(nullptr)+ , colscale(nullptr)+ , dropout_keep_p(1.f)+ , dropout_scale(1.f)+ , is_rms_norm(false)+ , workspace(nullptr)+ , barrier(nullptr)+ {+ }++ // For Multi-CTA, number of different CTA groups. Otherwise same as gridDim.x.+ int ctas_per_col;++ // Input is interpreted as matrix. We normalize across columns.+ int rows;+ int cols;++ // Common data pointers.+ void *x0;+ void *x1;+ void *residual;+ void *x;+ void *dmask;+ void *dmask1;+ void *mu;+ void *rs;+ void *gamma;+ void *gamma1;+ void *rowscale;+ void *colscale;+ void *x0_subset;+ void *z_subset;++ float inverse_cols;++ float dropout_keep_p;+ float dropout_scale;+ float rowscale_const;++ bool is_rms_norm;++ // Multi-CTA workspace in gmem.+ void *workspace;++ // Multi-CTA sync barriers in gmem.+ int *barrier;++};++////////////////////////////////////////////////////////////////////////////////////////////////////++struct FwdParams : public ParamsBase {+ FwdParams()+ : ParamsBase()+ , z(nullptr)+ , z1(nullptr)+ , beta(nullptr)+ , beta1(nullptr)+ , epsilon(0.f)+ {+ }++ // Output of LN FWD.+ void *z;+ void *z1;+ void *beta;+ void *beta1;+ float epsilon;++ // Random state.+ // at::PhiloxCudaState philox_args;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++using FwdFunction = std::function<cudaError_t(LaunchParams<FwdParams>&, const bool)>;+using FunctionKey = uint64_t;+using FwdRegistry = std::unordered_map<FunctionKey, FwdFunction>;++extern FwdRegistry FWD_FUNCS;++////////////////////////////////////////////////////////////////////////////////////////////////////++using fp32 = float;+using fp16 = half;+using bf16 = nv_bfloat16;++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+struct TypeId{};++template<>+struct TypeId<fp16>{+ constexpr static uint32_t Value = 0;+};++template<>+struct TypeId<bf16>{+ constexpr static uint32_t Value = 1;+};++template<>+struct TypeId<fp32>{+ constexpr static uint32_t Value = 2;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, int S>+struct Type2Key{+ constexpr static uint32_t Value = TypeId<T>::Value << S;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+struct WeightType2Key : public Type2Key<T, 0>{};++template<typename T>+struct InputType2Key : public Type2Key<T, 2>{};++template<typename T>+struct ResidualType2Key : public Type2Key<T, 4>{};++template<typename T>+struct OutputType2Key : public Type2Key<T, 6>{};++template<typename T>+struct ComputeType2Key : public Type2Key<T, 8>{};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename W, typename I, typename R, typename O, typename C>+struct Types2Key{+ constexpr static uint32_t Value = WeightType2Key<W>::Value | InputType2Key<I>::Value | ResidualType2Key<R>::Value | OutputType2Key<O>::Value | ComputeType2Key<C>::Value;+ constexpr static inline uint64_t get(const uint64_t hidden_size){+ constexpr uint64_t type_key = Value;+ return (type_key << 32) | hidden_size;+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename W, typename I, typename R, typename O, typename C, uint64_t HIDDEN_SIZE>+struct FwdRegistrar{+ FwdRegistrar(FwdFunction f){+ uint64_t key = Types2Key<W,I,R,O,C>::get(HIDDEN_SIZE);+ FWD_FUNCS.insert({ key, f });+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++} // namespace layer_normdiff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_api.cu b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_api.cunew file mode 100644index 000000000..b79d290bf--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_api.cu@@ -0,0 +1,281 @@+#include "ln.h"+#include "ln_fwd_kernels.cuh"+#include <iostream>++/*+Ada++Supported Type combinations:++input residual compute weights output+============================================+fp32 fp32 fp32 fp32 fp32+fp16 fp32 fp32 fp32 fp16+fp16 fp16 fp32 fp32 fp16+bf16 fp32 fp32 fp32 bf16+bf16 bf16 fp32 fp32 bf16+fp16 fp16 fp32 fp16 fp16+bf16 bf16 fp32 bf16 bf16++Remarks:+Output type = Input type+Compute always in FP32++*/++namespace layer_norm {++FwdRegistry FWD_FUNCS;++uint64_t get_key(uint32_t wtype, uint32_t itype, uint32_t rtype, uint32_t otype, uint32_t ctype, uint64_t hidden_size) {+ using namespace layer_norm;+ uint64_t type_key = wtype | (itype << 2) | (rtype << 4) | (otype << 6) | (ctype << 8);+ uint64_t launcher_key = (type_key << 32) | hidden_size;+ return launcher_key;+}++}++layer_norm::FwdFunction * get_fwd_launcher(uint32_t wtype, uint32_t itype, uint32_t rtype, uint32_t otype, uint32_t ctype, uint32_t hidden_size) {+ auto iter = layer_norm::FWD_FUNCS.find(layer_norm::get_key(wtype, itype, rtype, otype, ctype, hidden_size));+ if (iter == layer_norm::FWD_FUNCS.end()) {+ return nullptr;+ }+ return &iter->second;+}++REGISTER_FWD_LAUNCHER( 256, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 256, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 512, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 512, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 768, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 768, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 1024, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1024, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 1280, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1280, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 1536, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 1536, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 2048, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2048, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 2560, fp32, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp16, fp32, fp32, fp32, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp32, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp16, fp16, fp32, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp32, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp32, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, bf16, bf16, fp32, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp32, bf16, bf16, bf16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, fp16, fp16, fp16, fp16, fp32, 1, 4, 1, 16);+REGISTER_FWD_LAUNCHER( 2560, bf16, bf16, bf16, bf16, fp32, 1, 4, 1, 16);++REGISTER_FWD_LAUNCHER( 3072, fp32, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp16, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp32, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp16, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp32, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp32, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, bf16, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp32, bf16, bf16, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, fp16, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 3072, bf16, bf16, bf16, bf16, fp32, 1, 1, 4, 16);++REGISTER_FWD_LAUNCHER( 4096, fp32, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp16, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp32, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp16, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp32, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp32, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, bf16, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp32, bf16, bf16, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, fp16, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 4096, bf16, bf16, bf16, bf16, fp32, 1, 1, 4, 16);++REGISTER_FWD_LAUNCHER( 5120, fp32, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp16, fp32, fp32, fp32, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp32, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp16, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp32, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp32, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, bf16, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp32, bf16, bf16, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, fp16, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 5120, bf16, bf16, bf16, bf16, fp32, 1, 1, 4, 16);++REGISTER_FWD_LAUNCHER( 6144, fp32, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp16, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp32, fp16, fp32, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp16, fp16, fp32, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp32, fp16, fp16, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp32, bf16, fp32, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, bf16, bf16, fp32, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp32, bf16, bf16, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, fp16, fp16, fp16, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 6144, bf16, bf16, bf16, bf16, fp32, 1, 1, 8, 16);++REGISTER_FWD_LAUNCHER( 7168, fp32, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 7168, fp16, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 7168, fp32, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, fp16, fp16, fp32, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, fp32, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, fp32, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, bf16, bf16, fp32, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, fp32, bf16, bf16, bf16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, fp16, fp16, fp16, fp16, fp32, 1, 1, 4, 16);+REGISTER_FWD_LAUNCHER( 7168, bf16, bf16, bf16, bf16, fp32, 1, 1, 4, 16);++REGISTER_FWD_LAUNCHER( 8192, fp32, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp16, fp32, fp32, fp32, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp32, fp16, fp32, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp16, fp16, fp32, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp32, fp16, fp16, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp32, bf16, fp32, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, bf16, bf16, fp32, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp32, bf16, bf16, bf16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, fp16, fp16, fp16, fp16, fp32, 1, 1, 8, 16);+REGISTER_FWD_LAUNCHER( 8192, bf16, bf16, bf16, bf16, fp32, 1, 1, 8, 16);++extern "C" int run_ln(+ void *x,+ void *residual,+ void *gamma,+ void *beta,+ void *dst_add,+ void *dst,+ void *mu,+ void *rsigma,++ float epsilon,++ uint32_t hidden_size_rounded,+ uint32_t rows,+ uint32_t cols,+ int32_t multi_processor_count,++ uint32_t wtype,+ uint32_t itype,+ uint32_t rtype,+ uint32_t otype,+ uint32_t ctype,++ int is_rms_norm,+ void *stream+) {+ layer_norm::LaunchParams<layer_norm::FwdParams> launch_params;++ launch_params.multi_processor_count = multi_processor_count;+ // Candle's production device uses CUDA's legacy default stream (a null+ // driver stream). This translation unit is compiled with PTDS semantics,+ // so make the legacy intent explicit instead of interpreting null as PTDS.+ launch_params.stream = stream == nullptr+ ? cudaStreamLegacy+ : static_cast<cudaStream_t>(stream);++ launch_params.params.dropout_keep_p = 1.f;+ launch_params.params.residual = residual;+ launch_params.params.rowscale = nullptr;+ launch_params.params.colscale = nullptr;+ launch_params.params.x0_subset = nullptr;+ launch_params.params.z_subset = nullptr;++ // Request the kernel launcher.+ auto launcher = get_fwd_launcher(wtype, itype, rtype, otype, ctype, hidden_size_rounded);+ if (launcher == nullptr) {+ return cudaErrorInvalidValue;+ }++ // Set the kernel runtime parameters.+ layer_norm::FwdParams ¶ms = launch_params.params;++ params.rows = rows;+ params.cols = cols;+ params.x0 = x;+ params.x = dst_add;+ params.dmask = nullptr;+ params.mu = mu;+ params.rs = rsigma;+ params.gamma = gamma;+ params.beta = beta;+ params.z = dst;+ params.epsilon = epsilon;+ params.dropout_scale = 1.f;+ params.inverse_cols = 1.f / float(params.cols);+ params.rowscale_const = 1.f;+ params.is_rms_norm = is_rms_norm;++ // Query the kernel-specific launch parameters.+ auto status = (*launcher)(launch_params, true);+ if (status != cudaSuccess) {+ return status;+ }++ // Launch the kernel.+ status = (*launcher)(launch_params, false);+ if (status != cudaSuccess) {+ return status;+ }+ return cudaGetLastError();+}diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_fwd_kernels.cuh b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_fwd_kernels.cuhnew file mode 100644index 000000000..0f189b098--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_fwd_kernels.cuh@@ -0,0 +1,292 @@+#pragma once++// #ifdef OLD_GENERATOR_PATH+// #include <ATen/CUDAGeneratorImpl.h>+// #else+// #include <ATen/cuda/CUDAGeneratorImpl.h>+// #endif++// #include <ATen/cuda/detail/UnpackRaw.cuh> // For at::cuda::philox::unpack+#include <curand_kernel.h>++#include "ln.h"+#include "ln_utils.cuh"+#include "ln_kernel_traits.h"+#include "static_switch.h"++namespace layer_norm {++template<typename Ktraits, bool Is_dropout, bool Has_colscale, bool Has_subset, bool Is_even_cols>+__global__ __launch_bounds__(Ktraits::THREADS_PER_CTA)+void ln_fwd_kernel(FwdParams params) {++ enum { ROWS_PER_CTA = Ktraits::ROWS_PER_CTA };+ enum { WARPS_N = Ktraits::WARPS_N };+ enum { WARPS_M = Ktraits::WARPS_M };+ enum { THREADS_PER_ROW = Ktraits::THREADS_PER_ROW };+ enum { VEC_COLS_PER_LDG = Ktraits::VEC_COLS_PER_LDG };+ enum { BYTES_PER_ROW = Ktraits::BYTES_PER_ROW };+ enum { LDGS = Ktraits::LDGS };+ enum { NUM_ELTS = Ktraits::NUM_ELTS };+ enum { CTAS_PER_ROW = Ktraits::CTAS_PER_ROW };++ using input_t = typename Ktraits::input_t;+ using residual_t = typename Ktraits::residual_t;+ using output_t = typename Ktraits::output_t;+ using index_t = typename Ktraits::index_t;+ using compute_t = typename Ktraits::compute_t;+ using mask_t = typename Ktraits::mask_t;+ using Ivec = typename Ktraits::Ivec;+ using Rvec = typename Ktraits::Rvec;+ using Ovec = typename Ktraits::Ovec;+ using Wvec = typename Ktraits::Wvec;+ using Cvec = typename Ktraits::Cvec;+ using Mvec = typename Ktraits::Mvec;++ using Stats = typename Ktraits::Stats;+ using stats_t = typename Stats::stats_t;++ const bool has_residual = params.residual != nullptr;+ const bool save_x = params.x != nullptr && (has_residual || Is_dropout || Has_colscale || (params.rowscale != nullptr) || Has_subset || !(std::is_same<input_t, residual_t>::value));++ extern __shared__ char smem_[];++ const index_t tidx = threadIdx.x;+ const index_t bidn = blockIdx.x % CTAS_PER_ROW;+ const index_t bidm = blockIdx.x / CTAS_PER_ROW;+ const index_t lane = tidx % THREADS_PER_WARP;+ const index_t warp = tidx / THREADS_PER_WARP;+ const index_t warp_m = warp / WARPS_N;+ const index_t warp_n = warp % WARPS_N;++ const index_t r = bidm * ROWS_PER_CTA + warp_m;+ const index_t c = bidn * THREADS_PER_ROW + warp_n * THREADS_PER_WARP + lane;++ Stats stats(params, bidm, bidn, warp_m, warp_n, lane, smem_);++ compute_t *mu_ptr = static_cast<compute_t *>(params.mu);+ compute_t *rs_ptr = static_cast<compute_t *>(params.rs);++ const input_t *rowscale = static_cast<input_t *>(params.rowscale);+ const index_t *x0_subset = static_cast<index_t *>(params.x0_subset);+ const index_t *z_subset = static_cast<index_t *>(params.z_subset);++ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/cuda/Dropout.cu+ // curandStatePhilox4_32_10_t state;+ // if (Is_dropout) {+ // auto seeds = at::cuda::philox::unpack(params.philox_args);+ // const index_t tidx_global = blockIdx.x * blockDim.x + threadIdx.x;+ // curand_init(std::get<0>(seeds), tidx_global, std::get<1>(seeds), &state);+ //}++ const index_t num_valid_ldgs = ((params.cols / Ktraits::ELTS_PER_LDG) - 1 - c + VEC_COLS_PER_LDG) / VEC_COLS_PER_LDG;++ Wvec gamma[LDGS];+ Wvec beta[LDGS];+ Wvec colscale[LDGS];+ index_t idx = c;+ #pragma unroll+ for( int it = 0; it < LDGS; it++ ) {+ if (Is_even_cols || (it < num_valid_ldgs)) {+ gamma[it].load_from(params.gamma, idx);+ if (params.beta != nullptr) {+ beta[it].load_from(params.beta, idx);+ } else {+ beta[it].zero_();+ }+ if (Has_colscale) { colscale[it].load_from(params.colscale, idx); }+ idx += VEC_COLS_PER_LDG;+ }+ }++ for( int row = r; row < params.rows; row += params.ctas_per_col * ROWS_PER_CTA ) {+ const compute_t rowscale_val = !Has_subset ? (params.rowscale == nullptr ? 1.0f : compute_t(rowscale[row])) : params.rowscale_const;+ const int row_x0 = !Has_subset ? row + 1 : x0_subset[row];+ const int row_z = !Has_subset ? row + 1 : z_subset[row];+ const bool load_x0 = !Has_subset || row_x0 > 0;+ index_t idx_x = row * params.cols / Ktraits::ELTS_PER_LDG + c;+ index_t idx_x0 = !Has_subset ? idx_x : (load_x0 ? (row_x0 - 1) * params.cols / Ktraits::ELTS_PER_LDG + c : 0);+ compute_t xf[LDGS * NUM_ELTS];+ #pragma unroll+ for( int it = 0; it < LDGS; it++ ) {+ if (Is_even_cols || (it < num_valid_ldgs)) {+ Ivec x0;+ Rvec residual;+ Rvec x;+ Mvec dmask;+ if (load_x0) { x0.load_from(params.x0, !Has_subset ? idx_x : idx_x0); }+ if (has_residual) { residual.load_from(params.residual, idx_x); }+ #pragma unroll+ for( int jt = 0; jt < NUM_ELTS; jt++ ) {+ // TD [2022-04-22]: We're memory bound, not compute bound, so we don't need to use+ // the more efficient curand_uniform4.+ compute_t x_ij;+ if (load_x0) {+ //mask_t keep = !Is_dropout ? true : curand_uniform(&state) <= params.dropout_keep_p;+ mask_t keep = false;+ // if (Is_dropout) { dmask.data.elt[jt] = keep; }+ compute_t x0_ij = compute_t(x0.data.elt[jt]) * rowscale_val;+ // x0_ij = keep ? (Is_dropout ? x0_ij * params.dropout_scale : x0_ij) : 0.0f;+ if (Has_colscale) { x0_ij *= compute_t(colscale[it].data.elt[jt]); }+ x_ij = has_residual ? x0_ij + compute_t(residual.data.elt[jt]) : x0_ij;+ } else {+ x_ij = has_residual ? compute_t(residual.data.elt[jt]) : 0.f;+ }+ if (save_x) { x.data.elt[jt] = x_ij; }+ xf[it * NUM_ELTS + jt] = x_ij;+ }+ if (save_x) { x.store_to(params.x, idx_x); }+ // if (Is_dropout && load_x0) { dmask.store_to(params.dmask, !Has_subset ? idx_x : idx_x0); }+ idx_x += VEC_COLS_PER_LDG;+ idx_x0 += VEC_COLS_PER_LDG;+ }+ }++ static_assert(CTAS_PER_ROW == 1, "Don't support multiple CTAs per row for now");+ const index_t num_vecs = params.cols / Ktraits::ELTS_PER_LDG;+ const index_t num_full_ldgs = num_vecs / Ktraits::VEC_COLS_PER_LDG;+ const index_t remaining_vecs = num_vecs % Ktraits::VEC_COLS_PER_LDG;+ auto valid_elts_in_warp_fn = [num_full_ldgs, remaining_vecs] (int warp_n) -> int {+ // Need to convert to int, otherwise the subtraction will wrap around.+ const index_t valid_partial_vecs_in_warp =+ std::min(std::max(int(remaining_vecs) - int(warp_n * THREADS_PER_WARP), int(0)),+ int(THREADS_PER_WARP));+ return (num_full_ldgs * THREADS_PER_WARP + valid_partial_vecs_in_warp) * NUM_ELTS;+ };+ stats_t s = stats.template compute<Is_even_cols>(+ xf, params.inverse_cols, valid_elts_in_warp_fn, num_valid_ldgs * NUM_ELTS+ );++ compute_t mu = layer_norm::Get<0>::of<stats_t, compute_t>(s);+ compute_t m2 = layer_norm::Get<1>::of<stats_t, compute_t>(s);++ if( mu_ptr != nullptr && bidn == 0 && warp_n == 0 && lane == 0 ) {+ mu_ptr[row] = mu;+ }++ compute_t rs = rsqrtf(m2 * params.inverse_cols + params.epsilon + (!params.is_rms_norm ? 0.f : mu * mu));++ if( rs_ptr != nullptr && bidn == 0 && warp_n == 0 && lane == 0 ) {+ rs_ptr[row] = rs;+ }++ const bool save_z = !Has_subset || row_z > 0;+ if (save_z) {+ index_t idx_z = (!Has_subset ? row : (row_z - 1)) * params.cols / Ktraits::ELTS_PER_LDG + c;+ #pragma unroll+ for( int it = 0; it < LDGS; it++ ) {+ if (Is_even_cols || (it < num_valid_ldgs)) {+ Ovec z;+ #pragma unroll+ for( int jt = 0; jt < NUM_ELTS; jt++ ) {+ compute_t y_ij = compute_t(rs * (xf[it * NUM_ELTS + jt] - (!params.is_rms_norm ? mu : 0.f)));+ compute_t g_ij = gamma[it].data.elt[jt];+ compute_t b_ij = beta[it].data.elt[jt];+ z.data.elt[jt] = output_t(g_ij * y_ij + b_ij);+ }+ z.store_to(params.z, idx_z);+ idx_z += VEC_COLS_PER_LDG;+ }+ }+ }++ }+}++} // namespace layer_norm++using namespace layer_norm;++template<+ typename weight_t,+ typename input_t,+ typename residual_t,+ typename output_t,+ typename compute_t,+ typename index_t,+ int HIDDEN_SIZE,+ int CTAS_PER_ROW,+ int WARPS_M,+ int WARPS_N,+ int BYTES_PER_LDG+>+cudaError_t launch_(LaunchParams<FwdParams> &launch_params, const bool configure_params){++ using Kernel_traits = Kernel_traits<weight_t,+ input_t,+ residual_t,+ output_t,+ compute_t,+ index_t,+ HIDDEN_SIZE,+ CTAS_PER_ROW,+ WARPS_M,+ WARPS_N,+ BYTES_PER_LDG+ >;+ bool has_colscale = launch_params.params.colscale != nullptr;+ bool has_subset = launch_params.params.x0_subset != nullptr;+ bool is_even_cols = launch_params.params.cols == HIDDEN_SIZE;+ cudaError_t status = cudaSuccess;+ BOOL_SWITCH(launch_params.params.dropout_keep_p < 1.f, IsDropoutConst, [&] {+ BOOL_SWITCH(has_colscale, HasColscaleConst, [&] {+ BOOL_SWITCH(has_subset, HasSubsetConst, [&] {+ BOOL_SWITCH(is_even_cols, IsEvenColsConst, [&] {+ auto kernel = &ln_fwd_kernel<Kernel_traits, IsDropoutConst, HasColscaleConst, HasSubsetConst, IsEvenColsConst>;+ if( configure_params ) {+ int ctas_per_sm;+ status = check_cuda_(+ cudaOccupancyMaxActiveBlocksPerMultiprocessor(+ &ctas_per_sm, kernel, Kernel_traits::THREADS_PER_CTA, Kernel_traits::SMEM_BYTES_FWD),+ __FILE__,+ __LINE__);+ if( status != cudaSuccess ) {+ return;+ }+ launch_params.params.ctas_per_col = launch_params.multi_processor_count * ctas_per_sm / Kernel_traits::CTAS_PER_ROW;+ const size_t rows_per_loop = launch_params.params.ctas_per_col * Kernel_traits::ROWS_PER_CTA;+ launch_params.elts_per_thread = (launch_params.params.rows + rows_per_loop - 1) / rows_per_loop * Kernel_traits::LDGS * Kernel_traits::NUM_ELTS;+ launch_params.barrier_size = 0;+ launch_params.workspace_bytes = 0;+ if(Kernel_traits::CTAS_PER_ROW > 1) {+ launch_params.barrier_size = 2 * launch_params.params.ctas_per_col;+ launch_params.workspace_bytes = launch_params.params.ctas_per_col+ * Kernel_traits::WARPS_M+ * Kernel_traits::CTAS_PER_ROW+ * sizeof(typename Kernel_traits::Stats::stats_t)+ * 2;+ }+ return;+ }++ if( Kernel_traits::SMEM_BYTES_FWD >= 48 * 1024 ) {+ status = check_cuda_(+ cudaFuncSetAttribute(kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, Kernel_traits::SMEM_BYTES_FWD),+ __FILE__,+ __LINE__);+ if( status != cudaSuccess ) {+ return;+ }+ }+ auto stream = launch_params.stream;+ auto ctas_per_col = launch_params.params.ctas_per_col;++ if( Kernel_traits::CTAS_PER_ROW == 1 ) {+ kernel<<<ctas_per_col, Kernel_traits::THREADS_PER_CTA, Kernel_traits::SMEM_BYTES_FWD, stream>>>(launch_params.params);+ } else {+ dim3 grid(Kernel_traits::CTAS_PER_ROW * ctas_per_col);+ dim3 block(Kernel_traits::THREADS_PER_CTA);+ void *params_ = (void *)&launch_params.params;+ status = check_cuda_(+ cudaLaunchCooperativeKernel((void *)kernel, grid, block, (void **)¶ms_, Kernel_traits::SMEM_BYTES_FWD, stream),+ __FILE__,+ __LINE__);+ return;+ }+ status = cudaGetLastError();+ });+ });+ });+ });+ return status;+}diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_kernel_traits.h b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_kernel_traits.hnew file mode 100644index 000000000..1006f8af3--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_kernel_traits.h@@ -0,0 +1,172 @@+#pragma once++////////////////////////////////////////////////////////////////////////////////////////////////////++namespace layer_norm {+template<+ uint32_t HIDDEN_SIZE_,+ typename weight_t_,+ typename input_t_,+ typename residual_t_,+ typename output_t_,+ typename compute_t_,+ typename index_t_,+ uint32_t THREADS_PER_CTA_+>+struct Kernel_traits_base {++ using weight_t = weight_t_;+ using input_t = input_t_;+ using residual_t = residual_t_;+ using output_t = output_t_;+ using compute_t = compute_t_;+ using index_t = index_t_;++ enum { HIDDEN_SIZE = HIDDEN_SIZE_ };+ enum { THREADS_PER_CTA = THREADS_PER_CTA_ };+ enum { THREADS_PER_WARP = 32 };++};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<+ uint32_t HIDDEN_SIZE_,+ typename weight_t_,+ typename input_t_,+ typename residual_t_,+ typename output_t_,+ typename compute_t_,+ typename index_t_,+ bool Has_colscale,+ uint32_t THREADS_PER_CTA_,+ uint32_t BYTES_PER_LDG_,+ typename Base = Kernel_traits_base<HIDDEN_SIZE_,+ weight_t_,+ input_t_,+ residual_t_,+ output_t_,+ compute_t_,+ index_t_,+ THREADS_PER_CTA_>+>+struct Kernel_traits_finalize : public Base {+ enum { ROWS_PER_CTA = Base::THREADS_PER_CTA / Base::THREADS_PER_WARP };+ static_assert((int) ROWS_PER_CTA <= (int) Base::THREADS_PER_WARP);+ // Bytes per global load from the input.+ enum { BYTES_PER_LDG = BYTES_PER_LDG_ };+ // Number of elements fetched by a global load.+ enum { ELTS_PER_LDG = BYTES_PER_LDG / sizeof(compute_t_) };+ // Bytes per global store of the weights.+ enum { BYTES_PER_STG = ELTS_PER_LDG * sizeof(weight_t_) };+ static_assert(sizeof(BYTES_PER_LDG) == 4, "Conflict-free smem transpose only implemented for 4B compute type!");+ static_assert(Base::THREADS_PER_CTA == ROWS_PER_CTA * Base::THREADS_PER_WARP, "We assume one warp per row!");+ // The total number of BYTES_PER_LDG-wide words in a hidden vector.+ enum { COLS = HIDDEN_SIZE_ * sizeof(compute_t_) / BYTES_PER_LDG };+ static_assert(COLS * BYTES_PER_LDG == HIDDEN_SIZE_ * sizeof(compute_t_));++ // Shared memory size to transpose the CTA result.+ enum { SMEM_BYTES_TRANSPOSE = Base::THREADS_PER_CTA * BYTES_PER_LDG };+ // Shared memory size to coalsece the CTA result.+ enum { SMEM_BYTES_OUTPUT = Base::THREADS_PER_WARP * BYTES_PER_LDG };+ // Shared memory requirement per CTA.+ static constexpr int NUM_FACTORS = Has_colscale ? 3 : 2;+ enum { SMEM_BYTES_PER_CTA = NUM_FACTORS * SMEM_BYTES_TRANSPOSE + NUM_FACTORS * SMEM_BYTES_OUTPUT };++ // The type of the reducer.+ using Reducer = layer_norm::Reducer<compute_t_, 1, 1, 1>;++ // Condition for the whole CTA to participate in syncthreads.+ static_assert(COLS % Base::THREADS_PER_WARP == 0);+ enum { CTAS = COLS / Base::THREADS_PER_WARP };+};++////////////////////////////////////////////////////////////////////////////////////////////////////+++template<+ typename weight_t_,+ typename input_t_,+ typename residual_t_,+ typename output_t_,+ typename compute_t_,+ typename index_t_,+ uint32_t HIDDEN_SIZE_,+ uint32_t CTAS_PER_ROW_,+ uint32_t WARPS_M_,+ uint32_t WARPS_N_,+ uint32_t BYTES_PER_LDG_ = 16,+ typename Base = Kernel_traits_base<+ HIDDEN_SIZE_,+ weight_t_,+ input_t_,+ residual_t_,+ output_t_,+ compute_t_,+ index_t_,+ WARPS_M_*WARPS_N_*THREADS_PER_WARP+ >+>+struct Kernel_traits : public Base {++ using input_t = typename Base::input_t;+ using residual_t = typename Base::residual_t;+ using weight_t = typename Base::weight_t;+ using compute_t = typename Base::compute_t;+ using output_t = typename Base::output_t;+ using index_t = typename Base::index_t;+ // using mask_t = unsigned char;+ using mask_t = bool;++ enum { CTAS_PER_ROW = CTAS_PER_ROW_ };+ enum { WARPS_M = WARPS_M_ };+ enum { WARPS_N = WARPS_N_ };+ enum { COLS = HIDDEN_SIZE_ };+ enum { HIDDEN_SIZE = HIDDEN_SIZE_ };+ enum { BYTES_PER_LDG = BYTES_PER_LDG_ };+ enum { NUM_ELTS = BYTES_PER_LDG / sizeof(input_t) };++ enum { THREADS_PER_ROW = WARPS_N * THREADS_PER_WARP };+ enum { THREADS_PER_CTA = WARPS_M * THREADS_PER_ROW };+ enum { ROWS_PER_CTA = WARPS_M };++ enum { BYTES_PER_ROW = COLS * sizeof(input_t) };+ enum { BYTES_PER_ROW_PER_CTA = THREADS_PER_ROW * BYTES_PER_LDG };+ // Multi-row per CTA not supported for multi-CTA => no smem for WGRAD needed+ enum { SMEM_BYTES_WGRAD = CTAS_PER_ROW > 1 ? 0 : ROWS_PER_CTA * COLS * sizeof(compute_t) };+ static_assert(WARPS_M == 1 || CTAS_PER_ROW == 1);++ using reduce_t = typename layer_norm::TypeToVec2<compute_t>::Type;+ using Reducer = layer_norm::Reducer<reduce_t, CTAS_PER_ROW, WARPS_M, WARPS_N>;++ enum { SMEM_BYTES_DGRAD = Reducer::SMEM_BYTES };+ enum { SMEM_BYTES = SMEM_BYTES_DGRAD + SMEM_BYTES_WGRAD };++ using Ivec = layer_norm::Vec<input_t, NUM_ELTS>;+ using Rvec = layer_norm::Vec<residual_t, NUM_ELTS>;+ using Ovec = layer_norm::Vec<output_t, NUM_ELTS>;+ using Wvec = layer_norm::Vec<weight_t, NUM_ELTS>;+ using Cvec = layer_norm::Vec<compute_t, NUM_ELTS>;+ using Mvec = layer_norm::Vec<mask_t, NUM_ELTS>;+ enum { ELTS_PER_LDG = BYTES_PER_LDG / sizeof(input_t) };++ // Assume that each thread can handle the same number of elements in the output and weights as in the input.+ static_assert(sizeof(input_t) == sizeof(output_t));+ static_assert(sizeof(input_t) <= sizeof(residual_t));+ // The number of columns fetched per load from input: one per thread.+ enum { VEC_COLS_PER_LDG = CTAS_PER_ROW * THREADS_PER_ROW };+ // The total number of vectorized loads/stores per hidden vector.+ enum { VEC_COLS = COLS / ELTS_PER_LDG };+ // The number of loads per thread for the input.+ enum { LDGS = VEC_COLS / VEC_COLS_PER_LDG };+ static_assert(LDGS * VEC_COLS_PER_LDG == VEC_COLS);+ //static_assert(LDGS * BYTES_PER_ROW_PER_CTA * CTAS_PER_ROW == BYTES_PER_ROW, "");++ using Stats = layer_norm::Stats<compute_t, CTAS_PER_ROW, WARPS_M, WARPS_N>;+ enum { SMEM_BYTES_FWD = Stats::SMEM_BYTES };++};++////////////////////////////////////////////////////////////////////////////////////////////////////++} // namespace layer_normdiff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_utils.cuh b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_utils.cuhnew file mode 100644index 000000000..2fa9a40ee--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/ln_utils.cuh@@ -0,0 +1,733 @@+#pragma once++#include <cassert>++#include <cuda_bf16.h>+#include <cuda_fp16.h>++#include "ln.h"++////////////////////////////////////////////////////////////////////////////////////////////////////++constexpr uint32_t THREADS_PER_WARP = 32;++////////////////////////////////////////////////////////////////////////////////////////////////////++inline cudaError_t check_cuda_(cudaError_t status, const char *file, int line) {+ if( status != cudaSuccess ) {+ fprintf(stderr, "CUDA Error: %s %s %d\n", cudaGetErrorString(status), file, line);+ }+ return status;+}++////////////////////////////////////////////////////////////////////////////////////////////////////++#define CHECK_CUDA(ans) \+ { \+ cudaError_t status_ = check_cuda_((ans), __FILE__, __LINE__); \+ if (status_ != cudaSuccess) { \+ return status_; \+ } \+ }++////////////////////////////////////////////////////////////////////////////////////////////////////++#define DIVUP(x, y) (((x) + ((y)-1)) / (y))++////////////////////////////////////////////////////////////////////////////////////////////////////++#define REGISTER_FWD_LAUNCHER(HIDDEN_SIZE, WTYPE, ITYPE, RTYPE, OTYPE, CTYPE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG) \+ cudaError_t ln_fwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##RTYPE##_##OTYPE##_##CTYPE(LaunchParams<FwdParams> &launch_params, \+ const bool configure_params) { \+ return launch_<WTYPE, ITYPE, RTYPE, OTYPE, CTYPE, uint32_t, HIDDEN_SIZE, CTAS_PER_ROW, WARPS_M, WARPS_N, BYTES_PER_LDG>( \+ launch_params, configure_params); \+ } \+ static FwdRegistrar<WTYPE, ITYPE, RTYPE, OTYPE, CTYPE, HIDDEN_SIZE> reg_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##RTYPE##_##OTYPE##_##CTYPE( \+ ln_fwd_##HIDDEN_SIZE##_##WTYPE##_##ITYPE##_##RTYPE##_##OTYPE##_##CTYPE)++////////////////////////////////////////////////////////////////////////////////////////////////////++inline __device__ float2 operator+(const float2 & a, const float2 & b){+ return {a.x + b.x, a.y + b.y};+}++////////////////////////////////////////////////////////////////////////////////////////////////////++inline __device__ void operator+=(float2 & a, const float2 & b){+ a.x += b.x;+ a.y += b.y;+}++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+struct Sum {+ inline __device__ Sum(){}+ inline __device__ T operator()(const T &a, const T &b){+ return a + b;+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+inline __device__ T warp_shuffle_xor(const T & x, uint32_t idx){+ return __shfl_xor_sync(uint32_t(-1), x, idx);+}++template<>+inline __device__ float2 warp_shuffle_xor<float2>(const float2 & x, uint32_t idx){+ return { warp_shuffle_xor(x.x, idx), warp_shuffle_xor(x.y, idx) };+}++template<typename T>+inline __device__ T warp_shuffle_down(const T & x, uint32_t idx){+ return __shfl_down_sync(uint32_t(-1), x, idx);+}++template<>+inline __device__ float2 warp_shuffle_down<float2>(const float2 & x, uint32_t idx){+ return { warp_shuffle_down(x.x, idx), warp_shuffle_down(x.y, idx) };+}++////////////////////////////////////////////////////////////////////////////////////////////////////++namespace layer_norm {++////////////////////////////////////////////////////////////////////////////////////////////////////++struct uint16 {+ uint4 u;+ uint4 v;+ uint4 s;+ uint4 t;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++struct uint8 {+ uint4 u;+ uint4 v;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<int BYTES>+struct BytesToType {};++template<>+struct BytesToType<64> {+ using Type = uint16;+ static_assert(sizeof(Type) == 64);+};++template<>+struct BytesToType<32> {+ using Type = uint8;+ static_assert(sizeof(Type) == 32);+};++template<>+struct BytesToType<16> {+ using Type = uint4;+ static_assert(sizeof(Type) == 16);+};++template<>+struct BytesToType<8> {+ using Type = uint64_t;+ static_assert(sizeof(Type) == 8);+};++template<>+struct BytesToType<4> {+ using Type = uint32_t;+ static_assert(sizeof(Type) == 4);+};++template<>+struct BytesToType<2> {+ using Type = uint16_t;+ static_assert(sizeof(Type) == 2);+};++template<>+struct BytesToType<1> {+ using Type = uint8_t;+ static_assert(sizeof(Type) == 1);+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+struct TypeToVec2 {};++template<>+struct TypeToVec2<float> {+ using Type = float2;+};++template<>+struct TypeToVec2<half> {+ using Type = half2;+};++template<>+struct TypeToVec2<nv_bfloat16> {+ using Type = nv_bfloat162;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<int INDEX>+struct Get {+ template<typename T, typename R>+ static inline __device__ R of(const T &vec);+};++template<>+template<typename T, typename R>+inline __device__ R Get<0>::of(const T &vec) {+ return vec.x;+}++template<>+template<typename T, typename R>+inline __device__ R Get<1>::of(const T &vec) {+ return vec.y;+}++template<>+template<typename T, typename R>+inline __device__ R Get<2>::of(const T &vec) {+ return vec.z;+}++template<>+template<typename T, typename R>+inline __device__ R Get<3>::of(const T &vec) {+ return vec.w;+}++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename Src, typename Dst>+struct Converter{+ static inline __device__ Dst convert(const Src &from) {+ return Dst(from);+ }+};++template<>+struct Converter<float2, half2>{+ static inline __device__ half2 convert(const float2 &x) {+ return __float22half2_rn(x);+ }+};++template<>+struct Converter<float2, nv_bfloat162>{+ static inline __device__ nv_bfloat162 convert(const float2 &x) {+#if __CUDA_ARCH__ >= 800+ return __float22bfloat162_rn(x);+#else+ union {+ nv_bfloat162 raw;+ nv_bfloat16 x;+ nv_bfloat16 y;+ } tmp;+ tmp.x = __float2bfloat16_rn(x.x);+ tmp.y = __float2bfloat16_rn(x.y);+ return tmp.raw;+#endif+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T>+struct Zeros{+ static inline __device__ T get() {+ return T(0.f);+ }+};++template<>+struct Zeros<float2>{+ static inline __device__ float2 get() {+ return make_float2(0.f, 0.f);+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename Elt_type, uint32_t NUM_ELT>+struct Vec {++ enum { BYTES = NUM_ELT * sizeof(Elt_type) };++ using Vec_type = typename BytesToType<BYTES>::Type;++ using Alias_type = union {+ Vec_type vec;+ Elt_type elt[NUM_ELT];+ };++ Alias_type data;++ template<typename S>+ inline __device__ void to(Vec<S, NUM_ELT> &other) {+ #pragma unroll+ for( int it = 0; it < NUM_ELT; it++ ) {+ other.data.elt[it] = S(this->data.elt[it]);+ }+ }++ template<typename Op>+ inline __device__ void assign(const Op &op) {+ #pragma unroll+ for( int it = 0; it < NUM_ELT; it++ ) {+ this->data.elt[it] = op(it);+ }+ }++ inline __device__ void zero_() {+ #pragma unroll+ for( int it = 0; it < NUM_ELT; it++ ) {+ this->data.elt[it] = Elt_type(0.f);+ }+ }++ inline __device__ void load_from(const void *base_ptr, const size_t idx) {+ this->data.vec = static_cast<const Vec_type *>(base_ptr)[idx];+ }++ inline __device__ void store_to(void *base_ptr, const size_t idx) {+ static_cast<Vec_type *>(base_ptr)[idx] = this->data.vec;+ }+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<uint32_t CTAS_PER_ROW>+struct InterCTASync {++ template<typename Params>+ inline __device__ InterCTASync(Params & params, uint32_t bidm, uint32_t bidn)+ : phase_counter_(0)+ , b0_(params.barrier + bidm) // The barrier for this group of CTAs.+ , b1_(params.barrier + bidm + params.ctas_per_col) // The barrier for this group of CTAs.+ {+ // BARRIERS ARE ASSUMED TO BE INITIALIZED TO 0!+ }++ inline __device__ void spin_wait_(int *barrier, int step, int expected) {+ asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(barrier), "r"(step));+ for( int found = -1; found != expected; ) {+ asm volatile("ld.global.acquire.gpu.b32 %0, [%1];" : "=r"(found) : "l"(barrier));+ }+ }++ inline __device__ void sync(){+ // ALL THREADS MUST ENTER!++ // We switch barrier every iteration.+ int *barrier = phase_counter_ & 0x1 ? b1_ : b0_;+ // We decrement every other iteration.+ bool dec = phase_counter_ & 0x2;+ int step = dec ? -1 : 1;+ int expected = dec ? 0 : CTAS_PER_ROW;+ // There are only 4 phases: up/down for b0/b1.+ phase_counter_ = (phase_counter_ + 1) & 0x3;++ if( threadIdx.x == 0 ) {+ spin_wait_(barrier, step, expected);+ }+ // CTA waits for thread 0+ __syncthreads();+ }++ int phase_counter_;+ int * b0_;+ int * b1_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N>+struct Reducer : public Reducer<T, 1, WARPS_M, WARPS_N> {++ using InterCTASync = InterCTASync<CTAS_PER_ROW>;+ using Base = Reducer<T, 1, WARPS_M, WARPS_N>;+ using Type = typename Base::Type;++ enum { SMEM_BYTES = Base::SMEM_BYTES };++ enum { WS_BARRIER_BYTES = 2 * sizeof(int) };+ enum { WS_DATA_BYTES = WARPS_M * CTAS_PER_ROW * sizeof(T) };++ // size of the barriers + temporary result per CTA (multiply with CTAS_PER_ROW to get total)+ enum { WORKSPACE_BYTES_PER_GROUP = Base::WORKSPACE_BYTES_PER_GROUP + WS_BARRIER_BYTES + WS_DATA_BYTES };++ template<typename Params>+ inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : Base(params, bidm, bidn, warp_m, warp_n, lane, smem)+ , inter_cta_(params, bidm, bidn)+ , bidn_(bidn) // CTA id within the group.+ , w0_(static_cast<T*>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW)+ , w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW)+ {+ }++ template<typename Op>+ inline __device__ T allreduce(T data, Op &op) {+ data = Base::reduce(data, op);+ // We switch workspace every iteration.+ T *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_;++ // Warp leaders 0 hold the CTA-local results.+ if( this->warp_n_ == 0 && this->lane_ == 0 ) {+ workspace[bidn_] = data;+ }+ inter_cta_.sync();+ static_assert(CTAS_PER_ROW <= 32);+ T total = Zeros<T>::get();+ if(this->lane_ < CTAS_PER_ROW){+ total = workspace[this->lane_];+ }+ total = Reducer<T, 1, 1, 1>::allreduce_(total, op);++ return total;+ }++ InterCTASync inter_cta_;++ T *w0_;+ T *w1_;+ int bidn_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t WARPS_M>+struct Reducer<T, 1, WARPS_M, 1> {++ using Type = T;+ enum { SMEM_BYTES = 0 };+ enum { WORKSPACE_BYTES_PER_GROUP = 0 };++ enum { THREADS_PER_WARP = 32 };++ template<typename Params>+ inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : warp_n_(warp_n)+ , lane_(lane)+ {+ }++ template<typename Op>+ static inline __device__ T allreduce_(T data, Op &op) {+ #pragma unroll+ for( int it = 1; it < THREADS_PER_WARP; it *= 2 ) {+ data = op(data, warp_shuffle_xor(data, it));+ }+ return data;+ }++ template<typename Op>+ inline __device__ T allreduce(T data, Op &op) {+ return allreduce_(data, op);+ }++ template<typename Op>+ inline __device__ T reduce(T data, Op &op){+ // only lane 0 holds the result!+ #pragma unroll+ for( int it = THREADS_PER_WARP / 2; it > 0; it /= 2 ) {+ data = op(data, warp_shuffle_down(data, it));+ }+ return data;+ }+ int warp_n_;+ int lane_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t WARPS_M, uint32_t WARPS_N>+struct Reducer<T, 1, WARPS_M, WARPS_N> : public Reducer<T, 1, WARPS_M, 1> {++ using Base = Reducer<T, 1, WARPS_M, 1>;++ using Type = T;++ enum { SMEM_BYTES = Base::SMEM_BYTES + WARPS_M * WARPS_N * sizeof(T) * 2 };+ enum { WORKSPACE_BYTES_PER_GROUP = 0 };++ enum { THREADS_PER_WARP = 32 };++ template<typename Params>+ inline __device__ Reducer(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : Base(params, bidm, bidn, warp_m, warp_n, lane, smem)+ , use0_(true)+ {+ smem0_ = &static_cast<T *>(smem)[warp_m * WARPS_N];+ smem1_ = smem0_ + WARPS_M * WARPS_N;+ }++ template<typename Op>+ inline __device__ T allreduce(T data, Op & op) {+ T * smem = use0_ ? smem0_ : smem1_;+ use0_ = !use0_;+ data = Base::reduce(data, op);+ if( this->lane_ == 0 ) {+ smem[this->warp_n_] = data;+ }+ __syncthreads();+ T out = Zeros<T>::get();+ #pragma unroll+ for( int it = 0; it < WARPS_N; it++ ) {+ out = op(out, smem[it]);+ }+ return out;+ }++ template<typename Op>+ inline __device__ T reduce(T data, Op &op) {+ T * smem = use0_ ? smem0_ : smem1_;+ use0_ = !use0_;+ // only intra-CTA group leader holds the result!+ data = Base::reduce(data, op);+ if( this->lane_ == 0 ) {+ smem[this->warp_n_] = data;+ }+ __syncthreads();+ T out = Zeros<T>::get();+ if( this->warp_n_ == 0 && this->lane_ == 0 ) {+ #pragma unroll+ for( int it = 0; it < WARPS_N; it++ ) {+ out = op(out, smem[it]);+ }+ }+ return out;+ }++ T * smem0_;+ T * smem1_;+ bool use0_;++};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, typename int_t>+inline __device__ void warp_chan_upd_dynamic(T &m_a, T &m2_a, int_t &n_a, int num_active){+ //Assume at least leftmost is valid and init: step = next_pow2(num_active) / 2 (might get NaN otherwise)+ const int highest_bit_set = (8 * sizeof(num_active)) - __clz(num_active - 1);++ #pragma unroll+ for( int step = (1 << (highest_bit_set - 1)); step > 0; step /= 2 ) {+ // Exchange+ int_t n_b = warp_shuffle_down(n_a, step);+ T m_b = warp_shuffle_down(m_a, step);+ T m2_b = warp_shuffle_down(m2_a, step);++ // Update+ const int_t n_ab = n_a + n_b; // We can handle one of them being 0, not both.+ const T rn_ab = 1.f / n_ab; // Might have different n per thread, otherwise this would simplify :(+ const T delta = m_a - m_b;+ const float m2_ab = m2_a + m2_b + delta * delta * n_a * n_b * rn_ab;+ const float m_ab = (n_a * m_a + n_b * m_b) * rn_ab;++ n_a = n_ab;+ m_a = m_ab;+ m2_a = m2_ab;+ }+ // Intra-warp broadcast (only lane 0 has valid stats).+ m_a = __shfl_sync(uint32_t(-1), m_a, 0);+ m2_a = __shfl_sync(uint32_t(-1), m2_a, 0);+}++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t CTAS_PER_ROW, uint32_t WARPS_M, uint32_t WARPS_N>+struct Stats {+ // This could be done generically with the Reducer. But then we would have to exchange 3 instead of 2 fields.++ using InterCTASync = InterCTASync<CTAS_PER_ROW>;+ using BlockStats = Stats<T, 1, WARPS_M, WARPS_N>;+ using stats_t = typename BlockStats::stats_t;++ enum { SMEM_BYTES = BlockStats::SMEM_BYTES };++ template<typename Params>+ inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : inter_cta_(params, bidm, bidn)+ , block_stats_(params, bidm, bidn, warp_m, warp_n, lane, smem)+ , bidn_(bidn) // CTA id within the group.+ , w0_(static_cast<stats_t*>(params.workspace) + (bidm * WARPS_M + warp_m) * CTAS_PER_ROW)+ , w1_(w0_ + params.ctas_per_col * WARPS_M * CTAS_PER_ROW)+ , warp_n_(warp_n)+ , lane_(lane)+ {+ }++ template<uint32_t N>+ inline __device__ stats_t compute(const T (&elts)[N], const T rn) {+ constexpr T ELTS_PER_ROW_PER_CTA = N * WARPS_N * THREADS_PER_WARP;+ // TODO rn is not really needed here..+ constexpr T block_rn = 1.f / T(ELTS_PER_ROW_PER_CTA);+ stats_t block_stats = block_stats_.compute(elts, block_rn);++ stats_t *workspace = inter_cta_.phase_counter_ & 0x1 ? w1_ : w0_;++ if( warp_n_ == 0 && lane_ == 0 ) {+ workspace[bidn_] = block_stats;+ }++ // Wait for all CTAS_PER_ROW CTAS in the group to have written their result.+ inter_cta_.sync();++ T n = Zeros<T>::get();+ T m = Zeros<T>::get();+ T m2 = Zeros<T>::get();++ // Assume CTA group size in N less than 32, such that we can finalize with a single warp.+ static_assert(CTAS_PER_ROW <= 32);++ // Every warp does the final reduction locally.+ if( lane_ < CTAS_PER_ROW ) {+ stats_t result = workspace[lane_];+ n = ELTS_PER_ROW_PER_CTA;+ m = layer_norm::Get<0>::of<stats_t, T>(result);+ m2 = layer_norm::Get<1>::of<stats_t, T>(result);+ }++ warp_chan_upd_dynamic(m, m2, n, CTAS_PER_ROW);++ return { m, m2 };+ }++ InterCTASync inter_cta_;+ BlockStats block_stats_;++ stats_t *w0_;+ stats_t *w1_;+ int bidn_;+ int warp_n_;+ int lane_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t WARPS_M, uint32_t WARPS_N>+struct Stats<T, 1, WARPS_M, WARPS_N> {++ using WarpStats = Stats<T, 1, WARPS_M, 1>;+ using stats_t = typename WarpStats::stats_t;++ enum { SMEM_BYTES = WARPS_M * WARPS_N * sizeof(stats_t) * 2 };++ template<typename Params>+ inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : warp_stats_(params, bidm, bidn, warp_m, warp_n, lane, smem)+ , use0_(true)+ {+ smem0_ = static_cast<stats_t*>(smem) + warp_m * WARPS_N;+ smem1_ = smem0_ + WARPS_M * WARPS_N;+ }++ template<bool Is_even_cols, uint32_t N, typename function_t>+ inline __device__ stats_t compute(const T (&elts)[N], const T row_norm_factor,+ function_t valid_elts_in_warp_fn, const int num_valid_elts = N) {+ stats_t * smem = use0_ ? smem0_ : smem1_;+ use0_ = !use0_;+ // Compute warp local for all WARPS_N+ const auto warp_n = warp_stats_.reducer_.warp_n_;+ const T warp_norm_factor = 1.f / T(Is_even_cols ? N * THREADS_PER_WARP : valid_elts_in_warp_fn(warp_n));+ stats_t warp_stats = warp_stats_.template compute<Is_even_cols>(+ elts, warp_norm_factor, valid_elts_in_warp_fn, num_valid_elts+ );++ //Each warp warp leader stores its stats+ const auto lane = warp_stats_.reducer_.lane_;+ if( lane == 0 ) {+ smem[warp_n] = warp_stats;+ }+ __syncthreads();++ int n = 0;;+ T m = Zeros<T>::get();+ T m2 = Zeros<T>::get();++ // Assume that there are less than 32 warps, such that we can finalize with a single warp+ static_assert(WARPS_N <= 32);+ if(lane < WARPS_N){+ stats_t result = smem[lane];+ n = Is_even_cols ? N * THREADS_PER_WARP : valid_elts_in_warp_fn(lane);+ m = layer_norm::Get<0>::of<stats_t, T>(result);+ m2 = layer_norm::Get<1>::of<stats_t, T>(result);+ }++ warp_chan_upd_dynamic(m, m2, n, WARPS_N);++ return { m, m2 };+ }+ WarpStats warp_stats_;+ stats_t * smem0_;+ stats_t * smem1_;+ bool use0_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++template<typename T, uint32_t WARPS_M>+struct Stats<T, 1, WARPS_M, 1> {++ using stats_t = typename TypeToVec2<T>::Type;+ // The simple Warp reducer.+ using Reducer = Reducer<T, 1, WARPS_M, 1>;++ enum { SMEM_BYTES = 0 };++ template<typename Params>+ inline __device__ Stats(Params & params, uint32_t bidm, uint32_t bidn, uint32_t warp_m, uint32_t warp_n, uint32_t lane, void * smem)+ : reducer_(params, bidm, bidn, warp_m, warp_n, lane, smem)+ {+ }++ template<bool Is_even_cols, uint32_t N, typename function_t>+ inline __device__ stats_t compute(const T (&elts)[N], const T row_norm_factor,+ // const int valid_elts_in_warp_ignored_, const int num_valid_elts = N) {+ function_t valid_elts_in_warp_fn, const int num_valid_elts = N) {++ auto sum = Sum<T>();++ T m = Zeros<T>::get();+ #pragma unroll+ for( int it = 0; it < N; it++ ) {+ if (Is_even_cols || (it < num_valid_elts)) {+ m += elts[it];+ }+ }+ m = reducer_.allreduce(m, sum) * row_norm_factor;++ T m2 = Zeros<T>::get();+ #pragma unroll+ for( int it = 0; it < N; it++ ) {+ if (Is_even_cols || (it < num_valid_elts)) {+ T diff = (elts[it] - m);+ m2 += diff * diff;+ }+ }+ m2 = reducer_.allreduce(m2, sum);++ return {m, m2};+ }++ Reducer reducer_;+};++////////////////////////////////////////////////////////////////////////////////////////////////////++} // namespace layer_normdiff --git a/packages/sie_server_rust/vendor/candle-layer-norm/kernels/static_switch.h b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/static_switch.hnew file mode 100644index 000000000..7920ac045--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/kernels/static_switch.h@@ -0,0 +1,25 @@+// Inspired by https://github.com/NVIDIA/DALI/blob/main/include/dali/core/static_switch.h+// and https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Dispatch.h++#pragma once++/// @param COND - a boolean expression to switch by+/// @param CONST_NAME - a name given for the constexpr bool variable.+/// @param ... - code to execute for true and false+///+/// Usage:+/// ```+/// BOOL_SWITCH(flag, BoolConst, [&] {+/// some_function<BoolConst>(...);+/// });+/// ```+#define BOOL_SWITCH(COND, CONST_NAME, ...) \+ [&] { \+ if (COND) { \+ constexpr bool CONST_NAME = true; \+ return __VA_ARGS__(); \+ } else { \+ constexpr bool CONST_NAME = false; \+ return __VA_ARGS__(); \+ } \+ }()diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/src/ffi.rs b/packages/sie_server_rust/vendor/candle-layer-norm/src/ffi.rsnew file mode 100644index 000000000..445015288--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/src/ffi.rs@@ -0,0 +1,30 @@+use core::ffi::{c_int, c_void};++extern "C" {+ pub(crate) fn run_ln(+ x: *const c_void,+ residual: *const c_void,+ gamma: *const c_void,+ beta: *const c_void,+ dst_add: *mut c_void,+ dst: *mut c_void,+ mu: *mut c_void,+ rsigma: *mut c_void,++ epsilon: f32,++ hidden_size_rounded: u32,+ rows: u32,+ cols: u32,+ multi_processor_count: i32,++ wtype: u32,+ itype: u32,+ rtype: u32,+ otype: u32,+ ctype: u32,++ is_rms_norm: c_int,+ stream: *mut c_void,+ ) -> c_int;+}diff --git a/packages/sie_server_rust/vendor/candle-layer-norm/src/lib.rs b/packages/sie_server_rust/vendor/candle-layer-norm/src/lib.rsnew file mode 100644index 000000000..b21a2e4c3--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-layer-norm/src/lib.rs@@ -0,0 +1,611 @@+mod ffi;++use candle::backend::BackendStorage;+use candle::cuda_backend::cudarc::driver::sys::CUdevice_attribute::CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT;+use candle::cuda_backend::cudarc::driver::DevicePtrMut;+use candle::cuda_backend::WrapErr;+use candle::{CpuStorage, DType, Layout, Result, Shape, Storage, Tensor};+use half::{bf16, f16};+use std::ptr;++fn layer_norm_internal_type(dtype: DType) -> Result<u32> {+ let internal_type = match dtype {+ DType::F16 => 0,+ DType::BF16 => 1,+ DType::F32 => 2,+ dtype => candle::bail!("dtype {dtype:?} is not supported"),+ };+ Ok(internal_type)+}++pub struct LayerNorm {+ pub epsilon: f32,+ pub is_rms_norm: bool,+ pub output_only: bool,+ pub gamma: Tensor,+ pub beta: Option<Tensor>,+}++fn round_multiple(x: usize, m: usize) -> usize {+ (x + m - 1) / m * m+}++impl LayerNorm {+ fn fwd<+ T: candle::cuda_backend::CudaDType + candle::cuda_backend::cudarc::driver::DeviceRepr,+ >(+ &self,+ x: &candle::CudaStorage,+ x_l: &Layout,+ r: Option<&candle::CudaStorage>,+ r_l: Option<&Layout>,+ ) -> Result<(candle::CudaStorage, Shape)> {+ // Assume all tensors are on the same device and take device of x+ let dev = x.device();++ // Get internal layer norm type id for the given dtype+ let layer_norm_type = layer_norm_internal_type(x.dtype())?;++ // Make sure that gamma is a CUDA tensor and get the underlying storage+ let (g, g_l) = self.gamma.storage_and_layout();+ let g = match &*g {+ Storage::Cuda(g) => g,+ _ => candle::bail!("gamma must be a cuda tensor"),+ };++ // Get cuda slices for all tensors+ let x = x.as_cuda_slice::<T>()?;+ let g = g.as_cuda_slice::<T>()?;++ // Input matrix layout+ let (rows, cols) = x_l.shape().dims2()?;++ if !(cols % 8 == 0 && cols <= 8192) {+ candle::bail!("hidden size must be % 8 and <= 8192")+ }+ if g_l.shape().elem_count() != cols {+ candle::bail!("gamma length must match hidden size {cols}")+ }++ let x_stride = x_l.stride();+ let g_stride = g_l.stride();++ let x_rank = x_stride.len();+ let g_rank = g_stride.len();++ if x_rank != 2 {+ candle::bail!("layer-norm expects input tensors of rank 2. Found: {x_rank}")+ }+ if g_rank == 0 {+ candle::bail!("gamma must have at least one dimension")+ }+ if x_stride[x_rank - 1] != 1 {+ candle::bail!("the last dim of x must be contiguous {x_stride:?}")+ }+ if g_stride[g_rank - 1] != 1 {+ candle::bail!("the last dim of g must be contiguous {g_stride:?}")+ }++ // Get cuda views for all tensors+ let x = x.slice(x_l.start_offset()..);+ let g = g.slice(g_l.start_offset()..);++ // Round cols to match with the correct kernel+ let cols_rounded = if cols <= 1536 {+ round_multiple(cols, 256)+ } else if cols <= 3072 {+ round_multiple(cols, 512)+ } else {+ round_multiple(cols, 1024)+ };++ let is_rms_norm = if self.is_rms_norm { 1 } else { 0 };+ let stream = dev.cuda_stream();+ let beta_storage = self.beta.as_ref().map(Tensor::storage_and_layout);++ // If beta is et, get ids device pointer+ let (b_ptr, b_sync) = if let Some((b, b_l)) = beta_storage.as_ref() {+ // Make sure that beta is a CUDA tensor and get the underlying storage+ let b = match &**b {+ Storage::Cuda(b) => b,+ _ => candle::bail!("beta must be a cuda tensor"),+ };++ if b_l.shape().elem_count() != cols {+ candle::bail!("beta length must match hidden size {cols}")+ }+ let b = b.as_cuda_slice::<T>()?;+ let b = b.slice(b_l.start_offset()..);++ let b_stride = b_l.stride();+ let b_rank = b_stride.len();++ if b_rank == 0 {+ candle::bail!("beta must have at least one dimension")+ }+ if b_stride[b_rank - 1] != 1 {+ candle::bail!("the last dim of b must be contiguous {b_stride:?}")+ }+ let (b_ptr, b_sync) = b.view_ptr(&stream);+ (b_ptr as *const core::ffi::c_void, Some(b_sync))+ } else {+ (ptr::null() as *const std::ffi::c_void, None)+ };++ // If residual is set, get its device pointer+ let (r_ptr, r_sync) = if let (Some(r), Some(r_l)) = (r, r_l) {+ // Check shape+ let expected_shape = x_l.shape().dims2()?;+ if r_l.shape().dims2()? != expected_shape {+ candle::bail!("shape mismatch x {:?} and r {:?}", x_l.shape(), r_l.shape());+ }++ let r = r.as_cuda_slice::<T>()?;+ let r = r.slice(r_l.start_offset()..);++ let r_stride = r_l.stride();+ let r_rank = r_stride.len();++ if r_rank != 2 {+ candle::bail!("layer-norm expects input tensors of rank 2. Found: {r_rank}")+ }++ if r_stride[r_rank - 1] != 1 {+ candle::bail!("the last dim of r must be contiguous {r_stride:?}")+ }+ let (r_ptr, r_sync) = r.view_ptr(&stream);+ (r_ptr as *const std::ffi::c_void, Some(r_sync))+ } else {+ (ptr::null() as *const std::ffi::c_void, None)+ };++ let output_rows = if self.output_only { rows } else { rows * 2 };+ let out_shape = Shape::from((output_rows, cols));++ let mut out = unsafe { dev.alloc::<T>(out_shape.elem_count()) }?;+ let (mut dst, mut dst_add) = if self.output_only {+ (out.slice_mut(..rows * cols), None)+ } else {+ let (dst, dst_add) = out.split_at_mut(rows * cols);+ (dst, Some(dst_add))+ };++ // The output-only path does not expose the statistics, so avoid allocating them.+ let mut mu = if self.output_only {+ None+ } else {+ Some(unsafe { dev.alloc::<f32>(rows) }?)+ };+ let mut rsigma = if self.output_only {+ None+ } else {+ Some(unsafe { dev.alloc::<f32>(rows) }?)+ };++ // Get cuda device pointers from cuda slices+ let (x_ptr, x_sync) = x.view_ptr(&stream);+ let (g_ptr, g_sync) = g.view_ptr(&stream);+ let (dst_add_ptr, dst_add_sync) = if let Some(dst_add) = dst_add.as_mut() {+ let (dst_add_ptr, dst_add_sync) = dst_add.device_ptr_mut(&stream);+ (dst_add_ptr as *mut core::ffi::c_void, Some(dst_add_sync))+ } else {+ (ptr::null_mut(), None)+ };+ let (dst_ptr, dst_sync) = dst.device_ptr_mut(&stream);+ let (mu_ptr, mu_sync) = if let Some(mu) = mu.as_mut() {+ let (mu_ptr, mu_sync) = mu.device_ptr_mut(&stream);+ (mu_ptr as *mut core::ffi::c_void, Some(mu_sync))+ } else {+ (ptr::null_mut(), None)+ };+ let (rsigma_ptr, rsigma_sync) = if let Some(rsigma) = rsigma.as_mut() {+ let (rsigma_ptr, rsigma_sync) = rsigma.device_ptr_mut(&stream);+ (rsigma_ptr as *mut core::ffi::c_void, Some(rsigma_sync))+ } else {+ (ptr::null_mut(), None)+ };+ let x_ptr = x_ptr as *const core::ffi::c_void;+ let g_ptr = g_ptr as *const core::ffi::c_void;+ let dst_ptr = dst_ptr as *mut core::ffi::c_void;++ let multi_processors_count = stream+ .context()+ .attribute(CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT)+ .w()?;++ let status = unsafe {+ // Launch Kernel+ ffi::run_ln(+ x_ptr,+ r_ptr,+ g_ptr,+ b_ptr,+ dst_add_ptr,+ dst_ptr,+ mu_ptr,+ rsigma_ptr,+ self.epsilon,+ cols_rounded as u32,+ rows as u32,+ cols as u32,+ multi_processors_count,+ layer_norm_type,+ layer_norm_type,+ layer_norm_type,+ layer_norm_type,+ 2,+ is_rms_norm,+ stream.cu_stream().cast(),+ )+ };+ if status != 0 {+ candle::bail!("layer-norm CUDA kernel failed with status {status}");+ }+ drop((+ b_sync,+ r_sync,+ x_sync,+ g_sync,+ dst_add_sync,+ dst_sync,+ mu_sync,+ rsigma_sync,+ ));++ let out = candle::CudaStorage::wrap_cuda_slice(out, dev.clone());++ Ok((out, out_shape))+ }+}++impl candle::CustomOp1 for LayerNorm {+ fn name(&self) -> &'static str {+ "fused-layer-norm"+ }++ fn cpu_fwd(&self, _: &CpuStorage, _: &Layout) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for fused-layer-norm")+ }++ fn cuda_fwd(+ &self,+ x: &candle::CudaStorage,+ x_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match x.dtype() {+ DType::F16 => self.fwd::<f16>(x, x_l, None, None),+ DType::BF16 => self.fwd::<bf16>(x, x_l, None, None),+ DType::F32 => self.fwd::<f32>(x, x_l, None, None),+ dt => {+ candle::bail!("fused-layer-norm is only supported for f32, f16 and bf16 ({dt:?})")+ }+ }+ }+}++impl candle::CustomOp2 for LayerNorm {+ fn name(&self) -> &'static str {+ "fused-layer-norm"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("no cpu support for fused-layer-norm")+ }++ fn cuda_fwd(+ &self,+ x: &candle::CudaStorage,+ x_l: &Layout,+ r: &candle::CudaStorage,+ r_l: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ match x.dtype() {+ DType::F16 => self.fwd::<f16>(x, x_l, Some(r), Some(r_l)),+ DType::BF16 => self.fwd::<bf16>(x, x_l, Some(r), Some(r_l)),+ DType::F32 => self.fwd::<f32>(x, x_l, Some(r), Some(r_l)),+ dt => {+ candle::bail!("fused-layer-norm is only supported for f32, f16 and bf16 ({dt:?})")+ }+ }+ }+}++/// Layer Normalization Layer+///+/// # Arguments+///+/// * `x` - Input tensor of rank 2+/// * `gamma` - Channel scale+/// * `beta` - Channel bias+/// * `epsilon` - A value added to the denominator for numerical stability+///+/// The resulting tensor has the same dimensions as `x`+pub fn layer_norm(+ x: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f32,+) -> Result<Tensor> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: false,+ output_only: false,+ };+ let results = x.apply_op1(op)?;+ let rows = x.dims()[0];+ results.narrow(0, 0, rows)+}++/// Layer Normalization Layer that only returns the normalized output.+///+/// Unlike [`layer_norm`], this avoids allocating the unused residual-add and statistics buffers.+pub fn layer_norm_output_only(+ x: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f32,+) -> Result<Tensor> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: false,+ output_only: true,+ };+ x.apply_op1(op)+}++/// Fused Add Layer Normalization Layer+///+/// # Arguments+///+/// * `x` - Input tensor of rank 2+/// * `res` - Residual tensor of rank 2. Will be added to `x` before normalization. Must have+/// the same shape as `x`.+/// * `gamma` - Channel scale+/// * `beta` - Channel bias+/// * `epsilon` - A value added to the denominator for numerical stability+///+/// The resulting tensors have the same dimensions as `x`+/// First tensor is the result of the normalization, second is the result of the residual add+pub fn fused_add_layer_norm(+ x: &Tensor,+ res: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f32,+) -> Result<(Tensor, Tensor)> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: false,+ output_only: false,+ };+ let results = x.apply_op2(&res, op)?;+ let rows = x.dims()[0];+ Ok((results.narrow(0, 0, rows)?, results.narrow(0, rows, rows)?))+}++/// Fused Add Layer Normalization Layer that only returns the normalized output.+///+/// The residual is still added before normalization, but the intermediate sum is not stored.+pub fn fused_add_layer_norm_output_only(+ x: &Tensor,+ res: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f32,+) -> Result<Tensor> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: false,+ output_only: true,+ };+ x.apply_op2(res, op)+}++/// Layer RMS Normalization Layer+///+/// # Arguments+///+/// * `x` - Input tensor of rank 2+/// * `gamma` - Channel scale+/// * `beta` - Channel bias+/// * `epsilon` - A value added to the denominator for numerical stability+///+/// The resulting tensor has the same dimensions as `x`+pub fn rms_norm(x: &Tensor, gamma: &Tensor, beta: Option<&Tensor>, epsilon: f32) -> Result<Tensor> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: true,+ output_only: false,+ };+ let results = x.apply_op1(op)?;+ let rows = x.dims()[0];+ results.narrow(0, 0, rows)+}++/// Fused Add RMS Normalization Layer+///+/// # Arguments+///+/// * `x` - Input tensor of rank 2+/// * `res` - Residual tensor of rank 2. Will be added to `x` before normalization. Must have+/// the same shape as `x`.+/// * `gamma` - Channel scale+/// * `beta` - Channel bias+/// * `epsilon` - A value added to the denominator for numerical stability+///+/// The resulting tensors have the same dimensions as `x`+/// First tensor is the result of the normalization, second is the result of the residual add+pub fn fused_add_rms_norm(+ x: &Tensor,+ res: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f32,+) -> Result<(Tensor, Tensor)> {+ let op = LayerNorm {+ epsilon,+ gamma: gamma.clone(),+ beta: beta.cloned(),+ is_rms_norm: true,+ output_only: false,+ };+ let results = x.apply_op2(&res, op)?;+ let rows = x.dims()[0];+ Ok((results.narrow(0, 0, rows)?, results.narrow(0, rows, rows)?))+}++#[cfg(test)]+mod tests {+ use super::*;+ use candle::{DType, Device};++ fn layer_norm_truth(+ x: &Tensor,+ gamma: &Tensor,+ beta: Option<&Tensor>,+ epsilon: f64,+ rms: bool,+ ) -> Result<Tensor> {+ let x_dtype = x.dtype();+ let internal_dtype = match x_dtype {+ DType::F16 | DType::BF16 => DType::F32,+ d => d,+ };++ let (_seq_len, hidden_size) = x.shape().dims2()?;+ let x = x.to_dtype(internal_dtype)?;++ let x = if !rms {+ let mean_x = (x.sum_keepdim(1)? / hidden_size as f64)?;+ x.broadcast_sub(&mean_x)?+ } else {+ x+ };++ let norm_x = (x.sqr()?.sum_keepdim(1)? / hidden_size as f64)?;+ let x_normed = x.broadcast_div(&(norm_x + epsilon)?.sqrt()?)?;++ let mut x = x_normed.to_dtype(x_dtype)?.broadcast_mul(gamma)?;+ if let Some(beta) = beta {+ x = x.broadcast_add(beta)?;+ }+ Ok(x)+ }++ fn to_vec2_round(t: Tensor, digits: i32) -> Result<Vec<Vec<f32>>> {+ let b = 10f32.powi(digits);+ let t = t.to_dtype(DType::F32)?.to_vec2::<f32>()?;+ let t = t+ .iter()+ .map(|t| t.iter().map(|t| f32::round(t * b) / b).collect())+ .collect();+ Ok(t)+ }++ #[test]+ fn test_layer_norm() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let res = layer_norm(&x, &g, Some(&b), 1e-12)?;+ let truth = layer_norm_truth(&x, &g, Some(&b), 1e-12, false)?;++ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }++ #[test]+ fn test_layer_norm_no_bias() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let res = layer_norm(&x, &g, None, 1e-12)?;+ let truth = layer_norm_truth(&x, &g, None, 1e-12, false)?;++ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }++ #[test]+ fn test_rms_norm() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let res = rms_norm(&x, &g, Some(&b), 1e-12)?;+ let truth = layer_norm_truth(&x, &g, Some(&b), 1e-12, true)?;+ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }++ #[test]+ fn test_rms_norm_no_bias() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let res = rms_norm(&x, &g, None, 1e-12)?;+ let truth = layer_norm_truth(&x, &g, None, 1e-12, true)?;++ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }++ #[test]+ fn test_layer_norm_add() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let r = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let (res, res_add) = fused_add_layer_norm(&x, &r, &g, Some(&b), 1e-12)?;+ let truth_add = (x + r)?;+ let truth = layer_norm_truth(&truth_add, &g, Some(&b), 1e-12, false)?;+ assert_eq!(to_vec2_round(res_add, 3)?, to_vec2_round(truth_add, 3)?);+ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }++ #[test]+ fn test_rms_norm_add() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let x = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let r = Tensor::randn(0., 1., (4, 8), &device)?.to_dtype(DType::F32)?;+ let g = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;+ let b = Tensor::randn(0., 1., 8, &device)?.to_dtype(DType::F32)?;++ let (res, res_add) = fused_add_rms_norm(&x, &r, &g, Some(&b), 1e-12)?;+ let truth_add = (x + r)?;+ let truth = layer_norm_truth(&truth_add, &g, Some(&b), 1e-12, true)?;+ assert_eq!(to_vec2_round(res_add, 3)?, to_vec2_round(truth_add, 3)?);+ assert_eq!(to_vec2_round(res, 3)?, to_vec2_round(truth, 3)?);+ Ok(())+ }+}diff --git a/packages/sie_server_rust/vendor/candle-rotary/Cargo.toml b/packages/sie_server_rust/vendor/candle-rotary/Cargo.tomlnew file mode 100644index 000000000..cf4ba6411--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/Cargo.toml@@ -0,0 +1,61 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+name = "candle-rotary"+version = "0.0.1"+build = "build.rs"+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "Rotary layer for the candle ML framework."+readme = "README.md"+keywords = [+ "tensor",+ "machine-learning",+]+categories = ["science"]+license = "MIT OR Apache-2.0"++[lib]+name = "candle_rotary"+path = "src/lib.rs"++[[test]]+name = "rotary_tests"+path = "tests/rotary_tests.rs"++[dependencies.candle]+version = "0.10.2"+features = ["cuda"]+package = "candle-core"++[dependencies.half]+version = "2.3.1"+features = ["num-traits"]++[dev-dependencies.anyhow]+version = "1"+features = ["backtrace"]++[dev-dependencies.candle-nn]+version = "0.10.2"+features = ["cuda"]++[build-dependencies.anyhow]+version = "1"+features = ["backtrace"]++[build-dependencies.bindgen_cuda]+version = "0.1.1"diff --git a/packages/sie_server_rust/vendor/candle-rotary/LICENSE-APACHE b/packages/sie_server_rust/vendor/candle-rotary/LICENSE-APACHEnew file mode 100644index 000000000..261eeb9e9--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/LICENSE-APACHE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/packages/sie_server_rust/vendor/candle-rotary/LICENSE-MIT b/packages/sie_server_rust/vendor/candle-rotary/LICENSE-MITnew file mode 100644index 000000000..31aa79387--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/LICENSE-MIT@@ -0,0 +1,23 @@+Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/packages/sie_server_rust/vendor/candle-rotary/README.md b/packages/sie_server_rust/vendor/candle-rotary/README.mdnew file mode 100644index 000000000..303d92d78--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/README.md@@ -0,0 +1,4 @@+# Candle Rotary++All files in `kernels` are adapted from https://github.com/vllm-project/vllm/tree/main/csrc and are under the vLLM+Project copyright.diff --git a/packages/sie_server_rust/vendor/candle-rotary/build.rs b/packages/sie_server_rust/vendor/candle-rotary/build.rsnew file mode 100644index 000000000..a37ecd144--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/build.rs@@ -0,0 +1,59 @@+// Build script to run nvcc and generate the C glue code for launching the rotary kernel.+// The CUDA build time can be long, so set CANDLE_ROTARY_BUILD_DIR to reuse compiled+// artifacts across builds.+use anyhow::{Context, Result};+use std::path::PathBuf;++const KERNEL_FILES: [&str; 1] = ["kernels/rotary.cu"];++fn main() -> Result<()> {+ println!("cargo:rerun-if-changed=build.rs");+ for kernel_file in KERNEL_FILES.iter() {+ println!("cargo:rerun-if-changed={kernel_file}");+ }+ let out_dir = PathBuf::from(std::env::var("OUT_DIR").context("OUT_DIR not set")?);+ let build_dir = match std::env::var("CANDLE_ROTARY_BUILD_DIR") {+ Err(_) =>+ {+ #[allow(clippy::redundant_clone)]+ out_dir.clone()+ }+ Ok(build_dir) => {+ let path = PathBuf::from(build_dir);+ let current_dir = std::env::current_dir()?;+ path.canonicalize().unwrap_or_else(|_| {+ panic!(+ "Directory does not exist: {} (the current directory is {})",+ path.display(),+ current_dir.display()+ )+ })+ }+ };++ let kernels: Vec<_> = KERNEL_FILES.iter().collect();+ let builder = bindgen_cuda::Builder::default()+ .kernel_paths(kernels)+ .out_dir(build_dir.clone())+ .arg("-std=c++17")+ .arg("-O3")+ .arg("-U__CUDA_NO_HALF_OPERATORS__")+ .arg("-U__CUDA_NO_HALF_CONVERSIONS__")+ .arg("-U__CUDA_NO_HALF2_OPERATORS__")+ .arg("-U__CUDA_NO_BFLOAT16_CONVERSIONS__")+ .arg("--expt-relaxed-constexpr")+ .arg("--expt-extended-lambda")+ .arg("--use_fast_math")+ .arg("--ptxas-options=-v")+ .arg("--verbose");++ let out_file = build_dir.join("librotary.a");+ builder.build_lib(out_file);++ println!("cargo:rustc-link-search={}", build_dir.display());+ println!("cargo:rustc-link-lib=rotary");+ println!("cargo:rustc-link-lib=dylib=cudart");+ println!("cargo:rustc-link-lib=dylib=stdc++");++ Ok(())+}diff --git a/packages/sie_server_rust/vendor/candle-rotary/kernels/cuda_compat.h b/packages/sie_server_rust/vendor/candle-rotary/kernels/cuda_compat.hnew file mode 100644index 000000000..ed3ebe7dc--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/kernels/cuda_compat.h@@ -0,0 +1,27 @@+#pragma once++#ifndef USE_ROCM+ #define VLLM_LDG(arg) __ldg(arg)+#else+ #define VLLM_LDG(arg) *(arg)+#endif++#ifndef USE_ROCM+ #define VLLM_SHFL_XOR_SYNC(var, lane_mask) __shfl_xor_sync(uint32_t(-1), var, lane_mask)+#else+ #define VLLM_SHFL_XOR_SYNC(var, lane_mask) __shfl_xor(var, lane_mask)+#endif++#ifndef USE_ROCM+ #define VLLM_SHFL_SYNC(var, src_lane) __shfl_sync(uint32_t(-1), var, src_lane)+#else+ #define VLLM_SHFL_SYNC(var, src_lane) __shfl(var, src_lane)+#endif++#ifndef USE_ROCM+ #define VLLM_DevFuncAttribute_SET_MaxDynamicSharedMemorySize(FUNC, VAL) \+ cudaFuncSetAttribute(FUNC, cudaFuncAttributeMaxDynamicSharedMemorySize, VAL)+#else+ #define VLLM_DevFuncAttribute_SET_MaxDynamicSharedMemorySize(FUNC, VAL) \+ hipFuncSetAttribute(FUNC, hipFuncAttributeMaxDynamicSharedMemorySize, VAL)+#endifdiff --git a/packages/sie_server_rust/vendor/candle-rotary/kernels/rotary.cu b/packages/sie_server_rust/vendor/candle-rotary/kernels/rotary.cunew file mode 100644index 000000000..b5c975cb8--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/kernels/rotary.cu@@ -0,0 +1,131 @@+#include <cuda_fp16.h>+#include <cuda_bf16.h>+#include <stdint.h>++#include "cuda_compat.h"++namespace vllm {++template<typename scalar_t, bool IS_NEOX>+inline __device__ void apply_rotary_embedding(+ scalar_t* __restrict__ arr,+ const scalar_t* __restrict__ cos_ptr,+ const scalar_t* __restrict__ sin_ptr,+ int rot_offset,+ int rot_dim)+{+ int x_index, y_index;+ scalar_t cos, sin;+ if (IS_NEOX) {+ // GPT-NeoX style rotary embedding.+ x_index = rot_offset;+ y_index = rot_dim + rot_offset;+ cos = VLLM_LDG(cos_ptr + x_index);+ sin = VLLM_LDG(sin_ptr + x_index);+ } else {+ // GPT-J style rotary embedding.+ x_index = 2 * rot_offset;+ y_index = 2 * rot_offset + 1;+ cos = VLLM_LDG(cos_ptr + x_index / 2);+ sin = VLLM_LDG(sin_ptr + x_index / 2);+ }++ const scalar_t x = arr[x_index];+ const scalar_t y = arr[y_index];+ arr[x_index] = x * cos - y * sin;+ arr[y_index] = y * cos + x * sin;+}++template<typename scalar_t, bool IS_NEOX>+__global__ void rotary_embedding_kernel(+ scalar_t* __restrict__ query, // [num_tokens, num_heads, head_size]+ scalar_t* __restrict__ key, // [num_tokens, num_heads, head_size]+ const scalar_t* __restrict__ cos_cache, // [num_tokens, rot_dim]+ const scalar_t* __restrict__ sin_cache, // [num_tokens, rot_dim]+ const int rot_dim,+ const int64_t query_stride,+ const int64_t key_stride,+ const int num_heads,+ const int num_kv_heads,+ const int head_size) {+ // Each thread block is responsible for one token.+ const int token_idx = blockIdx.x;++ const scalar_t* cos_ptr = cos_cache + token_idx * rot_dim;+ const scalar_t* sin_ptr = sin_cache + token_idx * rot_dim;++ const int nq = num_heads * rot_dim;+ for (int i = threadIdx.x; i < nq; i += blockDim.x) {+ const int head_idx = i / rot_dim;+ const int64_t token_head = token_idx * query_stride + head_idx * head_size;+ const int rot_offset = i % rot_dim;+ apply_rotary_embedding<scalar_t, IS_NEOX>(query + token_head, cos_ptr,+ sin_ptr, rot_offset, rot_dim);+ }++ const int nk = num_kv_heads * rot_dim;+ for (int i = threadIdx.x; i < nk; i += blockDim.x) {+ const int head_idx = i / rot_dim;+ const int64_t token_head = token_idx * key_stride + head_idx * head_size;+ const int rot_offset = i % rot_dim;+ apply_rotary_embedding<scalar_t, IS_NEOX>(key + token_head, cos_ptr,+ sin_ptr, rot_offset, rot_dim);+ }+}++} // namespace vllm++#define CALL_ROTARY(T, IS_NEOX) \+ vllm::rotary_embedding_kernel<T, IS_NEOX><<<grid, block, 0, stream>>>( \+ reinterpret_cast<T*>(query), \+ reinterpret_cast<T*>(key), \+ reinterpret_cast<T*>(cos_cache), \+ reinterpret_cast<T*>(sin_cache), \+ rot_dim, \+ query_stride, \+ key_stride, \+ num_heads, \+ num_kv_heads, \+ head_size);++extern "C" void rotary_embedding(+ void *query, // [num_tokens, num_heads, head_size]+ void *key, // [num_tokens, num_kv_heads, head_size]+ void *cos_cache, // [num_tokens, rot_dim]+ void *sin_cache, // [num_tokens, rot_dim]+ int32_t is_neox,++ int32_t head_size,+ int64_t num_tokens,+ int32_t rot_dim,+ int32_t num_heads,+ int32_t num_kv_heads,+ int64_t query_stride,+ int64_t key_stride,++ uint32_t dtype // 0 => f16; 1 => bf16; 2 => f32+ ) {++ dim3 grid(num_tokens);+ dim3 block(std::min(num_heads * rot_dim, 512));+ const cudaStream_t stream = 0;+ const bool is_neox_bool = is_neox;++ if (is_neox_bool) {+ if (dtype == 0){+ CALL_ROTARY(half, true);+ } else if (dtype == 1) {+ CALL_ROTARY(__nv_bfloat16, true);+ } else if (dtype == 2) {+ CALL_ROTARY(float, true);+ }+ } else {+ if (dtype == 0){+ CALL_ROTARY(half, false);+ } else if (dtype == 1) {+ CALL_ROTARY(__nv_bfloat16, false);+ } else if (dtype == 2) {+ CALL_ROTARY(float, false);+ }+ }+}diff --git a/packages/sie_server_rust/vendor/candle-rotary/src/ffi.rs b/packages/sie_server_rust/vendor/candle-rotary/src/ffi.rsnew file mode 100644index 000000000..3839177b5--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/src/ffi.rs@@ -0,0 +1,22 @@+use core::ffi::{c_int, c_long, c_void};++extern "C" {+ pub(crate) fn rotary_embedding(+ query: *const c_void,+ key: *const c_void,+ cos_cache: *const c_void,+ sin_cache: *const c_void,++ is_neox: c_int,++ head_size: c_int,+ num_tokens: c_long,+ rot_dim: c_int,+ num_heads: c_int,+ num_kv_heads: c_int,+ query_stride: c_long,+ key_stride: c_long,++ dtype: u32,+ );+}diff --git a/packages/sie_server_rust/vendor/candle-rotary/src/lib.rs b/packages/sie_server_rust/vendor/candle-rotary/src/lib.rsnew file mode 100644index 000000000..89fb4d981--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/src/lib.rs@@ -0,0 +1,181 @@+mod ffi;++use candle::{DType, Device, Result, Storage, Tensor};+use half::{bf16, f16};+use std::ffi::{c_int, c_long};++fn apply_rotary_<+ T: candle::cuda_backend::CudaDType + candle::cuda_backend::cudarc::driver::DeviceRepr,+>(+ query: &Tensor,+ key: &Tensor,+ cos_cache: &Tensor,+ sin_cache: &Tensor,+ is_neox: bool,+) -> Result<()> {+ let dtype = query.dtype();+ if key.dtype() != dtype || cos_cache.dtype() != dtype || sin_cache.dtype() != dtype {+ candle::bail!("apply-rotary expects all tensors to have the same dtype");+ }++ let internal_type = match dtype {+ DType::F16 => 0,+ DType::BF16 => 1,+ DType::F32 => 2,+ dtype => candle::bail!("dtype {dtype:?} is not supported"),+ };++ let (q, q_l) = query.storage_and_layout();+ let q = match &*q {+ Storage::Cuda(q) => q,+ _ => candle::bail!("query must be a cuda tensor"),+ };++ let (k, k_l) = key.storage_and_layout();+ let k = match &*k {+ Storage::Cuda(k) => k,+ _ => candle::bail!("key must be a cuda tensor"),+ };++ let (cc, cc_l) = cos_cache.storage_and_layout();+ let cc = match &*cc {+ Storage::Cuda(cc) => cc,+ _ => candle::bail!("cos_cache must be a cuda tensor"),+ };++ let (sc, sc_l) = sin_cache.storage_and_layout();+ let sc = match &*sc {+ Storage::Cuda(sc) => sc,+ _ => candle::bail!("sin_cache must be a cuda tensor"),+ };++ let q_rank = q_l.stride().len();+ let k_rank = k_l.stride().len();+ let cc_rank = cc_l.stride().len();+ let sc_rank = sc_l.stride().len();++ if q_rank != 3 || k_rank != 3 {+ candle::bail!("apply-rotary expects input tensors of rank 3 (k: {q_l:?}, v: {k_l:?})")+ }++ if cc_rank != 2 || sc_rank != 2 {+ candle::bail!("apply-rotary expects cache tensors of rank 2 (k: {cc_l:?}, v: {sc_l:?})")+ }++ let stream = q.device.cuda_stream();++ // Get cuda slices for all tensors+ let q = q.as_cuda_slice::<T>()?;+ let k = k.as_cuda_slice::<T>()?;+ let cc = cc.as_cuda_slice::<T>()?;+ let sc = sc.as_cuda_slice::<T>()?;++ // Get cuda views for all tensors+ let q = q.slice(q_l.start_offset()..);+ let k = k.slice(k_l.start_offset()..);+ let cc = cc.slice(cc_l.start_offset()..);+ let sc = sc.slice(sc_l.start_offset()..);++ let (num_tokens, num_heads, head_size) = q_l.shape().dims3()?;+ let (num_tokens_kv, num_kv_heads, head_size_kv) = k_l.shape().dims3()?;++ if (num_tokens, head_size) != (num_tokens_kv, head_size_kv) {+ candle::bail!("shape mismatch q {:?} and k {:?}", q_l.shape(), k_l.shape())+ }++ let rot_dim = cc_l.dims()[1];+ if (num_tokens, rot_dim) != cc_l.shape().dims2()? {+ candle::bail!(+ "shape mismatch cos_cache {:?}, expected {:?}",+ cc_l.shape(),+ (num_tokens, rot_dim)+ )+ }++ if (num_tokens, rot_dim) != sc_l.shape().dims2()? {+ candle::bail!(+ "shape mismatch sin_cache {:?}, expected {:?}",+ sc_l.shape(),+ (num_tokens, rot_dim)+ )+ }++ let query_stride = q_l.stride()[0];+ let key_stride = k_l.stride()[0];++ let (q_ptr, q_sync) = q.view_ptr(&stream);+ let (k_ptr, k_sync) = k.view_ptr(&stream);+ let (cc_ptr, cc_sync) = cc.view_ptr(&stream);+ let (sc_ptr, sc_sync) = sc.view_ptr(&stream);+ let q_ptr = q_ptr as *const core::ffi::c_void;+ let k_ptr = k_ptr as *const core::ffi::c_void;+ let cc_ptr = cc_ptr as *const core::ffi::c_void;+ let sc_ptr = sc_ptr as *const core::ffi::c_void;++ let neox = if is_neox { 1 } else { 0 };++ unsafe {+ ffi::rotary_embedding(+ q_ptr,+ k_ptr,+ cc_ptr,+ sc_ptr,+ neox,+ head_size as c_int,+ num_tokens as c_long,+ rot_dim as c_int,+ num_heads as c_int,+ num_kv_heads as c_int,+ query_stride as c_long,+ key_stride as c_long,+ internal_type,+ )+ }+ drop((q_sync, k_sync, cc_sync, sc_sync));+ Ok(())+}++pub fn inv_freqs(dim: usize, base: f32, device: &Device) -> Result<Tensor> {+ let inv_freq: Vec<_> = (0..dim)+ .step_by(2)+ .map(|i| 1f32 / base.powf(i as f32 / dim as f32))+ .collect();+ let inv_freq_len = inv_freq.len();+ Tensor::from_vec(inv_freq, (1, inv_freq_len), device)+}++pub fn cos_sin(length: usize, inv_freqs: &Tensor, dtype: DType) -> Result<(Tensor, Tensor)> {+ let t = Tensor::arange(0u32, length as u32, inv_freqs.device())?+ .to_dtype(DType::F32)?+ .reshape((length, 1))?;+ let freqs = t.matmul(&inv_freqs)?;+ let cos = freqs.cos()?.to_dtype(dtype)?;+ let sin = freqs.sin()?.to_dtype(dtype)?;+ Ok((cos, sin))+}++/// Apply Rotary position encoding inplace+///+/// # Arguments+///+/// * `query` - Query tensor of shape `(num_tokens, num_heads, head_size)`.+/// * `key` - Key tensor of shape `(num_tokens, num_kv_heads, head_size)`.+/// * `cos_cache` - Aligned cache of shape `(num_tokens, rot_dim)`+/// * `sin_cache` - Aligned cache of shape `(num_tokens, rot_dim)`+/// * `is_neox` - Use neox encoding instead of gpt-j style rotary+pub fn apply_rotary_inplace(+ query: &Tensor,+ key: &Tensor,+ cos_cache: &Tensor,+ sin_cache: &Tensor,+ is_neox: bool,+) -> Result<()> {+ match key.dtype() {+ DType::F16 => apply_rotary_::<f16>(query, key, cos_cache, sin_cache, is_neox),+ DType::BF16 => apply_rotary_::<bf16>(query, key, cos_cache, sin_cache, is_neox),+ DType::F32 => apply_rotary_::<f32>(query, key, cos_cache, sin_cache, is_neox),+ dt => {+ candle::bail!("apply_rotary is only supported for f32, f16 and bf16 ({dt:?})")+ }+ }+}diff --git a/packages/sie_server_rust/vendor/candle-rotary/tests/rotary_tests.rs b/packages/sie_server_rust/vendor/candle-rotary/tests/rotary_tests.rsnew file mode 100644index 000000000..ed6a611d9--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-rotary/tests/rotary_tests.rs@@ -0,0 +1,86 @@+use anyhow::Result;+use candle::{DType, Device, Tensor, D};++fn to_vec3_round(t: Tensor, digits: i32) -> Result<Vec<Vec<Vec<f32>>>> {+ let b = 10f32.powi(digits);+ let t = t.to_vec3::<f32>()?;+ let t = t+ .iter()+ .map(|t| {+ t.iter()+ .map(|t| t.iter().map(|t| f32::round(t * b) / b).collect())+ .collect()+ })+ .collect();+ Ok(t)+}++fn rotate_half(xs: &Tensor) -> candle::error::Result<Tensor> {+ let last_dim = xs.dim(D::Minus1)?;+ let xs1 = xs.narrow(D::Minus1, 0, last_dim / 2)?;+ let xs2 = xs.narrow(D::Minus1, last_dim / 2, last_dim / 2)?;+ Tensor::cat(&[&xs2.neg()?, &xs1], D::Minus1)+}++fn freqs(rot_dim: usize, seqlen: usize, dev: &Device) -> candle::error::Result<Tensor> {+ let inv_freq: Vec<_> = (0..rot_dim)+ .step_by(2)+ .map(|i| 1f32 / 10000f32.powf(i as f32 / rot_dim as f32))+ .collect();+ let inv_freq_len = inv_freq.len();+ let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?;+ let t = Tensor::arange(0u32, seqlen as u32, dev)?+ .to_dtype(DType::F32)?+ .reshape((seqlen, 1))?;+ t.matmul(&inv_freq)+}++fn apply_rotary_emb_qkv(+ q: &Tensor,+ k: &Tensor,+ cos: &Tensor,+ sin: &Tensor,+) -> Result<(Tensor, Tensor)> {+ let cos = cos.unsqueeze(1)?; // (seq_len, 1, dim)+ let sin = sin.unsqueeze(1)?; // (seq_len, 1, dim)+ let q_embed = (q.broadcast_mul(&cos)? + rotate_half(q)?.broadcast_mul(&sin))?;+ let k_embed = (k.broadcast_mul(&cos)? + rotate_half(k)?.broadcast_mul(&sin))?;+ Ok((q_embed, k_embed))+}++#[test]+#[ignore = "requires CUDA"]+fn rotary() -> Result<()> {+ let device = Device::new_cuda(0)?;++ let seqlen = 12;+ let num_heads = 8;+ let rot_dim = 64;++ let q = Tensor::randn(0.0, 1.0, (seqlen, num_heads, rot_dim), &device)?.to_dtype(DType::F32)?;+ let k = Tensor::randn(0.0, 1.0, (seqlen, num_heads, rot_dim), &device)?.to_dtype(DType::F32)?;++ let (expected_q, expected_k) = {+ let freqs = freqs(rot_dim, seqlen, &device)?;+ let freqs = Tensor::cat(&[&freqs, &freqs], D::Minus1)?;+ apply_rotary_emb_qkv(&q, &k, &freqs.cos()?, &freqs.sin()?)+ }?;++ // Create inv freqs+ let inv_freqs = candle_rotary::inv_freqs(rot_dim, 10000f32, &device)?;+ // Create an over-sized cos sin cache like you would usually do+ let (cos, sin) = candle_rotary::cos_sin(32, &inv_freqs, DType::F32)?;+ // Positions for seqlen+ let position_ids = Tensor::arange(0, seqlen as u32, &device)?;+ // Filter cos and sin+ let cos = cos.index_select(&position_ids, 0)?;+ let sin = sin.index_select(&position_ids, 0)?;++ // Inplace+ candle_rotary::apply_rotary_inplace(&q, &k, &cos, &sin, true)?;++ assert_eq!(to_vec3_round(expected_q, 3)?, to_vec3_round(q, 3)?);+ assert_eq!(to_vec3_round(expected_k, 3)?, to_vec3_round(k, 3)?);++ Ok(())+}diff --git a/packages/sie_server_rust/vendor/candle-splade-pool/Cargo.toml b/packages/sie_server_rust/vendor/candle-splade-pool/Cargo.tomlnew file mode 100644index 000000000..304736c3a--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-splade-pool/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2021"+name = "candle-splade-pool"+version = "0.0.1"+build = "build.rs"+publish = false+description = "CUDA segmented max-log1p pooling for packed SPLADE activations."+license = "MIT OR Apache-2.0"++[lib]+name = "candle_splade_pool"+path = "src/lib.rs"++[dependencies.candle]+version = "0.10.2"+features = ["cuda"]+package = "candle-core"++[dependencies.half]+version = "2.3.1"+features = ["num-traits"]++[build-dependencies.anyhow]+version = "1"+features = ["backtrace"]diff --git a/packages/sie_server_rust/vendor/candle-splade-pool/build.rs b/packages/sie_server_rust/vendor/candle-splade-pool/build.rsnew file mode 100644index 000000000..d63935bad--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-splade-pool/build.rs@@ -0,0 +1,173 @@+use anyhow::{Context, Result};+use std::path::PathBuf;++const KERNEL_FILE: &str = "splade_pool.cu";++fn main() -> Result<()> {+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=kernels/{KERNEL_FILE}");+ println!("cargo:rerun-if-env-changed=CANDLE_SPLADE_POOL_BUILD_DIR");+ println!("cargo:rerun-if-env-changed=CANDLE_NVCC_CCBIN");+ set_cuda_include_dir()?;++ let out_dir = PathBuf::from(std::env::var("OUT_DIR").context("OUT_DIR not set")?);+ let build_dir = match std::env::var("CANDLE_SPLADE_POOL_BUILD_DIR") {+ Ok(build_dir) => PathBuf::from(build_dir)+ .canonicalize()+ .context("CANDLE_SPLADE_POOL_BUILD_DIR does not exist")?,+ Err(_) => out_dir.clone(),+ };+ let ccbin = std::env::var("CANDLE_NVCC_CCBIN").ok();+ let compute_cap = compute_cap()?;+ let kernel_path = PathBuf::from("kernels").join(KERNEL_FILE);+ let object_path = out_dir.join("splade_pool.o");+ let library_path = build_dir.join("libspladepool.a");+ let stamp_path = build_dir.join("libspladepool.stamp");+ let build_stamp = format!(+ "KERNEL_BUILD_VERSION=1\nCUDA_COMPUTE_CAP={compute_cap}\nCANDLE_NVCC_CCBIN={}\n",+ ccbin.as_deref().unwrap_or("")+ );++ let library_modified = library_path.metadata().and_then(|meta| meta.modified());+ let kernel_is_newer = match (kernel_path.metadata(), library_modified) {+ (Ok(kernel_meta), Ok(library_modified)) => kernel_meta+ .modified()+ .map(|modified| modified > library_modified)+ .unwrap_or(true),+ _ => true,+ };+ let should_compile = !library_path.exists()+ || kernel_is_newer+ || std::fs::read_to_string(&stamp_path).ok().as_deref() != Some(build_stamp.as_str());++ if should_compile {+ let mut compile = std::process::Command::new("nvcc");+ compile+ .arg("-std=c++17")+ .arg("-O3")+ .arg("-U__CUDA_NO_HALF_OPERATORS__")+ .arg("-U__CUDA_NO_HALF_CONVERSIONS__")+ .arg(format!("--gpu-architecture=sm_{compute_cap}"))+ .arg("-c")+ .args(["-o", object_path.to_str().context("non-UTF8 object path")?])+ .arg("--verbose");+ if let Some(ccbin) = ccbin.as_deref() {+ compile+ .arg("-allow-unsupported-compiler")+ .args(["-ccbin", ccbin]);+ }+ compile.arg(&kernel_path);+ run(&mut compile, "compile SPLADE pooling CUDA kernel")?;++ let mut archive = std::process::Command::new("nvcc");+ archive+ .arg("--lib")+ .args([+ "-o",+ library_path.to_str().context("non-UTF8 library path")?,+ ])+ .arg(&object_path);+ run(&mut archive, "archive SPLADE pooling CUDA kernel")?;+ std::fs::write(&stamp_path, build_stamp).with_context(|| {+ format!("write SPLADE pooling build stamp {}", stamp_path.display())+ })?;+ }++ println!("cargo:rustc-link-search={}", build_dir.display());+ println!("cargo:rustc-link-lib=spladepool");+ println!("cargo:rustc-link-lib=dylib=cudart");+ println!("cargo:rustc-link-lib=dylib=stdc++");+ Ok(())+}++fn run(command: &mut std::process::Command, action: &str) -> Result<()> {+ let output = command+ .output()+ .with_context(|| format!("failed to {action}"))?;+ if output.status.success() {+ return Ok(());+ }+ anyhow::bail!(+ "failed to {action}: {command:?}\n\n# stdout\n{}\n\n# stderr\n{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ )+}++fn set_cuda_include_dir() -> Result<()> {+ let env_roots = [+ "CUDA_PATH",+ "CUDA_ROOT",+ "CUDA_TOOLKIT_ROOT_DIR",+ "CUDNN_LIB",+ ]+ .into_iter()+ .filter_map(|name| std::env::var(name).ok())+ .map(PathBuf::from);+ let standard_roots = [+ "/usr",+ "/usr/local/cuda",+ "/opt/cuda",+ "/usr/lib/cuda",+ "C:/Program Files/NVIDIA GPU Computing Toolkit",+ "C:/CUDA",+ ]+ .into_iter()+ .map(PathBuf::from);+ let root = env_roots+ .chain(standard_roots)+ .find(|path| path.join("include/cuda.h").is_file())+ .context("cannot find include/cuda.h")?;+ println!(+ "cargo:rustc-env=CUDA_INCLUDE_DIR={}",+ root.join("include").display()+ );+ Ok(())+}++fn compute_cap() -> Result<usize> {+ println!("cargo:rerun-if-env-changed=CUDA_COMPUTE_CAP");+ let compute_cap = if let Ok(value) = std::env::var("CUDA_COMPUTE_CAP") {+ value+ .parse::<usize>()+ .context("could not parse CUDA_COMPUTE_CAP")?+ } else {+ let output = std::process::Command::new("nvidia-smi")+ .args(["--query-gpu=compute_cap", "--format=csv,noheader"])+ .output()+ .context("nvidia-smi failed; set CUDA_COMPUTE_CAP explicitly")?;+ std::str::from_utf8(&output.stdout)+ .context("nvidia-smi output is not UTF-8")?+ .lines()+ .next()+ .context("nvidia-smi returned no compute capability")?+ .trim()+ .replace('.', "")+ .parse::<usize>()+ .context("could not parse nvidia-smi compute capability")?+ };++ let output = std::process::Command::new("nvcc")+ .arg("--list-gpu-code")+ .output()+ .context("nvcc failed; ensure the CUDA toolkit is installed")?;+ let supported = std::str::from_utf8(&output.stdout)+ .context("nvcc output is not UTF-8")?+ .lines()+ .filter_map(|line| {+ let parts = line.split('_').collect::<Vec<_>>();+ if parts.contains(&"sm") {+ parts.get(1).and_then(|code| code.parse().ok())+ } else {+ None+ }+ })+ .collect::<Vec<usize>>();+ if !supported.contains(&compute_cap) {+ anyhow::bail!(+ "nvcc cannot target GPU architecture {compute_cap}; available targets: {supported:?}"+ )+ }+ println!("cargo:rustc-env=CUDA_COMPUTE_CAP={compute_cap}");+ Ok(compute_cap)+}diff --git a/packages/sie_server_rust/vendor/candle-splade-pool/kernels/splade_pool.cu b/packages/sie_server_rust/vendor/candle-splade-pool/kernels/splade_pool.cunew file mode 100644index 000000000..f9015213c--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-splade-pool/kernels/splade_pool.cu@@ -0,0 +1,71 @@+#include <cuda_fp16.h>+#include <cuda_runtime.h>+#include <math_constants.h>+#include <cmath>+#include <stdint.h>++__global__ void splade_segmented_max_log1p_f16_kernel(+ const half* __restrict__ input,+ const uint32_t* __restrict__ offsets,+ half* __restrict__ output,+ int64_t total_tokens,+ int32_t vocab_size) {+ const int32_t batch = static_cast<int32_t>(blockIdx.y);+ const int32_t vocab =+ static_cast<int32_t>(blockIdx.x * blockDim.x + threadIdx.x);+ if (vocab >= vocab_size) {+ return;+ }++ const uint32_t start = offsets[batch];+ const uint32_t end = offsets[batch + 1];+ if (start >= end || static_cast<int64_t>(end) > total_tokens ||+ (batch == 0 && start != 0) ||+ (batch + 1 == static_cast<int32_t>(gridDim.y) &&+ static_cast<int64_t>(end) != total_tokens)) {+ output[static_cast<int64_t>(batch) * vocab_size + vocab] =+ __float2half(CUDART_NAN_F);+ return;+ }++ // Keep the reduction in half precision, but evaluate true log1p in float+ // before rounding the pooled result to half. Performing 1 + x in half first+ // erases small positive SPLADE weights that PyTorch log1p preserves.+ // __hmax_nan also preserves the existing non-finite-output rejection path.+ half max_value = __float2half(-INFINITY);+ for (uint32_t token = start; token < end; ++token) {+ max_value = __hmax_nan(+ max_value,+ input[static_cast<int64_t>(token) * vocab_size + vocab]);+ }+ output[static_cast<int64_t>(batch) * vocab_size + vocab] =+ __float2half_rn(log1pf(__half2float(max_value)));+}++extern "C" int splade_segmented_max_log1p_f16(+ const void* input,+ const void* offsets,+ void* output,+ int64_t total_tokens,+ int32_t vocab_size,+ int32_t batch_size,+ cudaStream_t stream) {+ if (input == nullptr || offsets == nullptr || output == nullptr ||+ total_tokens <= 0 || vocab_size <= 0 || batch_size <= 0 ||+ batch_size > 65535) {+ return static_cast<int>(cudaErrorInvalidValue);+ }++ constexpr int32_t threads = 256;+ const uint32_t vocab_tiles =+ (static_cast<uint32_t>(vocab_size) + threads - 1) / threads;+ const dim3 grid(vocab_tiles, static_cast<uint32_t>(batch_size));+ const dim3 block(threads);+ splade_segmented_max_log1p_f16_kernel<<<grid, block, 0, stream>>>(+ reinterpret_cast<const half*>(input),+ reinterpret_cast<const uint32_t*>(offsets),+ reinterpret_cast<half*>(output),+ total_tokens,+ vocab_size);+ return static_cast<int>(cudaGetLastError());+}diff --git a/packages/sie_server_rust/vendor/candle-splade-pool/src/ffi.rs b/packages/sie_server_rust/vendor/candle-splade-pool/src/ffi.rsnew file mode 100644index 000000000..b1f1b9452--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-splade-pool/src/ffi.rs@@ -0,0 +1,13 @@+use core::ffi::{c_int, c_void};++extern "C" {+ pub(crate) fn splade_segmented_max_log1p_f16(+ input: *const c_void,+ offsets: *const c_void,+ output: *mut c_void,+ total_tokens: i64,+ vocab_size: c_int,+ batch_size: c_int,+ stream: *mut c_void,+ ) -> c_int;+}diff --git a/packages/sie_server_rust/vendor/candle-splade-pool/src/lib.rs b/packages/sie_server_rust/vendor/candle-splade-pool/src/lib.rsnew file mode 100644index 000000000..26669b801--- /dev/null+++ b/packages/sie_server_rust/vendor/candle-splade-pool/src/lib.rs@@ -0,0 +1,159 @@+mod ffi;++use candle::backend::BackendStorage;+use candle::cuda_backend::cudarc::driver::DevicePtrMut;+use candle::{CpuStorage, DType, Layout, Result, Shape, Tensor};+use half::f16;++const MAX_GRID_Y: usize = 65_535;++#[derive(Debug)]+struct SegmentedMaxLog1p;++fn validate_layouts(+ input_layout: &Layout,+ offsets_layout: &Layout,+) -> Result<(usize, usize, usize, usize, Shape)> {+ let input_dims = input_layout.dims();+ if input_dims.len() != 2 {+ candle::bail!(+ "SPLADE segmented pool expects input shape [tokens, vocab], got rank {}",+ input_dims.len()+ )+ }+ let offsets_dims = offsets_layout.dims();+ if offsets_dims.len() != 1 {+ candle::bail!(+ "SPLADE segmented pool expects offsets shape [batch + 1], got rank {}",+ offsets_dims.len()+ )+ }+ if input_layout.contiguous_offsets().is_none() {+ candle::bail!("SPLADE segmented pool expects contiguous input")+ }+ if offsets_layout.contiguous_offsets().is_none() {+ candle::bail!("SPLADE segmented pool expects contiguous offsets")+ }++ let total_tokens = input_dims[0];+ let vocab_size = input_dims[1];+ let offset_count = offsets_dims[0];+ if total_tokens == 0 {+ candle::bail!("SPLADE segmented pool requires at least one token")+ }+ if vocab_size == 0 {+ candle::bail!("SPLADE segmented pool requires a non-empty vocabulary")+ }+ if offset_count < 2 {+ candle::bail!("SPLADE segmented pool requires at least one sequence")+ }++ let batch_size = offset_count - 1;+ if batch_size > MAX_GRID_Y {+ candle::bail!(+ "SPLADE segmented pool batch {batch_size} exceeds CUDA grid.y limit {MAX_GRID_Y}"+ )+ }+ if total_tokens > u32::MAX as usize {+ candle::bail!("SPLADE segmented pool token count exceeds U32 offsets")+ }+ if vocab_size > i32::MAX as usize {+ candle::bail!("SPLADE segmented pool vocabulary exceeds i32 kernel ABI")+ }+ if batch_size > i32::MAX as usize {+ candle::bail!("SPLADE segmented pool batch exceeds i32 kernel ABI")+ }+ let output_elems = batch_size+ .checked_mul(vocab_size)+ .ok_or_else(|| candle::Error::msg("SPLADE segmented pool output size overflow"))?;++ Ok((+ total_tokens,+ vocab_size,+ batch_size,+ output_elems,+ Shape::from((batch_size, vocab_size)),+ ))+}++impl candle::CustomOp2 for SegmentedMaxLog1p {+ fn name(&self) -> &'static str {+ "splade-segmented-max-log1p"+ }++ fn cpu_fwd(+ &self,+ _: &CpuStorage,+ _: &Layout,+ _: &CpuStorage,+ _: &Layout,+ ) -> Result<(CpuStorage, Shape)> {+ candle::bail!("SPLADE segmented pool is only supported on CUDA")+ }++ fn cuda_fwd(+ &self,+ input: &candle::CudaStorage,+ input_layout: &Layout,+ offsets: &candle::CudaStorage,+ offsets_layout: &Layout,+ ) -> Result<(candle::CudaStorage, Shape)> {+ if input.dtype() != DType::F16 {+ candle::bail!(+ "SPLADE segmented pool only supports F16 input, got {:?}",+ input.dtype()+ )+ }+ if offsets.dtype() != DType::U32 {+ candle::bail!(+ "SPLADE segmented pool requires U32 offsets, got {:?}",+ offsets.dtype()+ )+ }+ let (total_tokens, vocab_size, batch_size, output_elems, output_shape) =+ validate_layouts(input_layout, offsets_layout)?;+ let (input_start, input_end) = input_layout+ .contiguous_offsets()+ .ok_or_else(|| candle::Error::msg("SPLADE segmented pool expects contiguous input"))?;+ let (offsets_start, offsets_end) =+ offsets_layout.contiguous_offsets().ok_or_else(|| {+ candle::Error::msg("SPLADE segmented pool expects contiguous offsets")+ })?;++ let device = input.device();+ let stream = device.cuda_stream();+ let input = input.as_cuda_slice::<f16>()?.slice(input_start..input_end);+ let offsets = offsets+ .as_cuda_slice::<u32>()?+ .slice(offsets_start..offsets_end);+ let mut output = unsafe { device.alloc::<f16>(output_elems)? };++ let (input_ptr, input_sync) = input.view_ptr(&stream);+ let (offsets_ptr, offsets_sync) = offsets.view_ptr(&stream);+ let (output_ptr, output_sync) = output.device_ptr_mut(&stream);+ let status = unsafe {+ ffi::splade_segmented_max_log1p_f16(+ input_ptr as *const core::ffi::c_void,+ offsets_ptr as *const core::ffi::c_void,+ output_ptr as *mut core::ffi::c_void,+ total_tokens as i64,+ vocab_size as i32,+ batch_size as i32,+ stream.cu_stream().cast(),+ )+ };+ drop((input_sync, offsets_sync, output_sync));+ if status != 0 {+ candle::bail!("SPLADE segmented pool CUDA kernel failed with status {status}")+ }++ let output = candle::CudaStorage::wrap_cuda_slice(output, device.clone());+ Ok((output, output_shape))+ }+}++/// Max-pool packed non-negative F16 SPLADE activations by sequence and apply+/// `log1p` to each pooled vocabulary weight in the same CUDA kernel.+pub fn segmented_max_log1p(input: &Tensor, offsets: &Tensor) -> Result<Tensor> {+ input.apply_op2_no_bwd(offsets, &SegmentedMaxLog1p)+}diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 91f663bde..5a2d9a5b2 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.7.2"+version = "0.7.3"edition = "2021"publish = falsedescription = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex e612f7f2c..0ecf20dc2 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -5642,20 +5642,24 @@ mod tests {}let work = wi("req-load", 0, "Qwen/Qwen3-4B-Instruct-2507", "generate");- let bytes =- encode_generate_terminal_error_chunk(&work, MODEL_LOADING_ERROR_CODE, "loading")- .expect("chunk encodes");- let decoded: DecodedChunk = rmp_serde::from_slice(&bytes).expect("chunk decodes");-- assert_eq!(decoded.kind, "chunk");- assert_eq!(decoded.request_id, "req-load");- assert_eq!(decoded.attempt_id, "req-load.0:model-loading");- assert_eq!(decoded.seq, 0);- assert_eq!(decoded.text_delta, "");- assert!(decoded.done);- assert_eq!(decoded.finish_reason, "error");- assert_eq!(decoded.error.code, MODEL_LOADING_ERROR_CODE);- assert_eq!(decoded.error.message, "loading");+ for (code, message) in [+ (MODEL_LOADING_ERROR_CODE, "loading"),+ (MODEL_LOAD_FAILED_ERROR_CODE, "load failed"),+ ] {+ let bytes =+ encode_generate_terminal_error_chunk(&work, code, message).expect("chunk encodes");+ let decoded: DecodedChunk = rmp_serde::from_slice(&bytes).expect("chunk decodes");++ assert_eq!(decoded.kind, "chunk");+ assert_eq!(decoded.request_id, "req-load");+ assert_eq!(decoded.attempt_id, "req-load.0:model-loading");+ assert_eq!(decoded.seq, 0);+ assert_eq!(decoded.text_delta, "");+ assert!(decoded.done);+ assert_eq!(decoded.finish_reason, "error");+ assert_eq!(decoded.error.code, code);+ assert_eq!(decoded.error.message, message);+ }}#[test]diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.mdindex 4ffc06d71..c62bb192c 100644--- a/packages/sie_ts_sdk/README.md+++ b/packages/sie_ts_sdk/README.md@@ -29,6 +29,13 @@ const managed = new SIEClient("https://your-gateway.example.com", {> For browser apps, route requests through a backend proxy that holds> the key.+> **Cold-start continuations:** non-streaming requests through a managed+> gateway may receive a bounded Modal result continuation. Consuming it safely+> requires a server-side Fetch runtime (Node.js >= 22) that exposes the status+> and `Location` of a `redirect: "manual"` response. Browser Fetch exposes an+> opaque redirect instead, so the SDK fails closed; route these browser calls+> through a backend proxy as well.+## Encoding```typescript@@ -130,7 +137,9 @@ the HTTP connection was healthy but the worker or gateway emitted anerror envelope partway through. Branch on `error.code` (for example`empty_model_output`, a terminal generation that produced no visibletext) and, when `error.requestId` is present, use it to correlate with-gateway logs.+gateway logs. For a validated `RESOURCE_EXHAUSTED` terminal,+`error.retryAfter` carries the operator hint in milliseconds; its presence+does not make retrying generation safe after output has already arrived.## Licensediff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 37e0a9393..bad70da5b 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.7.2",+ "version": "0.7.3","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.tsindex 7b8bf5dc8..64705a51d 100644--- a/packages/sie_ts_sdk/src/client.ts+++ b/packages/sie_ts_sdk/src/client.ts@@ -70,6 +70,7 @@ import {ESTIMATE_PATH,buildEstimateEnvelope,getErrorCode,+ getErrorParam,getRetryAfter,handleError,parseCapacityInfo,@@ -77,6 +78,7 @@ import {parseExtractResults,parseGenerateResult,parseScoreResult,+ readRequestId,settledChargeFields,throwIfEstimateUnroutable,throwIfInputTooLong,@@ -414,6 +416,10 @@ function parseRequestMetadata(headers: Headers, body?: unknown): RequestMetadataif (executionIdentitySha256 !== null && /^[0-9a-f]{64}$/.test(executionIdentitySha256)) {metadata.executionIdentitySha256 = executionIdentitySha256;}+ const executionBindingSha256 = headers.get("x-sie-execution-binding-sha256");+ if (executionBindingSha256 !== null && /^[0-9a-f]{64}$/.test(executionBindingSha256)) {+ metadata.executionBindingSha256 = executionBindingSha256;+ }const usageHeaders = {inputTokens: "x-sie-units-input-tokens",@@ -668,21 +674,36 @@ async function itemsForExtractWire(items: ExtractItem[]): Promise<ExtractItemFor* normal delta. Defined at module scope so it has zero coupling to* `SIEClient` state.*/+function validatedStreamRetryAfter(error: {+ code?: string;+ retry_after_s?: unknown;+}): number | undefined {+ const value = error.retry_after_s;+ return error.code === RESOURCE_EXHAUSTED_ERROR_CODE &&+ typeof value === "number" &&+ Number.isInteger(value) &&+ value >= 1 &&+ value <= 60+ ? value * 1_000+ : undefined;+}++function validatedStreamErrorParam(error: { param?: unknown }): string | null | undefined {+ return typeof error.param === "string" || error.param === null ? error.param : undefined;+}+function extractChatChunkError(chunk: ChatCompletionChunk): SIEStreamError | null {- const withError = chunk as ChatCompletionChunk & {- error?: { message?: string; type?: string; param?: string | null; code?: string };- request_id?: string;- };- if (!withError.error) return null;+ if (!chunk.error) return null;// The gateway request id rides in-band on the chat error chunk too (#3136)// — the `chatcmpl-*` id is not the correlation key gateway logs use, and// streamed responses have no terminal headers. Forward it for correlation.- const requestId = validateRequestId(withError.request_id);- return new SIEStreamError(withError.error.message ?? "stream error", {- code: withError.error.code,- errorType: withError.error.type,- param: withError.error.param,+ const requestId = validateRequestId(chunk.request_id);+ return new SIEStreamError(chunk.error.message ?? "stream error", {+ code: chunk.error.code,+ errorType: chunk.error.type,+ param: validatedStreamErrorParam(chunk.error),requestId,+ retryAfter: validatedStreamRetryAfter(chunk.error),});}@@ -765,13 +786,27 @@ function modalContinuationUrl(baseUrl: string, response: Response): string | und}}+function requireVisibleManualRedirect(response: Response): void {+ if (response.type === "opaqueredirect") {+ throw new SIEConnectionError(+ "Modal result continuations require a server-side Fetch runtime that exposes manual redirect status and Location",+ "other",+ );+ }+}+/** SIE-native chunk variant — see `sse.rs::build_generate_chunk_event`. */function extractGenerateChunkError(chunk: GenerateChunk): SIEStreamError | null {if (!chunk.error) return null;// The gateway request id rides in-band on the error chunk (streamed// responses have no terminal headers), so forward it for correlation (#3136).const requestId = validateRequestId(chunk.request_id);- return new SIEStreamError(chunk.error.message, { code: chunk.error.code, requestId });+ return new SIEStreamError(chunk.error.message, {+ code: chunk.error.code,+ param: validatedStreamErrorParam(chunk.error),+ requestId,+ retryAfter: validatedStreamRetryAfter(chunk.error),+ });}/**@@ -1316,6 +1351,7 @@ export class SIEClient {redirect: "manual",});for (let hop = 0; hop < MODAL_CONTINUATION_MAX_HOPS; hop += 1) {+ requireVisibleManualRedirect(response);const continuationUrl = modalContinuationUrl(this.baseUrl, response);if (!continuationUrl) return response;response = await fetch(continuationUrl, {@@ -1325,6 +1361,12 @@ export class SIEClient {redirect: "manual",});}+ requireVisibleManualRedirect(response);+ if (modalContinuationUrl(this.baseUrl, response)) {+ throw new ProvisioningError(+ `Provisioning result remained in flight after ${MODAL_CONTINUATION_MAX_HOPS} continuation hops`,+ );+ }return response;} catch (err) {if (err instanceof Error && err.name === "AbortError") {@@ -1656,6 +1698,7 @@ export class SIEClient {"No capacity available. Server is provisioning.",gpu,getRetryAfter(attemptResponse),+ await getErrorParam(attemptResponse.clone()),);}const elapsed = Date.now() - startTime;@@ -1664,6 +1707,7 @@ export class SIEClient {`Provisioning timeout after ${elapsed}ms`,gpu,getRetryAfter(attemptResponse),+ await getErrorParam(attemptResponse.clone()),);}const retryAfter = getRetryAfter(attemptResponse);@@ -1684,7 +1728,11 @@ export class SIEClient {if (errorCode === MODEL_LOADING_ERROR_CODE) {const elapsed = Date.now() - startTime;if (elapsed >= this.provisionTimeout) {- throw new ModelLoadingError(`Model loading timeout for '${model}'`, model);+ throw new ModelLoadingError(+ `Model loading timeout for '${model}'`,+ model,+ await getErrorParam(attemptResponse.clone()),+ );}const delay = getRetryAfter(attemptResponse) ?? MODEL_LOADING_DEFAULT_DELAY;if (@@ -1704,7 +1752,11 @@ export class SIEClient {if (!waitForCapacity) {throw new ResourceExhaustedError(`Server resource exhausted after ${oomRetries} retry attempt(s) for model '${model}'`,- { model, retries: oomRetries },+ {+ model,+ retries: oomRetries,+ param: await getErrorParam(attemptResponse.clone()),+ },);}const delay = nextOomRetryDelay({@@ -1714,6 +1766,7 @@ export class SIEClient {elapsedMs: Date.now() - startTime,provisionTimeoutMs: this.provisionTimeout,model,+ param: await getErrorParam(attemptResponse.clone()),});oomRetries += 1;if (await abortableSleep(delay, controller.signal)) {@@ -1733,6 +1786,8 @@ export class SIEClient {"non-idempotent (retrying could double-bill).",await getErrorCode(attemptResponse.clone()),HTTP_GATEWAY_TIMEOUT,+ readRequestId(attemptResponse),+ await getErrorParam(attemptResponse.clone()),);}@@ -2449,7 +2504,7 @@ export class SIEClient {while (true) {let response: Response;try {- response = await this.request(path, body, pool, gpu);+ response = await this.request(path, body, pool, gpu, startTime);} catch (err) {// Only retry connect-time failures; see docstring for rationale.if (waitForCapacity && err instanceof SIEConnectionError && err.kind === "connect") {@@ -2494,6 +2549,7 @@ export class SIEClient {`No capacity available for GPU '${gpu}'. Server is provisioning.`,gpu,retryAfter,+ await getErrorParam(response.clone()),);}@@ -2503,6 +2559,7 @@ export class SIEClient {`Provisioning timeout after ${elapsed}ms waiting for GPU '${gpu}'`,gpu,retryAfter,+ await getErrorParam(response.clone()),);}@@ -2521,6 +2578,7 @@ export class SIEClient {`LoRA loading timeout after ${loraRetries} retries`,undefined, // We don't have lora name at this levelmodel,+ await getErrorParam(response.clone()),);}@@ -2538,6 +2596,7 @@ export class SIEClient {throw new ModelLoadingError(`Model loading timeout after ${(elapsed / 1000).toFixed(1)}s for '${model}'`,model,+ await getErrorParam(response.clone()),);}@@ -2562,6 +2621,7 @@ export class SIEClient {elapsedMs: Date.now() - startTime,provisionTimeoutMs: this.provisionTimeout,model,+ param: await getErrorParam(response.clone()),});oomRetries += 1;await sleep(delay);@@ -2617,6 +2677,7 @@ export class SIEClient {body?: unknown,pool?: string,gpu?: string,+ startTime = Date.now(),): Promise<Response> {const url = `${this.baseUrl}${path}`;@@ -2642,30 +2703,77 @@ export class SIEClient {headers.Authorization = `Bearer ${this.apiKey}`;}- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), this.timeout);+ const fetchWithinBudget = async (+ requestUrl: string,+ init: Omit<RequestInit, "signal">,+ followingContinuation: boolean,+ ): Promise<Response> => {+ const remaining = this.provisionTimeout - (Date.now() - startTime);+ if (followingContinuation && remaining <= 0) {+ throw new ProvisioningError(+ `Provisioning timeout after ${this.provisionTimeout}ms awaiting request result`,+ gpu,+ );+ }+ const requestTimeout = followingContinuation+ ? Math.min(this.timeout, remaining)+ : this.timeout;+ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), requestTimeout);+ try {+ return await fetch(requestUrl, { ...init, signal: controller.signal });+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ throw new SIEConnectionError(`Request timeout after ${requestTimeout}ms`, "timeout");+ }+ if (error instanceof TypeError) {+ if (followingContinuation) {+ throw new SIEConnectionError(+ `Failed to retrieve the in-flight request result: ${error.message}`,+ "other",+ );+ }+ throw connectionErrorFromFetchTypeError(error);+ }+ throw error;+ } finally {+ clearTimeout(timeoutId);+ }+ };- try {- const response = await fetch(url, {+ let response = await fetchWithinBudget(+ url,+ {method: "POST",headers,body: body !== undefined ? packMessage(body) : undefined,- signal: controller.signal,- redirect: "error",- });+ redirect: "manual",+ },+ false,+ );- return response;- } catch (error) {- if (error instanceof Error && error.name === "AbortError") {- throw new SIEConnectionError(`Request timeout after ${this.timeout}ms`, "timeout");- }- if (error instanceof TypeError) {- throw connectionErrorFromFetchTypeError(error);- }- throw error;- } finally {- clearTimeout(timeoutId);+ for (let hop = 0; hop < MODAL_CONTINUATION_MAX_HOPS; hop += 1) {+ requireVisibleManualRedirect(response);+ const continuationUrl = modalContinuationUrl(this.baseUrl, response);+ if (!continuationUrl) return response;+ response = await fetchWithinBudget(+ continuationUrl,+ {+ method: "GET",+ headers,+ redirect: "manual",+ },+ true,+ );+ }+ requireVisibleManualRedirect(response);+ if (modalContinuationUrl(this.baseUrl, response)) {+ throw new ProvisioningError(+ `Provisioning result remained in flight after ${MODAL_CONTINUATION_MAX_HOPS} continuation hops`,+ gpu,+ );}+ return response;}/**diff --git a/packages/sie_ts_sdk/src/errors.ts b/packages/sie_ts_sdk/src/errors.tsindex 199ffba86..4c5a8501b 100644--- a/packages/sie_ts_sdk/src/errors.ts+++ b/packages/sie_ts_sdk/src/errors.ts@@ -81,13 +81,22 @@ export class RequestError extends SIEError {* so failures stay correlatable with gateway logs (#3136).*/readonly requestId: string | undefined;+ /** Offending request field from the server error envelope, when known. */+ readonly param: string | null | undefined;- constructor(message: string, code?: string, statusCode?: number, requestId?: string) {+ constructor(+ message: string,+ code?: string,+ statusCode?: number,+ requestId?: string,+ param?: string | null,+ ) {super(message);this.name = "RequestError";this.code = code;this.statusCode = statusCode;this.requestId = requestId;+ this.param = param;}}@@ -111,13 +120,22 @@ export class ServerError extends SIEError {* so failures stay correlatable with gateway logs (#3136).*/readonly requestId: string | undefined;+ /** Offending request field from the server error envelope, when known. */+ readonly param: string | null | undefined;- constructor(message: string, code?: string, statusCode?: number, requestId?: string) {+ constructor(+ message: string,+ code?: string,+ statusCode?: number,+ requestId?: string,+ param?: string | null,+ ) {super(message);this.name = "ServerError";this.code = code;this.statusCode = statusCode;this.requestId = requestId;+ this.param = param;}}@@ -136,12 +154,15 @@ export class ProvisioningError extends SIEError {readonly gpu: string | undefined;/** Suggested retry delay in milliseconds (from server Retry-After header) */readonly retryAfter: number | undefined;+ /** Offending request field from the server error envelope, when known. */+ readonly param: string | null | undefined;- constructor(message: string, gpu?: string, retryAfter?: number) {+ constructor(message: string, gpu?: string, retryAfter?: number, param?: string | null) {super(message);this.name = "ProvisioningError";this.gpu = gpu;this.retryAfter = retryAfter;+ this.param = param;}}@@ -183,12 +204,15 @@ export class LoraLoadingError extends SIEError {readonly lora: string | undefined;/** The model the LoRA was requested for */readonly model: string | undefined;+ /** Offending request field from the server error envelope, when known. */+ readonly param: string | null | undefined;- constructor(message: string, lora?: string, model?: string) {+ constructor(message: string, lora?: string, model?: string, param?: string | null) {super(message);this.name = "LoraLoadingError";this.lora = lora;this.model = model;+ this.param = param;}}@@ -205,11 +229,14 @@ export class LoraLoadingError extends SIEError {export class ModelLoadingError extends SIEError {/** The model that was requested */readonly model: string | undefined;+ /** Offending request field from the server error envelope, when known. */+ readonly param: string | null | undefined;- constructor(message: string, model?: string) {+ constructor(message: string, model?: string, param?: string | null) {super(message);this.name = "ModelLoadingError";this.model = model;+ this.param = param;}}@@ -233,8 +260,11 @@ export class ResourceExhaustedError extends ServerError {/** Number of retry attempts made before giving up */readonly retries: number;- constructor(message: string, options?: { model?: string; retries?: number }) {- super(message, "RESOURCE_EXHAUSTED", 503);+ constructor(+ message: string,+ options?: { model?: string; retries?: number; param?: string | null },+ ) {+ super(message, "RESOURCE_EXHAUSTED", 503, undefined, options?.param);this.name = "ResourceExhaustedError";this.model = options?.model;this.retries = options?.retries ?? 0;@@ -244,9 +274,9 @@ export class ResourceExhaustedError extends ServerError {/*** Error surfaced mid-stream from `streamChatCompletions` / `streamGenerate`.*- * The SSE wire shape includes optional `error: {message, type, param, code}`- * (chat) or `error: {code, message}` (SIE-native generate) on the terminal- * chunk. When the SDK sees such a chunk it does NOT yield the chunk; instead+ * The SSE wire shape includes optional+ * `error: {message, type, param, code, retry_after_s?}` on the terminal chunk.+ * When the SDK sees such a chunk it does NOT yield the chunk; instead* it throws `SIEStreamError`, mirroring the non-streaming `handleError` path* so callers can catch the same way they would for HTTP-level failures.*@@ -260,8 +290,10 @@ export class SIEStreamError extends SIEError {readonly code: string | undefined;/** OpenAI-style error type (e.g. `context_length_exceeded`, `server_error`). */readonly errorType: string | undefined;- /** Offending field name when known (chat shape only). */+ /** Offending field name when known. */readonly param: string | null | undefined;+ /** Validated RESOURCE_EXHAUSTED retry hint, in milliseconds. */+ readonly retryAfter: number | undefined;/*** Gateway request id carried in-band by the error chunk (SIE-native* generate shape only — streamed responses have no terminal headers).@@ -272,7 +304,13 @@ export class SIEStreamError extends SIEError {constructor(message: string,- options?: { code?: string; errorType?: string; param?: string | null; requestId?: string },+ options?: {+ code?: string;+ errorType?: string;+ param?: string | null;+ requestId?: string;+ retryAfter?: number;+ },) {super(message);this.name = "SIEStreamError";@@ -280,6 +318,7 @@ export class SIEStreamError extends SIEError {this.errorType = options?.errorType;this.param = options?.param;this.requestId = options?.requestId;+ this.retryAfter = options?.retryAfter;}}@@ -317,9 +356,10 @@ export class ModelLoadFailedError extends ServerError {errorClass?: string;permanent?: boolean;attempts?: number;+ param?: string | null;},) {- super(message, "MODEL_LOAD_FAILED", 502);+ super(message, "MODEL_LOAD_FAILED", 502, undefined, options?.param);this.name = "ModelLoadFailedError";this.model = options?.model;this.errorClass = options?.errorClass;@@ -345,8 +385,8 @@ export class InputTooLongError extends RequestError {/** The model that was requested */readonly model: string | undefined;- constructor(message: string, options?: { model?: string }) {- super(message, "INPUT_TOO_LONG", 400);+ constructor(message: string, options?: { model?: string; param?: string | null }) {+ super(message, "INPUT_TOO_LONG", 400, undefined, options?.param);this.name = "InputTooLongError";this.model = options?.model;}@@ -400,9 +440,10 @@ export class IncompleteBatchError extends ServerError {model?: string;missingIds?: string[];requestId?: string;+ param?: string | null;},) {- super(message, options.code, 200, options.requestId);+ super(message, options.code, 200, options.requestId, options.param);this.name = "IncompleteBatchError";this.expected = options.expected;this.received = options.received;@@ -492,8 +533,8 @@ export class MalformedChunkError extends SIEError {* Subclass of {@link ServerError} so existing 5xx handlers keep working.*/export class EstimateUnroutableError extends ServerError {- constructor(message: string, code?: string) {- super(message, code, 503);+ constructor(message: string, code?: string, param?: string | null) {+ super(message, code, 503, undefined, param);this.name = "EstimateUnroutableError";}}@@ -518,9 +559,9 @@ export class RateLimitError extends RequestError {constructor(message: string,- options?: { retryAfter?: number; code?: string; requestId?: string },+ options?: { retryAfter?: number; code?: string; requestId?: string; param?: string | null },) {- super(message, options?.code ?? "RATE_LIMIT", 429, options?.requestId);+ super(message, options?.code ?? "RATE_LIMIT", 429, options?.requestId, options?.param);this.name = "RateLimitError";this.retryAfter = options?.retryAfter;}@@ -537,8 +578,8 @@ export class RateLimitError extends RequestError {* Mirrors the Python SDK's `InsufficientCreditsError`.*/export class InsufficientCreditsError extends RequestError {- constructor(message: string, options?: { requestId?: string }) {- super(message, "INSUFFICIENT_CREDITS", 402, options?.requestId);+ constructor(message: string, options?: { requestId?: string; param?: string | null }) {+ super(message, "INSUFFICIENT_CREDITS", 402, options?.requestId, options?.param);this.name = "InsufficientCreditsError";}}@@ -555,8 +596,8 @@ export class InsufficientCreditsError extends RequestError {* Mirrors the Python SDK's `SpendLimitError`.*/export class SpendLimitError extends RequestError {- constructor(message: string, options?: { requestId?: string }) {- super(message, "KEY_SPEND_LIMIT_EXCEEDED", 402, options?.requestId);+ constructor(message: string, options?: { requestId?: string; param?: string | null }) {+ super(message, "KEY_SPEND_LIMIT_EXCEEDED", 402, options?.requestId, options?.param);this.name = "SpendLimitError";}}@@ -574,8 +615,8 @@ export class SpendLimitError extends RequestError {* Mirrors the Python SDK's `AccountInactiveError`.*/export class AccountInactiveError extends RequestError {- constructor(message: string, code?: string, requestId?: string) {- super(message, code, 403, requestId);+ constructor(message: string, code?: string, requestId?: string, param?: string | null) {+ super(message, code, 403, requestId, param);this.name = "AccountInactiveError";}}@@ -594,8 +635,8 @@ export class AccountInactiveError extends RequestError {* Mirrors the Python SDK's `AccountStateUnavailableError`.*/export class AccountStateUnavailableError extends ServerError {- constructor(message: string, requestId?: string) {- super(message, "ACCOUNT_STATE_UNAVAILABLE", 503, requestId);+ constructor(message: string, requestId?: string, param?: string | null) {+ super(message, "ACCOUNT_STATE_UNAVAILABLE", 503, requestId, param);this.name = "AccountStateUnavailableError";}}diff --git a/packages/sie_ts_sdk/src/index.ts b/packages/sie_ts_sdk/src/index.tsindex 41f85fc4f..6f6146c24 100644--- a/packages/sie_ts_sdk/src/index.ts+++ b/packages/sie_ts_sdk/src/index.ts@@ -134,6 +134,7 @@ export type {StreamGenerateOptions,GenerateResult,// Streaming generate (SSE)+ GenerationChunkError,GenerateChunk,// Chat completions (OpenAI-compatible)ChatMessage,diff --git a/packages/sie_ts_sdk/src/internal/parsing.ts b/packages/sie_ts_sdk/src/internal/parsing.tsindex 39e443aaf..fea72fe6f 100644--- a/packages/sie_ts_sdk/src/internal/parsing.ts+++ b/packages/sie_ts_sdk/src/internal/parsing.ts@@ -53,6 +53,7 @@ import { getRetryAfter as getRetryAfterFromHeader } from "./retry.js";const SIE_ERROR_CODE_HEADER = "X-SIE-Error-Code";const REQUEST_ID_HEADER = "x-sie-request-id";+const INVALID_ERROR_MESSAGE = "Request failed";function normalizeErrorCode(code: string | undefined): string | undefined {if (code === "provisioning") return PROVISIONING_ERROR_CODE;@@ -143,6 +144,19 @@ export async function getErrorDetail(return undefined;}+/** Preserve the OpenAI-compatible nullable/string `error.param` contract. */+function errorParamFromDetail(+ detail: Record<string, unknown> | undefined,+): string | null | undefined {+ const param = detail?.param;+ return typeof param === "string" || param === null ? param : undefined;+}++/** Extract a validated nullable/string error parameter from JSON or msgpack. */+export async function getErrorParam(response: Response): Promise<string | null | undefined> {+ return errorParamFromDetail(await getErrorDetail(response));+}+/*** Extract error code from response body (handles both JSON and msgpack)*/@@ -195,6 +209,7 @@ export async function throwIfModelLoadFailed(response: Response, model?: string)errorClass,permanent,attempts,+ param: errorParamFromDetail(detail),});}@@ -218,7 +233,7 @@ export async function throwIfInputTooLong(response: Response, model?: string): Ptypeof detail.message === "string"? detail.message: "Input exceeds the model's maximum token capacity";- throw new InputTooLongError(message, { model });+ throw new InputTooLongError(message, { model, param: errorParamFromDetail(detail) });}/** The one exact path of the cost-estimate dry run (#2435). */@@ -278,7 +293,7 @@ export async function throwIfEstimateUnroutable(response: Response): Promise<voidetail && typeof detail.message === "string"? detail.message: "the active rate book cannot price this request";- throw new EstimateUnroutableError(message, code);+ throw new EstimateUnroutableError(message, code, errorParamFromDetail(detail));}/**@@ -294,12 +309,14 @@ export async function handleError(response: Response, gpu?: string): Promise<nevlet code: string | undefined;let message: string;+ let param: string | null | undefined;if (detail) {const c = detail.code;code = typeof c === "string" ? c : undefined;const m = detail.message;- message = typeof m === "string" ? m : JSON.stringify(detail);+ message = typeof m === "string" ? m : INVALID_ERROR_MESSAGE;+ param = errorParamFromDetail(detail);} else {try {const data = (await response.json()) as Record<string, unknown>;@@ -313,9 +330,11 @@ export async function handleError(response: Response, gpu?: string): Promise<nevcode = typeof data.code === "string" ? data.code : undefined;message = response.statusText;}+ param = errorParamFromDetail(data);} catch {code = undefined;message = response.statusText;+ param = undefined;}}code = response.headers.get(SIE_ERROR_CODE_HEADER) ?? normalizeErrorCode(code);@@ -323,7 +342,7 @@ export async function handleError(response: Response, gpu?: string): Promise<nevif (status === 503 && code === PROVISIONING_ERROR_CODE) {const retryAfter = getRetryAfter(response);- throw new ProvisioningError(message, gpu, retryAfter);+ throw new ProvisioningError(message, gpu, retryAfter, param);}// Rate limit (pass-2 audit B1). Retried on the admission ladder in the@@ -331,7 +350,12 @@ export async function handleError(response: Response, gpu?: string): Promise<nev// covers the terminal paths (streaming, listModels, estimate, …) so a 429 is// always a typed RateLimitError rather than a generic RequestError.if (status === HTTP_TOO_MANY_REQUESTS) {- throw new RateLimitError(message, { retryAfter: getRetryAfter(response), code, requestId });+ throw new RateLimitError(message, {+ retryAfter: getRetryAfter(response),+ code,+ requestId,+ param,+ });}// Terminal credit / account failures (pass-2 audit B3). 402/403 are NEVER@@ -339,34 +363,34 @@ export async function handleError(response: Response, gpu?: string): Promise<nev// first response. Unrecognised 402/403 codes stay generic RequestError.if (status === HTTP_PAYMENT_REQUIRED) {if (code === INSUFFICIENT_CREDITS_ERROR_CODE)- throw new InsufficientCreditsError(message, { requestId });+ throw new InsufficientCreditsError(message, { requestId, param });if (code === KEY_SPEND_LIMIT_EXCEEDED_ERROR_CODE)- throw new SpendLimitError(message, { requestId });+ throw new SpendLimitError(message, { requestId, param });}if (status === HTTP_FORBIDDEN &&(code === ACCOUNT_SUSPENDED_ERROR_CODE || code === ACCOUNT_PENDING_REVIEW_ERROR_CODE)) {- throw new AccountInactiveError(message, code, requestId);+ throw new AccountInactiveError(message, code, requestId, param);}if (status === 503 && code === ACCOUNT_STATE_UNAVAILABLE_ERROR_CODE) {- throw new AccountStateUnavailableError(message, requestId);+ throw new AccountStateUnavailableError(message, requestId, param);}if (status >= HTTP_CLIENT_ERROR_MIN && status <= HTTP_CLIENT_ERROR_MAX) {if (status === 400 && code === "INPUT_TOO_LONG") {// Fallback dispatch — ``model`` is only attached by the helper-style// short-circuit (``throwIfInputTooLong``) on the extract path.- throw new InputTooLongError(message);+ throw new InputTooLongError(message, { param });}- throw new RequestError(message, code, status, requestId);+ throw new RequestError(message, code, status, requestId, param);}if (status >= HTTP_SERVER_ERROR_MIN && status <= HTTP_SERVER_ERROR_MAX) {- throw new ServerError(message, code, status, requestId);+ throw new ServerError(message, code, status, requestId, param);}- throw new ServerError(message, code, status, requestId);+ throw new ServerError(message, code, status, requestId, param);}// Wire format types (what server sends)diff --git a/packages/sie_ts_sdk/src/internal/provisioning.ts b/packages/sie_ts_sdk/src/internal/provisioning.tsindex 6cf63c404..a679c56eb 100644--- a/packages/sie_ts_sdk/src/internal/provisioning.ts+++ b/packages/sie_ts_sdk/src/internal/provisioning.ts@@ -47,6 +47,7 @@ import {} from "./constants.js";import {getErrorCode,+ getErrorParam,getRetryAfter,handleError,readRequestId,@@ -116,15 +117,17 @@ export function nextOomRetryDelay(opts: {elapsedMs: number;provisionTimeoutMs: number;model: string;+ param?: string | null;}): number {- const { retryAfter, oomRetries, maxOomRetries, elapsedMs, provisionTimeoutMs, model } = opts;+ const { retryAfter, oomRetries, maxOomRetries, elapsedMs, provisionTimeoutMs, model, param } =+ opts;const message = `Server resource exhausted after ${oomRetries} retry attempt(s) for model '${model}'`;if (oomRetries >= maxOomRetries || elapsedMs >= provisionTimeoutMs) {- throw new ResourceExhaustedError(message, { model, retries: oomRetries });+ throw new ResourceExhaustedError(message, { model, retries: oomRetries, param });}const delay = computeOomBackoff(retryAfter, oomRetries);if (delay >= provisionTimeoutMs - elapsedMs) {- throw new ResourceExhaustedError(message, { model, retries: oomRetries });+ throw new ResourceExhaustedError(message, { model, retries: oomRetries, param });}return delay;}@@ -179,7 +182,11 @@ export async function admissionRetryDelay(// terminal 429 mapped by `handleError` (#3136).throw new RateLimitError(`Rate limited (429); retry budget (${provisionTimeoutMs}ms) exhausted after ${elapsed}ms`,- { retryAfter, requestId: readRequestId(response) },+ {+ retryAfter,+ requestId: readRequestId(response),+ param: await getErrorParam(response.clone()),+ },);}return delay;@@ -250,6 +257,7 @@ export async function withProvisioningRetry("No capacity available. Server is provisioning.",opts.gpu,getRetryAfter(response),+ await getErrorParam(response.clone()),);}const elapsed = Date.now() - startTime;@@ -258,6 +266,7 @@ export async function withProvisioningRetry(`Provisioning timeout after ${elapsed}ms`,opts.gpu,getRetryAfter(response),+ await getErrorParam(response.clone()),);}const retryAfter = getRetryAfter(response);@@ -268,7 +277,11 @@ export async function withProvisioningRetry(if (errorCode === MODEL_LOADING_ERROR_CODE) {const elapsed = Date.now() - startTime;if (elapsed >= opts.provisionTimeoutMs) {- throw new ModelLoadingError(`Model loading timeout for '${opts.model}'`, opts.model);+ throw new ModelLoadingError(+ `Model loading timeout for '${opts.model}'`,+ opts.model,+ await getErrorParam(response.clone()),+ );}const delay = getRetryAfter(response) ?? MODEL_LOADING_DEFAULT_DELAY;await sleep(Math.min(delay, opts.provisionTimeoutMs - elapsed));@@ -284,6 +297,7 @@ export async function withProvisioningRetry(elapsedMs: Date.now() - startTime,provisionTimeoutMs: opts.provisionTimeoutMs,model: opts.model,+ param: await getErrorParam(response.clone()),});oomRetries += 1;await sleep(delay);@@ -320,6 +334,8 @@ export async function withProvisioningRetry("non-idempotent (retrying could double-bill). Re-issue manually if needed.",await getErrorCode(response.clone()),HTTP_GATEWAY_TIMEOUT,+ readRequestId(response),+ await getErrorParam(response.clone()),);}diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.tsindex ed314b1b6..14c21d7ad 100644--- a/packages/sie_ts_sdk/src/types.ts+++ b/packages/sie_ts_sdk/src/types.ts@@ -140,6 +140,8 @@ export interface RequestMetadata {id?: string;/** Worker-origin immutable release/runtime identity digest. */executionIdentitySha256?: string;+ /** Stable release/deployment binding shared by placement variants. */+ executionBindingSha256?: string;usage?: RequestUsage;/*** Exact committed debit — the authoritative charge for this request.@@ -202,6 +204,8 @@ export interface ModelDims {* under FP8; route SQL-critical traffic to a BF16 bundle via the `sql` alias).*/export interface ModelCapabilities {+ /** Whether the model supports incremental public generation output */+ streaming?: boolean | null;/** Supported grammar kinds: ["json_schema", "regex", "ebnf"] */grammar?: string[];/** Whether the model supports tool / function calling */@@ -1322,6 +1326,16 @@ export interface ChatChunkChoice {logprobs: null;}+/** Typed terminal error carried by a generation SSE chunk. */+export interface GenerationChunkError {+ code: string;+ message: string;+ type?: string;+ param?: string | null;+ /** Authoritative retry hint for RESOURCE_EXHAUSTED, in seconds. */+ retry_after_s?: number | null;+}+/*** One SSE event from `streamChatCompletions`.*@@ -1336,6 +1350,10 @@ export interface ChatCompletionChunk {system_fingerprint: string | null;choices: ChatChunkChoice[];usage?: ChatUsage;+ /** Gateway correlation id carried in-band on terminal errors. */+ request_id?: string;+ /** Populated when the worker / gateway errored mid-stream. */+ error?: GenerationChunkError;}/**@@ -1399,7 +1417,7 @@ export interface GenerateChunk {/** Time-to-first-token, milliseconds. Terminal chunk only. */ttft_ms?: number;/** Populated when the worker / gateway errored mid-stream. */- error?: { code: string; message: string };+ error?: GenerationChunkError;}/**diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex baa4e1ede..945c876d2 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.7.2"; // x-release-please-version+export const SDK_VERSION = "0.7.3"; // x-release-please-versiondiff --git a/packages/sie_ts_sdk/tests/backpressureBilling.test.ts b/packages/sie_ts_sdk/tests/backpressureBilling.test.tsindex 44dc74dca..69d2d7c1d 100644--- a/packages/sie_ts_sdk/tests/backpressureBilling.test.ts+++ b/packages/sie_ts_sdk/tests/backpressureBilling.test.ts@@ -34,8 +34,9 @@ function detailResponse(status: number,code: string,headers: Record<string, string> = {},+ param?: string | null,): Response {- return new Response(JSON.stringify({ detail: { code, message: code.toLowerCase() } }), {+ return new Response(JSON.stringify({ detail: { code, message: code.toLowerCase(), param } }), {status,headers: { "Content-Type": "application/json", ...headers },});@@ -262,7 +263,10 @@ describe("handleError billing/backpressure mapping", () => {[403, "ACCOUNT_PENDING_REVIEW", AccountInactiveError],[503, "ACCOUNT_STATE_UNAVAILABLE", AccountStateUnavailableError],] as const)("maps %s %s", async (status, code, ctor) => {- await expect(handleError(detailResponse(status, code))).rejects.toBeInstanceOf(ctor);+ await expect(handleError(detailResponse(status, code, {}, "account"))).rejects.toMatchObject({+ name: ctor.name,+ param: "account",+ });});it("leaves an unrecognized 403 code as a generic RequestError", async () => {diff --git a/packages/sie_ts_sdk/tests/client.test.ts b/packages/sie_ts_sdk/tests/client.test.tsindex 3c9890cf4..d77178e3d 100644--- a/packages/sie_ts_sdk/tests/client.test.ts+++ b/packages/sie_ts_sdk/tests/client.test.ts@@ -56,6 +56,153 @@ function createMsgpackResponse(});}+type TerminalOperation = "encode" | "score" | "extract";++function terminalPayload(operation: TerminalOperation): Record<string, unknown> {+ if (operation === "encode") {+ return { model: "m", items: [{ dense: { values: new Float32Array([0.5]) } }] };+ }+ if (operation === "score") {+ return { model: "m", scores: [{ item_id: "0", score: 0.5, rank: 0 }] };+ }+ return { model: "m", items: [{ entities: [] }] };+}++async function invokeTerminal(client: SIEClient, operation: TerminalOperation): Promise<unknown> {+ if (operation === "encode") return client.encode("m", { text: "input" });+ if (operation === "score") return client.score("m", { text: "query" }, [{ text: "candidate" }]);+ return client.extract("m", { text: "input" }, { labels: ["entity"] });+}++describe("SIEClient terminal Modal continuations", () => {+ beforeEach(() => {+ mockFetch.mockReset();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it.each(["encode", "score", "extract"] as const)(+ "consumes a same-origin %s continuation by authenticated MsgPack GET",+ async (operation) => {+ const path = `/v1/${operation}/m?__modal_attempt_token=opaque`;+ mockFetch+ .mockResolvedValueOnce(new Response(null, { status: 303, headers: { Location: path } }))+ .mockResolvedValueOnce(createMsgpackResponse(terminalPayload(operation)));++ const client = new SIEClient("https://gateway.example.test", { apiKey: "secret" });+ await invokeTerminal(client, operation);++ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[0]?.[1]).toMatchObject({ method: "POST", redirect: "manual" });+ expect(mockFetch.mock.calls[1]?.[0]).toBe(`https://gateway.example.test${path}`);+ expect(mockFetch.mock.calls[1]?.[1]).toMatchObject({ method: "GET", redirect: "manual" });+ const headers = mockFetch.mock.calls[1]?.[1]?.headers as Record<string, string>;+ expect(headers.Accept).toBe("application/msgpack");+ expect(headers.Authorization).toBe("Bearer secret");+ },+ );++ it("preserves MsgPack credentials across every continuation hop", async () => {+ mockFetch+ .mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: "/result?__modal_attempt_token=one" },+ }),+ )+ .mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: "/result?__modal_attempt_token=two" },+ }),+ )+ .mockResolvedValueOnce(createMsgpackResponse(terminalPayload("encode")));++ const client = new SIEClient("https://gateway.example.test", { apiKey: "secret" });+ await client.encode("m", { text: "input" });++ expect(mockFetch).toHaveBeenCalledTimes(3);+ const signals = mockFetch.mock.calls.map((call) => (call[1] as RequestInit).signal);+ expect(signals.every((signal) => signal instanceof AbortSignal)).toBe(true);+ expect(new Set(signals).size).toBe(signals.length);+ for (const call of mockFetch.mock.calls.slice(1)) {+ const init = call[1] as RequestInit;+ const headers = init.headers as Record<string, string>;+ expect(init).toMatchObject({ method: "GET", redirect: "manual" });+ expect(headers.Accept).toBe("application/msgpack");+ expect(headers.Authorization).toBe("Bearer secret");+ }+ });++ it("does not replay the POST when continuation retrieval fails", async () => {+ mockFetch+ .mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: "/result?__modal_attempt_token=opaque" },+ }),+ )+ .mockRejectedValueOnce(new TypeError("fetch failed"));++ const client = new SIEClient("https://gateway.example.test", {+ provisionTimeout: 60_000,+ });++ await expect(+ client.encode("m", { text: "input" }, { waitForCapacity: true }),+ ).rejects.toBeInstanceOf(SIEConnectionError);+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[0]?.[1].method).toBe("POST");+ expect(mockFetch.mock.calls[1]?.[1].method).toBe("GET");+ });++ it("refuses a continuation GET after the provisioning budget expires", async () => {+ vi.spyOn(Date, "now").mockReturnValueOnce(0).mockReturnValueOnce(0).mockReturnValue(60_001);+ mockFetch.mockResolvedValueOnce(+ new Response(null, {+ status: 303,+ headers: { Location: "/result?__modal_attempt_token=opaque" },+ }),+ );+ const client = new SIEClient("https://gateway.example.test", {+ provisionTimeout: 60_000,+ });++ await expect(client.encode("m", { text: "input" })).rejects.toBeInstanceOf(ProvisioningError);+ expect(mockFetch).toHaveBeenCalledOnce();+ });++ it("fails closed when browser Fetch hides a manual redirect", async () => {+ mockFetch.mockResolvedValueOnce({ type: "opaqueredirect" } as Response);+ const client = new SIEClient("https://gateway.example.test");++ await expect(client.encode("m", { text: "input" })).rejects.toMatchObject({+ name: "SIEConnectionError",+ kind: "other",+ });+ expect(mockFetch).toHaveBeenCalledOnce();+ });++ it("raises ProvisioningError when the continuation hop limit is exhausted", async () => {+ mockFetch.mockImplementation(async () =>+ Promise.resolve(+ new Response(null, {+ status: 303,+ headers: { Location: "/result?__modal_attempt_token=opaque" },+ }),+ ),+ );+ const client = new SIEClient("https://gateway.example.test");++ await expect(client.encode("m", { text: "input" })).rejects.toThrow(+ /remained in flight after 20 continuation hops/,+ );+ expect(mockFetch).toHaveBeenCalledTimes(21);+ });+});+describe("SIEClient construction", () => {beforeEach(() => {mockFetch.mockClear();@@ -290,6 +437,7 @@ describe("SIEClient.encode() - basic usage", () => {{"x-sie-request-id": "req-encode","x-sie-execution-identity-sha256": "a".repeat(64),+ "x-sie-execution-binding-sha256": "b".repeat(64),"x-sie-units-input-tokens": "11","x-sie-units-pairs": "2","x-sie-units-images": "1",@@ -309,6 +457,7 @@ describe("SIEClient.encode() - basic usage", () => {expect(results[0]?.request).toEqual({id: "req-encode",executionIdentitySha256: "a".repeat(64),+ executionBindingSha256: "b".repeat(64),usage: {inputTokens: 11,pairs: 2,@@ -329,6 +478,7 @@ describe("SIEClient.encode() - basic usage", () => {createMsgpackResponse({ items: [{ dense: { values: new Float32Array([0.1]) } }] }, 200, {"x-sie-request-id": "réq-bad","x-sie-execution-identity-sha256": "A".repeat(64),+ "x-sie-execution-binding-sha256": "B".repeat(64),"x-sie-units-input-tokens": "01","x-sie-units-pairs": "2","x-sie-credits-debited": "9007199254740992",diff --git a/packages/sie_ts_sdk/tests/generate.test.ts b/packages/sie_ts_sdk/tests/generate.test.tsindex 932682a23..42ffa4349 100644--- a/packages/sie_ts_sdk/tests/generate.test.ts+++ b/packages/sie_ts_sdk/tests/generate.test.ts@@ -507,7 +507,13 @@ describe("SIEClient.generate retry semantics (B1c)", () => {mockFetch.mockResolvedValueOnce(new Response(- JSON.stringify({ error: { code: "RESOURCE_EXHAUSTED", message: "out of memory" } }),+ JSON.stringify({+ error: {+ code: "RESOURCE_EXHAUSTED",+ message: "out of memory",+ param: "max_new_tokens",+ },+ }),{ status: 503, headers: { "Content-Type": "application/json" } },),)@@ -540,18 +546,26 @@ describe("SIEClient.generate retry semantics (B1c)", () => {mockFetch.mockImplementation(() =>Promise.resolve(new Response(- JSON.stringify({ error: { code: "RESOURCE_EXHAUSTED", message: "out of memory" } }),+ JSON.stringify({+ error: {+ code: "RESOURCE_EXHAUSTED",+ message: "out of memory",+ param: "max_new_tokens",+ },+ }),{ status: 503, headers: { "Content-Type": "application/json" } },),),);const promise = client.generate("m", "hi", { maxNewTokens: 8 });- const expectation = expect(promise).rejects.toThrow(ResourceExhaustedError);+ const errorPromise = promise.catch((error: unknown) => error);// Max backoff schedule (no Retry-After): ≤5s, ≤10s, ≤20s → ≤35s total.await vi.advanceTimersByTimeAsync(35_000);- await expectation;+ const error = await errorPromise;+ expect(error).toBeInstanceOf(ResourceExhaustedError);+ expect(error).toMatchObject({ param: "max_new_tokens" });// RESOURCE_EXHAUSTED_MAX_RETRIES = 3 → 4 requests (initial + 3 retries).expect(mockFetch).toHaveBeenCalledTimes(4);@@ -568,18 +582,27 @@ describe("SIEClient.generate retry semantics (B1c)", () => {mockFetch.mockResolvedValue(new Response(JSON.stringify({ error: { code: "GATEWAY_TIMEOUT", message: "result deadline" } }),- { status: 504, headers: { "Content-Type": "application/json" } },+ {+ status: 504,+ headers: {+ "Content-Type": "application/json",+ "x-sie-request-id": "req-generate-504",+ },+ },),);await expect(client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),- ).rejects.toThrow(/non-idempotent/);- await expect(- client.generate("m", "hi", { maxNewTokens: 8, waitForCapacity: true }),- ).rejects.toBeInstanceOf(ServerError);-- // Crucially: one call per generate() invocation, no retry.- expect(mockFetch).toHaveBeenCalledTimes(2);+ ).rejects.toMatchObject({+ name: "ServerError",+ code: "GATEWAY_TIMEOUT",+ statusCode: 504,+ requestId: "req-generate-504",+ message: expect.stringMatching(/non-idempotent/),+ } satisfies Partial<ServerError>);++ // Crucially: the generate() invocation is not retried.+ expect(mockFetch).toHaveBeenCalledTimes(1);});});diff --git a/packages/sie_ts_sdk/tests/inputTooLong.test.ts b/packages/sie_ts_sdk/tests/inputTooLong.test.tsindex 9158e168f..4ba69ed2b 100644--- a/packages/sie_ts_sdk/tests/inputTooLong.test.ts+++ b/packages/sie_ts_sdk/tests/inputTooLong.test.ts@@ -18,10 +18,13 @@ const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);function inputTooLongResponse(message = "Input exceeds capacity (4096 tokens)"): Response {- return new Response(JSON.stringify({ detail: { code: "INPUT_TOO_LONG", message } }), {- status: 400,- headers: { "Content-Type": "application/json" },- });+ return new Response(+ JSON.stringify({ detail: { code: "INPUT_TOO_LONG", message, param: "input" } }),+ {+ status: 400,+ headers: { "Content-Type": "application/json" },+ },+ );}function validationErrorResponse(): Response {@@ -86,6 +89,7 @@ describe("400 INPUT_TOO_LONG short-circuit", () => {expect(e.code).toBe("INPUT_TOO_LONG");expect(e.statusCode).toBe(400);expect(e.message).toBe("Too many tokens");+ expect(e.param).toBe("input");}});@@ -132,6 +136,7 @@ describe("handleError dispatch (direct)", () => {code: "INPUT_TOO_LONG",statusCode: 400,message: "Too many tokens",+ param: "input",});});diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.tsindex 977570d57..deed7fbc1 100644--- a/packages/sie_ts_sdk/tests/internal.test.ts+++ b/packages/sie_ts_sdk/tests/internal.test.ts@@ -19,6 +19,7 @@ import {parseGpuParam,} from "../src/internal/parsing.js";import { computeBackoffWithJitter, getRetryAfter } from "../src/internal/retry.js";+import { packMessage } from "../src/msgpack.js";describe("Default provision timeout", () => {it("matches the Python SDK's DEFAULT_PROVISION_TIMEOUT_S (900s)", () => {@@ -261,6 +262,33 @@ describe("handleError (gateway / FastAPI bodies)", () => {});});+ it("uses a non-sensitive fallback for a non-string nested error message", async () => {+ const res = new Response(+ JSON.stringify({+ detail: {+ code: "INTERNAL_ERROR",+ message: { private: "message-secret" },+ param: "param-secret",+ },+ }),+ { status: 500, headers: { "Content-Type": "application/json" } },+ );++ try {+ await handleError(res);+ throw new Error("expected handleError to throw");+ } catch (error) {+ expect(error).toMatchObject({+ name: "ServerError",+ message: "Request failed",+ code: "INTERNAL_ERROR",+ param: "param-secret",+ });+ expect((error as Error).message).not.toContain("message-secret");+ expect((error as Error).message).not.toContain("param-secret");+ }+ });+it("carries the x-sie-request-id header onto typed errors (#3136)", async () => {const res = new Response(JSON.stringify({@@ -391,6 +419,7 @@ describe("handleError (gateway / FastAPI bodies)", () => {message: 'field "model" is required',code: "invalid_request",statusCode: 400,+ param: "model",});});@@ -411,6 +440,36 @@ describe("handleError (gateway / FastAPI bodies)", () => {message: "queue unavailable",code: "transport_failure",statusCode: 503,+ param: null,+ });+ });++ it("preserves nullable/string param from msgpack and rejects other types", async () => {+ const msgpack = new Response(+ packMessage({+ error: {+ message: "bad sampling field",+ code: "unsupported_field",+ param: "top_k",+ },+ }),+ { status: 400, headers: { "Content-Type": "application/msgpack" } },+ );+ await expect(handleError(msgpack)).rejects.toMatchObject({+ name: "RequestError",+ code: "unsupported_field",+ param: "top_k",+ });++ const malformed = new Response(+ JSON.stringify({+ error: { message: "bad field", code: "unsupported_field", param: { field: "top_k" } },+ }),+ { status: 400, headers: { "Content-Type": "application/json" } },+ );+ await expect(handleError(malformed)).rejects.toMatchObject({+ name: "RequestError",+ param: undefined,});});diff --git a/packages/sie_ts_sdk/tests/streaming.test.ts b/packages/sie_ts_sdk/tests/streaming.test.tsindex af40dca31..1cbd7902b 100644--- a/packages/sie_ts_sdk/tests/streaming.test.ts+++ b/packages/sie_ts_sdk/tests/streaming.test.ts@@ -13,6 +13,7 @@ import {RequestError,SIEConnectionError,SIEStreamError,+ type ServerError,} from "../src/errors.js";import type { ChatCompletionChunk, GenerateChunk } from "../src/types.js";import { MINIMAL_JPEG_BASE64, MINIMAL_JPEG_BYTES } from "./fixtures.js";@@ -273,12 +274,74 @@ describe("SIEClient.streamChatCompletions", () => {expect(streamErr.code).toBe("context_exceeded");expect(streamErr.errorType).toBe("context_length_exceeded");expect(streamErr.message).toBe("prompt too long");+ expect(streamErr.param).toBeNull();// Pre-#3136 gateways omit request_id on chat error chunks; the SDK// must tolerate its absence.expect(streamErr.requestId).toBeUndefined();}});+ it("drops a malformed chat stream error param", async () => {+ const errorChunkBody = {+ id: "chatcmpl-x",+ object: "chat.completion.chunk",+ created: 1_700_000_000,+ model: "m",+ system_fingerprint: null,+ choices: [],+ error: {+ message: "bad request",+ type: "invalid_request_error",+ param: { private: "must-not-surface" },+ code: "invalid_request",+ },+ };+ mockFetch.mockResolvedValueOnce(sseResponse([JSON.stringify(errorChunkBody)]));++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamChatCompletions({+ model: "m",+ messages: [{ role: "user", content: "hi" }],+ });++ await expect(gen.next()).rejects.toMatchObject({+ name: "SIEStreamError",+ param: undefined,+ });+ });++ it("exposes a validated RESOURCE_EXHAUSTED retry hint on chat stream errors", async () => {+ const errorChunkBody: ChatCompletionChunk = {+ id: "chatcmpl-x",+ object: "chat.completion.chunk",+ created: 1_700_000_000,+ model: "m",+ system_fingerprint: null,+ choices: [],+ error: {+ message: "capacity unavailable",+ type: "server_error",+ code: "RESOURCE_EXHAUSTED",+ retry_after_s: 12,+ },+ };+ mockFetch.mockResolvedValueOnce(sseResponse([JSON.stringify(errorChunkBody)]));++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamChatCompletions({+ model: "m",+ messages: [{ role: "user", content: "hi" }],+ });++ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ expect((err as SIEStreamError).retryAfter).toBe(12_000);+ }+ });+it("surfaces the in-band gateway request id on chat error chunks (#3136)", async () => {// The chat error chunk now carries the gateway request id as an additive// top-level member (the `chatcmpl-*` id is not the correlation key gateway@@ -517,7 +580,7 @@ describe("SIEClient.streamGenerate", () => {generateChunk(0, "", {done: true,finish_reason: "error",- error: { code: "cancelled", message: "client closed" },+ error: { code: "unsupported_field", message: "top_k is unavailable", param: "top_k" },}),]),);@@ -530,12 +593,105 @@ describe("SIEClient.streamGenerate", () => {throw new Error("expected SIEStreamError");} catch (err) {expect(err).toBeInstanceOf(SIEStreamError);- expect((err as SIEStreamError).code).toBe("cancelled");- expect((err as SIEStreamError).message).toBe("client closed");+ expect((err as SIEStreamError).code).toBe("unsupported_field");+ expect((err as SIEStreamError).message).toBe("top_k is unavailable");+ expect((err as SIEStreamError).param).toBe("top_k");expect((err as SIEStreamError).requestId).toBe("req-1");}});+ it("drops a malformed native stream error param", async () => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([+ JSON.stringify({+ request_id: "req-1",+ seq: 0,+ text_delta: "",+ done: true,+ finish_reason: "error",+ error: {+ code: "invalid_request",+ message: "bad request",+ param: ["must-not-surface"],+ },+ }),+ ]),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });++ await expect(gen.next()).rejects.toMatchObject({+ name: "SIEStreamError",+ param: undefined,+ });+ });++ it("exposes a validated RESOURCE_EXHAUSTED retry hint on native stream errors", async () => {+ mockFetch.mockResolvedValueOnce(+ sseResponse([+ generateChunk(0, "", {+ done: true,+ finish_reason: "error",+ error: {+ code: "RESOURCE_EXHAUSTED",+ message: "capacity unavailable",+ retry_after_s: 12,+ },+ }),+ ]),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });+ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ expect((err as SIEStreamError).retryAfter).toBe(12_000);+ }+ });++ it.each([+ ["missing", "RESOURCE_EXHAUSTED", undefined],+ ["null", "RESOURCE_EXHAUSTED", null],+ ["boolean", "RESOURCE_EXHAUSTED", true],+ ["fractional", "RESOURCE_EXHAUSTED", 12.5],+ ["string", "RESOURCE_EXHAUSTED", "12"],+ ["below-domain", "RESOURCE_EXHAUSTED", 0],+ ["above-domain", "RESOURCE_EXHAUSTED", 61],+ ["wrong-code", "MODEL_LOADING", 12],+ ])("drops a %s native retry hint", async (_label, code, retryAfterSeconds) => {+ const error: Record<string, unknown> = {+ code,+ message: "capacity unavailable",+ };+ if (retryAfterSeconds !== undefined) error.retry_after_s = retryAfterSeconds;+ mockFetch.mockResolvedValueOnce(+ sseResponse([+ JSON.stringify({+ request_id: "req-1",+ seq: 0,+ text_delta: "",+ done: true,+ finish_reason: "error",+ error,+ }),+ ]),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });+ try {+ await gen.next();+ throw new Error("expected SIEStreamError");+ } catch (err) {+ expect(err).toBeInstanceOf(SIEStreamError);+ expect((err as SIEStreamError).retryAfter).toBeUndefined();+ }+ });+it("surfaces the empty_model_output terminal code and request id (#3136)", async () => {// PR #3139: a stream that ends with no meaningful visible output carries// error_code="empty_model_output" on the terminal chunk. The caller must@@ -730,6 +886,32 @@ describe("SIEClient.streamGenerate", () => {}});+ it("preserves the request id on a terminal streaming 504", async () => {+ mockFetch.mockResolvedValueOnce(+ new Response(+ JSON.stringify({ error: { code: "GATEWAY_TIMEOUT", message: "result deadline" } }),+ {+ status: 504,+ headers: {+ "Content-Type": "application/json",+ "x-sie-request-id": "req-stream-504",+ },+ },+ ),+ );++ const client = new SIEClient("http://localhost:8080");+ const gen = client.streamGenerate("m", "hi", { maxNewTokens: 8 });++ await expect(gen.next()).rejects.toMatchObject({+ name: "ServerError",+ code: "GATEWAY_TIMEOUT",+ statusCode: 504,+ requestId: "req-stream-504",+ } satisfies Partial<ServerError>);+ expect(mockFetch).toHaveBeenCalledTimes(1);+ });+// BUG 13b (MEDIUM): the streaming path must retry SAFE pre-execution// model-loading signals before opening the stream — parallel to generate().it("retries 503 MODEL_LOADING then streams the 200 when waitForCapacity:true (BUG 13b)", async () => {diff --git a/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.ts b/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.tsindex 518ea6938..e295c0a98 100644--- a/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.ts+++ b/packages/sie_ts_sdk/tests/typecheck/model-info-nullable.ts@@ -36,5 +36,15 @@ const modelWithExplicitNulls: ModelInfo = {aliases: [],};+const modelWithExplicitNullStreaming: ModelInfo = {+ name: "Qwen/Qwen3-4B-Instruct",+ loaded: true,+ inputs: ["text"],+ outputs: ["text"],+ aliases: [],+ capabilities: { streaming: null },+};+void wireWithExplicitNulls;void modelWithExplicitNulls;+void modelWithExplicitNullStreaming;diff --git a/packages/sie_ts_sdk/tests/types.test.ts b/packages/sie_ts_sdk/tests/types.test.tsindex 67930b7d7..19ea9c60e 100644--- a/packages/sie_ts_sdk/tests/types.test.ts+++ b/packages/sie_ts_sdk/tests/types.test.ts@@ -12,11 +12,13 @@import { describe, expect, it } from "vitest";import type {AudioInput,+ ChatCompletionChunk,DocumentInput,EncodeResult,Entity,ExtractItem,ExtractResult,+ GenerateChunk,Item,ModelCapabilities,ModelInfo,@@ -125,6 +127,36 @@ describe("Item creation - common user patterns", () => {});});+describe("Generation SSE error types", () => {+ it("represents the additive retry hint on chat and native chunks", () => {+ const error = {+ code: "RESOURCE_EXHAUSTED",+ message: "capacity unavailable",+ retry_after_s: 12,+ };+ const generate: GenerateChunk = {+ request_id: "req-generate",+ seq: 0,+ text_delta: "",+ done: true,+ error,+ };+ const chat: ChatCompletionChunk = {+ id: "chatcmpl-1",+ object: "chat.completion.chunk",+ created: 0,+ model: "m",+ system_fingerprint: null,+ choices: [],+ request_id: "req-chat",+ error,+ };++ expect(generate.error?.retry_after_s).toBe(12);+ expect(chat.error?.retry_after_s).toBe(12);+ });+});+describe("EncodeResult - working with embeddings", () => {it("provides dense embeddings as Float32Array", () => {// User scenario: "I need to store embeddings in a vector database"@@ -421,6 +453,7 @@ describe("ModelInfo - model discovery", () => {it("surfaces generation capabilities for code/sql/guard discovery", () => {// User scenario: "Show generation models that support text-to-SQL"const capabilities: ModelCapabilities = {+ streaming: false,grammar: ["json_schema", "regex"],tools: true,lora_adapters: ["sql-lora"],@@ -439,10 +472,14 @@ describe("ModelInfo - model discovery", () => {};expect(model.capabilities?.code).toBe(true);+ expect(model.capabilities?.streaming).toBe(false);expect(model.capabilities?.sql).toBe(true);expect(model.capabilities?.guard).toBe(false);expect(model.capabilities?.grammar).toEqual(["json_schema", "regex"]);expect(model.capabilities?.profile_lora_adapters?.default).toEqual(["sql-lora"]);++ const gatewayNullableCapabilities: ModelCapabilities = { streaming: null };+ expect(gatewayNullableCapabilities.streaming).toBeNull();});});diff --git a/telemetry/README.md b/telemetry/README.mdindex 0df561dae..b39de7b25 100644--- a/telemetry/README.md+++ b/telemetry/README.md@@ -67,6 +67,15 @@ safe completion log that belong to that one semantic event. The request pathstill calls the facade only once. It must never call a Prometheus client and anOTel client for the same event.+The sampled `inference.request.completed` log schema v2 carries the canonical+model, machine profile, request duration, admission outcome, HTTP outcome, and+operation. It does not carry account, WorkOS user, API-key, request, contact,+or payload identifiers. Durable per-account product events belong to the+authenticated control-plane analytics export, not the Better Stack pipeline.+Collectors accept schema v1 only while older gateway pods drain during a+rolling update; they preserve its version and never relabel an incomplete v1+record as v2.+Every deployment uses the same application path: OTel instruments and logrecords leave the process through OTLP. Prometheus is a collector exporter, notan application instrumentation API. The bundled OSS/Kubernetes collectordiff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex 585466d82..98e4b0e88 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -1,5 +1,5 @@schema_version: 1-contract_version: "2026-08-14"+contract_version: "2026-08-27"# This is the machine-readable telemetry source of truth. A request path emits# one typed semantic event; the owning facade is the only code allowed to turn@@ -696,6 +696,7 @@ traces:enums:operation: [encode, score, extract, embeddings, moderations, generate, other]activity_window: [1h, 24h]+ signup_review_status: [pending, approved, rejected, other]launch_credit_status: [pending, approved, rejected, other]request_outcome: [success, redirect, client_error, server_error, other]admission_outcome:@@ -969,6 +970,8 @@ attribute_sets:operation: operationcontrol_plane_activity:window: activity_window+ control_plane_signup_review:+ status: signup_review_statuscontrol_plane_launch_credit:status: launch_credit_statusgateway_request:@@ -1323,6 +1326,14 @@ metrics:attributes: noneprometheus_name: sie_control_plane_signup_activatedexport: [otlp]+ - name: sie.control_plane.signup.reviews+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{account}"+ attributes: control_plane_signup_review+ prometheus_name: sie_control_plane_signup_reviews+ export: [otlp]- name: sie.control_plane.starter.creditsowner: control_planefacade_event: control_plane.aggregate_snapshot@@ -1331,6 +1342,22 @@ metrics:attributes: noneprometheus_name: sie_control_plane_starter_creditsexport: [otlp]+ - name: sie.control_plane.starter.grants+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{grant}"+ attributes: control_plane_activity+ prometheus_name: sie_control_plane_starter_grants+ export: [otlp]+ - name: sie.control_plane.starter.grant.limit+ owner: control_plane+ facade_event: control_plane.aggregate_snapshot+ type: gauge+ unit: "{grant}"+ attributes: control_plane_activity+ prometheus_name: sie_control_plane_starter_grant_limit+ export: [otlp]- name: sie.control_plane.terminal.requestsowner: control_planefacade_event: control_plane.aggregate_snapshot@@ -2556,15 +2583,20 @@ logs:sampling: enclosing_trace_sampledattributes:event.name: inference.request.completed- event.schema.version: "1"+ event.schema.version: "2"operation: operationoutcome: request_outcomehttp.status_code: http.status_code+ model: canonical_model_or_other+ machine_profile: canonical_machine_profile+ duration_ms: request_duration_ms+ admission_outcome: bounded_admission_outcomecorrelation: [trace_id, span_id]export: [structured_stdout, otlp]log_processing:declared_events_only: true+ accepted_schema_versions: ["1", "2"]helm_receiver_binding:receiver: gatewayother_receivers: reject@@ -2576,6 +2608,7 @@ log_processing:service.version: producer_optionalforbidden_metric_attributes:+ - account_id- tenant_id- organization_id- api_key_id@@ -2591,6 +2624,10 @@ forbidden_metric_attributes:forbidden_managed_log_fields:- authorization- api_key+ - api_key_id+ - account_id+ - workos_user_id- prompt- document- embeddingdiff --git a/uv.lock b/uv.lockindex 50d2dba9f..d5daf67f7 100644--- a/uv.lock+++ b/uv.lock@@ -4506,12 +4506,12 @@ dev = [[[package]]name = "sie-audio-prep"-version = "0.7.2"+version = "0.7.3"source = { editable = "packages/sie_audio_prep" }[[package]]name = "sie-chroma"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -4591,7 +4591,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -4616,7 +4616,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -4641,7 +4641,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -4668,7 +4668,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -4695,7 +4695,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -4722,7 +4722,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -4788,7 +4788,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -4811,7 +4811,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.7.2"+version = "0.7.3"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -4868,7 +4868,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.7.2"+version = "0.7.3"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -4997,7 +4997,7 @@ dev = [][[package]]name = "sie-weaviate"-version = "0.7.2"+version = "0.7.3"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },