Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
0da6147
fix(bcg): copy Qwen3-VL input_deepstack_embeds into a stable replay slot
bowenwan6 Aug 5, 2026
58a978b
test(bcg): unit tests for DeepStack BCG replay-slot contract
bowenwan6 Aug 5, 2026
29db2fe
refactor(bcg): shrink DeepStack replay-slot patch after adversarial r…
bowenwan6 Aug 5, 2026
a8197da
style(bcg): apply black auto-formatting for DeepStack replay-slot patch
bowenwan6 Aug 5, 2026
b1fd27a
refactor(bcg): trim DeepStack replay comments, warn on slot mismatch
JustinTong0323 Aug 6, 2026
4b6af41
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Aug 7, 2026
9de2ca7
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Aug 11, 2026
85275c5
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Aug 13, 2026
f2596d5
fix(bcg): fail closed on malformed DeepStack replay input
bowenwan6 Aug 15, 2026
ecf3edb
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Aug 15, 2026
7ffa726
test(bcg): prune DeepStack replay slot tests to what the code pins
JustinTong0323 Aug 15, 2026
ec15d8d
style(bcg): trim DeepStack replay slot comments
JustinTong0323 Aug 15, 2026
5f56637
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Aug 15, 2026
a687f92
feat(bcg): allowlist Qwen3-VL for breakable prefill CUDA graph
JustinTong0323 Aug 15, 2026
639cef9
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Aug 16, 2026
800e907
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Aug 17, 2026
8d0e460
Merge remote-tracking branch 'upstream/main' into fix/bcg-deepstack-r…
JustinTong0323 Aug 19, 2026
72b3fba
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Aug 24, 2026
74234e4
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Aug 25, 2026
c31e6fe
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Aug 29, 2026
d1cd8c5
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Sep 2, 2026
32dbab0
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Sep 3, 2026
2fc7119
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Sep 8, 2026
e605c74
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 5, 2026
c65396e
test(bcg): scope the MTP draft replay stub to the input_embeds slot
bowenwan6 Oct 5, 2026
6f1b06f
style(bcg): apply ruff-format to DeepStack replay-slot tests
bowenwan6 Oct 5, 2026
0d2e0a2
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 5, 2026
533bbb9
fix(bcg): gate DeepStack slot to eager-tail backends, harden refresh …
JustinTong0323 Oct 9, 2026
6fc13d5
Merge remote-tracking branch 'upstream/main' into fix/bcg-deepstack-r…
JustinTong0323 Oct 9, 2026
ce3127e
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 9, 2026
4d7d9cc
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 11, 2026
5e4322f
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 12, 2026
d73b050
refactor(bcg): declare DeepStack replay support through a protocol
bowenwan6 Oct 13, 2026
841be30
test(bcg): import the model classes at module scope
bowenwan6 Oct 13, 2026
6fcaecd
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 16, 2026
b58855b
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 17, 2026
ccfda8d
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Oct 17, 2026
920874d
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Oct 21, 2026
e943a3b
test(bcg): set is_dsv41_model on the replay-slot test runner
bowenwan6 Oct 17, 2026
8364aa2
Merge branch 'main' into fix/bcg-deepstack-replay-slot
bowenwan6 Nov 7, 2026
09685ed
Merge branch 'main' into fix/bcg-deepstack-replay-slot
JustinTong0323 Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions python/sglang/srt/model_executor/cuda_graph_buffer_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,6 +806,7 @@ def build_prefill_registry(
is_multimodal: bool = False,
hidden_size: int = 0,
embed_dtype: Optional[torch.dtype] = None,
deepstack_replay_width: int = 0,
enable_mamba_track: bool = False,
enable_num_token_non_padded: bool = False,
require_gathered_buffer: bool = False,
Expand Down Expand Up @@ -894,6 +895,17 @@ def _bs(bs: int, _mt: int) -> Tuple[int, ...]:
copy_from_fb=False,
)
)
if deepstack_replay_width > 0:
slots.append(
GraphSlot(
"input_deepstack_embeds",
lambda _bs2, mt: (mt, deepstack_replay_width),
embed_dtype,
axis="tokens",
padding_policy=PaddingPolicy.ZERO,
copy_from_fb=False,
)
)
if enable_mamba_track:
slots.append(GraphSlot("mamba_track_indices", _bs, torch.int64, axis="bs"))
slots.append(GraphSlot("mamba_track_mask", _bs, torch.bool, axis="bs"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,13 @@ def __init__(self, model_runner: ModelRunner):

self.mamba_track_enabled = self._is_mamba_track_enabled()

deepstack_replay_width = (
self.model_runner.model_config.hidden_size
* getattr(self.model_runner.model, "num_deepstack_embeddings", 0)
if getattr(self.model_runner.model, "supports_bcg_deepstack_replay", False)
else 0
)

# --- buffers ---------------------------------------------------
self.buffers: PrefillInputBuffers = PrefillInputBuffers.create(
device=self.device,
Expand All @@ -307,6 +314,7 @@ def __init__(self, model_runner: ModelRunner):
hidden_size=self.model_runner.model_config.hidden_size,
dtype=self.model_runner.dtype,
enable_mamba_track=self.mamba_track_enabled,
deepstack_replay_width=deepstack_replay_width,
)
self.buffers.share_buffers()
# Token-axis FB-shared slot registry adopting PrefillInputBuffers
Expand All @@ -320,6 +328,7 @@ def __init__(self, model_runner: ModelRunner):
is_multimodal=self.is_multimodal,
hidden_size=self.model_runner.model_config.hidden_size,
embed_dtype=self.model_runner.dtype,
deepstack_replay_width=deepstack_replay_width,
enable_mamba_track=self.mamba_track_enabled,
enable_num_token_non_padded=enable_num_token_non_padded(),
require_gathered_buffer=require_gathered_buffer(model_runner.server_args),
Expand Down Expand Up @@ -667,11 +676,19 @@ def _run_forward(self, forward_batch: ForwardBatch, num_tokens: int):
if self._uses_eager_prefill_tail():
# BCG / Full: capture the transformer body only.
positions = self._get_layer_model_positions(forward_batch)
extra_kwargs = {}
if self.buffer_registry.has_slot("input_deepstack_embeds"):
extra_kwargs["input_deepstack_embeds"] = (
self.buffer_registry.get_slot(
"input_deepstack_embeds"
).slice_for(1, num_tokens)
)
return self.layer_model.forward(
forward_batch.input_ids,
positions,
forward_batch,
forward_batch.input_embeds,
**extra_kwargs,
)
# tc_piecewise: compile/capture the outer model.forward path.
return self.model_runner.model.forward(
Expand Down Expand Up @@ -1637,6 +1654,39 @@ def replay_layer_forward(*args, **layer_kwargs):
self.buffer_registry.get_slot("input_embeds").slice_for(
1, static_num_tokens
)[: ie.shape[0]].copy_(ie)
# DeepStack replay slot: same lifecycle as ``input_embeds``
# above. The else branch zeros the slice so a stale image
# contribution cannot bleed into a text-only or smaller
# request that reuses this bucket — the LM applies the
# slot via ``add_`` (not through attention), so unmasked
# padded rows would corrupt real tokens otherwise.
if self.buffer_registry.has_slot("input_deepstack_embeds"):
slot = self.buffer_registry.get_slot(
"input_deepstack_embeds"
).slice_for(1, static_num_tokens)
de = layer_kwargs.get("input_deepstack_embeds")
if (
de is not None
and de.numel() > 0
and de.shape[0] <= static_num_tokens
and de.shape[1:] == slot.shape[1:]
and de.dtype == slot.dtype
and de.device == slot.device
):
slot[: de.shape[0]].copy_(de)
if de.shape[0] < static_num_tokens:
slot[de.shape[0] :].zero_()
else:
if de is not None:
logger.warning(
"DeepStack replay slot rejected a non-empty "
"input_deepstack_embeds (shape=%s, dtype=%s, device=%s); "
"replaying with zero contribution.",
tuple(de.shape),
de.dtype,
de.device,
)
slot.zero_()
hs = self.backend.replay(shape_key, static_forward_batch, **kwargs)
return _slice_output_rows(hs, raw_num_tokens) if full_path else hs

Expand Down
10 changes: 10 additions & 0 deletions python/sglang/srt/model_executor/runner_utils/buffers.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ class PrefillInputBuffers(ForwardInputBuffers):
positions: torch.Tensor
input_embeds: Optional[torch.Tensor]
mrope_positions: Optional[torch.Tensor]
input_deepstack_embeds: Optional[torch.Tensor]

@classmethod
def create(
Expand All @@ -355,6 +356,7 @@ def create(
hidden_size: int,
dtype: torch.dtype,
enable_mamba_track: bool,
deepstack_replay_width: int = 0,
) -> PrefillInputBuffers:
with torch.device(device):
input_ids = torch.zeros((max_num_tokens,), dtype=torch.int64)
Expand All @@ -378,9 +380,16 @@ def create(
if is_multimodal:
input_embeds = torch.zeros((max_num_tokens, hidden_size), dtype=dtype)
mrope_positions = torch.zeros((3, max_num_tokens), dtype=torch.int64)
if deepstack_replay_width > 0:
input_deepstack_embeds = torch.zeros(
(max_num_tokens, deepstack_replay_width), dtype=dtype
)
else:
input_deepstack_embeds = None
else:
input_embeds = None
mrope_positions = None
input_deepstack_embeds = None

return cls(
input_ids=input_ids,
Expand All @@ -392,6 +401,7 @@ def create(
positions=positions,
input_embeds=input_embeds,
mrope_positions=mrope_positions,
input_deepstack_embeds=input_deepstack_embeds,
)

def populate_from_forward_batch(
Expand Down
5 changes: 5 additions & 0 deletions python/sglang/srt/models/qwen3_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,11 @@ def forward(


class Qwen3VLForConditionalGeneration(nn.Module):
# Opt in to the optional BCG DeepStack replay slot (see
# PrefillCudaGraphRunner). Runtime activation additionally
# requires ``num_deepstack_embeddings > 0`` on the instance.
supports_bcg_deepstack_replay = True

# To ensure correct weight loading and mapping.
hf_to_sglang_mapper = WeightsMapper(
orig_to_new_substr={
Expand Down
194 changes: 194 additions & 0 deletions test/registered/unit/model_executor/test_deepstack_replay_slot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
"""Unit tests for the optional DeepStack BCG replay slot.

Covers the three-site contract:

* ``build_prefill_registry`` registers an ``input_deepstack_embeds``
slot iff ``is_multimodal AND register_input_embeds AND
deepstack_replay_width > 0``.
* ``PrefillInputBuffers.create`` allocates the matching
``input_deepstack_embeds`` field iff both ``is_multimodal`` and
``deepstack_replay_width > 0`` hold.
* ``Qwen3VLForConditionalGeneration`` declares the explicit opt-in
class attribute ``supports_bcg_deepstack_replay = True`` and its
MoE subclass inherits it; ``Qwen2_5_VLForConditionalGeneration``
and text-only ``Qwen3ForCausalLM`` do not.

All tests are CPU-only — the registry / dataclass logic under test is
GPU-agnostic; ``torch.zeros`` on the ``cpu`` device is sufficient.
"""

import unittest

import torch

from sglang.srt.model_executor.cuda_graph_buffer_registry import (
build_prefill_registry,
)
from sglang.srt.model_executor.runner_utils.buffers import PrefillInputBuffers
from sglang.test.ci.ci_register import register_cpu_ci
from sglang.test.test_utils import CustomTestCase

register_cpu_ci(est_time=5, suite="base-a-test-cpu")


_DEVICE = torch.device("cpu")


def _reg(**overrides):
base = dict(
device=_DEVICE,
max_bs=1,
max_num_token=128,
cache_loc_dtype=torch.int32,
is_multimodal=True,
hidden_size=64,
embed_dtype=torch.bfloat16,
deepstack_replay_width=0,
)
base.update(overrides)
return build_prefill_registry(**base)


def _buffers(**overrides):
base = dict(
device=_DEVICE,
max_bs=1,
max_num_tokens=128,
cache_loc_dtype=torch.int32,
is_multimodal=True,
hidden_size=64,
dtype=torch.bfloat16,
enable_mamba_track=False,
deepstack_replay_width=0,
)
base.update(overrides)
return PrefillInputBuffers.create(**base)


class TestDeepStackReplaySlotRegistration(CustomTestCase):

def test_slot_absent_when_any_gate_is_off(self):
"""The DeepStack slot is registered only when all three gates
pass: is_multimodal, register_input_embeds, and
deepstack_replay_width > 0. Any missing gate → no slot."""
cases = [
dict(is_multimodal=False, deepstack_replay_width=192),
dict(is_multimodal=True, deepstack_replay_width=0),
dict(
is_multimodal=True,
deepstack_replay_width=192,
register_input_embeds=False,
),
]
for kwargs in cases:
with self.subTest(**kwargs):
reg = _reg(**kwargs)
self.assertFalse(reg.has_slot("input_deepstack_embeds"))

def test_slot_present_when_all_gates_pass(self):
reg = _reg(is_multimodal=True, deepstack_replay_width=192)
self.assertTrue(reg.has_slot("input_deepstack_embeds"))

def test_slot_shape_and_dtype_match_contract(self):
reg = _reg(
is_multimodal=True,
hidden_size=64,
embed_dtype=torch.bfloat16,
deepstack_replay_width=192,
)
buf = reg.get_slot("input_deepstack_embeds").buffer
self.assertEqual(buf.shape[-1], 192)
self.assertEqual(buf.dtype, torch.bfloat16)


class TestPrefillInputBuffersDeepStackField(CustomTestCase):

def test_buffer_none_when_width_zero(self):
buf = _buffers(is_multimodal=True, deepstack_replay_width=0)
self.assertIsNone(buf.input_deepstack_embeds)

def test_buffer_none_when_not_multimodal(self):
buf = _buffers(is_multimodal=False, deepstack_replay_width=192)
self.assertIsNone(buf.input_deepstack_embeds)

def test_buffer_allocated_when_multimodal_and_width_positive(self):
buf = _buffers(
is_multimodal=True,
hidden_size=64,
dtype=torch.bfloat16,
deepstack_replay_width=192,
max_num_tokens=128,
)
self.assertIsNotNone(buf.input_deepstack_embeds)
self.assertEqual(buf.input_deepstack_embeds.shape, (128, 192))
self.assertEqual(buf.input_deepstack_embeds.dtype, torch.bfloat16)

def test_buffer_field_backs_registry_adoption(self):
"""The registry uses ``getattr(source, slot.name, None)`` when
adopting; the buffer field must exist and be a tensor when the
slot is registered so adoption succeeds."""
buf = _buffers(is_multimodal=True, deepstack_replay_width=192)
reg = build_prefill_registry(
device=_DEVICE,
max_bs=1,
max_num_token=128,
cache_loc_dtype=torch.int32,
is_multimodal=True,
hidden_size=64,
embed_dtype=torch.bfloat16,
deepstack_replay_width=192,
source=buf,
)
adopted = reg.get_slot("input_deepstack_embeds").buffer
self.assertIs(adopted, buf.input_deepstack_embeds)


class TestQwen3VLCapabilityOptIn(CustomTestCase):

def test_qwen3vl_declares_capability(self):
from sglang.srt.models.qwen3_vl import Qwen3VLForConditionalGeneration

self.assertTrue(
getattr(
Qwen3VLForConditionalGeneration,
"supports_bcg_deepstack_replay",
False,
)
)

def test_qwen3vl_moe_inherits_capability(self):
from sglang.srt.models.qwen3_vl_moe import (
Qwen3VLMoeForConditionalGeneration,
)

self.assertTrue(
getattr(
Qwen3VLMoeForConditionalGeneration,
"supports_bcg_deepstack_replay",
False,
)
)

def test_qwen2_5_vl_does_not_declare_capability(self):
from sglang.srt.models.qwen2_5_vl import (
Qwen2_5_VLForConditionalGeneration,
)

self.assertFalse(
getattr(
Qwen2_5_VLForConditionalGeneration,
"supports_bcg_deepstack_replay",
False,
)
)

def test_text_only_qwen3_does_not_declare_capability(self):
from sglang.srt.models.qwen3 import Qwen3ForCausalLM

self.assertFalse(
getattr(Qwen3ForCausalLM, "supports_bcg_deepstack_replay", False)
)


if __name__ == "__main__":
unittest.main()
Loading