Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions deepspeed/module_inject/segment_ki.py
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,8 @@ def segki_refresh(model: torch.nn.Module) -> None:
redesigned cache scheme) is still under design; expect this entry
point to change.
"""
# Decode graphs that captured the dropped tensors key on this to recapture.
model._ki_refresh_generation = getattr(model, "_ki_refresh_generation", 0) + 1
op = None
for module in model.modules():
for attr in ("_ki_tp_cat_w", "_ki_attn_cat_w", "_ki_conv_w_local", "_ki_gates_cache"):
Expand Down
697 changes: 435 additions & 262 deletions deepspeed/runtime/rollout/hybrid_engine_rollout.py

Large diffs are not rendered by default.

14 changes: 10 additions & 4 deletions deepspeed/runtime/zero/linear.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ def _get_autocast_decorators():
def _is_autocast_enabled(device_type):
try:
return torch.is_autocast_enabled(device_type)
except TypeError:
legacy_getter = getattr(torch, f'is_autocast_{device_type}_enabled', None)
except (AttributeError, TypeError):
legacy_names = (("is_autocast_cuda_enabled", "is_autocast_gpu_enabled") if device_type == "cuda" else
(f"is_autocast_{device_type}_enabled", ))
legacy_getter = next(
(getattr(torch, name, None) for name in legacy_names if getattr(torch, name, None) is not None), None)
if legacy_getter is not None:
return legacy_getter()
return torch.is_autocast_enabled()
Expand All @@ -70,8 +73,11 @@ def _is_autocast_enabled(device_type):
def _get_autocast_dtype(device_type):
try:
return torch.get_autocast_dtype(device_type)
except TypeError:
legacy_getter = getattr(torch, f'get_autocast_{device_type}_dtype', None)
except (AttributeError, TypeError):
legacy_names = (("get_autocast_gpu_dtype", "get_autocast_cuda_dtype") if device_type == "cuda" else
(f"get_autocast_{device_type}_dtype", ))
legacy_getter = next(
(getattr(torch, name, None) for name in legacy_names if getattr(torch, name, None) is not None), None)
if legacy_getter is not None:
return legacy_getter()
return None
Expand Down
43 changes: 29 additions & 14 deletions docs/code-docs/source/inference-engine.rst
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,32 @@ forward. Results remain in the user-requested matrix order.
HybridEngine Rollout CUDA Graph Decode
--------------------------------------

``HybridEngineRolloutConfig(use_graph_capture=True)`` captures the decode
forward pass in a CUDA graph and replays it for every generated token. Only the
model forward is captured; the next token is chosen from the graph's output
logits after each replay. Greedy decoding (``temperature <= 0``) takes the
argmax. Sampling applies the ``temperature``, ``top_k`` and ``top_p`` settings
of ``SamplingConfig`` with Hugging Face's logits warpers, in the order
``generate()`` applies them, so both paths sample from the same distribution.
``HybridEngineRolloutConfig(use_graph_capture=True)`` captures one decode step
in a CUDA graph and replays it for every generated token. The step is the model
forward followed by the choice of the next token and the update of the decode
position, attention mask and output buffer, so a replay needs no host work. The
host checks for EOS every 16 steps and stops once every row has produced it.
Greedy decoding (``temperature <= 0``) takes the argmax. Sampling applies the
``temperature``, ``top_k`` and ``top_p`` settings of ``SamplingConfig`` with
Hugging Face's logits warpers, in the order ``generate()`` applies them, so both
paths sample from the same distribution.
Both greedy decoding and sampling first apply the repetition penalty from the
model's ``generation_config``, as ``generate()`` does. Other
``generation_config`` settings are not applied on the graph path. Continuous
batching, with or without graph capture, picks tokens the same way.

The captured graph and its static cache are reused by later ``generate()``
calls with the same batch size, prompt width plus ``max_new_tokens``, device,
dtype, parameter layout, training mode and autocast setting. The prompt is still
prefilled eagerly on every call, so one graph serves all prompt widths with the
same total length. In-place weight updates, such as an optimizer step, are
replayed without recapturing. The graph and cache stay allocated between
rollouts until the shape changes or ``rollout.shutdown()`` releases them.
Because the graph also selects the tokens, changing the sampling settings, the
repetition penalty or the EOS ids captures it again. With
``use_segki=True``, ``sync_weights()`` and ``refresh_weights()`` also release
them, because the injected kernels cache tensors derived from the weights.

Shared Prompt Prefill
---------------------

Expand Down Expand Up @@ -108,13 +122,14 @@ Scope and semantics

- **Throughput numbers** count executed decode steps (all rows step together);
tokens produced after a row's EOS are padded, so valid-token rates can be
lower at early EOS. Graph warm-up + capture happens per ``generate()`` call
(~1–1.5 s on a 4B model) and is excluded from decode-rate measurements.
- **Graph reuse**: a fresh graph is captured on every ``generate()`` call, so
weights updated by training between calls are picked up. Replaying one
captured graph across a training step (weight mutation without recapture)
is not supported — the capture reads current parameter memory, so stale
addresses could otherwise persist.
lower at early EOS. Graph warm-up + capture (~1–1.5 s on a 4B model) runs
on the first ``generate()`` call for a decode shape and is excluded from
decode-rate measurements.
- **Graph reuse**: later calls with the same decode shape replay the captured
graph. ``sync_weights()`` / ``refresh_weights()`` drop the derived weight
caches and release the graph, so the next call recaptures with the trained
weights. Updating weights without calling either of them is not supported
while segment kernels are enabled.
- **Packed (varlen) sequences**: the GDN conv/scan wrappers forward the
packed-sequence boundary markers (``seq_idx`` / ``cu_seqlens``) exactly as
the native forward does; packed *training* (gradients through the packed
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/module_inject/test_segment_ki_kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,48 @@ def test_inplace_update_refresh_matches_fresh_injection(self):
out_fresh), (f"refresh path diverged from fresh injection: "
f"{(out_refreshed != out_fresh).sum().item()} of {out_fresh.numel()} tokens differ")

@pytest.mark.parametrize("batch_size", [1, 2])
def test_graph_reused_until_refresh(self, batch_size, monkeypatch):
"""The decode graph is captured once per shape and replayed by later
rollouts; segki_refresh frees the derived tensors it captured, so the
next rollout must capture again."""
pytest.importorskip("transformers")
accelerator = get_accelerator()
if accelerator.device_name() == "cpu" or accelerator.create_graph() is None:
pytest.skip("requires graph capture")
try:
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(_TEST_MODEL)
except Exception as e:
pytest.skip(f"model {_TEST_MODEL} unavailable: {e}")
object.__setattr__(tok, "eos_token_id", -1)
torch.manual_seed(17)
ids = torch.randint(1000, 50000, (batch_size, 64), device=accelerator.device_name())

original_capture_to_graph = accelerator.capture_to_graph
capture_count = 0

def counted_capture_to_graph(*args, **kwargs):
nonlocal capture_count
capture_count += 1
return original_capture_to_graph(*args, **kwargs)

monkeypatch.setattr(accelerator, "capture_to_graph", counted_capture_to_graph)
rollout, m = self._make_rollout(tok)
first = self._gen(rollout, ids)
assert torch.equal(self._gen(rollout, ids), first)
assert capture_count == 1

from deepspeed.module_inject.segment_ki import segki_refresh
segki_refresh(m)
assert torch.equal(self._gen(rollout, ids), first)
assert capture_count == 2

rollout.refresh_weights()
assert torch.equal(self._gen(rollout, ids), first)
assert capture_count == 3
rollout.shutdown()

def test_glu_only_model_refresh_clears_backend_cat_cache(self):
"""GLU-only (dense) models carry the backend handle on _ki_dual_op;
segki_refresh must still reach the process-wide g_glu_cat_cache
Expand Down
46 changes: 44 additions & 2 deletions tests/unit/runtime/rollout/test_hybrid_engine_rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from deepspeed.ops.transformer.inference.op_binding.workspace import WorkspaceOp
from deepspeed.runtime.hybrid_engine import DeepSpeedHybridEngine
from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig
from deepspeed.runtime.zero.linear import _get_autocast_dtype, _is_autocast_enabled
from deepspeed.runtime.rollout.hybrid_engine_rollout import (
GlobalWorkRemaining,
HybridEngineRollout,
HybridEngineRolloutConfig,
_GlobalEosStoppingCriteria,
_disable_autocast_weight_cache,
)
from deepspeed.utils.static_cache import DeepSpeedStaticCache
from unit.common import DistributedTest
Expand All @@ -47,6 +49,33 @@ def _make_tokenizer():
return tok


def test_graph_signature_supports_legacy_autocast_getters(monkeypatch):

def legacy_enabled():
return True

monkeypatch.setattr(torch, "is_autocast_enabled", legacy_enabled)
monkeypatch.setattr(torch, "is_autocast_cuda_enabled", lambda: True, raising=False)
monkeypatch.delattr(torch, "get_autocast_dtype")
monkeypatch.setattr(torch, "get_autocast_gpu_dtype", lambda: torch.bfloat16, raising=False)

assert _is_autocast_enabled("cuda")
assert _get_autocast_dtype("cuda") is torch.bfloat16


def test_disable_autocast_weight_cache_restores_previous_setting(monkeypatch):
state = [True]
monkeypatch.setattr(torch, "is_autocast_cache_enabled", lambda: state[0], raising=False)
monkeypatch.setattr(torch,
"set_autocast_cache_enabled",
lambda enabled: state.__setitem__(0, enabled),
raising=False)

with _disable_autocast_weight_cache():
assert state[0] is False
assert state[0] is True


def _make_request():
return RolloutRequest(
prompt_ids=torch.tensor([[0, 1, 2], [0, 3, 4]]),
Expand Down Expand Up @@ -1623,6 +1652,7 @@ def test_sync_weights_drops_derived_caches():
engine.module = torch.nn.Identity()
engine.module._ki_tp_cat_w = object() # a derived-weight cache stand-in
rollout = HybridEngineRollout(engine, _make_tokenizer())
rollout.use_segki = True
rollout.sync_weights(step=0)
assert not hasattr(engine.module, "_ki_tp_cat_w")

Expand Down Expand Up @@ -1976,12 +2006,24 @@ def capture(_graph):
accelerator.current_stream.return_value = stream
accelerator.stream.side_effect = lambda _stream: nullcontext()
accelerator.capture_to_graph.side_effect = capture
accelerator.replay_graph.side_effect = lambda _graph: replay_views.append(
masked_columns(module.captured_masks[0]).clone())

def replay(decode_step):
replay_views.append(masked_columns(module.captured_masks[0]).clone())
decode_step()

accelerator.replay_graph.side_effect = replay

rollout = HybridEngineRollout(SimpleNamespace(module=module),
_make_tokenizer(),
cfg=HybridEngineRolloutConfig(use_graph_capture=True))
capture_static_graph = rollout._capture_static_graph

def capture_replayable_graph(module, state, decode_step, *args):
capture_static_graph(module, state, decode_step, *args)
# A replay reruns the captured step, which also advances the mask for the next replay.
state.graph = decode_step

rollout._capture_static_graph = capture_replayable_graph
request = RolloutRequest(torch.tensor([[1, 3, 4], [5, 6, 7]]), prompt_attention)
batch = rollout.generate(request, SamplingConfig(max_new_tokens=max_new_tokens, temperature=0))

Expand Down
Loading
Loading