Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

perf(sparse): pool before the sparse activation and keep doc-v3 batches at full size (#642)

svonava9075c1f6373f
diff --git a/packages/sie_config/src/sie_config/model_config.schema.json b/packages/sie_config/src/sie_config/model_config.schema.json
index bde61c193..57d4ae9e4 100644
--- a/packages/sie_config/src/sie_config/model_config.schema.json
+++ b/packages/sie_config/src/sie_config/model_config.schema.json
@@ -252,6 +252,18 @@
"additionalProperties": false,
"description": "Per-model adaptive batching overrides.\n\nAll fields are optional. None means inherit from engine config or parent\nprofile. This enables fieldwise merge: a child profile can override one\nfield while inheriting the rest from the parent or engine defaults.",
"properties": {
+ "enabled": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Enabled"
+ },
"target_p50_ms": {
"anyOf": [
{
diff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml
index d199bf95d..bdf4c87a1 100644
--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml
+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-distill.yaml
@@ -18,6 +18,12 @@ max_sequence_length: 512
profiles:
default:
max_batch_tokens: 16384
+ # Document expansion is bulk work. Under load the adaptive controller sees
+ # request latency (queue time included) above its target and cuts the batch
+ # budget to a quarter, which made document expansion about 1.6x slower on an
+ # H100; this profile keeps the fixed 16,384-token budget instead.
+ adaptive_batching:
+ enabled: false
compute_precision: null
adapter_path: sie_server.adapters.splade_flash.adapter:SPLADEFlashAdapter
adapter_options:
diff --git a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-gte.yaml b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-gte.yaml
index 75280980a..70bd0659e 100644
--- a/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-gte.yaml
+++ b/packages/sie_server/models/opensearch-project__opensearch-neural-sparse-encoding-doc-v3-gte.yaml
@@ -18,6 +18,12 @@ max_sequence_length: 512
profiles:
default:
max_batch_tokens: 16384
+ # Document expansion is bulk work. Under load the adaptive controller sees
+ # request latency (queue time included) above its target and cuts the batch
+ # budget to a quarter, which made document expansion about 1.6x slower on an
+ # H100; this profile keeps the fixed 16,384-token budget instead.
+ adaptive_batching:
+ enabled: false
compute_precision: null
adapter_path: sie_server.adapters.gte_sparse_flash:GTESparseFlashAdapter
adapter_options:
diff --git a/packages/sie_server/src/sie_server/adapters/_sparse_rows.py b/packages/sie_server/src/sie_server/adapters/_sparse_rows.py
new file mode 100644
index 000000000..47002ae26
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/_sparse_rows.py
@@ -0,0 +1,37 @@
+"""Turn pooled ``[batch, vocab]`` sparse weights into per-row ``SparseVector`` outputs.
+
+The rows are compacted on the device, so only the per-row counts and the
+nonzero entries cross to the host, instead of the whole ``[batch, vocab]``
+matrix followed by a per-row ``numpy.where``. (``nonzero()`` synchronizes with
+the device, since its output size depends on the data; copying to the host
+would anyway.) The result is identical to that path: each row's
+indices are ascending ``int32`` and its values are the ``float32`` weights.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import torch
+
+from sie_server.core.inference_output import SparseVector
+
+
+def sparse_rows(weights: torch.Tensor) -> list[SparseVector]:
+ """The strictly positive entries of each row of ``weights`` (``[batch, vocab]``)."""
+ if weights.shape[0] == 0:
+ return []
+ mask = weights > 0
+ counts = mask.sum(dim=1)
+ # nonzero() walks the matrix in row-major order, so each row's columns come
+ # out ascending; the values are gathered at the same coordinates.
+ rows, cols = mask.nonzero(as_tuple=True)
+ columns = cols.to(torch.int32)
+ values = weights[rows, cols].float()
+ counts_host = counts.cpu().numpy()
+ columns_host = columns.cpu().numpy()
+ values_host = values.cpu().numpy()
+ bounds = np.cumsum(counts_host)[:-1]
+ return [
+ SparseVector(indices=indices, values=row_values)
+ for indices, row_values in zip(np.split(columns_host, bounds), np.split(values_host, bounds), strict=True)
+ ]
diff --git a/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
index ff19e1a2d..97eccd88e 100644
--- a/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gte_sparse_flash/__init__.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import importlib.util
+import itertools
import logging
from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast
@@ -8,6 +9,7 @@ import numpy as np
import torch
from sie_server.adapters._flash_base import FlashBaseAdapter
+from sie_server.adapters._sparse_rows import sparse_rows
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecision
from sie_server.adapters._utils import (
@@ -236,11 +238,18 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Inference-free query encoding via IDF lookup (doc-* checkpoint pattern)
if is_query and self._idf is not None:
- return self._encode_query_idf(texts, is_query)
-
- if self._use_flash:
- return self._encode_flash(texts, is_query)
- return self._encode_native(texts, is_query)
+ output = self._encode_query_idf(texts, is_query)
+ elif self._use_flash:
+ output = self._encode_flash(texts, is_query)
+ else:
+ return self._encode_native(texts, is_query)
+ # The token counts this adapter just produced are the metering counts
+ # (``count_input_tokens`` re-tokenizes each item's text the same way)
+ # only when no template changed the text; otherwise leave metering to
+ # that hook, as before, instead of tokenizing every document twice.
+ if any(text != item.text for text, item in zip(texts, items, strict=True)):
+ output.extra.pop("input_token_counts", None)
+ return output
def _encode_native(self, texts: list[str], is_query: bool) -> EncodeOutput:
"""Encode using native forward pass (for CPU or fallback)."""
@@ -304,20 +313,16 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
- # Pack input_ids into a single 1-D tensor
- input_ids_packed = torch.tensor(
- [tok_id for ids in batch_encoding["input_ids"] for tok_id in ids],
- dtype=torch.long,
- device=self._device,
+ # Pack input_ids and cu_seqlens on the host: one copy each
+ flat_ids = np.fromiter(
+ itertools.chain.from_iterable(batch_encoding["input_ids"]), dtype=np.int64, count=total_tokens
)
-
- # Build cu_seqlens using cumsum
- cu_seqlens = torch.zeros(len(texts) + 1, dtype=torch.int32, device=self._device)
- cu_seqlens[1:] = torch.tensor(seq_lengths, dtype=torch.int32, device=self._device).cumsum(0)
+ input_ids_packed = torch.from_numpy(flat_ids).to(self._device)
+ cu_seqlens = torch.from_numpy(np.concatenate(([0], np.cumsum(seq_lengths))).astype(np.int32)).to(self._device)
with torch.inference_mode():
- # Build position IDs for RoPE
- position_ids = self._build_position_ids(cu_seqlens)
+ # Build position IDs for RoPE (the host-known total avoids a device sync)
+ position_ids = self._build_position_ids(cu_seqlens, total_tokens=total_tokens)
# Compute RoPE cos/sin
cos, sin = self._compute_rope(position_ids, max_seqlen)
@@ -333,21 +338,26 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Run MLM head
logits = self._model.lm_head(hidden) # [total_tokens, V]
- # Compute activation weights on full tensor
- weights = self._sparse_activation(logits.float())
+ # Max-pool the logits over each sequence's tokens, then activate the
+ # pooled [B, V] rows, as the native path does. The activation is
+ # monotone, so this is the max of the activated tokens without
+ # upcasting and activating the whole [total_tokens, V] tensor.
+ pooled = torch.segment_reduce(logits, "max", offsets=cu_seqlens)
+ sparse_list = self._pooled_to_sparse(self._sparse_activation(pooled.float()))
- # Max-pool over tokens per sequence to get sparse vectors
- sparse_list = self._aggregate_sparse(weights, cu_seqlens, seq_lengths)
-
- return EncodeOutput(sparse=sparse_list, batch_size=len(texts), is_query=is_query)
+ output = EncodeOutput(sparse=sparse_list, batch_size=len(texts), is_query=is_query)
+ output.extra["input_token_counts"] = [int(n) for n in seq_lengths]
+ return output
- def _build_position_ids(self, cu_seqlens: torch.Tensor) -> torch.Tensor:
+ def _build_position_ids(self, cu_seqlens: torch.Tensor, *, total_tokens: int | None = None) -> torch.Tensor:
"""Build position IDs for packed sequences (each starts from 0)."""
- total_tokens = int(cu_seqlens[-1].item())
+ if total_tokens is None:
+ total_tokens = int(cu_seqlens[-1].item())
positions = torch.arange(total_tokens, device=self._device)
offsets = torch.repeat_interleave(
cu_seqlens[:-1],
cu_seqlens[1:] - cu_seqlens[:-1],
+ output_size=total_tokens,
)
return positions - offsets
@@ -358,22 +368,14 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
seq_lengths: list[int],
) -> list[SparseVector]:
"""Aggregate token weights to sparse vectors via max-pooling."""
- num_seqs = len(seq_lengths)
- max_weights = torch.segment_reduce(weights, "max", offsets=cu_seqlens)
+ del seq_lengths # The offsets carry the sequence boundaries.
+ return self._pooled_to_sparse(torch.segment_reduce(weights, "max", offsets=cu_seqlens))
+
+ def _pooled_to_sparse(self, max_weights: torch.Tensor) -> list[SparseVector]:
+ """Per-sequence sparse vectors from pooled ``[B, V]`` weights, special tokens zeroed."""
if self._special_token_ids:
max_weights[:, self._special_token_ids] = 0.0
- dense = max_weights.cpu().float().numpy()
- results: list[SparseVector] = []
- for i in range(num_seqs):
- row = dense[i]
- mask = row > 0
- results.append(
- SparseVector(
- indices=np.where(mask)[0].astype(np.int32),
- values=row[mask],
- )
- )
- return results
+ return sparse_rows(max_weights)
def _compute_rope(
self,
@@ -591,4 +593,6 @@ class GTESparseFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
)
)
- return EncodeOutput(sparse=sparse_list, batch_size=len(texts), is_query=is_query)
+ output = EncodeOutput(sparse=sparse_list, batch_size=len(texts), is_query=is_query)
+ output.extra["input_token_counts"] = [len(input_ids) for input_ids in batch_encoding["input_ids"]]
+ return output
diff --git a/packages/sie_server/src/sie_server/adapters/splade_flash/adapter.py b/packages/sie_server/src/sie_server/adapters/splade_flash/adapter.py
index 22bac8991..0e56b5c8f 100644
--- a/packages/sie_server/src/sie_server/adapters/splade_flash/adapter.py
+++ b/packages/sie_server/src/sie_server/adapters/splade_flash/adapter.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import importlib.util
+import itertools
import json
import logging
import math
@@ -12,6 +13,7 @@ import torch
from sie_server.adapters._flash_base import FlashBaseAdapter
from sie_server.adapters._flash_pack import build_position_ids
+from sie_server.adapters._sparse_rows import sparse_rows
from sie_server.adapters._spec import AdapterSpec
from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
from sie_server.adapters._utils import extract_texts, resolve_query_instruction, validate_output_types
@@ -327,22 +329,22 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
total_tokens = sum(seq_lengths)
max_seqlen = max(seq_lengths)
- input_ids_packed = torch.tensor(
- [tok_id for ids in batch_encoding["input_ids"] for tok_id in ids],
- dtype=torch.long,
- device=self._device,
+ flat_ids = np.fromiter(
+ itertools.chain.from_iterable(batch_encoding["input_ids"]), dtype=np.int64, count=total_tokens
)
-
- cu_seqlens = torch.zeros(len(texts) + 1, dtype=torch.int32, device=self._device)
- cu_seqlens[1:] = torch.tensor(seq_lengths, dtype=torch.int32, device=self._device).cumsum(0)
+ input_ids_packed = torch.from_numpy(flat_ids).to(self._device)
+ cu_seqlens = torch.from_numpy(np.concatenate(([0], np.cumsum(seq_lengths))).astype(np.int32)).to(self._device)
with torch.inference_mode():
- position_ids_packed = self._build_position_ids(cu_seqlens)
+ position_ids_packed = self._build_position_ids(cu_seqlens, total_tokens=total_tokens)
hidden = self._run_embeddings(input_ids_packed, position_ids_packed)
hidden = self._run_transformer_flash(hidden, cu_seqlens, max_seqlen, total_tokens)
logits = self._run_mlm_head(hidden)
- weights = torch.log1p(torch.relu_(logits))
- sparse_list = self._aggregate_sparse(weights, cu_seqlens, seq_lengths)
+ # Max-pool the logits over each sequence's tokens, then activate the
+ # pooled [B, V] rows. log1p(relu(.)) is monotone, so this is the max
+ # of the activated tokens without activating [total_tokens, V].
+ pooled = torch.segment_reduce(logits, "max", offsets=cu_seqlens)
+ sparse_list = sparse_rows(torch.log1p(torch.relu_(pooled)))
return sparse_list, seq_lengths
@@ -350,7 +352,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
# Flash path internals
# ------------------------------------------------------------------
- def _build_position_ids(self, cu_seqlens: torch.Tensor) -> torch.Tensor:
+ def _build_position_ids(self, cu_seqlens: torch.Tensor, *, total_tokens: int | None = None) -> torch.Tensor:
"""Build position IDs for packed sequences, restarting per sequence.
BERT/DistilBERT use 0-based positions; RoBERTa offsets each sequence by
@@ -363,7 +365,7 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
offset = 0
if self._arch == "roberta":
offset = self._get_base_model().embeddings.padding_idx + 1
- return build_position_ids(cu_seqlens, offset=offset)
+ return build_position_ids(cu_seqlens, offset=offset, total_tokens=total_tokens)
def _get_base_model(self) -> Any:
if self._arch == "bert":
@@ -481,36 +483,13 @@ class SPLADEFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):
seq_lengths: list[int],
) -> list[SparseVector]:
"""Max-pool packed token weights into per-sequence sparse vectors."""
- num_seqs = len(seq_lengths)
- max_weights = torch.segment_reduce(weights, "max", offsets=cu_seqlens)
- dense = max_weights.cpu().float().numpy()
- results: list[SparseVector] = []
- for i in range(num_seqs):
- row = dense[i]
- mask = row > 0
- results.append(
- SparseVector(
- indices=np.where(mask)[0].astype(np.int32),
- values=row[mask],
- )
- )
- return results
+ del seq_lengths # The offsets carry the sequence boundaries.
+ return sparse_rows(torch.segment_reduce(weights, "max", offsets=cu_seqlens))
@staticmethod
def _dense_to_sparse_list(max_weights: torch.Tensor) -> list[SparseVector]:
"""Convert dense [batch, vocab_size] weights to a list of SparseVector."""
- dense = max_weights.cpu().float().numpy()
- results: list[SparseVector] = []
- for i in range(dense.shape[0]):
- row = dense[i]
- mask = row > 0
- results.append(
- SparseVector(
- indices=np.where(mask)[0].astype(np.int32),
- values=row[mask],
- )
- )
- return results
+ return sparse_rows(max_weights)
# ------------------------------------------------------------------
# IDF / query-weight utilities
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index b1a24b8c1..d8adca13d 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -503,6 +503,11 @@ class ProfileAdaptiveBatching(BaseModel):
model_config = ConfigDict(extra="forbid")
+ # False turns adaptive batching off for this model; None or True keeps the
+ # server-wide setting. Encoders that serve large offline batches can be held
+ # back by the controller, which shrinks the batch budget whenever request
+ # latency (queue time included) is above target, as it always is under load.
+ enabled: bool | None = None
target_p50_ms: float | None = None
calibration_multiplier: float | None = None
min_target_p50_ms: float | None = None
@@ -833,6 +838,7 @@ def _merge_profile_adaptive_batching(
# Fieldwise merge: child overrides parent per-field
return ProfileAdaptiveBatching(
+ enabled=child.enabled if child.enabled is not None else parent.enabled,
target_p50_ms=child.target_p50_ms if child.target_p50_ms is not None else parent.target_p50_ms,
calibration_multiplier=child.calibration_multiplier
if child.calibration_multiplier is not None
diff --git a/packages/sie_server/src/sie_server/core/model_loader.py b/packages/sie_server/src/sie_server/core/model_loader.py
index 25d4fb45c..30455a5a2 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -954,7 +954,8 @@ def _merge_adaptive_params(
if profile is None:
return engine
return AdaptiveBatchingParams(
- enabled=engine.enabled,
+ # A profile can turn adaptive batching off for its model, never on.
+ enabled=engine.enabled and profile.enabled is not False,
target_p50_ms=profile.target_p50_ms if profile.target_p50_ms is not None else engine.target_p50_ms,
calibration_multiplier=profile.calibration_multiplier
if profile.calibration_multiplier is not None
diff --git a/packages/sie_server/tests/adapters/test_sparse_rows.py b/packages/sie_server/tests/adapters/test_sparse_rows.py
new file mode 100644
index 000000000..d7a014359
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_sparse_rows.py
@@ -0,0 +1,95 @@
+"""``sparse_rows`` and the pooled sparse paths of the doc-only sparse encoders."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+from sie_server.adapters._sparse_rows import sparse_rows
+from sie_server.adapters.gte_sparse_flash import GTESparseFlashAdapter
+from sie_server.core.inference_output import EncodeOutput, SparseVector
+from sie_server.types.inputs import Item
+
+
+def _reference(weights: torch.Tensor) -> list[SparseVector]:
+ """The previous conversion: copy the dense rows to the host, then numpy.where per row."""
+ dense = weights.cpu().float().numpy()
+ out = []
+ for row in dense:
+ mask = row > 0
+ out.append(SparseVector(indices=np.where(mask)[0].astype(np.int32), values=row[mask]))
+ return out
+
+
+ "device",
+ ["cpu", pytest.param("cuda", marks=pytest.mark.skipif(not torch.cuda.is_available(), reason="needs CUDA"))],
+)
[email protected]("dtype", [torch.float32, torch.float16, torch.bfloat16])
+def test_sparse_rows_matches_dense_conversion(dtype: torch.dtype, device: str) -> None:
+ torch.manual_seed(3)
+ weights = torch.relu(torch.randn(6, 97)).to(device, dtype)
+ weights[2] = 0 # a row with no nonzero entry
+ actual = sparse_rows(weights)
+ expected = _reference(weights)
+ assert len(actual) == len(expected) == 6
+ for got, want in zip(actual, expected, strict=True):
+ assert got.indices.dtype == np.int32
+ assert got.values.dtype == np.float32
+ np.testing.assert_array_equal(got.indices, want.indices)
+ np.testing.assert_array_equal(got.values, want.values)
+ assert len(actual[2].indices) == 0
+
+
+def test_sparse_rows_of_an_empty_batch() -> None:
+ assert sparse_rows(torch.zeros(0, 10)) == []
+
+
+def test_gte_pool_then_activate_equals_activate_then_pool() -> None:
+ adapter = GTESparseFlashAdapter("test-gte-sparse-model", trust_remote_code=True)
+ adapter._special_token_ids = [0, 1]
+ torch.manual_seed(11)
+ seq_lengths = [3, 1, 6]
+ logits = torch.randn(sum(seq_lengths), 64).half()
+ cu_seqlens = torch.tensor([0, 3, 4, 10], dtype=torch.int32)
+
+ before = adapter._aggregate_sparse(adapter._sparse_activation(logits.float()), cu_seqlens, seq_lengths)
+ pooled = torch.segment_reduce(logits, "max", offsets=cu_seqlens)
+ after = adapter._pooled_to_sparse(adapter._sparse_activation(pooled.float()))
+
+ for got, want in zip(after, before, strict=True):
+ np.testing.assert_array_equal(got.indices, want.indices)
+ np.testing.assert_array_equal(got.values, want.values)
+
+
+def _stub_flash(adapter: GTESparseFlashAdapter, counts: list[int]) -> None:
+ def encode_flash(texts: list[str], is_query: bool) -> EncodeOutput:
+ output = EncodeOutput(
+ sparse=[SparseVector(indices=np.zeros(0, np.int32), values=np.zeros(0, np.float32)) for _ in texts],
+ batch_size=len(texts),
+ is_query=is_query,
+ )
+ output.extra["input_token_counts"] = counts
+ return output
+
+ adapter._encode_flash = encode_flash # type: ignore[method-assign]
+ adapter._use_flash = True
+ adapter._tokenizer = object() # type: ignore[assignment]
+ adapter._model = object()
+ adapter._idf = None
+
+
+def test_gte_reports_its_own_token_counts_for_untemplated_documents() -> None:
+ adapter = GTESparseFlashAdapter("test-gte-sparse-model", trust_remote_code=True)
+ _stub_flash(adapter, [5, 7])
+ output = adapter.encode([Item(text="red shoe"), Item(text="blue hat")], ["sparse"])
+ assert output.extra["input_token_counts"] == [5, 7]
+
+
+def test_gte_leaves_templated_documents_to_the_metering_hook() -> None:
+ adapter = GTESparseFlashAdapter("test-gte-sparse-model", trust_remote_code=True)
+ _stub_flash(adapter, [5, 7])
+ output = adapter.encode(
+ [Item(text="red shoe"), Item(text="blue hat")], ["sparse"], options={"doc_template": "passage: {text}"}
+ )
+ assert "input_token_counts" not in output.extra
diff --git a/packages/sie_server/tests/core/test_adaptive_batching.py b/packages/sie_server/tests/core/test_adaptive_batching.py
index 956b611e9..93acb9113 100644
--- a/packages/sie_server/tests/core/test_adaptive_batching.py
+++ b/packages/sie_server/tests/core/test_adaptive_batching.py
@@ -945,7 +945,28 @@ class TestProfileAdaptiveBatchingMerge:
assert result.target_p50_ms == 25.0 # from profile
assert result.gain == 0.3 # from engine
assert result.integral_gain == 0.05 # from engine
- assert result.enabled is True # always from engine
+ assert result.enabled is True # the profile does not set enabled
+
+ @pytest.mark.parametrize(
+ ("engine_enabled", "profile_enabled", "expected"),
+ [(True, False, False), (True, True, True), (True, None, True), (False, True, False), (False, None, False)],
+ )
+ def test_profile_can_turn_adaptive_batching_off_but_not_on(
+ self, engine_enabled: bool, profile_enabled: bool | None, expected: bool
+ ) -> None:
+ from sie_server.config.model import ProfileAdaptiveBatching
+ from sie_server.core.model_loader import _merge_adaptive_params
+
+ engine = AdaptiveBatchingParams(enabled=engine_enabled, target_p50_ms=None, gain=0.3)
+ result = _merge_adaptive_params(engine, ProfileAdaptiveBatching(enabled=profile_enabled))
+ assert result.enabled is expected
+
+ def test_child_profile_inherits_and_overrides_enabled(self) -> None:
+ from sie_server.config.model import ProfileAdaptiveBatching, _merge_profile_adaptive_batching
+
+ parent = ProfileAdaptiveBatching(enabled=False, gain=0.3)
+ assert _merge_profile_adaptive_batching(parent, ProfileAdaptiveBatching(gain=0.2)).enabled is False
+ assert _merge_profile_adaptive_batching(parent, ProfileAdaptiveBatching(enabled=True)).enabled is True
def test_engine_merge_none_profile(self) -> None:
"""No profile overrides → engine params unchanged."""