diff --git a/deepspeed/module_inject/segment_ki.py b/deepspeed/module_inject/segment_ki.py index b17f99e9b0e2..1b8062004b36 100644 --- a/deepspeed/module_inject/segment_ki.py +++ b/deepspeed/module_inject/segment_ki.py @@ -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"): diff --git a/deepspeed/runtime/rollout/hybrid_engine_rollout.py b/deepspeed/runtime/rollout/hybrid_engine_rollout.py index 5b60121ba88a..413393cc0783 100644 --- a/deepspeed/runtime/rollout/hybrid_engine_rollout.py +++ b/deepspeed/runtime/rollout/hybrid_engine_rollout.py @@ -18,6 +18,7 @@ import itertools import math import time +from contextlib import contextmanager from copy import copy from dataclasses import dataclass, replace from functools import lru_cache @@ -31,9 +32,24 @@ from deepspeed.runtime.rollout.base import RolloutBatch, RolloutEngine, RolloutRequest, SamplingConfig from deepspeed.runtime.rollout.continuous_batching import (ContinuousBatchRequest, ContinuousBatchScheduler, plan_prefill_buckets) +from deepspeed.runtime.zero.linear import _get_autocast_dtype, _is_autocast_enabled from deepspeed.utils import logger +@contextmanager +def _disable_autocast_weight_cache(): + cache_enabled = getattr(torch, "is_autocast_cache_enabled", None) + cache_setter = getattr(torch, "set_autocast_cache_enabled", None) + previous = cache_enabled() if cache_enabled is not None else None + if cache_setter is not None and previous: + cache_setter(False) + try: + yield + finally: + if cache_setter is not None and previous is not None: + cache_setter(previous) + + class _ForwardProfiler: """Measure top-level model forwards without synchronizing each call.""" @@ -164,6 +180,26 @@ class _ContinuousGraphState: static_logits: torch.Tensor +@dataclass +class _StaticGraphState: + signature: tuple + cache: object + # Hybrid models only: the HF prefill cache whose linear-attention slots the + # decode cache binds. Each call prefills into it, so the graph's GDN reads + # keep their captured addresses. + prefill_cache: object + write_position: torch.Tensor + static_input: torch.Tensor + static_attention: torch.Tensor + token_buffer: torch.Tensor + # Token positions the repetition penalty counts. + penalized_tokens: torch.Tensor + # Rows that have produced EOS. + finished: torch.Tensor + graph: object = None + step_kernel_mounted: bool = False + + class HybridEngineRollout(RolloutEngine): """Rollout engine using DeepSpeed hybrid engine. @@ -173,6 +209,9 @@ class HybridEngineRollout(RolloutEngine): cfg: Optional HybridEngineRolloutConfig. """ + # Decode steps between the graph path's EOS checks, each of which waits for the device. + _EOS_CHECK_INTERVAL = 16 + def __init__(self, engine, tokenizer, cfg=None): self.engine = engine self.tokenizer = tokenizer @@ -196,6 +235,7 @@ def __init__(self, engine, tokenizer, cfg=None): self.continuous_cache_capacity = getattr(cfg, 'continuous_cache_capacity', None) if cfg else None self._last_profile = None self._continuous_graph_state = None + self._static_graph_state = None self._last_continuous_stats = None self._generation_defaults = None @@ -210,19 +250,25 @@ def refresh_weights(self) -> None: Drops the injected forwards' derived-weight caches. The weights themselves are read live, so only the derived tensors go stale. - A retained continuous-batching graph captures those tensors' - addresses, so it is released here too (re-captured on the next + With segKI, the retained decode graphs capture those tensors' + addresses, so they are released here too (re-captured on the next rollout) -- replays would otherwise read freed memory. Interim cost: one re-capture per sync; remove when refresh refills the derived tensors in place and graphs survive by construction. + Without segKI the graphs read only the parameters, which an in-place + update keeps at their captured addresses, so they are kept. PROVISIONAL contract — see segki_refresh; the final weight-sync handshake is still under design. """ + if not self.use_segki: + return + from deepspeed.module_inject.segment_ki import segki_refresh - if self._continuous_graph_state is not None: + if self._continuous_graph_state is not None or self._static_graph_state is not None: get_accelerator().synchronize() self._continuous_graph_state = None + self._static_graph_state = None # Resolve through the engine like every other module access; unit # tests hand us SimpleNamespace(module=...) engines. module = getattr(self.engine, "module", None) or getattr(self, "module", None) @@ -869,8 +915,13 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b request_by_id[request_id] = request responses[request_id] = [] - state = self._get_continuous_graph_state(module, max_batch_size, max_cache_len, device, model_dtype, - DeepSpeedStaticCache) + state = self._get_continuous_graph_state(module, + max_batch_size, + max_cache_len, + device, + model_dtype, + DeepSpeedStaticCache, + capture=False) cache = state.cache static_input = state.static_input static_attention = state.static_attention @@ -937,6 +988,30 @@ def _generate_continuous_graph(self, original_request, requests, sampling, max_b generation_config=generation_config, ) next_tokens.update(admitted_tokens) + post_prefill_signature = self._graph_signature(module, max_batch_size, max_cache_len, device, + model_dtype) + needs_capture = graph is None or state.signature != post_prefill_signature + if self._group_needs_capture(needs_capture): + if graph is not None: + get_accelerator().synchronize() + state.signature = post_prefill_signature + state.graph = None + state.static_logits = None + # Capture at an unused cache position so prompt KV copied by + # this prefill is not overwritten by warmup or capture. + static_write_positions.fill_(max_cache_len - 1) + graph, static_logits = self._capture_continuous_graph( + module, + cache, + static_input, + static_causal_attention, + static_write_positions, + state.static_cache_position, + static_position_ids, + ) + static_write_positions.zero_() + state.graph = graph + state.static_logits = static_logits decode_ids = tuple(request_id for request_id in update.active_ids if request_id not in admitted_ids) static_input.zero_() @@ -1019,10 +1094,17 @@ def _validate_continuous_graph_options(self, prompt_len, sampling): and self.continuous_cache_capacity < prompt_len + sampling.max_new_tokens): raise ValueError("continuous_cache_capacity must fit the prompt and all generated tokens") - def _get_continuous_graph_state(self, module, max_batch_size, max_cache_len, device, model_dtype, cache_type): - signature = self._continuous_graph_signature(module, max_batch_size, max_cache_len, device, model_dtype) + def _get_continuous_graph_state(self, + module, + max_batch_size, + max_cache_len, + device, + model_dtype, + cache_type, + capture=True): + signature = self._graph_signature(module, max_batch_size, max_cache_len, device, model_dtype) state = self._continuous_graph_state - if state is None or state.signature != signature: + if self._group_needs_capture(state is None or state.signature != signature): # Free the stale cache and graph pool before allocating replacements. self._continuous_graph_state = None state = None @@ -1040,15 +1122,17 @@ def _get_continuous_graph_state(self, module, max_batch_size, max_cache_len, dev # validity is represented by static_attention, so a fixed upper bound # lets one captured graph serve requests at different decode lengths. static_cache_position = torch.tensor([max_cache_len - 1], dtype=torch.long, device=device) - graph, static_logits = self._capture_continuous_graph( - module, - cache, - static_input, - static_causal_attention, - static_write_positions, - static_cache_position, - static_position_ids, - ) + graph = static_logits = None + if capture: + graph, static_logits = self._capture_continuous_graph( + module, + cache, + static_input, + static_causal_attention, + static_write_positions, + static_cache_position, + static_position_ids, + ) state = _ContinuousGraphState( signature, cache, @@ -1071,19 +1155,44 @@ def _get_continuous_graph_state(self, module, max_batch_size, max_cache_len, dev state.static_write_positions.zero_() return state - @staticmethod - def _continuous_graph_signature(module, max_batch_size, max_cache_len, device, model_dtype): + def _graph_signature(self, module, max_batch_size, max_cache_len, device, model_dtype): # Replay reads parameters and buffers through the address and layout fixed # at capture, so in-place value updates need no recapture, but a moved or # re-laid-out tensor does. Prefill runs eagerly, so the prompt width only # matters through max_cache_len. tensor_signature = tuple((tensor.data_ptr(), tensor.device, tensor.dtype, tuple(tensor.shape), tensor.stride()) for tensor in itertools.chain(module.parameters(), module.buffers())) + module_modes = tuple(child.training for child in module.modules()) device_index = device.index if device_index is None and device.type == get_accelerator().device_name(): # torch.device("cuda") and torch.device("cuda", 0) name the same device. device_index = get_accelerator().current_device() - return (id(module), device.type, device_index, model_dtype, max_batch_size, max_cache_len, tensor_signature) + # Replay keeps the kernels of the mode it was captured in, e.g. dropout, + # and of the autocast precision active at capture. + autocast_enabled = _is_autocast_enabled(device.type) + autocast_dtype = _get_autocast_dtype(device.type) if autocast_enabled else None + # segki_refresh frees the injected kernels' derived-weight tensors, which + # a graph captured before it would still read. + segki_generation = getattr(module, "_ki_refresh_generation", 0) if self.use_segki else 0 + return (id(module), module.training, autocast_enabled, autocast_dtype, device.type, device_index, model_dtype, + max_batch_size, max_cache_len, segki_generation, module_modes, tensor_signature) + + def _group_needs_capture(self, local_needs_capture): + """Return whether any rank of the AutoTP group must capture again. + + Capture runs forwards that hold TP collectives, so a rank whose own + signature changed must not capture while its peers replay. + """ + autotp_size = getattr(self.engine, "autotp_size", None) + if not callable(autotp_size) or autotp_size() <= 1: + return local_needs_capture + from deepspeed.utils import groups + + flag = torch.tensor(int(local_needs_capture), + dtype=torch.int32, + device=get_accelerator().current_device_name()) + dist.all_reduce(flag, op=dist.ReduceOp.MAX, group=groups.get_tensor_model_parallel_group()) + return bool(flag.item()) @staticmethod def _update_static_causal_attention(static_attention, static_causal_attention): @@ -1110,11 +1219,23 @@ def _capture_continuous_graph(module, cache, static_input, static_attention, sta cache_position=static_cache_position, position_ids=static_position_ids, ) - warmup_stream = accelerator.Stream() - warmup_stream.wait_stream(accelerator.current_stream()) - with accelerator.stream(warmup_stream): - for _ in range(3): - module( + with _disable_autocast_weight_cache(): + warmup_stream = accelerator.Stream() + warmup_stream.wait_stream(accelerator.current_stream()) + with accelerator.stream(warmup_stream): + for _ in range(3): + module( + static_input, + attention_mask=static_attention, + past_key_values=cache, + use_cache=True, + cache_position=static_cache_position, + position_ids=static_position_ids, + ) + accelerator.current_stream().wait_stream(warmup_stream) + graph = accelerator.create_graph() + with accelerator.capture_to_graph(graph): + output = module( static_input, attention_mask=static_attention, past_key_values=cache, @@ -1122,17 +1243,6 @@ def _capture_continuous_graph(module, cache, static_input, static_attention, sta cache_position=static_cache_position, position_ids=static_position_ids, ) - accelerator.current_stream().wait_stream(warmup_stream) - graph = accelerator.create_graph() - with accelerator.capture_to_graph(graph): - output = module( - static_input, - attention_mask=static_attention, - past_key_values=cache, - use_cache=True, - cache_position=static_cache_position, - position_ids=static_position_ids, - ) finally: module._forward_pre_hooks.update(saved_pre) module._forward_hooks.update(saved_post) @@ -1788,9 +1898,13 @@ def _hf_sampling_kwargs(sampling): } def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, module, device, sampling): - """Decode with DeepSpeedStaticCache + graph capture, greedy or sampled per ``sampling``.""" + """Decode with DeepSpeedStaticCache + graph capture, greedy or sampled per ``sampling``. + + One replay runs a whole decode step: the forward, the choice of the next + token, and the update of the position, attention mask and output buffer. + """ from transformers import StaticCache - from deepspeed.utils.static_cache import DeepSpeedStaticCache + from deepspeed.utils.static_cache import DSStaticGDNSlot if getattr(module.config, "_attn_implementation", None) == "flash_attention_2": raise ValueError("graph capture does not support flash_attention_2") @@ -1798,102 +1912,285 @@ def _generate_graph(self, prompt_ids, prompt_attn, max_new_tokens, pad_token_id, batch_size = prompt_ids.shape[0] prompt_len = prompt_ids.shape[1] max_len = prompt_len + max_new_tokens - eos_token_id = self.tokenizer.eos_token_id model_dtype = next(module.parameters()).dtype select_next_tokens = self._token_selector(sampling) repetition_penalty = self._repetition_penalty(module) - output_ids = [prompt_ids] + eos_ids = self._eos_ids(device) - def next_tokens(logits): - if repetition_penalty != 1.0: - logits = self._apply_repetition_penalty(logits, torch.cat(output_ids, dim=1), repetition_penalty, - prompt_attn) - return select_next_tokens(logits) - - # --- Prefill with HF StaticCache (correct attention semantics) --- - prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, model_dtype) # Hybrid models take a per-type mask dict (GDN must see None; a 2D # mask corrupts its conv-state init); standard models take a tensor. is_hybrid = "linear_attention" in (getattr(getattr(module.config, "text_config", module.config), "layer_types", None) or []) - prefill_mask = {"full_attention": None, "linear_attention": None} if is_hybrid else prompt_attn - prefill_out = module( - prompt_ids, - attention_mask=prefill_mask, - past_key_values=prefill_cache, - use_cache=True, - # explicit position tensors: HF derives them from the cache - # otherwise, which D2H-syncs and aborts stream capture on some - # model/cache combinations (reproduced with LLaMA + StaticCache) - cache_position=torch.arange(prompt_len, device=device), - **self._last_logits_kwargs(module), - ) - next_token = next_tokens(prefill_out.logits[:, -1, :]) - - # --- Copy prefill KV into DeepSpeedStaticCache --- - # per-row positions: the batched step and decode-attention kernels - # advance one entry per sequence (a shared scalar would race) - write_pos = torch.full((batch_size, ), prompt_len, dtype=torch.long, device=device) - ds_cache = DeepSpeedStaticCache(module.config, max_cache_len=max_len) - ds_cache.set_write_position(write_pos) - # Trigger lazy init then copy real data. Hybrid models carry - # linear-attention (GDN) slots alongside KV slots; the GDN slots are - # bound by reference to the prefill cache's HF slot objects, whose - # state management is already cudagraph-safe by construction. - from deepspeed.utils.static_cache import DSStaticGDNSlot - # Infer each layer's local KV shape from prefill before graph capture. + # The b=1 step kernel picks the greedy token without a repetition penalty; + # every other decode setup picks it with PyTorch ops inside the graph. + use_step_kernel = batch_size == 1 and sampling.temperature <= 0.0 and repetition_penalty == 1.0 + state = self._get_static_graph_state(module, batch_size, max_len, device, model_dtype, is_hybrid, + use_step_kernel, sampling, repetition_penalty, eos_ids) + + def run_prefill(cache): + prefill_mask = {"full_attention": None, "linear_attention": None} if is_hybrid else prompt_attn + return module( + prompt_ids, + attention_mask=prefill_mask, + past_key_values=cache, + use_cache=True, + # explicit position tensors: HF derives them from the cache + # otherwise, which D2H-syncs and aborts stream capture on some + # model/cache combinations (reproduced with LLaMA + StaticCache) + cache_position=torch.arange(prompt_len, device=device), + **self._last_logits_kwargs(module), + ) + + # --- Prefill with HF StaticCache (correct attention semantics) --- + prefill_cache = state.prefill_cache + if prefill_cache is None: + prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, + model_dtype) + prefill_out = run_prefill(prefill_cache) + post_prefill_signature = self._static_graph_signature(module, batch_size, max_len, device, model_dtype, + use_step_kernel, sampling, repetition_penalty, eos_ids) + if self._group_needs_capture(state.signature != post_prefill_signature): + self._static_graph_state = None + prefill_out = None + prefill_cache = None + state = None + state = self._get_static_graph_state(module, batch_size, max_len, device, model_dtype, is_hybrid, + use_step_kernel, sampling, repetition_penalty, eos_ids) + prefill_cache = state.prefill_cache + if prefill_cache is None: + prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, + model_dtype) + prefill_out = run_prefill(prefill_cache) + prefill_logits = self._apply_repetition_penalty(prefill_out.logits[:, -1, :], prompt_ids, repetition_penalty, + prompt_attn) + next_token = select_next_tokens(prefill_logits) + if max_new_tokens == 1: + return torch.cat([prompt_ids, next_token], dim=1) + + # --- Copy prefill KV into the decode cache --- + # Linear-attention (GDN) slots are bound to the retained prefill cache's + # HF slot objects, whose state management is already cudagraph-safe by + # construction, so the prefill above already wrote their state. + ds_cache = state.cache for layer_idx in range(self._cache_layer_count(ds_cache)): ds_layer = ds_cache.layers[layer_idx] if isinstance(ds_layer, DSStaticGDNSlot): - ds_layer.bind(prefill_cache.layers[layer_idx]) continue hf_keys, hf_values = self._cache_layer_tensors(prefill_cache, layer_idx) - ds_layer = ds_cache.layers[layer_idx] if not ds_layer.is_initialized: + # Size each layer from the model's local (e.g. AutoTP-sharded) KV tensors. ds_layer.lazy_initialization(hf_keys, hf_values) ds_layer.keys[:, :, :prompt_len, :].copy_(hf_keys[:, :, :prompt_len, :]) ds_layer.values[:, :, :prompt_len, :].copy_(hf_values[:, :, :prompt_len, :]) - output_ids.append(next_token) - - # --- Static buffers for graph capture --- - static_token = torch.zeros(batch_size, 1, dtype=torch.long, device=device) - # Full-width static causal mask for the full-attention layers; revealed - # one position per decode step by in-place writes (graph-replay safe). - # GDN layers must receive None: their recurrence ignores attention masks - # and a non-None value corrupts the conv-state updates. - static_attn = torch.zeros(batch_size, max_len, dtype=torch.bool, device=device) - static_attn[:, :prompt_len] = prompt_attn.bool() - static_attn[:, prompt_len] = True - static_causal_attn = torch.zeros((batch_size, 1, 1, max_len), dtype=model_dtype, device=device) - self._update_static_causal_attention(static_attn, static_causal_attn) - - # Decode-step mask argument: the per-type dict for hybrid models, the - # plain 4-D tensor for standard full-attention ones. - decode_mask = ({ - "full_attention": static_causal_attn, - "linear_attention": None - } if is_hybrid else static_causal_attn) + # Prompt tokens the repetition penalty counts, as _apply_repetition_penalty does. + penalized_prompt = prompt_attn.bool() if self._repetition_penalty_ignores_padding() else True + + def load_decode_inputs(): + state.write_position.fill_(prompt_len) + state.static_input.copy_(next_token) + static_attn = state.static_attention + static_attn.zero_() + static_attn[:, :, :, :prompt_len] = prompt_attn.unsqueeze(1).unsqueeze(1).bool() + static_attn[:, :, :, prompt_len] = True + token_buffer = state.token_buffer + token_buffer.zero_() + token_buffer[:, :prompt_len] = prompt_ids + token_buffer[:, prompt_len] = next_token.view(-1) # first generated token per row + penalized = state.penalized_tokens + penalized.zero_() + penalized[:, :prompt_len] = penalized_prompt + penalized[:, prompt_len] = True + if eos_ids is None: + state.finished.zero_() + else: + state.finished.copy_((next_token == eos_ids).any(dim=-1)) + + load_decode_inputs() + if state.graph is None: + decode_step = self._static_decode_step(module, state, model_dtype, device, is_hybrid, use_step_kernel, + select_next_tokens, repetition_penalty, eos_ids) + self._capture_static_graph(module, state, decode_step, max_len, device, model_dtype) + # Warmup and capture may have advanced the decode inputs. + load_decode_inputs() + + # --- Decode loop: each replay picks the next token and advances the static state on the device --- + generated_len = prompt_len + 1 + for step in range(max_new_tokens - 1): + # Checking for EOS synchronizes with the device, so poll only periodically. + if eos_ids is not None and step % self._EOS_CHECK_INTERVAL == 0 and bool(state.finished.all()): + break + get_accelerator().replay_graph(state.graph) + generated_len += 1 + + output_len = generated_len + if eos_ids is not None and generated_len > prompt_len + 1 and bool(state.finished.all()): + # Like generate(), end at the step where the last row produced EOS; the + # periodic check may have replayed a few steps past it. The caller pads + # each row after its own first EOS. + response = state.token_buffer[:, prompt_len:generated_len] + first_eos = torch.isin(response, eos_ids).int().argmax(dim=1) + output_len = prompt_len + int(first_eos.max()) + 1 + return state.token_buffer[:, :output_len].clone() + + def _eos_ids(self, device): + eos_token_id = self.tokenizer.eos_token_id + if eos_token_id is None: + return None + return torch.as_tensor(eos_token_id, dtype=torch.long, device=device).flatten() + + @staticmethod + def _graph_repetition_penalty(logits, token_ids, penalized, repetition_penalty): + """Penalize the tokens of ``token_ids`` marked in ``penalized``, as ``_apply_repetition_penalty`` does. + + Columns not marked map to an extra vocabulary slot that is dropped, so the + ops keep fixed shapes and need no host synchronization. + """ + logits = logits.float() + vocab_size = logits.shape[-1] + present = torch.zeros((logits.shape[0], vocab_size + 1), dtype=torch.bool, device=logits.device) + present.scatter_(1, torch.where(penalized, token_ids, vocab_size), True) + scores = torch.where(logits < 0, logits * repetition_penalty, logits / repetition_penalty) + return torch.where(present[:, :vocab_size], scores, logits) + + def _get_static_graph_state(self, module, batch_size, max_len, device, model_dtype, is_hybrid, use_step_kernel, + sampling, repetition_penalty, eos_ids): + """Return the fixed-batch decode state for this shape and decoding setup, reset for a new prompt. + + A new state, allocated when the signature changes, has no graph yet: the + caller prefills, loads the prompt and then captures. + """ + from transformers import StaticCache + from deepspeed.utils.static_cache import DeepSpeedStaticCache, DSStaticGDNSlot + + signature = self._static_graph_signature(module, batch_size, max_len, device, model_dtype, use_step_kernel, + sampling, repetition_penalty, eos_ids) + state = self._static_graph_state + if self._group_needs_capture(state is None or state.signature != signature): + # Free the stale cache and graph pool before allocating replacements. + self._static_graph_state = None + state = None + # The KV layers are sized from the prefill's local KV tensors on first use. + cache = DeepSpeedStaticCache(module.config, max_cache_len=max_len) + prefill_cache = None + if is_hybrid: + prefill_cache = self._create_static_cache(StaticCache, module.config, batch_size, max_len, device, + model_dtype) + for layer_idx, ds_layer in enumerate(cache.layers): + if isinstance(ds_layer, DSStaticGDNSlot): + ds_layer.bind(prefill_cache.layers[layer_idx]) + # per-row positions: the batched step and decode-attention kernels + # advance one entry per sequence (a shared scalar would race) + write_pos = torch.zeros(batch_size, dtype=torch.long, device=device) + cache.set_write_position(write_pos) + state = _StaticGraphState( + signature, + cache, + prefill_cache, + write_pos, + static_input=torch.zeros(batch_size, 1, dtype=torch.long, device=device), + # Full-width causal mask for the full-attention layers; each step + # reveals the position of its output token in place (graph-replay safe). + static_attention=torch.zeros(batch_size, 1, 1, max_len, dtype=torch.bool, device=device), + # Prompt and generated tokens; each step writes its output token one position ahead. + token_buffer=torch.zeros(batch_size, max_len, dtype=torch.long, device=device), + penalized_tokens=torch.zeros(batch_size, max_len, dtype=torch.bool, device=device), + finished=torch.zeros(batch_size, dtype=torch.bool, device=device), + ) + self._static_graph_state = state + + # Resetting the GDN slots also resets the prefill cache they are bound to. + state.cache.reset() + if state.prefill_cache is not None: + state.prefill_cache.reset() + return state + def _static_graph_signature(self, module, batch_size, max_len, device, model_dtype, use_step_kernel, sampling, + repetition_penalty, eos_ids): + # Token selection is captured with the forward, so the decoding settings are part of the graph. + decode_signature = (use_step_kernel, sampling.temperature, sampling.top_k, sampling.top_p, repetition_penalty, + None if eos_ids is None else tuple(eos_ids.tolist())) + return self._graph_signature(module, batch_size, max_len, device, model_dtype) + (decode_signature, ) + + def _static_decode_step(self, module, state, model_dtype, device, is_hybrid, use_step_kernel, select_next_tokens, + repetition_penalty, eos_ids): + """Return the decode step that ``_capture_static_graph`` captures for ``state``.""" + batch_size = state.static_input.shape[0] + ds_cache = state.cache + write_pos = state.write_position + static_token = state.static_input + static_attn = state.static_attention + token_buffer = state.token_buffer + penalized = state.penalized_tokens # Persistent decode position tensors as VIEWS of write_pos: the - # captured forwards read this memory, and the in-graph step kernel - # advances write_pos itself — so replays see the new position with - # no host-side mirror updates. (A clone here would freeze the - # captured value and desync the b=1 full-step path.) + # captured forwards read this memory, and the step advances write_pos + # itself — so replays see the new position with no host-side updates. static_cache_pos = write_pos[:1] static_pos_ids = write_pos.unsqueeze(1) + # Eager attention adds the mask to the scores, so it needs an additive + # mask. It is built inside the graph from the boolean one. + additive_mask = getattr(module.config, "_attn_implementation", None) == "eager" - full_token_buf = torch.zeros(batch_size, max_len, dtype=torch.long, device=device) - full_token_buf[:, :prompt_len] = prompt_ids - full_token_buf[:, prompt_len] = next_token.view(-1) # first generated token per row - - write_pos.fill_(prompt_len) + step_op = None + if use_step_kernel: + try: + from deepspeed.ops.module_inject import get_fused_glu_op + candidate = get_fused_glu_op() + if hasattr(candidate, "decode_step_graph"): + step_op = candidate + except Exception: + step_op = None + + def decode_step(): + causal_mask = static_attn + if additive_mask: + causal_mask = torch.zeros(static_attn.shape, dtype=model_dtype, + device=device).masked_fill_(~static_attn, + torch.finfo(model_dtype).min) + # Decode-step mask argument: the per-type dict for hybrid models, + # the plain 4-D tensor for standard full-attention ones. + decode_mask = {"full_attention": causal_mask, "linear_attention": None} if is_hybrid else causal_mask + logits = module( + static_token, + attention_mask=decode_mask, + past_key_values=ds_cache, + use_cache=True, + cache_position=static_cache_pos, + position_ids=static_pos_ids, + ).logits[:, -1, :] + # The fused kernel takes only CUDA bf16 logits; other dtypes keep the PyTorch step. + state.step_kernel_mounted = (step_op is not None and logits.dtype is torch.bfloat16 + and get_accelerator().on_accelerator(logits)) + if state.step_kernel_mounted: + # argmax -> next input token -> advance write_pos -> reveal mask -> output buffer + step_op.decode_step_graph(logits.contiguous(), static_token.view(batch_size, 1), write_pos, + static_attn, token_buffer) + next_token = static_token + else: + if repetition_penalty != 1.0: + logits = self._graph_repetition_penalty(logits, token_buffer, penalized, repetition_penalty) + next_token = select_next_tokens(logits) + static_token.copy_(next_token) + write_pos.add_(1) + # The output token is the next step's input, at the advanced position. + next_pos = write_pos.unsqueeze(1) + token_buffer.scatter_(1, next_pos, next_token) + penalized.scatter_(1, next_pos, True) + static_attn.view(batch_size, -1).scatter_(1, next_pos, True) + if eos_ids is not None: + state.finished.logical_or_((next_token == eos_ids).any(dim=-1)) + + return decode_step + + def _capture_static_graph(self, module, state, decode_step, max_len, device, model_dtype): + """Capture ``decode_step`` for ``state`` from its loaded prompt.""" + ds_cache = state.cache + write_pos = state.write_position # Replace SDPA in the full-attention layers with the custom # decode_attn kernel for the b=1 decode steps (prefill and any # non-graph path keep the original forward). Must happen before the # warmup forwards so the captured graph records the kernel. - attn_patched = 0 module._ki_fused_norm_patched = 0 if self.use_segki: try: @@ -1915,8 +2212,8 @@ def next_tokens(logits): cos_t, sin_t = rotary(torch.zeros(1, max_len, dtype=model_dtype, device=device), positions) cos_t = cos_t[0].float().contiguous() sin_t = sin_t[0].float().contiguous() - attn_patched = install_decode_attention(module, write_pos, attn_op, cos_table=cos_t, - sin_table=sin_t) if hasattr(attn_op, "decode_attn") else 0 + if hasattr(attn_op, "decode_attn"): + install_decode_attention(module, write_pos, attn_op, cos_table=cos_t, sin_table=sin_t) module._ki_fused_norm_patched = install_fused_norm(module, attn_op) install_lm_head(module, attn_op) except Exception as e: @@ -1927,7 +2224,6 @@ def next_tokens(logits): # visible instead of looking like normal slow decoding. logger.warning_once(f"segKI decode install failed; rollout falls back to the HF forward " f"({type(e).__name__}: {e}). Decode will run without the injected kernels.") - attn_patched = 0 module._ki_fused_norm_patched = 0 # Snapshot the GDN states right after prefill: the warmup forwards @@ -1949,161 +2245,37 @@ def restore_gdn_states(): saved_post = dict(module._forward_hooks) module._forward_pre_hooks.clear() module._forward_hooks.clear() + # Warmup draws random numbers when sampling; restore the generator so the + # rollout draws the same ones as without capture. + rng_state = get_accelerator().get_rng_state() + start_pos = write_pos.clone() try: - # Warmup on side stream - static_token.copy_(next_token) - s = get_accelerator().Stream() - s.wait_stream(get_accelerator().current_stream()) - with get_accelerator().stream(s): - for _ in range(3): - out = module( - static_token, - attention_mask=decode_mask, - past_key_values=ds_cache, - use_cache=True, - cache_position=static_cache_pos, - position_ids=static_pos_ids, - ) - get_accelerator().current_stream().wait_stream(s) - restore_gdn_states() - - # Capture: full-step graph (forward + argmax + buffer updates). - # The step-update kernel indexes token_buf via write_pos (a GPU - # tensor the kernel itself advances), so no host-side step counter - # is needed — the graph is fully self-contained for replay. - graph_op = None - step_kernel_mounted = False - try: - from deepspeed.ops.module_inject import get_fused_glu_op - candidate = get_fused_glu_op() - if hasattr(candidate, "decode_step_graph"): - graph_op = candidate - except Exception: - graph_op = None - - graph = get_accelerator().create_graph() - with get_accelerator().capture_to_graph(graph): - self._update_static_causal_attention(static_attn, static_causal_attn) - out = module( - static_token, - attention_mask=decode_mask, - past_key_values=ds_cache, - use_cache=True, - cache_position=static_cache_pos, - position_ids=static_pos_ids, - ) - static_logits = out.logits - # decode_step_graph kernel is b=1 only (single-sequence argmax); - # for b>1 the graph captures forward only and Python handles - # argmax + buffer updates outside the graph. The kernel also - # only accepts CUDA bf16 logits — fp16 models must keep the - # PyTorch argmax path instead of failing during capture. - is_greedy = sampling is None or sampling.temperature <= 0.0 - if (batch_size == 1 and graph_op is not None and is_greedy and repetition_penalty == 1.0 - and static_logits.dtype is torch.bfloat16 and get_accelerator().on_accelerator(static_logits)): - graph_op.decode_step_graph(static_logits[:, -1, :].contiguous(), static_token.view(batch_size, 1), - write_pos, static_attn, full_token_buf) - step_kernel_mounted = True - - # The capture run advanced the GDN conv/recurrent states (its - # forward consumed static_token) and mutated write_pos whether - # or not decode_step_graph was mounted; restore unconditionally - # so the fallback graph (native op unavailable) does not start - # from a state that already consumed the first decode token. - restore_gdn_states() - write_pos.fill_(prompt_len) - static_attn[:, prompt_len + 1:].zero_() - static_token.copy_(next_token) + with _disable_autocast_weight_cache(): + # Warmup on side stream. Each step advances the position, so every + # warmup starts from the prompt to stay inside the cache. + s = get_accelerator().Stream() + s.wait_stream(get_accelerator().current_stream()) + with get_accelerator().stream(s): + for _ in range(3): + write_pos.copy_(start_pos) + decode_step() + get_accelerator().current_stream().wait_stream(s) + write_pos.copy_(start_pos) + restore_gdn_states() + + graph = get_accelerator().create_graph() + with get_accelerator().capture_to_graph(graph): + decode_step() + # Restore the GDN states, so the first replay does not start from a + # state that already consumed the first decode token. + restore_gdn_states() finally: module._forward_pre_hooks.update(saved_pre) module._forward_hooks.update(saved_post) + get_accelerator().set_rng_state(rng_state) - # --- Decode loop: full-step graph (b=1) > graph+Python (b>1) > Python loop --- - if graph is not None and batch_size > 1: - # Graph forward + Python argmax for b>1: the graph eliminates kernel - # launch overhead for the forward pass; argmax and buffer updates - # stay in Python (PyTorch argmax is batch-native). The Python - # overhead (~50us/step) is a smaller fraction of the larger GPU - # workload at higher batch. - # 1 = check every step: EOS-heavy rollouts (RL responses end - # early; max_new_tokens is only a cap) would otherwise replay up - # to eos_check_every - 1 dead steps after the last row finishes, - # which costs far more than the per-step sync saves (measured - # +0.1-0.3% at b=32 without EOS vs up to ~20% with early EOS). - eos_check_every = 1 - eos_mask = torch.zeros(batch_size, dtype=torch.bool, device=device) - for step in range(max_new_tokens - 1): - static_token.copy_(next_token) - pos = prompt_len + step - write_pos.fill_(pos) - # Reveal only the current token's own slot: the pos+1 slot has - # not been written yet (warmup/capture leftovers), and SDPA at - # b>1 attends every slot the mask reveals. - static_attn[:, pos] = True - self._update_static_causal_attention(static_attn, static_causal_attn) - get_accelerator().replay_graph(graph) - next_token = next_tokens(static_logits[:, -1, :]) - output_ids.append(next_token) - # eos_mask.all() is a device->host sync; running it every step - # serializes the ~50us of Python glue against the replay and - # idles the GPU between steps. Amortize it like the b=1 path: - # check every eos_check_every steps and break with a bulk pad. - # Tokens generated after a row's EOS (at most - # eos_check_every - 1 of them) are padded away by - # _pad_after_eos, so the output is identical. - if eos_token_id is None: - continue - eos_mask |= (next_token.view(batch_size) == eos_token_id) - if step % eos_check_every == eos_check_every - 1 and bool(eos_mask.all()): - remaining = max_new_tokens - 2 - step - if remaining > 0: - output_ids.append( - torch.full((batch_size, remaining), pad_token_id, dtype=torch.long, device=device)) - break - return torch.cat(output_ids, dim=1) - - # Full-step graph requires the step kernel to actually be in the - # graph: mounting is conditional (b=1, CUDA bf16 logits), and a - # kernel-less graph replay would read a token buffer nobody wrote. - if step_kernel_mounted: - # This path avoids a device sync on every b=1 replay. EOS can be - # late by up to 15 steps, which is padded away below; batched - # graph+Python decode checks each step because one dead replay is - # multiplied by every active row. - eos_check_every = 16 - for step in range(max_new_tokens - 1): - get_accelerator().replay_graph(graph) - if eos_token_id is not None and step % eos_check_every == eos_check_every - 1: - if bool((static_token.view(-1) == eos_token_id).all().item()): - break - # pad each row's tail after its own first EOS (response region only; - # a prompt may legitimately contain the EOS id as content) - if eos_token_id is not None: - resp = full_token_buf[:, prompt_len:] - is_eos = resp == eos_token_id - first_eos = torch.where(is_eos.any(dim=1), - is_eos.float().argmax(dim=1), torch.full_like(write_pos[0], resp.shape[1])) - for r in (first_eos < resp.shape[1]).nonzero(as_tuple=True)[0].tolist(): - full_token_buf[r, prompt_len + first_eos[r].item() + 1:] = pad_token_id - gen_ids = full_token_buf[:, prompt_len:prompt_len + max_new_tokens] - return torch.cat([prompt_ids, gen_ids], dim=1) - - eos_mask = torch.zeros(batch_size, dtype=torch.bool, device=device) - for step in range(max_new_tokens - 1): - if eos_mask.all(): - output_ids.append(torch.full((batch_size, 1), pad_token_id, dtype=torch.long, device=device)) - continue - static_token.copy_(next_token) - pos = prompt_len + step - write_pos.fill_(pos) - static_attn[:, pos] = True - self._update_static_causal_attention(static_attn, static_causal_attn) - get_accelerator().replay_graph(graph) - next_token = next_tokens(static_logits[:, -1, :]) - output_ids.append(next_token) - eos_mask |= (next_token.view(1) == eos_token_id) - return torch.cat(output_ids, dim=1) + state.graph = graph def sync_weights(self, step: int) -> None: # noqa: ARG002 """Invalidate derived-weight caches after in-place weight updates. @@ -2118,13 +2290,14 @@ def sync_weights(self, step: int) -> None: # noqa: ARG002 self.refresh_weights() def shutdown(self) -> None: - """Release the captured continuous decode graph and its static cache. + """Release the captured decode graphs and their static caches. The rollout stays usable and captures again on the next graph rollout. - Under tensor parallelism the graph holds captured collectives, so release - it before destroying the process group. + Under tensor parallelism the graphs hold captured collectives, so release + them before destroying the process group. """ - if self._continuous_graph_state is None: + if self._continuous_graph_state is None and self._static_graph_state is None: return get_accelerator().synchronize() self._continuous_graph_state = None + self._static_graph_state = None diff --git a/deepspeed/runtime/zero/linear.py b/deepspeed/runtime/zero/linear.py index c191889e0925..9bae8a9545f9 100644 --- a/deepspeed/runtime/zero/linear.py +++ b/deepspeed/runtime/zero/linear.py @@ -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() @@ -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 diff --git a/docs/code-docs/source/inference-engine.rst b/docs/code-docs/source/inference-engine.rst index f19347d0d9c3..82f612aec9ec 100644 --- a/docs/code-docs/source/inference-engine.rst +++ b/docs/code-docs/source/inference-engine.rst @@ -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 --------------------- @@ -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 diff --git a/tests/unit/module_inject/test_segment_ki_kernels.py b/tests/unit/module_inject/test_segment_ki_kernels.py index 9c7f56ed26a8..47dcf571ea29 100644 --- a/tests/unit/module_inject/test_segment_ki_kernels.py +++ b/tests/unit/module_inject/test_segment_ki_kernels.py @@ -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 diff --git a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py index 39b8f8cbea8c..6d8bd2091895 100644 --- a/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py +++ b/tests/unit/runtime/rollout/test_hybrid_engine_rollout.py @@ -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 @@ -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]]), @@ -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") @@ -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)) diff --git a/tests/unit/v1/test_hybrid_engine_rollout_v1.py b/tests/unit/v1/test_hybrid_engine_rollout_v1.py index 9790877b6833..19b8931f2f19 100644 --- a/tests/unit/v1/test_hybrid_engine_rollout_v1.py +++ b/tests/unit/v1/test_hybrid_engine_rollout_v1.py @@ -2,6 +2,7 @@ # DeepSpeed Team """Accelerator-backed v1 HybridEngineRollout tests.""" +import copy import gc import os from types import SimpleNamespace @@ -12,6 +13,7 @@ from transformers.cache_utils import Cache import deepspeed +import deepspeed.comm as dist from deepspeed.accelerator import get_accelerator from deepspeed.runtime.rollout.base import RolloutRequest, SamplingConfig from deepspeed.runtime.rollout.hybrid_engine_rollout import HybridEngineRollout, HybridEngineRolloutConfig @@ -42,7 +44,9 @@ def forward(self, input_ids, attention_mask, past_key_values=None, cache_positio layer_idx=0, cache_kwargs={"cache_position": cache_position}) if attention_mask.dim() == 4: - valid = attention_mask[:, 0, 0, :] == 0 + mask = attention_mask[:, 0, 0, :] + # Boolean masks mark valid columns True, additive ones with 0. + valid = mask if mask.dtype == torch.bool else mask == 0 else: valid = torch.zeros((values.shape[0], values.shape[2]), dtype=torch.bool, device=input_ids.device) valid[:, :attention_mask.shape[1]] = attention_mask.bool() @@ -240,6 +244,82 @@ def test_matches_generate_on_sharded_llama(self, use_graph): accelerator.synchronize() +class TestAutoTPGraphRecapture(DistributedTest): + world_size = 2 + + @pytest.mark.parametrize("continuous_batch_size", [None, 2]) + def test_ranks_recapture_together(self, continuous_batch_size, monkeypatch): + accelerator = get_accelerator() + if accelerator.create_graph() is None: + pytest.skip("requires graph capture") + + from transformers import AutoModelForCausalLM, LlamaConfig + + config = LlamaConfig(vocab_size=128, + hidden_size=64, + intermediate_size=128, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=4, + max_position_embeddings=64) + torch.manual_seed(0) + model = AutoModelForCausalLM.from_config(config) + ds_config = { + "train_micro_batch_size_per_gpu": 1, + "tensor_parallel": { + "autotp_size": 2 + }, + "zero_optimization": { + "stage": 0 + }, + } + engine, _, _, _ = deepspeed.initialize(model=model, config=ds_config) + model.eval() + + device = torch.device(accelerator.current_device_name()) + prompt_ids = torch.tensor([[5, 17, 42, 9], [33, 8, 71, 2]], device=device) + prompt_attn = torch.ones_like(prompt_ids) + new_tokens = 6 + with torch.no_grad(): + expected = model.generate(prompt_ids, + attention_mask=prompt_attn, + max_new_tokens=new_tokens, + do_sample=False, + eos_token_id=None, + pad_token_id=0) + + 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 = HybridEngineRollout(engine, + SimpleNamespace(pad_token_id=0, eos_token_id=-1), + cfg=HybridEngineRolloutConfig(use_graph_capture=True)) + sampling = SamplingConfig(max_new_tokens=new_tokens, + temperature=0, + continuous_batch_size=continuous_batch_size) + try: + for step in range(2): + if step == 1 and dist.get_rank() == 1: + # Only this rank's signature changes; its peer must capture with it, + # since capture runs forwards that hold TP collectives. + weight = model.model.layers[0].mlp.down_proj.weight + weight.data = weight.data.clone() + output = rollout.generate(RolloutRequest(prompt_ids, prompt_attn), sampling) + assert torch.equal(output.input_ids, expected) + assert capture_count == 2 + finally: + # A live graph holding NCCL work hangs process-group teardown. + del rollout + gc.collect() + accelerator.synchronize() + + @pytest.mark.parametrize("attn_implementation", ["eager", "sdpa"]) def test_static_graph_matches_native_llama_generation(attn_implementation): accelerator = get_accelerator() @@ -281,6 +361,159 @@ def test_static_graph_matches_native_llama_generation(attn_implementation): assert output.input_ids.tolist() == expected.tolist() +def test_static_graph_is_reused_across_rollouts_with_the_same_decode_shape(monkeypatch): + accelerator = get_accelerator() + if not accelerator.is_available() or accelerator.create_graph() is None: + pytest.skip("requires graph capture") + + from transformers import LlamaConfig, LlamaForCausalLM + + torch.manual_seed(1234) + config = LlamaConfig(vocab_size=64, + hidden_size=64, + intermediate_size=128, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=2, + max_position_embeddings=128) + config._attn_implementation = "sdpa" + device = torch.device(accelerator.device_name()) + model = LlamaForCausalLM(config).to(device).eval() + generator = torch.Generator().manual_seed(1) + short_prompts = torch.randint(1, 64, (4, 8), generator=generator).to(device) + long_prompts = torch.randint(1, 64, (4, 12), generator=generator).to(device) + # eos -1 never matches, so every row generates the full length. + rollout = HybridEngineRollout(SimpleNamespace(module=model), + SimpleNamespace(pad_token_id=0, eos_token_id=-1), + cfg=HybridEngineRolloutConfig(use_graph_capture=True)) + + 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) + # The decode graph depends on the batch size and prompt width plus max_new_tokens, not on the + # prompt width alone: 8 + 16 and 12 + 12 share one graph, while 8 + 8 needs another. + outputs = [] + for step, (prompt_ids, new_tokens) in enumerate( + ((short_prompts, 16), (short_prompts, 16), (long_prompts, 12), (short_prompts, 8))): + if step == 1: + # Apply the same in-place update an optimizer step would make. + with torch.no_grad(): + for parameter in model.parameters(): + parameter.add_(torch.randn_like(parameter) * 0.05) + rollout.sync_weights(step=1) + attention_mask = torch.ones_like(prompt_ids) + with torch.no_grad(): + expected = model.generate(prompt_ids, + attention_mask=attention_mask, + max_new_tokens=new_tokens, + do_sample=False, + eos_token_id=None, + pad_token_id=0) + output = rollout.generate(RolloutRequest(prompt_ids, attention_mask), + SamplingConfig(max_new_tokens=new_tokens, temperature=0)) + assert output.input_ids.tolist() == expected.tolist() + outputs.append(output.input_ids) + + # The update must change the tokens, otherwise a graph replaying stale weights would also pass. + assert not torch.equal(outputs[0], outputs[1]) + assert capture_count == 2 + + # A graph captured in eval mode must not be replayed in training mode. + model.train() + rollout.generate(RolloutRequest(short_prompts, torch.ones_like(short_prompts)), + SamplingConfig(max_new_tokens=8, temperature=0)) + model.eval() + assert capture_count == 3 + + # Child module mode changes must also invalidate a retained graph. + child = model.model.layers[0] + child.train() + rollout.generate(RolloutRequest(short_prompts, torch.ones_like(short_prompts)), + SamplingConfig(max_new_tokens=8, temperature=0)) + child.eval() + assert capture_count == 4 + + # Nor may a graph captured without autocast be replayed under it. Autocast + # still changes kernels at the model's own dtype, e.g. softmax runs in fp32. + bf16_rollout = HybridEngineRollout(SimpleNamespace(module=copy.deepcopy(model).to(torch.bfloat16)), + SimpleNamespace(pad_token_id=0, eos_token_id=-1), + cfg=HybridEngineRolloutConfig(use_graph_capture=True)) + bf16_request = RolloutRequest(short_prompts, torch.ones_like(short_prompts)) + bf16_rollout.generate(bf16_request, SamplingConfig(max_new_tokens=8, temperature=0)) + with torch.autocast(device_type=accelerator.device_name(), dtype=torch.bfloat16): + bf16_rollout.generate(bf16_request, SamplingConfig(max_new_tokens=8, temperature=0)) + bf16_rollout.shutdown() + assert capture_count == 6 + + head_dim = config.hidden_size // config.num_attention_heads + # Keys and values for every layer at batch 4 and cache length 8 + 8. + cache_bytes = 2 * config.num_hidden_layers * 4 * config.num_key_value_heads * 16 * head_dim * 4 + allocated = accelerator.memory_allocated() + rollout.shutdown() + assert accelerator.memory_allocated() <= allocated - cache_bytes + + +@pytest.mark.parametrize("continuous_batch_size", [None, 2]) +def test_graph_revalidates_tensors_replaced_during_prefill(monkeypatch, continuous_batch_size): + accelerator = get_accelerator() + if not accelerator.is_available() or accelerator.create_graph() is None: + pytest.skip("requires graph capture") + + from transformers import LlamaConfig, LlamaForCausalLM + + torch.manual_seed(1234) + config = LlamaConfig(vocab_size=64, + hidden_size=64, + intermediate_size=128, + num_hidden_layers=2, + num_attention_heads=4, + num_key_value_heads=2, + max_position_embeddings=128) + config._attn_implementation = "eager" + device = torch.device(accelerator.device_name()) + model = LlamaForCausalLM(config).to(device).eval() + prompt_ids = torch.randint(1, 64, (2, 8), generator=torch.Generator().manual_seed(1)).to(device) + attention_mask = torch.ones_like(prompt_ids) + sampling = SamplingConfig(max_new_tokens=6, temperature=0, continuous_batch_size=continuous_batch_size) + tokenizer = SimpleNamespace(pad_token_id=0, eos_token_id=-1) + rollout = HybridEngineRollout(SimpleNamespace(module=model), + tokenizer, + cfg=HybridEngineRolloutConfig(use_graph_capture=True)) + capture_count = 0 + original_capture_to_graph = accelerator.capture_to_graph + + 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) + first = rollout.generate(RolloutRequest(prompt_ids, attention_mask), sampling) + assert capture_count == 1 + + replaced = [False] + handle = None + + def replace_buffer_once(*_args, **_kwargs): + if not replaced[0]: + rotary = model.model.rotary_emb + rotary.inv_freq = rotary.inv_freq.clone() + replaced[0] = True + handle.remove() + + handle = model.register_forward_pre_hook(replace_buffer_once) + second = rollout.generate(RolloutRequest(prompt_ids, attention_mask), sampling) + assert replaced[0] + assert torch.equal(second.input_ids, first.input_ids) + assert capture_count == 2 + + def test_continuous_generation_profile_on_accelerator(): accelerator = get_accelerator() if not accelerator.is_available(): @@ -463,7 +696,9 @@ def counted_capture_to_graph(*args, **kwargs): monkeypatch.setattr(accelerator, "capture_to_graph", counted_capture_to_graph) # Three requests and two slots force refill; the second call also exercises graph reuse. - for rollout in (eager_rollout, graph_rollout, graph_rollout): + for rollout_index, rollout in enumerate((eager_rollout, graph_rollout, graph_rollout)): + if rollout_index == 2: + rollout.sync_weights(step=1) output = rollout.generate(request, sampling) assert torch.equal(output.input_ids, reference) assert torch.equal(output.attention_mask, expected_attention) @@ -617,6 +852,42 @@ def _random_request(batch_size, prompt_len, device): return RolloutRequest(prompt_ids.to(device), torch.ones_like(prompt_ids).to(device)) +def test_static_graph_stops_once_every_row_has_produced_eos(monkeypatch): + accelerator = get_accelerator() + if not accelerator.is_available() or accelerator.device_name() != "cuda": + pytest.skip("CUDA is required for CUDA graph decode coverage") + + device = torch.device(accelerator.device_name()) + model = _tiny_llama(device) + new_tokens = 48 + request = _random_request(batch_size=8, prompt_len=8, device=device) + sampling = SamplingConfig(max_new_tokens=new_tokens, temperature=0) + unstopped = _rollout(model, use_graph_capture=False).generate(request, sampling).input_ids + # Every row's third generated token is an EOS id, so all rows finish early. + eos_ids = sorted(set(unstopped[:, 8 + 2].tolist())) + + def rollout(use_graph_capture): + return HybridEngineRollout(SimpleNamespace(module=model), + SimpleNamespace(pad_token_id=0, eos_token_id=eos_ids), + cfg=HybridEngineRolloutConfig(use_graph_capture=use_graph_capture)) + + expected = rollout(use_graph_capture=False).generate(request, sampling) + replay_count = 0 + original_replay_graph = accelerator.replay_graph + + def counted_replay_graph(graph): + nonlocal replay_count + replay_count += 1 + return original_replay_graph(graph) + + monkeypatch.setattr(accelerator, "replay_graph", counted_replay_graph) + output = rollout(use_graph_capture=True).generate(request, sampling) + + assert output.input_ids.tolist() == expected.input_ids.tolist() + assert output.attention_mask.tolist() == expected.attention_mask.tolist() + assert replay_count < new_tokens - 1 + + @pytest.mark.parametrize("use_graph_capture, continuous_batch_size", [(True, None), (True, 8), (False, 8)]) @pytest.mark.parametrize("temperature, top_k, top_p", [(1.0, 0, 1.0), (0.7, 5, 1.0), (1.0, 0, 0.8)]) def test_decode_sampling_matches_hf_generate(temperature, top_k, top_p, use_graph_capture, continuous_batch_size):