# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import threading import time import traceback import uuid from collections import Counter, defaultdict from itertools import chain from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, cast import numpy as np import torch import tensorrt_llm.bindings from tensorrt_llm import logger from tensorrt_llm._torch.disaggregation import diagnostics as disagg_diagnostics from tensorrt_llm._torch.disaggregation.base import CacheKind, TokenRange from tensorrt_llm._torch.disaggregation.base.agent import use_pure_python_transfer_agent from tensorrt_llm._torch.disaggregation.base.transfer import ( RxSessionBase, SessionStatus, TxSessionBase, WaitResult, get_unique_rid, ) from tensorrt_llm._torch.disaggregation.kv_cache_transceiver import ( _KV_LIFECYCLE_ENFORCEMENT_ENV, CtxTransferStatus, GenTransferStatus, KvCacheTransceiver, ) from tensorrt_llm._torch.disaggregation.native.context_first_profile import ( supports_context_first_bf16, ) from tensorrt_llm._torch.disaggregation.native.extent import CacheExtent, Chunk from tensorrt_llm._torch.disaggregation.native.fetch import PeerFetch from tensorrt_llm._torch.disaggregation.native.perf_logger import perf_log_manager from tensorrt_llm._torch.disaggregation.native.publish import PeerPublish from tensorrt_llm._torch.disaggregation.native.retirement import ( QuiescenceFatalEvent, RetirementDeadline, ) from tensorrt_llm._torch.disaggregation.native.transfer import ( RxSession, TransferWorker, TransferWorkerConfig, TxSession, _validate_rank_info_auth_key, ) from tensorrt_llm._torch.disaggregation.resource.cache_reuse import ( CacheReuseAdapter, create_cache_reuse_adapter, ) from tensorrt_llm._torch.disaggregation.resource.utils import get_pool_view_slot_bytes from tensorrt_llm._torch.distributed.communicator import Distributed from tensorrt_llm._torch.pyexecutor import hang_detector from tensorrt_llm._torch.pyexecutor.kv_cache.kv_cache_manager_v2 import ( BlockReusePolicy, KVCacheManagerV2, ) from tensorrt_llm._torch.pyexecutor.kv_cache.mamba_cache_manager import MambaHybridCacheManagerV2 from tensorrt_llm._torch.pyexecutor.llm_request import LlmRequest from tensorrt_llm._torch.pyexecutor.resource_manager import CacheTypeCpp from tensorrt_llm._utils import ENABLE_MULTI_DEVICE, mpi_comm, mpi_disabled, nvtx_range from tensorrt_llm.bindings import DataType, LlmRequestState from tensorrt_llm.bindings.executor import ContextPhaseParams from tensorrt_llm.disaggregated_params import DisaggScheduleStyle from tensorrt_llm.llmapi.llm_args import CacheTransceiverConfig from tensorrt_llm.mapping import Mapping if TYPE_CHECKING: from mpi4py import MPI _FP4_MLA_OWNERSHIP_BRIDGE_ENV = "TRTLLM_ENABLE_FP4_MLA_KV_OWNERSHIP_BRIDGE" _FATAL_LOG_JOIN_TIMEOUT_S = 0.5 def _log_unproven_kv_transfer(event: QuiescenceFatalEvent) -> None: """Emit best-effort fatal diagnostics on a dedicated thread. Args: event: The sticky expiry event retained by the watchdog. """ try: logger.critical( "UNPROVEN_FATAL: hard-stopping through MPI/launcher; termination may include " "other executors in the same job. Retaining KV " f"and transport roots until process teardown. request_id={event.request_id}, " f"direction={event.direction}, reason={event.reason}, " "deadline_owner=retirement_grace progress_at_observation=unproven_quiescence, " f"deadline={event.deadline}, expired_at={event.expired_at}" ) except Exception: # noqa: BLE001 - diagnostics cannot alter containment pass def _fail_unproven_kv_transfer( event: QuiescenceFatalEvent, communicator: Optional["MPI.Comm"] = None ) -> None: """Terminate the executor world without running ordinary resource cleanup. Called by the independent retirement watchdog after fatal expiry is sticky and transfer admission is closed. The existing MPI/launcher crash path makes the endpoint unhealthy; request failure is not memory-release proof. The communicator identifies the executor, not an isolated failure domain: Open MPI aborts the entire job, including other executors in split worlds. Launcher-driven termination can likewise extend beyond this executor. A supervisor may replace the world only after qualified platform teardown, not merely after this function requests termination. Args: event: The first unproven physical owner whose drain deadline expired. communicator: Validated executor world captured before the watchdog starts. """ try: log_thread = threading.Thread( target=_log_unproven_kv_transfer, args=(event,), name="kv-retirement-fatal-log", daemon=True, ) log_thread.start() # Allow a fast diagnostic to finish without waiting indefinitely for # a blocked handler. Admission and unresolved roots remain fenced. log_thread.join(timeout=_FATAL_LOG_JOIN_TIMEOUT_S) finally: # Do not call PyExecutor._handle_errors(), request termination, or # transceiver.shutdown(): their normal cleanup may recycle KV pages. hang_detector.propagate_hard_kill(diagnostics=False, communicator=communicator) def _warn_retirement_termination_scope(mapping: Mapping) -> None: """Warn the executor's lead rank about the configured containment boundary. Args: mapping: The executor's rank mapping. """ if mapping.rank == 0: logger.warning( "KV transfer lifecycle enforcement ENABLED. KV retirement fail-stop may " "terminate the entire MPI job, including other " "CTX/GEN executors sharing the launch. A split communicator does not isolate " "MPI_Abort. Use separate launcher jobs when independent availability is required, " "and qualify their termination boundaries." ) def _retirement_executor_comm(mapping: Mapping, *, warn: bool = True) -> "MPI.Comm": """Capture the MPI executor world that the deadline watchdog may abort. Rank/size validation does not isolate termination. Shared MPI launches can lose every executor when one executor reaches fatal expiry. Args: mapping: The executor's expected worker rank and world size. warn: Emit the launcher-wide termination warning when selecting the communicator. Returns: The exact communicator, retained rather than resolved on another thread. Raises: ValueError: MPI cannot safely terminate the complete executor world. """ message = ( "KV retirement fail-stop requires an initialized MPI executor world with " "MPI_THREAD_MULTIPLE and communicator rank/size matching Mapping; " "non-MPI launchers are not qualified" ) if not ENABLE_MULTI_DEVICE or mpi_disabled(): raise ValueError(message) from mpi4py import MPI if not MPI.Is_initialized() or MPI.Is_finalized() or MPI.Query_thread() != MPI.THREAD_MULTIPLE: raise ValueError(message) communicator = mpi_comm() if ( communicator == MPI.COMM_NULL or communicator.Is_inter() or communicator.Get_size() != mapping.world_size or communicator.Get_rank() != mapping.rank ): raise ValueError(message) if warn: _warn_retirement_termination_scope(mapping) return communicator def _find_consensus_request_ids(request_ids_all_ranks, sync_size): frequency_map = defaultdict(int) consensus = [] for rid in chain.from_iterable(request_ids_all_ranks): frequency_map[rid] += 1 for rid, freq in sorted(frequency_map.items(), key=lambda x: x[1], reverse=True): if freq == sync_size: consensus.append(rid) else: break return consensus def _validate_fp4_mla_bridge_profile( mapping: Mapping, kv_cache_manager: KVCacheManagerV2, cache_transceiver_config: CacheTransceiverConfig, *, enabled: bool | None = None, ) -> bool: """Select the bridge only for its explicit no-retry FP4-MLA deployment cell.""" if enabled is None: enabled = os.getenv(_FP4_MLA_OWNERSHIP_BRIDGE_ENV, "0") == "1" if not enabled: return False fp4_mla_layout = ( isinstance(kv_cache_manager, KVCacheManagerV2) and kv_cache_manager.is_disagg and kv_cache_manager.dtype == DataType.NVFP4 and kv_cache_manager.kv_cache_type == CacheTypeCpp.SELFKONLY ) supported = ( fp4_mla_layout and os.getenv("TRTLLM_DISAGG_NO_RETRY", "0") == "1" and not use_pure_python_transfer_agent() and cache_transceiver_config.kv_transfer_timeout_ms is not None and cache_transceiver_config.kv_transfer_timeout_ms > 0 and mapping.enable_attention_dp and mapping.pp_size == 1 and mapping.cp_size == 1 # The C++ agent bounce scatters into the destination on the receiver agent's threads, # which can still be writing after a failure is reported; the bridge cannot prove that # those writes stopped. and cache_transceiver_config.kv_cache_bounce_size_mb == 0 and not cache_transceiver_config.enable_pipelined_transfer and os.getenv("TRTLLM_DISABLE_KV_CACHE_TRANSFER_OVERLAP") != "1" and os.getenv("TRTLLM_DISAGG_LAYERWISE") != "1" ) if not supported: raise ValueError( "FP4 MLA lifecycle bridge requires a disaggregated NVFP4 SELFKONLY " "KVCacheManagerV2, the C++ NIXL agent binding, a finite timeout, " "no-retry ADP, PP1/CP1, " "async monolithic non-layerwise transfer, and kv_cache_bounce_size_mb=0 " "(transfer-agent bounce disabled)" ) return True def _select_lifecycle_ownership( mapping: Mapping, manager: KVCacheManagerV2, config: CacheTransceiverConfig, dist: Distributed, ) -> tuple[bool, bool, Optional["MPI.Comm"]]: """Agree on protection before any rank publishes transfer metadata. The global setting requires a supported profile when explicitly enabled. Unset preserves the legacy FP4 opt-in and leaves context-first inactive. Selection failures participate in the collective so peers cannot continue with a different ownership mode. This is executor-local agreement, not negotiation with a remote executor or a general startup-failure handler. Args: mapping: Executor rank and topology. manager: Initialized local cache manager. config: Resolved transfer settings. dist: The executor's startup collective interface. Returns: FP4 and context-first activation, and the local containment communicator. Raises: ValueError: Requested protection cannot be established on every rank. """ fp4 = context_first = False communicator = None failure = None try: setting = os.getenv(_KV_LIFECYCLE_ENFORCEMENT_ENV) legacy_fp4 = os.getenv(_FP4_MLA_OWNERSHIP_BRIDGE_ENV, "0") == "1" if setting not in (None, "0", "1"): raise ValueError(f"{_KV_LIFECYCLE_ENFORCEMENT_ENV} must be 0 or 1") if setting == "0" and legacy_fp4: raise ValueError("KV lifecycle enforcement is disabled but the FP4 bridge is enabled") if setting != "0": fp4 = _validate_fp4_mla_bridge_profile(mapping, manager, config) if setting == "1" and not fp4: if manager.dtype == DataType.NVFP4: fp4 = _validate_fp4_mla_bridge_profile(mapping, manager, config, enabled=True) else: context_first = supports_context_first_bf16(mapping, manager, config) if not context_first: raise ValueError( "KV lifecycle enforcement requires a supported no-retry FP4 MLA or " "direct BF16 context-first profile; the local configuration is unsupported" ) if fp4 or context_first: communicator = _retirement_executor_comm(mapping, warn=False) except Exception as error: # Exchange all rank-local failures before raising so peers reach agreement. failure = f"{type(error).__name__}: {error}" selections = dist.allgather((fp4, context_first, failure)) failures = [f"rank {rank}: {item[2]}" for rank, item in enumerate(selections) if item[2]] if failures: raise ValueError("KV lifecycle initialization rejected: " + "; ".join(failures)) if len(selections) != mapping.world_size or any( item[:2] != (fp4, context_first) for item in selections ): raise ValueError("KV lifecycle ownership must agree on every executor rank") if fp4 or context_first: _warn_retirement_termination_scope(mapping) return fp4, context_first, communicator def _chunk_bytes_by_kind(page_table, chunk: Chunk) -> Tuple[int, int]: """This rank's (paged, STATE) KV bytes in a chunk, as the mappers move them. Per view, the valid block count (one slot for STATE) times the view's transferable slot region. The sum is expected_write_bytes: verified-reuse admission compares the sender's attested bytes against it. The pair also feeds kv_cache_size. So count the bytes the mappers move, never physical slot bytes: a coalesced pool carries one view per role class (summing slot_bytes per view would double count the slot) and ignored-role buffers occupy slot offsets no view transfers. """ if page_table is None: return 0, 0 paged_bytes = state_bytes = 0 for lg_id, block_ids in enumerate(chunk.block_ids_per_layer_groups): if block_ids is None or block_ids.size == 0: continue n = int((block_ids >= 0).sum()) if n == 0: continue lg = page_table.layer_groups[lg_id] for pool_idx, pv in enumerate(lg.pool_views): if (lg_id, pool_idx) in chunk.excluded_pool_views: continue # The view's byte regions within one slot (all of its layers). view_bytes = get_pool_view_slot_bytes(pv) if lg.kind == CacheKind.STATE: # STATE: one slot per request; the transfer covers each # view region once regardless of the block count. state_bytes += view_bytes else: # Paged: n blocks, each covering the view's regions. paged_bytes += n * view_bytes return paged_bytes, state_bytes class KvCacheTransceiverV2(KvCacheTransceiver): # GEN idle-poll skip state; _init_gen_idle_poll sets the instance values. _gen_idle_poll_skip: bool = False _gen_idle_agreed: bool = False # Helix GEN idle probe; _init_sync_policy sets the instance value. _gen_idle_probe: bool = False _gen_deferred_receives: int = 0 _pending_rank_info_admissions: Optional[dict[int, tuple[LlmRequest, Optional[str]]]] = None _rank_info_start_failures: Optional[dict[int, LlmRequest]] = None @property def consumes_transfer_buffer(self) -> bool: return False @property def reads_unique_tokens(self) -> bool: return False def __init__( self, mapping: Mapping, dist: Distributed, kv_cache_manager: KVCacheManagerV2, cache_transceiver_config: CacheTransceiverConfig, ): if not isinstance(kv_cache_manager, KVCacheManagerV2): raise ValueError( "KvCacheTransceiverV2 does not support KV cache manager V1. " f"Selected manager: {type(kv_cache_manager).__name__}. " "Use a compatible KVCacheManagerV2 configuration for " "transceiver_runtime='PYTHON'; enabling " "use_kv_cache_manager_v2=True does not override incompatible " "model features. To use V1, select transceiver_runtime='CPP' " "with use_kv_cache_manager_v2=False for a model that supports V1." ) self._shutdown_lock = threading.Lock() self._shutdown_complete = False self._dist: Distributed = dist self._kv_cache_manager = kv_cache_manager self._mapping = mapping self.kv_transfer_timeout_ms = cache_transceiver_config.kv_transfer_timeout_ms if self.kv_transfer_timeout_ms is None: raise ValueError("KvCacheTransceiverV2 requires a finite kv_transfer_timeout_ms") self.kv_transfer_poll_interval_ms = cache_transceiver_config.kv_transfer_poll_interval_ms self._sender_future_timeout_ms = ( cache_transceiver_config.kv_transfer_sender_future_timeout_ms ) transfer_timeout_s = self.kv_transfer_timeout_ms / 1000.0 sender_wait_slice_s = ( self._sender_future_timeout_ms / 1000.0 if self._sender_future_timeout_ms is not None else None ) self._check_compatible() _validate_rank_info_auth_key(cache_transceiver_config._rank_info_auth_key) ( enforce_physical_ownership, self._context_first_ownership, self._retirement_mpi_comm, ) = _select_lifecycle_ownership(mapping, kv_cache_manager, cache_transceiver_config, dist) self._fp4_mla_bridge_enabled = enforce_physical_ownership self._context_first_ownership_logged = False ownership_capable = enforce_physical_ownership or self._context_first_ownership self._reuse_adapter: CacheReuseAdapter = create_cache_reuse_adapter(kv_cache_manager) self._device_id = torch.cuda.current_device() logger.info(f"device_id: {self._device_id} in KvCacheTransceiverV2") # Setup interleaves MPI collectives (broadcast/allgather below) with # per-rank native NIXL/UCX initialization inside TransferWorker. A rank # that blocks or dies in the native phase leaves its peers stuck in the # next collective, so log each phase per rank to make the blocking # rank/phase identifiable from the logs (see the 'setup:' lines). rank = self._dist.rank logger.info(f"KvCacheTransceiverV2 setup: rank={rank} broadcast instance name (collective)") self._instance_name = self._broadcast_instance_name() logger.info( f"KvCacheTransceiverV2 setup: rank={rank} creating TransferWorker " "(native NIXL agent init + KV memory registration)" ) self._transfer_worker = TransferWorker( TransferWorkerConfig( kv_cache_manager=kv_cache_manager, device_id=self._device_id, instance_name=self._instance_name, # Context-only requests are released after KV transfer completes, so many batches # can be in-flight simultaneously. AuxBuffer holds only small CPU metadata, so a # large multiplier is cheap. max_concurrent_sessions=max(1, int(kv_cache_manager.max_batch_size)) * 20000, tx_timeout_s=sender_wait_slice_s, tx_overall_timeout_s=transfer_timeout_s, rx_timeout_s=transfer_timeout_s, enforce_physical_ownership=enforce_physical_ownership, context_first_ownership=self._context_first_ownership, quiescence_fatal_callback=( self._fail_unproven_transfer if ownership_capable else None ), # kv_cache_bounce_size_mb sizes the C++ transfer-agent bounce buffer (one # arena shared by send and receive); 0 disables it. agent_buffer_size_mb=cache_transceiver_config.kv_cache_bounce_size_mb, agent_bounce_params=cache_transceiver_config.agent_bounce_params, rank_info_auth_key=cache_transceiver_config._rank_info_auth_key, ) ) if enforce_physical_ownership: logger.info( "FP4 MLA KV ownership bridge ENABLED: " f"rank={rank}/{mapping.world_size}, backend=NIXL, runtime=PYTHON, " "request_schedule_required=GENERATION_FIRST, attention_dp=True, pp=1, cp=1, " "retry=False, async=True, layerwise=False, bounce_mb=0, " "unproven_retirement=fail_stop, termination_scope=mpi_job_or_launcher, " f"kv_transfer_timeout_ms={self.kv_transfer_timeout_ms}" ) logger.info( f"KvCacheTransceiverV2 setup: rank={rank} TransferWorker ready; " "broadcast context endpoint (collective)" ) self._dp_rank = mapping.tp_rank if mapping.enable_attention_dp else 0 self._context_info_endpoint = self._broadcast_context_endpoint() self._init_sync_policy() logger.info(f"KvCacheTransceiverV2 setup: rank={rank} exchange rank info (collective)") self._exchange_rank_info() logger.info(f"KvCacheTransceiverV2 setup: rank={rank} complete") self._send_sessions: Dict[int, TxSessionBase] = {} self._recv_sessions: Dict[int, RxSessionBase] = {} self._send_reqs = {} self._recv_reqs = {} self._cancelled_receive_fences: Dict[int, tuple[torch.cuda.Event, RetirementDeadline]] = {} self._wait_reqs = {} self._page_table = self._transfer_worker.page_table try: self._enable_pipelined_transfer = self._resolve_pipelined_transfer( cache_transceiver_config ) except ValueError: # The transfer worker is already live by this point. self._transfer_worker.shutdown() raise self._kv_size_rank_factor = self._kv_size_rank_factor_for(mapping) # Sticky role markers; flip True once any session opens, used to short-circuit # per-iter tp_allgather when this transceiver never sends/receives. self._ever_had_send_session: bool = False self._ever_had_recv_session: bool = False # Keyed multi-rank receives agree on admission before publication. self._pending_rank_info_admissions = ( {} if cache_transceiver_config._rank_info_auth_key is not None and self._gen_need_sync else None ) @staticmethod def _gen_idle_poll_skip_applies(mapping: Mapping, gen_need_sync: bool) -> bool: """Whether an idle generation worker may skip its receive-status collectives. Requires a synchronized status poll in which every rank owns every request (no attention DP, one PP stage, no context parallelism), so every rank requests the same receives in the same iteration. """ return ( gen_need_sync and not mapping.enable_attention_dp and mapping.pp_size == 1 and mapping.cp_size == 1 ) def _init_gen_idle_poll(self, enabled: bool) -> None: """Set up the idle-poll skip of check_gen_transfer_status (called by _init_sync_policy). Precondition of ``enabled``: every rank requests the same receives in the same iteration (_gen_idle_poll_skip_applies), so all ranks clear the agreement together and never split on whether to enter a collective. """ self._gen_idle_poll_skip = enabled # Set from a gathered status round in which no rank held a receive session, # cleared by every receive request; while set, every rank skips the # status-poll collectives. self._gen_idle_agreed = False # Admitted receives the caller has not started yet (set_gen_deferred_receives); # they count as sessions in the idle check. self._gen_deferred_receives = 0 def _fail_unproven_transfer(self, event: QuiescenceFatalEvent) -> None: """Fail-stop while the watchdog retains this transceiver's resource roots. The bound callback keeps request maps, KV manager, transfer worker and agent alive through the watchdog's persistent fatal thread even if the termination call raises or unexpectedly returns. Args: event: The sticky physical-retirement deadline expiry. """ _fail_unproven_kv_transfer(event, self._retirement_mpi_comm) def _broadcast_instance_name(self) -> str: if self._dist.rank == 0: name = str(uuid.uuid4()) self._dist.broadcast(name, 0) return name return cast(str, self._dist.broadcast(None, 0)) def _broadcast_context_endpoint(self) -> str: if self._dist.rank == 0: endpoint = self._transfer_worker.rank_info_server_endpoint or "" self._dist.broadcast(endpoint, 0) return endpoint return cast(str, self._dist.broadcast(None, 0)) @staticmethod def _kv_size_rank_factor_for(mapping) -> int: """Number of TP ranks that receive each request's KV. Every TP rank receives the same number of bytes, split or replicated, so the TP total is tp_size times this rank's bytes; under attention DP one DP rank holds the request. Helix CP ranks receive different paged bytes, so CP is scaled per request (see _request_kv_bytes). """ return 1 if mapping.enable_attention_dp else max(1, mapping.tp_size) def _request_kv_bytes(self, req: LlmRequest, paged_bytes: int, state_bytes: int) -> int: """KV bytes the request's transfer moves into the TP and CP ranks of this PP stage. A metric only. The C++ transceiver can sum what every rank received, PP stages included. This computes that sum for this PP stage alone from this rank's paged and STATE bytes (_chunk_bytes_by_kind), with no collective. Both scale by the TP factor. Each CP rank also holds a STATE (recurrent) slot of the same size, so STATE bytes scale by the CP size too. Paged bytes follow the prompt blocks each CP rank holds instead (_request_paged_bytes). """ tp_paged = paged_bytes * self._kv_size_rank_factor tp_state = state_bytes * self._kv_size_rank_factor return self._request_paged_bytes(req, tp_paged) + tp_state * self._mapping.cp_size def _request_paged_bytes(self, req: LlmRequest, paged_bytes: int) -> int: """Request-total paged bytes, given this CP rank's paged bytes times the TP factor. Helix deals prompt blocks round-robin over the CP ranks, so this rank holds ceil(prompt_len / tpb) of the ceil(total_input_len_cp / tpb) blocks (prompt_len is the rank-local slice) and the shares differ by up to one block. Scaling the per-block bytes by the global block count gives the request total. A CP rank that owns no block has no paged bytes; responses come from CP rank 0, which owns block 0. """ if paged_bytes == 0 or self._mapping.cp_size == 1: return paged_bytes tpb = self._reuse_adapter.tokens_per_block local_blocks = (req.prompt_len + tpb - 1) // tpb global_blocks = (req.total_input_len_cp + tpb - 1) // tpb if local_blocks == 0: return paged_bytes return paged_bytes * global_blocks // local_blocks def _init_sync_policy(self): m = self._mapping # The ctx side never syncs over CP: helix pairs a cp=1 context instance # with a cp=N generation instance (see attention/peer.py check_peer_compatible), # so on the context side the CP group is always a single rank. self._ctx_need_tp_sync = m.tp_size > 1 and not m.enable_attention_dp self._ctx_need_pp_sync = m.pp_size > 1 if m.enable_attention_dp: # DP groups schedule independently, but the PP or helix CP ranks of # one DP group share the same requests, so gen-side consensus spans # that group (like the C++ transceiver's mGroupDataComm). Without it # a CP rank can start decoding before its partner received the KV and # the helix all-to-all deadlocks. # # Invariant: check_gen_transfer_status gathers over this group, and # besides the per-iteration poll the executor also enters it from # receive_gen_init, only on ranks that admitted gen-init requests. # The CP ranks of one DP group must therefore admit the same requests # in the same iteration. Equal KV capacity is not enough: a client # cancel or transfer timeout retires a request rank-locally, so one # CP rank can have room before its peer. The pp=1 loops intersect # the admitted ids over CP first # (DisaggTransferCoordinator.align_gen_admission_across_cp). # The PP loop does not, so _check_compatible rejects attention-DP # with both helix CP and pp_size > 1. # # Non-DP TP x CP gathers over the world. Its scheduling loop aligns # admission over both TP and CP before entering receive_gen_init. self._gen_need_sync = m.pp_size * m.cp_size > 1 self._gen_allgather: Callable = self._dp_group_allgather else: self._gen_need_sync = m.world_size > 1 self._gen_allgather = self._dist.allgather self._init_gen_idle_poll(self._gen_idle_poll_skip_applies(m, self._gen_need_sync)) self._gen_idle_probe = self._gen_idle_probe_applies(m, self._gen_need_sync) @staticmethod def _gen_idle_probe_applies(mapping: Mapping, gen_need_sync: bool) -> bool: """Whether an idle non-blocking status poll is decided by one int64 allgather. For context parallelism (helix), where the idle-poll skip does not apply: without attention DP and with one PP stage the status consensus spans the world, which is the TP x CP group the int64 allgather spans, so every rank takes the same branch. The probe is a collective every round, so ranks one round apart never split on entering one. """ return ( gen_need_sync and not mapping.enable_attention_dp and mapping.pp_size == 1 and mapping.cp_size > 1 and mapping.world_size == mapping.tp_size * mapping.cp_size ) def _any_rank_has_recv_sessions(self) -> bool: """Whether any rank of the group has a receive in progress. Counts what the full consensus would act on, as the idle-poll skip does (_consensus_outcome's local_session_count): sessions, receives admitted but not started yet, RankInfo admissions that start their session only inside _poll_rank_info_admissions, and coordinated start failures. """ local = ( len(self._recv_sessions) + self._gen_deferred_receives + len(self._pending_rank_info_admissions or {}) + len(self._rank_info_start_failures or {}) ) counts = self._dist.tp_cp_allgather_int64([local]) return bool(counts.any()) def _dp_group_allgather(self, obj): """Allgather over the CP ranks, then the PP ranks, of this DP group. Under attention-DP, _check_compatible keeps cp_size or pp_size at 1, so at most one of the two gathers runs. """ m = self._mapping gathered = list(self._dist.cp_allgather(obj)) if m.cp_size > 1 else [obj] if m.pp_size > 1: gathered = [x for part in self._dist.pp_allgather(gathered) for x in part] return gathered def _exchange_rank_info(self): endpoints = cast(list, self._dist.allgather(self._transfer_worker.sender_endpoint)) layer_num = len(self._kv_cache_manager.pp_layers) layer_num_per_pp = cast(list, getattr(self._dist, "pp_allgather")(layer_num)) self._transfer_worker.populate_instance_and_rank_info( endpoints=endpoints, layer_num_per_pp=layer_num_per_pp ) logger.info(f"transfer worker ctx_server_endpoints: {endpoints}") logger.info(f"layer_num_per_pp: {layer_num_per_pp}") logger.info(f"self._context_info_endpoint: {self._context_info_endpoint}") def get_status_dump(self) -> str: """Return a one-line summary of transceiver state for debugging hangs.""" def summarize( sessions: Dict[int, Any], include_receiver_ready: bool, ) -> str: sessions_snapshot = list(sessions.values()) status_counts = Counter() receiver_ready = 0 for session in sessions_snapshot: status = session.status if isinstance(status, SessionStatus): status_counts[status] += 1 else: status_counts["unknown"] += 1 if include_receiver_ready: receiver_ready += int(bool(session.receiver_ready)) fields = [ f"sessions={len(sessions_snapshot)}", f"init={status_counts[SessionStatus.INIT]}", f"ready_to_transfer={status_counts[SessionStatus.READY]}", f"transferring={status_counts[SessionStatus.TRANSFERRING]}", f"transferred={status_counts[SessionStatus.TRANSFERRED]}", f"error={status_counts[SessionStatus.ERROR]}", f"cancelled={status_counts[SessionStatus.CANCELLED]}", f"unknown={status_counts['unknown']}", ] if include_receiver_ready: fields.append(f"peer_ready={receiver_ready}/{len(sessions_snapshot)}") return ", ".join(fields) tx_status = summarize(self._send_sessions, include_receiver_ready=True) rx_status = summarize(self._recv_sessions, include_receiver_ready=False) return ( f"KV cache transceiver | backend=NIXL | TX({tx_status}) | RX({rx_status}) | " f"waiting_for_peer_info={len(self._wait_reqs)}" ) def _get_shutdown_lock(self) -> threading.Lock: """Return the shutdown lock, including after partial initialization.""" lock = getattr(self, "_shutdown_lock", None) if lock is None: lock = threading.Lock() self._shutdown_lock = lock return lock def prepare_shutdown(self) -> None: """Retire sessions and stop transfers without deregistering the KV pools.""" with self._get_shutdown_lock(): if getattr(self, "_shutdown_complete", False): return self._close_sessions_for_shutdown() self._transfer_worker.prepare_shutdown() def shutdown(self) -> None: with self._get_shutdown_lock(): self._shutdown_once() def _shutdown_once(self) -> None: if getattr(self, "_shutdown_complete", False): return self._close_sessions_for_shutdown() self._transfer_worker.shutdown() # Record completion only after every owner and worker has shut down. # A refusal leaves shutdown retryable after the physical operation drains. self._shutdown_complete = True def _close_sessions_for_shutdown(self) -> None: # Preflight may refuse closure while DMA remains active. Start the # bounded drain before that refusal, not only in worker.prepare_shutdown(). self._transfer_worker.request_shutdown() for rid in list(getattr(self, "_cancelled_receive_fences", {})): if not self._retire_cancelled_receive_fence(rid): raise RuntimeError(f"Unpublished receive {rid} still owns destination memory") # Close receive owners before touching send-side or worker state. The # separate drain snapshot would not be sufficient: late evidence can make an # owner unretirable before close() acquires its lock. for rid, session in list(self._recv_sessions.items()): if getattr(session, "_retirement", None) is not None: # Close unpublished admission before inspecting drain state. # Published accessors remain retained; do not notify peers here. session.cancel_local() self._close_session_or_raise(session, rid, "shutdown") for rid, session in list(self._send_sessions.items()): self._close_session_or_raise(session, rid, "shutdown") self._send_sessions.clear() self._send_reqs.clear() self._recv_sessions.clear() self._recv_reqs.clear() if self._pending_rank_info_admissions is not None: self._pending_rank_info_admissions.clear() self._rank_info_start_failures = None def __enter__(self): return self def __exit__(self, _exc_type, _exc_val, _exc_tb): self.shutdown() def _get_mamba_slot_for_request(self, req: LlmRequest) -> Optional[int]: """Get the mamba state slot index for a request, or None.""" if isinstance(self._kv_cache_manager, MambaHybridCacheManagerV2): if self._kv_cache_manager.local_num_mamba_layers > 0: return self._kv_cache_manager._request_id_to_state_index[req.py_request_id] return None def _create_chunk(self, req: LlmRequest) -> Chunk: """Just the blocks, for the callers that have no use for the rest of the extent.""" return self._describe_local(req) def _create_cache_extent(self, req: LlmRequest) -> CacheExtent: """This request's whole prompt as the sole piece of a transfer, under the name it is registered by.""" rid = get_unique_rid(req) assert rid is not None return CacheExtent(name=rid, local=self._describe_local(req)) def _describe_local(self, req: LlmRequest) -> Chunk: """The blocks this rank holds, one list per layer group. Every paged group gets ``ceil(prompt_len / tpb)`` entries indexed by block ordinal: the local pool slot, or -1 where this side has nothing there. Eviction and allocation state come straight from the cache manager (``get_block_ordinals``), so ctx and gen never have to agree on *when* a block left the window -- the sender simply pairs the ordinals both sides still hold. The only request-derived bound is prompt_len, which drops the speculative tail and the ctx first-token block (num_extra_kv_tokens slots are not transferred; both sides use prompt_len, so the ranges stay consistent). On the receiver the already-cached prefix is masked so the sender skips it. A STATE group carries one slot, or nothing when this rank has none. """ adapter = self._reuse_adapter tpb = adapter.tokens_per_block assert self._page_table is not None layer_groups = self._page_table.layer_groups remote_tail_start = getattr(req, "py_csa2_remote_tail_start", None) transfer_len = remote_tail_start if remote_tail_start is not None else req.prompt_len prompt_blocks = (transfer_len + tpb - 1) // tpb remote_tail_split = getattr(req, "py_csa2_remote_tail_split", None) excluded_pool_views = set() if remote_tail_split is not None: exclude = getattr(self._kv_cache_manager, "remote_tail_excluded_pool_views", None) if exclude is None: raise ValueError("remote-tail replay requires a CSA2 cache manager") excluded_pool_views = exclude(self._page_table, remote_tail_split) is_gen_only = req.is_generation_only_request cached_per_lg = ( adapter.get_cached_token_count_per_layer_group(req, layer_groups) if is_gen_only else [0] * len(layer_groups) ) empty = np.array([], dtype=np.int64) groups = [] kinds = [lg.kind for lg in layer_groups] for idx, lg in enumerate(layer_groups): if lg.kind == CacheKind.STATE: slot = self._get_mamba_slot_for_request(req) if lg.pool_views else None group = np.array([slot], dtype=np.int64) if slot is not None else empty else: # Block lists carry beam 0 only (beam-search attention reads # prompt positions through beam 0's block table), so the # positional path applies to every beam width. ordinals = adapter.get_block_ordinals(req, idx, lg) group = self._positional_window(ordinals, prompt_blocks, cached_per_lg[idx] // tpb) groups.append(group) return Chunk( block_ids_per_layer_groups=groups, kind_per_layer_group=kinds, token_range=TokenRange(start=0, end=transfer_len), is_last=True, excluded_pool_views=excluded_pool_views, ) @staticmethod def _positional_window( ordinals: np.ndarray, prompt_blocks: int, cached_blocks: int ) -> np.ndarray: """Fit a manager block table into the prompt's ordinal range. Pads with -1 when fewer blocks are allocated than the prompt spans (incremental ctx allocation), truncates the speculative / first-token tail, and masks the receiver's cached prefix. """ window = np.full(prompt_blocks, -1, dtype=np.int64) n = min(int(ordinals.size), prompt_blocks) window[:n] = ordinals[:n] window[: min(cached_blocks, prompt_blocks)] = -1 return window @staticmethod def _need_aux_transfer(req: LlmRequest) -> bool: params = req.py_disaggregated_params return params is not None and params.schedule_style == DisaggScheduleStyle.GENERATION_FIRST def _validate_bridge_req(self, req: LlmRequest, synchronous: bool = False) -> bool: params = req.py_disaggregated_params fp4_bridge = getattr(self, "_fp4_mla_bridge_enabled", False) context_first = ( getattr(self, "_context_first_ownership", False) and params is not None and params.schedule_style == DisaggScheduleStyle.CONTEXT_FIRST ) if not fp4_bridge and not context_first: return True required_schedule = ( DisaggScheduleStyle.GENERATION_FIRST if fp4_bridge else DisaggScheduleStyle.CONTEXT_FIRST ) rid = None if params is None else params.disagg_request_id if ( synchronous or params is None or params.schedule_style != required_schedule or type(rid) is not int or rid < 0 ): logger.error( f"KV ownership requires async {required_schedule.name} requests " "with a non-negative integer disagg_request_id" ) req.state = LlmRequestState.DISAGG_TRANS_ERROR return False if context_first and not self._context_first_ownership_logged: logger.info( "Context-first BF16 KV ownership ENABLED: " f"rank={self._mapping.rank}/{self._mapping.world_size}, " "backend=NIXL/UCX, runtime=PYTHON, attention_dp=False, pp=1, cp=1, " "retry=False, async=True, layerwise=False, bounce_mb=0, " "unproven_retirement=fail_stop, termination_scope=mpi_job_or_launcher; " "MPI abort may terminate other CTX/GEN executors in the same launcher job" ) self._context_first_ownership_logged = True return True def _ctx_consensus(self, local_ids: list) -> list: # TP consensus: ensure all TP ranks have peer info sync_size = self._dist.tp_size if self._ctx_need_tp_sync else 1 all_ranks = self._dist.tp_allgather(local_ids) if self._ctx_need_tp_sync else [local_ids] ready_ids = _find_consensus_request_ids(all_ranks, sync_size) # PP consensus: ensure all PP ranks have peer info before promoting. # In PP, the first PP rank schedules and propagates to others. If a # request is promoted on the first rank but peer info hasn't arrived # on other ranks, respond_and_send_async on those ranks would fail # to dispatch the KV transfer (gen-first skips listener dispatch). # TODO: This is a workaround for functionality: pp_allgather impacts # the pp loop performance. One possible solution is to let pp rank0 # decide the ready request ids, the other pp ranks treat the unready # request as ctx-first requests. if self._ctx_need_pp_sync: pp_all_ranks = getattr(self._dist, "pp_allgather")(ready_ids) ready_ids = _find_consensus_request_ids(pp_all_ranks, self._mapping.pp_size) return ready_ids def _gen_consensus(self, local_ids: list) -> list: if not self._gen_need_sync: return list(local_ids) all_ranks = self._gen_allgather(local_ids) return _find_consensus_request_ids(all_ranks, len(all_ranks)) @staticmethod def _union(all_lists: List[List[int]]) -> set: merged: set = set() for ids in all_lists: merged.update(ids) return merged @staticmethod def _intersection(all_lists: List[List[int]], n_ranks: int) -> set: if n_ranks == 0: return set() cnt: Dict[int, int] = defaultdict(int) for ids in all_lists: for rid in set(ids): cnt[rid] += 1 return {rid for rid, c in cnt.items() if c == n_ranks} def _consensus_outcome( self, to_process, cancelled, failed, completed, allgather: Callable, need_sync: bool, locally_quiesced=None, locally_verified=None, local_session_count: Optional[int] = None, ): # CANCELLED/FAILED on any rank → global; COMPLETED only when ALL ranks agree. # Quiescence and write-verification, when requested, also require # agreement from every rank. # Batch the id lists into one allgather to cut the per-step collective count. # With local_session_count, the payload also carries each rank's # receive-session count and the result ends with whether every rank # reported zero sessions. local_outcome = [list(cancelled), list(failed), list(completed)] if locally_quiesced is not None: local_outcome.append(list(locally_quiesced)) if locally_verified is not None: local_outcome.append(list(locally_verified)) if local_session_count is not None: local_outcome.append([local_session_count]) if not need_sync: packed = [local_outcome] else: packed = list(allgather(local_outcome)) all_c = [p[0] for p in packed] all_f = [p[1] for p in packed] all_done = [p[2] for p in packed] n = len(all_c) global_cancelled = self._union(all_c) global_failed = self._union(all_f) global_completed = self._intersection(all_done, n) new_cancelled = [rid for rid in to_process if rid in global_cancelled] cancel_set = set(new_cancelled) new_failed = [rid for rid in to_process if rid in global_failed and rid not in cancel_set] terminal = cancel_set | set(new_failed) new_completed = [ rid for rid in to_process if rid in global_completed and rid not in terminal ] result = [new_cancelled, new_failed, new_completed] idx = 3 if locally_quiesced is not None: all_quiesced = [p[idx] for p in packed] idx += 1 global_quiesced = self._intersection(all_quiesced, n) result.append([rid for rid in to_process if rid in global_quiesced]) if locally_verified is not None: # Per-rank reuse trees stay consistent only if every rank admits # the same tokens, so a request counts as write-verified only # when EVERY rank verified its local shard. all_verified = [p[idx] for p in packed] idx += 1 global_verified = self._intersection(all_verified, n) result.append({rid for rid in to_process if rid in global_verified}) if local_session_count is not None: result.append(all(p[idx][0] == 0 for p in packed)) return tuple(result) def _gen_consensus_outcome(self, to_process, cancelled, failed, completed, locally_verified): # A failure/cancellation may be global, but reuse is safe only after # every participating rank has drained its local physical accessor. locally_retirable = [] for rid in to_process: # A coordinated start failure may precede session creation on this rank. session = self._recv_sessions.get(rid) if not self._retirement_blocked(session): locally_retirable.append(rid) idle_skip = self._gen_idle_poll_skip deferred = self._gen_deferred_receives pending_admissions = len(self._pending_rank_info_admissions or {}) outcome = self._consensus_outcome( to_process, cancelled, failed, completed, self._gen_allgather, self._gen_need_sync, locally_retirable, locally_verified, local_session_count=( len(self._recv_sessions) + deferred + pending_admissions if idle_skip else None ), ) new_cancelled, new_failed, new_completed, globally_retirable, verified = outcome[:5] if idle_skip: # Every rank derives this from the same gathered payload. self._gen_idle_agreed = outcome[5] retirable = set(globally_retirable) return ( [rid for rid in new_cancelled if rid in retirable], [rid for rid in new_failed if rid in retirable], new_completed, verified, ) def _ctx_consensus_outcome(self, to_process, cancelled, failed, completed, locally_quiesced): # TP first, then PP. A local timeout remains nonterminal, so it is # represented by the absence of that request from completed. c, f, d, q = self._consensus_outcome( to_process, cancelled, failed, completed, self._dist.tp_allgather, self._ctx_need_tp_sync, locally_quiesced, ) if self._ctx_need_pp_sync: pp_allgather: Callable = getattr(self._dist, "pp_allgather") c, f, d, q = self._consensus_outcome(to_process, c, f, d, pp_allgather, True, q) return c, f, d, q def _sync_transfer_timing(self, reqs: list): """Allgather timing for a batch of completed requests in one collective. Matches C++ ``batchUpdateKVCacheTransferBW()`` in ``cacheTransceiver.cpp``. Only runs when ``TRTLLM_KVCACHE_TIME_OUTPUT_PATH`` is set (same gate as C++) and multi-rank sync is needed. All ranks that participate in the allgather update their local request objects. """ if not reqs: return if not os.getenv("TRTLLM_KVCACHE_TIME_OUTPUT_PATH"): return if not self._gen_need_sync: return # Pack local timing for all completed requests into one dict. local_data = { get_unique_rid(req): ( req.get_kv_cache_transfer_start(), req.get_kv_cache_transfer_end(), req.kv_cache_size, ) for req in reqs } # Single allgather for the whole batch. all_data = self._gen_allgather(local_data) # Merge: per-rid min(start), max(end), sum(size) across ranks. merged: dict = {} for rank_data in all_data: for rid, (start, end, size) in rank_data.items(): if rid in merged: prev = merged[rid] merged[rid] = ( min(prev[0], start), max(prev[1], end), prev[2] + size, ) else: merged[rid] = (start, end, size) # Every rank updates its own local requests. rid_to_req = {get_unique_rid(r): r for r in reqs} for rid, (min_start, max_end, total_size) in merged.items(): req = rid_to_req.get(rid) if req is not None: req.set_kv_cache_transfer_start(min_start) req.set_kv_cache_transfer_end(max_end) req.set_kv_cache_size(total_size) def _collect_done(self, sessions: dict, reqs: dict): """Scan sessions and return (completed_rids, failed_rids).""" completed, failed = [], [] for rid, session in sessions.items(): if session.is_completed(): completed.append(rid) elif session.has_failed(): if self._ownership_blocks_retirement(session): if isinstance(session, RxSession): try: session.notify_cancel() except RuntimeError as error: # Notification failure is not retirement evidence. # Keep the owner under its original grace deadline. logger.warning( f"Receive {rid} cancellation notification failed; " f"retaining resources and retrying: {error}\n{traceback.format_exc()}" ) continue if self._retirement_blocked(session): continue failed.append(rid) return completed, failed def _build_to_process( self, sessions: dict, consensus: list, wait_num: int, block_all: bool ) -> list: if block_all: return list(sessions.keys()) to_process = list(consensus) for rid in sessions: if len(to_process) >= wait_num: break if rid not in to_process: to_process.append(rid) return to_process def _close_failed_sessions( self, sessions: dict, reqs: dict, failed: list, mark_retired: bool = False ): for rid in failed: session = sessions.get(rid) if session is None: continue self._close_session_or_raise(session, rid, "failed") req = reqs.pop(rid, None) if req is not None: if not mark_retired: req.state = LlmRequestState.DISAGG_TRANS_ERROR else: req.py_kv_send_session_retired = True sessions.pop(rid, None) def _retire_send_session( self, rid: int, req: Optional[LlmRequest] = None, *, outcome: str = "retired", session_already_closed: bool = False, ) -> None: """Close a send session and prevent later chunks from recreating it.""" session = self._send_sessions.get(rid) if session is not None and not session_already_closed: if getattr(session, "_enforce_physical_ownership", False): self._close_session_or_raise(session, rid, outcome) else: session.close() self._send_sessions.pop(rid, None) # Early teardown may occur before _send_reqs is populated. req = req if req is not None else self._send_reqs.get(rid) self._send_reqs.pop(rid, None) if req is not None: req.py_kv_send_session_retired = True @staticmethod def _ownership_blocks_retirement(session: object) -> bool: """Whether a session still holds physical transfer resources.""" if isinstance(session, TxSession) and not session.resources_drained(): return True if not getattr(session, "_enforce_physical_ownership", False): return False resources_drained = getattr(session, "resources_drained", None) return resources_drained is None or not resources_drained() @classmethod def _retirement_blocked(cls, session: object) -> bool: """Whether a terminal session must stay open for an accessor that may still be active. Besides ownership-held resources, this covers a failed receive whose other writers have not all reported yet (see ``RxSession.failed_receive_awaits_writers``). """ if cls._ownership_blocks_retirement(session): return True return isinstance(session, RxSession) and session.failed_receive_awaits_writers() def _close_session_or_raise(self, session: object, rid: int, outcome: str) -> None: """Close one terminal session or fail-stop instead of diverging locally.""" if self._ownership_blocks_retirement(session): raise RuntimeError( f"refusing to retire {outcome} KV transfer rid={rid}: " "physical resources remain active" ) if session.close() is False: raise RuntimeError( f"refusing to retire {outcome} KV transfer rid={rid}: session close refused" ) def _emit_transfer_settled( self, side: str, rid: Optional[int], req: Optional[LlmRequest], session: Optional[object], outcome: str, ) -> None: """Report session retirement, not physical drain, without polling state.""" with disagg_diagnostics.suppress_diagnostic_errors(): request_id_scope = "unknown" if req is not None: rid = disagg_diagnostics.get_request_id(req) request_id_scope = disagg_diagnostics.get_request_id_scope( req.py_disaggregated_params ) elif session is not None: rid = session.disagg_request_id request_id_scope = disagg_diagnostics.get_request_id_scope( session._base_args.params ) disagg_diagnostics.emit_event( f"{side}_transfer_settled", side=side, request_id=rid, request_id_scope=request_id_scope, local_request_id=(req.py_request_id if req is not None else None), rank=self._mapping.rank, instance=self._instance_name, outcome=outcome, session_retired=True, tp_rank=self._mapping.tp_rank, pp_rank=self._mapping.pp_rank, cp_rank=self._mapping.cp_rank, dp_rank=self._dp_rank, ) def _emit_receive_start( self, req: LlmRequest, transfer_bytes: int, *, timeout_expected: bool ) -> None: """Record the receive publication boundary using existing payload metadata.""" with disagg_diagnostics.suppress_diagnostic_errors(): disagg_diagnostics.emit_request_event( "gen_receive_start", req, side="gen", dist=self._mapping, instance=self._instance_name, slice_id=0, transfer_bytes=transfer_bytes, timeout_expected=timeout_expected, dp_rank=self._dp_rank, ) def _apply_aux(self, session, req: LlmRequest): """Unpack aux tokens from session into request's context_phase_params.""" session.unpack_aux(req) first_gen_tokens = req.py_first_gen_tokens # type: ignore[attr-defined] draft_tokens = req.py_draft_tokens if req.context_phase_params is None: assert req.py_request_id is not None req.context_phase_params = ContextPhaseParams( first_gen_tokens=first_gen_tokens, req_id=req.py_request_id, opaque_state=b"", draft_tokens=draft_tokens, ctx_dp_rank=0, disagg_info_endpoint="", ) else: req.context_phase_params.first_gen_tokens = first_gen_tokens req.context_phase_params.draft_tokens = draft_tokens def _get_or_create_send_session(self, req: LlmRequest) -> Optional[TxSessionBase]: self._ever_had_send_session = True rid = get_unique_rid(req) assert rid is not None if rid not in self._send_sessions: if req.py_kv_send_session_retired: logger.warning( f"rid={rid}: send session already retired; failing the request " "rather than re-creating one with no peer registration" ) req.state = LlmRequestState.DISAGG_TRANS_ERROR return None self._send_sessions[rid] = self._transfer_worker.create_tx_session(req) return self._send_sessions[rid] def _finalize_send(self, req: LlmRequest, session: TxSessionBase): """Pack aux and set context phase params. Call after the last slice.""" rid = get_unique_rid(req) assert rid is not None if self._need_aux_transfer(req): session.pack_aux(req) session.send_aux() req.context_phase_params = ContextPhaseParams( first_gen_tokens=[], req_id=rid, opaque_state=None, draft_tokens=None, ctx_dp_rank=self._dp_rank, disagg_info_endpoint=self._context_info_endpoint, ) self._send_reqs[rid] = req @property def pipeline_transfer_enabled(self) -> bool: """Whether pipelined prefill-transfer is enabled.""" return self._enable_pipelined_transfer def has_inflight_transfer(self, req: LlmRequest) -> bool: """Whether a transfer session or cancelled admission fence retains resources.""" rid = get_unique_rid(req) return ( rid in self._send_sessions or rid in self._recv_sessions or rid in getattr(self, "_cancelled_receive_fences", {}) ) def context_transfer_is_waiting_for_peer(self, req: LlmRequest) -> bool: # Waiting until every peer rank's REQUEST_DATA has arrived (receiver_ready), # even while the ranks that already asked are being written. A retired, # cancelled or failed send is not waiting and must time out normally. session = self._send_sessions.get(get_unique_rid(req)) if session is None or session.status in (SessionStatus.ERROR, SessionStatus.CANCELLED): return False return not session.receiver_ready def context_transfer_peer_ready_time(self, req: LlmRequest) -> Optional[float]: session = self._send_sessions.get(get_unique_rid(req)) return None if session is None else getattr(session, "peer_ready_time", None) def has_retired_send_session(self, req: LlmRequest) -> bool: """Whether req's send session was torn down before its last slice.""" return req.py_kv_send_session_retired and get_unique_rid(req) not in self._send_sessions def _build_prefill_extent( self, req: LlmRequest, ) -> Optional[CacheExtent]: """Build an extent for completed prefill blocks, or None.""" assert req.py_beam_width == 1, "beam_width > 1 is not supported for chunked KV transfer" rid = get_unique_rid(req) assert rid is not None self._send_reqs[rid] = req chunk_start_pos, chunk_end_pos = req.py_last_context_chunk tpb = self._kv_cache_manager.tokens_per_block # Include any reused prefix in the first transferred chunk. is_first_chunk = chunk_start_pos == req.prepopulated_prompt_len is_last_chunk = req.context_remaining_length == 0 # Defer partial blocks except at the prompt's final chunk. chunk_start = 0 if is_first_chunk else chunk_start_pos // tpb chunk_end = (chunk_end_pos + tpb - 1) // tpb if is_last_chunk else chunk_end_pos // tpb # The final chunk is sent even when it contains no complete block. if chunk_end <= chunk_start and not is_last_chunk: return None whole = self._describe_local(req) all_block_ids = whole.block_ids_per_layer_groups chunk_block_ids = [] assert self._page_table is not None for lg, block_ids in zip(self._page_table.layer_groups, all_block_ids): window_size = getattr(lg, "sliding_window_size", None) if window_size is not None and window_size < req.prompt_len: # SWA pages can leave the active window between chunks. Defer # the group and send its complete final active window at once. chunk_block_ids.append(block_ids if is_last_chunk else np.full_like(block_ids, -1)) else: # Positional: keep the chunk's ordinals, blank everything else. chunk = np.full_like(block_ids, -1) chunk[chunk_start:chunk_end] = block_ids[chunk_start:chunk_end] chunk_block_ids.append(chunk) if not is_last_chunk and not any((ids >= 0).any() for ids in chunk_block_ids): return None # The block window is rounded up; the span this piece delivers is not. Every reader below # rounds back to blocks, and a recurrent-state group reads the end as an exact checkpoint. chunk_end_token = min(chunk_end * tpb, req.prompt_len) if is_last_chunk else chunk_end * tpb return CacheExtent( name=rid, local=Chunk( block_ids_per_layer_groups=chunk_block_ids, kind_per_layer_group=whole.kind_per_layer_group, token_range=TokenRange(start=chunk_start * tpb, end=chunk_end_token), is_last=is_last_chunk, excluded_pool_views=whole.excluded_pool_views, ), ) @nvtx_range("KvCacheTransceiverV2.respond_and_send_async") def respond_and_send_async(self, req: LlmRequest) -> None: """Send the request's next KV slice to the generation server.""" if not self._validate_bridge_req(req): return self._ever_had_send_session = True # Keep the latest slice's transfer-start timestamp. req.set_kv_cache_transfer_start(tensorrt_llm.bindings.global_steady_clock_now()) rid = get_unique_rid(req) assert rid is not None session = self._get_or_create_send_session(req) if session is None: return bridge_enabled = getattr(session, "_enforce_physical_ownership", False) if bridge_enabled: # Root the request before backend admission so its source pages # outlive every ownership-enabled NIXL operation. self._send_reqs[rid] = req req.state = LlmRequestState.DISAGG_CONTEXT_TRANS_IN_PROGRESS # A remote cancellation can win before the local TxSession is # created. Sender.setup_session() records that terminal state and # acknowledges the fenced session to every known receiver; # leave retirement to the normal status path without attempting # to publish KV or auxiliary memory afterward. if session.has_failed(): return try: if self.pipeline_transfer_enabled: extent = self._build_prefill_extent(req) if extent is None: return else: extent = self._create_cache_extent(req) chunk = extent.local # The handle that comes back is the contract's answer about this piece. What retires # the request is the sweep over the session tables, as it was before. PeerPublish(session, req).publish(extent) if chunk.is_last: self._finalize_send(req, session) if not bridge_enabled: # Preserve the legacy pipelined-transfer state boundary: # intermediate chunks must remain schedulable for prefill. req.state = LlmRequestState.DISAGG_CONTEXT_TRANS_IN_PROGRESS except Exception as error: if bridge_enabled: cast(Any, session).set_exception(f"transfer admission failed: {error}") raise @nvtx_range("KvCacheTransceiverV2.request_and_receive_sync") def request_and_receive_sync(self, req: LlmRequest) -> None: # Before anything that can return or raise: every rank requests the # same receives, so they all resume status polling together. self._gen_idle_agreed = False if self._pending_rank_info_admissions is not None: # Synchronous receives enter in the same admitted-request order on # every generation rank, without rank-local CUDA-fence deferral. # Agree before publication: a rejected rank cannot supply its shard. error = None try: self._transfer_worker.prepare_rank_info(req) except Exception as exc: error = str(exc) errors = self._gen_allgather(error) if any(error is not None for error in errors): logger.error(f"Synchronous RankInfo admission failed: {errors}") req.state = LlmRequestState.DISAGG_TRANS_ERROR return if not self._validate_bridge_req(req, synchronous=True): return rid = get_unique_rid(req) self._ever_had_recv_session = True if rid in self._recv_sessions: logger.warning( f"request_and_receive_sync: rid={rid} already has a recv session, skipping" ) return req.state = LlmRequestState.DISAGG_GENERATION_TRANS_IN_PROGRESS session = None fetches = None receive_started = False settlement_outcome = None try: extent = self._create_cache_extent(req) paged_bytes, state_bytes = _chunk_bytes_by_kind(self._page_table, extent.local) fetches = self._open_peer_source(req) if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: with disagg_diagnostics.suppress_diagnostic_errors(): diagnostic_transfer_bytes = self._request_kv_bytes( req, paged_bytes, state_bytes ) self._emit_receive_start(req, diagnostic_transfer_bytes, timeout_expected=False) receive_started = True # Same submission the asynchronous entry makes; what differs is who waits. The session # underneath is read back for the blocking wait, the auxiliary buffer and the close. fetches.fetch(extent, expected_write_bytes=paged_bytes + state_bytes) session = self._legacy_session(fetches) self._recv_sessions[rid] = session self._recv_reqs[rid] = req result = session.wait_complete(blocking=True) if result == WaitResult.COMPLETED: # Verified-range reuse admission (local verdict; this # blocking path has no cross-rank outcome consensus). req.py_kv_transfer_verified = session.kv_write_verified() # KV-transfer timing setters deferred to #15871 (clock-source consistency); size only. req.set_kv_cache_size(self._request_kv_bytes(req, paged_bytes, state_bytes)) if self._need_aux_transfer(req): self._apply_aux(session, req) self._assert_disagg_history_declared(req) req.state = LlmRequestState.DISAGG_GENERATION_TRANS_COMPLETE settlement_outcome = "completed" else: req.state = LlmRequestState.DISAGG_TRANS_ERROR settlement_outcome = "failed" except Exception: req.state = LlmRequestState.DISAGG_TRANS_ERROR settlement_outcome = "failed" raise finally: # The adapter opens the session before it submits, so a submission that raises leaves # one to close while the local above is still unassigned; read it back off the adapter. if session is None and fetches is not None: session = self._legacy_session(fetches) close_succeeded = session is None or session.close() is not False if close_succeeded: self._recv_sessions.pop(rid, None) self._recv_reqs.pop(rid, None) if ( disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED and receive_started and settlement_outcome is not None ): self._emit_transfer_settled("gen", rid, req, session, settlement_outcome) else: logger.error( f"request_and_receive_sync: retaining rid={rid} because receive " "resources remain active" ) def _open_peer_source(self, req: LlmRequest) -> PeerFetch: """The paired backend: pull this request's cache from the worker that ran its context.""" return PeerFetch(self._transfer_worker, req) @staticmethod def _legacy_session(fetches: PeerFetch): """The native session under the adapter, for the sweep that retires it and for the auxiliary buffer. Named as the escape hatch it is: both jobs are the reason the contract does not cover everything here yet. """ return fetches.session def set_gen_deferred_receives(self, count: int) -> None: """Report the admitted receives whose start the caller defers. The disagg coordinator starts each admitted receive only once that rank's admission readiness event completes, so ranks start the same receive in different iterations, while admission is the same on every rank. A nonzero count clears the idle-poll agreement on every rank in the admitting iteration, and the count joins the session count of the idle check, so no rank agrees it is idle while a peer still has a receive to start (the start would clear the flag on that rank only and send it into a status collective its peers skip). """ if count: self._gen_idle_agreed = False self._gen_deferred_receives = count @nvtx_range("KvCacheTransceiverV2.request_and_receive_async") def request_and_receive_async(self, req: LlmRequest) -> None: """Start background KV cache receive from the context server. The receiver always uses a single monolithic slice. Chunking is sender-only: the sender splits its source blocks into chunks and slices the receiver's destination blocks to match each chunk. Args: req: The generation request whose KV cache blocks to receive into. """ # Before anything that can return or raise: every rank requests the # same receives, so they all resume status polling together. self._gen_idle_agreed = False if not self._validate_bridge_req(req): return self._ever_had_recv_session = True req.set_kv_cache_transfer_start(tensorrt_llm.bindings.global_steady_clock_now()) rid = get_unique_rid(req) if rid in self._recv_sessions: logger.warning( f"request_and_receive_async: rid={rid} already has a recv session, skipping" ) return pending = self._pending_rank_info_admissions if pending is not None: if rid not in pending: error = None try: self._transfer_worker.prepare_rank_info(req) except Exception as exc: # Network/decoding failures must also reach the symmetric # poll instead of skipping a collective on this rank. error = str(exc) pending[rid] = (req, error) req.state = LlmRequestState.DISAGG_GENERATION_TRANS_IN_PROGRESS return self._start_async_receive(req) def _poll_rank_info_admissions(self, local_done: list[int]) -> tuple[list[int], list[int]]: pending = self._pending_rank_info_admissions if pending is None: return self._gen_consensus(local_done), [] # Piggyback on the existing status collective, including ranks whose # CUDA fence has not admitted any local receive yet. votes = self._gen_allgather( (local_done, {rid: error for rid, (_, error) in pending.items()}) ) done = _find_consensus_request_ids([vote[0] for vote in votes], len(votes)) admissions = [vote[1] for vote in votes] ready = set.intersection(*(set(vote) for vote in admissions)) failed = [] started = {} start_errors = {} for rid in sorted(ready): req, _ = pending.pop(rid) error = next((vote[rid] for vote in admissions if vote[rid] is not None), None) if error is not None: logger.error(f"RankInfo admission failed for request {rid}: {error}") req.state = LlmRequestState.DISAGG_TRANS_ERROR failed.append(rid) else: started[rid] = req try: self._start_async_receive(req) except Exception as exc: start_errors[rid] = str(exc) req.state = LlmRequestState.DISAGG_GENERATION_TRANS_IN_PROGRESS if started: # Every rank starts the same admitted IDs. Even a failure before session # creation must reach this vote and the subsequent outcome collective. errors_by_rank = self._gen_allgather(start_errors) for rid in sorted(set().union(*(errors.keys() for errors in errors_by_rank))): error = next(errors[rid] for errors in errors_by_rank if rid in errors) logger.error(f"Receive start failed for request {rid}: {error}") if self._rank_info_start_failures is None: self._rank_info_start_failures = {} self._rank_info_start_failures[rid] = started[rid] session = self._recv_sessions.get(rid) if session is not None: session.fail_admission(RuntimeError(error)) return done, failed def _start_async_receive(self, req: LlmRequest) -> None: rid = get_unique_rid(req) extent = self._create_cache_extent(req) paged_bytes, state_bytes = _chunk_bytes_by_kind(self._page_table, extent.local) req.py_kv_cache_xfer_bytes = self._request_kv_bytes(req, paged_bytes, state_bytes) fetches = self._open_peer_source(req) # Claimed to be transferring only once there is something to transfer: a builder that # raises above leaves the request where it was, not in a state nothing advances. req.state = LlmRequestState.DISAGG_GENERATION_TRANS_IN_PROGRESS # Root the destination before publication can escape. Registering only on success leaves a # failed publication as a session the sweep can see but cannot pair with a request. self._recv_reqs[rid] = req try: if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: with disagg_diagnostics.suppress_diagnostic_errors(): self._emit_receive_start( req, req.py_kv_cache_xfer_bytes, timeout_expected=self.kv_transfer_timeout_ms is not None, ) # The handle that comes back is the contract's answer about this piece. What retires # the request is the sweep over the session tables, as it was before. fetches.fetch(extent, expected_write_bytes=paged_bytes + state_bytes) except Exception: # No session means no publication and nothing the sweep could ever pair the request # with, so the registration made here is undone here and the request goes terminal. if self._legacy_session(fetches) is None: del self._recv_reqs[rid] req.state = LlmRequestState.DISAGG_TRANS_ERROR raise finally: # The session exists even when publication failed, and the legacy sweep owns it. session = self._legacy_session(fetches) if session is not None: self._recv_sessions[rid] = session @staticmethod def _describe_timeout_session(session: TxSessionBase | RxSessionBase | None) -> str: """Read optional native progress without changing timeout handling. Args: session: Existing local transfer session, if still retained. Returns: Local progress or an explicit unavailable reason. """ if isinstance(session, (TxSession, RxSession)): try: return session._timeout_progress_description() except Exception: # noqa: BLE001 - Reporting must not change timeout handling. return "progress_at_observation=unavailable(snapshot_failed)" reason = "session_not_found" if session is None else "alternate_session" return f"progress_at_observation=unavailable({reason})" def _describe_transfer_timeout(self, req: LlmRequest) -> str: """Describe local progress for an executor-owned timeout observation. Args: req: Request whose existing executor clock expired. Returns: Best-effort native progress; no deadline or backend is polled. """ rid = get_unique_rid(req) sessions = self._send_sessions if req.is_context_only_request else self._recv_sessions return self._describe_timeout_session(sessions.get(rid)) def check_context_transfer_status( self, at_least_request_num: Optional[int], mark_complete: bool = False ) -> CtxTransferStatus: # A worker that never sends KV has nothing to reconcile here, so skip the consensus. Safe # because the flag flips together on every rank and never resets, so they all skip in step; # gating on the live session dict instead would not be, since a cancel clears it per-rank. # Keep the original sweep (only when tp/pp sync is on) so nothing is leaked. if not self._ever_had_send_session: if self._ctx_need_tp_sync or self._ctx_need_pp_sync: self._transfer_worker.sweep_stale_req_infos() return CtxTransferStatus([], []) block_all = at_least_request_num is None wait_num = at_least_request_num if not block_all else 0 need_progress = wait_num > 0 if need_progress: self._poll_sessions_for_interval( self._send_sessions, self._send_reqs, wait_num, self._sender_future_timeout_ms, ) local_completed, local_failed = self._collect_done(self._send_sessions, self._send_reqs) to_process = self._build_to_process( self._send_sessions, self._ctx_consensus(local_completed + local_failed), 0 if need_progress else wait_num, block_all, ) completed, failed, cancelled = [], [], [] for rid in to_process: session = self._send_sessions[rid] result = session.wait_complete(blocking=block_all) if session.status == SessionStatus.CANCELLED: if getattr(session, "_enforce_physical_ownership", False) and ( session.has_transferring_tasks() ): continue cancelled.append(rid) elif result == WaitResult.COMPLETED: completed.append(rid) elif result is None: continue elif result == WaitResult.TIMEOUT: logger.warning( f"TxSession rid={session.disagg_request_id} exceeded " f"kv_transfer_timeout_ms={self.kv_transfer_timeout_ms}ms; " "keeping it in progress; deadline_owner=native_sender_overall_wait " f"{self._describe_timeout_session(session)}" ) else: logger.warning(f"TxSession rid={session.disagg_request_id} failed") failed.append(rid) # CANCELLED/ERROR are logical terminal states; a fabric write may still # be reading the request's pages. Include each rank's physical-writer # state in the outcome exchange so retirement also requires consensus. locally_quiesced = [ rid for rid in to_process if not self._send_sessions[rid].has_transferring_tasks() ] cancelled, failed, completed, quiesced_ids = self._ctx_consensus_outcome( to_process, cancelled, failed, completed, locally_quiesced ) quiesced = set(quiesced_ids) cancelled = [rid for rid in cancelled if rid in quiesced] failed = [rid for rid in failed if rid in quiesced] owned_cancelled = [ rid for rid in cancelled if getattr(self._send_sessions[rid], "_enforce_physical_ownership", False) ] diagnostics_enabled = disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED for rid in cancelled: diagnostic_record = None if diagnostics_enabled: with disagg_diagnostics.suppress_diagnostic_errors(): diagnostic_record = ( self._send_reqs.get(rid), self._send_sessions[rid], ) self._retire_send_session(rid, outcome="cancelled") if diagnostic_record is not None: req, session = diagnostic_record self._emit_transfer_settled("ctx", rid, req, session, "cancelled") for rid in completed: req = self._send_reqs[rid] diagnostic_session = None if diagnostics_enabled: with disagg_diagnostics.suppress_diagnostic_errors(): diagnostic_session = self._send_sessions[rid] self._retire_send_session(rid, outcome="completed") if mark_complete: req.state = LlmRequestState.DISAGG_CONTEXT_COMPLETE if diagnostic_session is not None: self._emit_transfer_settled("ctx", rid, req, diagnostic_session, "completed") failed_records = None if diagnostics_enabled: with disagg_diagnostics.suppress_diagnostic_errors(): failed_records = [] for rid in failed: session = self._send_sessions.get(rid) if session is not None: failed_records.append((rid, self._send_reqs.get(rid), session)) self._close_failed_sessions(self._send_sessions, self._send_reqs, failed, mark_retired=True) if failed_records: for rid, req, session in failed_records: self._emit_transfer_settled("ctx", rid, req, session, "failed") # Sweep orphaned RecvReqInfo entries from ADP broadcast on non-assigned # DP ranks (entries that will never have a TxSession created for them). self._transfer_worker.sweep_stale_req_infos() # CtxTransferStatus has no cancellation channel. An owned session's # quiesced cancellation must release its AsyncTransferManager claim. failed.extend(rid for rid in owned_cancelled if rid not in failed) return CtxTransferStatus(completed, failed) def check_gen_transfer_status(self, at_least_request_num: Optional[int]) -> GenTransferStatus: if not self._ever_had_recv_session and not self._gen_need_sync: return GenTransferStatus([], [], []) if self._gen_idle_agreed: # Zero sessions on every rank last round and no receive requested # since (that clears the flag on all ranks in the same iteration): # this round's consensus would be empty everywhere. return GenTransferStatus([], [], []) if ( self._gen_idle_probe and at_least_request_num == 0 and not self._any_rank_has_recv_sessions() ): # No receive session on any rank: the consensus would gather empty # lists and return three empty lists without side effects. Only the # non-blocking poll is short-circuited; blocking and at-least-N # calls keep their pacing. return GenTransferStatus([], [], []) block_all = at_least_request_num is None wait_num = at_least_request_num if not block_all else 0 need_progress = wait_num > 0 if need_progress: self._poll_gen_sessions_for_poll_interval(wait_num) local_completed, local_failed = self._collect_done(self._recv_sessions, self._recv_reqs) consensus, admission_failed = self._poll_rank_info_admissions( local_completed + local_failed ) to_process = self._build_to_process( self._recv_sessions, consensus, 0 if need_progress else wait_num, block_all, ) start_failures = self._rank_info_start_failures or {} to_process = list(dict.fromkeys([*to_process, *start_failures])) completed, failed, cancelled = [], [], [] for rid in to_process: if rid in start_failures: session = self._recv_sessions.get(rid) if session is not None and self._retirement_blocked(session): session.notify_cancel() continue failed.append(rid) continue session = self._recv_sessions[rid] result = session.wait_complete(blocking=block_all) if session.status == SessionStatus.CANCELLED: # A cancel after a failure must not free pages a writer is still writing. if self._retirement_blocked(session): continue # Session cancelled — either by local cancel_request() (user # cancel) or by a remote CANCEL_SESSION message (e.g. CTX # server timeout). Return the req objects so the caller can # distinguish the two cases and set the appropriate state. cancelled.append(rid) elif result == WaitResult.COMPLETED: req = self._recv_reqs[rid] if session.transfer_end_time is not None: req.set_kv_cache_transfer_end(session.transfer_end_time) if session.kv_cache_size_bytes > 0: req.set_kv_cache_size(session.kv_cache_size_bytes) completed.append(rid) elif result == WaitResult.FAILED: # RxSession.wait_complete() already withholds FAILED while an # accessor may remain active. Keep the caller boundary # fail-closed as well so alternate/test session # implementations cannot authorize request retirement early. if self._retirement_blocked(session): continue failed.append(rid) # else: None — KV done but aux still in flight; re-poll next cycle # Verified-range reuse admission: a rid qualifies only when this # rank's session attests full write coverage of the published # destination bytes (see RxSession.kv_write_verified). locally_verified = [ rid for rid in completed if self._recv_sessions[rid].kv_write_verified() ] # All ranks must agree on per-rid outcome to avoid req.state divergence. cancelled, failed, completed, verified = self._gen_consensus_outcome( to_process, cancelled, failed, completed, locally_verified ) diagnostics_enabled = disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED cancelled_reqs = [] for rid in cancelled: session = self._recv_sessions[rid] req = self._recv_reqs[rid] self._close_session_or_raise(session, rid, "cancelled") cancelled_reqs.append(req) del self._recv_reqs[rid] del self._recv_sessions[rid] if diagnostics_enabled: self._emit_transfer_settled("gen", rid, req, session, "cancelled") # Log gen-side transfer summary after consensus. if completed and os.getenv("TRTLLM_KVCACHE_TIME_OUTPUT_PATH"): # Batch-sync timing for all completed requests in one allgather. self._sync_transfer_timing([self._recv_reqs[rid] for rid in completed]) for rid in completed: req = self._recv_reqs[rid] perf_log_manager.log_gen_transfer_summary( unique_rid=rid, instance_name=self._instance_name, instance_rank=self._mapping.rank, gen_side_transfer_time_ms=req.kv_cache_transfer_time_ms, kv_cache_size=req.kv_cache_size, ) for rid in completed: session = self._recv_sessions[rid] req = self._recv_reqs[rid] # Stamp the write-verification verdict on the request before the # session is closed and dropped: commit_blocks_for_reuse runs # later (batch preparation) and gates reuse admission on it. req.py_kv_transfer_verified = rid in verified # transfer_end already stamped at completion detection above. req.set_kv_cache_size(getattr(req, "py_kv_cache_xfer_bytes", 0)) if self._need_aux_transfer(req): self._apply_aux(session, req) self._assert_disagg_history_declared(req) self._close_session_or_raise(session, rid, "completed") req.state = LlmRequestState.DISAGG_GENERATION_TRANS_COMPLETE del self._recv_reqs[rid] del self._recv_sessions[rid] if diagnostics_enabled: self._emit_transfer_settled("gen", rid, req, session, "completed") if failed: logger.warning( f"Disagg gen transfer FAILED rank={self._dist.rank} " f"rids={failed} gen_need_sync={self._gen_need_sync}" ) failed_records = None if diagnostics_enabled: with disagg_diagnostics.suppress_diagnostic_errors(): failed_records = [] for rid in failed: session = self._recv_sessions.get(rid) if session is not None: failed_records.append((rid, self._recv_reqs.get(rid), session)) self._close_failed_sessions(self._recv_sessions, self._recv_reqs, failed) if failed_records: for rid, req, session in failed_records: self._emit_transfer_settled("gen", rid, req, session, "failed") for rid in failed: req = start_failures.pop(rid, None) if req is not None: req.state = LlmRequestState.DISAGG_TRANS_ERROR self._recv_reqs.pop(rid, None) return GenTransferStatus(completed, failed + admission_failed, cancelled_reqs) def _poll_gen_sessions_for_poll_interval(self, wait_num: int) -> None: self._poll_sessions_for_interval( self._recv_sessions, self._recv_reqs, wait_num, self.kv_transfer_poll_interval_ms, ) def _poll_sessions_for_interval( self, sessions: dict, reqs: dict, wait_num: int, poll_interval_ms: Optional[int], ) -> None: # The exit condition can only ever count in-flight sessions, so a # target above len(sessions) is unsatisfiable and the loop would sleep # out the whole interval for nothing. The idle executor loop hits # exactly that: check_context_transfer_status(1) with no in-flight # sends burns a full kv_transfer_sender_future_timeout_ms per # iteration and delays scheduling of newly arrived requests # (nvbugs 6647405). Clamping is safe under rank-divergent session # counts because this helper is purely local (no collectives). wait_num = min(wait_num, len(sessions)) if wait_num <= 0: return poll_interval_s = (poll_interval_ms or 0) / 1000.0 deadline = time.monotonic() + poll_interval_s while True: completed, failed = self._collect_done(sessions, reqs) if len(completed) + len(failed) >= wait_num: return remaining_s = deadline - time.monotonic() if remaining_s <= 0: return for session in sessions.values(): session.wait_complete(blocking=False) time.sleep(min(0.001, remaining_s)) def check_gen_transfer_complete(self): return not self._recv_sessions and not getattr(self, "_cancelled_receive_fences", {}) def _assert_disagg_history_declared(self, req: LlmRequest) -> None: """Verify the V2 scheduler pre-declared prompt_len as history. Call right before the TRANS_COMPLETE state transition. The V2 scheduler's ``_try_schedule_disagg_gen_init`` calls ``prepare_disagg_gen_init``, which sets ``kv_cache.history_length`` to ``prompt_len`` at allocation time so SWA stale computation skips pre-window blocks. If that contract is violated, SWA / sparse-attn pools may fill with pre-window prompt blocks and the V2 scheduler can deadlock under high concurrency (e.g., benchmark fill-phase). """ prompt_len = getattr(req, "py_csa2_remote_tail_start", None) if prompt_len is None: prompt_len = getattr(req, "prompt_len", None) if not prompt_len or prompt_len <= 0: return history = self._kv_cache_manager.get_history_length(req) if history is None: # Cache was already released (e.g., cancelled mid-transfer); nothing to verify. return if history < prompt_len: raise RuntimeError( f"req {req.py_request_id}: kv_cache.history_length={history} " f"< prompt_len={prompt_len} at TRANS_COMPLETE boundary. " f"V2 scheduler must call prepare_disagg_gen_init() in " f"_try_schedule_disagg_gen_init." ) def supports_idle_request_cancellation(self, req: Optional[LlmRequest] = None) -> bool: """Allow bridge cancellation or a session-free generation-first CTX wait.""" if getattr(self, "_fp4_mla_bridge_enabled", False) is True: return True return ( req is not None and req.is_context_only_request and req.py_disaggregated_params is not None and req.py_disaggregated_params.schedule_style == DisaggScheduleStyle.GENERATION_FIRST and not self.has_inflight_transfer(req) ) def cancel_gen_logically( self, req: LlmRequest, ready: Optional[torch.cuda.Event] = None ) -> bool: """Close GEN admission while retaining unquiesced destination resources. Args: req: Model-idle generation request in the ownership-enabled profile. ready: Unpublished destination's local CUDA admission fence, if any. Returns: Whether cancellation is the committed logical outcome. An earlier failure and legacy configurations keep their existing response path. With the bridge enabled, a passed ready fence remains retained until cancel_request returns True, even when this method returns False. """ if not getattr(self, "_fp4_mla_bridge_enabled", False): return False rid = get_unique_rid(req) if ready is not None: fences = getattr(self, "_cancelled_receive_fences", None) if fences is None: fences = self._cancelled_receive_fences = {} if rid not in fences: # Register before querying: a CUDA error must not drop the only # root or leave an unobservable accessor without a grace clock. owner = self._transfer_worker.create_receive_retirement(req.py_request_id) self._recv_reqs[rid] = req fences[rid] = (ready, owner) owner.retain_unproven(req, "cancelled receive admission") session = self._recv_sessions.get(rid) if session is not None: session.cancel_local() return req.state != LlmRequestState.DISAGG_TRANS_ERROR and ( session is None or session.status != SessionStatus.ERROR ) def supports_logical_context_cancellation(self, req: Optional[LlmRequest] = None) -> bool: """Whether this request has independently retained context-transfer ownership. Args: req: The request to check, or None to check the runtime capability. Returns: True only for the qualified, immutable-ID context-first profile. """ if getattr(self, "_context_first_ownership", False) is not True: return False if req is None: return True params = req.py_disaggregated_params return ( req.is_context_only_request and params is not None and params.schedule_style == DisaggScheduleStyle.CONTEXT_FIRST and type(params.disagg_request_id) is int and params.disagg_request_id >= 0 ) def request_logical_context_cancellation(self, req: LlmRequest) -> bool: """Close context admission without releasing an outstanding transfer. Args: req: The exact context request to cancel. Returns: Whether cancellation was accepted. This does not authorize resource release; the normal send reaper must still observe safe retirement. """ if not self.supports_logical_context_cancellation(req): return False rid = get_unique_rid(req) session = self._send_sessions.get(rid) if session is None: # No publication exists, or the previous session already retired. # Do not let a later executor pass create another send for this ID. req.py_kv_send_session_retired = True return True if not getattr(session, "_enforce_physical_ownership", False): return False session.cancel() # Keep both the native session and its request root until every physical # operation settles. Repeated cancellation joins the same drain window. return True def cancel_request(self, req: LlmRequest) -> bool: """Cancel the transfer for the given request. Returns False while physical access or qualified context group retirement is pending; caller must keep progressing and retry. Returns True when this transceiver no longer holds the request's resources. """ rid = get_unique_rid(req) if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: with disagg_diagnostics.suppress_diagnostic_errors(): for side, sessions in ( ("ctx", self._send_sessions), ("gen", self._recv_sessions), ): if rid not in sessions: continue disagg_diagnostics.emit_request_event( "transfer_cancel_requested", req, side=side, dist=self._mapping, instance=self._instance_name, dp_rank=self._dp_rank, ) # A pending admission has not published any destination. if self._pending_rank_info_admissions is not None: self._pending_rank_info_admissions.pop(rid, None) if self.supports_logical_context_cancellation(req): # Local quiescence cannot remove a TP participant's retirement vote. # Keep the session until the normal send reaper agrees across ranks. accepted = self.request_logical_context_cancellation(req) return accepted and rid not in self._send_sessions # Not yet started (generation-first wait queue). self._wait_reqs.pop(rid, None) has_transferring = False if rid in self._send_sessions: session = self._send_sessions[rid] session.cancel() if session.has_transferring_tasks(): has_transferring = True elif session.close() is False: has_transferring = True else: self._retire_send_session( rid, req, outcome="cancelled", session_already_closed=True, ) if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: self._emit_transfer_settled("ctx", rid, req, session, "cancelled") if rid in self._recv_sessions: session = self._recv_sessions[rid] if getattr(self, "_fp4_mla_bridge_enabled", False): session.cancel_local() # Logical acceptance may already have closed admission. Peer # notification is retryable and deduplicated by the session. session.notify_cancel() else: session.cancel() if session.has_transferring_tasks(): has_transferring = True elif session.close() is False: has_transferring = True else: # The bridge has a stable, rank-local receive outcome. Keep # an earlier failure when cancellation retires the session. if ( getattr(self, "_fp4_mla_bridge_enabled", False) and self._recv_sessions[rid].status == SessionStatus.ERROR ): req.state = LlmRequestState.DISAGG_TRANS_ERROR del self._recv_reqs[rid] del self._recv_sessions[rid] if disagg_diagnostics.DISAGG_TRANSFER_DIAGNOSTICS_ENABLED: self._emit_transfer_settled("gen", rid, req, session, "cancelled") if not self._retire_cancelled_receive_fence(rid): has_transferring = True if has_transferring: return False return True def _retire_cancelled_receive_fence(self, rid: int) -> bool: """Release an unpublished receive root only after its CUDA fence completes. Args: rid: Transfer identity of the destination being retired. Returns: Whether no unproven local access remains for this destination. """ fences = getattr(self, "_cancelled_receive_fences", {}) if rid not in fences: return True ready, owner = fences[rid] if not ready.query() or not owner.settle(self._recv_reqs[rid]) or not owner.close(): return False del fences[rid] if rid not in self._recv_sessions: self._recv_reqs.pop(rid, None) return True def get_disaggregated_params(self) -> Dict[str, Any]: # Keep this aligned with fields populated in respond_and_send_async(). # These values are server-level metadata used to seed generation-first # requests before context-phase response data arrives. # # With ADP (enable_attention_dp), ctx_dp_rank is not known at # registration time because the context scheduler has not yet assigned # the request to a DP rank. Return None so that the gen-side Receiver # broadcasts REQUEST_DATA to all ctx DP ranks. The actual ctx_dp_rank # is stamped into ContextPhaseParams by respond_and_send_async() after # the prefill is scheduled. ctx_dp_rank = None if self._mapping.enable_attention_dp else self._dp_rank return { "ctx_dp_rank": ctx_dp_rank, "ctx_info_endpoint": [self._context_info_endpoint] if self._context_info_endpoint else None, } def prepare_context_requests(self, requests: List[LlmRequest]) -> None: # Place new generation-first context requests into wait state, then # use allgather consensus to promote ready requests to CONTEXT_INIT. for req in requests: if not self._validate_bridge_req(req): continue rid = get_unique_rid(req) if rid not in self._send_sessions: self._wait_reqs[rid] = req req.state = LlmRequestState.DISAGG_CONTEXT_WAIT_SCHEDULER # Nothing waiting on any rank, so skip the consensus. The waiting set is the same on every # rank, so they all skip together. if not self._wait_reqs: return # Check which waiting requests have peer info locally, then allgather # consensus so all TP/PP ranks agree before promoting. # Without consensus, background peer info arriving at different times on # different ranks causes scheduling mismatches → hang. local_ready = [ rid for rid in self._wait_reqs if self._transfer_worker.has_all_peer_req_infos_for_send(rid) ] for rid in self._ctx_consensus(local_ready): self._wait_reqs[rid].state = LlmRequestState.CONTEXT_INIT del self._wait_reqs[rid] def _check_compatible(self): m = self._mapping if m.cp_size != 1 and not m.has_cp_helix(): raise ValueError( f"KvCacheTransceiverV2: _check_compatible: unsupported context parallelism " f"(cp_size={m.cp_size}, cp_type={m.cp_config.get('cp_type')}); " f"only cp_size == 1 or helix CP is supported" ) # Under attention-DP the gen-side completion consensus spans the helix CP # ranks of a DP group, so they must admit the same gen-init requests in # the same iteration. The pp=1 executor loops align that admission # (DisaggTransferCoordinator.align_gen_admission_across_cp). The PP loop # does not: under attention-DP with tp_size > 1, each rank of the first # PP stage schedules and admits on its own # (PyExecutor._pp_schedule_and_propagate), so a CP rank can admit a # request its peers did not and hang alone in the gen transfer status # collective. With tp_size == 1 only rank 0 schedules and the CP ranks # follow it, but the check rejects that case too to keep one rule; it # costs nothing, since attention-DP then has a single DP rank. # KVCacheManagerV2 rejects the same combination at construction; lift # both checks together. if m.enable_attention_dp and m.has_cp_helix() and m.pp_size > 1: raise ValueError( "KvCacheTransceiverV2 does not support attention-DP with helix " f"context parallelism when pp_size > 1 (got pp_size={m.pp_size}). " "Set pipeline_parallel_size=1 or enable_attention_dp=False." ) def _resolve_pipelined_transfer(self, cfg: CacheTransceiverConfig) -> bool: """Return whether this rank supports pipelined KV transfer.""" if not cfg.enable_pipelined_transfer: return False blockers = [] if isinstance(self._kv_cache_manager, MambaHybridCacheManagerV2): blockers.append("a Mamba/hybrid cache manager") # Refused for the configuration, not for the piece: the per-chunk guard downstream only sees # a piece short of the whole prompt, so a prompt that fits one chunk would slip past it. if self._mapping.cp_size > 1: blockers.append(f"context parallelism (cp_size={self._mapping.cp_size})") # Policies other than all_reusable defer the whole prompt's commit to the final # chunk. Committing a prefix block that a concurrent request already committed # rebases it onto that request's page and frees ours, which an earlier chunk's # in-flight read may still be sourcing from. if ( self._kv_cache_manager.enable_block_reuse and self._kv_cache_manager.block_reuse_policy != BlockReusePolicy.ALL_REUSABLE ): blockers.append( f"block reuse policy '{self._kv_cache_manager.block_reuse_policy}' " f"(only '{BlockReusePolicy.ALL_REUSABLE}' is supported)" ) if blockers: raise ValueError( "enable_pipelined_transfer is not supported with " + "; ".join(blockers) ) return True def commit_blocks_for_reuse(self, req) -> None: # Without block reuse nothing is committed, so nothing needs verifying. if not self._reuse_adapter.enable_block_reuse: return # Verified-range admission (fail-closed): commit the received range # to the reuse tree only when every published destination byte has # attested write coverage on every rank. Transfer SUCCESS alone is # not proof the destination pages were written — a false-success # would otherwise admit never-written pages under the prompt's token # hashes and reuse would re-serve the poisoned prefix. Skipping the # commit never affects the request itself: generation proceeds # normally, the blocks just stay out of the reuse tree. if not getattr(req, "py_kv_transfer_verified", False): logger.warning( "Skipping KV block reuse admission for request " f"{req.py_request_id}: the received range is not verified as " "written (attested bytes did not cover the published " "destination on every rank)" ) return self._reuse_adapter.commit_blocks_for_reuse(req) def get_context_state(self): raise NotImplementedError("get_context_state is not implemented")