Skip to content
Merged
Show file tree
Hide file tree
Changes from 56 commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
5845099
[Feat] srt: Add attention, memory and DFlash DP support for Beam (3/5)
Jiminator Oct 19, 2026
efad1b5
[Feat] beam: Add Beam model, checkpoints and tests (4/5)
Jiminator Oct 19, 2026
a80a6ab
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator Oct 20, 2026
48c5264
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator Oct 20, 2026
2a2b7e3
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator Oct 20, 2026
422389f
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator Oct 20, 2026
f5133c7
Move the cuTile router dispatch to its own PR
Jiminator Oct 20, 2026
1f36b57
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator Oct 20, 2026
cbf000c
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator Oct 20, 2026
fca4b46
Revert "[Test] Set finite capacity in allocation eviction fixture"
Jiminator Oct 21, 2026
8392f58
Revert "[unified-memory] Free SWA segments without a host sync"
Jiminator Oct 21, 2026
2151b35
Revert "[unified-memory] Stop allocation eviction on the joint FULL/S…
Jiminator Oct 21, 2026
7169d2c
Revert "[SWA] Keep a whole window behind the page an insert can end on"
Jiminator Oct 21, 2026
6ecdf2b
Revert "feat(unified-memory): admit trtllm_mha on the translated MHA …
Jiminator Oct 21, 2026
c624303
Revert "[trtllm_mha] Copy only the batch's pages for the fmha_v2 pref…
Jiminator Oct 21, 2026
83ccbf7
Revert "[trtllm_mha] Keep fmha_v2 prefill out of XQA's workspace sema…
Jiminator Oct 21, 2026
8af671f
Revert "[unified-memory] Keep the slot-0 sink out of the debug poison…
Jiminator Oct 21, 2026
9d152b6
Revert "[unified-memory] Require packed page tables on trtllm_mha's g…
Jiminator Oct 21, 2026
6a5e96d
Revert "[unified-memory] Zero MHA page envelopes on hand-out"
Jiminator Oct 21, 2026
5a9cd12
Revert "[unified-memory] Lift the trtllm_mha decode-graph refusal"
Jiminator Oct 21, 2026
007447a
Revert "fix(nccl): widen the graph-register guard from decode to any …
Jiminator Oct 21, 2026
1b2f9d7
Revert "test(nccl): cover the generalized graph-register guard"
Jiminator Oct 21, 2026
79c4504
Revert "fix(nccl): disable graph buffer registration whenever a decod…
Jiminator Oct 21, 2026
6bf1f05
Restore parallel_hook.py to its base after dropping #43216
Jiminator Oct 21, 2026
e45c6c1
Drop the srt layer's test changes
Jiminator Oct 21, 2026
e9e299a
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator Oct 21, 2026
c5e1ac7
Drop the model layer's tests and test fixture
Jiminator Oct 21, 2026
97d8e8f
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator Oct 21, 2026
16f9707
Follow the kernel op moves in beam.py
Jiminator Oct 21, 2026
19246e0
Update existing CPU tests for Beam
Jiminator Oct 21, 2026
103e601
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator Oct 21, 2026
5557e15
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator Oct 21, 2026
8216f36
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 21, 2026
501afce
Drop compressed-tensors NVFP4 support for Beam
Jiminator Oct 21, 2026
871f69e
Give the MegaMoE autotune sweep a caller output buffer
Jiminator Oct 21, 2026
ad02fe1
Scope the MegaMoE decode workspace to its consumer
Jiminator Oct 21, 2026
35f1612
Validate CUDA DFlash with DP attention at config time
Jiminator Oct 21, 2026
2bd28a1
Snapshot DFlash decode lengths for forward-pass metrics
Jiminator Oct 21, 2026
b3c336c
Tighten Beam's deferred expert sum and decode GEMV gate
Jiminator Oct 21, 2026
359a501
Drop the FlashInfer full-plan reuse for short sliding prefills
Jiminator Oct 21, 2026
1df0cd2
Clean up Beam's config workaround, comments and tuner import
Jiminator Oct 21, 2026
0fd6cf9
Document the Beam decode GEMV and MegaMoE decode workspace env vars
Jiminator Oct 21, 2026
614c1b5
Warn about an unusable Beam decode GEMV through print_warning_once
Jiminator Oct 21, 2026
a30f5d9
Cache DFlash's DP embedding table only for vocab-parallel targets
Jiminator Oct 22, 2026
475d646
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 22, 2026
658a617
Warm DFlash's eager selector during startup
Jiminator Oct 22, 2026
ab93cea
Reuse a replicated DFlash target embedding without a gather
Jiminator Oct 22, 2026
d142c2c
Drop the unreachable singleton guard from MegaMoE decode selection
Jiminator Oct 22, 2026
c8625a8
Require BF16 experts in the Beam decode GEMV gate
Jiminator Oct 22, 2026
a18c578
Correct the Beam GEMV and MegaMoE decode-capacity env docs
Jiminator Oct 22, 2026
d256b9b
Tighten comments on the Beam GEMV gate and the TRT-LLM FP8 tail
Jiminator Oct 22, 2026
0812ad0
Slice DFlash's DP embedding shard in one statement
Jiminator Oct 22, 2026
0fc533e
Use the default MegaMoE forward in the decode-workspace test
Jiminator Oct 22, 2026
2dbc6ec
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 22, 2026
3818ff6
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 22, 2026
f698850
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 23, 2026
8d276ab
Leave the FlashInfer ragged sliding-window fix to its own PR
Jiminator Oct 24, 2026
914e3f7
Leave the MegaMoE autotune fix and decode workspace to their own PR
Jiminator Oct 24, 2026
d365acd
Allow DFlash with CUDA dp attention only for Beam targets
Jiminator Oct 24, 2026
6757701
Drop the pool-configurator and Beam override unit tests
Jiminator Oct 24, 2026
1fc8fcd
Leave the SWA pool start layer fix to its own PR
Jiminator Oct 24, 2026
b8c1956
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 24, 2026
cc9e906
[Feat] parser: Add Beam reasoning, tool calls and response templates …
Jiminator Oct 25, 2026
1c9663c
Merge beam-stack-02-kernels into beam-stack-04-model
Jiminator Oct 25, 2026
903d45e
Reuse upstream DFlash CUDA DP support for Beam
Jiminator Oct 25, 2026
46196e5
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator Oct 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benchmark/kernels/fused_moe_triton/common_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def get_model_config(
topk = config.num_experts_per_tok
intermediate_size = config.intermediate_size
elif architecture in [
"BeamForCausalLM",
"Qwen2MoeForCausalLM",
"Qwen3MoeForCausalLM",
"Qwen3NextForCausalLM",
Expand Down
10 changes: 10 additions & 0 deletions docs/docs/references/environment_variables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,11 @@ SGLang supports various environment variables that can be used to configure its
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Per-rank FlashInfer MegaMOE symmetric-workspace token capacity. A value of <code>0</code> derives the capacity from the runtime token limits.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>0</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_FLASHINFER_MEGAMOE_DECODE_MAX_TOKENS_PER_RANK</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Per-rank token capacity of an extra, smaller FlashInfer MegaMOE workspace for decode-only forwards of ModelOpt NVFP4 MoE layers. Either <code>0</code> (off) or <code>0 &lt; capacity &lt; main capacity</code>, where the main capacity is <code>SGLANG_FLASHINFER_MEGAMOE_MAX_TOKENS_PER_RANK</code> or its derived value; any other value fails when the first MegaMOE layer is built. A forward uses it only when no DP rank extends and every EP rank's batch fits; otherwise it uses the main workspace. Unused (logged once) while MegaMoE startup autotuning runs, since the tuned capacity profiles already serve small batches; it takes effect with <code>--disable-flashinfer-autotune</code> or <code>--flashinfer-autotune-skip-ops flashinfer_megamoe</code>.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>0</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_FLASHINFER_MEGAMOE_IN_KERNEL_FC2_REDUCE</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Permit CuTe DSL MegaMOE in-kernel FC2 reduction for NVFP4 W4A4, NVFP4 W4A16, and MXFP8. FlashInfer's tuning profile may still select external reduction. BF16 atomic accumulation is nondeterministic; leave disabled for reproducibility. Requires BF16 combine.</td>
Expand Down Expand Up @@ -770,6 +775,11 @@ SGLang supports various environment variables that can be used to configure its
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>For DeepSeek V4, quantize the SWA FP8 KV cache from BF16-rounded values instead of FP32 registers. This matches trainer-side QAT and the DSA prefill-CP path, at the cost of an extra BF16 KV materialization and separate cache-store kernels.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>false</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_OPT_BEAM_DECODE_GEMV</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Run single-token Beam MoE decode through a fused GEMV on SM103 (GB300) for BF16 experts with MoE TP4 and EP1, where Beam fuses the expert sum into its all-reduce (Triton MoE runner). Requires <code>SGLANG_OPT_FUSE_SWIGLU_INTERLEAVED=1</code>. Unsupported setups and forwards keep their normal MoE path. Only a failed static check (device, BF16 experts, MoE TP/EP or expert shape) logs that the switch is unused.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>false</code></td>
</tr>
</tbody>
</table>

Expand Down
1 change: 1 addition & 0 deletions python/sglang/srt/arg_groups/model_overrides/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"""

from sglang.srt.arg_groups.model_overrides import bailing_moe_v3 # noqa: F401
from sglang.srt.arg_groups.model_overrides import beam # noqa: F401
from sglang.srt.arg_groups.model_overrides import cohere2_moe # noqa: F401
from sglang.srt.arg_groups.model_overrides import deepseek_v2 # noqa: F401
from sglang.srt.arg_groups.model_overrides import deepseek_v4 # noqa: F401
Expand Down
45 changes: 45 additions & 0 deletions python/sglang/srt/arg_groups/model_overrides/beam.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Config-time override declarations for beam.

Architectures: BeamForCausalLM.
"""

import logging
from typing import Any, Dict

from sglang.srt.arg_groups.model_override_base import (
_register_for,
is_attention_backend_not_set,
resolving_view,
)
from sglang.srt.runtime_context import get_platform
from sglang.srt.utils.common import get_quantization_config

logger = logging.getLogger(__name__)


@_register_for("BeamForCausalLM")
def _beam_overrides(server_args: Any, hf_config: Any) -> dict:
cfg = resolving_view(server_args)
overrides: Dict[str, Any] = {}
# Beam serves on TRT-LLM MHA (FMHA-v2/XQA on Hopper and SM120, trtllm-gen
# on Blackwell) rather than the generic Hopper default (fa3). Other
# platforms keep the generic selection.
if is_attention_backend_not_set(cfg) and (
get_platform().is_sm90 or get_platform().is_sm100 or get_platform().is_sm120
):
logger.info("Use trtllm_mha as default attention backend for Beam")
overrides["attention_backend"] = "trtllm_mha"
# Select defaults by checkpoint format; explicit runner choices are preserved.
quantization = cfg.quantization or get_quantization_config(hf_config)
quant_config = getattr(hf_config, "quantization_config", None) or {}
if quantization == "modelopt":
quantization = quant_config.get("quant_algo")
if (
quantization in ("modelopt_fp4", "NVFP4")
and get_platform().is_sm100
and cfg.moe_runner_backend == "auto"
and cfg.moe_a2a_backend == "none"
):
logger.info("Use flashinfer_trtllm as MoE runner backend for quantized Beam")
overrides["moe_runner_backend"] = "flashinfer_trtllm"
return overrides
1 change: 1 addition & 0 deletions python/sglang/srt/arg_groups/moe_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ def validate_flashinfer_megamoe_model(server_args: Any) -> None:
model_config = model_config_of(server_args)
architectures = model_config.hf_config.architectures or []
validated_architectures = (
"BeamForCausalLM",
"DeepseekV2ForCausalLM",
"DeepseekV3ForCausalLM",
"DeepseekV32ForCausalLM",
Expand Down
43 changes: 36 additions & 7 deletions python/sglang/srt/arg_groups/speculative_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,13 +299,6 @@ def _handle_dflash(server_args: ServerArgs) -> None:
f"{type(current_platform).__name__} on device {cfg.device!r}."
)

# DFLASH + dp attention is validated on NPU only.
if attn_dp_enabled_of(cfg) and not cfg.device == "npu":
raise ValueError(
"Currently DFLASH speculative decoding does not support dp "
"attention on non-NPU devices."
)

if cfg.pp_size != 1:
raise ValueError(
"Currently DFLASH speculative decoding only supports pp_size == 1."
Expand All @@ -316,6 +309,42 @@ def _handle_dflash(server_args: ServerArgs) -> None:
"DFLASH speculative decoding requires setting --speculative-draft-model-path."
)

if attn_dp_enabled_of(cfg) and cfg.device != "npu":
if not cfg.device.startswith("cuda"):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems dp attention + dflash is open to every model. Can we add a guard that throws error when detecting the model is not Beam here

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

raise ValueError("DFLASH with dp attention requires CUDA or NPU.")
if not cfg.enable_dp_lm_head:
raise ValueError("DFLASH with dp attention requires --enable-dp-lm-head.")
if cfg.attn_cp_size != 1:
raise ValueError(
"DFLASH with dp attention does not support context parallel."
)
if cfg.moe_a2a_backend not in ("none", "flashinfer_megamoe"):
raise ValueError(
"DFLASH with dp attention requires moe_a2a_backend 'none' or "
"'flashinfer_megamoe'."
)
# An idle DP rank's verify batch carries no mRoPE positions to pad.
if model_config_of(server_args).model_is_mrope:
raise ValueError(
"DFLASH with dp attention on CUDA does not support mRoPE targets."
)
from sglang.srt.speculative.dflash_utils import parse_dflash_draft_config
from sglang.srt.utils.hf_transformers_utils import get_config

draft_hf_config = get_config(
cfg.speculative_draft_model_path,
trust_remote_code=cfg.trust_remote_code,
revision=cfg.speculative_draft_model_revision,
model_override_args=json.loads(cfg.json_model_override_args),
)
if parse_dflash_draft_config(draft_hf_config=draft_hf_config).is_domino or (
"LiLiCorrDraftModel" in (draft_hf_config.architectures or [])
):
raise ValueError(
"DFLASH with dp attention on CUDA supports plain DFlash and "
"DFlash2 drafts; Domino and LiLiCorr heads are not supported."
)

# DFLASH does not use EAGLE-style `num_steps`/`topk`, but those fields still
# affect generic scheduler/KV-cache accounting (buffer sizing, KV freeing,
# RoPE reservation). Force them to 1 to avoid surprising memory behavior.
Expand Down
2 changes: 2 additions & 0 deletions python/sglang/srt/configs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from sglang.srt.configs.afmoe import AfmoeConfig
from sglang.srt.configs.bailing_hybrid import BailingHybridConfig, BailingMoeV3VLConfig
from sglang.srt.configs.bailing_moe_v2 import BailingMM2Config
from sglang.srt.configs.beam import BeamConfig
from sglang.srt.configs.chatglm import ChatGLMConfig
from sglang.srt.configs.cohere2_moe import Cohere2MoeConfig
from sglang.srt.configs.cosmos3 import (
Expand Down Expand Up @@ -99,6 +100,7 @@
"BailingHybridConfig",
"BailingMM2Config",
"BailingMoeV3VLConfig",
"BeamConfig",
"ExaoneConfig",
"ChatGLMConfig",
"Cosmos3Config",
Expand Down
215 changes: 215 additions & 0 deletions python/sglang/srt/configs/beam.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
# Copyright 2026 SGLang Team
# 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.
# ==============================================================================
"""Configuration for native Beam inference."""

from typing import List, Optional, Union

from transformers import PretrainedConfig

_DEFAULT_ROPE_THETA = 10000.0


def _normalize_rope_parameters(raw: Optional[dict]) -> dict:
"""Return the per-layer-type RoPE dict: default RoPE on sliding layers, NoPE on full."""
raw = raw or {}
if raw.keys() - {"sliding_attention", "full_attention"}:
raise ValueError("rope_parameters must use per-layer-type keys")
if raw.get("full_attention") is not None:
raise ValueError("full_attention must run without rotary embeddings")
sliding = raw.get("sliding_attention") or {}
if sliding.get("rope_type", "default") != "default":
raise ValueError("Beam supports only default RoPE")
return {
"sliding_attention": {
"rope_type": "default",
"rope_theta": float(sliding.get("rope_theta", _DEFAULT_ROPE_THETA)),
},
"full_attention": None,
}


class BeamConfig(PretrainedConfig):
model_type = "beam"
keys_to_ignore_at_inference = ["past_key_values"]

def __init__(
self,
vocab_size: int = 151936,
hidden_size: int = 5120,
intermediate_size: int = 20480,
num_hidden_layers: int = 52,
num_attention_heads: int = 48,
num_key_value_heads: int = 8,
head_dim: int = 128,
hidden_act: str = "silu",
max_position_embeddings: int = 1_048_576,
initializer_range: float = 0.02,
rms_norm_eps: float = 1e-6,
use_cache: bool = True,
tie_word_embeddings: bool = False,
rope_parameters: Optional[dict] = None,
attention_bias: bool = False,
attention_dropout: float = 0.0,
sliding_window: Optional[int] = 512,
layer_types: Optional[List[str]] = None,
mlp_layer_types: Optional[List[str]] = None,
moe_intermediate_size: int = 2560,
num_experts: int = 256,
num_experts_per_tok: int = 8,
norm_topk_prob: bool = True,
n_group: int = 8,
topk_group: int = 4,
routed_scaling_factor: float = 2.5,
final_logit_softcapping: Optional[float] = 30.0,
pad_token_id: Optional[int] = None,
bos_token_id: Optional[int] = None,
eos_token_id: Optional[Union[int, List[int]]] = None,
**kwargs,
):
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.head_dim = head_dim
self.hidden_act = hidden_act
self.max_position_embeddings = max_position_embeddings
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.tie_word_embeddings = tie_word_embeddings
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.sliding_window = sliding_window
self.moe_intermediate_size = moe_intermediate_size
self.num_experts = num_experts
self.num_experts_per_tok = num_experts_per_tok
self.norm_topk_prob = norm_topk_prob
self.n_group = n_group
self.topk_group = topk_group
self.routed_scaling_factor = routed_scaling_factor
self.final_logit_softcapping = final_logit_softcapping

if num_hidden_layers <= 0:
raise ValueError("num_hidden_layers must be positive")
if layer_types is None:
layer_types = [
"sliding_attention" if (i + 1) % 6 else "full_attention"
for i in range(num_hidden_layers)
]
layer_types[-1] = "full_attention"
self.layer_types = list(layer_types)
if mlp_layer_types is None:
num_dense_layers = min(3, num_hidden_layers)
mlp_layer_types = ["dense"] * num_dense_layers + ["sparse"] * (
num_hidden_layers - num_dense_layers
)
self.mlp_layer_types = list(mlp_layer_types)
# Validate the schedules before the Transformers constructor, whose own
# layer-type check raises a non-ValueError with a generic message.
self._validate_layer_schedules()

kwargs.setdefault("architectures", ["BeamForCausalLM"])
if kwargs.get("dtype") is None and kwargs.get("torch_dtype") is None:
kwargs["dtype"] = "bfloat16"
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)

# Assign after the Transformers constructor: its RoPE compatibility
# pass would flatten a per-layer-type dictionary it finds early.
self.rope_parameters = _normalize_rope_parameters(rope_parameters)

self._validate_beam_config()

def _validate_layer_schedules(self):
for name in ("layer_types", "mlp_layer_types"):
if len(getattr(self, name)) != self.num_hidden_layers:
raise ValueError(f"{name} length must equal num_hidden_layers")
if any(
kind not in ("sliding_attention", "full_attention")
for kind in self.layer_types
):
raise ValueError(
"layer_types must contain sliding_attention or full_attention"
)
if any(kind not in ("dense", "sparse") for kind in self.mlp_layer_types):
raise ValueError("mlp_layer_types must contain dense or sparse")

def _validate_beam_config(self):
for name in (
"vocab_size",
"hidden_size",
"intermediate_size",
"num_attention_heads",
"head_dim",
"max_position_embeddings",
):
if getattr(self, name) <= 0:
raise ValueError(f"{name} must be positive")
if self.head_dim % 2:
raise ValueError("head_dim must be even for split-half RoPE")
if "sliding_attention" in self.layer_types and (
self.sliding_window is None or self.sliding_window < 2
):
raise ValueError(
"sliding_attention layers require sliding_window >= 2; "
"native attention cannot represent a one-token window"
)
if (
self.num_key_value_heads <= 0
or self.num_attention_heads % self.num_key_value_heads
):
raise ValueError(
"num_attention_heads must be divisible by num_key_value_heads"
)
if "sparse" in self.mlp_layer_types:
if (
self.n_group <= 0
or self.num_experts % self.n_group
or self.num_experts // self.n_group < 2
):
raise ValueError(
"num_experts must form n_group equal groups with at least two experts"
)
if not 1 <= self.topk_group <= self.n_group:
raise ValueError("topk_group must be between 1 and n_group")
if (
not 1
<= self.num_experts_per_tok
<= self.topk_group * (self.num_experts // self.n_group)
):
raise ValueError(
"num_experts_per_tok exceeds the selected expert groups"
)

# These fields describe the numerical contract of native Beam inference.
# Fail early for variants that the model does not implement.
required = {
"hidden_act": "silu",
"tie_word_embeddings": False,
"attention_bias": False,
"norm_topk_prob": True,
}
for name, expected in required.items():
if getattr(self, name) != expected:
raise ValueError(f"Native Beam requires {name}={expected!r}")


__all__ = ["BeamConfig"]
Loading
Loading