[Refactor] Rename layer boundary protocols, contracts and helpers (#41750)

This commit is contained in:
Cheng Wan
2026-09-29 21:05:48 -07:00
committed by GitHub
parent cb3ba2f2b7
commit 01b5f572b7
109 changed files with 2240 additions and 2243 deletions
@@ -19,7 +19,7 @@ from sglang.srt.layers.layer_boundary import (
tbo_split_moves,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
from sglang.srt.layers.layer_boundary.residual.access import finish_layer_stack
from sglang.srt.layers.layer_boundary.residual.access import export_output
from sglang.srt.layers.layer_boundary.residual.stream import ResidualStream
from sglang.srt.layers.moe import (
get_deepep_mode,
@@ -954,9 +954,9 @@ def model_forward_stages(
if not enable_tbo:
return execute_operations(inputs, strategy.operations)["hidden_states"]
stream = residual_batch.current(forward_batch)
stream = residual_batch.stream_of(forward_batch)
pending = stream.pending
hidden_states, residual = stream.finish(hidden_states)
hidden_states, residual = stream.export(hidden_states)
inputs["hidden_states"] = hidden_states
parts = _model_forward_tbo_split_inputs(
**inputs,
@@ -964,7 +964,7 @@ def model_forward_stages(
layer_input_rows=layers[0].attn_boundary.incoming_residual_rows,
)
for part in parts:
part["hidden_states"], child_stream = ResidualStream.arrive(
part["hidden_states"], child_stream = ResidualStream.from_handoff(
part["hidden_states"],
part.pop("residual"),
pending.update if pending is not None else None,
@@ -987,7 +987,7 @@ def model_forward_stages(
delta_stages=[0, strategy.tbo_delta_stages],
)
for output in outputs:
output["residual"] = residual_batch.current(output["forward_batch"])
output["residual"] = residual_batch.stream_of(output["forward_batch"])
hidden_states, forward_batch.residual_stream = _model_forward_tbo_merge_outputs(
*outputs, original_len
)
@@ -1110,7 +1110,7 @@ def _model_forward_tbo_merge_outputs(output_a, output_b, original_len):
assert pending_a.update is pending_b.update
update = pending_a.update
for output in (output_a, output_b):
output["hidden_states"], output["residual"] = finish_layer_stack(
output["hidden_states"], output["residual"] = export_output(
output["hidden_states"], output["residual"], output["forward_batch"]
)
@@ -1133,7 +1133,7 @@ def _model_forward_tbo_merge_outputs(output_a, output_b, original_len):
hidden, residual = _handle_key("hidden_states"), _handle_key("residual")
return (
ResidualStream.arrive(hidden, residual, update)
ResidualStream.from_handoff(hidden, residual, update)
if has_stream
else (hidden, residual)
)
@@ -35,7 +35,7 @@ def forward_mha_prepare_npu(
hidden_states: torch.Tensor,
forward_batch: "ForwardBatch",
zero_allocator: "BumpAllocator",
input_on_attention_tp_slices: bool,
input_on_attn_tp_slices: bool,
):
if m.q_lora_rank is not None:
q, latent_cache = (
@@ -63,7 +63,7 @@ def forward_mha_prepare_npu(
else:
q = m.q_a_layernorm(q)
if _use_ag_after_qlora and input_on_attention_tp_slices:
if _use_ag_after_qlora and input_on_attn_tp_slices:
q = scattered_to_tp_attn_full(q, forward_batch)
latent_cache = scattered_to_tp_attn_full(latent_cache, forward_batch)
q = m.q_b_proj(q)[0].view(-1, m.num_local_heads, m.qk_head_dim)
@@ -157,7 +157,7 @@ def forward_mla_prepare_npu(
hidden_states: torch.Tensor,
forward_batch: "ForwardBatch",
zero_allocator: "BumpAllocator",
input_on_attention_tp_slices: bool,
input_on_attn_tp_slices: bool,
):
if is_mla_preprocess_enabled():
if not hasattr(m, "mla_preprocess"):
@@ -190,7 +190,7 @@ def forward_mla_prepare_npu(
q_lora = None
if m.q_lora_rank is not None:
qkv_latent = get_attn_tp_context().fetch_qkv_latent()
if _use_ag_after_qlora and input_on_attention_tp_slices:
if _use_ag_after_qlora and input_on_attn_tp_slices:
q, latent_cache = qkv_latent.split(
[m.q_lora_rank, m.kv_lora_rank + m.qk_rope_head_dim],
dim=-1,
@@ -362,7 +362,7 @@ def forward_dsa_prepare_npu(
hidden_states: torch.Tensor,
forward_batch: "ForwardBatch",
zero_allocator: "BumpAllocator",
input_on_attention_tp_slices: bool,
input_on_attn_tp_slices: bool,
prev_topk_indices: torch.Tensor = None,
):
dynamic_scale = None
@@ -396,7 +396,7 @@ def forward_dsa_prepare_npu(
)
# overlap qk norm
q = m.q_a_layernorm(q)
if _use_ag_after_qlora and input_on_attention_tp_slices:
if _use_ag_after_qlora and input_on_attn_tp_slices:
q = scattered_to_tp_attn_full(q, forward_batch)
latent_cache = scattered_to_tp_attn_full(latent_cache, forward_batch)
q_lora = q.clone() # required for topk_indices
@@ -485,7 +485,7 @@ def forward_dsa_prepare_npu(
positions,
forward_batch,
m.layer_id,
input_on_attention_tp_slices,
input_on_attn_tp_slices,
dynamic_scale,
)
else:
@@ -60,7 +60,7 @@ class DSANPUIndexerMixin:
positions: torch.Tensor,
forward_batch: ForwardBatch,
layer_id: int,
input_on_attention_tp_slices: bool = False,
input_on_attn_tp_slices: bool = False,
dynamic_scale: torch.Tensor = None,
) -> torch.Tensor:
if get_attn_backend().forward_metadata.seq_lens_cpu_int is None:
@@ -140,7 +140,7 @@ class DSANPUIndexerMixin:
k_proj = self.wk(x)[0] # [b, s, 7168] @ [7168, 128] = [b, s, 128]
k = self.k_norm(k_proj)
if _use_ag_after_qlora and input_on_attention_tp_slices:
if _use_ag_after_qlora and input_on_attn_tp_slices:
k = scattered_to_tp_attn_full(k, forward_batch)
k_pe, k_nope = torch.split(
k,
@@ -284,7 +284,7 @@ class DSANPUIndexerMixin:
torch.npu.current_stream().wait_event(q_rope_event)
if envs.SGLANG_NPU_USE_MULTI_STREAM.get():
torch.npu.current_stream().wait_event(weights_event)
if _use_ag_after_qlora and input_on_attention_tp_slices:
if _use_ag_after_qlora and input_on_attn_tp_slices:
weights = scattered_to_tp_attn_full(weights, forward_batch)
block_table = get_attn_backend().forward_metadata.block_tables
if (
@@ -941,7 +941,7 @@ def can_use_flashinfer_allreduce(
# Size checks stay last: they read the token dim, which is symbolic under
# Dynamo, so statically-off configs must short-circuit before reaching them
# (same ordering rule as apply_flashinfer_allreduce_fusion).
# (same ordering rule as flashinfer_ar_fusion_applies).
token_num, hidden_dim = input_.shape
# MNNVL hard-fails instead of falling back when the width is not float4-aligned
@@ -18,27 +18,27 @@ from sglang.srt.layers.layer_boundary.adapters.attention import (
get_attn_tp_context,
)
from sglang.srt.layers.layer_boundary.boundary import (
make_boundary,
make_output_boundary,
bind_entry,
bind_exit,
tbo_split_moves,
)
from sglang.srt.layers.layer_boundary.construction import (
BatchVariant,
StageEdges,
VariantEdges,
)
from sglang.srt.layers.layer_boundary.contracts import (
EdgeDecl,
FusedMlpInput,
HandoffRows,
EdgeContract,
EntryPath,
ExitRows,
FfnInputFusion,
InputContract,
OutputContract,
ProducerReduction,
StageDecl,
StageEntry,
StageInput,
StageContract,
StageKind,
StageOutput,
StageSteps,
StagePath,
)
from sglang.srt.layers.layer_boundary.exit import FfnCompletion, FfnExit, MixerExit
from sglang.srt.layers.layer_boundary.exit import ExitDecision, FfnExit, MixerExit
from sglang.srt.layers.layer_boundary.factories import (
declare_attn,
declare_ffn,
@@ -50,9 +50,9 @@ from sglang.srt.layers.layer_boundary.layout import (
Layout,
SumGroup,
TokenAxis,
enable_moe_dense_fully_dp,
moe_cp_gathers_sparse_moe_input,
sparse_moe_gathers_over_moe_cp,
batch_gathers_over_moe_cp,
is_dense_ffn_fully_dp,
moe_gathers_over_moe_cp,
token_axis_sizes,
)
from sglang.srt.layers.layer_boundary.ops import (
@@ -60,17 +60,17 @@ from sglang.srt.layers.layer_boundary.ops import (
tp_reduce_scatter,
)
from sglang.srt.layers.layer_boundary.output import (
HandoffOutput,
DeferredFinalize,
UnreducedOutput,
reduce_output,
complete_owed,
)
from sglang.srt.layers.layer_boundary.residual import LayerResidual
from sglang.srt.layers.layer_boundary.residual import LayerResidualOps
from sglang.srt.layers.layer_boundary.residual.add_norm import (
ADD,
FUSE_ALLREDUCE_MAX_BATCH_SIZE,
NORM_QUANT_READ,
NORM_READ,
PLAIN_RESIDUAL,
NORM_QUANT_READOUT,
NORM_READOUT,
PLAIN_ADD,
PLAIN_RESIDUAL_OPS,
)
from sglang.srt.layers.layer_boundary.residual.mhc import (
MHCState,
@@ -82,40 +82,40 @@ __all__ = [
"make_attn_stage",
"make_ffn_stage",
"make_stages",
"ADD",
"PLAIN_ADD",
"AttentionInputs",
"StageSteps",
"EdgeDecl",
"HandoffRows",
"StagePath",
"EdgeContract",
"ExitRows",
"ProducerReduction",
"FUSE_ALLREDUCE_MAX_BATCH_SIZE",
"FfnCompletion",
"ExitDecision",
"FfnExit",
"FusedMlpInput",
"HandoffOutput",
"LayerResidual",
"FfnInputFusion",
"DeferredFinalize",
"LayerResidualOps",
"Layout",
"MHCState",
"MixerExit",
"NORM_QUANT_READ",
"NORM_READ",
"PLAIN_RESIDUAL",
"StageDecl",
"StageEntry",
"StageInput",
"NORM_QUANT_READOUT",
"NORM_READOUT",
"PLAIN_RESIDUAL_OPS",
"StageContract",
"EntryPath",
"InputContract",
"StageKind",
"StageOutput",
"OutputContract",
"SumGroup",
"TokenAxis",
"UnreducedOutput",
"enable_moe_dense_fully_dp",
"is_dense_ffn_fully_dp",
"get_attn_tp_context",
"make_boundary",
"make_output_boundary",
"moe_cp_gathers_sparse_moe_input",
"bind_entry",
"bind_exit",
"batch_gathers_over_moe_cp",
"move_rows",
"reduce_output",
"sparse_moe_gathers_over_moe_cp",
"complete_owed",
"moe_gathers_over_moe_cp",
"tbo_split_moves",
"token_axis_sizes",
"tp_reduce_scatter",
@@ -26,7 +26,7 @@ from sglang.srt.layers.dp_attention import (
is_dp_attention_enabled,
)
from sglang.srt.layers.layer_boundary.layout import (
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
)
from sglang.srt.layers.moe import get_moe_a2a_backend
from sglang.srt.model_executor.cuda_graph_config import (
@@ -107,7 +107,7 @@ class AttnTpContext:
and get_parallel().tp_size > 1
and not is_dp_attention_enabled()
and get_moe_a2a_backend().is_none()
and not enable_moe_dense_fully_dp()
and not is_dense_ffn_fully_dp()
and not check_cuda_graph_backend(Phase.PREFILL, Backend.TC_PIECEWISE)
and get_spec().speculative_algorithm != "EAGLE3"
)
@@ -168,7 +168,7 @@ def get_attn_tp_context():
return ATTN_TP_CONTEXT
def _redistribute_from_attn_tp_shards(tensor: torch.Tensor) -> torch.Tensor:
def attn_tp_gather(tensor: torch.Tensor) -> torch.Tensor:
gathered = get_local_dp_buffer(
get_parallel().attn_tp_group, hidden_size=tensor.shape[-1]
)
@@ -176,6 +176,6 @@ def _redistribute_from_attn_tp_shards(tensor: torch.Tensor) -> torch.Tensor:
return gathered
def _redistribute_to_attn_tp_shards(tensor: torch.Tensor) -> torch.Tensor:
def attn_tp_slice(tensor: torch.Tensor) -> torch.Tensor:
parallel = get_parallel()
return tensor.tensor_split(parallel.attn_tp_size)[parallel.attn_tp_rank]
@@ -37,8 +37,8 @@ def branch_input(
"""The FFN input and residual that ``source``'s boundary read for its
own FFN, for this layer's FFN, which branches from the same input: moved
to the rows this FFN needs and its residual's rows."""
rows, residual_rows, _ = source._branch_rows(forward_batch)
to, residual_to, _ = plan._branch_rows(forward_batch)
rows, residual_rows, _ = source.branch_rows(forward_batch)
to, residual_to, _ = plan.branch_rows(forward_batch)
if stream.pending is not None:
raise RuntimeError("a branch must start from a prepared stage input")
residual = stream.residual
@@ -56,7 +56,7 @@ def branch_output(
"""This layer's complete FFN output as a branch's contribution, which
adds to the layer's output without writing the residual: moved to the
rows the layer hands on."""
rows, _, to = plan._branch_rows(forward_batch)
rows, _, to = plan.branch_rows(forward_batch)
return move_rows(hidden_states, rows, to, forward_batch)
@@ -71,15 +71,15 @@ def merge_branch(
"""A contribution from ``branch_output`` summed with what ``source``'s
layer hands on, ``hidden_states`` and ``residual``, moved to the rows
this layer hands on."""
_, _, rows = source._branch_rows(forward_batch)
_, _, to = plan._branch_rows(forward_batch)
_, _, rows = source.branch_rows(forward_batch)
_, _, to = plan.branch_rows(forward_batch)
stream.check(hidden_states)
if stream.pending is None:
raise RuntimeError("branch merge requires a pending producer contribution")
update = stream.pending.update
hidden_states, residual = stream.finish(hidden_states)
hidden_states, residual = stream.export(hidden_states)
hidden_states = move_rows(hidden_states, rows, to, forward_batch)
residual = move_rows(residual, rows, to, forward_batch)
output = contribution + hidden_states
stream.write(residual)
return stream.leave(output, update), stream
return stream.record(output, update), stream
@@ -49,7 +49,7 @@ def maybe_prefetch_next_full_attention_kv(
prefetch_kv_buffer(next_full_attention_layer_id)
def dsa_cp_gather_hidden_states(hidden_states: torch.Tensor):
def attn_cp_gather(hidden_states: torch.Tensor):
attn_dp_size = get_parallel().attn_dp_size
attn_tp_size = get_parallel().attn_tp_size
assert attn_dp_size == 1 and attn_tp_size == 1
@@ -61,7 +61,7 @@ def dsa_cp_gather_hidden_states(hidden_states: torch.Tensor):
return hidden_states
def dsa_cp_reduce_scatter_hidden_states(hidden_states: torch.Tensor):
def attn_cp_reduce_scatter(hidden_states: torch.Tensor):
attn_dp_size = get_parallel().attn_dp_size
attn_tp_size = get_parallel().attn_tp_size
assert attn_dp_size == 1 and attn_tp_size == 1
@@ -17,12 +17,12 @@ from sglang.srt.layers.layer_boundary.layout import TokenAxis
from sglang.srt.runtime_context import LoRABatchLayout, get_forward
def publish_attention(enabled):
def publish_attn_lora_rows(enabled):
if enabled:
get_forward().set("lora_batch_layout", LoRABatchLayout.DP_LOCAL)
def publish_ffn(enabled, input_rows):
def publish_ffn_lora_rows(enabled, input_rows):
if enabled:
get_forward().set(
"lora_batch_layout",
@@ -1,26 +1,25 @@
"""Row requirements at the entrance to two-batch overlap."""
from sglang.srt.layers.layer_boundary.contracts import HandoffRows
from sglang.srt.layers.layer_boundary.layout import enable_moe_dense_fully_dp
from sglang.srt.layers.layer_boundary.contracts import ExitRows
from sglang.srt.layers.layer_boundary.layout import is_dense_ffn_fully_dp
from sglang.srt.runtime_context import get_exec
def tbo_handoff(sparse, next_sparse):
def tbo_exit_rows(sparse, next_layer_sparse):
"""Record a potential split between a dense layer and a sparse layer."""
return HandoffRows.TBO_SPLIT if not sparse and next_sparse else None
return ExitRows.TBO_SPLIT if not sparse and next_layer_sparse else None
def resolve_handoff_rows(requirement):
"""Bind a handoff requirement with the construction-time parallel config.
def resolve_exit_rows(requirement):
"""Bind an exit-row requirement to the construction-time parallel config.
Dense-local output must reach attention rows before the TBO split.
Moving that gather after the split changes padding and collective sizes.
"""
if requirement is HandoffRows.TBO_SPLIT:
if requirement is ExitRows.TBO_SPLIT:
return (
HandoffRows.ATTENTION
if enable_moe_dense_fully_dp()
and get_exec().overlap.enable_two_batch_overlap
ExitRows.ATTENTION
if is_dense_ffn_fully_dp() and get_exec().overlap.enable_two_batch_overlap
else None
)
return requirement
@@ -21,47 +21,47 @@ import msgspec
from sglang.srt.layers.layer_boundary.contracts import (
CpMoves,
EdgeDecl,
FusedMlpInput,
StageInput,
StageOutput,
EdgeContract,
FfnInputFusion,
InputContract,
OutputContract,
)
from sglang.srt.layers.layer_boundary.layout import (
Layout,
SumGroup,
TokenAxis,
_gathers_over_attention_cp,
_cp_gathers_over_attn_cp,
_same_ranks,
_sum_group,
token_axis_sizes,
)
from sglang.srt.layers.layer_boundary.ops import (
gather_attention_tp,
identity_output,
attn_cp_reduce_scatter_output,
attn_cp_take_back_output,
attn_tp_gather_input,
attn_tp_slice_output,
dp_cp_take_back_output,
keep_output,
moe_cp_take_back_output,
move_rows,
output_on_residual_shard,
reduce_scatter_over_cp,
scatter_moe_cp_output,
scatter_output,
take_back_attention_cp_shard,
take_back_cp_shard,
residual_slice_output,
tp_reduce_scatter,
tp_slice,
update_and_gather,
update_attn_tp_gather_output,
)
from sglang.srt.layers.layer_boundary.prepare import (
_consumer_step,
_dispatch_consumer,
_mlp_input_dp_partial,
_mlp_input_dp_replicate,
_mlp_input_gather_attention_cp,
_mlp_input_gather_moe_cp,
_mlp_input_on_residual_shard,
_mlp_input_residual_into_sum,
_mlp_input_scatter,
_mlp_input_slice,
_mlp_input_without_dp,
_read_input,
_attn_tp_reduce_scatter_update_read,
_attn_tp_slice_update_read,
_dispatch_by_update,
_dp_gather_sum_read,
_reduce_update_read,
_reduce_update_read_dp_gather,
_run_entry,
_then_attn_cp_gather,
_then_moe_cp_gather,
_tp_reduce_scatter_update_read_gather,
_tp_sum_with_residual_read,
_update_read,
)
from sglang.srt.runtime_context import get_parallel
@@ -75,11 +75,11 @@ def tbo_split_moves(layer_input_rows: Layout) -> Tuple[Callable, Callable]:
)
if layer_input_rows == attention:
return identity_output, identity_output
if layer_input_rows.sharded - attention.sharded == {TokenAxis.ATTN_TP_SCATTER}:
return keep_output, keep_output
if layer_input_rows.sharded - attention.sharded == {TokenAxis.ATTN_TP}:
# Each rank's slice: write the residual in and gather over attention
# TP, then take the slice of each half.
return update_and_gather, scatter_output
return update_attn_tp_gather_output, attn_tp_slice_output
raise NotImplementedError(f"{layer_input_rows=}")
@@ -87,26 +87,26 @@ def _cp_moves() -> CpMoves:
"""DSA and MLA CP gather equal shards over the attention-CP group and can
complete a sum over it. GQA prefill CP gathers blocks padded to the longest
over the MoE-CP group and takes back only a complete output."""
if _gathers_over_attention_cp():
if _cp_gathers_over_attn_cp():
return CpMoves(
gather=_mlp_input_gather_attention_cp,
take_back=take_back_attention_cp_shard,
reduce_scatter=reduce_scatter_over_cp,
gather=_then_attn_cp_gather,
take_back=attn_cp_take_back_output,
reduce_scatter=attn_cp_reduce_scatter_output,
reduce_scatter_group=lambda: get_parallel().attn_cp_group,
)
return CpMoves(
gather=_mlp_input_gather_moe_cp,
take_back=scatter_moe_cp_output,
gather=_then_moe_cp_gather,
take_back=moe_cp_take_back_output,
)
class Boundary(msgspec.Struct, frozen=True):
class EdgeBinding(msgspec.Struct, frozen=True):
"""The steps one layer runs at one boundary, chosen from both sides'
declarations. A layer runs the consumer's half of a boundary into one of
its stages, and the producer's half of the boundary after its last stage;
the neighbouring layer runs the other half of that one."""
edge: EdgeDecl
edge: EdgeContract
# The consumer's half: completing what the input owes, the add and the
# norm, and the moves onto the rows it needs that come before the read.
prepare: Optional[Callable] = None
@@ -141,21 +141,22 @@ class Boundary(msgspec.Struct, frozen=True):
)
def input_rows(edge: EdgeDecl) -> Layout:
def input_rows(edge: EdgeContract) -> Layout:
"""Consumer rows, retaining the axes it gathers inside its computation."""
return Layout(
edge.need.layout.sharded | (edge.residual_to.sharded & edge.need.gathers_itself)
edge.need.layout.sharded
| (edge.residual_to.sharded & edge.need.gathered_by_compute)
)
def make_boundary(
edge: EdgeDecl,
def bind_entry(
edge: EdgeContract,
*,
fusions: Tuple["FusedMlpInput", ...] = (),
fusions: Tuple["FfnInputFusion", ...] = (),
carried_fusions: Tuple[Callable, ...] = (),
cp_moves: Optional[CpMoves] = None,
enters_stack: bool = False,
) -> Boundary:
) -> EdgeBinding:
"""Bind the consumer half of an edge at construction time.
Args:
@@ -170,15 +171,15 @@ def make_boundary(
Multiple update capabilities select among preconstructed paths; a single
capability needs no runtime dispatcher.
"""
capabilities = edge.update_capabilities
capabilities = edge.arriving_plain_add
if not capabilities:
if edge.produced.update is None:
raise ValueError("an arrival must declare its update capabilities")
capabilities = (edge.produced.update.adds_plainly,)
capabilities = (edge.produced.update.is_plain_add,)
paths = {
capability: _bind_consumer(
capability: _bind_entry_path(
edge,
adds_plainly=capability,
is_plain_add=capability,
fusions=fusions,
carried_fusions=carried_fusions,
cp_moves=cp_moves,
@@ -195,21 +196,21 @@ def make_boundary(
first,
preserves_residual=None,
prepare=partial(
_dispatch_consumer,
_dispatch_by_update,
paths={capability: path.prepare for capability, path in paths.items()},
),
)
def _bind_consumer(
edge: EdgeDecl,
def _bind_entry_path(
edge: EdgeContract,
*,
adds_plainly: bool,
fusions: Tuple["FusedMlpInput", ...] = (),
is_plain_add: bool,
fusions: Tuple["FfnInputFusion", ...] = (),
carried_fusions: Tuple[Callable, ...] = (),
cp_moves: Optional[CpMoves] = None,
enters_stack: bool = False,
) -> Boundary:
) -> EdgeBinding:
"""The consumer's half of ``edge``, chosen from the edge's declarations and
the producer's update: what a value carries for a batch (a sum or a handoff
its producer left) is completed first, trying ``carried_fusions``; a sum
@@ -221,26 +222,26 @@ def _bind_consumer(
first stage. The steps read only this edge's declarations, never what the
producer chose for a batch."""
# A fused kernel runs the add and the norm itself.
plain = adds_plainly and edge.need.read.norms_plainly
step, input_move = _select_input_steps(
plain = is_plain_add and edge.need.read.is_plain_norm
step, input_move = _select_entry_step(
edge.produced,
residual=edge.residual,
residual_to=edge.residual_to,
need=edge.need,
adds_plainly=adds_plainly,
is_plain_add=is_plain_add,
fusions=fusions if plain else (),
residual_joins_sum=edge.residual_joins_sum,
cp_moves=cp_moves,
enters_stack=enters_stack,
)
completed_step = None
if edge.produced.always_leaves:
completed_step, _ = _select_input_steps(
msgspec.structs.replace(edge.produced, always_leaves=False),
if edge.produced.always_partial:
completed_step, _ = _select_entry_step(
msgspec.structs.replace(edge.produced, always_partial=False),
residual=edge.residual,
residual_to=edge.residual_to,
need=edge.need,
adds_plainly=adds_plainly,
is_plain_add=is_plain_add,
fusions=(),
residual_joins_sum=False,
cp_moves=cp_moves,
@@ -250,12 +251,12 @@ def _bind_consumer(
# again (e.g. MHC expansion). Both alternatives are bound at construction.
written_step = None
if enters_stack:
written_step, _ = _select_input_steps(
written_step, _ = _select_entry_step(
edge.produced,
residual=edge.residual,
residual_to=edge.residual_to,
need=edge.need,
adds_plainly=adds_plainly,
is_plain_add=is_plain_add,
fusions=fusions if plain else (),
residual_joins_sum=edge.residual_joins_sum,
cp_moves=cp_moves,
@@ -263,10 +264,10 @@ def _bind_consumer(
)
preserves_residual = None
if (
edge.produced.always_leaves
edge.produced.always_partial
and edge.produced.group is SumGroup.ATTN_TP
and isinstance(step, partial)
and step.func is _mlp_input_without_dp
and step.func is _reduce_update_read
and not step.keywords["gathers_residual"]
):
selected = step.keywords["fusions"]
@@ -276,15 +277,15 @@ def _bind_consumer(
preserves_residual = next(
f.preserves_residual for f in fusions if f.run == selected[0]
)
return Boundary(
return EdgeBinding(
edge,
preserves_residual=preserves_residual,
prepare=partial(
_consumer_step,
_run_entry,
step=step,
adds_plainly=adds_plainly,
is_plain_add=is_plain_add,
carried_fusions=carried_fusions if plain else (),
expected_sum=edge.produced.group if edge.produced.always_leaves else None,
expected_sum=edge.produced.group if edge.produced.always_partial else None,
completed_step=completed_step,
written_step=written_step,
),
@@ -292,10 +293,8 @@ def _bind_consumer(
)
def make_output_boundary(
edge: EdgeDecl, *, cp_moves: Optional[CpMoves] = None
) -> Boundary:
"""Bind the producer half of a layer/branch handoff.
def bind_exit(edge: EdgeContract, *, cp_moves: Optional[CpMoves] = None) -> EdgeBinding:
"""Bind the producer half of a layer or branch exit.
Args:
edge: Output contract and destination/residual rows. Deferred updates
@@ -308,24 +307,24 @@ def make_output_boundary(
transport. The receiver binds its read independently.
"""
update = edge.produced.update
if not getattr(update, "at_producer", False):
if not getattr(update, "can_defer_across_layers", False):
if not getattr(update, "applied_at_exit", False):
if not getattr(update, "outlives_layer", False):
raise NotImplementedError(
"a deferred update must guarantee its lifetime across layers"
)
if not update.adds_plainly and get_parallel().pp_size > 1:
if not update.is_plain_add and get_parallel().pp_size > 1:
raise NotImplementedError(
"pipeline boundaries require a plain add or a producer-written residual"
)
if edge.need.layout != edge.residual_to:
raise NotImplementedError(f"{edge=}")
returns_over_dp, output_move, completes_sum = _select_ffn_output_move(
returns_over_dp, output_move, completes_sum = _select_exit_move(
edge.produced,
residual=edge.residual,
to=edge.residual_to,
cp_moves=cp_moves,
)
return Boundary(
return EdgeBinding(
edge,
output_move=output_move,
returns_over_dp=returns_over_dp,
@@ -333,14 +332,14 @@ def make_output_boundary(
)
def _select_input_steps(
produced: StageOutput,
def _select_entry_step(
produced: OutputContract,
*,
residual: Layout,
residual_to: Layout,
need: StageInput,
adds_plainly: bool,
fusions: Tuple[FusedMlpInput, ...],
need: InputContract,
is_plain_add: bool,
fusions: Tuple[FfnInputFusion, ...],
residual_joins_sum: bool,
cp_moves: Optional[CpMoves],
enters_stack: bool,
@@ -357,17 +356,17 @@ def _select_input_steps(
read = need.read
# What the input owes by construction; a sum the producer leaves only for
# some batches comes with the value and is completed before these steps.
owes = produced.group if produced.always_leaves else None
if produced.always_leaves and owes is None:
owes = produced.group if produced.always_partial else None
if produced.always_partial and owes is None:
raise NotImplementedError(f"{produced=}")
gathered = produced.layout.sharded - need.layout.sharded - need.gathers_itself
gathered = produced.layout.sharded - need.layout.sharded - need.gathered_by_compute
sliced = need.layout.sharded - produced.layout.sharded
if sliced:
# Each attention-TP rank takes its own slice: the reduce-scatter
# completes the attention-TP sum and slices in one collective; a
# complete value is only sliced.
if (
sliced != {TokenAxis.ATTN_TP_SCATTER}
sliced != {TokenAxis.ATTN_TP}
or gathered
or owes not in (None, SumGroup.ATTN_TP)
or residual_to != need.layout
@@ -376,13 +375,15 @@ def _select_input_steps(
raise NotImplementedError(f"{produced=} {residual=} {need=}")
return (
partial(
_mlp_input_scatter if owes is SumGroup.ATTN_TP else _mlp_input_slice,
_attn_tp_reduce_scatter_update_read
if owes is SumGroup.ATTN_TP
else _attn_tp_slice_update_read,
scatters_residual=residual != residual_to,
read=read,
),
None,
)
if residual_to.sharded - produced.layout.sharded == {TokenAxis.ATTN_TP_SCATTER}:
if residual_to.sharded - produced.layout.sharded == {TokenAxis.ATTN_TP}:
if residual == residual_to:
# The residual stays on each rank's slice while the stage takes the
# rows around it (MHC on an input-scattered batch).
@@ -390,7 +391,9 @@ def _select_input_steps(
raise NotImplementedError(f"{produced=} {residual=} {need=}")
return (
partial(
_mlp_input_on_residual_shard, read=read, reduces=owes is not None
_tp_reduce_scatter_update_read_gather,
read=read,
reduces=owes is not None,
),
None,
)
@@ -399,14 +402,14 @@ def _select_input_steps(
if (
owes not in (None, SumGroup.TP)
or residual.sharded
or TokenAxis.ATTN_TP_SCATTER not in need.gathers_itself
or residual_to.sharded != {TokenAxis.ATTN_TP_SCATTER}
or TokenAxis.ATTN_TP not in need.gathered_by_compute
or residual_to.sharded != {TokenAxis.ATTN_TP}
):
raise NotImplementedError(f"{produced=} {residual=} {need=}")
return (
partial(
_read_input,
layer_input=tp_reduce_scatter if owes is not None else tp_slice,
_update_read,
pre_move=tp_reduce_scatter if owes is not None else tp_slice,
enters_stack=enters_stack,
read=read,
),
@@ -416,19 +419,19 @@ def _select_input_steps(
# Each CP rank completes its own chunk, then the CP moves gather them.
if cp_moves is None:
raise NotImplementedError(f"{produced=} {need=}")
on_chunk, _ = _select_input_steps(
on_chunk, _ = _select_entry_step(
produced,
residual=residual,
residual_to=residual_to,
need=StageInput(produced.layout, read=read),
adds_plainly=adds_plainly,
need=InputContract(produced.layout, read=read),
is_plain_add=is_plain_add,
fusions=fusions,
residual_joins_sum=residual_joins_sum,
cp_moves=cp_moves,
enters_stack=enters_stack,
)
return (partial(cp_moves.gather, gather=on_chunk), None)
if gathered == {TokenAxis.ATTN_TP_SCATTER}:
if gathered == {TokenAxis.ATTN_TP}:
# A complete input on each rank's slice, gathered over attention TP
# once it is read.
if (
@@ -439,12 +442,12 @@ def _select_input_steps(
raise NotImplementedError(f"{produced=} {residual=} {need=}")
return (
partial(
_read_input,
layer_input=None,
_update_read,
pre_move=None,
enters_stack=enters_stack,
read=read,
),
gather_attention_tp,
attn_tp_gather_input,
)
if (
residual_to != produced.layout
@@ -455,7 +458,7 @@ def _select_input_steps(
{TokenAxis.ATTN_DP, TokenAxis.ATTN_CP},
)
or residual.sharded - residual_to.sharded
not in (frozenset(), {TokenAxis.ATTN_TP_SCATTER})
not in (frozenset(), {TokenAxis.ATTN_TP})
):
raise NotImplementedError(f"{produced=} {residual=} {need=}")
# A residual arriving on each rank's slice is gathered back first.
@@ -465,7 +468,7 @@ def _select_input_steps(
if gathers_residual:
return (
partial(
_mlp_input_without_dp,
_reduce_update_read,
gathers_residual=True,
fusions=(),
group=None,
@@ -475,8 +478,8 @@ def _select_input_steps(
)
return (
partial(
_read_input,
layer_input=None,
_update_read,
pre_move=None,
enters_stack=enters_stack,
read=read,
),
@@ -485,9 +488,9 @@ def _select_input_steps(
if gathers_residual and residual_joins_sum:
# Each rank adds its slice of the residual into its share of the
# sum, so the all-reduce also brings the residual back to every row.
if owes is not SumGroup.ATTN_TP or not adds_plainly:
if owes is not SumGroup.ATTN_TP or not is_plain_add:
raise NotImplementedError(f"{produced=} {residual=} {need=}")
return (partial(_mlp_input_residual_into_sum, read=read), None)
return (partial(_tp_sum_with_residual_read, read=read), None)
# A sum over TP completes only on rows every TP rank holds: the TP group
# spans attention DP and CP.
if owes is not SumGroup.ATTN_TP and (
@@ -497,7 +500,7 @@ def _select_input_steps(
fused = tuple(f for f in fusions if f.completes is owes)
return (
partial(
_mlp_input_without_dp,
_reduce_update_read,
gathers_residual=gathers_residual,
fusions=tuple(f.run for f in fused),
group=owes,
@@ -516,13 +519,13 @@ def _select_input_steps(
places_cp_shards = TokenAxis.ATTN_CP in gathered
if (
owes_attention_tp
and not read.before_gather
and adds_plainly
and read.norms_plainly
and not read.reads_before_dp_gather
and is_plain_add
and read.is_plain_norm
):
return (
partial(
_mlp_input_dp_partial,
_dp_gather_sum_read,
gathers_residual=gathers_residual,
places_cp_shards=places_cp_shards,
read=read,
@@ -531,7 +534,7 @@ def _select_input_steps(
)
return (
partial(
_mlp_input_dp_replicate,
_reduce_update_read_dp_gather,
gathers_residual=gathers_residual,
reduces_attention_tp=owes_attention_tp,
places_cp_shards=places_cp_shards,
@@ -541,8 +544,8 @@ def _select_input_steps(
)
def _select_ffn_output_move(
produced: StageOutput,
def _select_exit_move(
produced: OutputContract,
*,
residual: Layout,
to: Layout,
@@ -557,22 +560,22 @@ def _select_ffn_output_move(
update = produced.update
if produced.layout == residual:
if to == residual:
return False, identity_output, False
if to.sharded == residual.sharded - {TokenAxis.ATTN_TP_SCATTER}:
return False, keep_output, False
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_and_gather, update=update), False
return False, partial(update_attn_tp_gather_output, update=update), False
raise NotImplementedError(f"{produced=} {residual=} {to=}")
returned = residual.sharded - produced.layout.sharded
if returned == {TokenAxis.ATTN_TP_SCATTER} and to in (residual, produced.layout):
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.leaves_for_reduce_scatter
sums = produced.may_reduce_scatter
return (
False,
partial(
output_on_residual_shard,
residual_slice_output,
sums=sums,
gathers_back=to != residual,
update=update,
@@ -584,7 +587,7 @@ def _select_ffn_output_move(
if returned == {TokenAxis.ATTN_CP}:
if cp_moves is None:
raise NotImplementedError(f"{produced=} {residual=} {to=}")
if not produced.leaves_for_reduce_scatter:
if not produced.may_reduce_scatter:
# A complete output: this rank's block of it, nothing summed.
return False, cp_moves.take_back, False
# The FFN leaves its sum: only a take-back that sums over the same
@@ -596,7 +599,7 @@ def _select_ffn_output_move(
return False, cp_moves.reduce_scatter, True
if returned == {TokenAxis.ATTN_DP, TokenAxis.ATTN_CP}:
# This rank's CP shard, from where the DP gather put it.
return False, take_back_cp_shard, False
return False, dp_cp_take_back_output, False
if returned != {TokenAxis.ATTN_DP}:
raise NotImplementedError(f"{produced=} {residual=} {to=}")
return True, None, False
@@ -21,33 +21,33 @@ from sglang.srt.environ import envs
from sglang.srt.layers.layer_boundary.adapters.attention import get_attn_tp_context
from sglang.srt.layers.layer_boundary.boundary import (
_cp_moves,
make_boundary,
make_output_boundary,
bind_entry,
bind_exit,
)
from sglang.srt.layers.layer_boundary.contracts import (
BatchVariant,
CpMoves,
EdgeDecl,
EdgeContract,
EntryPath,
ProducerReduction,
StageEntry,
StageKind,
StageSteps,
StagePath,
)
from sglang.srt.layers.layer_boundary.exit import OutputBoundary
from sglang.srt.layers.layer_boundary.exit import ExitPolicy
from sglang.srt.layers.layer_boundary.fusions.allreduce import (
attention_fusions,
ffn_fusions,
attn_input_fusions,
ffn_input_fusions,
)
from sglang.srt.layers.layer_boundary.layout import (
TokenAxis,
_batch_shards_over_cp,
_gathers_over_attention_cp,
_generic_prefill_cp_shards_tokens,
enable_moe_dense_fully_dp,
_cp_gathers_over_attn_cp,
_prefill_cp_shards_tokens,
is_dense_ffn_fully_dp,
)
from sglang.srt.layers.layer_boundary.prepare import (
_hand_qkv_hook_its_input,
_hand_scattered_input_to_attention,
_attn_input_default,
_attn_input_scattered,
)
from sglang.srt.layers.layer_boundary.stage import StageBoundary
from sglang.srt.layers.moe import (
@@ -64,14 +64,14 @@ from sglang.srt.speculative.spec_info import SpeculativeAlgorithm
_use_ag_after_qlora = envs.SGLANG_USE_AG_AFTER_QLORA.get()
def _refuse_uncovered_cp_moe(moe_on_local_rows: bool, cp_shards: bool) -> None:
def _reject_unsupported_cp_moe(moe_on_local_rows: bool, cp_shards: bool) -> None:
"""A MoE layer under attention CP whose tokens the steps cannot bring
to it: under a prefill CP, one dispatched per DP shard under attention DP
and GQA CP, and one on the TP group whose data-parallel groups are the CP
ranks under DSA or MLA CP; and under attention DP, one on the TP group
whose data-parallel groups are the CP ranks."""
parallel = get_parallel()
gqa = not _gathers_over_attention_cp()
gqa = not _cp_gathers_over_attn_cp()
if moe_on_local_rows:
if cp_shards and gqa and parallel.attn_dp_size > 1:
raise NotImplementedError(
@@ -90,7 +90,7 @@ def _refuse_uncovered_cp_moe(moe_on_local_rows: bool, cp_shards: bool) -> None:
)
def _input_can_be_scattered() -> bool:
def _input_scattered_possible() -> bool:
"""Whether a batch may run this layer with input-scattered attention:
configured, on TP without attention DP, a prefill CP, an a2a backend or
a dense MLP on every rank. The rest of what ``AttnTpContext.init_context`` requires is only
@@ -100,28 +100,28 @@ def _input_can_be_scattered() -> bool:
parallel.enable_attn_tp_input_scattered
and parallel.tp_size > 1
and parallel.attn_dp_size == 1
and not _generic_prefill_cp_shards_tokens()
and not _prefill_cp_shards_tokens()
and get_moe_a2a_backend().is_none()
and not enable_moe_dense_fully_dp()
and not is_dense_ffn_fully_dp()
)
@dataclass(frozen=True)
class StageEdges:
class VariantEdges:
"""One stage's incoming and outgoing contracts for one batch variant.
Fields:
incoming: Consumer-side contract used to bind prepare.
outgoing: Producer-side contract used to bind exit transport.
handoff: Optional attention adapter run after input preparation/movement.
attn_input_adapter: Optional attention adapter run after input preparation/movement.
cp_moves: Strategy-specific context-parallel gather and return operations.
No executable neighbouring stage or neighbouring norm is required.
"""
incoming: EdgeDecl
outgoing: EdgeDecl
handoff: Optional[Callable] = None
incoming: EdgeContract
outgoing: EdgeContract
attn_input_adapter: Optional[Callable] = None
cp_moves: Optional[CpMoves] = None
@@ -135,13 +135,13 @@ class StagePlan:
Args:
kind: Boundary role selecting attention or FFN fusion adapters.
norm: This stage's consumer normalization module.
variants: Mapping from BatchVariant to StageEdges. Construction binds
variants: Mapping from BatchVariant to VariantEdges. Construction binds
each entry once; a forward selects an existing path by batch facts.
enters_stack: Whether this stage initializes the residual from embeddings.
prepared_input: Branch reusing an already-read input; requires branch_input
is_branch: Branch reusing an already-read input; requires branch_input
instead of a normal prepare to avoid repeating the read/update.
terminal: Whether the stage ends the model's layer stack.
direct_handoff: Attention can publish its output with finish instead of
finishes_directly: Attention can publish its output with finish instead of
an exit scope and output transport.
qkv_latent_func: Optional hook for prepared attention input.
fusions: Optional backend provider of ordered consumer fusion candidates
@@ -158,17 +158,17 @@ class StagePlan:
variants,
*,
enters_stack=False,
prepared_input=False,
is_branch=False,
terminal=False,
direct_handoff=False,
finishes_directly=False,
qkv_latent_func=None,
fusions=None,
):
self.norm = norm
self.variants = dict(variants)
self.edges = dict(variants)
self.enters_stack = enters_stack
self.terminal = terminal
self.direct_handoff = direct_handoff
self.finishes_directly = finishes_directly
self.qkv_latent_func = qkv_latent_func
self.fusions = fusions
self._speculative_algo = SpeculativeAlgorithm.from_string(
@@ -177,50 +177,48 @@ class StagePlan:
self._publish_lora_layout = get_parallel().enable_dp_attention and bool(
get_lora().enable_lora
)
self._fusion_rows = None
self._next_input_rows = None
carried = (
attention_fusions(
self, next(iter(self.variants.values())).incoming.need.read
)
attn_input_fusions(self, next(iter(self.edges.values())).incoming.need.read)
if kind is StageKind.ATTENTION
else ()
)
fused = ffn_fusions(self) if kind is StageKind.FFN else ()
self._paths = {}
for variant, edges in self.variants.items():
if prepared_input:
fused = ffn_input_fusions(self) if kind is StageKind.FFN else ()
self.paths = {}
for variant, edges in self.edges.items():
if is_branch:
# The branch adapter moves an already-read input and forks its
# stream. Binding a normal prepare would add or norm it twice.
entry = StageEntry(
entry = EntryPath(
prepare=_requires_branch_input,
input_rows=edges.incoming.need.layout,
)
else:
into = make_boundary(
into = bind_entry(
edges.incoming,
fusions=fused,
carried_fusions=carried,
cp_moves=edges.cp_moves,
enters_stack=enters_stack,
)
entry = StageEntry(
entry = EntryPath(
prepare=into.prepare,
input_rows=into.input_rows,
input_move=into.input_move,
handoff=edges.handoff,
attn_input_adapter=edges.attn_input_adapter,
capture_move=into.capture_move,
capture_move_allocates=into.capture_move_allocates,
preserves_residual=into.preserves_residual,
input_sum=edges.incoming.produced.group
if edges.incoming.produced.always_leaves
declared_sum=edges.incoming.produced.group
if edges.incoming.produced.always_partial
else None,
)
out = (
None
if direct_handoff
else make_output_boundary(edges.outgoing, cp_moves=edges.cp_moves)
if finishes_directly
else bind_exit(edges.outgoing, cp_moves=edges.cp_moves)
)
self._paths[variant] = StageSteps(
self.paths[variant] = StagePath(
entry=entry,
output=edges.outgoing.produced,
output_move=None if out is None else out.output_move,
@@ -232,13 +230,13 @@ class StagePlan:
@property
def incoming_residual_rows(self):
return self.variants[BatchVariant.ORDINARY].incoming.residual
return self.edges[BatchVariant.ORDINARY].incoming.residual
@property
def input_on_attention_tp_slices(self):
return TokenAxis.ATTN_TP_SCATTER in self.incoming_residual_rows.sharded
def input_on_attn_tp_slices(self):
return TokenAxis.ATTN_TP in self.incoming_residual_rows.sharded
def _variant(self, forward_batch):
def variant_for(self, forward_batch):
# The batch determines its rows; missing paths must not change them.
if get_forward().sp_active:
return BatchVariant.SEQUENCE_PARALLEL
@@ -248,32 +246,32 @@ class StagePlan:
return BatchVariant.CONTEXT_PARALLEL
return BatchVariant.ORDINARY
def _batch_steps(self, forward_batch):
variant = self._variant(forward_batch)
def path_for(self, forward_batch):
variant = self.variant_for(forward_batch)
try:
return self._paths[variant]
return self.paths[variant]
except KeyError:
raise NotImplementedError(
f"no stage boundary path for the active {variant.name} batch"
) from None
def fusion_rows(self, forward_batch):
if self._fusion_rows is not None:
return self._fusion_rows[self._variant(forward_batch)]
entry = self._batch_steps(forward_batch)
def fused_input_rows(self, forward_batch):
if self._next_input_rows is not None:
return self._next_input_rows[self.variant_for(forward_batch)]
entry = self.path_for(forward_batch)
return entry.entry.input_rows
def produced(self, forward_batch):
return self._batch_steps(forward_batch).output
return self.path_for(forward_batch).output
@cached_property
def output(self):
return OutputBoundary(self)
return ExitPolicy(self)
def _branch_rows(self, forward_batch):
if self._variant(forward_batch) is not BatchVariant.ORDINARY:
def branch_rows(self, forward_batch):
if self.variant_for(forward_batch) is not BatchVariant.ORDINARY:
raise NotImplementedError("branch transport requires ordinary batch rows")
edges = self.variants[BatchVariant.ORDINARY]
edges = self.edges[BatchVariant.ORDINARY]
return (
edges.incoming.need.layout,
edges.incoming.residual_to,
@@ -289,30 +287,32 @@ def _bind_stage(declaration, norm, incoming, outgoing, **options):
variants = {}
for variant, edge in incoming.entries.items():
if (
declaration.update.at_producer
declaration.update.applied_at_exit
and TokenAxis.ATTN_CP
in edge.produced.layout.sharded - edge.need.layout.sharded
):
raise NotImplementedError("MHC with a gather over attention CP")
handoff = None
attn_input_adapter = None
if declaration.kind is StageKind.ATTENTION:
handoff = (
_hand_scattered_input_to_attention
attn_input_adapter = (
_attn_input_scattered
if variant is BatchVariant.INPUT_SCATTERED
and not declaration.update.adds_plainly
else _hand_qkv_hook_its_input
and not declaration.update.is_plain_add
else _attn_input_default
)
moves = _cp_moves() if variant is BatchVariant.CONTEXT_PARALLEL else None
variants[variant] = StageEdges(edge, outgoing.exits[variant], handoff, moves)
variants[variant] = VariantEdges(
edge, outgoing.exits[variant], attn_input_adapter, moves
)
plan = StagePlan(
declaration.kind,
norm,
variants,
enters_stack=incoming.producer is None,
prepared_input=declaration.prepared_from is not None,
is_branch=declaration.prepared_from is not None,
terminal=declaration.terminal,
direct_handoff=declaration.kind is StageKind.ATTENTION
and declaration.reduction is ProducerReduction.PARTIAL,
finishes_directly=declaration.kind is StageKind.ATTENTION
and declaration.reduction is ProducerReduction.ALWAYS_PARTIAL,
**options,
)
if declaration.kind is StageKind.ATTENTION and outgoing.consumer is not None:
@@ -320,7 +320,7 @@ def _bind_stage(declaration, norm, incoming, outgoing, **options):
# link to its execution plan. Kernel binding remains consumer-owned.
from sglang.srt.layers.layer_boundary.boundary import input_rows
plan._fusion_rows = {
plan._next_input_rows = {
v: input_rows(edge) for v, edge in outgoing.entries.items()
}
@@ -22,28 +22,29 @@ import torch
from sglang.srt.distributed import GroupCoordinator
from sglang.srt.layers.layer_boundary.layout import Layout, SumGroup, TokenAxis
from sglang.srt.layers.layer_boundary.output import OutputTransform
from sglang.srt.layers.layer_boundary.residual import StageRead, StageUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import ADD, NORM_READ
from sglang.srt.layers.layer_boundary.residual import ResidualReadout, ResidualUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import NORM_READOUT, PLAIN_ADD
class ProducerReduction(Enum):
"""Describe compute's cooperation with its output boundary.
PARTIAL is attention-only: finish() publishes its partial sum. SCOPED
follows exit() flags for an FFN or single-stage mixer. LOCAL_TAIL is FFN-only:
ALWAYS_PARTIAL is attention-only: finish() publishes its partial sum. EXIT_SCOPED
follows exit() flags for an FFN or single-stage mixer. TAIL_AFTER_SUM is FFN-only:
compute adds a replicated component after its internal sum, so the
boundary never defers that sum to the next layer. A selected reduce-scatter
still applies, so compute must add the tail only when it completes the sum.
"""
PARTIAL = auto()
SCOPED = auto()
ALWAYS_PARTIAL = auto()
EXIT_SCOPED = auto()
# A replicated component is added after the sum inside compute.
LOCAL_TAIL = auto()
TAIL_AFTER_SUM = auto()
class HandoffRows(Enum):
"""A required layer/branch handoff, independent of compute's input rows."""
class ExitRows(Enum):
"""The rows a layer or branch must leave its output on, independent of
compute's input rows."""
ATTENTION = auto()
TBO_SPLIT = auto()
@@ -56,12 +57,12 @@ class BatchVariant(Enum):
SEQUENCE_PARALLEL = auto()
class StageInput(msgspec.Struct, frozen=True):
class InputContract(msgspec.Struct, frozen=True):
"""Declare the consumer's input rows and read operation.
Fields:
layout: Token sharding required by compute.
gathers_itself: Token axes compute can gather internally; the boundary
gathered_by_compute: Token axes compute can gather internally; the boundary
may hand it input still sharded over those axes.
read: Operation that derives input from the updated residual.
"""
@@ -69,23 +70,23 @@ class StageInput(msgspec.Struct, frozen=True):
layout: Layout
# Token axes the consumer gathers over itself when its input arrives
# sharded over them.
gathers_itself: FrozenSet[TokenAxis] = frozenset()
gathered_by_compute: FrozenSet[TokenAxis] = frozenset()
# How the consumer reads its input from the residual.
read: StageRead = NORM_READ
read: ResidualReadout = NORM_READOUT
class StageOutput(msgspec.Struct, frozen=True):
class OutputContract(msgspec.Struct, frozen=True):
"""Declare producer rows and permitted reduction handoffs at construction.
Fields:
layout: Token sharding of the producer contribution.
group: Named sum group, or None when there is no reduction.
always_leaves: Compute always returns a partial sum.
leaves_for_next_layer: Compute can skip reduction under the exit scope
always_partial: Compute always returns a partial sum.
may_defer_to_next: Compute can skip reduction under the exit scope
and let the following layer complete it.
leaves_for_reduce_scatter: Compute can leave reduction to a fixed-size
may_reduce_scatter: Compute can leave reduction to a fixed-size
reduce-scatter selected by the boundary.
leaves_for_reduce_scatterv: Compute can leave reduction to the selected
may_reduce_scatterv: Compute can leave reduction to the selected
variable-size attention-DP combine.
update: Producer residual operation; None on an arrival contract that
declares capabilities and obtains the actual update from the stream.
@@ -100,20 +101,20 @@ class StageOutput(msgspec.Struct, frozen=True):
group: Optional[SumGroup] = None
# The producer never reduces its output, e.g. a row-parallel projection
# built with reduce_results=False.
always_leaves: bool = False
always_partial: bool = False
# Otherwise it leaves the sum only when the boundary publishes the flag for
# it: fuse_mlp_allreduce, or mlp_reduce_scatter.
leaves_for_next_layer: bool = False
leaves_for_reduce_scatter: bool = False
may_defer_to_next: bool = False
may_reduce_scatter: bool = False
# Whether the selected attention-DP combine may complete this sum.
leaves_for_reduce_scatterv: bool = False
may_reduce_scatterv: bool = False
# How the producer's output is written into the residual. An arrival
# description has no producer object; its edge declares capabilities only.
update: Optional[StageUpdate] = ADD
update: Optional[ResidualUpdate] = PLAIN_ADD
transform: Optional[OutputTransform] = None
class StageDecl(msgspec.Struct, frozen=True):
class StageContract(msgspec.Struct, frozen=True):
"""Resolved input and output contracts for one stage and batch variant.
Fields:
@@ -121,11 +122,11 @@ class StageDecl(msgspec.Struct, frozen=True):
output: Producer row, reduction and residual-update contract.
"""
input: StageInput
output: StageOutput
input: InputContract
output: OutputContract
class EdgeDecl(msgspec.Struct, frozen=True):
class EdgeContract(msgspec.Struct, frozen=True):
"""Describe both sides of a boundary and the residual's row movement.
Fields:
@@ -135,23 +136,23 @@ class EdgeDecl(msgspec.Struct, frozen=True):
residual_to: Residual layout after the boundary.
residual_joins_sum: Whether one rank may add the residual into a partial
before reduction; valid only for an eligible plain-add update.
update_capabilities: Allowed values of StageUpdate.adds_plainly for
arriving_plain_add: Allowed values of ResidualUpdate.is_plain_add for
arriving contributions. Empty means use produced.update's capability.
The actual update object travels with the residual stream.
"""
produced: StageOutput
need: StageInput
produced: OutputContract
need: InputContract
residual: Layout
residual_to: Layout
# Whether the residual is added into one rank's share of the produced sum
# before that sum completes, instead of after it.
residual_joins_sum: bool = False
# Capabilities allowed to arrive from another layer, not its update object.
update_capabilities: Tuple[bool, ...] = ()
arriving_plain_add: Tuple[bool, ...] = ()
class FusedMlpInput(msgspec.Struct, frozen=True):
class FfnInputFusion(msgspec.Struct, frozen=True):
"""A kernel that completes the sum the attention output owes together with
the residual add and the post-attention norm, in that order.
@@ -181,7 +182,7 @@ class CpMoves(msgspec.Struct, frozen=True):
reduce_scatter_group: Optional[Callable[[], GroupCoordinator]] = None
class StageEntry(msgspec.Struct, frozen=True):
class EntryPath(msgspec.Struct, frozen=True):
"""Bound consumer operations for one batch variant.
Fields:
@@ -189,15 +190,15 @@ class StageEntry(msgspec.Struct, frozen=True):
returning compute input and updated residual; finishes owed work,
applies the producer update and performs the consumer read.
input_rows: Layout handed to compute after preparation and input_move.
input_move: Optional movement after prepare, before the compute handoff.
handoff: Optional callable(input, forward_batch, qkv_latent_func) that
input_move: Optional movement after prepare, before compute takes the input.
attn_input_adapter: Optional callable(input, forward_batch, qkv_latent_func) that
adapts already-placed input for attention.
capture_move: Optional movement of the updated residual back onto the
producer's rows for auxiliary capture.
capture_move_allocates: Whether capture_move returns fresh storage (a
gather) rather than a view (a cut); capture then retains it
without copying.
input_sum: Statically owed sum group for an otherwise raw input tensor.
declared_sum: Statically owed sum group for an otherwise raw input tensor.
preserves_residual: Optional (residual, batch) predicate certifying this
input path leaves residual untouched, including backend fallback.
capture_preserves_residual: Same guarantee for the local following stage,
@@ -215,21 +216,21 @@ class StageEntry(msgspec.Struct, frozen=True):
input_move: Optional[Callable] = None
# Hands the stage its input once it is on its rows:
# (hidden_states, forward_batch, qkv_latent_func) -> hidden_states.
handoff: Optional[Callable] = None
attn_input_adapter: Optional[Callable] = None
# Return the updated residual to the producer's rows for aux capture.
capture_move: Optional[Callable] = None
capture_move_allocates: bool = False
input_sum: Optional[SumGroup] = None
declared_sum: Optional[SumGroup] = None
preserves_residual: Optional[Callable] = None
# Bound from a local successor at construction; no runtime plan lookup.
capture_preserves_residual: Optional[Callable] = None
class StageSteps(msgspec.Struct, frozen=True):
class StagePath(msgspec.Struct, frozen=True):
"""Precomputed entry and exit work for one stage and batch variant.
Fields:
entry: Bound consumer preparation and handoff.
entry: Bound consumer half: preparation, input move and input adapter.
output: Producer contract used by the exit decision.
output_move: Fixed output transport, or None when absent or chosen per
batch by the attention-DP exit path.
@@ -237,8 +238,8 @@ class StageSteps(msgspec.Struct, frozen=True):
returns_over_dp: Whether output uses batch-dependent attention-DP transport.
"""
entry: StageEntry
output: StageOutput
entry: EntryPath
output: OutputContract
# None means no fixed move. returns_over_dp selects batch-dependent DP transport.
output_move: Optional[Callable]
output_move_completes_sum: bool = False
+77 -88
View File
@@ -35,18 +35,18 @@ from sglang.srt.layers.layer_boundary.layout import (
_sum_group,
)
from sglang.srt.layers.layer_boundary.ops import (
_all_reduce_then_to_local_tokens,
_redistribute_output,
_reduce_and_redistribute_output_max_len,
_reduce_and_redistribute_output_varlen,
_to_local_tokens,
_dp_scatter_step,
all_reduce_to_dp_local,
dp_reduce_scatter,
dp_reduce_scatterv,
to_dp_local,
)
from sglang.srt.layers.layer_boundary.output import (
UnreducedOutput,
)
from sglang.srt.layers.layer_boundary.residual.add_norm import (
apply_aiter_all_reduce_fusion,
apply_flashinfer_allreduce_fusion,
aiter_ar_fusion_applies,
flashinfer_ar_fusion_applies,
)
from sglang.srt.layers.layer_boundary.residual.stream import ResidualStream
from sglang.srt.layers.moe import (
@@ -67,49 +67,49 @@ from sglang.srt.runtime_context import (
)
def _reduce_and_redistribute_output_step(
def _select_dp_reduce_scatter(
forward_batch: ForwardBatch,
*,
leaves_for_reduce_scatter: bool,
leaves_for_reduce_scatterv: bool,
may_reduce_scatter: bool,
may_reduce_scatterv: bool,
) -> Optional[Callable[[torch.Tensor, torch.Tensor, ForwardBatch], None]]:
"""The reduce-scatter that brings an FFN output gathered over attention
DP back to this rank's tokens when the FFN leaves its sum to it (see
StageOutput); None when the FFN reduces the output and only a scatter
OutputContract); None when the FFN reduces the output and only a scatter
remains."""
if should_use_dp_reduce_scatterv() and leaves_for_reduce_scatterv:
return _reduce_and_redistribute_output_varlen
if should_use_dp_reduce_scatterv() and may_reduce_scatterv:
return dp_reduce_scatterv
if (
leaves_for_reduce_scatter
may_reduce_scatter
and forward_batch.dp_padding_mode.is_max_len()
and can_use_dp_reduce_scatter()
):
return _reduce_and_redistribute_output_max_len
return dp_reduce_scatter
return None
class OutputBoundary:
class ExitPolicy:
"""Choose and finish one producer's output; the batch owns its residual."""
def __init__(self, plan):
self.plan = plan
def postprocess_layer(
def finish_complete_output(
self,
hidden_states: torch.Tensor,
stream: ResidualStream,
forward_batch: ForwardBatch,
):
"""Move a complete output from the operation-scheduled producer path."""
steps = self.plan._batch_steps(forward_batch)
hidden_states, residual = self._complete_ffn_output_now(
steps = self.plan.path_for(forward_batch)
hidden_states, residual = self._complete_now(
hidden_states,
stream.residual,
forward_batch=forward_batch,
dp_step=None,
steps=steps,
)
return self._leave_ffn_output(
return self._record_output(
hidden_states,
residual,
stream,
@@ -117,14 +117,14 @@ class OutputBoundary:
)
@staticmethod
def _leave_ffn_output(hidden_states, residual, stream, update, declared_sum=None):
def _record_output(hidden_states, residual, stream, update, declared_sum=None):
stream.residual = residual
if update.at_producer:
if update.applied_at_exit:
return stream.write(hidden_states)
return stream.leave(hidden_states, update, declared_sum=declared_sum)
return stream.record(hidden_states, update, declared_sum=declared_sum)
@staticmethod
def _declared_ffn_sum(steps, skipped_reduction):
def _sum_owed_after_skip(steps, skipped_reduction):
# The input-scattered path leaves the sum for the next input's TP
# reduce-scatter. Other skip paths complete it in the output move.
if (
@@ -135,13 +135,13 @@ class OutputBoundary:
return SumGroup.TP
return None
def _local_token_move_can_go_to_next_layer(self, steps) -> bool:
def _next_input_can_scatter(self, steps) -> bool:
"""Whether the next layer's input can run this layer's move of its FFN
output back to this rank's tokens: the base postprocess scatter, when
the next layer's input also writes the output into the residual."""
return steps.returns_over_dp and not steps.output.update.at_producer
return steps.returns_over_dp and not steps.output.update.applied_at_exit
def _postprocess_dp_step(
def _dp_reduce_scatter_step(
self, forward_batch: ForwardBatch, steps
) -> Optional[Callable[[torch.Tensor, torch.Tensor, ForwardBatch], None]]:
"""The reduce-scatter that brings this layer's FFN output back to this
@@ -149,21 +149,19 @@ class OutputBoundary:
only scatter, or does not move tokens."""
if not steps.returns_over_dp:
return None
return _reduce_and_redistribute_output_step(
return _select_dp_reduce_scatter(
forward_batch,
leaves_for_reduce_scatter=steps.output.leaves_for_reduce_scatter,
leaves_for_reduce_scatterv=steps.output.leaves_for_reduce_scatterv,
may_reduce_scatter=steps.output.may_reduce_scatter,
may_reduce_scatterv=steps.output.may_reduce_scatterv,
)
def _ffn_leaves_sum_to_reduce_scatter(
self, steps, dp_step: Optional[Callable]
) -> bool:
def _skips_sum_for_reduce_scatter(self, steps, dp_step: Optional[Callable]) -> bool:
"""Whether the FFN leaves its sum out because a reduce-scatter completes
it: the attention-DP one ``dp_step`` names, or the CP / input-scattered
one."""
if dp_step is not None:
return True
if not steps.output.leaves_for_reduce_scatter:
if not steps.output.may_reduce_scatter:
return False
if steps.output_move_completes_sum:
return True
@@ -174,15 +172,13 @@ class OutputBoundary:
group on a sparse layer, the TP group a dense MLP reduces over."""
return _sum_group(steps.output.group)
def _select_ffn_completion(
self, forward_batch: ForwardBatch, steps
) -> FfnCompletion:
def _decide(self, forward_batch: ForwardBatch, steps) -> ExitDecision:
"""Decide once, before the FFN runs, what it skips and what completes its
output: the next layer's input, or this layer's postprocess step."""
dp_step = self._postprocess_dp_step(forward_batch, steps)
mlp_reduce_scatter = self._ffn_leaves_sum_to_reduce_scatter(steps, dp_step)
dp_step = self._dp_reduce_scatter_step(forward_batch, steps)
mlp_reduce_scatter = self._skips_sum_for_reduce_scatter(steps, dp_step)
complete_now = partial(
self._complete_ffn_output_now,
self._complete_now,
forward_batch=forward_batch,
dp_step=dp_step,
steps=steps,
@@ -191,10 +187,10 @@ class OutputBoundary:
self.plan.fusions is not None
and self.plan.fusions.can_defer_finalize(self.plan, forward_batch)
)
if not steps.output.leaves_for_next_layer and not (
if not steps.output.may_defer_to_next and not (
self.plan.terminal and defer_moe_finalize
):
return FfnCompletion(
return ExitDecision(
defer_moe_finalize=False,
fuse_mlp_allreduce=False,
mlp_reduce_scatter=mlp_reduce_scatter,
@@ -202,7 +198,7 @@ class OutputBoundary:
)
# Producers declare remaining work independently of the kernel chosen
# by the consumer. Every handoff also carries an unfused completion.
fuse_mlp_allreduce = defer_moe_finalize or self._ffn_sum_moves_to_next_layer(
fuse_mlp_allreduce = defer_moe_finalize or self._defers_sum(
forward_batch, steps, mlp_reduce_scatter=mlp_reduce_scatter, dp_step=dp_step
)
if fuse_mlp_allreduce:
@@ -212,37 +208,35 @@ class OutputBoundary:
# this rank's tokens.
wrap = partial(
UnreducedOutput,
reduce_and_redistribute=partial(
_all_reduce_then_to_local_tokens, group, forward_batch
reduce_to_dp_local=partial(
all_reduce_to_dp_local, group, forward_batch
),
)
else:
wrap = partial(UnreducedOutput, group=group)
complete = partial(_leave_to_next_layer, wrap)
complete = partial(_defer, wrap)
elif (
dp_step is not None
and not self.plan.terminal
and self._local_token_move_can_go_to_next_layer(steps)
and self._next_input_can_scatter(steps)
):
complete = partial(
_leave_to_next_layer,
_defer,
partial(
UnreducedOutput,
reduce_and_redistribute=partial(
_to_local_tokens, dp_step, forward_batch
),
reduce_to_dp_local=partial(to_dp_local, dp_step, forward_batch),
),
)
else:
complete = complete_now
return FfnCompletion(
return ExitDecision(
defer_moe_finalize=defer_moe_finalize,
fuse_mlp_allreduce=fuse_mlp_allreduce,
mlp_reduce_scatter=mlp_reduce_scatter,
complete=complete,
)
def _complete_ffn_output_now(
def _complete_now(
self,
hidden_states: torch.Tensor,
residual: torch.Tensor,
@@ -257,8 +251,8 @@ class OutputBoundary:
if steps.output.transform is not None:
hidden_states = steps.output.transform.apply(hidden_states)
if steps.returns_over_dp:
hidden_states = _to_local_tokens(
dp_step or _redistribute_output, forward_batch, hidden_states
hidden_states = to_dp_local(
dp_step or _dp_scatter_step, forward_batch, hidden_states
)
else:
hidden_states, residual = steps.output_move(
@@ -267,7 +261,7 @@ class OutputBoundary:
forward_batch=forward_batch,
)
update = steps.output.update
if residual is not None and update.at_producer:
if residual is not None and update.applied_at_exit:
hidden_states = update.update(hidden_states, residual)
residual = None
return hidden_states, residual
@@ -287,8 +281,8 @@ class OutputBoundary:
result as a context manager around the FFN call, then call ``finish``."""
return FfnExit(self, forward_batch, stream=stream)
def _ffn_sum_can_move_to_next_layer(self, steps) -> bool:
# Under the MoE-CP all-gather the fusion path would skip postprocess_layer
def _sum_deferral_allowed(self, steps) -> bool:
# Under the MoE-CP all-gather the fusion path would skip finish_complete_output
# and its MoE-CP scatter, leaving hidden_states longer than the residual.
if is_enable_moe_cp_allgather() or steps.output.group is None:
return False
@@ -314,7 +308,7 @@ class OutputBoundary:
return not get_attn_tp_context().input_scattered
def _ffn_sum_moves_to_next_layer(
def _defers_sum(
self,
forward_batch: ForwardBatch,
steps,
@@ -328,22 +322,19 @@ class OutputBoundary:
return (
get_parallel().tp_size > 1
and not self.plan.terminal
and self._ffn_sum_can_move_to_next_layer(steps)
and _can_defer_ffn_reduction(forward_batch, self.plan)
and self._sum_deferral_allowed(steps)
and _batch_allows_deferred_sum(forward_batch, self.plan)
and not mlp_reduce_scatter
# Under attention DP the next layer must also run postprocess's
# scatter back to this rank's tokens, and nothing more.
and (
not is_dp_attention_enabled()
or (
self._local_token_move_can_go_to_next_layer(steps)
and dp_step is None
)
or (self._next_input_can_scatter(steps) and dp_step is None)
)
)
def _can_defer_ffn_reduction(forward_batch: ForwardBatch, boundary=None) -> bool:
def _batch_allows_deferred_sum(forward_batch: ForwardBatch, boundary=None) -> bool:
"""Admit ordinary single-sum outputs, plus LoRA and TP1 shared-expert
outputs when a fused consumer (the backend's can_defer_all_reduce,
FlashInfer or aiter) can take them.
@@ -371,16 +362,14 @@ def _can_defer_ffn_reduction(forward_batch: ForwardBatch, boundary=None) -> bool
and boundary.fusions.can_defer_all_reduce(boundary, forward_batch)
):
return True
if apply_flashinfer_allreduce_fusion(forward_batch.input_ids.shape[0]):
if flashinfer_ar_fusion_applies(forward_batch.input_ids.shape[0]):
return True
# Aiter also checks width and bytes, so use the actual residual storage.
residual = forward_batch.residual_stream.residual
return residual is not None and apply_aiter_all_reduce_fusion(
residual, forward_batch
)
return residual is not None and aiter_ar_fusion_applies(residual, forward_batch)
class FfnCompletion(msgspec.Struct, frozen=True):
class ExitDecision(msgspec.Struct, frozen=True):
"""One decision shared by compute flags and the matching output completion.
Fields:
@@ -400,7 +389,7 @@ class FfnCompletion(msgspec.Struct, frozen=True):
complete: Callable[[torch.Tensor, torch.Tensor], Tuple]
def _leave_to_next_layer(
def _defer(
wrap: Callable[[torch.Tensor], UnreducedOutput],
hidden_states: torch.Tensor,
residual: torch.Tensor,
@@ -420,7 +409,7 @@ class MixerExit:
__slots__ = (
"skips_reduction",
"_hands_on",
"_defers",
"_scope",
"_update",
"_declared_sum",
@@ -429,23 +418,23 @@ class MixerExit:
def __init__(
self,
boundary: OutputBoundary,
boundary: ExitPolicy,
forward_batch: ForwardBatch,
*,
stream: ResidualStream,
):
steps = boundary.plan._batch_steps(forward_batch)
steps = boundary.plan.path_for(forward_batch)
produced = steps.output
self._stream = stream
self._update = produced.update
self._declared_sum = produced.group if produced.always_leaves else None
self._hands_on = (
produced.leaves_for_next_layer
self._declared_sum = produced.group if produced.always_partial else None
self._defers = (
produced.may_defer_to_next
and get_parallel().tp_size > 1
and not is_dp_attention_enabled()
and boundary._ffn_sum_can_move_to_next_layer(steps)
and boundary._sum_deferral_allowed(steps)
)
self.skips_reduction = produced.always_leaves or self._hands_on
self.skips_reduction = produced.always_partial or self._defers
self._scope = get_forward().scoped(fuse_mlp_allreduce=self.skips_reduction)
def __enter__(self) -> MixerExit:
@@ -457,11 +446,11 @@ class MixerExit:
def finish(self, hidden_states: torch.Tensor):
"""Hand the actual mixer result to the next boundary through the stream."""
if self._hands_on:
if self._defers:
hidden_states = UnreducedOutput(
hidden_states, group=get_parallel().tp_group
)
return self._stream.leave(
return self._stream.record(
hidden_states, self._update, declared_sum=self._declared_sum
)
@@ -470,7 +459,7 @@ class FfnExit:
"""Scope a selected FFN output decision and retain its completion action.
Args:
boundary: OutputBoundary that owns the producer's bound paths.
boundary: ExitPolicy that owns the producer's bound paths.
forward_batch: Batch selecting reduction/finalize eligibility.
stream: This invocation's residual stream, updated by finish().
@@ -498,21 +487,21 @@ class FfnExit:
def __init__(
self,
boundary: OutputBoundary,
boundary: ExitPolicy,
forward_batch: ForwardBatch,
*,
stream: ResidualStream,
):
self._stream = stream
self.boundary = boundary
steps = boundary.plan._batch_steps(forward_batch)
completion = boundary._select_ffn_completion(forward_batch, steps)
steps = boundary.plan.path_for(forward_batch)
completion = boundary._decide(forward_batch, steps)
self.defer_moe_finalize = completion.defer_moe_finalize
self.fuse_mlp_allreduce = completion.fuse_mlp_allreduce
self.mlp_reduce_scatter = completion.mlp_reduce_scatter
self._complete = completion.complete
self._update = steps.output.update
self._declared_sum = boundary._declared_ffn_sum(
self._declared_sum = boundary._sum_owed_after_skip(
steps, completion.mlp_reduce_scatter
)
self._scope = get_forward().scoped(
@@ -536,6 +525,6 @@ class FfnExit:
assert self.defer_moe_finalize, "unrequested deferred MoE handoff"
else:
hidden_states, residual = self._complete(hidden_states, residual)
return self.boundary._leave_ffn_output(
return self.boundary._record_output(
hidden_states, residual, self._stream, self._update, self._declared_sum
)
@@ -10,78 +10,78 @@ import msgspec
from sglang.srt.layers import layernorm_sp
from sglang.srt.layers.layer_boundary.adapters.overlap import (
resolve_handoff_rows,
tbo_handoff,
resolve_exit_rows,
tbo_exit_rows,
)
from sglang.srt.layers.layer_boundary.boundary import _cp_moves
from sglang.srt.layers.layer_boundary.construction import (
BatchVariant,
_bind_stage,
_input_can_be_scattered,
_refuse_uncovered_cp_moe,
_input_scattered_possible,
_reject_unsupported_cp_moe,
_use_ag_after_qlora,
)
from sglang.srt.layers.layer_boundary.contracts import (
EdgeDecl,
HandoffRows,
EdgeContract,
ExitRows,
InputContract,
OutputContract,
ProducerReduction,
StageDecl,
StageInput,
StageContract,
StageKind,
StageOutput,
)
from sglang.srt.layers.layer_boundary.layout import (
Layout,
SumGroup,
TokenAxis,
_gathers_over_attention_cp,
_generic_prefill_cp_shards_tokens,
enable_moe_dense_fully_dp,
sparse_moe_gathers_over_moe_cp,
_cp_gathers_over_attn_cp,
_prefill_cp_shards_tokens,
is_dense_ffn_fully_dp,
moe_gathers_over_moe_cp,
token_axis_sizes,
)
from sglang.srt.layers.layer_boundary.output import OutputTransform
from sglang.srt.layers.layer_boundary.residual import StageRead, StageUpdate
from sglang.srt.layers.layer_boundary.residual import ResidualReadout, ResidualUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import (
ADD,
NORM_QUANT_READ,
NORM_READ,
NORM_QUANT_READOUT,
NORM_READOUT,
PLAIN_ADD,
)
from sglang.srt.layers.moe import is_moe_input_scattered_across_dp_ranks
from sglang.srt.runtime_context import get_exec, get_parallel
def _variants():
def _active_variants():
yield BatchVariant.ORDINARY
if _generic_prefill_cp_shards_tokens():
if _prefill_cp_shards_tokens():
yield BatchVariant.CONTEXT_PARALLEL
if _input_can_be_scattered():
if _input_scattered_possible():
yield BatchVariant.INPUT_SCATTERED
if layernorm_sp.layernorm_sp_enabled():
yield BatchVariant.SEQUENCE_PARALLEL
def _rows(variant):
def _row_layouts(variant):
axes = token_axis_sizes(cp_active=variant is BatchVariant.CONTEXT_PARALLEL)
attention = Layout.sharded_over(
TokenAxis.ATTN_DP, TokenAxis.ATTN_CP, axis_sizes=axes
)
local = Layout.sharded_over(
TokenAxis.ATTN_DP, TokenAxis.ATTN_CP, TokenAxis.ATTN_TP_SCATTER, axis_sizes=axes
TokenAxis.ATTN_DP, TokenAxis.ATTN_CP, TokenAxis.ATTN_TP, axis_sizes=axes
)
return axes, attention, local, Layout.sharded_over(axis_sizes=axes)
def _ffn_decl(
def _resolve_ffn(
variant,
*,
sparse,
terminal=False,
output_transform=None,
read=NORM_READ,
update=ADD,
read=NORM_READOUT,
update=PLAIN_ADD,
dense_tp_size=None,
reduction=ProducerReduction.SCOPED,
reduction=ProducerReduction.EXIT_SCOPED,
):
parallel = get_parallel()
if dense_tp_size not in (None, 1, parallel.tp_size):
@@ -94,48 +94,46 @@ def _ffn_decl(
can_move_output = output_transform is None or output_transform.before_reduce_scatter
use_reduce_scatter = strategy in ("rs", "rs+rsv") and can_move_output
use_reduce_scatterv = strategy in ("rsv", "rs+rsv") and can_move_output
cp_shards = _generic_prefill_cp_shards_tokens()
axes, attention, local, full = _rows(variant)
on_local = (
cp_shards = _prefill_cp_shards_tokens()
axes, attention, local, full = _row_layouts(variant)
on_rank_rows = (
is_moe_input_scattered_across_dp_ranks()
if sparse
else (
enable_moe_dense_fully_dp() if dense_tp_size is None else dense_tp_size == 1
)
else (is_dense_ffn_fully_dp() if dense_tp_size is None else dense_tp_size == 1)
)
if parallel.attn_cp_size > 1 and sparse:
_refuse_uncovered_cp_moe(on_local, cp_shards)
on_cp = (
_reject_unsupported_cp_moe(on_rank_rows, cp_shards)
on_cp_shards = (
sparse
and parallel.attn_cp_size > 1
and parallel.moe_dp_size == parallel.attn_cp_size
and not _gathers_over_attention_cp()
and not _cp_gathers_over_attn_cp()
)
group = SumGroup.MOE_OUTPUT if sparse else SumGroup.TP
if variant is BatchVariant.SEQUENCE_PARALLEL:
return (
StageDecl(
StageInput(
StageContract(
InputContract(
full,
gathers_itself=frozenset({TokenAxis.ATTN_TP_SCATTER}),
gathered_by_compute=frozenset({TokenAxis.ATTN_TP}),
read=read,
),
StageOutput(local, update=update, transform=output_transform),
OutputContract(local, update=update, transform=output_transform),
),
local,
local,
)
if variant is BatchVariant.INPUT_SCATTERED:
scattered_residual = update.at_producer
scattered_residual = update.applied_at_exit
residual = local if scattered_residual else attention
returned = local if scattered_residual and not terminal else attention
return (
StageDecl(
StageInput(full, read=read),
StageOutput(
StageContract(
InputContract(full, read=read),
OutputContract(
attention,
group=group,
leaves_for_reduce_scatter=use_reduce_scatter
may_reduce_scatter=use_reduce_scatter
and (scattered_residual or not terminal),
update=update,
transform=output_transform,
@@ -148,38 +146,38 @@ def _ffn_decl(
may_leave = variant is not BatchVariant.CONTEXT_PARALLEL
may_scatter = True
elif cp_shards or parallel.attn_dp_size > 1:
may_leave = may_scatter = parallel.attn_cp_size == 1 or on_cp
may_leave = may_scatter = parallel.attn_cp_size == 1 or on_cp_shards
else:
may_leave = may_scatter = True
rows = (
local
if on_local
if on_rank_rows
else Layout.sharded_over(
*((TokenAxis.ATTN_CP,) if on_cp else ()), axis_sizes=axes
*((TokenAxis.ATTN_CP,) if on_cp_shards else ()), axis_sizes=axes
)
)
produced = (
StageOutput(rows, update=update, transform=output_transform)
if on_local
else StageOutput(
OutputContract(rows, update=update, transform=output_transform)
if on_rank_rows
else OutputContract(
rows,
group=group,
leaves_for_next_layer=may_leave
may_defer_to_next=may_leave
and not terminal
and not update.at_producer
and update.can_defer_across_layers
and not update.applied_at_exit
and update.outlives_layer
and output_transform is None
and reduction is ProducerReduction.SCOPED,
leaves_for_reduce_scatter=use_reduce_scatter and may_scatter,
leaves_for_reduce_scatterv=use_reduce_scatterv and may_leave,
and reduction is ProducerReduction.EXIT_SCOPED,
may_reduce_scatter=use_reduce_scatter and may_scatter,
may_reduce_scatterv=use_reduce_scatterv and may_leave,
update=update,
transform=output_transform,
)
)
returned = local if on_local and not terminal else attention
returned = local if on_rank_rows and not terminal else attention
return (
StageDecl(StageInput(rows, read=read), produced),
local if on_local else attention,
StageContract(InputContract(rows, read=read), produced),
local if on_rank_rows else attention,
returned,
)
@@ -202,10 +200,10 @@ class StageDeclaration:
residual update, with an explicit reduction-order contract.
reduction: Whether compute always leaves a partial sum, obeys the
exit scope, or adds a replicated component after its own sum.
gathers_tp_input: Whether attention gathers TP-sharded input itself.
gathers_attn_tp_input: Whether attention gathers TP-sharded input itself.
dense_tp_size: Dense FFN compute width: None uses the configured width,
1 means local compute, and the full TP size means TP compute.
handoff_rows: Required FFN output rows at the layer or branch handoff.
exit_rows: Required FFN output rows at the layer or branch exit.
previous: Declaration whose output this stage consumes. It may be
reconstructed locally, including across pipeline ranks.
prepared_from: Declaration whose already-read input a branch reuses.
@@ -215,15 +213,15 @@ class StageDeclaration:
"""
kind: StageKind
read: StageRead
update: StageUpdate
read: ResidualReadout
update: ResidualUpdate
sparse: bool = False
terminal: bool = False
output_transform: Optional[OutputTransform] = None
reduction: ProducerReduction = ProducerReduction.SCOPED
gathers_tp_input: bool = False
reduction: ProducerReduction = ProducerReduction.EXIT_SCOPED
gathers_attn_tp_input: bool = False
dense_tp_size: Optional[int] = None
handoff_rows: Optional[HandoffRows] = None
exit_rows: Optional[ExitRows] = None
# Only declarations participate in construction, never executable stages.
previous: Optional[StageDeclaration] = None
prepared_from: Optional[StageDeclaration] = None
@@ -242,9 +240,9 @@ class StageConnection:
Fields:
producer: Source declaration, or None at stack entry.
consumer: Destination declaration, or None at a layer/stack handoff.
exits: Producer-side EdgeDecl for each supported BatchVariant.
entries: Consumer-side EdgeDecl for each supported BatchVariant.
consumer: Destination declaration, or None at a layer or stack exit.
exits: Producer-side EdgeContract for each supported BatchVariant.
entries: Consumer-side EdgeContract for each supported BatchVariant.
Equivalent declarations can be reconstructed across pipeline partitions;
adjacent layers need not share the same connection object.
@@ -252,8 +250,8 @@ class StageConnection:
producer: Optional[StageDeclaration]
consumer: Optional[StageDeclaration]
exits: Mapping[BatchVariant, EdgeDecl]
entries: Mapping[BatchVariant, EdgeDecl]
exits: Mapping[BatchVariant, EdgeContract]
entries: Mapping[BatchVariant, EdgeContract]
def __post_init__(self):
object.__setattr__(self, "exits", MappingProxyType(dict(self.exits)))
@@ -264,11 +262,11 @@ def declare_attn(
*,
previous: Optional[StageDeclaration] = None,
prepared_from: Optional[StageDeclaration] = None,
read=NORM_QUANT_READ,
update=ADD,
read=NORM_QUANT_READOUT,
update=PLAIN_ADD,
terminal=False,
reduction=ProducerReduction.PARTIAL,
gathers_tp_input=True,
reduction=ProducerReduction.ALWAYS_PARTIAL,
gathers_attn_tp_input=True,
):
"""Declare attention or a mixer; construct its executable boundary later.
@@ -278,16 +276,16 @@ def declare_attn(
read: Input operation; defaults to normalization with quantization support.
update: Operation that adds this stage's output to the residual.
terminal: Whether this stage ends the model's layer stack.
reduction: PARTIAL for an output projection that always skips reduction;
SCOPED for a mixer that follows its exit scope's reduction decision.
LOCAL_TAIL is rejected for attention stages.
gathers_tp_input: Whether compute gathers attention-TP input slices itself.
reduction: ALWAYS_PARTIAL for an output projection that always skips reduction;
EXIT_SCOPED for a mixer that follows its exit scope's reduction decision.
TAIL_AFTER_SUM is rejected for attention stages.
gathers_attn_tp_input: Whether compute gathers attention-TP input slices itself.
Returns:
A StageDeclaration with no norm, tensors or execution plan.
"""
if reduction is ProducerReduction.LOCAL_TAIL:
raise ValueError("LOCAL_TAIL is not supported for attention stages")
if reduction is ProducerReduction.TAIL_AFTER_SUM:
raise ValueError("TAIL_AFTER_SUM is not supported for attention stages")
return StageDeclaration(
StageKind.ATTENTION,
read,
@@ -296,7 +294,7 @@ def declare_attn(
prepared_from=prepared_from,
terminal=terminal,
reduction=reduction,
gathers_tp_input=gathers_tp_input,
gathers_attn_tp_input=gathers_attn_tp_input,
)
@@ -305,14 +303,14 @@ def declare_ffn(
previous: Optional[StageDeclaration] = None,
prepared_from: Optional[StageDeclaration] = None,
sparse=False,
read=NORM_READ,
update=ADD,
read=NORM_READOUT,
update=PLAIN_ADD,
terminal=False,
output_transform=None,
next_sparse=False,
next_layer_sparse=False,
dense_tp_size=None,
reduction=ProducerReduction.SCOPED,
handoff_rows=None,
reduction=ProducerReduction.EXIT_SCOPED,
exit_rows=None,
):
"""Declare a dense or MoE FFN independently of its compute module.
@@ -324,21 +322,21 @@ def declare_ffn(
update: Operation writing FFN output into the residual.
terminal: Whether this stage ends the model's layer stack.
output_transform: Optional contribution transform before residual update.
next_sparse: Whether the next decoder layer's FFN is sparse; used only
to derive the TBO handoff when handoff_rows is not supplied.
next_layer_sparse: Whether the next decoder layer's FFN is sparse; used only
to derive the TBO exit rows when exit_rows is not supplied.
dense_tp_size: Dense compute width: None for configuration, 1 for local
compute, or the full TP size.
reduction: How compute cooperates with the exit's reduction decision:
SCOPED (default) follows the exit scope; LOCAL_TAIL marks a
replicated tail after the sum. PARTIAL is rejected for FFN stages.
handoff_rows: Explicit output-row requirement; otherwise derived from
EXIT_SCOPED (default) follows the exit scope; TAIL_AFTER_SUM marks a
replicated tail after the sum. ALWAYS_PARTIAL is rejected for FFN stages.
exit_rows: Explicit output-row requirement; otherwise derived from
the adjacent FFN kinds and TBO configuration.
Returns:
A StageDeclaration with no norm, tensors or execution plan.
"""
if reduction is ProducerReduction.PARTIAL:
raise ValueError("PARTIAL is not supported for ffn stages")
if reduction is ProducerReduction.ALWAYS_PARTIAL:
raise ValueError("ALWAYS_PARTIAL is not supported for ffn stages")
return StageDeclaration(
StageKind.FFN,
read,
@@ -350,23 +348,23 @@ def declare_ffn(
output_transform=output_transform,
dense_tp_size=dense_tp_size,
reduction=reduction,
handoff_rows=handoff_rows or tbo_handoff(sparse, next_sparse),
exit_rows=exit_rows or tbo_exit_rows(sparse, next_layer_sparse),
)
def _resolve(stage, variant, following=None):
axes, attention, local, full = _rows(variant)
if stage.update.at_producer:
if stage.sparse and sparse_moe_gathers_over_moe_cp():
def _resolve_stage(stage, variant, following=None):
axes, attention, local, full = _row_layouts(variant)
if stage.update.applied_at_exit:
if stage.sparse and moe_gathers_over_moe_cp():
raise NotImplementedError(
"MHC does not support a MoE gathered over the MoE-CP group"
)
if get_parallel().attn_cp_size > 1 and _input_can_be_scattered():
if get_parallel().attn_cp_size > 1 and _input_scattered_possible():
raise NotImplementedError(
"MHC with input-scattered attention under attention CP"
)
if stage.kind is StageKind.FFN:
declaration, residual, returned = _ffn_decl(
declaration, residual, returned = _resolve_ffn(
variant,
sparse=stage.sparse,
terminal=stage.terminal,
@@ -376,29 +374,29 @@ def _resolve(stage, variant, following=None):
dense_tp_size=stage.dense_tp_size,
reduction=stage.reduction,
)
if resolve_handoff_rows(stage.handoff_rows) is HandoffRows.ATTENTION:
if resolve_exit_rows(stage.exit_rows) is ExitRows.ATTENTION:
returned = attention
return declaration, residual, returned
sp = variant is BatchVariant.SEQUENCE_PARALLEL
scattered = variant is BatchVariant.INPUT_SCATTERED
gathers = (
frozenset({TokenAxis.ATTN_TP_SCATTER})
if stage.gathers_tp_input and (sp or scattered or _use_ag_after_qlora)
frozenset({TokenAxis.ATTN_TP})
if stage.gathers_attn_tp_input and (sp or scattered or _use_ag_after_qlora)
else frozenset()
)
owes = not sp and axes[TokenAxis.ATTN_TP_SCATTER] > 1
declaration = StageDecl(
StageInput(attention, gathers_itself=gathers, read=stage.read),
StageOutput(
owes = not sp and axes[TokenAxis.ATTN_TP] > 1
declaration = StageContract(
InputContract(attention, gathered_by_compute=gathers, read=stage.read),
OutputContract(
local if sp else attention,
group=SumGroup.ATTN_TP if owes else None,
always_leaves=owes
always_partial=owes
and (
stage.reduction is ProducerReduction.PARTIAL
stage.reduction is ProducerReduction.ALWAYS_PARTIAL
or (following is not None and following.kind is StageKind.FFN)
),
leaves_for_next_layer=owes
and stage.reduction is ProducerReduction.SCOPED
may_defer_to_next=owes
and stage.reduction is ProducerReduction.EXIT_SCOPED
and following is not None
and following.kind is StageKind.ATTENTION,
update=stage.update,
@@ -410,7 +408,7 @@ def _resolve(stage, variant, following=None):
def _connect(producer, consumer, *, residual_from=None):
"""Resolve producer and consumer declarations; None denotes an external endpoint.
A missing producer is the stack input; a missing consumer is a handoff
A missing producer is the stack input; a missing consumer is a layer or stack exit
whose next read is bound separately (or the terminal output).
``residual_from`` names the boundary that placed the producer's residual.
It is needed for attention, whose residual can stay on finer rows than its
@@ -420,21 +418,21 @@ def _connect(producer, consumer, *, residual_from=None):
raise ValueError("a boundary needs at least one declared side")
before, after = producer, consumer
exits, entries = {}, {}
for variant in _variants():
_, attention, local, _ = _rows(variant)
for variant in _active_variants():
_, attention, local, _ = _row_layouts(variant)
if before is None:
rows = local if variant is BatchVariant.SEQUENCE_PARALLEL else attention
owes = variant is BatchVariant.INPUT_SCATTERED
arrived = StageOutput(
arrived = OutputContract(
rows,
group=SumGroup.TP if owes else None,
always_leaves=owes,
always_partial=owes,
update=None,
)
residual = rows
capabilities = (True,)
else:
decl, during, returned = _resolve(before, variant, following=after)
decl, during, returned = _resolve_stage(before, variant, following=after)
if during is None:
if residual_from is not None:
if residual_from.consumer != producer:
@@ -442,59 +440,58 @@ def _connect(producer, consumer, *, residual_from=None):
during = residual_from.entries[variant].residual_to
elif (
before.kind is StageKind.ATTENTION
and before.reduction is ProducerReduction.SCOPED
and before.reduction is ProducerReduction.EXIT_SCOPED
):
during = attention
else:
raise ValueError(
"attention output needs its incoming residual placement"
)
exits[variant] = EdgeDecl(
decl.output, StageInput(returned), during, returned
exits[variant] = EdgeContract(
decl.output, InputContract(returned), during, returned
)
if (
before.kind is StageKind.ATTENTION
and before.reduction is ProducerReduction.PARTIAL
and before.reduction is ProducerReduction.ALWAYS_PARTIAL
):
arrived, residual, capabilities = decl.output, during, ()
else:
owes = (
variant is BatchVariant.INPUT_SCATTERED
and not before.update.at_producer
and not before.update.applied_at_exit
)
carries = (
(
before.kind is StageKind.ATTENTION
and before.reduction is ProducerReduction.SCOPED
and before.reduction is ProducerReduction.EXIT_SCOPED
)
or resolve_handoff_rows(before.handoff_rows)
is HandoffRows.ATTENTION
) and (decl.output.always_leaves or decl.output.leaves_for_next_layer)
arrived = StageOutput(
or resolve_exit_rows(before.exit_rows) is ExitRows.ATTENTION
) and (decl.output.always_partial or decl.output.may_defer_to_next)
arrived = OutputContract(
returned,
group=decl.output.group
if carries
else (SumGroup.TP if owes else None),
always_leaves=decl.output.always_leaves if carries else owes,
leaves_for_next_layer=decl.output.leaves_for_next_layer
always_partial=decl.output.always_partial if carries else owes,
may_defer_to_next=decl.output.may_defer_to_next
if carries
else False,
update=None,
)
residual, capabilities = returned, (before.update.adds_plainly,)
residual, capabilities = returned, (before.update.is_plain_add,)
if after is None:
continue
decl, during, _ = _resolve(after, variant)
decl, during, _ = _resolve_stage(after, variant)
if after.kind is StageKind.ATTENTION:
during = (
Layout(residual.sharded | {TokenAxis.ATTN_TP_SCATTER})
Layout(residual.sharded | {TokenAxis.ATTN_TP})
if variant is BatchVariant.INPUT_SCATTERED
and arrived.always_leaves
and arrived.always_partial
and arrived.update is None
and after.reduction is ProducerReduction.PARTIAL
and after.reduction is ProducerReduction.ALWAYS_PARTIAL
else residual
)
elif resolve_handoff_rows(after.handoff_rows) is HandoffRows.ATTENTION:
elif resolve_exit_rows(after.exit_rows) is ExitRows.ATTENTION:
during = (
decl.input.layout
if residual.sharded <= decl.input.layout.sharded
@@ -503,22 +500,22 @@ def _connect(producer, consumer, *, residual_from=None):
joins = (
variant is BatchVariant.INPUT_SCATTERED
and arrived.update is not None
and arrived.update.adds_plainly
and arrived.update.is_plain_add
and after.kind is StageKind.FFN
)
edge = EdgeDecl(
edge = EdgeContract(
arrived,
decl.input,
residual,
during,
residual_joins_sum=joins,
update_capabilities=capabilities,
arriving_plain_add=capabilities,
)
entries[variant] = edge
if (
before is not None
and before.kind is StageKind.ATTENTION
and before.reduction is ProducerReduction.PARTIAL
and before.reduction is ProducerReduction.ALWAYS_PARTIAL
):
exits[variant] = edge
return StageConnection(producer, consumer, exits, entries)
@@ -531,19 +528,19 @@ def _fork_input(prepared, consumer):
execute the branch's input norm again.
"""
entries = {}
for variant in _variants():
for variant in _active_variants():
if variant is not BatchVariant.ORDINARY:
raise NotImplementedError(
"prepared branch transport requires ordinary token rows"
)
source = prepared.entries[variant]
declaration, during, _ = _resolve(consumer, variant)
entries[variant] = EdgeDecl(
StageOutput(source.need.layout, update=None),
declaration, during, _ = _resolve_stage(consumer, variant)
entries[variant] = EdgeContract(
OutputContract(source.need.layout, update=None),
declaration.input,
source.residual_to,
during,
update_capabilities=(True,),
arriving_plain_add=(True,),
)
return StageConnection(prepared.consumer, consumer, {}, entries)
@@ -558,7 +555,7 @@ def _incoming(stage):
_incoming(previous)
if previous is not None
and previous.kind is StageKind.ATTENTION
and previous.reduction is ProducerReduction.PARTIAL
and previous.reduction is ProducerReduction.ALWAYS_PARTIAL
else None
)
return _connect(
@@ -594,7 +591,7 @@ def make_attn_stage(
declaration: Attention StageDeclaration, including its input source.
norm: This consumer's normalization module, never its neighbour's norm.
following: Local consumer declaration whose previous is declaration.
None leaves a layer/stack handoff for an independently bound reader.
None leaves a layer or stack exit for an independently bound reader.
qkv_latent_func: Optional attention input hook, invoked after preparation
and movement onto the compute input rows.
fusions: Optional backend provider. Consumer side: ordered
@@ -632,7 +629,7 @@ def make_ffn_stage(
declaration: FFN StageDeclaration, including its input source.
norm: This FFN's input normalization module.
following: Local consumer declaration whose previous is declaration;
None leaves a layer/stack handoff for an independently bound reader.
None leaves a layer or stack exit for an independently bound reader.
fusions: Optional backend fusion provider, as in make_attn_stage.
Returns:
@@ -663,7 +660,7 @@ def make_stages(
prepared_from: Already-read input declaration reused by the first stage
of a branch; mutually exclusive with previous.
following: External consumer declaration after the last local stage.
None denotes a layer/stack handoff with an independently bound read.
None denotes a layer or stack exit with an independently bound read.
terminal: Marks only the final stage as the end of the model's stack.
Returns:
@@ -717,15 +714,15 @@ def make_stages(
for producer, consumer in zip(boundaries, boundaries[1:]):
if not (
producer.kind is StageKind.ATTENTION
and producer.declaration.reduction is ProducerReduction.PARTIAL
and producer.declaration.reduction is ProducerReduction.ALWAYS_PARTIAL
and consumer.kind is StageKind.FFN
):
continue
for variant, steps in producer.plan._paths.items():
next_steps = consumer.plan._paths[variant]
for variant, steps in producer.plan.paths.items():
next_steps = consumer.plan.paths[variant]
predicate = next_steps.entry.preserves_residual
if predicate is not None:
producer.plan._paths[variant] = msgspec.structs.replace(
producer.plan.paths[variant] = msgspec.structs.replace(
steps,
entry=msgspec.structs.replace(
steps.entry, capture_preserves_residual=predicate
@@ -19,15 +19,15 @@ from typing import Callable, Optional, Tuple
import torch
from sglang.srt.layers.layer_boundary.contracts import FusedMlpInput
from sglang.srt.layers.layer_boundary.contracts import FfnInputFusion
from sglang.srt.layers.layer_boundary.layout import SumGroup
from sglang.srt.layers.layer_boundary.output import UnreducedOutput
from sglang.srt.layers.layer_boundary.residual.add_norm import (
NORM_QUANT_READ,
NORM_QUANT_READOUT,
Fp8Input,
NormQuantRead,
apply_aiter_all_reduce_fusion,
apply_flashinfer_allreduce_fusion,
NormQuantReadout,
aiter_ar_fusion_applies,
flashinfer_ar_fusion_applies,
)
from sglang.srt.layers.layernorm import GemmaRMSNorm, RMSNorm
from sglang.srt.layers.moe import post_experts_reduction_group
@@ -38,18 +38,18 @@ from sglang.srt.utils import get_bool_env_var, is_hip
_use_aiter = get_bool_env_var("SGLANG_USE_AITER") and is_hip()
def attention_fusions(plan, read=NORM_QUANT_READ) -> Tuple[Callable, ...]:
def attn_input_fusions(plan, read=NORM_QUANT_READOUT) -> Tuple[Callable, ...]:
"""The fused kernels that complete what the previous layer left together
with the residual update and the input norm, in the order they are tried.
Each takes (owed, residual, forward_batch, post_residual_addition) and
returns None when it does not take the batch. They add the residual
plainly; the boundary tries them only when the update it writes in is a
plain add. A backend's come first."""
given = plan.fusions.attention_input(plan) if plan.fusions else ()
given = plan.fusions.attn_input_fusions(plan) if plan.fusions else ()
if not hasattr(plan.norm, "forward_with_allreduce_fusion"):
return given
fuses_quant = (
isinstance(read, NormQuantRead)
isinstance(read, NormQuantReadout)
and read.fp8_input is not None
and _use_aiter
and not get_bool_env_var("SGLANG_DISABLE_FUSED_AR_QUANT", default="false")
@@ -59,7 +59,7 @@ def attention_fusions(plan, read=NORM_QUANT_READ) -> Tuple[Callable, ...]:
return (
*given,
partial(
complete_attention_input,
fused_attn_input,
plan,
fuses_quant=fuses_quant,
keep_bf16=fuses_quant and read.fp8_input is Fp8Input.TUPLE_AND_BF16,
@@ -67,7 +67,7 @@ def attention_fusions(plan, read=NORM_QUANT_READ) -> Tuple[Callable, ...]:
)
def complete_attention_input(
def fused_attn_input(
plan,
owed: UnreducedOutput,
residual: torch.Tensor,
@@ -91,8 +91,8 @@ def complete_attention_input(
return None
hidden_states = owed.partial
if not (
apply_aiter_all_reduce_fusion(hidden_states, forward_batch)
or apply_flashinfer_allreduce_fusion(hidden_states.shape[0])
aiter_ar_fusion_applies(hidden_states, forward_batch)
or flashinfer_ar_fusion_applies(hidden_states.shape[0])
):
return None
if fuses_quant:
@@ -111,19 +111,19 @@ def complete_attention_input(
)
def ffn_fusions(plan) -> Tuple["FusedMlpInput", ...]:
def ffn_input_fusions(plan) -> Tuple["FfnInputFusion", ...]:
"""The fused kernels that can take the attention -> FFN steps, in the
order they are tried. They add the residual plainly; the boundary tries
them only when the update it writes in is a plain add. A backend's come
first."""
given = plan.fusions.ffn_input(plan) if plan.fusions else ()
given = plan.fusions.ffn_input_fusions(plan) if plan.fusions else ()
if not hasattr(plan.norm, "forward_with_allreduce_fusion"):
return given
return (
*given,
FusedMlpInput(
FfnInputFusion(
completes=SumGroup.ATTN_TP,
run=partial(complete_ffn_input, plan),
run=partial(fused_ffn_input, plan),
preserves_residual=(
flashinfer_preserves_residual
if isinstance(plan.norm, (RMSNorm, GemmaRMSNorm))
@@ -143,11 +143,11 @@ def flashinfer_preserves_residual(value, forward_batch):
return (
not _use_aiter
and get_parallel().attn_tp_size > 1
and apply_flashinfer_allreduce_fusion(value.shape[0])
and flashinfer_ar_fusion_applies(value.shape[0])
)
def complete_ffn_input(
def fused_ffn_input(
plan,
hidden_states: torch.Tensor,
residual: torch.Tensor,
@@ -156,8 +156,8 @@ def complete_ffn_input(
"""The attention-TP all-reduce, residual add and norm in one aiter or
flashinfer kernel; None when neither takes the batch."""
if not (
apply_aiter_all_reduce_fusion(hidden_states, forward_batch)
or apply_flashinfer_allreduce_fusion(hidden_states.shape[0])
aiter_ar_fusion_applies(hidden_states, forward_batch)
or flashinfer_ar_fusion_applies(hidden_states.shape[0])
):
return None
return plan.norm.forward_with_allreduce_fusion(
@@ -3,7 +3,7 @@
Two patterns share one workspace, both consumed at the next layer's input
RMSNorm (and, with terminal_finalize, at the final norm): AR + residual +
RMSNorm, and the same with the MoE finalize and the shared-expert add folded in
when the runner hands back a MoeFinalizeHandoff.
when the runner hands back a MoeDeferredFinalize.
"""
from __future__ import annotations
@@ -16,8 +16,8 @@ import torch
from sglang.srt.layers.dp_attention import is_dp_attention_enabled
from sglang.srt.layers.layer_boundary import (
FusedMlpInput,
HandoffOutput,
DeferredFinalize,
FfnInputFusion,
SumGroup,
TokenAxis,
UnreducedOutput,
@@ -75,7 +75,7 @@ def _resolve_max_m(*, max_running_requests: int | None) -> int:
return max(positive)
class MoeFinalizeHandoff(HandoffOutput, frozen=True):
class MoeDeferredFinalize(DeferredFinalize, frozen=True):
"""Unfinalized routed output plus the separately gated shared contribution.
The next layer's fused finalize + AR + add + norm takes it; ``finish`` is
the MoE's own unfused tail, for any other reader."""
@@ -98,7 +98,7 @@ class MoeFinalizeHandoff(HandoffOutput, frozen=True):
gated_shared_output: torch.Tensor,
m: int,
reduce: Callable[[torch.Tensor], torch.Tensor],
) -> MoeFinalizeHandoff:
) -> MoeDeferredFinalize:
"""``reduce`` is the MoE's own sum of its finalized output."""
from sglang.srt.layers.moe.moe_runner.flashinfer_trtllm import (
finalize_flashinfer_trtllm_deferred_output,
@@ -123,7 +123,7 @@ class MoeFinalizeHandoff(HandoffOutput, frozen=True):
)
class CuteDSLFusionService:
class CuteDSLWorkspace:
def __init__(
self,
*,
@@ -167,7 +167,7 @@ class CuteDSLFusionService:
def finalize(
self,
handoff: MoeFinalizeHandoff,
handoff: MoeDeferredFinalize,
residual: torch.Tensor,
gamma: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
@@ -208,73 +208,71 @@ class CuteDSLFusion:
FFN when terminal_finalize is installed."""
def __init__(self) -> None:
self.service: CuteDSLFusionService | None = None
self.service: CuteDSLWorkspace | None = None
# Producer capabilities; consumer kernel selection is independent.
self.hands_off_finalize = False
self.defers_finalize = False
self.terminal_finalize = False
def install(
self,
service: CuteDSLFusionService,
service: CuteDSLWorkspace,
*,
hands_off_finalize: bool,
defers_finalize: bool,
terminal_finalize: bool = False,
) -> None:
"""Install the shared workspace and this producer's capabilities."""
self.service = service
self.hands_off_finalize = hands_off_finalize
self.defers_finalize = defers_finalize
self.terminal_finalize = terminal_finalize
def attention_input(self, layer) -> tuple:
def attn_input_fusions(self, plan) -> tuple:
return (
partial(self._finalize_output_and_update_and_read_residual, layer),
partial(self._reduce_output_and_update_and_read_residual, layer),
partial(self._finalize_add_norm, plan),
partial(self._all_reduce_add_norm, plan),
)
def ffn_input(self, layer) -> tuple:
def ffn_input_fusions(self, plan) -> tuple:
parallel = get_parallel()
if (
TokenAxis.ATTN_TP_SCATTER not in layer.incoming_residual_rows.sharded
TokenAxis.ATTN_TP not in plan.incoming_residual_rows.sharded
# The workspace sums over TP, which is then the attention-TP group.
and parallel.attn_tp_size == parallel.tp_size
and _fused_norm_gamma(layer.norm) is not None
and _fused_norm_gamma(plan.norm) is not None
):
return (
FusedMlpInput(
FfnInputFusion(
completes=SumGroup.ATTN_TP,
run=partial(
self._mlp_input_reduce_output_and_update_and_read_residual,
layer,
self._ffn_input_all_reduce_add_norm,
plan,
),
),
)
return ()
def _finalize_output_and_update_and_read_residual(
self, layer, owed, residual, forward_batch, post_residual_addition
def _finalize_add_norm(
self, plan, owed, residual, forward_batch, post_residual_addition
):
"""Finish a deferred MoE finalize with the all-reduce, residual add and
input norm, when this layer's kernel takes the batch; otherwise the
handoff is completed by its producer's own tail."""
if not isinstance(owed, MoeFinalizeHandoff):
if not isinstance(owed, MoeDeferredFinalize):
return None
gamma = _fused_norm_gamma(layer.norm)
if gamma is None or not self._should_use_finalize(layer, forward_batch, owed.m):
gamma = _fused_norm_gamma(plan.norm)
if gamma is None or not self._finalize_eligible(plan, forward_batch, owed.m):
return None
if post_residual_addition is not None:
residual = residual + post_residual_addition
assert self.service is not None
return self.service.finalize(handoff=owed, residual=residual, gamma=gamma)
def _reduce_output_and_update_and_read_residual(
self, layer, owed, residual, forward_batch, post_residual_addition
def _all_reduce_add_norm(
self, plan, owed, residual, forward_batch, post_residual_addition
):
"""Complete the all-reduce the previous layer left with the residual add
and input norm."""
if not isinstance(owed, UnreducedOutput) or not (
self._can_consume_post_moe_all_reduce(
layer, forward_batch, int(owed.partial.shape[0])
)
self._all_reduce_eligible(plan, forward_batch, int(owed.partial.shape[0]))
):
return None
if post_residual_addition is not None:
@@ -283,16 +281,16 @@ class CuteDSLFusion:
return self.service.all_reduce_residual_rms_norm(
local_contribution=owed.partial,
residual=residual,
gamma=_fused_norm_gamma(layer.norm),
gamma=_fused_norm_gamma(plan.norm),
)
def _mlp_input_reduce_output_and_update_and_read_residual(
self, layer, hidden_states, residual, forward_batch
def _ffn_input_all_reduce_add_norm(
self, plan, hidden_states, residual, forward_batch
):
"""The attention output's all-reduce with the residual add and the
post-attention norm."""
if not (
self._common_eligible(layer, forward_batch, int(hidden_states.shape[0]))
self._eligible(plan, forward_batch, int(hidden_states.shape[0]))
and residual is not None
and not get_exec().comm.enable_quant_communications
):
@@ -301,49 +299,44 @@ class CuteDSLFusion:
return self.service.all_reduce_residual_rms_norm(
local_contribution=hidden_states,
residual=residual,
gamma=_fused_norm_gamma(layer.norm),
gamma=_fused_norm_gamma(plan.norm),
)
def _should_use_finalize(self, layer, forward_batch: ForwardBatch, m: int) -> bool:
def _finalize_eligible(self, plan, forward_batch: ForwardBatch, m: int) -> bool:
return (
self._common_eligible(layer, forward_batch, m)
and get_parallel().moe_ep_size == 1
self._eligible(plan, forward_batch, m) and get_parallel().moe_ep_size == 1
)
def _can_consume_post_moe_all_reduce(
self, layer, forward_batch: ForwardBatch, m: int
) -> bool:
def _all_reduce_eligible(self, plan, forward_batch: ForwardBatch, m: int) -> bool:
"""Incoming, and independent of this layer's own successor."""
return (
self._common_eligible(layer, forward_batch, m)
and _fused_norm_gamma(layer.norm) is not None
self._eligible(plan, forward_batch, m)
and _fused_norm_gamma(plan.norm) is not None
and not get_exec().comm.enable_quant_communications
)
def can_defer_all_reduce(self, layer, forward_batch: ForwardBatch) -> bool:
def can_defer_all_reduce(self, plan, forward_batch: ForwardBatch) -> bool:
"""Preserve the producer's fused sum path when this workspace is usable.
The next consumer still selects its kernel and completes the sum with
an ordinary all-reduce if that kernel declines the actual input.
"""
return (
self._common_eligible(
layer, forward_batch, int(forward_batch.input_ids.shape[0])
)
self._eligible(plan, forward_batch, int(forward_batch.input_ids.shape[0]))
and not get_exec().comm.enable_quant_communications
)
def can_defer_finalize(self, layer, forward_batch: ForwardBatch) -> bool:
def can_defer_finalize(self, plan, forward_batch: ForwardBatch) -> bool:
"""Whether this producer can emit a handoff with an unfused fallback."""
return (
self.hands_off_finalize
and (not layer.terminal or self.terminal_finalize)
and self._should_use_finalize(
layer, forward_batch, int(forward_batch.input_ids.shape[0])
self.defers_finalize
and (not plan.terminal or self.terminal_finalize)
and self._finalize_eligible(
plan, forward_batch, int(forward_batch.input_ids.shape[0])
)
)
def _common_eligible(self, layer, forward_batch: ForwardBatch, m: int) -> bool:
def _eligible(self, plan, forward_batch: ForwardBatch, m: int) -> bool:
parallel = get_parallel()
return bool(
self.service is not None
@@ -357,8 +350,7 @@ class CuteDSLFusion:
and get_moe_a2a_backend().is_none()
and parallel.tp_size > 1
# The FFN runs on the full rows, not each rank's own slice.
and TokenAxis.ATTN_TP_SCATTER
not in layer.fusion_rows(forward_batch).sharded
and TokenAxis.ATTN_TP not in plan.fused_input_rows(forward_batch).sharded
)
@@ -376,13 +368,13 @@ def install_cutedsl_fusion(
can_defer_finalize: _LayerPredicate,
label: str,
terminal_finalize: bool = False,
) -> CuteDSLFusionService | None:
) -> CuteDSLWorkspace | None:
"""One shared workspace handle per fusion-enabled layer, or None.
Every entry of ``layers`` carries ``attn_boundary`` and ``ffn_boundary``.
terminal_finalize lets the last layer hand its finalize to the final norm;
the model must then pass the returned service as
residual_batch.norm(handoff_norm=...).
residual_batch.final_norm(finalize_norm=...).
"""
if get_flags().moe.in_speculative_scope:
# A draft shares the target's process, which holds one workspace.
@@ -407,7 +399,7 @@ def install_cutedsl_fusion(
f"{norm.variance_epsilon}"
)
service = CuteDSLFusionService(
service = CuteDSLWorkspace(
hidden_size=hidden_size,
top_k=top_k,
rms_epsilon=rms_epsilon,
@@ -417,11 +409,11 @@ def install_cutedsl_fusion(
fusion = _fusion_of(layer)
if fusion is None:
continue
hands_off_finalize = bool(can_defer_finalize(layer))
hands_off += hands_off_finalize
defers_finalize = bool(can_defer_finalize(layer))
hands_off += defers_finalize
fusion.install(
service,
hands_off_finalize=hands_off_finalize,
defers_finalize=defers_finalize,
terminal_finalize=terminal_finalize,
)
logger.info(
@@ -44,7 +44,7 @@ class TokenAxis(Enum):
ATTN_DP = auto()
ATTN_CP = auto()
# Each attention-TP rank holds a slice of its group's tokens.
ATTN_TP_SCATTER = auto()
ATTN_TP = auto()
class Layout(msgspec.Struct, frozen=True):
@@ -78,11 +78,11 @@ class SumGroup(Enum):
MOE_OUTPUT = auto()
def enable_moe_dense_fully_dp():
def is_dense_ffn_fully_dp():
return get_parallel().moe_dense_tp_size == 1
def _generic_prefill_cp_shards_tokens() -> bool:
def _prefill_cp_shards_tokens() -> bool:
"""Whether the strategy prefill CP path shards prefill tokens across CP ranks."""
parallel = get_parallel()
return parallel.attn_cp_size > 1 and parallel.enable_prefill_cp
@@ -116,7 +116,7 @@ def moe_cp_gathered_rows(forward_batch: ForwardBatch) -> Optional[List[int]]:
return None
def sparse_moe_gathers_over_moe_cp() -> bool:
def moe_gathers_over_moe_cp() -> bool:
"""Whether a sparse MoE's input is gathered over the MoE-CP group on a CP
extend: a MoE on the TP group under GQA CP whose MoE-CP group is wider than
the MoE's data-parallel groups. DSA and MLA CP gather over attention CP
@@ -124,17 +124,14 @@ def sparse_moe_gathers_over_moe_cp() -> bool:
return (
not is_moe_input_scattered_across_dp_ranks()
and is_enable_moe_cp_allgather()
and not _gathers_over_attention_cp()
and not _cp_gathers_over_attn_cp()
)
def moe_cp_gathers_sparse_moe_input(forward_batch: ForwardBatch) -> bool:
def batch_gathers_over_moe_cp(forward_batch: ForwardBatch) -> bool:
"""Whether a sparse MoE's input is gathered over the MoE-CP group on this
batch: a CP extend, for a MoE that gathers there."""
return (
sparse_moe_gathers_over_moe_cp()
and moe_cp_gathered_rows(forward_batch) is not None
)
return moe_gathers_over_moe_cp() and moe_cp_gathered_rows(forward_batch) is not None
def _cp_shard_token_rows(forward_batch: ForwardBatch) -> List[int]:
@@ -162,11 +159,11 @@ def token_axis_sizes(*, cp_active: bool = False) -> Dict[TokenAxis, int]:
return {
TokenAxis.ATTN_DP: parallel.attn_dp_size,
TokenAxis.ATTN_CP: parallel.attn_cp_size if cp_active else 1,
TokenAxis.ATTN_TP_SCATTER: parallel.attn_tp_size,
TokenAxis.ATTN_TP: parallel.attn_tp_size,
}
def _gathers_over_attention_cp() -> bool:
def _cp_gathers_over_attn_cp() -> bool:
"""Whether a CP extend gathers the FFN input over the attention-CP group in
equal shards and takes the output back with a reduce-scatter there: DSA and
MLA CP. GQA prefill CP gathers over the MoE-CP group instead."""
@@ -179,7 +176,7 @@ def _batch_shards_over_cp(forward_batch: ForwardBatch) -> bool:
never read the CP predicates."""
if not forward_batch.forward_mode.is_context_parallel_extend():
return False
if _gathers_over_attention_cp():
if _cp_gathers_over_attn_cp():
return dsa_use_prefill_cp(forward_batch) or is_mla_cp_active(forward_batch)
return moe_cp_gathered_rows(forward_batch) is not None
+41 -51
View File
@@ -41,11 +41,11 @@ from sglang.srt.layers.dp_attention import (
moe_cp_all_gather_into_tensor,
)
from sglang.srt.layers.layer_boundary.adapters.attention import (
_redistribute_from_attn_tp_shards,
_redistribute_to_attn_tp_shards,
attn_tp_gather,
attn_tp_slice,
)
from sglang.srt.layers.layer_boundary.adapters.context_parallel import (
dsa_cp_reduce_scatter_hidden_states,
attn_cp_reduce_scatter,
)
from sglang.srt.layers.layer_boundary.layout import (
Layout,
@@ -53,8 +53,8 @@ from sglang.srt.layers.layer_boundary.layout import (
_cp_shard_token_rows,
moe_cp_gathered_rows,
)
from sglang.srt.layers.layer_boundary.residual import StageUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import ADD
from sglang.srt.layers.layer_boundary.residual import ResidualUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import PLAIN_ADD
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.runtime_context import get_exec, get_parallel
@@ -89,7 +89,7 @@ def tp_slice(hidden_states, residual):
return hidden_states, residual
def gather_attention_tp(
def attn_tp_gather_input(
hidden_states: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
forward_batch: ForwardBatch,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
@@ -116,10 +116,10 @@ def gather_attention_tp(
gathered_hidden_states.append(output)
return tuple(gathered_hidden_states)
return _redistribute_from_attn_tp_shards(hidden_states)
return attn_tp_gather(hidden_states)
def _reduce_and_redistribute_output_to_attn_tp_shards(
def attn_tp_reduce_scatter(
hidden_states: torch.Tensor,
) -> torch.Tensor:
parallel = get_parallel()
@@ -130,7 +130,7 @@ def _reduce_and_redistribute_output_to_attn_tp_shards(
return local_hidden_states
def _redistribute_input_to_moe_cp(
def moe_cp_gather(
hidden_states: torch.Tensor, rows: List[int], moe_cp_size: int
) -> torch.Tensor:
# Zigzag split can produce unequal token counts across CP ranks
@@ -150,7 +150,7 @@ def _redistribute_input_to_moe_cp(
return output
def _mlp_input_reduce_output(
def attn_tp_all_reduce(
hidden_states: torch.Tensor, forward_batch: ForwardBatch, may_quantize: bool = True
) -> torch.Tensor:
if (
@@ -162,7 +162,7 @@ def _mlp_input_reduce_output(
return attention_tensor_model_parallel_all_reduce(hidden_states)
def _redistribute_input_to_dp(
def dp_gather(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
cp_shard_counts: Optional[List[int]] = None,
@@ -174,7 +174,7 @@ def _redistribute_input_to_dp(
return global_hidden_states
def _reduce_and_redistribute_output_to_dp(
def dp_gather_sum(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
cp_shard_counts: Optional[List[int]] = None,
@@ -198,15 +198,13 @@ def move_rows(
gathered, cut = rows.sharded - to.sharded, to.sharded - rows.sharded
if (gathered and cut) or TokenAxis.ATTN_CP in gathered | cut:
raise NotImplementedError(f"{rows=} {to=}")
if TokenAxis.ATTN_TP_SCATTER in gathered:
hidden_states = _redistribute_from_attn_tp_shards(hidden_states)
if TokenAxis.ATTN_TP in gathered:
hidden_states = attn_tp_gather(hidden_states)
if TokenAxis.ATTN_DP in gathered:
hidden_states = _redistribute_input_to_dp(hidden_states, forward_batch)
hidden_states = dp_gather(hidden_states, forward_batch)
if TokenAxis.ATTN_DP in cut:
hidden_states = _to_local_tokens(
_redistribute_output, forward_batch, hidden_states
)
if TokenAxis.ATTN_TP_SCATTER in cut:
hidden_states = to_dp_local(_dp_scatter_step, forward_batch, hidden_states)
if TokenAxis.ATTN_TP in cut:
parallel = get_parallel()
hidden_states = hidden_states.tensor_split(parallel.attn_tp_size)[
parallel.attn_tp_rank
@@ -214,9 +212,7 @@ def move_rows(
return hidden_states
def _tp_all_gather_scattered_rows(
hidden_states: torch.Tensor, forward_batch: ForwardBatch
) -> torch.Tensor:
def tp_gather(hidden_states: torch.Tensor, forward_batch: ForwardBatch) -> torch.Tensor:
# Input-scattered attention keeps the same number of tokens on every TP rank.
total_tokens = forward_batch.input_ids.shape[0]
output = hidden_states.new_empty((total_tokens, hidden_states.shape[-1]))
@@ -231,7 +227,7 @@ def _dp_scatter_group() -> GroupCoordinator:
return parallel.attn_tp_group
def _reduce_and_redistribute_output_varlen(
def dp_reduce_scatterv(
local_hidden_states: torch.Tensor,
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
@@ -243,7 +239,7 @@ def _reduce_and_redistribute_output_varlen(
)
def _reduce_and_redistribute_output_max_len(
def dp_reduce_scatter(
local_hidden_states: torch.Tensor,
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
@@ -251,7 +247,7 @@ def _reduce_and_redistribute_output_max_len(
dp_reduce_scatter_tensor(local_hidden_states, hidden_states)
def _redistribute_output(
def _dp_scatter_step(
local_hidden_states: torch.Tensor,
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
@@ -259,9 +255,7 @@ def _redistribute_output(
dp_scatter(local_hidden_states, hidden_states, forward_batch)
def _redistribute_output_from_moe_cp(
hidden_states: torch.Tensor, rows: List[int]
) -> torch.Tensor:
def moe_cp_take_back(hidden_states: torch.Tensor, rows: List[int]) -> torch.Tensor:
moe_cp_rank = get_moe_cp_rank()
# The allgather was padded to max_tokens_per_rank (equal chunks).
# Extract this rank's actual (non-padded) tokens from its chunk.
@@ -272,7 +266,7 @@ def _redistribute_output_from_moe_cp(
).contiguous()
def _to_local_tokens(
def to_dp_local(
step: Callable[[torch.Tensor, torch.Tensor, ForwardBatch], None],
forward_batch: ForwardBatch,
hidden_states: torch.Tensor,
@@ -282,15 +276,13 @@ def _to_local_tokens(
return local_hidden_states
def _all_reduce_then_to_local_tokens(
def all_reduce_to_dp_local(
group: GroupCoordinator, forward_batch: ForwardBatch, hidden_states: torch.Tensor
) -> torch.Tensor:
return _to_local_tokens(
_redistribute_output, forward_batch, group.all_reduce(hidden_states)
)
return to_dp_local(_dp_scatter_step, forward_batch, group.all_reduce(hidden_states))
def identity_output(
def keep_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
@@ -299,25 +291,25 @@ def identity_output(
return hidden_states, residual
def update_and_gather(
def update_attn_tp_gather_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
update: StageUpdate = ADD,
update: ResidualUpdate = PLAIN_ADD,
**kwargs,
):
hidden_states = update.update(hidden_states, residual)
return _redistribute_from_attn_tp_shards(hidden_states), None
return attn_tp_gather(hidden_states), None
def output_on_residual_shard(
def residual_slice_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
*,
sums: bool,
gathers_back: bool,
update: StageUpdate,
update: ResidualUpdate,
**kwargs,
):
"""Bring the FFN output onto the slice of the rows the residual is on:
@@ -339,16 +331,16 @@ def output_on_residual_shard(
return hidden_states, None
def scatter_output(
def attn_tp_slice_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
):
assert residual is None, "not yet handled residual!=None"
return _redistribute_to_attn_tp_shards(hidden_states), None
return attn_tp_slice(hidden_states), None
def take_back_attention_cp_shard(
def attn_cp_take_back_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
@@ -361,7 +353,7 @@ def take_back_attention_cp_shard(
return shard, residual
def reduce_scatter_over_cp(
def attn_cp_reduce_scatter_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
@@ -369,10 +361,10 @@ def reduce_scatter_over_cp(
):
"""DSA and MLA CP: sum the FFN output over the attention-CP group and
keep this rank's shard."""
return dsa_cp_reduce_scatter_hidden_states(hidden_states), residual
return attn_cp_reduce_scatter(hidden_states), residual
def take_back_cp_shard(
def dp_cp_take_back_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
@@ -393,7 +385,7 @@ def take_back_cp_shard(
return local_hidden_states, residual
def scatter_moe_cp_output(
def moe_cp_take_back_output(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
@@ -409,15 +401,13 @@ def scatter_moe_cp_output(
If DP>1, further scatter back to the local DP slice.
"""
# Only scatter back during prefill; decode was never allgathered so no-op.
# Safe w.r.t. empty tensors: same reasoning as _mlp_input_gather_moe_cp
# Safe w.r.t. empty tensors: same reasoning as _then_moe_cp_gather
# — CP extend always has non-zero tokens per rank, and decode skips this path.
rows = moe_cp_gathered_rows(forward_batch)
if rows is not None:
hidden_states = _redistribute_output_from_moe_cp(hidden_states, rows)
hidden_states = moe_cp_take_back(hidden_states, rows)
if get_parallel().attn_dp_size > 1:
hidden_states = _to_local_tokens(
_redistribute_output, forward_batch, hidden_states
)
hidden_states = to_dp_local(_dp_scatter_step, forward_batch, hidden_states)
return hidden_states, residual
@@ -43,42 +43,42 @@ class UnreducedOutput(msgspec.Struct, frozen=True):
Fields:
partial: Tensor containing this rank's contribution to the sum.
group: All-reduce group when no redistribution callable is supplied.
reduce_and_redistribute: Callable(partial) completing the sum and moving
reduce_to_dp_local: Callable(partial) completing the sum and moving
it to destination rows; takes precedence over group.
Exits hand this form to ResidualStream.leave(), which exposes an opaque
OwedOutput to models. Low-level adapters use reduce_output() before reading
it. A group is required when reduce_and_redistribute is absent.
Exits hand this form to ResidualStream.record(), which exposes an opaque
OwedOutput to models. Low-level adapters use complete_owed() before reading
it. A group is required when reduce_to_dp_local is absent.
"""
partial: torch.Tensor
group: Optional[GroupCoordinator] = None
# Under attention DP: the reduction that also brings ``partial`` back to this
# rank's tokens (a reduce-scatter, or an all-reduce then a scatter).
reduce_and_redistribute: Optional[Callable[[torch.Tensor], torch.Tensor]] = None
reduce_to_dp_local: Optional[Callable[[torch.Tensor], torch.Tensor]] = None
class HandoffOutput(msgspec.Struct, frozen=True):
class DeferredFinalize(msgspec.Struct, frozen=True):
"""A layer output that still owes work only its producer knows how to do (a
MoE's finalize and sum), left for the next layer's input or for a terminal
norm that accepts it (residual_batch.norm(handoff_norm=...)). A fused kernel
norm that accepts it (residual_batch.final_norm(finalize_norm=...)). A fused kernel
there may do that work together with its own; anything else passes it
through reduce_output(), which calls ``complete()``."""
through complete_owed(), which calls ``complete()``."""
def complete(self) -> torch.Tensor:
"""Do the owed work, unfused, and return the complete output."""
raise NotImplementedError
def reduce_output(
hidden_states: Union[torch.Tensor, UnreducedOutput, HandoffOutput, None],
def complete_owed(
hidden_states: Union[torch.Tensor, UnreducedOutput, DeferredFinalize, None],
) -> Optional[torch.Tensor]:
"""Run the work an UnreducedOutput or a HandoffOutput still owes; pass
"""Run the work an UnreducedOutput or a DeferredFinalize still owes; pass
anything else through."""
if isinstance(hidden_states, UnreducedOutput):
if hidden_states.reduce_and_redistribute is not None:
return hidden_states.reduce_and_redistribute(hidden_states.partial)
if hidden_states.reduce_to_dp_local is not None:
return hidden_states.reduce_to_dp_local(hidden_states.partial)
return hidden_states.group.all_reduce(hidden_states.partial)
if isinstance(hidden_states, HandoffOutput):
if isinstance(hidden_states, DeferredFinalize):
return hidden_states.complete()
return hidden_states
@@ -32,12 +32,12 @@ from sglang.srt.layers.dp_attention import (
)
from sglang.srt.layers.layer_boundary.adapters.attention import (
AttentionInputs,
_redistribute_from_attn_tp_shards,
_redistribute_to_attn_tp_shards,
attn_tp_gather,
attn_tp_slice,
get_attn_tp_context,
)
from sglang.srt.layers.layer_boundary.adapters.context_parallel import (
dsa_cp_gather_hidden_states,
attn_cp_gather,
)
from sglang.srt.layers.layer_boundary.layout import (
SumGroup,
@@ -45,12 +45,12 @@ from sglang.srt.layers.layer_boundary.layout import (
moe_cp_gathered_rows,
)
from sglang.srt.layers.layer_boundary.output import (
HandoffOutput,
DeferredFinalize,
UnreducedOutput,
reduce_output,
complete_owed,
)
from sglang.srt.layers.layer_boundary.residual import StageRead, StageUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import ADD, NORM_READ
from sglang.srt.layers.layer_boundary.residual import ResidualReadout, ResidualUpdate
from sglang.srt.layers.layer_boundary.residual.add_norm import NORM_READOUT, PLAIN_ADD
from sglang.srt.layers.layer_boundary.residual.stream import DeclaredSum
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.runtime_context import get_parallel
@@ -65,68 +65,68 @@ if _is_npu:
from sglang.srt.hardware_backend.npu.cmo import prepare_weight_cache
from sglang.srt.layers.layer_boundary.ops import (
_mlp_input_reduce_output,
_redistribute_input_to_dp,
_redistribute_input_to_moe_cp,
_reduce_and_redistribute_output_to_attn_tp_shards,
_reduce_and_redistribute_output_to_dp,
_tp_all_gather_scattered_rows,
attn_tp_all_reduce,
attn_tp_reduce_scatter,
dp_gather,
dp_gather_sum,
moe_cp_gather,
tp_gather,
)
def _mlp_input_without_dp(
def _reduce_update_read(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
gathers_residual: bool,
fusions: Tuple[Callable, ...],
group: SumGroup = SumGroup.ATTN_TP,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
"""Complete the sum the input owes over ``group`` on the rows it is on,
unless one of ``fusions`` does it with the residual add and the norm, then
write it into the residual and read the input."""
if gathers_residual:
residual = update.residual_from_attn_tp_shards(residual)
residual = update.gather_residual_attn_tp(residual)
for fused in fusions:
result = fused(hidden_states, residual, forward_batch)
if result is not None:
return result
if group is SumGroup.ATTN_TP:
# MHC sums its streams in full precision.
hidden_states = _mlp_input_reduce_output(
hidden_states, forward_batch, may_quantize=update.adds_plainly
hidden_states = attn_tp_all_reduce(
hidden_states, forward_batch, may_quantize=update.is_plain_add
)
elif group is SumGroup.TP:
hidden_states = tensor_model_parallel_all_reduce(hidden_states)
if _is_npu and cache is not None:
_ = prepare_weight_cache(hidden_states, cache)
return read.update_and_read(update, hidden_states, residual, layernorm)
return read.update_and_read(update, hidden_states, residual, norm)
def _mlp_input_dp_replicate(
def _reduce_update_read_dp_gather(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
gathers_residual: bool,
reduces_attention_tp: bool,
places_cp_shards: bool = False,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
"""Attention DP: complete the attention-TP sum if it is owed, write the
output into the residual and read the FFN input locally, then gather. With
``places_cp_shards`` each CP rank puts its shard of the DP group's tokens
beside the others' in the group's slot."""
if gathers_residual:
residual = update.residual_from_attn_tp_shards(residual)
residual = update.gather_residual_attn_tp(residual)
if hidden_states.shape[0] != 0:
if reduces_attention_tp:
hidden_states = attention_tensor_model_parallel_all_reduce(hidden_states)
@@ -135,48 +135,46 @@ def _mlp_input_dp_replicate(
disabled=not is_allocation_symmetric(),
):
hidden_states, residual = read.update_and_read(
update, hidden_states, residual, layernorm
update, hidden_states, residual, norm
)
else:
hidden_states, residual = read.update_and_read(
update, hidden_states, residual, layernorm
update, hidden_states, residual, norm
)
cp_shard_counts = _cp_shard_token_rows(forward_batch) if places_cp_shards else None
return (
_redistribute_input_to_dp(hidden_states, forward_batch, cp_shard_counts),
dp_gather(hidden_states, forward_batch, cp_shard_counts),
residual,
)
def _mlp_input_dp_partial(
def _dp_gather_sum_read(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
gathers_residual: bool,
places_cp_shards: bool = False,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
"""Attention DP: one rank adds the residual, the gather sums it, then read
the input from the sum. With ``places_cp_shards`` each CP rank puts its
shard of the DP group's tokens beside the others' in the group's slot."""
if gathers_residual:
residual = _redistribute_from_attn_tp_shards(residual)
residual = attn_tp_gather(residual)
if get_parallel().attn_tp_rank == 0:
hidden_states += residual
cp_shard_counts = _cp_shard_token_rows(forward_batch) if places_cp_shards else None
hidden_states = _reduce_and_redistribute_output_to_dp(
hidden_states, forward_batch, cp_shard_counts
)
hidden_states = dp_gather_sum(hidden_states, forward_batch, cp_shard_counts)
dp_scatter(residual, hidden_states, forward_batch, cp_shard_counts)
hidden_states, _ = read.read(hidden_states, layernorm)
hidden_states, _ = read.read(hidden_states, norm)
return hidden_states, residual
def _hand_qkv_hook_its_input(
def _attn_input_default(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
qkv_latent_func: Optional[Callable],
@@ -189,7 +187,7 @@ def _hand_qkv_hook_its_input(
return hidden_states
def _hand_scattered_input_to_attention(
def _attn_input_scattered(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
qkv_latent_func: Optional[Callable],
@@ -200,7 +198,7 @@ def _hand_scattered_input_to_attention(
told they are."""
ctx = get_attn_tp_context()
if ctx.is_dsa or qkv_latent_func is None:
hidden_states = _tp_all_gather_scattered_rows(hidden_states, forward_batch)
hidden_states = tp_gather(hidden_states, forward_batch)
if qkv_latent_func is not None:
ctx.set_attn_inputs(
AttentionInputs(
@@ -213,36 +211,36 @@ def _hand_scattered_input_to_attention(
return hidden_states
def _dispatch_consumer(
hidden_states, residual, forward_batch, norm, *, paths, update=ADD, **call
def _dispatch_by_update(
hidden_states, residual, forward_batch, norm, *, paths, update=PLAIN_ADD, **call
):
if residual is None:
# A missing residual cannot join a partial sum. The non-plain path
# performs enter/read without that optimization.
# performs init_residual/read without that optimization.
prepare = paths[False]
else:
try:
prepare = paths[update.adds_plainly]
prepare = paths[update.is_plain_add]
except KeyError:
raise RuntimeError("producer update has no bound input path") from None
return prepare(hidden_states, residual, forward_batch, norm, update=update, **call)
def _consumer_step(
hidden_states: Union[torch.Tensor, UnreducedOutput, HandoffOutput],
def _run_entry(
hidden_states: Union[torch.Tensor, UnreducedOutput, DeferredFinalize],
residual: Optional[torch.Tensor],
forward_batch: ForwardBatch,
norm: torch.nn.Module,
*,
step: Callable,
adds_plainly: bool,
is_plain_add: bool,
carried_fusions: Tuple[Callable, ...],
expected_sum: Optional[SumGroup] = None,
completed_step: Optional[Callable] = None,
pending=None,
written_step: Optional[Callable] = None,
written: bool = False,
update: StageUpdate = ADD,
update: ResidualUpdate = PLAIN_ADD,
**call,
):
"""A boundary's half into a stage: complete what the value carries, a sum
@@ -253,7 +251,7 @@ def _consumer_step(
whose declared sum is already completed uses ``completed_step`` instead;
a pending declared sum must match ``expected_sum``. ``call`` is what the stage's read takes (the attention's
``quant_format`` and ``post_residual_addition``)."""
if residual is not None and update.adds_plainly != adds_plainly:
if residual is not None and update.is_plain_add != is_plain_add:
raise RuntimeError("producer update does not match the boundary's capability")
if pending is not None:
if isinstance(pending.owed, DeclaredSum):
@@ -274,11 +272,8 @@ def _consumer_step(
f"an input that owes its sum by construction arrived as "
f"{type(owed).__name__}"
)
if (
isinstance(owed, UnreducedOutput)
and owed.reduce_and_redistribute is not None
):
hidden_states = reduce_output(owed)
if isinstance(owed, UnreducedOutput) and owed.reduce_to_dp_local is not None:
hidden_states = complete_owed(owed)
else:
for fused in carried_fusions:
result = fused(
@@ -286,36 +281,36 @@ def _consumer_step(
)
if result is not None:
return result
if isinstance(owed, HandoffOutput) or owed.partial.shape[0] != 0:
hidden_states = reduce_output(owed)
if isinstance(owed, DeferredFinalize) or owed.partial.shape[0] != 0:
hidden_states = complete_owed(owed)
else:
hidden_states = owed.partial
return step(hidden_states, residual, forward_batch, norm, update=update, **call)
def _read_input(
def _update_read(
hidden_states: torch.Tensor,
residual: Optional[torch.Tensor],
forward_batch: ForwardBatch,
norm: torch.nn.Module,
*,
cache=None,
layer_input: Optional[Callable],
pre_move: Optional[Callable],
enters_stack: bool,
read: StageRead,
update: StageUpdate = ADD,
read: ResidualReadout,
update: ResidualUpdate = PLAIN_ADD,
quant_format: str = "",
post_residual_addition: Optional[torch.Tensor] = None,
):
"""Complete what the input owes by construction (``layer_input``), then
"""Complete what the input owes by construction (``pre_move``), then
write the previous stage's output into the residual and read the stage's
input with ``norm``. The layer stack's first stage (``enters_stack``)
starts its residual from its input."""
enters = residual is None and enters_stack
if layer_input is not None:
hidden_states, residual = layer_input(hidden_states, residual)
if pre_move is not None:
hidden_states, residual = pre_move(hidden_states, residual)
if enters:
hidden_states, residual = read.enter(hidden_states), None
hidden_states, residual = read.init_residual(hidden_states), None
if residual is None:
# The previous layer already wrote its output into the residual.
return read.read(hidden_states, norm, quant_format)
@@ -329,50 +324,50 @@ def _read_input(
)
def _mlp_input_scatter(
def _attn_tp_reduce_scatter_update_read(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
scatters_residual: bool,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
hidden_states = _reduce_and_redistribute_output_to_attn_tp_shards(hidden_states)
hidden_states = attn_tp_reduce_scatter(hidden_states)
if scatters_residual:
residual = update.residual_to_attn_tp_shard(residual)
return read.update_and_read(update, hidden_states, residual, layernorm)
residual = update.slice_residual_attn_tp(residual)
return read.update_and_read(update, hidden_states, residual, norm)
def _mlp_input_slice(
def _attn_tp_slice_update_read(
hidden_states: torch.Tensor,
residual: Optional[torch.Tensor],
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
scatters_residual: bool,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
hidden_states = _redistribute_to_attn_tp_shards(hidden_states).clone()
hidden_states = attn_tp_slice(hidden_states).clone()
if scatters_residual and residual is not None:
residual = update.residual_to_attn_tp_shard(residual)
return read.update_and_read(update, hidden_states, residual, layernorm)
residual = update.slice_residual_attn_tp(residual)
return read.update_and_read(update, hidden_states, residual, norm)
def _mlp_input_on_residual_shard(
def _tp_reduce_scatter_update_read_gather(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
reduces: bool = True,
read: StageRead,
update: StageUpdate,
read: ResidualReadout,
update: ResidualUpdate,
):
"""The residual stays on each rank's slice while the FFN takes the full
rows: reduce-scatter the attention output onto the slice, which completes
@@ -386,54 +381,52 @@ def _mlp_input_on_residual_shard(
parallel.tp_group.reduce_scatter_tensor(shard, hidden_states)
else:
shard = shard.clone()
shard, residual = read.update_and_read(update, shard, residual, layernorm)
shard, residual = read.update_and_read(update, shard, residual, norm)
attn_tp_all_gather_into_tensor(hidden_states, shard)
return hidden_states, residual
def _mlp_input_residual_into_sum(
def _tp_sum_with_residual_read(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
read: StageRead = NORM_READ,
update: StageUpdate = ADD,
read: ResidualReadout = NORM_READOUT,
update: ResidualUpdate = PLAIN_ADD,
):
return _tp_all_reduce_with_scattered_residual(
hidden_states, residual, layernorm, read
)
return _tp_all_reduce_with_scattered_residual(hidden_states, residual, norm, read)
def _mlp_input_gather_attention_cp(
def _then_attn_cp_gather(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
gather: Callable,
update: StageUpdate = ADD,
update: ResidualUpdate = PLAIN_ADD,
):
"""DSA and MLA CP: complete this rank's shard, then gather the shards, of
equal length, over the attention-CP group. The residual stays on the
shard."""
hidden_states, residual = gather(
hidden_states, residual, forward_batch, layernorm, update=update, cache=cache
hidden_states, residual, forward_batch, norm, update=update, cache=cache
)
return dsa_cp_gather_hidden_states(hidden_states), residual
return attn_cp_gather(hidden_states), residual
def _mlp_input_gather_moe_cp(
def _then_moe_cp_gather(
hidden_states: torch.Tensor,
residual: torch.Tensor,
forward_batch: ForwardBatch,
layernorm: torch.nn.Module,
norm: torch.nn.Module,
*,
cache=None,
gather: Callable,
update: StageUpdate = ADD,
update: ResidualUpdate = PLAIN_ADD,
):
"""Gather for the FFN, then over the MoE-CP group so each rank holds all
tokens of its MoE group (moe_dp_size < attn_cp_size). The residual stays on
@@ -447,14 +440,12 @@ def _mlp_input_gather_moe_cp(
return hidden_states, residual
hidden_states, residual = gather(
hidden_states, residual, forward_batch, layernorm, update=update, cache=cache
hidden_states, residual, forward_batch, norm, update=update, cache=cache
)
rows = moe_cp_gathered_rows(forward_batch)
if rows is not None and hidden_states.shape[0] > 0:
hidden_states = _redistribute_input_to_moe_cp(
hidden_states, rows, get_moe_cp_size()
)
hidden_states = moe_cp_gather(hidden_states, rows, get_moe_cp_size())
return hidden_states, residual
@@ -462,8 +453,8 @@ def _mlp_input_gather_moe_cp(
def _tp_all_reduce_with_scattered_residual(
hidden_states: torch.Tensor,
residual: torch.Tensor,
layernorm: torch.nn.Module,
read: StageRead = NORM_READ,
norm: torch.nn.Module,
read: ResidualReadout = NORM_READOUT,
):
parallel = get_parallel()
if hidden_states.shape[0] == 0:
@@ -472,4 +463,4 @@ def _tp_all_reduce_with_scattered_residual(
scattered_states = hidden_states.tensor_split(parallel.tp_size)[parallel.tp_rank]
scattered_states += residual
residual = tensor_model_parallel_all_reduce(hidden_states)
return read.read(residual, layernorm)
return read.read(residual, norm)
@@ -21,31 +21,31 @@ from typing import NamedTuple, Optional, Protocol, Tuple
import torch
class StageUpdate(Protocol):
class ResidualUpdate(Protocol):
"""Producer-owned operation writing a contribution into the residual.
Fields:
adds_plainly: Whether update is plain addition, permitting compatible
is_plain_add: Whether update is plain addition, permitting compatible
add+norm fusion and adding the residual on one rank before a sum.
at_producer: Whether the producer writes the residual at its exit rather
applied_at_exit: Whether the producer writes the residual at its exit rather
than leaving the operation for the next prepare.
can_defer_across_layers: Whether parameters/state remain valid after
outlives_layer: Whether parameters/state remain valid after
leaving the producer layer, including any offload or state reuse.
The shard conversion methods must move any update-associated state together
with the residual. Nonlinear updates must not claim adds_plainly.
with the residual. Nonlinear updates must not claim is_plain_add.
"""
# A plain add, which one rank may run before the sum it adds into
# completes (the DP partial order, a residual that joins the attention
# output's sum), and which a fused add + norm kernel may run.
adds_plainly: bool
is_plain_add: bool
# The stage writes its output into the residual itself at its end, instead
# of leaving that to the next stage's read.
at_producer: bool
applied_at_exit: bool
# Its parameters and state remain valid after leaving the producer layer.
# Stateful or offloaded implementations must not opt in without that guarantee.
can_defer_across_layers: bool
outlives_layer: bool
def update(self, hidden_states, residual) -> torch.Tensor:
"""Write hidden_states, the producer contribution, into residual.
@@ -55,36 +55,37 @@ class StageUpdate(Protocol):
This operation does not perform the consumer's normalization.
"""
def residual_to_attn_tp_shard(self, residual) -> torch.Tensor:
def slice_residual_attn_tp(self, residual) -> torch.Tensor:
"""This attention-TP rank's slice of the residual, with whatever the
update reads along with it."""
def residual_from_attn_tp_shards(self, residual) -> torch.Tensor:
def gather_residual_attn_tp(self, residual) -> torch.Tensor:
"""The residual gathered from every attention-TP rank's slice."""
class StageRead(Protocol):
class ResidualReadout(Protocol):
"""Consumer-owned operation deriving compute input from the residual.
Fields:
norms_plainly: Read is normalization/optional quantization without changing
is_plain_norm: Read is normalization/optional quantization without changing
the residual, allowing compatible fused add+norm implementations.
before_gather: Preserve this read on source rows before a DP gather.
reads_before_dp_gather: Preserve this read on source rows before a DP gather.
enter initializes the stack residual. read consumes an already-written
residual; update_and_read first applies the actual producer's update.
Both reads return (compute_input, residual), preserving their kernel's
rounding order rather than normalizing a separately rounded snapshot.
init_residual initializes the stack residual. read consumes an
already-written residual; update_and_read first applies the actual
producer's update. Both reads return (compute_input, residual), preserving
their kernel's rounding order rather than normalizing a separately rounded
snapshot.
"""
# The input is the residual's norm, in the quantization the call asks for,
# and the residual is left as it is: what a fused add + norm kernel computes,
# and what may run on the rows a sum completes onto.
norms_plainly: bool
is_plain_norm: bool
# Preserve the read on the source rows before a DP gather.
before_gather: bool
reads_before_dp_gather: bool
def enter(self, hidden_states) -> torch.Tensor:
def init_residual(self, hidden_states) -> torch.Tensor:
"""The residual the layer stack starts from, given its input."""
def read(
@@ -110,7 +111,7 @@ class StageRead(Protocol):
def update_and_read(
self,
update: StageUpdate,
update: ResidualUpdate,
hidden_states,
residual,
norm,
@@ -120,7 +121,7 @@ class StageRead(Protocol):
"""Apply a producer update and read input while preserving kernel ordering.
Args:
update: Actual producer's StageUpdate, not a consumer-inferred operation.
update: Actual producer's ResidualUpdate, not a consumer-inferred operation.
hidden_states: Producer contribution after required communication.
residual: Previous residual, or None at entry where supported.
norm: Consumer normalization module.
@@ -133,11 +134,11 @@ class StageRead(Protocol):
"""
class LayerResidual(NamedTuple):
class LayerResidualOps(NamedTuple):
"""The reads and updates a decoder layer declares for its attention and
its FFN."""
attention_read: StageRead
attention_update: StageUpdate
ffn_read: StageRead
ffn_update: StageUpdate
attn_readout: ResidualReadout
attn_update: ResidualUpdate
ffn_readout: ResidualReadout
ffn_update: ResidualUpdate
@@ -19,16 +19,16 @@ import torch
from sglang.srt.distributed import GroupCoordinator
from sglang.srt.layers.layer_boundary.output import (
HandoffOutput,
DeferredFinalize,
UnreducedOutput,
reduce_output,
complete_owed,
)
from sglang.srt.layers.layer_boundary.residual.stream import OwedOutput, ResidualStream
from sglang.srt.model_executor.forward_batch_info import ForwardBatch, PPProxyTensors
def buffer(
hidden_states: Union[torch.Tensor, UnreducedOutput, HandoffOutput],
hidden_states: Union[torch.Tensor, UnreducedOutput, DeferredFinalize],
) -> Optional[torch.Tensor]:
"""Storage that can be reused after prepare consumes the input. A finalize
handoff has no reusable layer-output tensor. This does not complete or read
@@ -37,7 +37,7 @@ def buffer(
return hidden_states.contribution.value
if isinstance(hidden_states, UnreducedOutput):
return hidden_states.partial
if isinstance(hidden_states, HandoffOutput):
if isinstance(hidden_states, DeferredFinalize):
return None
return hidden_states
@@ -48,7 +48,7 @@ def add_to_output(hidden_states, residual, extra: torch.Tensor) -> Tuple:
hidden_states = (
residual.complete(hidden_states)
if isinstance(residual, ResidualStream)
else reduce_output(hidden_states)
else complete_owed(hidden_states)
)
hidden_states.add_(extra)
return hidden_states, residual
@@ -59,10 +59,10 @@ def fold(hidden_states, residual):
The following stage receives it with no outstanding residual addition."""
stream = residual if isinstance(residual, ResidualStream) else None
if stream is not None:
if stream.pending is not None and not stream.pending.update.adds_plainly:
if stream.pending is not None and not stream.pending.update.is_plain_add:
raise NotImplementedError("fold requires a plain residual update")
hidden_states, residual = stream.finish(hidden_states)
hidden_states = reduce_output(hidden_states)
hidden_states, residual = stream.export(hidden_states)
hidden_states = complete_owed(hidden_states)
if residual is not None:
hidden_states = hidden_states + residual
return (
@@ -77,33 +77,33 @@ def written(hidden_states):
return hidden_states, ResidualStream(hidden_states)
def finish_layer_stack(
hidden_states: Union[torch.Tensor, UnreducedOutput, HandoffOutput],
def export_output(
hidden_states: Union[torch.Tensor, UnreducedOutput, DeferredFinalize],
residual: Optional[torch.Tensor],
forward_batch: ForwardBatch,
*,
final_norm_takes_handoff: bool = False,
preserve_declared: bool = False,
) -> Tuple[Union[torch.Tensor, HandoffOutput], Optional[torch.Tensor]]:
) -> Tuple[Union[torch.Tensor, DeferredFinalize], Optional[torch.Tensor]]:
"""Complete what this layer left for a next layer, for callers that carry
an explicit residual tensor or merge TBO microbatches. Stage-boundary
decoders use residual_batch.norm(), to_pp() or take_output() instead:
decoders use residual_batch.final_norm(), to_pp() or take_output() instead:
to_pp() keeps a declared partial sum for the receiving from_pp(), which
this helper would complete early. A final norm that does a producer's
handoff together with its own work (``final_norm_takes_handoff``)
receives it as it is."""
if isinstance(residual, ResidualStream):
return residual.finish(
return residual.export(
hidden_states,
takes_handoff=final_norm_takes_handoff,
preserve_declared=preserve_declared,
)
if final_norm_takes_handoff and isinstance(hidden_states, HandoffOutput):
if final_norm_takes_handoff and isinstance(hidden_states, DeferredFinalize):
return hidden_states, residual
return reduce_output(hidden_states), residual
return complete_owed(hidden_states), residual
def norm_output(hidden_states, residual, norm, capture_output=None, **read_kwargs):
def final_norm_pair(hidden_states, residual, norm, capture=None, **read_kwargs):
"""The final norm and an optional capture of the same updated residual.
Keep add and norm together: normalizing a separately rounded residual is
@@ -111,12 +111,12 @@ def norm_output(hidden_states, residual, norm, capture_output=None, **read_kwarg
capture callback owns retention of the borrowed residual storage.
"""
if residual is None:
if capture_output is not None:
capture_output(hidden_states)
if capture is not None:
capture(hidden_states)
return norm(hidden_states)
hidden_states, residual = norm(hidden_states, residual, **read_kwargs)
if capture_output is not None:
capture_output(residual)
if capture is not None:
capture(residual)
return hidden_states
@@ -26,11 +26,11 @@ from sglang.srt.layers.flashinfer_comm_fusion import (
uses_cutedsl_ar_fusion,
)
from sglang.srt.layers.layer_boundary.adapters.attention import (
_redistribute_from_attn_tp_shards,
_redistribute_to_attn_tp_shards,
attn_tp_gather,
attn_tp_slice,
get_attn_tp_context,
)
from sglang.srt.layers.layer_boundary.residual import LayerResidual
from sglang.srt.layers.layer_boundary.residual import LayerResidualOps
from sglang.srt.layers.quantization.fp8_utils import (
_use_aiter_bpreshuffle_gfx95,
materialize_bpreshuffle_fp8_scale_tuple,
@@ -139,7 +139,7 @@ def _fused_rmsnorm_fp8_per_token_quant(
FUSE_ALLREDUCE_MAX_BATCH_SIZE = 2048
def apply_flashinfer_allreduce_fusion(batch_size: int):
def flashinfer_ar_fusion_applies(batch_size: int):
return (
# NOTE: flashinfer 0.6.1 caused performance regression on sm100 for allreduce fusion
# Ref: https://github.com/sgl-project/sglang/issues/17237
@@ -158,7 +158,7 @@ def apply_flashinfer_allreduce_fusion(batch_size: int):
)
def aiter_all_reduce_fusion_enabled_for(forward_mode: ForwardMode) -> bool:
def aiter_ar_fusion_enabled_for(forward_mode: ForwardMode) -> bool:
comm = get_exec().comm
if not comm.enable_aiter_allreduce_fusion:
return False
@@ -167,9 +167,7 @@ def aiter_all_reduce_fusion_enabled_for(forward_mode: ForwardMode) -> bool:
return not comm.disable_aiter_allreduce_fusion_in_decode
def apply_aiter_all_reduce_fusion(
input_tensor: torch.Tensor, forward_batch: ForwardBatch
):
def aiter_ar_fusion_applies(input_tensor: torch.Tensor, forward_batch: ForwardBatch):
n = input_tensor.shape[-1]
total_bytes = input_tensor.numel() * input_tensor.element_size()
# Aiter's should_custom_ar uses <= max_size/2 (64 MB); match that boundary.
@@ -180,7 +178,7 @@ def apply_aiter_all_reduce_fusion(
and total_bytes <= 8 * 1024 * 8192
and get_parallel().tp_size != 6
and not is_dp_attention_enabled()
and aiter_all_reduce_fusion_enabled_for(forward_batch.forward_mode)
and aiter_ar_fusion_enabled_for(forward_batch.forward_mode)
)
@@ -250,7 +248,7 @@ def _update_and_read_residual_aiter_fp8_per_token(
)
def _attn_input_update_and_read_residual(quant_format: str):
def _norm_quant_kernel(quant_format: str):
"""Add the previous layer's output to the residual and read the attention
input from it: the input norm, fused with the quantization this format
wants. Without a residual (the first layer, or one already folded into
@@ -264,22 +262,22 @@ def _attn_input_update_and_read_residual(quant_format: str):
return _update_and_read_residual_plain
class Add:
class PlainAdd:
"""A plain residual: the output is added into it."""
adds_plainly = True
at_producer = False
can_defer_across_layers = True
is_plain_add = True
applied_at_exit = False
outlives_layer = True
def update(self, hidden_states, residual):
hidden_states += residual
return hidden_states
def residual_to_attn_tp_shard(self, residual):
return _redistribute_to_attn_tp_shards(residual)
def slice_residual_attn_tp(self, residual):
return attn_tp_slice(residual)
def residual_from_attn_tp_shards(self, residual):
return _redistribute_from_attn_tp_shards(residual)
def gather_residual_attn_tp(self, residual):
return attn_tp_gather(residual)
class Fp8Input(Enum):
@@ -290,25 +288,23 @@ class Fp8Input(Enum):
@dataclass(frozen=True)
class NormQuantRead:
class NormQuantReadout:
"""The input is the residual's norm, fused with the quantization the
consumer asks for (``quant_format``) and a post-residual addition; a plain
add of the previous output runs in the same kernel. An empty batch skips
the norm."""
norms_plainly = True
before_gather: bool = False
is_plain_norm = True
reads_before_dp_gather: bool = False
fp8_input: Optional[Fp8Input] = None
def enter(self, hidden_states):
def init_residual(self, hidden_states):
return hidden_states
def read(self, residual, norm, quant_format="", post_residual_addition=None):
if residual.shape[0] == 0:
return residual, residual
return _attn_input_update_and_read_residual(quant_format)(
norm, residual, None, None
)
return _norm_quant_kernel(quant_format)(norm, residual, None, None)
def update_and_read(
self,
@@ -319,24 +315,24 @@ class NormQuantRead:
quant_format="",
post_residual_addition=None,
):
if not update.adds_plainly:
if not update.is_plain_add:
return self.read(update.update(hidden_states, residual), norm, quant_format)
if hidden_states.shape[0] == 0:
return hidden_states, hidden_states
return _attn_input_update_and_read_residual(quant_format)(
return _norm_quant_kernel(quant_format)(
norm, hidden_states, residual, post_residual_addition
)
@dataclass(frozen=True)
class NormRead:
class NormReadout:
"""The input is the residual's norm; a plain add of the previous output
runs in the same kernel. An empty batch skips the norm."""
norms_plainly = True
before_gather: bool = False
is_plain_norm = True
reads_before_dp_gather: bool = False
def enter(self, hidden_states):
def init_residual(self, hidden_states):
return hidden_states
def read(self, residual, norm, quant_format="", post_residual_addition=None):
@@ -360,7 +356,7 @@ class NormRead:
if residual is None:
# The layer stack starts at this stage: its input is the residual.
return self.read(hidden_states, norm, quant_format, post_residual_addition)
if not update.adds_plainly:
if not update.is_plain_add:
return self.read(update.update(hidden_states, residual), norm, quant_format)
if quant_format or post_residual_addition is not None:
raise NotImplementedError(
@@ -371,14 +367,14 @@ class NormRead:
return norm(hidden_states, residual)
ADD = Add()
NORM_QUANT_READ = NormQuantRead()
NORM_READ = NormRead()
PLAIN_ADD = PlainAdd()
NORM_QUANT_READOUT = NormQuantReadout()
NORM_READOUT = NormReadout()
# A plain residual: the attention reads with its input norm and the quantization
# it wants, the FFN with its norm, and each stage's output is added.
PLAIN_RESIDUAL = LayerResidual(
attention_read=NORM_QUANT_READ,
attention_update=ADD,
ffn_read=NORM_READ,
ffn_update=ADD,
PLAIN_RESIDUAL_OPS = LayerResidualOps(
attn_readout=NORM_QUANT_READOUT,
attn_update=PLAIN_ADD,
ffn_readout=NORM_READOUT,
ffn_update=PLAIN_ADD,
)
@@ -27,7 +27,7 @@ def start(forward_batch):
forward_batch.residual_stream = ResidualStream()
def current(forward_batch):
def stream_of(forward_batch):
stream = forward_batch.residual_stream
if stream is None:
raise RuntimeError("start the layer stack before entering a stage")
@@ -36,12 +36,12 @@ def current(forward_batch):
def complete_output(hidden_states, forward_batch):
"""Complete the contribution while retaining its pending residual update."""
return current(forward_batch).complete(hidden_states)
return stream_of(forward_batch).complete(hidden_states)
def take_output(hidden_states, forward_batch):
"""Release a terminal output whose residual update has already been written."""
stream = current(forward_batch)
stream = stream_of(forward_batch)
stream.check(hidden_states)
if stream.pending is not None:
raise RuntimeError("write the residual update before taking the final output")
@@ -49,13 +49,13 @@ def take_output(hidden_states, forward_batch):
return hidden_states
def norm(
def final_norm(
hidden_states,
forward_batch,
layernorm,
capture_output=None,
capture=None,
*,
handoff_norm=None,
finalize_norm=None,
skip_empty=False,
**read_kwargs,
):
@@ -65,9 +65,9 @@ def norm(
hidden_states: Current stream output or opaque owed handle.
forward_batch: Batch owning the residual stream.
layernorm: Final norm supporting the model's output/residual pair.
capture_output: Optional callback retaining the same updated residual;
capture: Optional callback retaining the same updated residual;
it must copy borrowed storage when retention requires ownership.
handoff_norm: Optional adapter with finalize(handoff, residual, gamma)
finalize_norm: Optional adapter with finalize(handoff, residual, gamma)
for a producer-specific finalize handoff; when a handoff arrives it
cannot be combined with capture. Without it, a handoff is completed
unfused first. Its gamma is layernorm.gemma_weight, so the final
@@ -79,29 +79,29 @@ def norm(
Normalized tensor. Add and norm remain together to preserve the kernel's
accumulation/rounding order; a snapshot is not used as the norm input.
"""
hidden_states, residual = current(forward_batch).finish(
hidden_states, takes_handoff=handoff_norm is not None
hidden_states, residual = stream_of(forward_batch).export(
hidden_states, takes_handoff=finalize_norm is not None
)
# The terminal consumer now owns the pair. Do not keep layer buffers alive
# through logits processing or the next forward on this batch.
forward_batch.residual_stream = None
from sglang.srt.layers.layer_boundary.output import HandoffOutput
from sglang.srt.layers.layer_boundary.output import DeferredFinalize
if isinstance(hidden_states, HandoffOutput):
if isinstance(hidden_states, DeferredFinalize):
if residual is None:
raise RuntimeError("invalid final deferred MoE handoff")
if capture_output is not None:
if capture is not None:
raise RuntimeError(
"final handoff capture requires an explicit capture adapter"
)
hidden_states, _ = handoff_norm.finalize(
hidden_states, _ = finalize_norm.finalize(
handoff=hidden_states, residual=residual, gamma=layernorm.gemma_weight
)
return hidden_states
if skip_empty and hidden_states.shape[0] == 0:
return hidden_states
return access.norm_output(
hidden_states, residual, layernorm, capture_output, **read_kwargs
return access.final_norm_pair(
hidden_states, residual, layernorm, capture, **read_kwargs
)
@@ -117,7 +117,7 @@ def to_pp(hidden_states, forward_batch, *, preserve_declared=True):
Runtime-selected completion work is finished before transport.
"""
hidden_states, residual = current(forward_batch).finish(
hidden_states, residual = stream_of(forward_batch).export(
hidden_states, preserve_declared=preserve_declared
)
forward_batch.residual_stream = None
@@ -125,19 +125,19 @@ def to_pp(hidden_states, forward_batch, *, preserve_declared=True):
def snapshot(hidden_states, forward_batch):
return current(forward_batch).snapshot(hidden_states)
return stream_of(forward_batch).snapshot(hidden_states)
def add_to_output(hidden_states, forward_batch, extra):
output, _ = access.add_to_output(hidden_states, current(forward_batch), extra)
output, _ = access.add_to_output(hidden_states, stream_of(forward_batch), extra)
return output
def fold(hidden_states, forward_batch):
output, _ = access.fold(hidden_states, current(forward_batch))
output, _ = access.fold(hidden_states, stream_of(forward_batch))
return output
def written(hidden_states, forward_batch):
def set_written(hidden_states, forward_batch):
forward_batch.residual_stream = ResidualStream(hidden_states)
return hidden_states
@@ -19,7 +19,7 @@ from typing import Callable, Optional
import torch
from sglang.kernels.ops.layernorm.mhc import hc_contract, hc_expand
from sglang.srt.layers.layer_boundary.residual import LayerResidual
from sglang.srt.layers.layer_boundary.residual import LayerResidualOps
from sglang.srt.runtime_context import get_parallel
@@ -28,7 +28,7 @@ class MHCState:
"""A layer's residual as hyper-connection streams: the residual is hc_mult
streams, a stage's output is written in with hc_post and the next stage's
input read with hc_pre and the norm. A read produces the h_res / h_post the
next write-back consumes; they move with the tokens. ``layer_residual()``
next write-back consumes; they move with the tokens. ``residual_ops()``
gives the reads and updates the layer's two stages declare. Parameters
belong to the owning layer; this state only holds scratch shared across
communication stages."""
@@ -50,7 +50,9 @@ class MHCState:
return None, None
return out_norm.weight.data, out_norm.variance_epsilon
def attn_split(self, hidden_states, out_norm: Optional[torch.nn.Module] = None):
def read_attn_input(
self, hidden_states, out_norm: Optional[torch.nn.Module] = None
):
residual = hidden_states
out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm)
hidden_states, self.h_res, self.h_post, norm_fused = self.hc_attn_pre(
@@ -60,7 +62,7 @@ class MHCState:
hidden_states = out_norm(hidden_states)
return hidden_states, residual
def attn_to_mlp(
def update_and_read_ffn_input(
self, hidden_states, residual, out_norm: Optional[torch.nn.Module] = None
):
out_norm_weight, out_norm_eps = self._resolve_out_norm(out_norm)
@@ -90,97 +92,99 @@ class MHCState:
hidden_states = out_norm(hidden_states)
return hidden_states, residual
def mlp_combine(self, hidden_states, residual):
def apply_post(self, hidden_states, residual):
return self.hc_post(hidden_states, residual, self.h_res, self.h_post)
def reset_aux(self):
def clear_coefficients(self):
self.h_res = None
self.h_post = None
def residual_to_attn_tp_shard(self, residual):
def slice_residual_attn_tp(self, residual):
parallel = get_parallel()
rank, size = parallel.attn_tp_rank, parallel.attn_tp_size
self.h_res = self.h_res.tensor_split(size)[rank]
self.h_post = self.h_post.tensor_split(size)[rank]
return residual.tensor_split(size)[rank]
def residual_from_attn_tp_shards(self, residual):
def gather_residual_attn_tp(self, residual):
raise NotImplementedError(
"Unsupported: h_res/h_post allgather not implemented."
)
def layer_residual(self) -> LayerResidual:
return LayerResidual(
attention_read=_AttentionRead(self),
attention_update=_AttentionUpdate(self),
ffn_read=_FfnRead(self),
def residual_ops(self) -> LayerResidualOps:
return LayerResidualOps(
attn_readout=_AttnReadout(self),
attn_update=_AttnUpdate(self),
ffn_readout=_FfnReadout(self),
ffn_update=_FfnUpdate(self),
)
class _AttentionRead:
class _AttnReadout:
"""hc_pre and the input norm, from streams that already hold the previous
layer's output: an MHC layer takes its input written back."""
norms_plainly = False
before_gather = False
is_plain_norm = False
reads_before_dp_gather = False
def __init__(self, state: MHCState):
self.state = state
def enter(self, hidden_states):
def init_residual(self, hidden_states):
return hc_expand(hidden_states, self.state.hc_mult)
def read(self, residual, norm, quant_format="", post_residual_addition=None):
if quant_format:
raise NotImplementedError(f"an MHC attention input in {quant_format=}")
return self.state.attn_split(residual, out_norm=norm)
return self.state.read_attn_input(residual, out_norm=norm)
def update_and_read(self, update, hidden_states, residual, norm, **kwargs):
raise NotImplementedError("an MHC layer takes its input written back")
class _AttentionUpdate:
class _AttnUpdate:
"""hc_post with the coefficients the attention's read produced. It is not a
plain add, so it runs only once the sum it writes in is complete."""
adds_plainly = False
at_producer = False
can_defer_across_layers = False
is_plain_add = False
applied_at_exit = False
outlives_layer = False
def __init__(self, state: MHCState):
self.state = state
def update(self, hidden_states, residual):
return self.state.mlp_combine(hidden_states, residual)
return self.state.apply_post(hidden_states, residual)
def residual_to_attn_tp_shard(self, residual):
return self.state.residual_to_attn_tp_shard(residual)
def slice_residual_attn_tp(self, residual):
return self.state.slice_residual_attn_tp(residual)
def residual_from_attn_tp_shards(self, residual):
return self.state.residual_from_attn_tp_shards(residual)
def gather_residual_attn_tp(self, residual):
return self.state.gather_residual_attn_tp(residual)
class _FfnRead:
class _FfnReadout:
"""The attention output's hc_post and the FFN input's hc_pre and norm, fused
in hc_ffn_post_pre when it takes the batch."""
norms_plainly = False
before_gather = False
is_plain_norm = False
reads_before_dp_gather = False
def __init__(self, state: MHCState):
self.state = state
def enter(self, hidden_states):
def init_residual(self, hidden_states):
return hc_expand(hidden_states, self.state.hc_mult)
def read(self, residual, norm, quant_format="", post_residual_addition=None):
raise NotImplementedError("an MHC FFN input read without its attention")
def update_and_read(self, update, hidden_states, residual, norm, **kwargs):
if not isinstance(update, _AttentionUpdate) or update.state is not self.state:
if not isinstance(update, _AttnUpdate) or update.state is not self.state:
raise NotImplementedError(f"an MHC FFN input after {update=}")
return self.state.attn_to_mlp(hidden_states, residual, out_norm=norm)
return self.state.update_and_read_ffn_input(
hidden_states, residual, out_norm=norm
)
class _FfnUpdate:
@@ -188,22 +192,22 @@ class _FfnUpdate:
layer runs itself; the last layer also contracts the streams into the
hidden states the layer stack hands on."""
adds_plainly = False
at_producer = True
can_defer_across_layers = False
is_plain_add = False
applied_at_exit = True
outlives_layer = False
def __init__(self, state: MHCState):
self.state = state
def update(self, hidden_states, residual):
hidden_states = self.state.mlp_combine(hidden_states, residual)
self.state.reset_aux()
hidden_states = self.state.apply_post(hidden_states, residual)
self.state.clear_coefficients()
if self.state.is_last_layer:
hidden_states = hc_contract(hidden_states, self.state.hc_mult)
return hidden_states
def residual_to_attn_tp_shard(self, residual):
return self.state.residual_to_attn_tp_shard(residual)
def slice_residual_attn_tp(self, residual):
return self.state.slice_residual_attn_tp(residual)
def residual_from_attn_tp_shards(self, residual):
return self.state.residual_from_attn_tp_shards(residual)
def gather_residual_attn_tp(self, residual):
return self.state.gather_residual_attn_tp(residual)
@@ -20,25 +20,25 @@ import torch
from sglang.srt.distributed import GroupCoordinator
from sglang.srt.layers.layer_boundary.layout import SumGroup, _sum_group
from sglang.srt.layers.layer_boundary.output import HandoffOutput, UnreducedOutput
from sglang.srt.layers.layer_boundary.residual import StageUpdate
from sglang.srt.layers.layer_boundary.output import DeferredFinalize, UnreducedOutput
from sglang.srt.layers.layer_boundary.residual import ResidualUpdate
class CarriedSum(msgspec.Struct, frozen=True):
class DeferredSum(msgspec.Struct, frozen=True):
"""Runtime reduction left by an exit decision.
Fields:
group: All-reduce group when no redistribution callable is supplied.
reduce_and_redistribute: Optional callable(value) returning a reduced
reduce_to_dp_local: Optional callable(value) returning a reduced
value on destination rows; takes precedence over group.
"""
group: Optional[GroupCoordinator] = None
reduce_and_redistribute: Optional[Callable] = None
reduce_to_dp_local: Optional[Callable] = None
def complete(self, value):
if self.reduce_and_redistribute is not None:
return self.reduce_and_redistribute(value)
if self.reduce_to_dp_local is not None:
return self.reduce_to_dp_local(value)
return self.group.all_reduce(value)
@@ -63,23 +63,23 @@ class Contribution(msgspec.Struct):
"""
value: Optional[torch.Tensor]
update: StageUpdate
owed: Union[CarriedSum, DeclaredSum, HandoffOutput, None] = None
update: ResidualUpdate
owed: Union[DeferredSum, DeclaredSum, DeferredFinalize, None] = None
def for_boundary(self):
# These forms are private inputs to the existing fused-kernel adapters.
if isinstance(self.owed, CarriedSum):
if isinstance(self.owed, DeferredSum):
return UnreducedOutput(
self.value, self.owed.group, self.owed.reduce_and_redistribute
self.value, self.owed.group, self.owed.reduce_to_dp_local
)
if isinstance(self.owed, HandoffOutput):
if isinstance(self.owed, DeferredFinalize):
return self.owed
return self.value
def complete(self):
if isinstance(self.owed, (CarriedSum, DeclaredSum)):
if isinstance(self.owed, (DeferredSum, DeclaredSum)):
value = self.owed.complete(self.value)
elif isinstance(self.owed, HandoffOutput):
elif isinstance(self.owed, DeferredFinalize):
value = self.owed.complete()
else:
return self.value
@@ -123,7 +123,7 @@ class ResidualStream:
self.pending = None
@classmethod
def arrive(cls, hidden, residual, update, *, declared_sum=None):
def from_handoff(cls, hidden, residual, update, *, declared_sum=None):
"""Reconstruct a stream from a tensor handoff, including a TBO microbatch.
Args:
@@ -139,7 +139,7 @@ class ResidualStream:
stream = cls(residual)
if residual is None:
return stream.write(hidden), stream
return stream.leave(hidden, update, declared_sum=declared_sum), stream
return stream.record(hidden, update, declared_sum=declared_sum), stream
def write(self, residual):
if self.pending is not None:
@@ -150,11 +150,11 @@ class ResidualStream:
self.pending = None
return residual
def leave(self, output, update, *, declared_sum=None):
def record(self, output, update, *, declared_sum=None):
"""Record one producer contribution without applying its residual update.
Args:
output: Complete tensor, UnreducedOutput, or producer-specific HandoffOutput.
output: Complete tensor, UnreducedOutput, or producer-specific DeferredFinalize.
update: Producer operation that the next boundary must apply.
declared_sum: SumGroup statically owed by a raw tensor, or None. Cannot
be combined with another output wrapper's completion contract.
@@ -173,9 +173,9 @@ class ResidualStream:
contribution = Contribution(
output.partial,
update,
CarriedSum(output.group, output.reduce_and_redistribute),
DeferredSum(output.group, output.reduce_to_dp_local),
)
elif isinstance(output, HandoffOutput):
elif isinstance(output, DeferredFinalize):
contribution = Contribution(None, update, output)
else:
contribution = Contribution(output, update)
@@ -207,7 +207,7 @@ class ResidualStream:
if self.pending is not None:
return self.pending.for_boundary(), self.residual
# An initialized, written stream needs read only. An uninitialized
# stream still uses the first stage's enter operation.
# stream still uses the first stage's init_residual.
return hidden, None
def complete(self, hidden):
@@ -219,17 +219,17 @@ class ResidualStream:
pending = self.pending
if pending is None:
return hidden.clone()
if not pending.update.adds_plainly:
if not pending.update.is_plain_add:
raise NotImplementedError("snapshot requires a plain residual update")
if pending.owed is None:
value = pending.value
elif isinstance(pending.owed, (CarriedSum, DeclaredSum)):
elif isinstance(pending.owed, (DeferredSum, DeclaredSum)):
value = pending.owed.complete(pending.value.clone())
else:
raise NotImplementedError("a finalize handoff requires main-output capture")
return value.clone() if self.residual is None else value + self.residual
def finish(self, hidden, *, takes_handoff=False, preserve_declared=False):
def export(self, hidden, *, takes_handoff=False, preserve_declared=False):
"""Export the output/residual pair without closing or consuming the stream.
Args:
@@ -248,6 +248,6 @@ class ResidualStream:
return hidden, None
if preserve_declared and isinstance(self.pending.owed, DeclaredSum):
return self.pending.value, self.residual
if takes_handoff and isinstance(self.pending.owed, HandoffOutput):
if takes_handoff and isinstance(self.pending.owed, DeferredFinalize):
return self.pending.owed, self.residual
return self.pending.complete(), self.residual
@@ -21,21 +21,21 @@ from sglang.srt.layers import layernorm_sp
from sglang.srt.layers.aux_hidden_states import AuxHiddenStateAccumulator
from sglang.srt.layers.layer_boundary.adapters import branch
from sglang.srt.layers.layer_boundary.adapters.lora import (
publish_attention,
publish_ffn,
publish_attn_lora_rows,
publish_ffn_lora_rows,
)
from sglang.srt.layers.layer_boundary.contracts import (
BatchVariant,
StageEntry,
EntryPath,
StageKind,
StageSteps,
StagePath,
)
from sglang.srt.layers.layer_boundary.ops import gather_attention_tp
from sglang.srt.layers.layer_boundary.ops import attn_tp_gather_input
from sglang.srt.layers.layer_boundary.residual.access import buffer, from_pp
from sglang.srt.layers.layer_boundary.residual.add_norm import (
ADD,
PLAIN_ADD,
)
from sglang.srt.layers.layer_boundary.residual.batch import current
from sglang.srt.layers.layer_boundary.residual.batch import stream_of
from sglang.srt.layers.layer_boundary.residual.stream import DeclaredSum, ResidualStream
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.runtime_context import get_forward
@@ -75,10 +75,10 @@ class StageBoundary:
return self.plan.norm
def entry(
self, forward_batch: ForwardBatch, steps: Optional[StageSteps] = None
) -> StageEntry:
self, forward_batch: ForwardBatch, steps: Optional[StagePath] = None
) -> EntryPath:
if steps is None:
steps = self.plan._batch_steps(forward_batch)
steps = self.plan.path_for(forward_batch)
return steps.entry
def _prepare(
@@ -86,7 +86,7 @@ class StageBoundary:
hidden_states,
stream: ResidualStream,
forward_batch: ForwardBatch,
steps: Optional[StageSteps] = None,
steps: Optional[StagePath] = None,
**call,
):
"""The stage's input and the residual, from the previous stage's output
@@ -96,10 +96,10 @@ class StageBoundary:
if (
stream.pending is None
and stream.residual is None
and entry.input_sum is not None
and entry.declared_sum is not None
):
hidden_states = stream.leave(
hidden_states, ADD, declared_sum=entry.input_sum
hidden_states = stream.record(
hidden_states, PLAIN_ADD, declared_sum=entry.declared_sum
)
if stream.pending is not None:
call["update"] = stream.pending.update
@@ -115,8 +115,8 @@ class StageBoundary:
hidden_states=hidden_states,
forward_batch=forward_batch,
)
if entry.handoff is not None:
hidden_states = entry.handoff(
if entry.attn_input_adapter is not None:
hidden_states = entry.attn_input_adapter(
hidden_states, forward_batch, self.plan.qkv_latent_func
)
stream.write(residual)
@@ -131,8 +131,8 @@ class StageBoundary:
return self.plan.incoming_residual_rows
@property
def input_on_attention_tp_slices(self):
return self.plan.input_on_attention_tp_slices
def input_on_attn_tp_slices(self):
return self.plan.input_on_attn_tp_slices
def prepare(self, hidden_states, forward_batch, *, cache=None, **call):
"""Finish the previous contribution and produce this stage's compute input.
@@ -143,9 +143,11 @@ class StageBoundary:
forward_batch: Batch owning the stream and selecting the prepared path.
cache: FFN-only NPU weight cache prefetched on the FFN input path.
**call: Attention-only read/adapter options: quant_format,
post_residual_addition, captured_last_layer_outputs and capture_output.
FFN stages do not accept these options. A capture callback is
called as capture_output(value, owned=bool): owned=True means
post_residual_addition, capture_gathered and capture. FFN
stages do not accept these options. capture is a callback on
the producer's rows; capture_gathered is a collector on the
attention's compute-input rows. A capture callback is
called as capture(value, owned=bool): owned=True means
value is fresh storage it may keep, and owned=False means it
must copy before retaining.
@@ -161,21 +163,21 @@ class StageBoundary:
else self._prepare_input
)
hidden_states, forward_batch.residual_stream = prepare(
hidden_states, current(forward_batch), forward_batch, **call
hidden_states, stream_of(forward_batch), forward_batch, **call
)
return hidden_states
def finish(self, hidden_states, forward_batch):
"""Hand this attention's actual contribution to the following stage."""
if self.kind is not StageKind.ATTENTION or not self.plan.direct_handoff:
if self.kind is not StageKind.ATTENTION or not self.plan.finishes_directly:
raise RuntimeError(
"use the stage exit scope for an FFN or single-stage mixer"
)
produced = self.plan.produced(forward_batch)
return current(forward_batch).leave(
return stream_of(forward_batch).record(
hidden_states,
produced.update,
declared_sum=produced.group if produced.always_leaves else None,
declared_sum=produced.group if produced.always_partial else None,
)
def exit(self, forward_batch):
@@ -191,10 +193,10 @@ class StageBoundary:
using the same decision rather than selecting a second path.
"""
result = (
self.plan.output.ffn_exit(forward_batch, stream=current(forward_batch))
self.plan.output.ffn_exit(forward_batch, stream=stream_of(forward_batch))
if self.kind is StageKind.FFN
else self.plan.output.mixer_exit(
forward_batch, stream=current(forward_batch)
forward_batch, stream=stream_of(forward_batch)
)
)
return result
@@ -216,18 +218,18 @@ class StageBoundary:
tensors,
residual_in_hidden=(
self.declaration.previous is not None
and self.declaration.previous.update.at_producer
and self.declaration.previous.update.applied_at_exit
),
allow_missing_residual=allow_missing_residual,
)
declared_sum = self.entry(forward_batch).input_sum
hidden_states, forward_batch.residual_stream = ResidualStream.arrive(
hidden_states, residual, ADD, declared_sum=declared_sum
declared_sum = self.entry(forward_batch).declared_sum
hidden_states, forward_batch.residual_stream = ResidualStream.from_handoff(
hidden_states, residual, PLAIN_ADD, declared_sum=declared_sum
)
return hidden_states
def snapshot(self, hidden_states, forward_batch):
return current(forward_batch).snapshot(hidden_states)
return stream_of(forward_batch).snapshot(hidden_states)
def capture_output(self, hidden_states, forward_batch, *, skip_empty=False):
"""Capture an output while preserving the caller's reduction timing.
@@ -242,7 +244,7 @@ class StageBoundary:
contribution; a declared sum is reduced only on the snapshot copy.
Always use updated_handle afterwards. Plain residual updates are required.
"""
stream = current(forward_batch)
stream = stream_of(forward_batch)
if skip_empty:
storage = buffer(hidden_states)
if storage is not None and storage.shape[0] == 0:
@@ -251,12 +253,12 @@ class StageBoundary:
hidden_states = stream.complete(hidden_states)
return hidden_states, stream.snapshot(hidden_states)
def postprocess(self, hidden_states, forward_batch):
def finish_complete_output(self, hidden_states, forward_batch):
"""Move an FFN output that compute already completed outside exit()
(the operation-scheduled TBO path) onto the rows the layer hands on;
it chooses no reduction step."""
return self.plan.output.postprocess_layer(
hidden_states, current(forward_batch), forward_batch
return self.plan.output.finish_complete_output(
hidden_states, stream_of(forward_batch), forward_batch
)
def branch_input(self, source, hidden_states, forward_batch):
@@ -264,7 +266,7 @@ class StageBoundary:
self.plan,
source.plan,
hidden_states,
current(forward_batch),
stream_of(forward_batch),
forward_batch,
)
forward_batch.residual_stream = stream
@@ -278,7 +280,7 @@ class StageBoundary:
self.plan,
contribution,
hidden_states,
current(forward_batch),
stream_of(forward_batch),
source.plan,
forward_batch,
)
@@ -288,9 +290,9 @@ class StageBoundary:
def _prepare_input(self, hidden_states, stream, forward_batch, **call):
plan = self.plan
if self.kind is StageKind.ATTENTION:
publish_attention(plan._publish_lora_layout)
publish_attn_lora_rows(plan._publish_lora_layout)
if (
plan._paths.get(BatchVariant.SEQUENCE_PARALLEL) is not None
plan.paths.get(BatchVariant.SEQUENCE_PARALLEL) is not None
and plan.enters_stack
):
get_forward().set(
@@ -299,7 +301,9 @@ class StageBoundary:
if get_forward().sp_active:
hidden_states = layernorm_sp.sp_entry_scatter(hidden_states)
else:
publish_ffn(plan._publish_lora_layout, self.entry(forward_batch).input_rows)
publish_ffn_lora_rows(
plan._publish_lora_layout, self.entry(forward_batch).input_rows
)
return self._prepare(hidden_states, stream, forward_batch, **call)
def _prepare_attention(
@@ -307,28 +311,28 @@ class StageBoundary:
hidden_states: torch.Tensor,
stream: ResidualStream,
forward_batch: ForwardBatch,
captured_last_layer_outputs: Optional[AuxHiddenStateAccumulator] = None,
capture_gathered: Optional[AuxHiddenStateAccumulator] = None,
post_residual_addition: Optional[torch.Tensor] = None,
quant_format: str = "",
capture_output: Optional[Callable] = None,
capture: Optional[Callable] = None,
):
# Aux consumers need a materialized output before the input norm.
# Complete communication here, preserving the existing add+norm kernel
# and its FP32 accumulation. Its residual result also supplies capture.
capture_before_read = capture_output is not None and (
capture_before_read = capture is not None and (
(stream.residual is None and stream.pending is None)
or post_residual_addition is not None
)
if capture_output is not None:
if capture is not None:
hidden_states = stream.complete(hidden_states)
if capture_before_read:
# Embeddings precede enter; HF deepstack capture precedes the
# extra addition. Neither is the residual returned by the read.
value, previous = stream.finish(hidden_states)
value, previous = stream.export(hidden_states)
if previous is None:
capture_output(value)
capture(value)
else:
capture_output(value + previous, owned=True)
capture(value + previous, owned=True)
hidden_states, stream = self._prepare_input(
hidden_states,
stream,
@@ -337,13 +341,13 @@ class StageBoundary:
post_residual_addition=post_residual_addition,
)
entry = self.entry(forward_batch)
if capture_output is not None and not capture_before_read:
if capture is not None and not capture_before_read:
value = stream.residual
move = entry.capture_move
if move is not None:
value = move(value, forward_batch=forward_batch)
keeps_input = entry.capture_preserves_residual
capture_output(
capture(
value,
owned=entry.capture_move_allocates
or (
@@ -352,7 +356,7 @@ class StageBoundary:
and keeps_input(value, forward_batch)
),
)
if captured_last_layer_outputs is not None:
if capture_gathered is not None:
residual_value = stream.residual
move = entry.input_move
gathered_last_layer_output = (
@@ -363,11 +367,11 @@ class StageBoundary:
forward_batch=forward_batch,
)
)
# Input gathers allocate fresh DP buffers (see gather_attention_tp).
# Input gathers allocate fresh DP buffers (see attn_tp_gather_input).
# Without a gather this is the mutable residual, so retention copies.
captured_last_layer_outputs.capture(
capture_gathered.capture(
gathered_last_layer_output,
owned=move is gather_attention_tp
owned=move is attn_tp_gather_input
or (
move is None
and entry.capture_preserves_residual is not None
@@ -1260,7 +1260,7 @@ class ForwardBatch(ForwardBatchDeepSeekMHAMixin):
def moe_num_token_non_padded(self) -> Optional[torch.Tensor]:
"""Bound for masking a sparse MoE's padded rows, or None when the MoE
input is a gathered buffer whose real rows are not a prefix of it."""
from sglang.srt.layers.layer_boundary import moe_cp_gathers_sparse_moe_input
from sglang.srt.layers.layer_boundary import batch_gathers_over_moe_cp
from sglang.srt.layers.moe.utils import is_moe_input_scattered_across_dp_ranks
if self.num_token_non_padded is None:
@@ -1269,7 +1269,7 @@ class ForwardBatch(ForwardBatchDeepSeekMHAMixin):
if is_moe_input_scattered_across_dp_ranks():
# a2a dispatch, FP4 all-gather and dwdp all route the local shard.
return self.num_token_non_padded
if moe_cp_gathers_sparse_moe_input(self):
if batch_gathers_over_moe_cp(self):
return None
# DSA / MLA CP all-gather across attention CP on a prefill, which leaves
# the real rows zigzag-permuted rather than in a prefix.
+7 -7
View File
@@ -41,7 +41,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -684,7 +684,7 @@ class BailingMoEBlock(nn.Module):
prefix=add_prefix("mlp", prefix),
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -704,12 +704,12 @@ class BailingMoEBlock(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -734,8 +734,8 @@ class BailingMoEBlock(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_output=capture_output,
capture_gathered=captured_last_layer_outputs,
capture=capture_output,
)
if hidden_states.shape[0] != 0:
@@ -847,7 +847,7 @@ class BailingMoEModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
@@ -830,11 +830,13 @@ class BailingMoELinearDecoderLayer(nn.Module):
(
declare_ffn(
sparse=is_moe_layer,
next_sparse=is_next_layer_moe_layer,
next_layer_sparse=is_next_layer_moe_layer,
),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=is_previous_moe_layer, next_sparse=is_moe_layer)
previous=declare_ffn(
sparse=is_previous_moe_layer, next_layer_sparse=is_moe_layer
)
if layer_id != 0
else None,
terminal=layer_id == (1 if is_nextn else config.num_hidden_layers) - 1,
@@ -1010,7 +1012,7 @@ class BailingMoELinearModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
@@ -183,7 +183,7 @@ class BailingMoEModelNextN(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.final_layernorm
)
+10 -8
View File
@@ -33,7 +33,7 @@ from sglang.srt.layers.dp_attention import is_dp_attention_enabled
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -1110,7 +1110,7 @@ class BailingMoELinearDecoderLayer(nn.Module):
is_next_layer_sparse = not (self.expert_num == 1) and (
self.layer_id + 1 >= config.first_k_dense_replace
)
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -1162,11 +1162,13 @@ class BailingMoELinearDecoderLayer(nn.Module):
(
declare_ffn(
sparse=is_moe_layer,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=is_previous_moe_layer, next_sparse=is_moe_layer)
previous=declare_ffn(
sparse=is_previous_moe_layer, next_layer_sparse=is_moe_layer
)
if layer_id != 0
else None,
terminal=layer_id == (1 if is_nextn else config.num_hidden_layers) - 1,
@@ -1183,7 +1185,7 @@ class BailingMoELinearDecoderLayer(nn.Module):
**kwargs,
) -> torch.Tensor:
hidden_states = self.attn_boundary.prepare(
hidden_states, forward_batch, capture_output=capture_output
hidden_states, forward_batch, capture=capture_output
)
if not forward_batch.forward_mode.is_idle():
@@ -1213,7 +1215,7 @@ class BailingMoELinearDecoderLayer(nn.Module):
with self.ffn_boundary.exit(forward_batch) as ffn_exit:
if not (
enable_moe_dense_fully_dp()
is_dense_ffn_fully_dp()
and (not self.is_layer_sparse)
and hidden_states.shape[0] == 0
):
@@ -1397,11 +1399,11 @@ class BailingMoELinearModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
capture_output=capture_output
capture=capture_output
if capture_aux and self.end_layer - 1 in self.layers_to_capture
else None,
)
+1 -1
View File
@@ -228,7 +228,7 @@ class DeepseekModelNextN(nn.Module):
)
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.shared_head.norm
)
+18 -19
View File
@@ -75,8 +75,8 @@ from sglang.srt.layers.flashinfer_comm_fusion import uses_cutedsl_ar_fusion
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
get_attn_tp_context,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.adapters.context_parallel import (
@@ -1112,10 +1112,10 @@ class DeepseekV2MoE(nn.Module):
# deferred_finalize excludes _shared_expert_tp1, so the shared add folds in.
assert shared_output is not None
from sglang.srt.layers.layer_boundary.fusions.cutedsl import (
MoeFinalizeHandoff,
MoeDeferredFinalize,
)
return MoeFinalizeHandoff.from_flashinfer(
return MoeDeferredFinalize.from_flashinfer(
final_hidden_states,
gated_shared_output=shared_output,
m=hidden_states.shape[0],
@@ -2294,7 +2294,7 @@ class DeepseekV2AttentionMLA(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
zero_allocator: BumpAllocator,
input_on_attention_tp_slices: bool = False,
input_on_attn_tp_slices: bool = False,
llama_4_scaling: Optional[torch.Tensor] = None,
prev_topk_indices: Optional[torch.Tensor] = None,
):
@@ -2303,7 +2303,7 @@ class DeepseekV2AttentionMLA(
hidden_states=hidden_states,
forward_batch=forward_batch,
zero_allocator=zero_allocator,
input_on_attention_tp_slices=input_on_attention_tp_slices,
input_on_attn_tp_slices=input_on_attn_tp_slices,
llama_4_scaling=llama_4_scaling,
prev_topk_indices=prev_topk_indices,
)
@@ -2315,7 +2315,7 @@ class DeepseekV2AttentionMLA(
hidden_states: torch.Tensor,
forward_batch: ForwardBatch,
zero_allocator: BumpAllocator,
input_on_attention_tp_slices: bool = False,
input_on_attn_tp_slices: bool = False,
llama_4_scaling: Optional[torch.Tensor] = None,
prev_topk_indices: Optional[torch.Tensor] = None,
):
@@ -2400,7 +2400,7 @@ class DeepseekV2AttentionMLA(
hidden_states,
forward_batch,
zero_allocator,
input_on_attention_tp_slices,
input_on_attn_tp_slices,
)
elif attn_forward_method == AttnForwardMethod.MLA_NPU:
inner_state = forward_mla_prepare_npu(
@@ -2409,7 +2409,7 @@ class DeepseekV2AttentionMLA(
hidden_states,
forward_batch,
zero_allocator,
input_on_attention_tp_slices,
input_on_attn_tp_slices,
)
elif attn_forward_method == AttnForwardMethod.DSA_NPU:
inner_state = forward_dsa_prepare_npu(
@@ -2418,7 +2418,7 @@ class DeepseekV2AttentionMLA(
hidden_states,
forward_batch,
zero_allocator,
input_on_attention_tp_slices,
input_on_attn_tp_slices,
prev_topk_indices,
)
else:
@@ -2599,7 +2599,7 @@ class DeepseekV2DecoderLayer(nn.Module):
is_nextn=is_nextn,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -2656,14 +2656,15 @@ class DeepseekV2DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=self._stage_next_sparse,
next_layer_sparse=self._stage_next_sparse,
output_transform=output,
),
post_attention_layernorm,
{"fusions": fusions},
),
previous=declare_ffn(
sparse=self._stage_previous_sparse, next_sparse=self.is_layer_sparse
sparse=self._stage_previous_sparse,
next_layer_sparse=self.is_layer_sparse,
)
if not self._stage_enters_stack
else None,
@@ -2726,7 +2727,7 @@ class DeepseekV2DecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
quant_format=self._resolve_gfx95_quant_format(),
)
@@ -2737,9 +2738,7 @@ class DeepseekV2DecoderLayer(nn.Module):
forward_batch=forward_batch,
zero_allocator=zero_allocator,
llama_4_scaling=llama_4_scaling,
input_on_attention_tp_slices=(
self.attn_boundary.input_on_attention_tp_slices
),
input_on_attn_tp_slices=(self.attn_boundary.input_on_attn_tp_slices),
prev_topk_indices=prev_topk_indices,
)
if isinstance(hidden_states, tuple):
@@ -2813,7 +2812,7 @@ class DeepseekV2DecoderLayer(nn.Module):
)
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -3158,7 +3157,7 @@ class DeepseekV2Model(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
@@ -3465,7 +3464,7 @@ def dsv2_flashinfer_moe_dual_stream_graph(
mlp_reduce_scatter=mlp_reduce_scatter,
flashinfer_trtllm_bypass=True,
lora_batch_layout=LoRABatchLayout.TP_GLOBAL,
# The op's Tensor schema cannot carry a MoeFinalizeHandoff.
# The op's Tensor schema cannot carry a MoeDeferredFinalize.
defer_moe_finalize=False,
):
return moe_fusion.forward_normal_dual_stream(hidden_states)
+4 -4
View File
@@ -100,8 +100,8 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.engram import Engram, EngramHasher, EngramLayout
from sglang.srt.layers.layer_boundary import get_attn_tp_context
from sglang.srt.layers.layer_boundary.adapters.context_parallel import (
dsa_cp_gather_hidden_states,
dsa_cp_reduce_scatter_hidden_states,
attn_cp_gather,
attn_cp_reduce_scatter,
)
from sglang.srt.layers.layernorm import RMSNorm
from sglang.srt.layers.linear import ColumnParallelLinear, RowParallelLinear
@@ -3819,7 +3819,7 @@ class DeepseekV4DecoderLayer(nn.Module):
if _use_cp:
moe_a2a_backend = get_moe_a2a_backend()
if moe_a2a_backend.is_none():
hidden_states = dsa_cp_gather_hidden_states(hidden_states)
hidden_states = attn_cp_gather(hidden_states)
else:
assert (
moe_a2a_backend.is_deepep()
@@ -3870,7 +3870,7 @@ class DeepseekV4DecoderLayer(nn.Module):
skip_shared_experts=_do_shared_local,
)
if _use_cp and get_moe_a2a_backend().is_none():
hidden_states = dsa_cp_reduce_scatter_hidden_states(hidden_states)
hidden_states = attn_cp_reduce_scatter(hidden_states)
elif _use_tp_moe_gather:
hidden_states, global_hidden_states = (
get_local_dp_buffer(get_parallel().tp_group),
@@ -61,7 +61,7 @@ from sglang.srt.layers.dp_attention import is_dp_attention_enabled
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -1553,7 +1553,7 @@ class Dots3DecoderLayer(nn.Module):
is_nextn=is_nextn,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -1577,12 +1577,12 @@ class Dots3DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1660,7 +1660,7 @@ class Dots3DecoderLayer(nn.Module):
def op_mlp(self, state):
hidden_states = state.pop("hidden_states_mlp_input")
if not (
enable_moe_dense_fully_dp()
is_dense_ffn_fully_dp()
and (not self.is_layer_sparse)
and hidden_states.shape[0] == 0
):
@@ -1671,7 +1671,7 @@ class Dots3DecoderLayer(nn.Module):
state.hidden_states_mlp_output = hidden_states
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -1800,7 +1800,7 @@ class Dots3Model(nn.Module):
return residual_batch.to_pp(hidden_states, forward_batch)
else:
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
@@ -122,7 +122,7 @@ class Dot3NoteModelNextN(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, head.shared_head.norm
)
return hidden_states
+2 -2
View File
@@ -26,7 +26,7 @@ from transformers.models.ernie4_5_moe.configuration_ernie4_5_moe import (
from sglang.srt.distributed import (
tensor_model_parallel_all_reduce,
)
from sglang.srt.layers.layer_boundary import enable_moe_dense_fully_dp
from sglang.srt.layers.layer_boundary import is_dense_ffn_fully_dp
from sglang.srt.layers.layernorm import RMSNorm
from sglang.srt.layers.logits_processor import LogitsProcessor
from sglang.srt.layers.moe.ep_moe.layer import get_moe_impl_class
@@ -198,7 +198,7 @@ class Ernie4DecoderLayer(nn.Module):
prefix=add_prefix("mlp", prefix),
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
+3 -3
View File
@@ -230,12 +230,12 @@ class FalconH1HybridAttentionDecoderLayer(nn.Module):
self.feed_forward.scale_output, before_reduce_scatter=True
),
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.pre_ff_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -442,7 +442,7 @@ class FalconH1Model(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.final_layernorm
)
+4 -4
View File
@@ -484,9 +484,7 @@ class GigaChat35DecoderLayer(deepseek_v2.DeepseekV2DecoderLayer):
hidden_states=hidden_states,
forward_batch=forward_batch,
zero_allocator=zero_allocator,
input_on_attention_tp_slices=(
self.attn_boundary.input_on_attention_tp_slices
),
input_on_attn_tp_slices=(self.attn_boundary.input_on_attn_tp_slices),
)
get_attn_tp_context().clear_attn_inputs()
@@ -586,7 +584,9 @@ class GigaChat35Model(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+1 -1
View File
@@ -122,7 +122,7 @@ class GigaChat35ModelNextN(nn.Module):
hidden_states_before_norm = residual_batch.snapshot(
hidden_states, forward_batch
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.shared_head.norm
)
+7 -7
View File
@@ -46,7 +46,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -847,7 +847,7 @@ class Glm4MoeDecoderLayer(nn.Module):
alt_stream=alt_stream,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -871,12 +871,12 @@ class Glm4MoeDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -946,7 +946,7 @@ class Glm4MoeDecoderLayer(nn.Module):
hidden_states,
forward_batch,
quant_format=self.attn_quant_format,
capture_output=capture_output,
capture=capture_output,
)
hidden_states = self.self_attn(
@@ -992,7 +992,7 @@ class Glm4MoeDecoderLayer(nn.Module):
)
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -1123,7 +1123,7 @@ class Glm4MoeModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
if len(aux_hidden_states) == 0:
+8 -10
View File
@@ -40,8 +40,8 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
get_attn_tp_context,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -560,7 +560,7 @@ class Glm4MoeLiteDecoderLayer(nn.Module):
is_nextn=is_nextn,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -590,12 +590,12 @@ class Glm4MoeLiteDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -637,7 +637,7 @@ class Glm4MoeLiteDecoderLayer(nn.Module):
hidden_states,
forward_batch,
quant_format=getattr(self, "_gfx95_quant_format", ""),
capture_output=capture_output,
capture=capture_output,
)
hidden_states = self.self_attn(
@@ -645,9 +645,7 @@ class Glm4MoeLiteDecoderLayer(nn.Module):
hidden_states=hidden_states,
forward_batch=forward_batch,
zero_allocator=zero_allocator,
input_on_attention_tp_slices=(
self.attn_boundary.input_on_attention_tp_slices
),
input_on_attn_tp_slices=(self.attn_boundary.input_on_attn_tp_slices),
)
if isinstance(hidden_states, tuple):
hidden_states = hidden_states[0]
@@ -694,7 +692,7 @@ class Glm4MoeLiteDecoderLayer(nn.Module):
)
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -830,7 +828,7 @@ class Glm4MoeLiteModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
@@ -123,7 +123,7 @@ class Glm4MoeLiteModelNextN(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.shared_head.norm
)
+1 -1
View File
@@ -107,7 +107,7 @@ class Glm4MoeModelNextN(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.shared_head.norm
)
+12 -16
View File
@@ -27,12 +27,12 @@ from sglang.srt.layers.attention import vision_utils
from sglang.srt.layers.attention.vision import VisionAttention
from sglang.srt.layers.aux_hidden_states import AuxHiddenStateList
from sglang.srt.layers.layer_boundary import (
PLAIN_RESIDUAL,
PLAIN_RESIDUAL_OPS,
MHCState,
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
get_attn_tp_context,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import access as residual_access
@@ -740,7 +740,7 @@ class Glm5NextDecoderLayer(nn.Module):
is_nextn=is_nextn,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -780,7 +780,7 @@ class Glm5NextDecoderLayer(nn.Module):
)
terminal = layer_id == (1 if is_nextn else config.num_hidden_layers) - 1
residual = PLAIN_RESIDUAL
residual = PLAIN_RESIDUAL_OPS
if self.config.mhc:
residual = MHCState(
hc_mult=config.hc_mult,
@@ -793,12 +793,10 @@ class Glm5NextDecoderLayer(nn.Module):
else None
),
is_last_layer=terminal,
).layer_residual()
).residual_ops()
self.attn_boundary, self.ffn_boundary = make_stages(
(
declare_attn(
read=residual.attention_read, update=residual.attention_update
),
declare_attn(read=residual.attn_readout, update=residual.attn_update),
self.input_layernorm,
{
"qkv_latent_func": self.self_attn.prepare_qkv_latent
@@ -809,15 +807,15 @@ class Glm5NextDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
read=residual.ffn_read,
next_layer_sparse=is_next_layer_sparse,
read=residual.ffn_readout,
update=residual.ffn_update,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse,
next_sparse=self.is_layer_sparse,
next_layer_sparse=self.is_layer_sparse,
update=residual.ffn_update,
)
if layer_id != 0
@@ -933,7 +931,7 @@ class Glm5NextDecoderLayer(nn.Module):
hidden_states_orig = residual_access.buffer(hidden_states)
hidden_states = self.attn_boundary.prepare(
hidden_states, forward_batch, capture_output=capture_output
hidden_states, forward_batch, capture=capture_output
)
hidden_states = self.self_attn(
@@ -941,9 +939,7 @@ class Glm5NextDecoderLayer(nn.Module):
hidden_states=hidden_states,
forward_batch=forward_batch,
zero_allocator=zero_allocator,
input_on_attention_tp_slices=(
self.attn_boundary.input_on_attention_tp_slices
),
input_on_attn_tp_slices=(self.attn_boundary.input_on_attn_tp_slices),
prev_topk_indices=prev_topk_indices,
)
if isinstance(hidden_states, tuple):
@@ -1195,7 +1191,7 @@ class Glm5NextModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
+5 -5
View File
@@ -604,12 +604,12 @@ class GptOssDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -624,7 +624,7 @@ class GptOssDecoderLayer(nn.Module):
capture_output=None,
) -> torch.Tensor:
hidden_states = self.attn_boundary.prepare(
hidden_states, forward_batch, capture_output=capture_output
hidden_states, forward_batch, capture=capture_output
)
if hidden_states.shape[0] != 0:
@@ -730,11 +730,11 @@ class GptOssModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
capture_output=aux_hidden_states.capture
capture=aux_hidden_states.capture
if self.end_layer in self.layers_to_capture
else None,
)
+15 -10
View File
@@ -21,7 +21,10 @@ from sglang.srt.layers.layer_boundary import (
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
from sglang.srt.layers.layer_boundary.residual.add_norm import Fp8Input, NormQuantRead
from sglang.srt.layers.layer_boundary.residual.add_norm import (
Fp8Input,
NormQuantReadout,
)
from sglang.srt.layers.layernorm import GemmaRMSNorm
from sglang.srt.layers.linear import (
QKVParallelLinear,
@@ -492,7 +495,7 @@ class InternS2MobiusLinearDecoderLayer(_InternS2MobiusDecoderMixin, nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(
declare_attn(
read=NormQuantRead(
read=NormQuantReadout(
fp8_input=Fp8Input.TUPLE_AND_BF16 if accepts_fp8_input else None
)
),
@@ -501,11 +504,11 @@ class InternS2MobiusLinearDecoderLayer(_InternS2MobiusDecoderMixin, nn.Module):
(
declare_ffn(
sparse=True,
next_sparse=True,
next_layer_sparse=True,
),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=True, next_sparse=True)
previous=declare_ffn(sparse=True, next_layer_sparse=True)
if layer_id != 0
else None,
terminal=layer_id == config.num_hidden_layers - 1,
@@ -521,7 +524,7 @@ class InternS2MobiusLinearDecoderLayer(_InternS2MobiusDecoderMixin, nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=kwargs.get("captured_last_layer_outputs"),
capture_gathered=kwargs.get("captured_last_layer_outputs"),
)
if not forward_batch.forward_mode.is_idle():
hidden_states = self.linear_attn(hidden_states, forward_batch)
@@ -624,7 +627,7 @@ class InternS2MobiusAttentionDecoderLayer(
self.attn_boundary, self.ffn_boundary = make_stages(
(
declare_attn(
read=NormQuantRead(
read=NormQuantReadout(
fp8_input=Fp8Input.TUPLE if accepts_fp8_input else None
)
),
@@ -633,11 +636,11 @@ class InternS2MobiusAttentionDecoderLayer(
(
declare_ffn(
sparse=True,
next_sparse=True,
next_layer_sparse=True,
),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=True, next_sparse=True)
previous=declare_ffn(sparse=True, next_layer_sparse=True)
if layer_id != 0
else None,
terminal=layer_id == config.num_hidden_layers - 1,
@@ -657,7 +660,7 @@ class InternS2MobiusAttentionDecoderLayer(
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
if not forward_batch.forward_mode.is_idle():
hidden_states = self.self_attention(
@@ -791,7 +794,9 @@ class InternS2MobiusForCausalLM(Qwen3_5ForCausalLM):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return (
hidden_states
if not aux_hidden_states
+5 -5
View File
@@ -462,12 +462,12 @@ class LagunaDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -482,7 +482,7 @@ class LagunaDecoderLayer(nn.Module):
capture_output=None,
) -> torch.Tensor:
hidden_states = self.attn_boundary.prepare(
hidden_states, forward_batch, capture_output=capture_output
hidden_states, forward_batch, capture=capture_output
)
if hidden_states.shape[0] != 0:
hidden_states = self.self_attn(
@@ -610,11 +610,11 @@ class LagunaModel(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
capture_output=aux_hidden_states.append
capture=aux_hidden_states.append
if self.end_layer in self.layers_to_capture
else None,
)
+5 -5
View File
@@ -37,7 +37,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -624,7 +624,7 @@ class LLaDA2MoeBlock(nn.Module):
prefix=add_prefix("mlp", prefix),
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -644,12 +644,12 @@ class LLaDA2MoeBlock(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -764,7 +764,7 @@ class LLaDA2MoeModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+9 -5
View File
@@ -432,11 +432,13 @@ class Llama4DecoderLayer(nn.Module):
(
declare_ffn(
sparse=is_moe_layer,
next_sparse=is_next_moe_layer,
next_layer_sparse=is_next_moe_layer,
),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=is_previous_moe_layer, next_sparse=is_moe_layer)
previous=declare_ffn(
sparse=is_previous_moe_layer, next_layer_sparse=is_moe_layer
)
if layer_id != 0
else None,
terminal=layer_id == config.num_hidden_layers - 1,
@@ -461,7 +463,7 @@ class Llama4DecoderLayer(nn.Module):
capture_output=None,
) -> torch.Tensor:
hidden_states = self.attn_boundary.prepare(
hidden_states, forward_batch, capture_output=capture_output
hidden_states, forward_batch, capture=capture_output
)
if hidden_states.shape[0] != 0:
@@ -538,7 +540,9 @@ class Llama4Model(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
if len(aux_hidden_states) == 0:
return hidden_states
@@ -578,7 +582,7 @@ class Llama4ForCausalLM(LlamaForCausalLM):
)
if end != self.model.config.num_hidden_layers:
return None
forward_batch.hidden_states = residual_batch.norm(
forward_batch.hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
return self.logits_processor(
+3 -3
View File
@@ -438,10 +438,10 @@ class LongcatFlashDecoderLayer(nn.Module):
{"qkv_latent_func": self.self_attn[0].prepare_qkv_latent},
),
(
declare_ffn(sparse=True, next_sparse=True),
declare_ffn(sparse=True, next_layer_sparse=True),
self.post_attention_layernorm[0],
),
previous=declare_ffn(sparse=True, next_sparse=True)
previous=declare_ffn(sparse=True, next_layer_sparse=True)
if self.layer_id != 0
else None,
terminal=self.layer_id == config.num_hidden_layers - 1,
@@ -642,7 +642,7 @@ class LongcatFlashModel(nn.Module):
topk_indices,
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm, skip_empty=True
)
@@ -168,7 +168,7 @@ class LongcatFlashDenseDecoderLayer(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(declare_attn(), self.input_layernorm),
(
declare_ffn(sparse=False, next_sparse=False),
declare_ffn(sparse=False, next_layer_sparse=False),
self.post_attention_layernorm,
),
previous=declare_ffn() if self.layer_id != 0 else None,
@@ -195,7 +195,9 @@ class LongcatFlashDenseDecoderLayer(nn.Module):
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)
hidden_states = self.ffn_boundary.postprocess(hidden_states, forward_batch)
hidden_states = self.ffn_boundary.finish_complete_output(
hidden_states, forward_batch
)
return hidden_states
@@ -275,7 +277,7 @@ class LongcatFlashModelNextN(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.final_layernorm
)
return hidden_states
+2 -2
View File
@@ -454,12 +454,12 @@ class MellumDecoderLayer(Qwen3MoeDecoderLayer):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
+7 -7
View File
@@ -38,7 +38,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -840,7 +840,7 @@ class MiMoV2DecoderLayer(nn.Module):
layer_id=layer_id,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -864,12 +864,12 @@ class MiMoV2DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -887,7 +887,7 @@ class MiMoV2DecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
if hidden_states.shape[0] != 0:
@@ -945,7 +945,7 @@ class MiMoV2DecoderLayer(nn.Module):
)
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -1092,7 +1092,7 @@ class MiMoV2Model(nn.Module):
hidden_states_before_norm = residual_batch.snapshot(
hidden_states, forward_batch
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
+5 -5
View File
@@ -27,7 +27,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -101,7 +101,7 @@ class MiMoV2MTPLayer(nn.Module):
is_previous_layer_sparse = True
is_next_layer_sparse = False
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -124,12 +124,12 @@ class MiMoV2MTPLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -235,7 +235,7 @@ class MiMoV2ModelNextN(nn.Module):
hidden_states_before_norm = residual_batch.snapshot(
hidden_states, forward_batch
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.final_layernorm
)
+7 -5
View File
@@ -988,12 +988,12 @@ class MiniMaxM2DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1011,7 +1011,7 @@ class MiniMaxM2DecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
if not forward_batch.forward_mode.is_idle():
hidden_states = self.self_attn(
@@ -1065,7 +1065,7 @@ class MiniMaxM2DecoderLayer(nn.Module):
def op_comm_postprocess_layer(self, state):
"""Communication postprocess for layer - TBO operation"""
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -1180,7 +1180,9 @@ class MiniMaxM2Model(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
if len(aux_hidden_states) == 0:
return hidden_states
+8 -6
View File
@@ -45,7 +45,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -1317,7 +1317,7 @@ class MiniMaxM3DecoderLayer(nn.Module):
prefix=add_prefix("mlp", prefix),
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -1359,12 +1359,12 @@ class MiniMaxM3DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1382,7 +1382,7 @@ class MiniMaxM3DecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
**kwargs,
)
@@ -1519,7 +1519,9 @@ class MiniMaxM3Model(nn.Module):
return residual_batch.to_pp(hidden_states, forward_batch)
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
if len(aux_hidden_states) == 0:
return hidden_states
+7 -3
View File
@@ -1020,7 +1020,7 @@ class MossVLSelfAttentionDecoderLayer(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(declare_attn(), self.input_layernorm),
(
declare_ffn(sparse=False, next_sparse=False),
declare_ffn(sparse=False, next_layer_sparse=False),
self.post_attention_layernorm,
),
previous=declare_ffn() if layer_id != 0 else None,
@@ -1120,7 +1120,9 @@ class MossVLTextModel(nn.Module):
positions=positions,
vision_position_ids=vision_position_ids,
)
hidden_states = residual_batch.written(hidden_states, forward_batch)
hidden_states = residual_batch.set_written(
hidden_states, forward_batch
)
elif isinstance(decoder_layer, MossVLSelfAttentionDecoderLayer):
hidden_states = decoder_layer(
positions=positions,
@@ -1130,7 +1132,9 @@ class MossVLTextModel(nn.Module):
else:
raise ValueError(f"Unknown decoder layer type {type(decoder_layer)}")
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+3 -1
View File
@@ -759,7 +759,9 @@ class NemotronHModel(nn.Module):
aux_hidden_states.append(
residual_batch.snapshot(hidden_states, forward_batch)
)
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm_f)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm_f
)
if aux_hidden_states:
return hidden_states, aux_hidden_states
return hidden_states
+4 -4
View File
@@ -105,7 +105,7 @@ class NemotronHMTPAttentionDecoderLayer(NemotronHAttentionDecoderLayer):
)
if self.has_start_projections:
hidden_states = residual_batch.written(hidden_states, forward_batch)
hidden_states = residual_batch.set_written(hidden_states, forward_batch)
hidden_states = super().forward(
hidden_states=hidden_states,
@@ -115,7 +115,7 @@ class NemotronHMTPAttentionDecoderLayer(NemotronHAttentionDecoderLayer):
if self.has_end_norm:
hidden_states = residual_batch.fold(hidden_states, forward_batch)
hidden_states = residual_batch.written(
hidden_states = residual_batch.set_written(
self.final_layernorm(hidden_states), forward_batch
)
@@ -187,7 +187,7 @@ class NemotronHMTPMoEDecoderLayer(NemotronHMoEDecoderLayer):
)
if self.has_start_projections:
hidden_states = residual_batch.written(hidden_states, forward_batch)
hidden_states = residual_batch.set_written(hidden_states, forward_batch)
hidden_states = super().forward(
hidden_states=hidden_states,
@@ -197,7 +197,7 @@ class NemotronHMTPMoEDecoderLayer(NemotronHMoEDecoderLayer):
if self.has_end_norm:
hidden_states = residual_batch.fold(hidden_states, forward_batch)
hidden_states = residual_batch.written(
hidden_states = residual_batch.set_written(
self.final_layernorm(hidden_states), forward_batch
)
+10 -7
View File
@@ -2,13 +2,16 @@
from sglang.srt.configs.nemotron_h import ATTENTION, MAMBA, MOE
from sglang.srt.layers.layer_boundary import (
HandoffRows,
ExitRows,
ProducerReduction,
declare_attn,
declare_ffn,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual.add_norm import NormQuantRead, NormRead
from sglang.srt.layers.layer_boundary.residual.add_norm import (
NormQuantReadout,
NormReadout,
)
from sglang.srt.layers.layernorm import RMSNorm
from sglang.srt.runtime_context import get_parallel
@@ -22,15 +25,15 @@ def is_attn_layer(layer_type: str) -> bool:
def _declaration(pattern: str, layer_idx: int):
if is_attn_layer(pattern[layer_idx]):
return declare_attn(
read=NormQuantRead(before_gather=True),
reduction=ProducerReduction.SCOPED,
gathers_tp_input=False,
read=NormQuantReadout(reads_before_dp_gather=True),
reduction=ProducerReduction.EXIT_SCOPED,
gathers_attn_tp_input=False,
)
return declare_ffn(
sparse=pattern[layer_idx] == MOE,
read=NormRead(before_gather=True),
read=NormReadout(reads_before_dp_gather=True),
dense_tp_size=get_parallel().tp_size if pattern[layer_idx] != MOE else None,
handoff_rows=HandoffRows.ATTENTION,
exit_rows=ExitRows.ATTENTION,
)
+2 -4
View File
@@ -28,7 +28,7 @@ from sglang.srt.distributed import (
from sglang.srt.layers.activation import SiluAndMul
from sglang.srt.layers.dp_attention import is_dp_attention_enabled
from sglang.srt.layers.layer_boundary.residual.access import (
finish_layer_stack,
export_output,
from_pp,
snapshot,
)
@@ -427,9 +427,7 @@ class Qwen2Model(nn.Module):
residual,
)
hidden_states, residual = finish_layer_stack(
hidden_states, residual, forward_batch
)
hidden_states, residual = export_output(hidden_states, residual, forward_batch)
if not self.pp_group.is_last_rank:
return PPProxyTensors(
{
+7 -7
View File
@@ -866,10 +866,10 @@ class Qwen2MoeSparseMoeBlock(nn.Module):
if shared_output is None:
raise RuntimeError("Qwen deferred finalize requires shared output")
from sglang.srt.layers.layer_boundary.fusions.cutedsl import (
MoeFinalizeHandoff,
MoeDeferredFinalize,
)
return MoeFinalizeHandoff.from_flashinfer(
return MoeDeferredFinalize.from_flashinfer(
final_hidden_states,
gated_shared_output=shared_output,
m=num_tokens,
@@ -1058,12 +1058,12 @@ class Qwen2MoeDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1082,7 +1082,7 @@ class Qwen2MoeDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
**kwargs,
)
@@ -1216,7 +1216,7 @@ class Qwen2MoeModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
@@ -1314,7 +1314,7 @@ class Qwen2MoeForCausalLM(nn.Module):
forward_batch.hidden_states, forward_batch
)
# norm
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
forward_batch.hidden_states = hidden_states
+6 -4
View File
@@ -379,7 +379,7 @@ class Qwen3DecoderLayer(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(declare_attn(), self.input_layernorm),
(
declare_ffn(sparse=False, next_sparse=False),
declare_ffn(sparse=False, next_layer_sparse=False),
self.post_attention_layernorm,
),
previous=declare_ffn() if layer_id != 0 else None,
@@ -399,7 +399,7 @@ class Qwen3DecoderLayer(nn.Module):
hidden_states,
forward_batch,
post_residual_addition=post_residual_addition,
capture_output=capture_output,
capture=capture_output,
)
if hidden_states.shape[0] != 0:
hidden_states = self.self_attn(
@@ -479,7 +479,9 @@ class Qwen3Model(Qwen2Model):
return residual_batch.to_pp(hidden_states, forward_batch)
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return (
(hidden_states, aux_hidden_states) if aux_hidden_states else hidden_states
)
@@ -607,7 +609,7 @@ class Qwen3ForCausalLM(nn.Module):
)
if end == self.model.config.num_hidden_layers:
forward_batch.hidden_states = residual_batch.norm(
forward_batch.hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
# logits process
+14 -11
View File
@@ -60,7 +60,10 @@ from sglang.srt.layers.layer_boundary import (
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
# Layers - Others
from sglang.srt.layers.layer_boundary.residual.add_norm import Fp8Input, NormQuantRead
from sglang.srt.layers.layer_boundary.residual.add_norm import (
Fp8Input,
NormQuantReadout,
)
from sglang.srt.layers.layernorm import GemmaRMSNorm
# Layers - Linear
@@ -1097,7 +1100,7 @@ class Qwen3_5LinearDecoderLayer(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(
declare_attn(
read=NormQuantRead(
read=NormQuantReadout(
fp8_input=Fp8Input.TUPLE_AND_BF16 if accepts_fp8_input else None
)
),
@@ -1109,13 +1112,13 @@ class Qwen3_5LinearDecoderLayer(nn.Module):
(
declare_ffn(
sparse=is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
{"fusions": boundary_fusions},
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=is_layer_sparse
)
if layer_id != 0
else None,
@@ -1132,7 +1135,7 @@ class Qwen3_5LinearDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=kwargs.get("captured_last_layer_outputs", None),
capture_gathered=kwargs.get("captured_last_layer_outputs", None),
)
# fused AR+quant hands down a (fp8, scale) / (bf16, fp8, scale) tuple
@@ -1303,7 +1306,7 @@ class Qwen3_5AttentionDecoderLayer(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(
declare_attn(
read=NormQuantRead(
read=NormQuantReadout(
fp8_input=Fp8Input.TUPLE if accepts_fp8_input else None
)
),
@@ -1315,13 +1318,13 @@ class Qwen3_5AttentionDecoderLayer(nn.Module):
(
declare_ffn(
sparse=is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
{"fusions": boundary_fusions},
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=is_layer_sparse
)
if layer_id != 0
else None,
@@ -1536,7 +1539,7 @@ class Qwen3_5AttentionDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
# fused AR+quant hands down a (fp8, scale) / (bf16, fp8, scale) tuple
@@ -1843,11 +1846,11 @@ class Qwen3_5ForCausalLM(nn.Module):
if not self.pp_group.is_last_rank:
return residual_batch.to_pp(hidden_states, forward_batch)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
handoff_norm=self.flashinfer_mnnvl_cutedsl_fusion,
finalize_norm=self.flashinfer_mnnvl_cutedsl_fusion,
skip_empty=True,
)
+6 -6
View File
@@ -871,12 +871,12 @@ class Qwen3MoeDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -896,8 +896,8 @@ class Qwen3MoeDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_output=capture_output,
capture_gathered=captured_last_layer_outputs,
capture=capture_output,
**kwargs,
)
@@ -945,7 +945,7 @@ class Qwen3MoeDecoderLayer(nn.Module):
)
def op_comm_postprocess_layer(self, state):
hidden_states = self.ffn_boundary.postprocess(
hidden_states = self.ffn_boundary.finish_complete_output(
state.pop("hidden_states_mlp_output"), state.forward_batch
)
@@ -1103,7 +1103,7 @@ class Qwen3MoeForCausalLM(nn.Module):
forward_batch.hidden_states, forward_batch
)
# norm
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
forward_batch.hidden_states = hidden_states
+9 -7
View File
@@ -542,12 +542,12 @@ class Qwen3HybridLinearDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -565,7 +565,7 @@ class Qwen3HybridLinearDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
if not forward_batch.forward_mode.is_idle():
@@ -710,12 +710,12 @@ class Qwen3HybridAttentionDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -835,7 +835,7 @@ class Qwen3HybridAttentionDecoderLayer(nn.Module):
hidden_states = self.attn_boundary.prepare(
hidden_states,
forward_batch,
captured_last_layer_outputs=captured_last_layer_outputs,
capture_gathered=captured_last_layer_outputs,
)
if not forward_batch.forward_mode.is_idle():
@@ -945,7 +945,9 @@ class Qwen3NextModel(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
if len(aux_hidden_states) == 0:
return hidden_states
+1 -1
View File
@@ -1269,7 +1269,7 @@ class Qwen3LLMModel(Qwen3Model):
return residual_batch.to_pp(hidden_states, forward_batch)
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
+1 -1
View File
@@ -159,7 +159,7 @@ class Qwen3MoeLLMModel(Qwen3MoeModel):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states,
forward_batch,
self.norm,
+10 -8
View File
@@ -25,7 +25,7 @@ from sglang.srt.layers.dp_attention import (
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -300,7 +300,7 @@ class SarvamMoESparseMoeBlock(nn.Module):
and config.num_shared_experts > 0
):
intermediate_size = config.moe_intermediate_size * config.num_shared_experts
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
shared_tp_rank, shared_tp_size = 0, 1
else:
shared_tp_rank, shared_tp_size = None, None
@@ -1028,7 +1028,7 @@ class SarvamMoEMLADecoderLayer(nn.Module):
alt_stream=alt_stream,
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -1059,12 +1059,12 @@ class SarvamMoEMLADecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1172,7 +1172,9 @@ class SarvamMLAModel(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
@@ -1275,7 +1277,7 @@ class SarvamMLAForCausalLM(nn.Module):
forward_batch.hidden_states = residual_batch.complete_output(
forward_batch.hidden_states, forward_batch
)
forward_batch.hidden_states = residual_batch.norm(
forward_batch.hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
return self.logits_processor(
@@ -1454,7 +1456,7 @@ class SarvamMoEForCausalLM(BailingMoEForCausalLM):
forward_batch.hidden_states = residual_batch.complete_output(
forward_batch.hidden_states, forward_batch
)
forward_batch.hidden_states = residual_batch.norm(
forward_batch.hidden_states = residual_batch.final_norm(
forward_batch.hidden_states, forward_batch, self.model.norm
)
+2 -2
View File
@@ -300,7 +300,7 @@ class SDARBlock(nn.Module):
(
declare_ffn(
sparse=False,
next_sparse=False,
next_layer_sparse=False,
),
self.post_attention_layernorm,
),
@@ -414,7 +414,7 @@ class SDARModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+5 -3
View File
@@ -360,10 +360,10 @@ class SDARMoeBlock(nn.Module):
self.attn_boundary, self.ffn_boundary = make_stages(
(declare_attn(), self.input_layernorm),
(
declare_ffn(sparse=True, next_sparse=True),
declare_ffn(sparse=True, next_layer_sparse=True),
self.post_attention_layernorm,
),
previous=declare_ffn(sparse=True, next_sparse=True)
previous=declare_ffn(sparse=True, next_layer_sparse=True)
if layer_id != 0
else None,
terminal=layer_id == config.num_hidden_layers - 1,
@@ -481,7 +481,9 @@ class SDARMoeModel(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if not forward_batch.forward_mode.is_idle():
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+6 -3
View File
@@ -379,12 +379,13 @@ class Step3TextDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=self.is_next_layer_sparse,
next_layer_sparse=self.is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=self.is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=self.is_previous_layer_sparse,
next_layer_sparse=self.is_layer_sparse,
)
if layer_id != 0
else None,
@@ -481,7 +482,9 @@ class Step3TextModel(nn.Module):
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(hidden_states, forward_batch, self.norm)
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states
+4 -3
View File
@@ -571,12 +571,13 @@ class Step3p5DecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_moe_layer,
next_sparse=self.is_next_layer_sparse,
next_layer_sparse=self.is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=self.is_previous_layer_sparse, next_sparse=self.is_moe_layer
sparse=self.is_previous_layer_sparse,
next_layer_sparse=self.is_moe_layer,
)
if not (0 if is_nextn else layer_id) == 0
else None,
@@ -721,7 +722,7 @@ class Step3p5Model(nn.Module):
hidden_states_before_norm = residual_batch.snapshot(
hidden_states, forward_batch
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
return hidden_states, hidden_states_before_norm
+1 -1
View File
@@ -123,7 +123,7 @@ class Step3p5AMultiTokenPredictor(nn.Module):
hidden_states_before_norm = residual_batch.snapshot(
hidden_states, forward_batch
)
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.shared_head.norm
)
+5 -5
View File
@@ -43,7 +43,7 @@ from sglang.srt.layers.dp_attention import is_dp_attention_enabled
from sglang.srt.layers.layer_boundary import (
declare_attn,
declare_ffn,
enable_moe_dense_fully_dp,
is_dense_ffn_fully_dp,
make_stages,
)
from sglang.srt.layers.layer_boundary.residual import batch as residual_batch
@@ -1512,7 +1512,7 @@ class XllmDecoderLayer(nn.Module):
prefix=add_prefix("mlp", prefix),
)
else:
if enable_moe_dense_fully_dp():
if is_dense_ffn_fully_dp():
mlp_tp_rank, mlp_tp_size = 0, 1
else:
mlp_tp_rank, mlp_tp_size = None, None
@@ -1533,12 +1533,12 @@ class XllmDecoderLayer(nn.Module):
(
declare_ffn(
sparse=self.is_layer_sparse,
next_sparse=is_next_layer_sparse,
next_layer_sparse=is_next_layer_sparse,
),
self.post_attention_layernorm,
),
previous=declare_ffn(
sparse=is_previous_layer_sparse, next_sparse=self.is_layer_sparse
sparse=is_previous_layer_sparse, next_layer_sparse=self.is_layer_sparse
)
if layer_id != 0
else None,
@@ -1648,7 +1648,7 @@ class XllmModel(nn.Module):
else:
hidden_states = residual_batch.complete_output(hidden_states, forward_batch)
if hidden_states.shape[0] != 0:
hidden_states = residual_batch.norm(
hidden_states = residual_batch.final_norm(
hidden_states, forward_batch, self.norm
)
+31 -33
View File
@@ -8,8 +8,8 @@ from sglang.srt.layers.layer_boundary.factories import (
declare_ffn,
make_stages,
)
from sglang.srt.layers.layer_boundary.ops import identity_output
from sglang.srt.layers.layer_boundary.residual.add_norm import PLAIN_RESIDUAL
from sglang.srt.layers.layer_boundary.ops import keep_output
from sglang.srt.layers.layer_boundary.residual.add_norm import PLAIN_RESIDUAL_OPS
from sglang.srt.layers.layer_boundary.stage import StageBoundary
@@ -21,8 +21,8 @@ def make_test_stages(
last=False,
sparse=False,
previous_sparse=False,
next_sparse=False,
residual=PLAIN_RESIDUAL,
next_layer_sparse=False,
residual=PLAIN_RESIDUAL_OPS,
output=None,
**options,
):
@@ -30,16 +30,14 @@ def make_test_stages(
None
if first
else declare_ffn(
sparse=previous_sparse, next_sparse=sparse, update=residual.ffn_update
sparse=previous_sparse, next_layer_sparse=sparse, update=residual.ffn_update
)
)
attention = declare_attn(
read=residual.attention_read, update=residual.attention_update
)
attention = declare_attn(read=residual.attn_readout, update=residual.attn_update)
ffn = declare_ffn(
sparse=sparse,
next_sparse=next_sparse,
read=residual.ffn_read,
next_layer_sparse=next_layer_sparse,
read=residual.ffn_readout,
update=residual.ffn_update,
output_transform=output,
)
@@ -63,8 +61,8 @@ def stub_plan():
plan.norm = None
plan.fusions = None
plan._publish_lora_layout = False
plan._fusion_rows = None
plan._paths = {}
plan._next_input_rows = None
plan.paths = {}
plan.enters_stack = False
return plan
@@ -83,29 +81,29 @@ def stub_stage(plan, kind):
def sp_region_steps():
"""Local SP rows with no owed sum, for tests of activation and exits."""
from sglang.srt.layers.layer_boundary import (
NORM_QUANT_READ,
EdgeDecl,
NORM_QUANT_READOUT,
EdgeContract,
EntryPath,
InputContract,
Layout,
StageEntry,
StageInput,
StageOutput,
StageSteps,
OutputContract,
StagePath,
TokenAxis,
make_boundary,
bind_entry,
)
from sglang.srt.layers.layer_boundary.prepare import _hand_qkv_hook_its_input
from sglang.srt.layers.layer_boundary.prepare import _attn_input_default
rows = Layout(frozenset({TokenAxis.ATTN_TP_SCATTER}))
output = StageOutput(rows)
rows = Layout(frozenset({TokenAxis.ATTN_TP}))
output = OutputContract(rows)
def entry(read, handoff=None):
selected = make_boundary(
EdgeDecl(output, StageInput(rows, read=read), rows, rows)
def entry(read, attn_input_adapter=None):
selected = bind_entry(
EdgeContract(output, InputContract(rows, read=read), rows, rows)
)
return StageEntry(selected.prepare, rows, handoff=handoff)
return EntryPath(selected.prepare, rows, attn_input_adapter=attn_input_adapter)
return StageSteps(
entry(NORM_QUANT_READ, _hand_qkv_hook_its_input), output, identity_output
return StagePath(
entry(NORM_QUANT_READOUT, _attn_input_default), output, keep_output
)
@@ -120,16 +118,16 @@ def prepare_attention(stage, hidden, residual, forward_batch, *args, **call):
def prepare_raw(stage, method, hidden, residual, forward_batch, *args, **call):
from sglang.srt.layers.layer_boundary.residual.add_norm import ADD
from sglang.srt.layers.layer_boundary.residual.add_norm import PLAIN_ADD
from sglang.srt.layers.layer_boundary.residual.stream import ResidualStream
if not isinstance(residual, ResidualStream):
stream = ResidualStream(residual)
if residual is not None:
hidden = stream.leave(
hidden = stream.record(
hidden,
call.get("update", ADD),
declared_sum=stage.entry(forward_batch).input_sum,
call.get("update", PLAIN_ADD),
declared_sum=stage.entry(forward_batch).declared_sum,
)
else:
stream = residual
@@ -155,7 +153,7 @@ def postprocess_output(boundary, hidden, residual, forward_batch):
stream = (
residual if isinstance(residual, ResidualStream) else ResidualStream(residual)
)
hidden = boundary.postprocess_layer(hidden, stream, forward_batch)
hidden = boundary.finish_complete_output(hidden, stream, forward_batch)
if isinstance(residual, ResidualStream):
return hidden, stream
return (hidden, None) if stream.pending is None else stream.input(hidden)