Repository navigation
[Feat] beam: Add Beam model, runtime support and checkpoints (4/7) #45256
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
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 efad1b5
[Feat] beam: Add Beam model, checkpoints and tests (4/5)
Jiminator a80a6ab
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator 48c5264
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator 2a2b7e3
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator 422389f
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator f5133c7
Move the cuTile router dispatch to its own PR
Jiminator 1f36b57
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator cbf000c
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator fca4b46
Revert "[Test] Set finite capacity in allocation eviction fixture"
Jiminator 8392f58
Revert "[unified-memory] Free SWA segments without a host sync"
Jiminator 2151b35
Revert "[unified-memory] Stop allocation eviction on the joint FULL/S…
Jiminator 7169d2c
Revert "[SWA] Keep a whole window behind the page an insert can end on"
Jiminator 6ecdf2b
Revert "feat(unified-memory): admit trtllm_mha on the translated MHA …
Jiminator c624303
Revert "[trtllm_mha] Copy only the batch's pages for the fmha_v2 pref…
Jiminator 83ccbf7
Revert "[trtllm_mha] Keep fmha_v2 prefill out of XQA's workspace sema…
Jiminator 8af671f
Revert "[unified-memory] Keep the slot-0 sink out of the debug poison…
Jiminator 9d152b6
Revert "[unified-memory] Require packed page tables on trtllm_mha's g…
Jiminator 6a5e96d
Revert "[unified-memory] Zero MHA page envelopes on hand-out"
Jiminator 5a9cd12
Revert "[unified-memory] Lift the trtllm_mha decode-graph refusal"
Jiminator 007447a
Revert "fix(nccl): widen the graph-register guard from decode to any …
Jiminator 1b2f9d7
Revert "test(nccl): cover the generalized graph-register guard"
Jiminator 79c4504
Revert "fix(nccl): disable graph buffer registration whenever a decod…
Jiminator 6bf1f05
Restore parallel_hook.py to its base after dropping #43216
Jiminator e45c6c1
Drop the srt layer's test changes
Jiminator e9e299a
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator c5e1ac7
Drop the model layer's tests and test fixture
Jiminator 97d8e8f
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator 16f9707
Follow the kernel op moves in beam.py
Jiminator 19246e0
Update existing CPU tests for Beam
Jiminator 103e601
Merge branch 'beam-stack-02-kernels' into beam-stack-03-srt
Jiminator 5557e15
Merge branch 'beam-stack-03-srt' into beam-stack-04-model
Jiminator 8216f36
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator 501afce
Drop compressed-tensors NVFP4 support for Beam
Jiminator 871f69e
Give the MegaMoE autotune sweep a caller output buffer
Jiminator ad02fe1
Scope the MegaMoE decode workspace to its consumer
Jiminator 35f1612
Validate CUDA DFlash with DP attention at config time
Jiminator 2bd28a1
Snapshot DFlash decode lengths for forward-pass metrics
Jiminator b3c336c
Tighten Beam's deferred expert sum and decode GEMV gate
Jiminator 359a501
Drop the FlashInfer full-plan reuse for short sliding prefills
Jiminator 1df0cd2
Clean up Beam's config workaround, comments and tuner import
Jiminator 0fd6cf9
Document the Beam decode GEMV and MegaMoE decode workspace env vars
Jiminator 614c1b5
Warn about an unusable Beam decode GEMV through print_warning_once
Jiminator a30f5d9
Cache DFlash's DP embedding table only for vocab-parallel targets
Jiminator 475d646
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator 658a617
Warm DFlash's eager selector during startup
Jiminator ab93cea
Reuse a replicated DFlash target embedding without a gather
Jiminator d142c2c
Drop the unreachable singleton guard from MegaMoE decode selection
Jiminator c8625a8
Require BF16 experts in the Beam decode GEMV gate
Jiminator a18c578
Correct the Beam GEMV and MegaMoE decode-capacity env docs
Jiminator d256b9b
Tighten comments on the Beam GEMV gate and the TRT-LLM FP8 tail
Jiminator 0812ad0
Slice DFlash's DP embedding shard in one statement
Jiminator 0fc533e
Use the default MegaMoE forward in the decode-workspace test
Jiminator 2dbc6ec
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator 3818ff6
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator f698850
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator 8d276ab
Leave the FlashInfer ragged sliding-window fix to its own PR
Jiminator 914e3f7
Leave the MegaMoE autotune fix and decode workspace to their own PR
Jiminator d365acd
Allow DFlash with CUDA dp attention only for Beam targets
Jiminator 6757701
Drop the pool-configurator and Beam override unit tests
Jiminator 1fc8fcd
Leave the SWA pool start layer fix to its own PR
Jiminator b8c1956
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator cc9e906
[Feat] parser: Add Beam reasoning, tool calls and response templates …
Jiminator 1c9663c
Merge beam-stack-02-kernels into beam-stack-04-model
Jiminator 903d45e
Reuse upstream DFlash CUDA DP support for Beam
Jiminator 46196e5
Merge branch 'beam-stack-02-kernels' into beam-stack-04-model
Jiminator File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done