vllm.distributed.kv_transfer.kv_connector.v1.nixl
¶
NIXL KV-cache transfer connector (disaggregated prefill / decode).
Modules:
-
base_scheduler–Base scheduler-side logic for the NIXL connector.
-
base_worker–Base worker-side logic for the NIXL connector.
-
connector–NIXL connector facades.
-
metadata–Metadata dataclasses and helpers for the NIXL connector.
-
pull_scheduler–Pull-specific scheduler-side logic for the NIXL connector.
-
pull_worker–Pull-specific (READ) worker-side logic for the NIXL connector.
-
push_scheduler–Push-specific scheduler-side logic for the NIXL connector.
-
push_worker–Push-specific (WRITE) worker-side logic for the NIXL connector.
-
scheduler–Backward-compatible re-export of NixlPullConnectorScheduler.
-
stats–Stats and Prometheus metrics for the NIXL connector.
-
tp_mapping–TP mapping computation for NIXL KV cache transfers.
-
utils–Shared constants, lazy imports and helpers for the NIXL connector.
-
worker–Backward-compatible re-export of NixlPullConnectorWorker.
Classes:
-
NixlBaseConnector–Base connector with common logic shared by pull and push modes.
-
NixlBaseConnectorScheduler–Base implementation of Scheduler side methods shared by pull and push.
-
NixlBaseConnectorWorker–Base implementation of Worker side methods shared by pull and push.
-
NixlHandshakePayload–Wrapper for NIXL handshake sent over the wire.
-
NixlKVConnectorStats–Container for transfer performance metrics.
-
NixlPullConnector–Pull-based (READ) NIXL KV transfer connector.
-
NixlPullConnectorScheduler–Pull-specific scheduler logic (READ-based KV transfer).
-
NixlPullConnectorWorker–Pull-specific (READ) worker logic.
-
NixlPushConnector–Push-based (WRITE) NIXL KV transfer connector.
-
NixlPushConnectorScheduler–Push-specific scheduler logic (WRITE-based KV transfer).
-
NixlPushConnectorWorker–Push-specific (WRITE) worker logic. See module docstring.
NixlBaseConnector
¶
Bases: KVConnectorBase_V1, SupportsHMA
Base connector with common logic shared by pull and push modes.
Methods:
-
get_block_ids_with_load_errors–Get block IDs that failed to load via NIXL.
-
get_finished–Get the finished recving and sending requests.
-
get_handshake_metadata–Get the KVConnector handshake metadata for this connector.
-
save_kv_layer–NixlConnector does not save explicitly.
-
set_xfer_handshake_metadata_pp_aware–Set handshake metadata keyed by (pp_rank, tp_rank) so the side
-
wait_for_layer_load–NixlConnector does not do layerwise saving.
get_block_ids_with_load_errors()
¶
Get block IDs that failed to load via NIXL.
get_finished(finished_req_ids)
¶
Get the finished recving and sending requests.
get_handshake_metadata()
¶
Get the KVConnector handshake metadata for this connector. This metadata is used for out-of-band connector handshake between P/D workers.
Returns:
-
KVConnectorHandshakeMetadata(KVConnectorHandshakeMetadata | None) –the handshake metadata.
-
KVConnectorHandshakeMetadata | None–None if no handshake metadata is available.
save_kv_layer(layer_name, kv_layer, attn_metadata, **kwargs)
¶
NixlConnector does not save explicitly.
set_xfer_handshake_metadata_pp_aware(metadata)
¶
wait_for_layer_load(layer_name)
¶
NixlConnector does not do layerwise saving.
NixlBaseConnectorScheduler
¶
Base implementation of Scheduler side methods shared by pull and push.
Methods:
-
get_exchange_clipped_blocks–Clip a request's block lists down to the transferable blocks.
-
on_new_request–Track a request that may need heartbeats.
-
set_xfer_handshake_metadata–Set the KV connector handshake metadata for this connector.
-
update_connector_output–Stop heartbeating for requests whose KV transfer completed.
_get_remote_prefill_token_count(request)
¶
D-side only. The number of prompt tokens to load from the prefiller:
the prompt minus _num_prefill_backoff_tokens(), mirroring P's cut.
In pull mode P also reports its count in remote_num_tokens, which
wins when the two sides disagree (e.g. a heterogeneous P that cuts at
a different Mamba checkpoint); that only costs a prefix-cache entry.
Push mode registers D's blocks before P finishes, so it relies on the
mirrored cut alone.
_nixl_handshake_listener(encoded_data, ready_event, stop_event, host, port)
staticmethod
¶
Background thread for getting new NIXL handshakes.
_num_prefill_backoff_tokens(num_prompt_tokens)
¶
Trailing prompt tokens the prefiller skips and the decoder
recomputes: _prefill_backoff(), widened for a prefix-cached Mamba
model down to the last checkpoint a local prefill would cache. P then
backs off up to one block and sends a state that sits on a checkpoint;
D recomputes the tail and caches that state, so later D-local turns of
the conversation hit it.
_prefill_backoff()
¶
Trailing prompt tokens the prefiller must not compute; the decoder recomputes them locally.
Mamba needs h(N-1) so the decoder can derive h(N) itself. DSV41's sliding window under bounded replay is not replayed after a P/D load, so it must be laid out for the token the decoder recomputes. Multi-module MTP needs to keep its whole lookahead window off of the prefiller, which would otherwise embed the unverified drafts in the MTP layer's KV cache. The decoder would never rebuild them, because the update is sized by the rejection count, which is zero for the first decode.
_stop_heartbeat(req_id)
¶
Remove req_id from heartbeat tracking (if tracked).
_truncate_request_for_prefill(request)
¶
P-side only: drop the trailing _num_prefill_backoff_tokens()
prompt tokens so the prefiller stops short of what the decoder
recomputes locally. For Mamba that is the single token needed to yield
h(N-1), or the tail past a prefix-cache checkpoint; for multi-module
MTP it is the drafter's whole lookahead window.
Guarded by _p_side_truncated to avoid repeated truncation if the
request is preempted and rescheduled.
get_exchange_clipped_blocks(block_ids, clip_ssm=True)
¶
Clip a request's block lists down to the transferable blocks.
Sliding-window groups keep only the in-window tail: the KV cache
manager allocates blocks for the entire sequence length and cleans up
out-of-window blocks only prior to the request_finished_all_groups
hook.
SSM groups keep only their state-bearing slot: the trailing speculative scratch slots and everything before the running state (null placeholders and the previous step's superseded state) go.
Use this at every block-id exchange point. Pass clip_ssm=False
for per-step partial lists (host-buffer save), where the SSM strip
does not apply.
on_new_request(request)
¶
Track a request that may need heartbeats.
set_xfer_handshake_metadata(metadata)
¶
update_connector_output(connector_output)
¶
Stop heartbeating for requests whose KV transfer completed.
NixlBaseConnectorWorker
¶
Base implementation of Worker side methods shared by pull and push.
Methods:
-
add_remote_agent–Add the remote NIXL agent and prepare the descriptors for reading cache
-
get_block_ids_with_load_errors–Return and clear the set of block IDs that failed to load.
-
get_finished–Compatibility wrapper for the legacy completion API.
-
get_kv_connector_stats–Get the KV transfer stats for the connector.
-
get_mapped_blocks–Calculates the new set of block IDs by mapping every element
-
get_transfer_results–Get transfers that completed on this specific worker.
-
initialize_host_xfer_buffer–Initialize transfer buffer in CPU mem for accelerators
-
post_process_device_kv_on_receive–Post process device kv cache after receiving from remote.
-
post_process_device_kv_on_receive_heterogeneous_attn–Post process device kv cache after receiving from remote
-
register_kv_caches–Register the KV Cache data in nixl.
-
register_local_xfer_handler–Function used for register local xfer handler with local block_size or
-
save_kv_to_host–Copy kv from device to host buffer.
-
set_host_xfer_buffer_ops–Assign copy (d2h, h2d) operations when host buffer is used.
-
shutdown–Shutdown the connector worker.
-
sync_recved_kv_to_device–Copy recved kv from host buffer to device.
_add_notif_only_remote_agent(metadata, remote_tp_size, remote_dcp_size=1)
¶
Load a remote agent for notifs only on the push-mode decode side.
Skips descriptor setup but records engine info for block accounting.
_add_remote_stage(nixl_agent_meta, pairs, pp_rank, pp_size)
¶
Register one PP stage of a remote engine (the whole engine when
pp_size is 1) once for all its TP ranks. nixl_agent_meta lists
only the paired regions.
_apply_dcp_prefix_caching(local_ids, remote_ids, remote_rank, local_dcp_size, local_dcp_rank, remote_dcp_size, local_num_computed_blocks, num_remote_blocks=None)
¶
Match local and remote block IDs by global DCP position.
local_ids excludes blocks already satisfied by the local prefix
cache, while remote_ids contains the full transferable remote list.
num_remote_blocks, when provided, is the global block count before
DCP partitioning and excludes allocation padding.
Example
local DCP size 2, rank 0 owns global positions=[0, 2, 4, 6] cached_blocks=[0,2,4] to transfer: [6] (the rest is cached)
remote DCP size 4 remote rank 0 owns [0, 4] -> no more match, skip the read remote rank 2 owns [2, 6] -> match position 6 and read
An empty result (rank 0 above) takes the notification-only path, allowing the remote to release its blocks without performing a transfer.
_apply_prefix_caching(decode_block_ids, prefill_block_ids, decode_physical_per_logical, prefill_physical_per_logical)
¶
Trim block ID lists so only the uncomputed suffix is transferred.
Inputs are kernel (physical) block IDs, already expanded from logical IDs with each side's physical-per-logical ratio. Both pull and push call this after that expansion so the trim happens at kernel granularity.
The prefix-cache hit is always on the decode (D) side, so decode
holds only its uncomputed blocks while prefill (P) holds the full
sequence. This is mode-independent: pull passes its own (D) blocks as
decode, push passes the remote D registration as decode.
For non-Mamba models: end-trim prefill to match decode count, so
already-cached prefix blocks are skipped in the transfer.
For Mamba hybrid: SSM groups pair state slots by position and FA groups end-trim to the uncomputed suffix when physical-per-logical matches.
_apply_prefix_caching_by_region(decode_block_ids, prefill_block_ids, *, num_computed_blocks=None, num_remote_blocks=None, remote_rank=0, remote_dcp_size=1)
¶
Pair an uncached decode suffix with the same prefill regions.
_block_ids_by_region(block_ids, region_group_ids)
staticmethod
¶
Expand group block IDs into the corresponding region order.
_block_strided_descs(base_addr, block_len, block_stride, num_blocks, block_size_ratio, device_id)
staticmethod
¶
Nx5 strided descs for num_blocks blocks, each split into
block_size_ratio sub-blocks of block_len bytes.
Evenly spaced sub-blocks collapse into one strided desc. In a padded block the sub-blocks abut only within the block, so each block gets its own.
_build_fa_local(base_addresses, block_size_ratio)
¶
Build local FA descriptors as Nx5 uint64 strided descs.
_build_fa_remote(plan, nixl_agent_meta, block_size_ratio, local_region_ids=None)
¶
Build remote FA descriptors as Nx5 uint64 strided descs.
local_region_ids gives a local region each remote region pairs with
(_RegionPairs.partner); remote region i pairs with local region
i without it.
_build_local_splits_from_plan(plan, src_blocks_data, num_fa_descs, block_size_ratio=1)
¶
Build split handle data for P_TP > D_TP scenario.
num_fa_descs is the boundary between FA and SSM descriptors. Split counts are derived from source_ranks_per_group lengths. FA uses rank_to_attention_slot for the slot offset; SSM uses the rank's positional index. Each Nx5 strided desc covers one region, so slicing it slices every block.
_build_mamba_local(base_addresses)
¶
Build desc regions (conv sub-projections + ssm) per layer for local mamba blocks with DS conv layout, as Nx5 uint64 strided descs.
A Mamba block interleaves conv and SSM state, which crucially differ in size, so the two are indexed as separate sub-regions. Attention blocks instead pack K and V into the content dim and transfer as a single unit. Reference diagram: KVCacheTensor (Shared) / \ / \ / \ Attention (FlashInfer) View Mamba View | | | | +-------------------+ +-------------------+ | KVCacheTensor | | KVCacheTensor | | | | | |<----- page ------>| |<----- page ------->| | size | | size | | Key 0 | Val 0 | |Conv 0 | SSM 0 | | Key 1 | Val 1 | |Conv 1 | SSM 1 | | ... | ... | | ... | ... | | Key N-2 | Val N-2 | |Conv N-2| SSM N-2 | | Key N-1 | Val N-1 | |Conv N-1| SSM N-1 | +-------------------+ +--------------------+ |1st_split-2nd_split| |1st_split-2nd_split |
Mamba state blocks are indivisible (not token-extent data), so the descriptors always use the local page geometry regardless of any attention block-size ratio; their desc ids are likewise never ratio-expanded (see _compute_desc_ids).
_build_mamba_remote(nixl_agent_meta, tp_ratio, transfer_info, pairs)
¶
Build remote desc regions (conv sub-projections + ssm) per layer.
For hetero-TP, each D rank reads only its sub-projection slice from
the P rank. The remote SSM and PLE regions come from pairs.
Returns Nx5 uint64 strided descs.
_check_remote_pp_supported(nixl_agent_meta)
¶
Refuse layouts that per-stage pulls from a pipeline-parallel producer do not support. Under HMA a stage may hold no layer of a cache group (a draft's group on the stages before the last); it then has no pair of that group, so its reads skip the group.
_cleanup_remote_engine(engine_id, *, log_eviction=True)
¶
Remove all state for a single remote engine.
Releases NIXL resources (dlist handles, remote agents) and clears all per-engine data structures. Used by TTL eviction, replaced/invalid peer cleanup and shutdown.
_cleanup_remote_engines()
¶
Release replaced or locally invalid pull peers after their reads drain.
_compat_backend_name()
¶
Attention backend name folded into the compatibility hash.
Backends of indexer caches do not count: a model may build indexers on some layers only, so a PP stage may start on, or hold only, layers without one.
_compute_desc_ids(block_ids, dst_num_blocks, block_size_ratio, physical_blocks_per_logical, pairs, region_num_blocks=None, ssm_regions=None)
¶
Compute NIXL descriptor IDs for given block IDs.
pairs is (regions, keys): region regions[k] is read at
block_ids[keys[k]], a cache group's blocks (a region's, for
region-mapped transfers).
ssm_regions lists this side's SSM regions in the order its SSM
descriptors are built; it defaults to the local ones.
_engines_with_inflight_transfers()
¶
Remote engines a transfer is still reading from.
The timestamp is stamped when a read is issued and not refreshed while it runs, so a transfer that outlives the TTL leaves its engine looking idle. A peer that has lost its NIC holds one indefinitely.
_ensure_handshake(engine_id, host, port, tp_size, dcp_size=1, pp_size=1, notif_agents_only=False)
¶
Ensure a handshake is in-flight (or already done) for engine_id.
Returns the Future if a handshake is pending (or was just
started), or None if the handshake already completed
successfully. Callers can attach per-request callbacks to the
returned future.
Failures to handshake are logged and the request is marked as failed.
_evict_stale_engines()
¶
Scan for and evict remote engines that have exceeded their TTL.
Called from the main thread in when a new remote engine appears. We can only go OOM as we discover and register a new remote, therefore we make sure we clean up stale engine data structures before then. This invariant prevents us from using background threads, though memory usage is not guaranteed to be "optimal" until a new handshake is performed.
Engines with active transfers, heartbeats or pending handshakes cannot be stale: - Reads stamp _engine_last_active when they are issued, and engines a transfer is still reading from are held back explicitly, since the stamp is not refreshed while the read runs. - Heartbeats stamp it too, so an engine stays registered while this instance holds requests waiting on it. - Pending handshakes don't have an _engine_last_active entry yet
_expand_remote_packed_rows(nixl_agent_meta)
staticmethod
¶
View each of the remote's packed rows as one region per layer.
A block-outermost peer may register one region whose block is a full
row holding every layer's page, while this worker registers one region
per layer (a PP push stage, or a HiSparse decoder on LB*). Using the
advertised packed_member_layouts, each row is rewritten in place as
one virtual region per layer, so that layers pair one to one:
remote row b: [ L0 page | L1 page | ... ] base=B, stride=S
^off0 ^off1
remote metadata, before: [(B, S, S)] # (base, len, stride)
remote metadata, after: [(B + off0, page0, S), # L0
(B + off1, page1, S)] # L1
Remote regions outside the rows (e.g. a separate indexer) pass through.
_fa_desc_replicated(desc_starts, num_fa_descs, block_size_ratio=1)
¶
Replicate flag per FA strided desc, given each one's flat block index.
_build_fa_local emits regions in order, with
region_num_blocks[i] * block_size_ratio blocks per region. A strided
desc never spans regions, so the region owning its first block decides.
_get_lease_lapsed_recvs(done_recving)
¶
Completed receives whose remote lease may have lapsed mid-read.
_get_new_notifs()
¶
Get req_ids which got a remote xfer notification.
Subclasses must implement this to handle mode-specific notifications.
_handle_failed_transfer(req_id, handle, failed_req_ids=None, record_failed_transfer=True, error=None)
¶
Record a failure and release its handle, returning False to retain it.
Parameters:
-
(req_id¶str) –The request ID.
-
(handle¶int | None) –The transfer handle.
-
(failed_req_ids¶set[str] | None, default:None) –Requests observed as failed; each stays listed until it has no outstanding handles.
-
(record_failed_transfer¶bool, default:True) –Whether to count the failure toward the transport-failure metric. Callers that already recorded a more specific metric (eg KV expiry, reported separately from transport failures) pass False.
-
(error¶BaseException | None, default:None) –The exception that failed the transfer, if any. A lost connection invalidates the remote engine.
_handle_heartbeat(payload)
¶
_has_inflight_send(req_id)
¶
Whether this worker is still sending the request's KV blocks.
_is_region_replicated(region_idx)
¶
Whether region region_idx is transferred REPLICATE vs SPLIT.
REPLICATE (MLA): identical on every rank, whole block read from one rank at offset 0, key-only. SPLIT (full-attn): head-sharded across TP. Defaults to SPLIT when the per-region map is unset (e.g. tests that set block_len_per_layer without register_kv_caches).
_leaves_dram_xfer_to_host_leader()
¶
Whether this rank leaves the DRAM regions' NIXL work to its node's HiSparse host leader.
A HiSparse host pool shared by a node's TP ranks (one mmap per node) is registered with NIXL and filled by the node's host leader alone: every rank would otherwise register the same pages on every NIC and READ the same host KV into them. Private pools are unaffected.
_log_failure(failure_type, req_id, msg='', error=None, meta=None, **extra_context)
¶
Log transfer failure with structured context for easier debugging.
_logical_to_kernel_block_ids(block_ids, ratio)
¶
Convert block ids to kernel physical block ids.
This is required when the logical block size (the one set by the user)
does not match the one required by the attn backend.
ratio is the number of physical blocks per logical block.
We always receive logical blocks from the engine, so we expand them here eg:
logical block ids: [(SW-clipped) [1], (FA) [2, 3]], ratio=2
physical block ids: [(SW-clipped) [2, 3], (FA) [4, 5, 6, 7]]
_map_block_ids_for_block_size_ratio(local_block_ids, remote_block_ids, block_size_ratio)
¶
Map attention-group block ids to remote-block granularity.
Positional pairing, only valid when both lists start at the same
token (push, and DCP pulls, which require equal logical block sizes).
Other pulls pair from the last token in _pair_blocks_by_last_token.
Each local attention block is split into block_size_ratio
sub-blocks paired 1:1 with remote blocks. Sub-blocks beyond the
remote list — the untransferred tail of the last local block — are
clipped here and zeroed in the receive post-process. Mamba state
blocks are indivisible and transfer 1:1, unexpanded.
ex: remote (prefill) block ids with block_size 4: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Local (decode) block ids with block_size 16: [1, 2, 3] expand to [4, 5, ..., 15], then clip to the first 10 to pair 1:1 with remote.
_mark_remote_engine_invalid(engine_id, now)
¶
Schedule release of an engine whose local NIXL metadata is gone.
The first invalidation is released as soon as reads drain. Repeats before the peer has stayed healthy for the max backoff double the delay, during which reads fail fast instead of re-handshaking.
_needs_split_local_xfer_handles(tp_ratio, plan)
¶
Whether reads need per-source slices of the local KV region.
Pure MLA attention is replicated across TP ranks and writes the whole local region. Multiple physical remote workers may still participate because DCP assigns them disjoint blocks, but that does not require splitting the local region. Hybrid MLA+SSM is different: its mapping contains multiple source ranks for the sharded SSM state.
_nixl_handshake(host, port, remote_tp_size, expected_engine_id, remote_dcp_size=1, remote_pp_size=1, notif_agents_only=False)
¶
Do a NIXL handshake with a remote instance.
_pack_strided_descs(strided_descs)
staticmethod
¶
Pack (addr, len, dev_id, stride, count) rows into an Nx5 uint64 array.
Each row describes count blocks of len bytes whose starts are
stride bytes apart; NIXL >= 1.5 prepares this layout directly.
_pair_blocks_by_last_token(local_block_ids, remote_block_ids, num_tokens, block_size_ratio, remote_physical_per_logical)
¶
Pair kernel blocks holding the same tokens across P/D block sizes.
Local blocks are split into remote-sized sub-blocks. Each side
allocates whole logical blocks up to the last of num_tokens, while
a local prefix hit or sliding-window clipping can start the lists at
different tokens. So drop each side's sub-blocks past that last token
and pair the lists from their ends. SSM groups pass through unpaired.
Returns the paired lists and, per group, the range of local sub-blocks the read covers.
_pair_regions(nixl_agent_meta, remote_pp_stage=False)
¶
Pair a peer's regions with the local ones through the layers both hold.
A layer's regions pair in order on both sides (two when K and V
register apart). The peer must hold every local layer, unless it is
a remote_pp_stage; layers only the peer holds are skipped on a PP
stage, which holds a slice of them. A peer's packed rows are first
rewritten as one region per layer when this worker registers its
layers apart.
_pair_ssm_regions(pairs, engine_id)
¶
Find the peer's SSM and PLE regions through the pairs.
SSM descriptors are built per region holding SSM state. The peer's SSM regions are listed in the order of the local SSM regions they pair with, so identical layouts keep identical descriptor lists.
_ple_page_len()
¶
Transfer length of one PLE state page.
The PLE page shares its region with the first page of other cache groups (block-outer layout), whose block_len may be smaller; the descriptors must cover the whole PLE page or part of the conv state never reaches the decode side.
_pop_done_transfers(transfers)
¶
Poll transfers, retaining handles until they can be released.
Parameters:
Returns:
_reap_expired_send_leases(done_sending)
¶
Reclaim expired send-side KV leases into done_sending.
_reqs_to_send is not ordered by expiry: heartbeats update the
deadline in place, and mixed TTLs share the map, so a live head
entry can sit in front of already-expired ones. Scan every entry
rather than stopping at the first still-live request.
_record_heartbeat_sent(key, now, deadline, extension)
¶
Mirror the remote's _handle_heartbeat for a heartbeat sent at now:
a live lease (initial deadline, our clock) renews to now + extension;
a lapsed one stays lapsed, as its deadline no longer moves.
_resolve_head_sharded_draft_kv_heads()
¶
Total KV heads of a non-MLA draft under an MLA target, else None.
Such a draft's KV is head-sharded while the target's is replicated.
_select_remote_regions(nixl_agent_meta, remote_regions)
staticmethod
¶
Keep the remote regions remote_regions, in that order.
_send_heartbeats(metadata)
¶
Send heartbeats to remote engines, extending the lease on KV blocks.
_send_pending_recv_notifs(req_id)
¶
Send notifications deferred by split DRAM/VRAM reads.
_single_remote_stage(engine_id)
¶
The only stage of a remote engine that runs PP=1.
_split_remote_blocks(meta)
¶
View remote blocks as gcd-sized kernel blocks when the local block size is not a multiple of the remote one.
Hybrid blocks are sized to cover the TP-sharded SSM page, so P and D differ with TP. Backends that accept any kernel block size keep them whole, and non-multiples cannot otherwise be paired.
_step_housekeeping()
¶
Per-step work kept out of get_transfer_results(), which may be polled between steps. Called at the end of start_load_kv().
_strided_desc_starts(strided_descs)
staticmethod
¶
Flat block index of each strided desc's first block.
_sync_device_after_direct_recv(done_recving)
¶
Make direct NIXL writes visible before model execution.
_track_remote_engine_replacement(engine_id, host, port)
¶
Record the engine currently serving a pull peer address.
_try_release_xfer_handle(req_id, handle)
¶
Release a handle, returning False if the caller must retain it.
_validate_csa_linear_tp_layout(remote_tp_size)
¶
Reject P/D pairs whose main-KV pages have different head layouts.
A rank at TP < total KV heads holds several heads per page, while a rank at TP >= total KV heads holds exactly one (replicated beyond that). CSA-linear pages are shared tensors that transfer as whole block units, so endpoints on opposite sides of that boundary lay them out differently and cannot exchange them.
_validate_remote_agent_handshake(nixl_agent_meta, remote_tp_size, remote_dcp_size=1, local_region_ids=None)
¶
Validate the remote agent handshake metadata ensuring the invariants hold true.
local_region_ids gives a local region each remote region pairs
with; remote region i pairs with local region i without it.
_zero_region_blocks(block_ids)
¶
Clear clipped physical pages in their owning region only.
add_remote_agent(nixl_agent_meta, remote_tp_rank=0, remote_tp_size=1, remote_dcp_size=1, remote_pp_rank=0, remote_pp_size=1)
¶
Add the remote NIXL agent and prepare the descriptors for reading cache blocks from remote.
A PP-sharded remote registers each stage separately: every stage holds a slice of the layers and is read into the local regions holding them.
In particular, handle both homogeneous and heterogeneous TP. The former requires local rank_i to read from remote rank_i. The latter, in the case of D.world_size < P.world_size, requires that a local (D) TP worker reads from multiple remote (P) TP workers. Conversely, assuming D.world_size > P.world_size, two or more local TP workers will read from a single remote TP worker.
Here's an example for the last case described above (non-MLA):
rank_offset p_remote_tp_rank (kv split no)
0 0 Worker0 ---- 1st half of KV ----> Worker0 [ KV Cache ]
/
1 0 Worker1 ---- 2nd half of KV -----/
0 1 Worker2 ---- 1st half of KV ----> Worker1 [ KV Cache ]
/
1 1 Worker3 ---- 2nd half of KV -----/
Decoder TP workers Prefix TP workers
(world_size=4) (world_size=2)
tp_ratio = 4 // 2 = 2
Considering the KV Caches, if P-Worker_i has cache size [2, num_blocksP, kv_heads, block_size, head_dim] then D-Worker_j has [2, num_blocksD, kv_heads//tp_ratio, block_size, head_dim]. Mind the "LBHNC" layout format. Assuming num_blocksD >= num_blocksP, D-Worker0 reads from P-Worker0 by preparing the kv_heads//tp_ratio first heads from all the slots of all the blocks. D-Worker1 will do the same, but reading the second split along the kv_heads dimension, and so forth until "tp_ratio" D TP workers have pulled from P-Worker0.
Note that the above will also hold true for the homogeneous TP case, where tp_ratio evaluates to 1.
Regarding MLA case, the cache is replicated across TP workers so the rank_offset will just always be 0 so that the whole cache is shared by "tp_ratio" D TP workers.
For Mamba hetero-TP, both tp_ratio > 0 (D_TP > P_TP) and tp_ratio < 0 (P_TP > D_TP) are supported by the 3-read transfer.
get_block_ids_with_load_errors()
¶
Return and clear the set of block IDs that failed to load.
This is called by the scheduler to identify blocks that need to be retried after a NIXL transfer failure.
get_finished()
¶
Compatibility wrapper for the legacy completion API.
get_kv_connector_stats()
¶
Get the KV transfer stats for the connector.
get_mapped_blocks(block_ids, block_size_ratio)
¶
Calculates the new set of block IDs by mapping every element in the (potentially sparse) input array. Example: block_ids=[0, 2], block_size_ratio=2 get_mapped_blocks 0 1 [2 3] 4 5 # remote is |h0-b0|h1-b0||h0-b1|h1-b1||h0-b1|h1-b1|| # local is |h0-b0......||h1-b0......||h2-b0........ local_block_ids 0 [1] 2
get_transfer_results()
¶
Get transfers that completed on this specific worker.
The scheduler process (via the MultiprocExecutor) will use this output to track which workers are done.
initialize_host_xfer_buffer(kv_caches)
¶
Initialize transfer buffer in CPU mem for accelerators NOT directly supported by NIXL (e.g., tpu)
post_process_device_kv_on_receive(block_size_ratio, block_ids_list, convert=True)
¶
Post process device kv cache after receiving from remote.
3 types of conversion supported (convert):
* kv_cache_postprocess_layout => convert from HND to NHD
* kv_cache_postprocess_blksize => convert from small block size
to large block size
* kv_cache_postprocess_blksize_and_layout => convert from small
block size to large block size and convert from HND to NHD
The transfer only covers covered_sub_blocks remote-sized
sub-blocks of each request's local attention blocks; the rest was
clipped when pairing local and remote blocks from the last token
(_pair_blocks_by_last_token). Those blocks were
excluded from the scheduler's alloc-time KV zeroing (which would race
the RDMA write), so everything outside the covered range is zeroed here.
Stale bytes would otherwise surface as garbage or NaNs once decode
grows into the untransferred tail.
post_process_device_kv_on_receive_heterogeneous_attn(block_ids)
¶
Post process device kv cache after receiving from remote for heterogeneous attention.
register_kv_caches(kv_caches)
¶
Register the KV Cache data in nixl.
register_local_xfer_handler(block_size)
¶
Function used for register local xfer handler with local block_size or Remote block_size.
When local block_size is same as remote block_size, we use local block_size to register local_xfer_handler during init.
When remote block size is less than local block size, we need to use register another local_xfer_handler using remote block len to ensure data copy correctness.
save_kv_to_host(metadata)
¶
Copy kv from device to host buffer.
set_host_xfer_buffer_ops(copy_operation)
¶
Assign copy (d2h, h2d) operations when host buffer is used.
shutdown()
¶
Shutdown the connector worker.
sync_recved_kv_to_device(req_id, meta)
¶
Copy recved kv from host buffer to device.
NixlHandshakePayload
dataclass
¶
Bases: KVConnectorHandshakeMetadata
Wrapper for NIXL handshake sent over the wire.
Enables two-phase decoding for graceful compatibility checking: 1. Decode NixlHandshakePayload to get compatibility_hash 2. Compute local hash and compare 3. Only if hashes match, decode agent_metadata_bytes
This prevents decoder errors when NixlAgentMetadata schema is incompatible, allowing graceful failure with clear error message.
NixlKVConnectorStats
dataclass
¶
Bases: KVConnectorStats
Container for transfer performance metrics.
Methods:
-
record_declined_expired_read–Record a remote read declined because the remote's lease ran out.
-
record_failed_handshake–Record a failed NIXL handshake.
-
record_failed_notification–Record a failed NIXL notification (send_notif).
-
record_failed_transfer–Record a failed NIXL transfer operation.
-
record_kv_expired_req–Record a request that had its KV blocks expire.
-
record_notification_after_expiry–Record a completion notification that arrived after its request expired.
record_declined_expired_read()
¶
Record a remote read declined because the remote's lease ran out.
record_failed_handshake()
¶
Record a failed NIXL handshake.
record_failed_notification()
¶
Record a failed NIXL notification (send_notif).
record_failed_transfer()
¶
Record a failed NIXL transfer operation.
record_kv_expired_req()
¶
Record a request that had its KV blocks expire.
record_notification_after_expiry()
¶
Record a completion notification that arrived after its request expired.
NixlPullConnector
¶
NixlPullConnectorScheduler
¶
Bases: NixlBaseConnectorScheduler
Pull-specific scheduler logic (READ-based KV transfer).
Methods:
-
get_num_new_matched_tokens–For remote prefill, pull all prompt blocks from remote
-
request_finished–Once a request is finished, determine whether request blocks
get_num_new_matched_tokens(request, num_computed_tokens)
¶
For remote prefill, pull all prompt blocks from remote asynchronously relative to engine execution.
Parameters:
-
(request¶Request) –the request object.
-
(num_computed_tokens¶int) –the number of locally computed tokens for this request
Returns: * the number of tokens that can be loaded from the external KV cache beyond what is already computed. * true if the external KV cache tokens will be loaded asynchronously (between scheduler steps).
request_finished(request, block_ids)
¶
Once a request is finished, determine whether request blocks should be freed now or will be sent asynchronously and freed later.
NixlPullConnectorWorker
¶
Bases: NixlBaseConnectorWorker
Pull-specific (READ) worker logic.
Methods:
-
start_load_kv–Start loading by triggering non-blocking nixl_xfer.
_get_lease_lapsed_recvs(done_recving)
¶
Completed reads that may have overlapped the remote's lease expiry, so the blocks could have been recycled while being read.
_get_new_notifs()
¶
Get req_ids which got a remote xfer message. When multiple consumers are reading from the same producer (heterogeneous TP or DCP scenario), wait for all consumers to be done pulling.
Also handles heartbeat notifications (HB_NOTIF_PREFIX + "req1,req2") by extending the lease on the referenced requests.
_is_remote_read_expired(meta)
¶
Whether the remote's lease on the blocks has (nearly) run out, after which they may hold other requests' KV. Uses the exported deadline, rebased by the clock offset and extended by our heartbeats' renewals.
_read_blocks(read_spec, dst_engine_id, request_id, remote_request_id, local_xfer_side_handle, local_dram_handle, remote_xfer_side_handle, expected_consumers, awaiting_kvs, region_pairs, remote_region_num_blocks, remote_agent)
¶
Post a READ point-to-point xfer request from a single local worker to a single remote worker.
The caller resolves the remote region mapping, block counts and notification agent.
Returns True when the read was posted (or was unnecessary), False when the request was routed to failure reporting — the caller must not post further transfers for it.
_read_blocks_mixed(request_id, local_block_size_key, local_device_handle, local_dram_handle, remote_xfer_side_handle, local_block_descs_ids, remote_block_descs_ids, notif_agent, notif_id)
¶
Split a READ across the local DRAM and device descriptor lists.
start_load_kv(metadata)
¶
Start loading by triggering non-blocking nixl_xfer. We check for these trnxs to complete in each step().
NixlPushConnector
¶
Bases: NixlBaseConnector
Push-based (WRITE) NIXL KV transfer connector.
Methods:
-
start_load_kv–Drive push processing on the worker.
start_load_kv(forward_context, **kwargs)
¶
Drive push processing on the worker.
The worker enqueues registrations / finished blocks for the
background nixl-push-writer thread; the writer issues the
WRITE transfers and polls NIXL notifs without further
engine-thread involvement.
NixlPushConnectorScheduler
¶
Bases: NixlBaseConnectorScheduler
Push-specific scheduler logic (WRITE-based KV transfer).
All P2P communication is deferred to the worker level via NIXL
notifications. The scheduler communicates with workers only through
the standard build_connector_meta / update_connector_output
hooks.
Methods:
-
get_num_new_matched_tokens–In push mode, D doesn't pull — it registers blocks and waits.
-
request_finished–Push-mode request_finished: stores blocks for workers.
-
update_connector_output–Clean up finished request blocks after push completes.
-
update_state_after_alloc–In push mode, D stores registration data for the worker to send
get_num_new_matched_tokens(request, num_computed_tokens)
¶
In push mode, D doesn't pull — it registers blocks and waits.
However, we still need to handle the do_remote_prefill case where D needs to know how many tokens will be pushed.
request_finished(request, block_ids)
¶
Push-mode request_finished: stores blocks for workers.
update_connector_output(connector_output)
¶
Clean up finished request blocks after push completes.
update_state_after_alloc(request, blocks, num_external_tokens)
¶
In push mode, D stores registration data for the worker to send
to P via NIXL notification (deferred to build_connector_meta).
NixlPushConnectorWorker
¶
Bases: NixlBaseConnectorWorker
Push-specific (WRITE) worker logic. See module docstring.
Methods:
-
start_load_kv–Pre-process metadata; defer NIXL ops to the writer thread.
_as_grouped_block_ids(block_ids)
staticmethod
¶
Normalise a sequence of block IDs to a tuple-of-groups shape.
BlockIds is canonically a tuple of per-group lists, but some
registration payloads collapse a single-group case to a flat
list. Re-wrap that case so downstream group-aware helpers see a
consistent shape.
_get_new_notifs()
¶
Drain HB / completion notifs forwarded by the writer thread.
The writer owns nixl_wrapper.get_new_notifs for push; PUSH_REG
notifs are handled there. P learns of finished pushes from its WRITE
handles, so this never reports finished sends.
_pop_matching_finished_blocks(request_id)
¶
Pop the P-side finished blocks matching request_id.
Same lookup as _pop_matching_registration: exact key, then a
match after stripping the random suffix from both sides.
_pop_matching_registration(request_id)
¶
Pop the D-side registration matching request_id.
Exact key first, then a match after stripping the random suffix from both sides. No match leaves the request unmatched (push not started).
_send_registration_to_p(req_id, reg_data)
¶
Handshake (if needed) then send PUSH_REG. send_notif always
executes on the writer; the handshake runs on the background executor
and the request is re-queued onto _reg_send_inbox once it
completes (at which point _ensure_handshake returns None and we
send directly).
_start_push_kv(request_id, local_block_ids, registration_data)
¶
Start push-based KV transfer from P worker to D node.
The P→D handshake runs on the base worker's background executor.
If it isn't ready yet we register a completion callback, defer the
WRITE, and re-drive this request via _deferred_push_inbox once
the handshake resolves -- so the writer thread never blocks on the
network (mirrors _send_registration_to_p).
_xfer_blocks(read_spec, dst_engine_id, request_id, remote_request_id, local_xfer_side_handle, remote_xfer_side_handle)
¶
Post a WRITE point-to-point xfer request.
Returns the in-flight transfer handle (so the caller can track all of
a request's handles atomically), or None if nothing was submitted.
_xfer_blocks_for_req(req_id, meta)
¶
Issue WRITE transfers to one or more remote TP ranks.
start_load_kv(metadata)
¶
Pre-process metadata; defer NIXL ops to the writer thread.