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
perf(laya): CUDA graphs for small requests, as an opt-in graphs profile (#718)
svonavaab6c039f434a
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex 31e092472..f87e0ea6d 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -798,6 +798,93 @@ graphs comparison, it is at least as accurate as the unfused rotation for`modernbert-embed-base`, `Reason-ModernColBERT` and `mLateOn`, and theirprofiles enable it. The other models load without it.+### Laya CUDA graphs++The Laya adapter answers typed questions with one encoder row per (state,+question) pair. One state with a few questions is a forward of a few rows, and+kernel launches, not the GPU, bound it: on an L4, a request of four rows and+710 tokens launches 680 to 860 kernels and keeps the GPU busy for 7 ms of a+22 ms forward on `laya-multilingual`, and for 17 ms of 28 on `laya`. The+adapter takes the load-time option the ModernBERT flash adapters have, and+records its encoder with the same runner:++```yaml+profiles:+ graphs:+ extends: default+ adapter_options:+ loadtime:+ cuda_graphs: bucketed+```++With it, a request whose rows hold at most 2,048 packed tokens replays the+encoder as one graph, and the decision head runs eagerly on the result. On+encoders wider than 768 the bound is 1,024 tokens. A larger request runs+eagerly as before: the GPU bounds it, and padding it to a graph's bucket costs+more than the launches save.++The three shipped checkpoints offer graphs as a second profile. Request+`convaiinnovations/laya:graphs`, `convaiinnovations/laya-typed-decisions:graphs`+or `convaiinnovations/laya-multilingual:graphs` in place of the model; the+default profile runs eagerly.++Speed on an NVIDIA L4 with 8 vCPUs: the forward of rows that are already+tokenized, eager and from a graph in one process, median of 15. One state is+a 118-word email with four questions:++| Model | 1 state: 4 rows, 710 tokens | 2 states: 8 rows, 1,420 tokens | 3 states: 12 rows, 2,130 tokens |+|--|--|--|--|+| `laya` | 29.0 → 23.2 ms | eager (39.6 ms) | eager |+| `laya-typed-decisions` | 28.3 → 23.3 ms | eager (39.7 ms) | eager |+| `laya-multilingual` | 21.8 → 9.3 ms | 23.1 → 17.8 ms | eager (24.4 ms) |++On the 1,024-wide checkpoints a graph at 1,416 tokens took 40.0 ms against+39.6 ms eagerly, which is where their bound comes from.++**Why graphs are not the default profile.** Padding to a bucket changes how+many rows a matrix multiply sees, so probabilities move by rounding. We sent+240 public texts with six questions each, one state per request, through a+graph and eagerly (1,440 answers per model), and measured the eager path's own+batching noise the same way: each state alone against the same state in a+request of eight.++| Model | Graphs: largest probability change | Graphs: top answers changed (largest eager margin) | Eager batching: largest probability change | Eager batching: top answers changed |+|--|--|--|--|--|+| `laya` | 0.091 | 4 (0.008) | 0.130 | 11 |+| `laya-typed-decisions` | 0.050 | 7 (0.008) | 0.079 | 13 |+| `laya-multilingual` | 0.034 | 3 (0.014) | 0.052 | 5 |++Graphs meet the second condition of the rule a speed-up ships enabled under+(see "When a speed-up ships enabled" above): every answer they change had an+eager margin far below the eager path's batching noise, and they move+probabilities less than sharing a request does. They do not meet the first, a+change of at most 0.02. Laya computes in bfloat16 through 22 or 28 layers, and+the adapter's eager answers already move by more than that with what else is+in the forward. So the default profiles stay+eager, and the `graphs` profile is there for callers who want the one-state+latency. Against a float32 forward of the reference package, the top answer+agrees on 1,427, 1,427 and 1,430 of the 1,440 rows from a graph, on 1,429,+1,431 and 1,433 eagerly with all rows in one call, and on 1,426, 1,428 and+1,433 from the package's own bfloat16 autocast.++**Forward size.** Rows run longest first in forwards of at most+`max_forward_tokens` padded tokens, a load-time option that stays at 16,384.+Called directly with 128 rows of up to 233 tokens (32 states with four+questions), the adapter takes 353, 353 and 139 ms at 4,096 on the three+models above, against 400, 399 and 154 ms at 16,384. Behind the server that+gain does not show: the server hands the adapter a 32-state request in+smaller calls already. Behind the sidecar, with 4,096, the same request took+371.5 against 372.5 ms and 370.6 against 374.5 ms on the 1,024-wide+checkpoints, and 162.6 against 155.7 ms on `laya-multilingual`.++**Fused rotary embedding.** The adapter also takes `fused_rope` (above). It+took 7 to 10% off 128-row requests, and no shipped profile enables it: with+it, agreement with the float32 reference was lower on two checkpoints with+all rows in one call (1,424 and 1,426 of 1,440, against 1,429 and 1,431).++The measurements, with their scripts, are in+[superlinked/sie-task-evidence](https://huggingface.co/datasets/superlinked/sie-task-evidence/tree/main/blog-laya-on-sie/2026-10-13b).+### Qwen3 reranker serving options`Qwen/Qwen3-Reranker-4B` and `Qwen/Qwen3-Reranker-0.6B` run ondiff --git a/packages/sie_server/models/convaiinnovations__laya-multilingual.yaml b/packages/sie_server/models/convaiinnovations__laya-multilingual.yamlindex 4de3e7654..ad9b2991e 100644--- a/packages/sie_server/models/convaiinnovations__laya-multilingual.yaml+++ b/packages/sie_server/models/convaiinnovations__laya-multilingual.yaml@@ -22,3 +22,15 @@ profiles:adapter_options:loadtime: {}runtime: {}+ # One state with a few questions is a small forward that kernel launches,+ # not the GPU, bound. This profile replays its encoder as a CUDA graph+ # (request it as `MODEL:graphs`). It is not the default because a graph+ # moves probabilities by more than the 0.02 the server README allows a+ # default speed-up, though by less than batching already does: see+ # "Laya CUDA graphs" there.+ graphs:+ extends: default+ adapter_options:+ loadtime:+ cuda_graphs: bucketed+ runtime: {}diff --git a/packages/sie_server/models/convaiinnovations__laya-typed-decisions.yaml b/packages/sie_server/models/convaiinnovations__laya-typed-decisions.yamlindex fd5de307b..ffe55bae1 100644--- a/packages/sie_server/models/convaiinnovations__laya-typed-decisions.yaml+++ b/packages/sie_server/models/convaiinnovations__laya-typed-decisions.yaml@@ -19,3 +19,15 @@ profiles:adapter_options:loadtime: {}runtime: {}+ # One state with a few questions is a small forward that kernel launches,+ # not the GPU, bound. This profile replays its encoder as a CUDA graph+ # (request it as `MODEL:graphs`). It is not the default because a graph+ # moves probabilities by more than the 0.02 the server README allows a+ # default speed-up, though by less than batching already does: see+ # "Laya CUDA graphs" there.+ graphs:+ extends: default+ adapter_options:+ loadtime:+ cuda_graphs: bucketed+ runtime: {}diff --git a/packages/sie_server/models/convaiinnovations__laya.yaml b/packages/sie_server/models/convaiinnovations__laya.yamlindex 8725738ea..a211fc42c 100644--- a/packages/sie_server/models/convaiinnovations__laya.yaml+++ b/packages/sie_server/models/convaiinnovations__laya.yaml@@ -19,3 +19,15 @@ profiles:adapter_options:loadtime: {}runtime: {}+ # One state with a few questions is a small forward that kernel launches,+ # not the GPU, bound. This profile replays its encoder as a CUDA graph+ # (request it as `MODEL:graphs`). It is not the default because a graph+ # moves probabilities by more than the 0.02 the server README allows a+ # default speed-up, though by less than batching already does: see+ # "Laya CUDA graphs" there.+ graphs:+ extends: default+ adapter_options:+ loadtime:+ cuda_graphs: bucketed+ runtime: {}diff --git a/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.pyindex 32e164029..e54eebfbe 100644--- a/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py+++ b/packages/sie_server/src/sie_server/adapters/_modernbert_flash_graphs.py@@ -378,6 +378,8 @@ class VarlenGraphRunner:self._failed: set[Key] = set()self._lock = threading.RLock()self._stream: torch.cuda.Stream | None = None+ # Threads that have run a forward on that stream (see ``_record``).+ self._warmed = threading.local()self._disabled = False# Set when the memory budget holds no more graphs.self._full = False@@ -628,10 +630,14 @@ class VarlenGraphRunner:"""Record the graph for ``key``.Recording runs on a stream of the runner's own, whose first use- creates per-stream state (the cuBLAS handle and workspace, compiled- Triton kernels) that cannot be created while recording: the first- recording warms that stream up with a forward of the smallest shape,- the only memory left cached on it. Recording launches no kernels; the+ creates state (the cuBLAS handle and workspace, compiled Triton+ kernels) that cannot be created while recording. PyTorch keeps the+ cuBLAS handle per thread and its workspace per handle and stream, and+ the server loads and warms a model on one thread and serves it on+ another. So each thread's first recording warms that stream up with a+ forward of the smallest shape, the only memory left cached on it;+ without that, the serving thread's first recording fails with+ ``CUBLAS_STATUS_NOT_INITIALIZED``. Recording launches no kernels; thecaller replays the graph to answer the forward.Raises:@@ -652,7 +658,7 @@ class VarlenGraphRunner:inputs = torch.zeros(2 * tokens + slots + 1, dtype=torch.int32, device=self._device)hidden = self._hidden_states(tokens)current = torch.cuda.current_stream(self._device)- warm_up = self._stream is None+ warm_up = self._stream is None or not getattr(self._warmed, "done", False)stream = self._stream or torch.cuda.Stream(device=self._device)pool = next(iter(self._graphs.values())).graph.pool() if self._graphs else Nonegraph = torch.cuda.CUDAGraph()@@ -666,6 +672,7 @@ class VarlenGraphRunner:self._forward(small, _MIN_TOKENS, _MIN_TOKENS)# Kept only once warmed up, so a failed warm-up is tried again.self._stream = stream+ self._warmed.done = Truefree_before = self._free_memory(self._device)graph.capture_begin(pool=pool, capture_error_mode="thread_local")try:diff --git a/packages/sie_server/src/sie_server/adapters/laya/adapter.py b/packages/sie_server/src/sie_server/adapters/laya/adapter.pyindex 43daf19f6..dda14a616 100644--- a/packages/sie_server/src/sie_server/adapters/laya/adapter.py+++ b/packages/sie_server/src/sie_server/adapters/laya/adapter.py@@ -34,6 +34,29 @@ Request contract:Metering counts every row the model encodes: an item's input tokens are the sumof its (state, question) row lengths, so cost scales with items x questions.++CUDA graphs (``adapter_options.loadtime.cuda_graphs: bucketed``; the shipped+configs offer it as the ``graphs`` profile, ``MODEL:graphs``). One state with a+few questions is a forward of a few rows, and its kernel launches (680 to 860+of them), not the GPU, bound it: on an L4 a four-row, 710-token forward+keeps the GPU busy for 7 ms of its 22 on ``laya-multilingual`` and for 17 ms of+its 28 on ``laya``. With graphs on, a request whose rows hold at most+``graph_token_bound`` packed tokens replays its encoder as one recorded graph+(``sie_server.adapters._modernbert_flash_graphs``, the runner the other+ModernBERT flash adapters use) and runs the decision head eagerly on the+result. Larger requests, which the GPU bounds, run eagerly as before: there a+graph's padding costs more than its launches save. Padding the token count up+to a graph's bucket changes how many rows a matrix multiply sees, so logits+move by floating-point rounding, as they do when a state shares a request with+others; the server README ("Laya CUDA graphs") has both measured.++Forward size. Rows run longest first in forwards of at most+``max_forward_tokens`` padded tokens, a load-time option (16,384 by default).+Called directly with 128 rows of up to 233 tokens, the adapter is faster at+4,096 on an L4 (353 against 400 ms on ``laya``, 139 against 154 ms on+``laya-multilingual``). Behind the server it is not: the server already hands+the adapter a 32-state request in smaller calls, and there 4,096 measured the+same on ``laya`` and slower on ``laya-multilingual``. So the default stays."""from __future__ import annotations@@ -51,6 +74,13 @@ import torchfrom huggingface_hub import snapshot_downloadfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._modernbert_flash import parse_fused_rope+from sie_server.adapters._modernbert_flash_graphs import (+ PackedForward,+ VarlenGraphRunner,+ parse_graph_mode,+ unsupported_reason,+)from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters.laya.model import LayaDecisionHead, LayaModel, apply_rope_parameters, split_checkpoint@@ -102,6 +132,9 @@ MAX_OPTIONS = 1024# item at max_len 1024, and all 64 at 512.MAX_ITEM_TOKENS = 32_768+# Padded tokens per forward (see "Forward size" in the module docstring).+DEFAULT_MAX_FORWARD_TOKENS = 16384+DEFAULT_LABELS_INSTRUCTION = "Which category does this text belong to?"_MIN_BF16_MAJOR = 8 # Ampere_LABELS_QUESTION_ID = "label"@@ -122,13 +155,28 @@ _ERR_STATE_JSON = "Laya metadata.state must be JSON-serializable"_ERR_TOO_MANY_OPTIONS = "Laya accepts at most {limit} {what} per request, got {count}"+def graph_token_bound(hidden_size: int) -> int:+ """Packed tokens a CUDA graph of a Laya encoder with this hidden size may hold.++ Twice the runner's own bound for encoders up to 768 wide and wider ones+ (``_modernbert_flash_graphs.token_bound``): 2,048 and 1,024. The adapter's+ eager forward launches more kernels than the dense adapters' do (the+ casts around a float32 residual stream, and the decision head), so a graph+ pays off for longer. On an L4 a 710-token request takes 9.3 ms from a graph+ against 21.8 ms eagerly on ``laya-multilingual`` (768 wide), which still+ gains at 1,420 tokens (17.8 against 23.1 ms). On ``laya`` (1,024 wide) it+ takes 23.2 against 29.0 ms, and at 1,416 tokens a graph is no faster.+ """+ return 2048 if hidden_size <= 768 else 1024++class LayaAdapter(BaseAdapter):"""Adapter for Laya decision models (``convaiinnovations/laya`` family)."""spec: ClassVar[AdapterSpec] = AdapterSpec(inputs=("text",),outputs=("json",),- unload_fields=("_model", "_tokenizer"),+ unload_fields=("_model", "_tokenizer", "_graphs"),)def __init__(@@ -136,9 +184,11 @@ class LayaAdapter(BaseAdapter):model_name_or_path: str | Path,*,max_seq_length: int | None = None,- max_forward_tokens: int = 16384,+ max_forward_tokens: int = DEFAULT_MAX_FORWARD_TOKENS,compute_precision: ComputePrecision = "bfloat16",revision: str | None = None,+ cuda_graphs: str | bool = "off",+ fused_rope: bool = False,**kwargs: Any,) -> None:"""Initialize the adapter.@@ -149,13 +199,26 @@ class LayaAdapter(BaseAdapter):max_seq_length: Upper bound on tokens per (state, question) row. Defaultsto the checkpoint's trained ``max_len``.max_forward_tokens: Padded-token budget per forward pass; rows beyond it- run in further passes.+ run in further passes (see "Forward size" in the module docstring).compute_precision: Projection precision on CUDA (``bfloat16`` matchesthe reference autocast). CPU and MPS always run float32.revision: Hugging Face revision (commit SHA) to pin.+ cuda_graphs: "off" (the default) or "bucketed": whether small requests+ replay the encoder as CUDA graphs (see the module docstring). An+ operator setting, fixed at load; it applies on CUDA with flash-attn.+ fused_rope: Rotate queries and keys with one fused kernel per layer+ on the flash path (``run_modernbert_flash_layers``). About a+ tenth faster on large requests; outputs differ by rounding, and+ no shipped profile enables it (see the server README).**kwargs: Additional loader arguments (ignored).++ Raises:+ ValueError: If ``cuda_graphs`` is not "off" or "bucketed", or+ ``fused_rope`` is not a boolean."""_ = kwargs+ self._cuda_graphs = parse_graph_mode(cuda_graphs, adapter="LayaAdapter")+ self._fused_rope = parse_fused_rope(fused_rope, adapter="LayaAdapter")self._model_name_or_path = str(model_name_or_path)self._max_seq_length = max_seq_lengthself._max_forward_tokens = max(1, int(max_forward_tokens))@@ -165,6 +228,10 @@ class LayaAdapter(BaseAdapter):self._model: LayaModel | None = Noneself._tokenizer: PreTrainedTokenizerFast | None = Noneself._device: str | None = None+ # Replays the encoder as CUDA graphs, when the operator enabled them,+ # for requests of at most this many packed tokens.+ self._graphs: VarlenGraphRunner | None = None+ self._graph_tokens = 0self._calibration = Calibration(temperature=(1.0, 1.0, 1.0), temperature_by_options={})self._max_len = 512self._head_max_len = 192@@ -258,11 +325,13 @@ class LayaAdapter(BaseAdapter):compute_dtype=compute_dtype,max_positions=self._max_len,embedding_dtype=embedding_dtype,+ fused_rope=self._fused_rope,)self._tokenizer = tokenizerself._model = modelself._device = device+ self._graphs = self._graph_runner()logger.info("Loaded Laya %s on %s (backbone=%s, compute=%s, max_len=%d, head_max_len=%d)",self._model_name_or_path,@@ -273,6 +342,37 @@ class LayaAdapter(BaseAdapter):self._head_max_len,)+ def _graph_runner(self) -> VarlenGraphRunner | None:+ """The CUDA graph runner for the loaded model; None when graphs are off or do not apply."""+ model, tokenizer, device = self._model, self._tokenizer, self._device+ if self._cuda_graphs == "off" or model is None or tokenizer is None or device is None:+ return None+ reason = unsupported_reason(device)+ if reason is None and not model.use_flash:+ reason = "graphs record the flash-attention encoder, and this model runs the padded one"+ if reason is not None:+ logger.warning(+ "Laya cuda_graphs=%s does not apply to %s, which runs eagerly: %s",+ self._cuda_graphs,+ self._model_name_or_path,+ reason,+ )+ return None+ encode, tables = model.graph_encoder()+ hidden_size = model.encoder.config.hidden_size+ self._graph_tokens = graph_token_bound(hidden_size)+ return VarlenGraphRunner(+ encode,+ hidden_size=hidden_size,+ dtype=torch.float32, # the encoder's residual stream and final norm+ device=device,+ window=self._max_len,+ pad_token_id=int(tokenizer.pad_token_id or 0),+ max_tokens=self._graph_tokens,+ static_tensors=tables,+ name=self._model_name_or_path,+ )+def warmup(self) -> None:"""Run one tiny decision to initialize kernels."""self.extract(@@ -490,6 +590,8 @@ class LayaAdapter(BaseAdapter):raise RuntimeError(ERR_NOT_LOADED)order = sorted(range(len(rows)), key=lambda r: len(rows[r]), reverse=True)results: list[np.ndarray] = [np.empty(0, dtype=np.float32)] * len(rows)+ # A small request replays the encoder as a CUDA graph; a larger one is GPU-bound and runs eagerly.+ replay = self._graphs is not None and sum(len(row) for row in rows) <= self._graph_tokensstart = 0while start < len(order):# Longest row first: the chunk's padded size is len(first) * n_rows.@@ -505,22 +607,43 @@ class LayaAdapter(BaseAdapter):qtype = torch.tensor([QTYPES[row_prefix[r].question.qtype] for r in chunk], dtype=torch.long)marker_pos, qtype = marker_pos.to(device), qtype.to(device)with torch.inference_mode():- if model.use_flash:- out = model.forward_flash(chunk_rows, marker_pos, qtype, device)- else:- out = model.forward_padded(- chunk_rows,- marker_pos,- qtype,- device,- pad_token_id=int(tokenizer.pad_token_id),- )- out_np = out.float().cpu().numpy()+ out_np = self._replay_rows(chunk_rows, marker_pos, qtype) if replay else None+ if out_np is None:+ if model.use_flash:+ out = model.forward_flash(chunk_rows, marker_pos, qtype, device)+ else:+ out = model.forward_padded(+ chunk_rows,+ marker_pos,+ qtype,+ device,+ pad_token_id=int(tokenizer.pad_token_id),+ )+ out_np = out.float().cpu().numpy()for j, r in enumerate(chunk):results[r] = out_np[j, : len(markers[j])]start += nreturn results+ def _replay_rows(self, rows: list[list[int]], marker_pos: torch.Tensor, qtype: torch.Tensor) -> np.ndarray | None:+ """Float32 logits for ``rows`` from a replayed CUDA graph; None when the forward runs eagerly.++ The graph holds the encoder. The decision head runs eagerly on the real+ rows of its output, inside the runner's lock, before the next replay+ overwrites them.+ """+ graphs, model, device = self._graphs, self._model, self._device+ if graphs is None or model is None or device is None:+ return None+ lengths = [len(row) for row in rows]+ token_ids = np.fromiter(chain.from_iterable(rows), dtype=np.int32, count=sum(lengths))++ def head(packed: PackedForward) -> np.ndarray:+ logits = model.head_logits(packed.hidden, packed.cu_seqlens, packed.lengths, marker_pos, qtype, device)+ return logits.float().cpu().numpy()++ return graphs.run(token_ids, lengths, head)+# ------------------------------------------------------------------ costdef extract_item_costs(diff --git a/packages/sie_server/src/sie_server/adapters/laya/model.py b/packages/sie_server/src/sie_server/adapters/laya/model.pyindex 8ee305747..eef206d4f 100644--- a/packages/sie_server/src/sie_server/adapters/laya/model.py+++ b/packages/sie_server/src/sie_server/adapters/laya/model.py@@ -18,6 +18,11 @@ Two backbones run the same math:* ``forward_padded``: everything else (CPU, MPS, CUDA without flash-attn). TheHugging Face ``ModernBertModel`` with SDPA attention plus the same head — thereference math, in float32 off-CUDA.++The flash path is split in two so that the encoder can be replayed as a CUDA+graph (``sie_server.adapters._modernbert_flash_graphs``): ``encode_packed`` is+what a graph records, and ``head_logits`` runs eagerly on its output, as it+does after an eager forward."""from __future__ import annotations@@ -34,6 +39,7 @@ from sie_server.adapters._modernbert_flash import (modernbert_rope_theta,run_modernbert_flash_layers,)+from sie_server.adapters._modernbert_flash_graphs import EncodeFnENCODER_PREFIX = "encoder."HEAD_PREFIXES = ("head.", "type_emb.", "scorer.")@@ -129,6 +135,7 @@ class LayaModel(nn.Module):self.head = headself._use_flash = Falseself._compute_dtype: torch.dtype = torch.float32+ self._fused_rope = Falseself._rope: dict[str, tuple[torch.Tensor, torch.Tensor]] = {}@property@@ -143,6 +150,7 @@ class LayaModel(nn.Module):compute_dtype: torch.dtype,max_positions: int,embedding_dtype: torch.dtype | None = None,+ fused_rope: bool = False,) -> None:"""Place the model for the chosen path. Call once after loading weights (float32).@@ -155,9 +163,13 @@ class LayaModel(nn.Module):On the flash path a float16 or bfloat16 table is kept at thatprecision, which is lossless because the values came from it;any other table stays float32.+ fused_rope: On the flash path, rotate queries and keys with one+ fused kernel per layer where it runs (see+ ``run_modernbert_flash_layers``). Outputs differ by rounding."""self._use_flash = use_flashself._compute_dtype = compute_dtype+ self._fused_rope = fused_rope and use_flashif use_flash:# Projections in the compute dtype; norms stay float32 for the float32# residual stream. The embedding lookup is upcast to float32.@@ -188,27 +200,24 @@ class LayaModel(nn.Module):return torch.autocast(device_type="cuda", dtype=self._compute_dtype)return nullcontext()- def forward_flash(+ def encode_packed(self,- rows: list[list[int]],- marker_pos: torch.Tensor,- qtype: torch.Tensor,- device: str,+ input_ids: torch.Tensor,+ positions: torch.Tensor,+ cu_seqlens: torch.Tensor,+ max_seqlen: int,+ total_tokens: int,) -> torch.Tensor:- """Packed varlen encoder + re-padded decision head. Returns float32 logits ``[rows, max_options]``."""- encoder = self.encoder- lengths = [len(r) for r in rows]- total_tokens = sum(lengths)- max_seqlen = max(lengths)- num_rows = len(rows)+ """The packed varlen encoder: token embeddings and their norm, the layers, the final norm.- flat = [token for row in rows for token in row]- input_ids = torch.tensor(flat, dtype=torch.long, device=device)- lengths_t = torch.tensor(lengths, dtype=torch.int32, device=device)- cu_seqlens = torch.zeros(num_rows + 1, dtype=torch.int32, device=device)- cu_seqlens[1:] = torch.cumsum(lengths_t, dim=0)- positions = build_position_ids(cu_seqlens, total_tokens=total_tokens)+ This is what a CUDA graph records (an ``EncodeFn``), and what the eager+ flash forward runs. ``input_ids`` and ``positions`` are integer device+ tensors of ``total_tokens`` entries; ``cu_seqlens`` is int32.+ Returns:+ Float32 hidden states ``[total_tokens, hidden]``.+ """+ encoder = self.encoderembeddings = encoder.embeddingshidden = embeddings.norm(embeddings.tok_embeddings(input_ids).float())global_cos, global_sin = self._rope["global"]@@ -224,19 +233,71 @@ class LayaModel(nn.Module):local_cos[positions],local_sin[positions],compute_dtype=self._compute_dtype,+ fused_rope=self._fused_rope,)- hidden = encoder.final_norm(hidden)+ return encoder.final_norm(hidden)- # Re-pad for the decision head: its layers attend over every token of a row.- row_index = torch.repeat_interleave(- torch.arange(num_rows, device=device), lengths_t.long(), output_size=total_tokens- )+ def graph_encoder(self) -> tuple[EncodeFn, list[torch.Tensor]]:+ """The encoder a CUDA graph records, and the RoPE tables it reads (for the runner's memory budget)."""+ return self.encode_packed, [table for pair in self._rope.values() for table in pair]++ def head_logits(+ self,+ hidden: torch.Tensor,+ cu_seqlens: torch.Tensor,+ lengths: list[int],+ marker_pos: torch.Tensor,+ qtype: torch.Tensor,+ device: str,+ ) -> torch.Tensor:+ """Re-pad packed encoder output and run the decision head on it.++ The head's layers attend over every token of a row, so the packed+ ``[total_tokens, hidden]`` states are laid out as ``[rows, max_seqlen,+ hidden]`` with the padding masked.++ Args:+ hidden: Packed encoder output of the real rows, row after row.+ cu_seqlens: Their cumulative lengths ``[rows + 1]`` (int32).+ lengths: Tokens per row (host copy of the same lengths).+ marker_pos: Marker positions ``[rows, max_options]``.+ qtype: Question type index per row.+ device: The model's device.++ Returns:+ Float32 logits ``[rows, max_options]``.+ """+ num_rows, max_seqlen, total_tokens = len(lengths), max(lengths), hidden.shape[0]+ lengths_t = (cu_seqlens[1:] - cu_seqlens[:-1]).long()+ positions = build_position_ids(cu_seqlens, total_tokens=total_tokens)+ row_index = torch.repeat_interleave(torch.arange(num_rows, device=device), lengths_t, output_size=total_tokens)padded = hidden.new_zeros(num_rows, max_seqlen, hidden.shape[-1])padded[row_index, positions] = hiddenpadding_mask = torch.arange(max_seqlen, device=device)[None, :] >= lengths_t[:, None]with self.autocast(device):return self.head(padded, padding_mask, qtype, marker_pos)+ def forward_flash(+ self,+ rows: list[list[int]],+ marker_pos: torch.Tensor,+ qtype: torch.Tensor,+ device: str,+ ) -> torch.Tensor:+ """Packed varlen encoder + re-padded decision head. Returns float32 logits ``[rows, max_options]``."""+ lengths = [len(r) for r in rows]+ total_tokens = sum(lengths)+ num_rows = len(rows)++ flat = [token for row in rows for token in row]+ input_ids = torch.tensor(flat, dtype=torch.long, device=device)+ lengths_t = torch.tensor(lengths, dtype=torch.int32, device=device)+ cu_seqlens = torch.zeros(num_rows + 1, dtype=torch.int32, device=device)+ cu_seqlens[1:] = torch.cumsum(lengths_t, dim=0)+ positions = build_position_ids(cu_seqlens, total_tokens=total_tokens)+ hidden = self.encode_packed(input_ids, positions, cu_seqlens, max(lengths), total_tokens)+ return self.head_logits(hidden, cu_seqlens, lengths, marker_pos, qtype, device)+def forward_padded(self,rows: list[list[int]],diff --git a/packages/sie_server/tests/adapters/test_laya_graphs.py b/packages/sie_server/tests/adapters/test_laya_graphs.pynew file mode 100644index 000000000..ea5c81713--- /dev/null+++ b/packages/sie_server/tests/adapters/test_laya_graphs.py@@ -0,0 +1,305 @@+"""The Laya adapter replaying its encoder as CUDA graphs.++The CPU tests use the stand-ins of ``test_modernbert_flash_graphs``: a recorded+graph is replaced by one whose replay runs the recorded encoder again on the+graph's static inputs, and a reference attention stands in for flash-attn's+kernel. That attention writes NaN to every row outside a sequence, as the real+kernel leaves them unwritten, so a padding token that reached a real row would+fail every comparison. They check what the adapter records (its packed encoder+on a float32 residual stream), what it makes of a replay (the decision head on+the real rows) and when it replays. The ``gpu_hw`` test records and replays+real graphs.+"""++from __future__ import annotations++import logging+import threading+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import numpy as np+import pytest+import torch+from sie_server.adapters._modernbert_flash_graphs import parse_graph_mode, token_buckets+from sie_server.adapters.laya.adapter import LayaAdapter, graph_token_bound+from sie_server.adapters.laya.model import LayaModel+from sie_server.adapters.laya.questions import QTYPE_NAMES+from sie_server.core.loader import load_model_configs, reject_unknown_loadtime_options++from .test_laya_model import (+ MARKERS,+ PAD_ID,+ QTYPES,+ ROWS,+ _encoder_config,+ _load_like_adapter,+ reference_checkpoint,+)+from .test_modernbert_flash_graphs import (+ _Runner,+ reference_flash,+)++_MODELS_DIR = Path(__file__).resolve().parents[2] / "models"+_LAYA_ADAPTER = "sie_server.adapters.laya.adapter:LayaAdapter"+_SHIPPED = {+ "convaiinnovations/laya",+ "convaiinnovations/laya-multilingual",+ "convaiinnovations/laya-typed-decisions",+}+_WINDOW = 64+# The adapter's own tolerance (``test_laya_model``): float32 logits against the reference forward.+_TOLERANCE = 1e-5+++def _prefixes() -> list[Any]:+ """One row prefix per ``ROWS`` entry: its option markers and question type."""+ return [+ SimpleNamespace(markers=markers, question=SimpleNamespace(qtype=QTYPE_NAMES[qtype]))+ for markers, qtype in zip(MARKERS, QTYPES, strict=True)+ ]+++def _flash_model(checkpoint: Path, *, fused_rope: bool = False) -> LayaModel:+ """The served model on its packed path, in float32 on the CPU."""+ model, embedding_dtype = _load_like_adapter(checkpoint, _encoder_config())+ model.prepare(+ "cpu",+ use_flash=True,+ compute_dtype=torch.float32,+ max_positions=_WINDOW,+ embedding_dtype=embedding_dtype,+ fused_rope=fused_rope,+ )+ return model+++def _adapter(model: LayaModel, *, cuda_graphs: str = "off") -> LayaAdapter:+ adapter = LayaAdapter("tiny", max_seq_length=_WINDOW, cuda_graphs=cuda_graphs)+ adapter._model, adapter._device, adapter._max_len = model, "cpu", _WINDOW+ adapter._tokenizer = SimpleNamespace(pad_token_id=PAD_ID) # ty: ignore[invalid-assignment]+ return adapter+++def _pair(checkpoint: Path) -> tuple[LayaAdapter, LayaAdapter, _Runner]:+ """One model behind two adapters: graphs replayed on the CPU, and eager."""+ model = _flash_model(checkpoint)+ graphed, eager = _adapter(model, cuda_graphs="bucketed"), _adapter(model)+ encode, tables = model.graph_encoder()+ runner = _Runner(+ encode, hidden_size=model.encoder.config.hidden_size, window=_WINDOW, max_tokens=256, static_tensors=tables+ )+ graphed._graphs, graphed._graph_tokens = runner, 256+ return graphed, eager, runner+++def _assert_rows_close(got: list[np.ndarray], want: list[np.ndarray]) -> None:+ assert len(got) == len(want) == len(ROWS)+ for mine, ref, markers in zip(got, want, MARKERS, strict=True):+ assert mine.dtype == np.float32+ assert mine.shape == (len(markers),)+ assert np.isfinite(mine).all()+ np.testing.assert_allclose(mine, ref, atol=_TOLERANCE, rtol=_TOLERANCE)+ # Guard against a vacuous pass: the options get distinct scores.+ assert float(ref.max() - ref.min()) > 1e-3++[email protected]("reference_flash")+class TestForward:+ def test_replayed_rows_match_the_eager_forward(self, reference_checkpoint: tuple[Any, Path]) -> None: # noqa: F811+ graphed, eager, runner = _pair(reference_checkpoint[1])+ want = eager._run_rows(ROWS, _prefixes())+ _assert_rows_close(graphed._run_rows(ROWS, _prefixes()), want)+ _assert_rows_close(graphed._run_rows(ROWS, _prefixes()), want)+ # 71 packed tokens in three rows: one 128-token graph, recorded once and replayed after.+ assert runner.recorded == [(128, 64)]+ assert (runner.stats.recorded, runner.stats.replayed, runner.stats.eager) == (1, 1, {})++ def test_the_graph_records_the_encoder_the_eager_forward_runs(+ self,+ reference_checkpoint: tuple[Any, Path], # noqa: F811+ ) -> None:+ """``encode_packed`` on a padded stream gives the real rows what the packed eager stream gives them."""+ model = _flash_model(reference_checkpoint[1])+ lengths = [len(row) for row in ROWS]+ total = sum(lengths)+ ids = torch.tensor([token for row in ROWS for token in row], dtype=torch.int32)+ cu = torch.tensor(np.concatenate([[0], np.cumsum(lengths)]), dtype=torch.int32)+ positions = torch.cat([torch.arange(n, dtype=torch.int32) for n in lengths])+ with torch.inference_mode():+ packed = model.encode_packed(ids, positions, cu, max(lengths), total)+ # As a 128-token graph lays it out: padding tokens that belong to no+ # sequence, and five empty sequence slots after the three rows.+ extra = 128 - total+ padded_ids = torch.cat([ids, torch.full((extra,), PAD_ID, dtype=torch.int32)])+ padded_positions = torch.cat([positions, torch.zeros(extra, dtype=torch.int32)])+ padded_cu = torch.cat([cu, torch.full((5,), total, dtype=torch.int32)])+ padded = model.encode_packed(padded_ids, padded_positions, padded_cu, _WINDOW, 128)+ assert packed.dtype == padded.dtype == torch.float32+ torch.testing.assert_close(padded[:total], packed, atol=_TOLERANCE, rtol=_TOLERANCE)++ def test_a_forward_past_the_bound_runs_eagerly(self, reference_checkpoint: tuple[Any, Path]) -> None: # noqa: F811+ graphed, eager, runner = _pair(reference_checkpoint[1])+ runner._max_tokens, runner._tokens = 64, (64,)+ _assert_rows_close(graphed._run_rows(ROWS, _prefixes()), eager._run_rows(ROWS, _prefixes()))+ assert runner.stats.eager == {"too_large": 1}+ assert runner.recorded == []++ def test_a_request_past_the_adapters_bound_is_not_offered_to_the_runner(+ self,+ reference_checkpoint: tuple[Any, Path], # noqa: F811+ ) -> None:+ """The GPU bounds a large request, so none of its forwards replays, however small the last one is."""+ graphed, eager, runner = _pair(reference_checkpoint[1])+ graphed._graph_tokens = 64 # the three rows hold 71 tokens+ graphed._max_forward_tokens = eager._max_forward_tokens = 40 # one row per forward, each within a graph+ _assert_rows_close(graphed._run_rows(ROWS, _prefixes()), eager._run_rows(ROWS, _prefixes()))+ assert runner.stats.forwards == 0++ def test_chunks_replay_one_at_a_time(self, reference_checkpoint: tuple[Any, Path]) -> None: # noqa: F811+ """A request split into several forwards replays each chunk that fits a graph."""+ graphed, eager, runner = _pair(reference_checkpoint[1])+ graphed._max_forward_tokens = eager._max_forward_tokens = 40 # one row per forward+ _assert_rows_close(graphed._run_rows(ROWS, _prefixes()), eager._run_rows(ROWS, _prefixes()))+ assert runner.stats.forwards == len(ROWS)+ assert runner.stats.eager == {}++ def test_unload_drops_the_graphs(self, reference_checkpoint: tuple[Any, Path]) -> None: # noqa: F811+ graphed, _, _ = _pair(reference_checkpoint[1])+ graphed.unload()+ assert graphed._graphs is None+ assert graphed._model is None+++class TestOptions:+ def test_cuda_graphs_is_a_load_time_option(self) -> None:+ reject_unknown_loadtime_options(LayaAdapter, {"cuda_graphs": "bucketed"}, model_name="m")+ assert LayaAdapter("m", cuda_graphs="bucketed")._cuda_graphs == "bucketed"+ assert LayaAdapter("m", cuda_graphs=False)._cuda_graphs == "off"+ assert LayaAdapter("m")._cuda_graphs == "off"+ with pytest.raises(ValueError, match="cuda_graphs must be 'off' or 'bucketed'"):+ LayaAdapter("m", cuda_graphs="exact")++ def test_fused_rope_is_a_load_time_option(self) -> None:+ reject_unknown_loadtime_options(LayaAdapter, {"fused_rope": True}, model_name="m")+ assert LayaAdapter("m", fused_rope=True)._fused_rope is True+ assert LayaAdapter("m")._fused_rope is False+ with pytest.raises(ValueError, match="fused_rope must be true or false"):+ LayaAdapter("m", fused_rope="yes") # ty: ignore[invalid-argument-type]++ def test_an_adapter_without_graphs_builds_no_runner(self) -> None:+ adapter = LayaAdapter("m")+ adapter._model, adapter._device = SimpleNamespace(use_flash=True), "cuda:0" # ty: ignore[invalid-assignment]+ adapter._tokenizer = SimpleNamespace(pad_token_id=PAD_ID) # ty: ignore[invalid-assignment]+ assert adapter._graph_runner() is None++ def test_off_cuda_the_adapter_builds_no_runner(+ self,+ reference_checkpoint: tuple[Any, Path], # noqa: F811+ caplog: pytest.LogCaptureFixture,+ ) -> None:+ adapter = _adapter(_flash_model(reference_checkpoint[1]), cuda_graphs="bucketed")+ with caplog.at_level(logging.WARNING):+ assert adapter._graph_runner() is None+ assert "CUDA graphs need a CUDA device" in caplog.text++ @pytest.mark.parametrize(("hidden_size", "tokens"), [(384, 2048), (768, 2048), (1024, 1024)])+ def test_the_bound_depends_on_the_width_and_is_a_bucket(self, hidden_size: int, tokens: int) -> None:+ assert graph_token_bound(hidden_size) == tokens+ assert token_buckets(tokens)[-1] == tokens++ def test_shipped_checkpoints_offer_graphs_as_their_own_profile(self) -> None:+ """Graphs are opt-in: the default profile runs eagerly, and ``MODEL:graphs`` is the same model with them on."""+ configs = load_model_configs(_MODELS_DIR)+ served = {+ config.sie_id+ for config in configs.values()+ if any(config.resolve_profile(name).adapter_path == _LAYA_ADAPTER for name in config.profiles)+ }+ assert served == _SHIPPED | {f"{sie_id}:graphs" for sie_id in _SHIPPED}+ for sie_id in _SHIPPED:+ default = configs[sie_id].resolve_profile("default")+ assert "cuda_graphs" not in default.loadtime+ graphs = configs[f"{sie_id}:graphs"].resolve_profile("default")+ reject_unknown_loadtime_options(LayaAdapter, dict(graphs.loadtime), model_name=f"{sie_id}:graphs")+ assert parse_graph_mode(graphs.loadtime.get("cuda_graphs"), adapter=_LAYA_ADAPTER) == "bucketed"+ assert (graphs.adapter_path, graphs.compute_precision, graphs.max_batch_tokens) == (+ default.adapter_path,+ default.compute_precision,+ default.max_batch_tokens,+ )+ assert configs[f"{sie_id}:graphs"].hf_revision == configs[sie_id].hf_revision+++def _cuda_ready() -> bool:+ if not torch.cuda.is_available():+ return False+ from sie_server.core.inference import is_flash_attention_available++ return is_flash_attention_available("cuda:0")+++def _gpu_pair(checkpoint: Path) -> tuple[LayaAdapter, LayaAdapter]:+ """The tiny model on the GPU in bfloat16 behind two adapters: real graphs, and eager."""+ adapters = []+ for graphs in ("bucketed", "off"):+ model, embedding_dtype = _load_like_adapter(checkpoint, _encoder_config())+ model.prepare(+ "cuda:0",+ use_flash=True,+ compute_dtype=torch.bfloat16,+ max_positions=_WINDOW,+ embedding_dtype=embedding_dtype,+ )+ adapter = LayaAdapter("tiny", max_seq_length=_WINDOW, cuda_graphs=graphs)+ adapter._model, adapter._device, adapter._max_len = model, "cuda:0", _WINDOW+ adapter._tokenizer = SimpleNamespace(pad_token_id=PAD_ID) # ty: ignore[invalid-assignment]+ adapter._graphs = adapter._graph_runner()+ adapters.append(adapter)+ return adapters[0], adapters[1]+++class TestOnGpu:+ def test_a_thread_other_than_the_first_records_a_graph(+ self,+ reference_checkpoint: tuple[Any, Path], # noqa: F811+ ) -> None:+ """The server warms a model up on one thread and serves it on another: both must be able to record."""+ if not _cuda_ready():+ pytest.skip("requires CUDA and flash-attn")+ graphed, eager = _gpu_pair(reference_checkpoint[1])+ runner = graphed._graphs+ assert runner is not None+ one_row = ([ROWS[1]], [_prefixes()[1]]) # 14 tokens: the 64-token graph+ graphed._run_rows(*one_row)+ assert runner.stats.recorded == 1++ results: list[Any] = []+ serving = threading.Thread(target=lambda: results.append(graphed._run_rows(ROWS, _prefixes())))+ serving.start()+ serving.join()+ # 71 tokens: the 128-token graph, recorded on a thread that has no cuBLAS handle yet.+ assert (runner.stats.recorded, runner.stats.recording_failures, runner.stats.eager) == (2, 0, {})+ for mine, ref in zip(results[0], eager._run_rows(ROWS, _prefixes()), strict=True):+ np.testing.assert_allclose(mine, ref, atol=5e-2)++ def test_recorded_graphs_match_eager(self, reference_checkpoint: tuple[Any, Path]) -> None: # noqa: F811+ if not _cuda_ready():+ pytest.skip("requires CUDA and flash-attn")+ graphed, eager = _gpu_pair(reference_checkpoint[1])+ assert graphed._graphs is not None+ assert eager._graphs is None+ for _ in range(3):+ got = graphed._run_rows(ROWS, _prefixes())+ want = eager._run_rows(ROWS, _prefixes())+ for mine, ref in zip(got, want, strict=True):+ # bfloat16 projections: the graph pads the packed stream, which moves sums by rounding.+ np.testing.assert_allclose(mine, ref, atol=5e-2)+ stats = graphed._graphs.stats+ assert stats.recorded == 1+ assert stats.replayed == 2+ assert stats.recording_failures == 0+ assert graphed._graphs.held_bytes > 0diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 517b70cbf..634645cbd 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -2260,8 +2260,11 @@ def _default_bundle_export() -> tuple[list[ReplaceModelConfigEntry], list[str],def _route_ids_using(entries: list[ReplaceModelConfigEntry], modules: frozenset[str]) -> list[str]:routes = []for entry in entries:- for profile_name, profile in yaml.safe_load(entry.model_config)["profiles"].items():- adapter_path = profile.get("adapter_path") or ""+ profiles = yaml.safe_load(entry.model_config)["profiles"]+ for profile_name, profile in profiles.items():+ # A profile that extends another runs on its adapter unless it names its own.+ parent = profiles.get(profile.get("extends") or "", {})+ adapter_path = profile.get("adapter_path") or parent.get("adapter_path") or ""if adapter_path.split(":", maxsplit=1)[0] in modules:routes.append(entry.model_id if profile_name == "default" else f"{entry.model_id}:{profile_name}")return sorted(routes)