From d41904f05e19388326cc06c42b5a62cd5a1bba30 Mon Sep 17 00:00:00 2001 From: Cheng Wan <54331508+ch-wan@users.noreply.github.com> Date: Tue, 29 Sep 2026 21:16:45 -0700 Subject: [PATCH] [Refactor] Build seven more decoders from stage boundaries (#41779) --- .../srt/layers/layer_boundary/boundary.py | 61 +++++++----- .../srt/layers/layer_boundary/construction.py | 1 + .../srt/layers/layer_boundary/contracts.py | 3 + .../sglang/srt/layers/layer_boundary/exit.py | 9 +- .../layer_boundary/residual/post_norm.py | 74 +++++++++++++++ python/sglang/srt/models/apertus.py | 75 ++++++++------- python/sglang/srt/models/arcee.py | 64 ++++++++----- python/sglang/srt/models/exaone4.py | 94 ++++++++++--------- python/sglang/srt/models/kimi_linear.py | 87 ++++++++++------- python/sglang/srt/models/mixtral.py | 54 ++++++----- python/sglang/srt/models/nanbeige.py | 81 ++++++++-------- python/sglang/srt/models/spark2_5.py | 74 +++++++-------- 12 files changed, 411 insertions(+), 266 deletions(-) create mode 100644 python/sglang/srt/layers/layer_boundary/residual/post_norm.py diff --git a/python/sglang/srt/layers/layer_boundary/boundary.py b/python/sglang/srt/layers/layer_boundary/boundary.py index 26464d24fc..267ab68904 100644 --- a/python/sglang/srt/layers/layer_boundary/boundary.py +++ b/python/sglang/srt/layers/layer_boundary/boundary.py @@ -112,6 +112,9 @@ class ExitMove(NamedTuple): # Whether output_move also completes the sum the producer leaves. output_move_completes_sum: bool = False returns_over_dp: bool = False + # When output_move completes the sum: the move of an output compute has + # already reduced onto the same rows. + complete_output_move: Optional[Callable] = None def input_rows(edge: EdgeContract) -> Layout: @@ -312,17 +315,12 @@ def bind_exit(edge: EdgeContract, *, cp_moves: Optional[CpMoves] = None) -> Exit ) if edge.need.layout != edge.residual_to: raise NotImplementedError(f"{edge=}") - returns_over_dp, output_move, completes_sum = _select_exit_move( + return _select_exit_move( edge.produced, residual=edge.residual, to=edge.residual_to, cp_moves=cp_moves, ) - return ExitMove( - output_move=output_move, - output_move_completes_sum=completes_sum, - returns_over_dp=returns_over_dp, - ) def _select_entry_step( @@ -543,37 +541,50 @@ def _select_exit_move( residual: Layout, to: Layout, cp_moves: Optional[CpMoves] = None, -) -> Tuple[bool, Optional[Callable], bool]: - """How the FFN output reaches the rows the layer hands on: whether it goes - back by undoing the attention-DP gather (the FFN exit and postprocess run - that step), or else the postprocess that moves it, None when there is none - to choose here; and whether that move also completes the sum the FFN - leaves.""" +) -> ExitMove: + """How the FFN output reaches the rows the layer hands on: by undoing the + attention-DP gather (the FFN exit and finish run that step), or else the + move that takes it there, None when there is none to choose here; whether + that move also completes the sum the FFN leaves, and if so the move for an + output compute already reduced.""" update = produced.update if produced.layout == residual: if to == residual: - return False, keep_output, False + return ExitMove(keep_output) if to.sharded == residual.sharded - {TokenAxis.ATTN_TP}: # Each rank's slice back to the attention's rows: write the output # into the residual, then gather over attention TP. - return False, partial(update_attn_tp_gather_output, update=update), False + return ExitMove(partial(update_attn_tp_gather_output, update=update)) raise NotImplementedError(f"{produced=} {residual=} {to=}") returned = residual.sharded - produced.layout.sharded if returned == {TokenAxis.ATTN_TP} and to in (residual, produced.layout): # The residual stays on each rank's slice (MHC on an input-scattered # batch): a reduce-scatter onto the slice completes the sum the FFN # leaves; a complete output is only sliced. - sums = produced.may_reduce_scatter - return ( - False, + if not produced.may_reduce_scatter: + return ExitMove( + partial( + residual_slice_output, + sums=False, + gathers_back=to != residual, + update=update, + ) + ) + return ExitMove( partial( residual_slice_output, - sums=sums, + sums=True, + gathers_back=to != residual, + update=update, + ), + output_move_completes_sum=True, + complete_output_move=partial( + residual_slice_output, + sums=False, gathers_back=to != residual, update=update, ), - sums, ) if to != residual or not produced.layout.sharded <= residual.sharded: raise NotImplementedError(f"{produced=} {residual=} {to=}") @@ -582,17 +593,21 @@ def _select_exit_move( raise NotImplementedError(f"{produced=} {residual=} {to=}") if not produced.may_reduce_scatter: # A complete output: this rank's block of it, nothing summed. - return False, cp_moves.take_back, False + return ExitMove(cp_moves.take_back) # The FFN leaves its sum: only a take-back that sums over the same # ranks completes it. if cp_moves.reduce_scatter is None or not _same_ranks( _sum_group(produced.group), cp_moves.reduce_scatter_group() ): raise NotImplementedError(f"{produced=} {residual=} {to=}") - return False, cp_moves.reduce_scatter, True + return ExitMove( + cp_moves.reduce_scatter, + output_move_completes_sum=True, + complete_output_move=cp_moves.take_back, + ) if returned == {TokenAxis.ATTN_DP, TokenAxis.ATTN_CP}: # This rank's CP shard, from where the DP gather put it. - return False, dp_cp_take_back_output, False + return ExitMove(dp_cp_take_back_output) if returned != {TokenAxis.ATTN_DP}: raise NotImplementedError(f"{produced=} {residual=} {to=}") - return True, None, False + return ExitMove(returns_over_dp=True) diff --git a/python/sglang/srt/layers/layer_boundary/construction.py b/python/sglang/srt/layers/layer_boundary/construction.py index da41e5ee19..1b9f0e6958 100644 --- a/python/sglang/srt/layers/layer_boundary/construction.py +++ b/python/sglang/srt/layers/layer_boundary/construction.py @@ -214,6 +214,7 @@ class StagePlan: output_move=out.output_move, output_move_completes_sum=out.output_move_completes_sum, returns_over_dp=out.returns_over_dp, + complete_output_move=out.complete_output_move, ) @property diff --git a/python/sglang/srt/layers/layer_boundary/contracts.py b/python/sglang/srt/layers/layer_boundary/contracts.py index aa72c5dafb..3f22096b02 100644 --- a/python/sglang/srt/layers/layer_boundary/contracts.py +++ b/python/sglang/srt/layers/layer_boundary/contracts.py @@ -236,6 +236,8 @@ class StagePath(msgspec.Struct, frozen=True): batch by the attention-DP exit path. output_move_completes_sum: Whether that move also reduces the output. returns_over_dp: Whether output uses batch-dependent attention-DP transport. + complete_output_move: The move for an output compute already reduced, + run instead of an output_move that also reduces it. """ entry: EntryPath @@ -245,6 +247,7 @@ class StagePath(msgspec.Struct, frozen=True): output_move_completes_sum: bool = False returns_over_dp: bool = False + complete_output_move: Optional[Callable] = None class StageKind(Enum): diff --git a/python/sglang/srt/layers/layer_boundary/exit.py b/python/sglang/srt/layers/layer_boundary/exit.py index 44c8a187e5..c4321f95db 100644 --- a/python/sglang/srt/layers/layer_boundary/exit.py +++ b/python/sglang/srt/layers/layer_boundary/exit.py @@ -108,6 +108,11 @@ class ExitPolicy: forward_batch=forward_batch, dp_step=None, steps=steps, + output_move=( + steps.complete_output_move + if steps.output_move_completes_sum + else steps.output_move + ), ) return self._record_output( hidden_states, @@ -182,6 +187,7 @@ class ExitPolicy: forward_batch=forward_batch, dp_step=dp_step, steps=steps, + output_move=steps.output_move, ) defer_moe_finalize = ( self.plan.fusions is not None @@ -244,6 +250,7 @@ class ExitPolicy: forward_batch: ForwardBatch, dp_step: Optional[Callable], steps, + output_move: Optional[Callable], ) -> Tuple[torch.Tensor, torch.Tensor]: """This layer's postprocess, run with the attention-DP step already chosen: the move back to where the next layer reads the FFN output, then @@ -255,7 +262,7 @@ class ExitPolicy: dp_step or _dp_scatter_step, forward_batch, hidden_states ) else: - hidden_states, residual = steps.output_move( + hidden_states, residual = output_move( hidden_states=hidden_states, residual=residual, forward_batch=forward_batch, diff --git a/python/sglang/srt/layers/layer_boundary/residual/post_norm.py b/python/sglang/srt/layers/layer_boundary/residual/post_norm.py new file mode 100644 index 0000000000..d46383c990 --- /dev/null +++ b/python/sglang/srt/layers/layer_boundary/residual/post_norm.py @@ -0,0 +1,74 @@ +# Copyright 2023-2024 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. +# ============================================================================== +"""A post-norm residual: each stage reads the residual as it is, and its +output is normalized before it is added (EXAONE 4.0).""" + +from sglang.srt.layers.layer_boundary.adapters.attention import ( + attn_tp_gather, + attn_tp_slice, +) + + +class PostNormAdd: + """``residual + norm(output)``. It is not a plain add, so it runs only on a + complete output. ``applied_at_exit`` makes the stage write it itself.""" + + is_plain_add = False + outlives_layer = True + + def __init__(self, norm, *, applied_at_exit: bool = False): + self.norm = norm + self.applied_at_exit = applied_at_exit + + def update(self, hidden_states, residual): + return self.norm(hidden_states) + residual + + def slice_residual_attn_tp(self, residual): + return attn_tp_slice(residual) + + def gather_residual_attn_tp(self, residual): + return attn_tp_gather(residual) + + +class PlainReadout: + """The input is the residual itself; the stage's norm is not applied.""" + + is_plain_norm = False + reads_before_dp_gather = False + + def init_residual(self, hidden_states): + return hidden_states + + def read(self, residual, norm, quant_format="", post_residual_addition=None): + if quant_format or post_residual_addition is not None: + raise NotImplementedError( + f"a plain read with {quant_format=} or a post-residual addition" + ) + return residual, residual + + def update_and_read( + self, + update, + hidden_states, + residual, + norm, + quant_format="", + post_residual_addition=None, + ): + if residual is not None: + hidden_states = update.update(hidden_states, residual) + return self.read(hidden_states, norm, quant_format, post_residual_addition) + + +PLAIN_READOUT = PlainReadout() diff --git a/python/sglang/srt/models/apertus.py b/python/sglang/srt/models/apertus.py index 90241e21c3..944cf90624 100644 --- a/python/sglang/srt/models/apertus.py +++ b/python/sglang/srt/models/apertus.py @@ -27,6 +27,13 @@ from torch import nn from transformers import ApertusConfig from sglang.srt.layers.activation import XIELU +from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( ColumnParallelLinear, @@ -161,6 +168,7 @@ class ApertusAttention(nn.Module): hidden_size, bias=bias_o_proj, quant_config=quant_config, + reduce_results=False, prefix=add_prefix("o_proj", prefix), ) @@ -256,20 +264,27 @@ class ApertusDecoderLayer(nn.Module): self.feedforward_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.attention_layernorm), + ( + declare_ffn(sparse=False, next_layer_sparse=False), + self.feedforward_layernorm, + ), + previous=declare_ffn() if layer_id != 0 else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], - ) -> Tuple[torch.Tensor, torch.Tensor]: + capture_output=None, + ) -> torch.Tensor: # Self Attention - if residual is None: - residual = hidden_states - hidden_states = self.attention_layernorm(hidden_states) - else: - hidden_states, residual = self.attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.prepare( + hidden_states, forward_batch, capture=capture_output + ) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -277,9 +292,10 @@ class ApertusDecoderLayer(nn.Module): ) # Fully Connected - hidden_states, residual = self.feedforward_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class ApertusModel(nn.Module): @@ -335,35 +351,29 @@ class ApertusModel(nn.Module): hidden_states = self.embed_tokens(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - # FIXME(@ying): reduce the number of proxy tensors by not fusing layer norms - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] - deferred_norm = None + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) - aux_hidden_states = [] + aux_hidden_states = AuxHiddenStateList() for i in range(self.start_layer, self.end_layer): - if i in self.layers_to_capture: - aux_hidden_states.append(hidden_states + residual) - layer = self.layers[i] - hidden_states, residual = layer( + hidden_states = self.layers[i]( positions, hidden_states, forward_batch, - residual, + capture_output=aux_hidden_states.capture + if i in self.layers_to_capture + else None, ) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - hidden_states, _ = self.norm(hidden_states, residual) + return residual_batch.to_pp(hidden_states, forward_batch) + hidden_states = residual_batch.final_norm( + hidden_states, forward_batch, self.norm + ) if len(aux_hidden_states) == 0: return hidden_states @@ -508,6 +518,7 @@ class ApertusForCausalLM(nn.Module): start, end = split_interval # embed if start == 0: + residual_batch.start(forward_batch) if input_embeds is None: forward_batch.hidden_states = self.model.embed_tokens(input_ids) else: @@ -515,19 +526,17 @@ class ApertusForCausalLM(nn.Module): # decoder layer for i in range(start, end): layer = self.model.layers[i] - forward_batch.hidden_states, forward_batch.residual = layer( + forward_batch.hidden_states = layer( positions, forward_batch.hidden_states, forward_batch, - forward_batch.residual, ) if end == self.model.config.num_hidden_layers: # norm - hidden_states, _ = self.model.norm( - forward_batch.hidden_states, forward_batch.residual + forward_batch.hidden_states = residual_batch.final_norm( + forward_batch.hidden_states, forward_batch, self.model.norm ) - forward_batch.hidden_states = hidden_states # logits process result = self.logits_processor( input_ids, forward_batch.hidden_states, self.lm_head, forward_batch diff --git a/python/sglang/srt/models/arcee.py b/python/sglang/srt/models/arcee.py index 7c0e8d03f0..37bd266a4e 100644 --- a/python/sglang/srt/models/arcee.py +++ b/python/sglang/srt/models/arcee.py @@ -21,6 +21,13 @@ from torch import nn from transformers import LlamaConfig from sglang.srt.layers.activation import get_act_fn +from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( ColumnParallelLinear, @@ -149,6 +156,7 @@ class ArceeAttention(nn.Module): hidden_size, bias=bias, quant_config=quant_config, + reduce_results=False, prefix=add_prefix("o_proj", prefix), ) @@ -232,20 +240,27 @@ class ArceeDecoderLayer(nn.Module): self.post_attention_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.input_layernorm), + ( + declare_ffn(sparse=False, next_layer_sparse=False), + self.post_attention_layernorm, + ), + previous=declare_ffn() if layer_id != 0 else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], - ) -> Tuple[torch.Tensor, torch.Tensor]: + capture_output=None, + ) -> torch.Tensor: # Self Attention - if residual is None: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - else: - hidden_states, residual = self.input_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.prepare( + hidden_states, forward_batch, capture=capture_output + ) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -253,9 +268,10 @@ class ArceeDecoderLayer(nn.Module): ) # Fully Connected - hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class ArceeModel(nn.Module): @@ -309,33 +325,29 @@ class ArceeModel(nn.Module): hidden_states = self.embed_tokens(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) - aux_hidden_states = [] + aux_hidden_states = AuxHiddenStateList() for i in range(self.start_layer, self.end_layer): - if i in self.layers_to_capture: - aux_hidden_states.append(hidden_states + residual) - layer = self.layers[i] - hidden_states, residual = layer( + hidden_states = self.layers[i]( positions, hidden_states, forward_batch, - residual, + capture_output=aux_hidden_states.capture + if i in self.layers_to_capture + else None, ) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - hidden_states, _ = self.norm(hidden_states, residual) + return residual_batch.to_pp(hidden_states, forward_batch) + hidden_states = residual_batch.final_norm( + hidden_states, forward_batch, self.norm + ) if len(aux_hidden_states) == 0: return hidden_states diff --git a/python/sglang/srt/models/exaone4.py b/python/sglang/srt/models/exaone4.py index 44563fed10..63181fe632 100644 --- a/python/sglang/srt/models/exaone4.py +++ b/python/sglang/srt/models/exaone4.py @@ -6,6 +6,16 @@ from torch import nn from transformers import Exaone4Config from sglang.srt.layers.activation import SiluAndMul +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch +from sglang.srt.layers.layer_boundary.residual.post_norm import ( + PLAIN_READOUT, + PostNormAdd, +) from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( MergedColumnParallelLinear, @@ -142,6 +152,7 @@ class Exaone4Attention(nn.Module): output_size=hidden_size, bias=bias_o_proj, quant_config=quant_config, + reduce_results=False, prefix=add_prefix("o_proj", prefix), tp_rank=attn_tp_rank, tp_size=attn_tp_size, @@ -263,39 +274,49 @@ class Exaone4DecoderLayer(nn.Module): self.post_feedforward_layernorm = RMSNorm( self.hidden_size, eps=config.rms_norm_eps ) + # Post-LN: each stage reads the residual as it is, and its output is + # normalized before it is added. The layer writes the FFN's itself. + ffn_update = PostNormAdd(self.post_feedforward_layernorm, applied_at_exit=True) + self.attn_boundary, self.ffn_boundary = make_stages( + ( + declare_attn( + read=PLAIN_READOUT, + update=PostNormAdd(self.post_attention_layernorm), + ), + None, + ), + ( + declare_ffn( + sparse=False, + next_layer_sparse=False, + read=PLAIN_READOUT, + update=ffn_update, + ), + None, + ), + previous=declare_ffn(update=ffn_update) if layer_id != 0 else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], - ) -> tuple[torch.Tensor, torch.Tensor]: - - if residual is None: - residual = hidden_states - + ) -> torch.Tensor: # Self Attention + hidden_states = self.attn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, forward_batch=forward_batch, ) - # Use post-LN - hidden_states = self.post_attention_layernorm(hidden_states) - hidden_states = hidden_states + residual - residual = hidden_states - # Fully Connected + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - - # Use post-LN - hidden_states = self.post_feedforward_layernorm(hidden_states) - hidden_states = hidden_states + residual - residual = hidden_states - - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class Exaone4Model(nn.Module): @@ -353,30 +374,18 @@ class Exaone4Model(nn.Module): hidden_states = self.get_input_embeddings(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) - for i in range(len(self.layers)): - layer = self.layers[i] - hidden_states, residual = layer( - positions, - hidden_states, - forward_batch, - residual, - ) + for i in range(self.start_layer, self.end_layer): + hidden_states = self.layers[i](positions, hidden_states, forward_batch) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - hidden_states = self.norm(hidden_states) - return hidden_states + return residual_batch.to_pp(hidden_states, forward_batch) + return residual_batch.final_norm(hidden_states, forward_batch, self.norm) class Exaone4ForCausalLM(nn.Module): @@ -497,6 +506,7 @@ class Exaone4ForCausalLM(nn.Module): start, end = split_interval # embed if start == 0: + residual_batch.start(forward_batch) if input_embeds is None: forward_batch.hidden_states = self.model.embed_tokens(input_ids) else: @@ -504,19 +514,17 @@ class Exaone4ForCausalLM(nn.Module): # decoder layer for i in range(start, end): layer = self.model.layers[i] - forward_batch.hidden_states, forward_batch.residual = layer( + forward_batch.hidden_states = layer( positions, forward_batch.hidden_states, forward_batch, - forward_batch.residual, ) if end == self.model.config.num_hidden_layers: # norm - hidden_states, _ = self.model.norm( - forward_batch.hidden_states, forward_batch.residual + forward_batch.hidden_states = residual_batch.final_norm( + forward_batch.hidden_states, forward_batch, self.model.norm ) - forward_batch.hidden_states = hidden_states # logits process result = self.logits_processor( input_ids, forward_batch.hidden_states, self.lm_head, forward_batch diff --git a/python/sglang/srt/models/kimi_linear.py b/python/sglang/srt/models/kimi_linear.py index 115327c057..cc7304fcd7 100644 --- a/python/sglang/srt/models/kimi_linear.py +++ b/python/sglang/srt/models/kimi_linear.py @@ -16,6 +16,12 @@ from sglang.srt.distributed import ( ) from sglang.srt.eplb.expert_distribution import get_global_expert_distribution_recorder from sglang.srt.layers.dcp.planner import prepare_decode_context_parallel_metadata +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( ColumnParallelBatchedLinear, @@ -60,10 +66,13 @@ def _get_kda_local_num_heads(num_heads: int, tp_size: int) -> int: return num_heads // tp_size -def _materialize_residual_stream( - hidden_states: torch.Tensor, residual: Optional[torch.Tensor] -) -> torch.Tensor: - return hidden_states if residual is None else hidden_states + residual +def _is_sparse_layer(config: KimiLinearConfig, layer_idx: int) -> bool: + return ( + config.is_moe + and config.num_experts is not None + and layer_idx >= config.first_k_dense_replace + and layer_idx % config.moe_layer_freq == 0 + ) class KimiMoE(nn.Module): @@ -568,6 +577,7 @@ class KimiDecoderLayer(nn.Module): config=config, quant_config=quant_config, prefix=f"{prefix}.self_attn", + reduce_results=False, ) else: self.self_attn = KimiMLAAttention( @@ -583,14 +593,11 @@ class KimiDecoderLayer(nn.Module): q_lora_rank=config.q_lora_rank, kv_lora_rank=config.kv_lora_rank, skip_rope=True, + reduce_results=False, ) - if ( - self.is_moe - and config.num_experts is not None - and layer_idx >= config.first_k_dense_replace - and layer_idx % config.moe_layer_freq == 0 - ): + sparse = _is_sparse_layer(config, layer_idx) + if sparse: self.block_sparse_moe = KimiMoE( config=config, quant_config=quant_config, @@ -611,22 +618,33 @@ class KimiDecoderLayer(nn.Module): self.post_attention_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + next_sparse = layer_idx + 1 < config.num_hidden_layers and _is_sparse_layer( + config, layer_idx + 1 + ) + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.input_layernorm), + ( + declare_ffn(sparse=sparse, next_layer_sparse=next_sparse), + self.post_attention_layernorm, + ), + previous=declare_ffn( + sparse=_is_sparse_layer(config, layer_idx - 1), + next_layer_sparse=sparse, + ) + if layer_idx != 0 + else None, + terminal=layer_idx == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], zero_allocator: BumpAllocator, - ) -> tuple[torch.Tensor, torch.Tensor]: + ) -> torch.Tensor: # Self Attention - if residual is None: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - else: - hidden_states, residual = self.input_layernorm(hidden_states, residual) - + hidden_states = self.attn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.self_attn( hidden_states=hidden_states, positions=positions, @@ -635,9 +653,10 @@ class KimiDecoderLayer(nn.Module): ) # Fully Connected - hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class KimiLinearModel(nn.Module): @@ -704,11 +723,12 @@ class KimiLinearModel(nn.Module): hidden_states = inputs_embeds else: hidden_states = self.embed_tokens(input_ids) - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) total_num_layers = self.end_layer - self.start_layer device = hidden_states.device @@ -727,12 +747,10 @@ class KimiLinearModel(nn.Module): for i in range(self.start_layer, self.end_layer): ctx = get_global_expert_distribution_recorder().with_current_layer(i) with ctx: - layer = self.layers[i] - hidden_states, residual = layer( + hidden_states = self.layers[i]( positions=positions, hidden_states=hidden_states, forward_batch=forward_batch, - residual=residual, zero_allocator=zero_allocator, ) if ( @@ -740,22 +758,19 @@ class KimiLinearModel(nn.Module): and i in self.dspark_layers_to_capture ): aux_hidden_states.append( - _materialize_residual_stream(hidden_states, residual) + residual_batch.snapshot(hidden_states, forward_batch) ) if not self.pp_group.is_last_rank: - proxy_tensors = {"hidden_states": hidden_states, "residual": residual} + proxy = residual_batch.to_pp(hidden_states, forward_batch) if aux_hidden_states: - proxy_tensors["dspark_hidden_states"] = torch.cat( + proxy.tensors["dspark_hidden_states"] = torch.cat( aux_hidden_states, dim=-1 ) - return PPProxyTensors(proxy_tensors) - else: - if hidden_states.shape[0] != 0: - if residual is None: - hidden_states = self.norm(hidden_states) - else: - hidden_states, _ = self.norm(hidden_states, residual) + return proxy + hidden_states = residual_batch.final_norm( + hidden_states, forward_batch, self.norm, skip_empty=True + ) if self.dspark_layers_to_capture is not None: return hidden_states, aux_hidden_states diff --git a/python/sglang/srt/models/mixtral.py b/python/sglang/srt/models/mixtral.py index 5eb781d762..3c0bf0d291 100644 --- a/python/sglang/srt/models/mixtral.py +++ b/python/sglang/srt/models/mixtral.py @@ -28,6 +28,12 @@ from transformers import MixtralConfig from sglang.srt.distributed import ( tensor_model_parallel_all_reduce, ) +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( QKVParallelLinear, @@ -166,6 +172,7 @@ class MixtralAttention(nn.Module): hidden_size, bias=False, quant_config=quant_config, + reduce_results=False, prefix=add_prefix("o_proj", prefix), ) self.rotary_emb = get_rope( @@ -234,20 +241,26 @@ class MixtralDecoderLayer(nn.Module): self.post_attention_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.input_layernorm), + ( + declare_ffn(sparse=True, next_layer_sparse=True), + self.post_attention_layernorm, + ), + previous=declare_ffn(sparse=True, next_layer_sparse=True) + if layer_id != 0 + else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], ) -> torch.Tensor: # Self Attention - if residual is None: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - else: - hidden_states, residual = self.input_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -255,9 +268,10 @@ class MixtralDecoderLayer(nn.Module): ) # Fully Connected - hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.block_sparse_moe(hidden_states) - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class MixtralModel(nn.Module): @@ -310,29 +324,19 @@ class MixtralModel(nn.Module): hidden_states = self.embed_tokens(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) for i in range(self.start_layer, self.end_layer): - layer = self.layers[i] - hidden_states, residual = layer( - positions, hidden_states, forward_batch, residual - ) + hidden_states = self.layers[i](positions, hidden_states, forward_batch) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - hidden_states, _ = self.norm(hidden_states, residual) - - return hidden_states + return residual_batch.to_pp(hidden_states, forward_batch) + return residual_batch.final_norm(hidden_states, forward_batch, self.norm) class MixtralForCausalLM(nn.Module): diff --git a/python/sglang/srt/models/nanbeige.py b/python/sglang/srt/models/nanbeige.py index b5fd34b167..98648c2d60 100644 --- a/python/sglang/srt/models/nanbeige.py +++ b/python/sglang/srt/models/nanbeige.py @@ -6,7 +6,14 @@ from torch import nn from sglang.srt.configs import NanbeigeConfig from sglang.srt.layers.activation import SiluAndMul +from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList from sglang.srt.layers.dp_attention import is_dp_attention_enabled +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( MergedColumnParallelLinear, @@ -149,6 +156,7 @@ class NanbeigeAttention(nn.Module): self.hidden_size, bias=False, quant_config=quant_config, + reduce_results=False, prefix=add_prefix("o_proj", prefix), ) @@ -220,6 +228,17 @@ class NanbeigeDecoderLayer(nn.Module): self.post_attention_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + # Each loop runs the physical layers as one stack: the model folds the + # residual back in and re-enters at layer 0. + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.input_layernorm), + ( + declare_ffn(sparse=False, next_layer_sparse=False), + self.post_attention_layernorm, + ), + previous=declare_ffn() if layer_id != 0 else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, @@ -227,14 +246,11 @@ class NanbeigeDecoderLayer(nn.Module): hidden_states: torch.Tensor, forward_batch: ForwardBatch, loop_idx: int, - residual: Optional[torch.Tensor], - ) -> Tuple[torch.Tensor, torch.Tensor]: - - if residual is None: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - else: - hidden_states, residual = self.input_layernorm(hidden_states, residual) + capture_output=None, + ) -> torch.Tensor: + hidden_states = self.attn_boundary.prepare( + hidden_states, forward_batch, capture=capture_output + ) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, @@ -243,10 +259,10 @@ class NanbeigeDecoderLayer(nn.Module): ) # Fully Connected - hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class NanbeigeModel(nn.Module): @@ -317,13 +333,14 @@ class NanbeigeModel(nn.Module): hidden_states = self.embed_tokens(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) - aux_hidden_states = [] + aux_hidden_states = AuxHiddenStateList() # Draft target_layer_ids are in unrolled depth space: # logical_id = loop_idx * num_hidden_layers + physical_i # e.g. num_hidden_layers=22, num_loops=2 → ids in [0, 44). @@ -332,19 +349,14 @@ class NanbeigeModel(nn.Module): for loop_idx in range(self.config.num_loops): for i in range(self.start_layer, self.end_layer): logical_id = loop_idx * num_physical_layers + i - if logical_id in self.layers_to_capture: - aux_hidden_states.append( - hidden_states + residual - if residual is not None - else hidden_states.clone() - ) - layer = self.layers[i] - hidden_states, residual = layer( + hidden_states = self.layers[i]( positions, hidden_states, forward_batch, loop_idx, - residual, + capture_output=aux_hidden_states.capture + if logical_id in self.layers_to_capture + else None, ) # Match the reference HF semantics for Nanbeige "loop models": @@ -354,25 +366,16 @@ class NanbeigeModel(nn.Module): # - If skip_loop_final_norm=False, HF applies RMSNorm after each loop # (including intermediate loops) before entering the next loop. if loop_idx != self.config.num_loops - 1: - if residual is not None: - hidden_states = hidden_states + residual - residual = None + hidden_states = residual_batch.fold(hidden_states, forward_batch) if not self.config.skip_loop_final_norm: hidden_states = self.norm(hidden_states) + residual_batch.start(forward_batch) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - if hidden_states.shape[0] != 0: - if residual is None: - hidden_states = self.norm(hidden_states) - else: - hidden_states, _ = self.norm(hidden_states, residual) + return residual_batch.to_pp(hidden_states, forward_batch) + hidden_states = residual_batch.final_norm( + hidden_states, forward_batch, self.norm, skip_empty=True + ) if len(aux_hidden_states) == 0: return hidden_states diff --git a/python/sglang/srt/models/spark2_5.py b/python/sglang/srt/models/spark2_5.py index 77a1c0e5d3..b8012f5f89 100644 --- a/python/sglang/srt/models/spark2_5.py +++ b/python/sglang/srt/models/spark2_5.py @@ -6,6 +6,12 @@ from torch import nn from sglang.srt.layers.activation import GeluAndMul from sglang.srt.layers.dp_attention import is_dp_attention_enabled +from sglang.srt.layers.layer_boundary import ( + declare_attn, + declare_ffn, + make_stages, +) +from sglang.srt.layers.layer_boundary.residual import batch as residual_batch from sglang.srt.layers.layernorm import RMSNorm from sglang.srt.layers.linear import ( ColumnParallelLinear, @@ -155,6 +161,7 @@ class Spark2_5Attention(nn.Module): quant_config=quant_config, tp_rank=attn_tp_rank, tp_size=attn_tp_size, + reduce_results=False, prefix=add_prefix("out_proj", prefix), ) @@ -263,30 +270,33 @@ class Spark2_5DecoderLayer(nn.Module): self.post_attention_layernorm = RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) + self.attn_boundary, self.ffn_boundary = make_stages( + (declare_attn(), self.input_layernorm), + ( + declare_ffn(sparse=False, next_layer_sparse=False), + self.post_attention_layernorm, + ), + previous=declare_ffn() if layer_id != 0 else None, + terminal=layer_id == config.num_hidden_layers - 1, + ) def forward( self, positions: torch.Tensor, hidden_states: torch.Tensor, forward_batch: ForwardBatch, - residual: Optional[torch.Tensor], - ) -> Tuple[torch.Tensor, torch.Tensor]: + ) -> torch.Tensor: # Self Attention - if residual is None: - residual = hidden_states - hidden_states = self.input_layernorm(hidden_states) - else: - hidden_states, residual = self.input_layernorm(hidden_states, residual) - + hidden_states = self.attn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.self_attn( positions=positions, hidden_states=hidden_states, forward_batch=forward_batch, ) - hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) + hidden_states = self.attn_boundary.finish(hidden_states, forward_batch) + hidden_states = self.ffn_boundary.prepare(hidden_states, forward_batch) hidden_states = self.mlp(hidden_states) - - return hidden_states, residual + return self.ffn_boundary.finish_complete_output(hidden_states, forward_batch) class Spark2_5Model(nn.Module): @@ -345,35 +355,20 @@ class Spark2_5Model(nn.Module): hidden_states = self.embed_tokens(input_ids) else: hidden_states = input_embeds - residual = None + residual_batch.start(forward_batch) else: assert pp_proxy_tensors is not None - hidden_states = pp_proxy_tensors["hidden_states"] - residual = pp_proxy_tensors["residual"] + hidden_states = self.layers[self.start_layer].attn_boundary.from_pp( + pp_proxy_tensors, forward_batch + ) for i in range(self.start_layer, self.end_layer): - layer = self.layers[i] - hidden_states, residual = layer( - positions, - hidden_states, - forward_batch, - residual, - ) + hidden_states = self.layers[i](positions, hidden_states, forward_batch) if not self.pp_group.is_last_rank: - return PPProxyTensors( - { - "hidden_states": hidden_states, - "residual": residual, - } - ) - else: - if hidden_states.shape[0] != 0: - if residual is None: - hidden_states = self.norm(hidden_states) - else: - hidden_states, _ = self.norm(hidden_states, residual) - - return hidden_states + return residual_batch.to_pp(hidden_states, forward_batch) + return residual_batch.final_norm( + hidden_states, forward_batch, self.norm, skip_empty=True + ) class Spark2_5ForCausalLM(nn.Module): @@ -450,6 +445,7 @@ class Spark2_5ForCausalLM(nn.Module): start, end = split_interval # embed if start == 0: + residual_batch.start(forward_batch) if input_embeds is None: forward_batch.hidden_states = self.model.embed_tokens(input_ids) else: @@ -457,19 +453,17 @@ class Spark2_5ForCausalLM(nn.Module): # decoder layer for i in range(start, end): layer = self.model.layers[i] - forward_batch.hidden_states, forward_batch.residual = layer( + forward_batch.hidden_states = layer( positions, forward_batch.hidden_states, forward_batch, - forward_batch.residual, ) if end == self.model.config.num_hidden_layers: # norm - hidden_states, _ = self.model.norm( - forward_batch.hidden_states, forward_batch.residual + forward_batch.hidden_states = residual_batch.final_norm( + forward_batch.hidden_states, forward_batch, self.model.norm ) - forward_batch.hidden_states = hidden_states # logits process result = self.logits_processor( input_ids, forward_batch.hidden_states, self.lm_head, forward_batch