diff --git a/docs/src/content/docs/deployment/optimization.md b/docs/src/content/docs/deployment/optimization.md index bc5be3d430..c77b540f2b 100644 --- a/docs/src/content/docs/deployment/optimization.md +++ b/docs/src/content/docs/deployment/optimization.md @@ -411,6 +411,13 @@ and fixed-token `prompt_logprob_token_ids` scoring, including fixed-token requests without ordinary prompt logprobs. Ordinary generation still uses the bounded decoder window. +With local prefix caching and `--prefix-cache-retention-interval 0` (the +default), the native backend also keeps the early-layer window at the last +reusable boundary of a completed generation. A continuation can reuse the +previous output up to that boundary, including with DSpark. The backend +keeps one extra cache-hit interval of live window history in the default +DSpark configuration. Decoder replay is unchanged. + For BF16 query chunks, including prefill, the backend fuses query/KV RMSNorm with MXFP8 query quantization and the KV rotary embedding. The query projection and optional indexer reuse the quantized query with their diff --git a/sonar/v1/core/kv_cache_coordinator.py b/sonar/v1/core/kv_cache_coordinator.py index 174085511a..e797165373 100644 --- a/sonar/v1/core/kv_cache_coordinator.py +++ b/sonar/v1/core/kv_cache_coordinator.py @@ -25,6 +25,7 @@ KVCacheConfig, KVCacheSpec, MambaSpec, + SlidingWindowMLASpec, SlidingWindowSpec, ) from sonar.v1.request import Request @@ -182,6 +183,13 @@ def __init__( # 0 = keep only the latest replay boundary; None = dense; self.retention_interval = kv_cache_config.prefix_cache_retention_interval _validate_prefix_cache_retention_interval(self.retention_interval, self.scheduler_block_size, kv_cache_config) + self.decode_tail_managers = tuple( + manager + for manager in self.single_type_managers + if manager.enable_caching + and isinstance(manager.kv_cache_spec, SlidingWindowMLASpec) + and manager.kv_cache_spec.decode_tail_retention_tokens + ) def get_num_blocks_to_allocate( self, @@ -364,6 +372,38 @@ def cache_blocks(self, request: Request, num_computed_tokens: int) -> None: replay_boundaries=boundaries, ) + def cache_finished_decode_tail(self, request: Request) -> None: + """Publish the final settled SWA window before its pages are freed.""" + if not self.decode_tail_managers: + return + pool = self.block_pool + boundary = round_down( + min( + request.num_computed_tokens - request.num_in_flight_tokens, + request.num_tokens - 1, + len(request.block_hashes) * pool.hash_block_size, + ), + self.scheduler_block_size, + ) + if boundary <= request.num_prompt_tokens - max(1, pool.num_hash_lookahead_tokens): + return + for manager in self.decode_tail_managers: + spec = manager.kv_cache_spec + assert isinstance(spec, SlidingWindowMLASpec) + end = boundary // manager.block_size + start = max(0, end - cdiv(spec.sliding_window - 1, manager.block_size)) + blocks = manager.req_to_blocks.get(request.request_id) + if blocks is None or end > len(blocks): + continue + window = blocks[start:end] + if any(block.is_null for block in window): + continue + mask = [block.block_hash is None for block in window] + if any(mask): + pool.cache_full_blocks( + request, blocks, start, end, manager.block_size, manager.kv_cache_group_id, block_mask=mask + ) + def emit_cached_block_events(self, request: Request, computed_blocks: tuple[list[KVCacheBlock], ...]) -> None: for group_idx, group_blocks in enumerate(computed_blocks): if group_blocks: diff --git a/sonar/v1/core/kv_cache_planning.py b/sonar/v1/core/kv_cache_planning.py index 33448c79af..5527eb7ea5 100644 --- a/sonar/v1/core/kv_cache_planning.py +++ b/sonar/v1/core/kv_cache_planning.py @@ -784,7 +784,7 @@ def promoted_page_size_padded(spec: AttentionSpec, block_size: int) -> int | Non # Promoted specs allocate blocks for all tokens and never free # below the window, so the trailing-edge extension and replay # bound are moot. - drop=("extra_retained_tokens", "bounded_replay"), + drop=("extra_retained_tokens", "bounded_replay", "decode_tail_retention_tokens"), block_size=block_size, page_size_padded=promoted_page_size_padded(spec, block_size), ) @@ -1568,6 +1568,41 @@ def get_kv_cache_configs( return kv_cache_configs +def _retain_native_dsv41_decode_tail(sonar_config: SonarConfig, groups: list[KVCacheGroupSpec]) -> None: + cache = sonar_config.cache_config + if ( + not cache.enable_prefix_caching + or cache.prefix_cache_retention_interval != 0 + or cache.kv_offloading_size is not None + or sonar_config.kv_transfer_config is not None + ): + return + spec_config = sonar_config.speculative_config + hash_lookahead = sonar_config.num_hash_lookahead_tokens + if spec_config is not None and spec_config.use_eagle_block_drop() and not hash_lookahead: + return + + # The final aligned hit can sit up to a scheduler block behind the + # computed prefix. Size this slack before the pool and admission checks. + alignment = math.lcm(*(group.kv_cache_spec.block_size for group in groups)) + tokens = alignment + max(0, hash_lookahead - 1) + for group in groups: + spec = group.kv_cache_spec + first = spec.first_spec if isinstance(spec, UniformTypeKVCacheSpecs) else spec + if not ( + isinstance(first, SlidingWindowMLASpec) and first.cache_dtype_str == "b12x_dsv41" and first.prefix_cacheable + ): + continue + if isinstance(spec, UniformTypeKVCacheSpecs): + layer_specs: dict[str, KVCacheSpec] = {} + for name, layer_spec in spec.kv_cache_specs.items(): + assert isinstance(layer_spec, SlidingWindowMLASpec) + layer_specs[name] = replace(layer_spec, decode_tail_retention_tokens=tokens) + group.kv_cache_spec = replace(spec, kv_cache_specs=layer_specs) + else: + group.kv_cache_spec = replace(first, decode_tail_retention_tokens=tokens) + + def get_global_kv_cache_groups( sonar_config: SonarConfig, kv_cache_specs: list[dict[str, KVCacheSpec]], @@ -1609,6 +1644,7 @@ def get_global_kv_cache_groups( for group in global_kv_cache_groups: group.is_eagle_group = not draft_layer_names.isdisjoint(group.layer_names) _warn_if_unannotated_eagle_mamba(spec_config, global_kv_cache_groups) + _retain_native_dsv41_decode_tail(sonar_config, global_kv_cache_groups) return global_kv_cache_groups diff --git a/sonar/v1/core/sched/scheduler.py b/sonar/v1/core/sched/scheduler.py index 8017986fc0..ef8a960d00 100644 --- a/sonar/v1/core/sched/scheduler.py +++ b/sonar/v1/core/sched/scheduler.py @@ -2389,6 +2389,11 @@ def update_from_output( finish_reason = request.get_finished_reason() finished = self._handle_stopped_request(request) if finished: + if not output_is_stale and request.status in ( + RequestStatus.FINISHED_STOPPED, + RequestStatus.FINISHED_LENGTH_CAPPED, + ): + self.kv_cache_manager.coordinator.cache_finished_decode_tail(request) kv_transfer_params, ec_transfer_params = self._free_request(request) if ( prefill_stats is not None diff --git a/sonar/v1/core/single_type_kv_cache_manager.py b/sonar/v1/core/single_type_kv_cache_manager.py index 802347960a..362ef2cea3 100644 --- a/sonar/v1/core/single_type_kv_cache_manager.py +++ b/sonar/v1/core/single_type_kv_cache_manager.py @@ -871,10 +871,7 @@ class SlidingWindowManager(SingleTypeKVCacheManager): def __init__(self, kv_cache_spec: SlidingWindowSpec, **kwargs) -> None: super().__init__(kv_cache_spec, **kwargs) self.sliding_window = kv_cache_spec.sliding_window - # Extra trailing tokens to retain below the window (never attended) so a - # multi-module MTP store-side lag can still reconstruct the window from - # cached blocks. - self.extra_retained_tokens = kv_cache_spec.extra_retained_tokens + self.num_retained_tokens = kv_cache_spec.num_retained_tokens @classmethod def _contiguous_blocks_for_hit(cls, window_size: int, block_size: int, use_eagle: bool) -> int: @@ -1077,11 +1074,8 @@ def get_num_skipped_tokens(self, num_computed_tokens: int) -> int: attention computation since they are outside the sliding window. Thus, get_num_skipped_tokens(7) == 4. - The trailing edge of the window is extended by `extra_retained_tokens` - so that those extra trailing tokens' blocks are retained (but not - attended). This is needed for multi-module spec decoding which can - re-prefill the last num_spec_prefill_tokens - 1 tokens from the end - of the sequence, and thus needs to delay freeing/caching of blocks. + The retained span can include tokens below the attention window for + speculative re-prefill or for a subsequent continuation. Args: num_computed_tokens: The number of tokens that have been computed. @@ -1090,10 +1084,7 @@ def get_num_skipped_tokens(self, num_computed_tokens: int) -> int: The number of tokens that will be skipped for attention computation. """ - return max( - 0, - num_computed_tokens - self.sliding_window + 1 - self.extra_retained_tokens, - ) + return max(0, num_computed_tokens - self.num_retained_tokens) class CircularBufferManager(FullAttentionManager): diff --git a/sonar/v1/kv_cache_interface.py b/sonar/v1/kv_cache_interface.py index fc6aa1f7a6..de8ad00a37 100644 --- a/sonar/v1/kv_cache_interface.py +++ b/sonar/v1/kv_cache_interface.py @@ -923,11 +923,10 @@ def max_admission_blocks_per_request(self, max_in_flight_tokens: int, max_model_ """ # During chunked prefill, we hold KV for the last `sliding_window-1` # computed tokens plus the in-flight tokens (frees happen on the - # processed-token basis); never more than `max_model_len`. An additional - # `extra_retained_tokens` trailing tokens are kept alive below the - # window for multi-module spec decoding, and must be accounted here too. + # processed-token basis). The retained span includes any history needed + # for speculative re-prefill or for a continuation cache hit. num_tokens = min( - self.sliding_window - 1 + self.extra_retained_tokens + max_in_flight_tokens, + self.num_retained_tokens + max_in_flight_tokens, max_model_len, ) # +1 because the sliding window may not start from the beginning of @@ -1007,6 +1006,7 @@ class SlidingWindowMLASpec(SlidingWindowSpec): alignment: int | None = None # Default to None for no padding. model_version: str | None = None bounded_replay: bool = False + decode_tail_retention_tokens: int = 0 # See MLAAttentionSpec.non_causal_multi_token_decode (windowed DSpark drafts). non_causal_multi_token_decode: bool = False @@ -1022,6 +1022,10 @@ def __post_init__(self): def prefix_cacheable(self) -> bool: return not self.bounded_replay + @property + def num_retained_tokens(self) -> int: + return super().num_retained_tokens + self.decode_tail_retention_tokens + @property def prefix_replay_tokens(self) -> int: return self.sliding_window if self.bounded_replay else 0 @@ -1037,6 +1041,7 @@ def merge(cls, specs: list[Self]) -> Self: sliding_window_set = set(spec.sliding_window for spec in specs) extra_retained_set = set(spec.extra_retained_tokens for spec in specs) bounded_replay_set = set(spec.bounded_replay for spec in specs) + decode_tail_retention_set = {spec.decode_tail_retention_tokens for spec in specs} block_stride_alignment_set = {spec.block_stride_alignment for spec in specs} kv_quant_mode_set = {spec.kv_quant_mode for spec in specs} alignment_set = {spec.alignment for spec in specs} @@ -1049,6 +1054,7 @@ def merge(cls, specs: list[Self]) -> Self: and len(sliding_window_set) == 1 and len(extra_retained_set) == 1 and len(bounded_replay_set) == 1 + and len(decode_tail_retention_set) == 1 and len(block_stride_alignment_set) == 1 and len(kv_quant_mode_set) == 1 and len(alignment_set) == 1 @@ -1076,6 +1082,7 @@ def merge(cls, specs: list[Self]) -> Self: tokens_per_state=tokens_per_state_set.pop(), model_version=model_version_set.pop(), bounded_replay=bounded_replay_set.pop(), + decode_tail_retention_tokens=decode_tail_retention_set.pop(), kv_quant_mode=kv_quant_mode_set.pop(), alignment=alignment_set.pop(), non_causal_multi_token_decode=any(spec.non_causal_multi_token_decode for spec in specs), diff --git a/tests/v1/core/test_prefix_replay.py b/tests/v1/core/test_prefix_replay.py index 4a562aad88..99d0aba5a5 100644 --- a/tests/v1/core/test_prefix_replay.py +++ b/tests/v1/core/test_prefix_replay.py @@ -5,19 +5,29 @@ blocks, and hands the worker the replay start.""" import dataclasses +from pathlib import Path import pytest import torch - +from transformers import OPTConfig + +from sonar.utils.hashing import sha256 +from sonar.v1.core.kv_cache_planning import get_global_kv_cache_groups, get_kv_cache_configs +from sonar.v1.core.kv_cache_utils import ( + generate_scheduler_kv_cache_config, + get_request_block_hasher, + resolve_kv_cache_block_sizes, +) from sonar.v1.core.sched.scheduler import Scheduler from sonar.v1.kv_cache_interface import ( FullAttentionSpec, KVCacheConfig, KVCacheGroupSpec, + MLAAttentionSpec, SlidingWindowMLASpec, ) -from sonar.v1.outputs import ModelRunnerOutput -from sonar.v1.request import RequestStatus +from sonar.v1.outputs import DraftTokenIds, ModelRunnerOutput +from sonar.v1.request import Request, RequestStatus from sonar.v1.structured_output import StructuredOutputManager from tests.v1.kv_connector.unit.utils import MockKVConfig, create_model_runner_output @@ -324,3 +334,76 @@ def test_kv_load_zeroing_respects_loaded_groups(is_async, loads_window): assert not new_ids & zeroed else: assert new_ids <= zeroed + + +@pytest.mark.cpu_test +@pytest.mark.parametrize( + "native,num_drafts,eviction,expected_hit", + [(False, None, "lru", 96), (True, None, "lru", 192), (True, 7, "queueguard", 192)], +) +def test_sm120_continuation_reuses_final_output_window(tmp_path: Path, native, num_drafts, eviction, expected_hit): + OPTConfig(architectures=["OPTForCausalLM"], max_position_embeddings=512).save_pretrained(tmp_path) + config = create_scheduler( + model=str(tmp_path), + skip_tokenizer_init=True, + enable_prefix_caching=True, + num_speculative_tokens=num_drafts, + block_size=32, + max_model_len=512, + ).sonar_config + config.cache_config.prefix_cache_eviction = eviction + config.cache_config.kv_cache_layout = "BLHNC" + window = SlidingWindowMLASpec( + block_size=16, + num_kv_heads=1, + head_size=16, + dtype=torch.uint8, + sliding_window=16, + cache_dtype_str="b12x_dsv41" if native else None, + ) + specs = { + "compressed": MLAAttentionSpec( + block_size=32, num_kv_heads=1, head_size=16, dtype=torch.uint8, tokens_per_state=2 + ), + "encoder-window": window, + "decoder-window": dataclasses.replace(window, bounded_replay=True), + } + groups = get_global_kv_cache_groups(config, [specs]) + cache = generate_scheduler_kv_cache_config(get_kv_cache_configs(config, [specs], [1 << 20], groups)) + block_size, hash_block_size = resolve_kv_cache_block_sizes(cache, config) + scheduler = Scheduler( + config, cache, StructuredOutputManager(config), block_size=block_size, hash_block_size=hash_block_size + ) + first = create_requests(num_requests=1, num_tokens=100, max_tokens=124, block_size=hash_block_size)[0] + scheduler.add_request(first) + step = 0 + while not first.is_finished(): + drafts = [2000 + step * 7 + i for i in range(num_drafts or 0)] + if drafts and step: + scheduler.update_draft_token_ids(DraftTokenIds([first.request_id], [drafts])) + output = scheduler.schedule() + offered = output.scheduled_spec_decode_tokens.get(first.request_id, []) + scheduler.update_from_output( + output, + ModelRunnerOutput( + req_ids=[first.request_id], + sampled_token_ids=[offered[: step % 3] + [1000]], + logprobs=None, + prompt_logprobs_dict={}, + pooler_output=None, + ), + ) + step += 1 + + # The 224th token was sampled, so a continuation can reuse through 192. + # The window ending there is already outside the live attention window. + continuation = Request( + "continuation", + prompt_token_ids=[*first.all_token_ids, 200], + sampling_params=first.sampling_params, + pooling_params=None, + block_hasher=get_request_block_hasher(hash_block_size, sha256), + ) + assert scheduler.kv_cache_manager.get_num_cached_tokens(continuation) == expected_hit + scheduler.add_request(continuation) + assert _new_req_data(scheduler.schedule(), continuation).replay_start == expected_hit - 16