Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 34 additions & 17 deletions python/sglang/srt/layers/attention/flashattention_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
prepare_swa_spec_page_table_triton,
)
from sglang.srt.layers.attention.utils import assert_buffer_fits
from sglang.srt.layers.cp.base import get_cp_strategy
from sglang.srt.layers.radix_attention import AttentionType
from sglang.srt.layers.utils.cp_utils import (
cp_allgather_and_save_kv_cache,
Expand Down Expand Up @@ -811,18 +812,27 @@ def forward_extend(
elif is_cp_mode:
# Dense-MHA CP: k, v are still rank-local; backend
# all-gathers and writes to the per-rank pool.
cp_allgather_and_save_kv_cache(
forward_batch,
layer,
k,
v,
self.attn_cp_size,
swa_loc=(
self.forward_metadata.swa_out_cache_loc
if self.use_sliding_window_kv_pool
else None
),
swa_loc = (
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
self.forward_metadata.swa_out_cache_loc
if self.use_sliding_window_kv_pool
else None
)
cp_strategy = get_cp_strategy()
if cp_strategy is not None:
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
forward_batch.cp_swa_out_cache_loc = swa_loc
try:
cp_strategy.materialize_full_kv(forward_batch, layer, k, v)
finally:
forward_batch.cp_swa_out_cache_loc = None
else:
cp_allgather_and_save_kv_cache(
forward_batch,
layer,
k,
v,
self.attn_cp_size,
swa_loc=swa_loc,
)
else:
self.token_to_kv_pool.set_kv_buffer(
layer,
Expand Down Expand Up @@ -967,12 +977,19 @@ def _fa_cp_attn(
**kwargs,
)

result = cp_attn_forward_extend(
forward_batch,
q.contiguous().view(-1, layer.tp_q_head_num, layer.head_dim),
self.device,
_fa_cp_attn,
)
q_cp = q.contiguous().view(-1, layer.tp_q_head_num, layer.head_dim)
cp_strategy = get_cp_strategy()
if cp_strategy is not None:
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
result = cp_strategy.run_attention(
q_cp, forward_batch, self.device, _fa_cp_attn
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
)
else:
result = cp_attn_forward_extend(
forward_batch,
q_cp,
self.device,
_fa_cp_attn,
)
elif self.fa_skip_kv_cache:
# Embedding mode: skip KV cache read and use raw K/V tensors
# directly via flash_attn_varlen_func. The KV cache write is
Expand Down
8 changes: 6 additions & 2 deletions python/sglang/srt/layers/cp/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,22 @@ def _get_cp_strategy() -> Optional[ContextParallelStrategy]:

def get_cp_strategy() -> Optional[ContextParallelStrategy]:
"""Return the configured CP strategy for runtime dispatch."""
from sglang.srt.environ import envs
Comment thread
Fridge003 marked this conversation as resolved.
Resolved

if not envs.SGLANG_ENABLE_CP_V2.get():
return None
return _get_cp_strategy()


def get_cp_strategy_kind() -> ContextParallelStrategyKind:
strategy = _get_cp_strategy()
strategy = get_cp_strategy()
if strategy is None:
return ContextParallelStrategyKind.NONE
return strategy.kind


def is_cp_enabled() -> bool:
return _get_cp_strategy() is not None
return get_cp_strategy() is not None


def is_zigzag() -> bool:
Expand Down
85 changes: 84 additions & 1 deletion python/sglang/srt/layers/cp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@
# limitations under the License.
# ==============================================================================

"""Public import facade for context parallel strategy helpers."""
"""Public import facade and runtime helpers for context parallel strategies."""

from contextlib import contextmanager
from typing import Any, Dict, Optional

from sglang.srt.layers.cp.base import (
BaseContextParallelMetadata,
ContextParallelStrategy,
ContextParallelStrategyKind,
CPAttentionBackendKind,
get_cp_strategy,
)
from sglang.srt.layers.cp.interleave import (
InterleaveContextParallelMetadata,
Expand All @@ -30,6 +34,81 @@
ZigzagCPStrategy,
)

Comment thread
Fridge003 marked this conversation as resolved.
Resolved

def maybe_prepare_cp_forward(forward_batch) -> None:
"""Build CP-v2 metadata for a prefill batch when the strategy can apply."""
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
strategy = get_cp_strategy()
if strategy is None:
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
return

input_ids = getattr(forward_batch, "input_ids", None)
if input_ids is None:
return

num_tokens = len(input_ids)
if not strategy.can_apply(num_tokens, forward_batch):
return

Comment thread
Fridge003 marked this conversation as resolved.
Resolved
seq_lens_cpu = _to_int_list(getattr(forward_batch, "seq_lens_cpu", None))
extend_lens_cpu = _to_int_list(getattr(forward_batch, "extend_seq_lens_cpu", None))
forward_batch.attn_cp_metadata = strategy.build_metadata(
num_tokens=num_tokens,
seqs_len=seq_lens_cpu,
extend_seqs_len=extend_lens_cpu,
)
forward_batch.cp_v2_active = True
Comment thread
Fridge003 marked this conversation as resolved.
Resolved


def maybe_cp_split_before_forward(
model: Any,
forward_batch,
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
kwargs: Dict[str, Any],
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
) -> Optional[Any]:
"""Shard embeddings and positions for CP-v2 model-runner forwarding."""
strategy = get_cp_strategy()
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
if (
strategy is None
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
or getattr(forward_batch, "attn_cp_metadata", None) is None
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
or not getattr(forward_batch, "cp_v2_active", False)
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
):
return None

Comment thread
Fridge003 marked this conversation as resolved.
Resolved
input_embeds = kwargs.get("input_embeds")
if input_embeds is None:
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
embed_layer = model.get_input_embeddings()
input_embeds = embed_layer(forward_batch.input_ids)
kwargs["input_embeds"] = strategy.shard_hidden_states(input_embeds, forward_batch)
return strategy.shard_position_ids(forward_batch.positions, forward_batch)


@contextmanager
def disable_legacy_cp_during_cp_v2(forward_batch):
Comment thread
Fridge003 marked this conversation as resolved.
Resolved
"""Prevent model-local legacy CP hooks from double-sharding CP-v2 inputs."""
if not getattr(forward_batch, "cp_v2_active", False):
yield
return

from sglang.srt.server_args import get_global_server_args

server_args = get_global_server_args()
old_enable_prefill_context_parallel = server_args.enable_prefill_context_parallel
server_args.enable_prefill_context_parallel = False
try:
yield
finally:
server_args.enable_prefill_context_parallel = (
old_enable_prefill_context_parallel
)


def _to_int_list(values) -> Optional[list[int]]:
if values is None:
return None
if hasattr(values, "tolist"):
values = values.tolist()
return [int(x) for x in values]


__all__ = [
"BaseContextParallelMetadata",
"CPAttentionBackendKind",
Expand All @@ -40,4 +119,8 @@
"InterleaveContextParallelMetadata",
"ZigzagCPStrategy",
"ZigzagContextParallelMetadata",
"disable_legacy_cp_during_cp_v2",
"get_cp_strategy",
"maybe_cp_split_before_forward",
"maybe_prepare_cp_forward",
]
Loading
Loading