vllm_v0.7.2-dynamo-kv-disagg-patch.patch 210 KB
Newer Older
1
diff --git a/vllm/config.py b/vllm/config.py
2
index 9ba497576..db2dc002f 100644
3
4
--- a/vllm/config.py
+++ b/vllm/config.py
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 ast
 import copy
@@ -2620,6 +2633,9 @@ class KVTransferConfig(BaseModel):
24
25
26
27
     # The KV connector for vLLM to transmit KV caches between vLLM instances.
     kv_connector: Optional[str] = None
 
+    # Whether to use NIXL prepped xfer for KV cache transfer.
28
+    use_prepped_xfer: bool = True
29
30
31
32
+
     # The device used by kv connector to buffer the KV cache.
     # Currently only support 'cuda'.
     kv_buffer_device: Optional[str] = "cuda"
33
@@ -2629,7 +2645,7 @@ class KVTransferConfig(BaseModel):
34
35
36
37
38
39
40
41
     kv_buffer_size: float = 1e9
 
     # Whether this vLLM instance produces, consumes KV cache, or both. Choices
-    # are 'kv_producer', 'kv_consumer', and 'both'.
+    # are 'kv_producer', 'kv_consumer', and 'kv_both'.
     kv_role: Optional[str] = None
 
     # The rank of this vLLM instance in the KV cache transfer. Typical value:
42
@@ -2647,6 +2663,14 @@ class KVTransferConfig(BaseModel):
43
44
45
46
47
48
49
50
51
52
53
54
55
56
     # The KV connector port, used to build distributed connection
     kv_port: int = 14579
 
+
+    # This does not need to be set by the user. It is set by the connector.
+    kv_producers_parallel_size: Optional[int] = None
+    kv_producers_tensor_parallel_size: Optional[int] = None
+    kv_producers_pipeline_parallel_size: Optional[int] = None
+    kv_consumers_tensor_parallel_size: Optional[int] = None
+    kv_consumers_pipeline_parallel_size: Optional[int] = None
+
     def compute_hash(self) -> str:
         """
         WARNING: Whenever a new field is added to this config,
57
@@ -2680,11 +2704,16 @@ class KVTransferConfig(BaseModel):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
58
59
60
61
                 f"Supported roles are `kv_producer`, `kv_consumer`, "
                 f"and `kv_both`")
 
-        if self.kv_connector is not None and self.kv_role is None:
Neelay Shah's avatar
Neelay Shah committed
62
+        if self.kv_connector is not None and self.kv_connector != "DynamoNixlConnector" and self.kv_role is None:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
63
             raise ValueError("Please specify kv_disagg_role when kv_connector "
64
65
66
                              "is set, supported roles are `kv_producer`, "
                              "`kv_consumer`, and `kv_both`")
 
67
68
69
70
+        if self.use_prepped_xfer is False:
+            logger.warning("`use_prepped_xfer` parameter is deprecated. All transfers will be done using prepped xfer.")
+            self.use_prepped_xfer = True
+
71
72
73
74
+
     @property
     def is_kv_transfer_instance(self) -> bool:
         return self.kv_connector is not None and \
75
@@ -2694,6 +2723,8 @@ class KVTransferConfig(BaseModel):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
76
77
78
     def need_kv_parallel_group(self) -> bool:
         # for those database-based connector, vLLM does not need to create
         # parallel group, and in that case the kv parallel size will be 1.
Neelay Shah's avatar
Neelay Shah committed
79
+        if self.kv_connector == "DynamoNixlConnector":
ptarasiewiczNV's avatar
ptarasiewiczNV committed
80
81
82
83
+            return False
         return self.kv_connector is not None and self.kv_parallel_size > 1
 
     @property
84
@@ -2706,6 +2737,18 @@ class KVTransferConfig(BaseModel):
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
         return self.kv_connector is not None and \
             self.kv_role in ["kv_consumer", "kv_both"]
 
+    @property
+    def tensor_parallel_multiplier(self) -> int:
+        return self.kv_consumers_tensor_parallel_size // self.kv_producers_tensor_parallel_size
+
+    @property
+    def kv_consumers_parallel_size(self) -> int:
+        return self.kv_parallel_size - self.kv_producers_parallel_size
+
+    @property
+    def kv_world_size(self) -> int:
+        return self.kv_producers_parallel_size + self.kv_consumers_parallel_size * self.tensor_parallel_multiplier
+
 
 class CompilationLevel:
     # constants for the levels of the compilation process
103
diff --git a/vllm/core/block/cpu_gpu_block_allocator.py b/vllm/core/block/cpu_gpu_block_allocator.py
104
index 359b5b263..7bac45ff0 100644
105
106
--- a/vllm/core/block/cpu_gpu_block_allocator.py
+++ b/vllm/core/block/cpu_gpu_block_allocator.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 
 from typing import Dict, FrozenSet, List, Optional, Tuple
 
@@ -6,6 +19,7 @@ from vllm.core.block.interfaces import (Block, BlockAllocator, BlockId,
126
127
128
129
130
131
132
                                         DeviceAwareBlockAllocator)
 from vllm.core.block.naive_block import NaiveBlock, NaiveBlockAllocator
 from vllm.core.block.prefix_caching_block import PrefixCachingBlockAllocator
+from vllm.core.event_manager import KVCacheEventManager
 from vllm.platforms import current_platform
 from vllm.utils import Device
 
133
@@ -28,6 +42,7 @@ class CpuGpuBlockAllocator(DeviceAwareBlockAllocator):
134
135
136
137
138
139
140
         num_gpu_blocks: int,
         num_cpu_blocks: int,
         block_size: int,
+        event_manager: Optional[KVCacheEventManager] = None,
     ) -> DeviceAwareBlockAllocator:
         """Creates a CpuGpuBlockAllocator instance with the specified
         configuration.
141
@@ -64,6 +79,7 @@ class CpuGpuBlockAllocator(DeviceAwareBlockAllocator):
142
143
144
145
146
147
148
         cpu_block_ids = block_ids[num_gpu_blocks:]
 
         if allocator_type == "naive":
+            assert event_manager is None, "Event API not supported with naive allocator."
             gpu_allocator: BlockAllocator = NaiveBlockAllocator(
                 create_block=NaiveBlock,  # type: ignore
                 num_blocks=num_gpu_blocks,
149
@@ -82,12 +98,14 @@ class CpuGpuBlockAllocator(DeviceAwareBlockAllocator):
150
151
152
153
154
155
156
157
158
159
160
161
162
163
                 num_blocks=num_gpu_blocks,
                 block_size=block_size,
                 block_ids=gpu_block_ids,
+                event_manager=event_manager,
             )
 
             cpu_allocator = PrefixCachingBlockAllocator(
                 num_blocks=num_cpu_blocks,
                 block_size=block_size,
                 block_ids=cpu_block_ids,
+                event_manager=event_manager,
             )
         else:
             raise ValueError(f"Unknown allocator type {allocator_type=}")
164
@@ -95,10 +113,12 @@ class CpuGpuBlockAllocator(DeviceAwareBlockAllocator):
165
166
167
168
169
170
171
172
173
174
175
176
177
         return CpuGpuBlockAllocator(
             cpu_block_allocator=cpu_allocator,
             gpu_block_allocator=gpu_allocator,
+            event_manager=event_manager,
         )
 
     def __init__(self, cpu_block_allocator: BlockAllocator,
-                 gpu_block_allocator: BlockAllocator):
+                 gpu_block_allocator: BlockAllocator,
+                 event_manager: Optional[KVCacheEventManager] = None,):
         assert not (
             cpu_block_allocator.all_block_ids
             & gpu_block_allocator.all_block_ids
178
@@ -108,6 +128,7 @@ class CpuGpuBlockAllocator(DeviceAwareBlockAllocator):
179
180
181
182
183
184
185
             Device.CPU: cpu_block_allocator,
             Device.GPU: gpu_block_allocator,
         }
+        self.event_manager = event_manager
 
         self._swap_mapping: Dict[int, int] = {}
         self._null_block: Optional[Block] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
186
diff --git a/vllm/core/block/naive_block.py b/vllm/core/block/naive_block.py
187
index c388366b8..3c223b519 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
188
189
--- a/vllm/core/block/naive_block.py
+++ b/vllm/core/block/naive_block.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
@@ -1,8 +1,21 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
205
206
207
208
209
210
211
212
 
 from collections import deque
 from typing import Deque, FrozenSet, Iterable, List, Optional, Tuple, Union
-
+import heapq
 from vllm.core.block.common import (BlockPool, CopyOnWriteTracker, RefCounter,
                                     get_all_blocks_recursively)
 from vllm.core.block.interfaces import Block, BlockAllocator, BlockId, Device
213
@@ -38,7 +51,7 @@ class NaiveBlockAllocator(BlockAllocator):
214
215
216
217
218
219
220
221
         if block_ids is None:
             block_ids = range(num_blocks)
 
-        self._free_block_indices: Deque[BlockId] = deque(block_ids)
+        self._free_block_indices: List[BlockId] = list(block_ids)
         self._all_block_indices = frozenset(block_ids)
         assert len(self._all_block_indices) == num_blocks
 
222
@@ -134,7 +147,8 @@ class NaiveBlockAllocator(BlockAllocator):
223
         if not self._free_block_indices:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
224
225
             raise BlockAllocator.NoFreeBlocksError()
 
226
227
-        block_id = self._free_block_indices.popleft()
+        block_id = heapq.heappop(self._free_block_indices)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
228
229
230
231
+        # TODO: figure out why sometime block_id is None
         self._refcounter.incr(block_id)
         return block_id
 
232
@@ -148,7 +162,7 @@ class NaiveBlockAllocator(BlockAllocator):
233
234
235
236
237
238
239
240
 
         refcount = self._refcounter.decr(block_id)
         if refcount == 0:
-            self._free_block_indices.appendleft(block_id)
+            heapq.heappush(self._free_block_indices, block_id)
 
     def free(self, block: Block, keep_block_object: bool = False) -> None:
         # Release the physical block id
241
diff --git a/vllm/core/block/prefix_caching_block.py b/vllm/core/block/prefix_caching_block.py
242
index 1ca9e49da..26fabb243 100644
243
244
--- a/vllm/core/block/prefix_caching_block.py
+++ b/vllm/core/block/prefix_caching_block.py
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
@@ -1,10 +1,23 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """Token blocks."""
 import sys
262
263
264
265
266
267
268
269
 from bisect import bisect_left
 from os.path import commonprefix
 from typing import (Callable, Dict, FrozenSet, Iterable, List, Optional, Set,
-                    Tuple)
+                    Tuple, TYPE_CHECKING)
 
 from vllm.core.block.common import (CacheMetricData, CopyOnWriteTracker,
                                     get_all_blocks_recursively)
270
@@ -23,6 +36,9 @@ PrefixHash = int
271
272
273
274
275
276
277
278
279
 # then we know this block hasn't been accessed yet.
 _DEFAULT_LAST_ACCESSED_TIME = -1
 
+if TYPE_CHECKING:
+    from vllm.core.event_manager import KVCacheEventManager
+
 logger = init_logger(__name__)
 
 
280
@@ -80,6 +96,7 @@ class PrefixCachingBlockAllocator(BlockAllocator):
281
282
283
284
285
286
287
         block_size: int,
         block_ids: Optional[Iterable[int]] = None,
         eviction_policy: EvictionPolicy = EvictionPolicy.LRU,
+        event_manager: Optional["KVCacheEventManager"] = None,
     ):
         if block_ids is None:
             block_ids = range(num_blocks)
288
@@ -131,6 +148,9 @@ class PrefixCachingBlockAllocator(BlockAllocator):
289
290
291
292
293
294
295
296
297
 
         self.metric_data = CacheMetricData()
 
+        self.event_manager = event_manager
+
+    # Implements Block.Factory.
     def _create_block(
         self,
         prev_block: Optional[Block],
298
@@ -337,6 +357,9 @@ class PrefixCachingBlockAllocator(BlockAllocator):
299
300
301
302
303
304
305
306
307
         assert self._refcounter.get(_block_id) == 0
         assert _block_id == block_id
 
+        if self.event_manager:
+            self.event_manager.enqueue_removed_event(content_hash_to_evict)
+
         self._cached_blocks.pop(content_hash_to_evict)
 
         self._refcounter.incr(block_id)
308
@@ -513,6 +536,10 @@ class PrefixCachingBlockAllocator(BlockAllocator):
309
310
311
312
313
314
315
316
317
318
             # Mark this block as touched so that it can be marked as
             # computed after the entire batch of sequences are scheduled.
             self._touched_blocks.add(block.block_id)
+
+            if self.event_manager:
+                self.event_manager.enqueue_stored_event(block.prev_block, block)
+
             return block.block_id
 
         # Reuse the cached content hash
319
@@ -579,9 +606,11 @@ class PrefixCachingBlockAllocator(BlockAllocator):
320
321
322
323
324
325
326
327
328
329
330
331
332
333
 
     def mark_blocks_as_computed(self, block_ids: List[int]) -> None:
         # Mark all touched blocks as computed.
-        for block_id in self._touched_blocks:
-            self._block_tracker[block_id].computed = True
-        self._touched_blocks.clear()
+        for block_id in block_ids:
+            if block_id in self._touched_blocks:
+                logger.debug("Mark block as computed: %s", block_id)
+                self._block_tracker[block_id].computed = True
+                self._touched_blocks.remove(block_id)
 
     def _track_block_id(self, block_id: Optional[BlockId],
                         computed: bool) -> None:
334
diff --git a/vllm/core/block_manager.py b/vllm/core/block_manager.py
335
index c5b3b04f3..d3a4b77f8 100644
336
337
--- a/vllm/core/block_manager.py
+++ b/vllm/core/block_manager.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """A block manager that manages token blocks."""
 from typing import Dict, List, Optional
 from typing import Sequence as GenericSequence
@@ -10,7 +23,10 @@ from vllm.core.block.interfaces import Block
357
358
359
 from vllm.core.block.prefix_caching_block import (ComputedBlocksTracker,
                                                   LastAccessBlocksTracker)
 from vllm.core.block.utils import check_no_caching_or_swa_for_blockmgr_encdec
GuanLuo's avatar
GuanLuo committed
360
+from vllm.core.event_manager import KVCacheEventManager
361
 from vllm.core.interfaces import AllocStatus, BlockSpaceManager
GuanLuo's avatar
GuanLuo committed
362
363
+from vllm.envs import (VLLM_KV_CAPI_PATH, VLLM_KV_COMPONENT, VLLM_KV_NAMESPACE,
+                       VLLM_WORKER_ID)
364
365
366
 from vllm.sequence import Sequence, SequenceGroup, SequenceStatus
 from vllm.utils import Device
 
367
@@ -60,6 +76,7 @@ class SelfAttnBlockSpaceManager(BlockSpaceManager):
368
369
370
 
     def __init__(
         self,
GuanLuo's avatar
GuanLuo committed
371
+        model_name: str,
372
373
374
         block_size: int,
         num_gpu_blocks: int,
         num_cpu_blocks: int,
375
@@ -91,11 +108,29 @@ class SelfAttnBlockSpaceManager(BlockSpaceManager):
376
377
378
 
         self.watermark_blocks = int(watermark * num_gpu_blocks)
 
GuanLuo's avatar
GuanLuo committed
379
380
381
382
383
384
385
386
387
388
389
390
+        kv_event_manager_params = [
+            VLLM_WORKER_ID, VLLM_KV_CAPI_PATH, VLLM_KV_NAMESPACE,
+            VLLM_KV_COMPONENT
+        ]
+        set_kv_event_manager_params = len(
+            [param for param in kv_event_manager_params if param is not None])
+
+        if set_kv_event_manager_params == len(kv_event_manager_params):
+            self.event_manager = KVCacheEventManager(
+                namespace=VLLM_KV_NAMESPACE,
+                component=VLLM_KV_COMPONENT,
+                worker_id=VLLM_WORKER_ID,
391
392
+                lib_path=VLLM_KV_CAPI_PATH,
+                kv_block_size=block_size)
393
394
395
396
397
398
399
400
401
402
403
404
+        else:
+            self.event_manager = None
+
         self.block_allocator = CpuGpuBlockAllocator.create(
             allocator_type="prefix_caching" if enable_caching else "naive",
             num_gpu_blocks=num_gpu_blocks,
             num_cpu_blocks=num_cpu_blocks,
             block_size=block_size,
+            event_manager=self.event_manager,
         )
 
         self.block_tables: Dict[SeqId, BlockTable] = {}
405
@@ -108,7 +143,8 @@ class SelfAttnBlockSpaceManager(BlockSpaceManager):
406
407
408
409
410
411
412
413
414
 
     def can_allocate(self,
                      seq_group: SequenceGroup,
-                     num_lookahead_slots: int = 0) -> AllocStatus:
+                     num_lookahead_slots: int = 0,
+                     is_remote_decode: bool = False) -> AllocStatus:
         # FIXME(woosuk): Here we assume that all sequences in the group share
         # the same prompt. This may not be true for preempted sequences.
 
415
@@ -121,6 +157,10 @@ class SelfAttnBlockSpaceManager(BlockSpaceManager):
416
417
418
419
420
421
422
423
424
425
             num_lookahead_slots=num_lookahead_slots,
         )
 
+        # if remote decode, we need to allocate twice as many blocks for staging
+        if is_remote_decode: 
+            num_required_blocks *= 2
+
         if seq_group.is_encoder_decoder():
             encoder_seq = seq_group.get_encoder_seq()
             assert encoder_seq is not None
426
427
diff --git a/vllm/core/event_manager.py b/vllm/core/event_manager.py
new file mode 100644
428
index 000000000..79eb8db67
429
430
--- /dev/null
+++ b/vllm/core/event_manager.py
431
432
@@ -0,0 +1,121 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
GuanLuo's avatar
GuanLuo committed
433
+# SPDX-License-Identifier: Apache-2.0
434
435
436
437
438
439
440
441
442
443
444
445
+#
+# 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.
446
+import ctypes
GuanLuo's avatar
GuanLuo committed
447
+import logging
448
+import uuid
GuanLuo's avatar
GuanLuo committed
449
450
451
452
+from ctypes import c_char_p, c_size_t, c_uint32, c_void_p, c_int64
+from typing import Optional
+
+from vllm.core.block.prefix_caching_block import PrefixCachingBlock, PrefixHash
453
454
455
+
+logger = logging.getLogger(__name__)
+
GuanLuo's avatar
GuanLuo committed
456
+
Neelay Shah's avatar
Neelay Shah committed
457
+class DynamoResult:
458
459
460
+    OK = 0
+    ERR = 1
+
GuanLuo's avatar
GuanLuo committed
461
+
462
+class KVCacheEventManager:
GuanLuo's avatar
GuanLuo committed
463
464
+
+    def __init__(self, namespace: str, component: str, worker_id: int,
465
+                 lib_path: str, kv_block_size: int):
466
467
468
469
+        self.lib = None
+
+        try:
+            self.lib = ctypes.CDLL(lib_path)
470
471
472
473
474
475
+            self.lib.dynamo_llm_init.argtypes = [
+                c_char_p,
+                c_char_p,
+                c_int64,
+                c_uint32,
+            ]
Neelay Shah's avatar
Neelay Shah committed
476
+            self.lib.dynamo_llm_init.restype = c_uint32
477
+
478
479
480
+            result = self.lib.dynamo_llm_init(
+                namespace.encode(), component.encode(), worker_id, kv_block_size
+            )
Neelay Shah's avatar
Neelay Shah committed
481
+            if result == DynamoResult.OK:
GuanLuo's avatar
GuanLuo committed
482
483
484
+                logger.info(
+                    "KVCacheEventManager initialized successfully. Ready to publish KV Cache Events"
+                )
485
486
487
488
489
490
+            else:
+                logger.info("KVCacheEventManager initialization failed!")
+
+        except Exception as e:
+            print(f"Failed to load {lib_path}")
+            raise e
GuanLuo's avatar
GuanLuo committed
491
+
Neelay Shah's avatar
Neelay Shah committed
492
+        self.lib.dynamo_kv_event_publish_stored.argtypes = [
GuanLuo's avatar
GuanLuo committed
493
494
495
496
497
498
499
+            ctypes.c_uint64,  # event_id
+            ctypes.POINTER(ctypes.c_uint32),  # token_ids
+            ctypes.POINTER(ctypes.c_size_t),  # num_block_tokens
+            ctypes.POINTER(ctypes.c_uint64),  # block_ids
+            ctypes.c_size_t,  # num_blocks
+            ctypes.POINTER(ctypes.c_uint64),  # parent_hash
+            ctypes.c_uint64,  # lora_id
500
+        ]
Neelay Shah's avatar
Neelay Shah committed
501
+        self.lib.dynamo_kv_event_publish_stored.restype = ctypes.c_uint32  # dynamo_llm_result_t
502
+
Neelay Shah's avatar
Neelay Shah committed
503
+        self.lib.dynamo_kv_event_publish_removed.argtypes = [
GuanLuo's avatar
GuanLuo committed
504
505
506
+            ctypes.c_uint64,  # event_id
+            ctypes.POINTER(ctypes.c_uint64),  # block_ids
+            ctypes.c_size_t,  # num_blocks
507
+        ]
Neelay Shah's avatar
Neelay Shah committed
508
+        self.lib.dynamo_kv_event_publish_removed.restype = ctypes.c_uint32  # dynamo_llm_result_t
509
510
511
+
+        self.event_id_counter = 0
+
GuanLuo's avatar
GuanLuo committed
512
513
514
515
+    def enqueue_stored_event(self, parent: Optional[PrefixCachingBlock],
+                             block: PrefixCachingBlock):
+        token_ids_arr = (ctypes.c_uint32 *
+                         len(block.token_ids))(*block.token_ids)
516
517
+        num_block_tokens = (ctypes.c_size_t * 1)(len(block.token_ids))
+        block_hash = (ctypes.c_uint64 * 1)(block.content_hash)
GuanLuo's avatar
GuanLuo committed
518
519
+        parent_hash = ((ctypes.c_uint64 * 1)(parent.content_hash)
+                       if parent is not None else None)
520
521
+
+        # Publish the event
Neelay Shah's avatar
Neelay Shah committed
522
+        result = self.lib.dynamo_kv_event_publish_stored(
GuanLuo's avatar
GuanLuo committed
523
524
525
526
527
528
529
+            self.event_id_counter,  # uint64_t event_id
+            token_ids_arr,  # const uint32_t *token_ids
+            num_block_tokens,  # const uintptr_t *num_block_tokens
+            block_hash,  # const uint64_t *block_ids
+            1,  # uintptr_t num_blocks
+            parent_hash,  # const uint64_t *parent_hash
+            0,  # uint64_t lora_id
530
531
+        )
+
Neelay Shah's avatar
Neelay Shah committed
532
+        if result == DynamoResult.OK:
533
534
+            logger.debug(f"Store - Published KV Event: {block.content_hash}")
+        else:
GuanLuo's avatar
GuanLuo committed
535
536
+            logger.debug(
+                f"Store - Failed to Publish KV Event: {block.content_hash}")
537
538
539
540
+
+        self.event_id_counter += 1
+
+    def enqueue_removed_event(self, block_hash: PrefixHash):
Neelay Shah's avatar
Neelay Shah committed
541
+        result = self.lib.dynamo_kv_event_publish_removed(
542
543
+            self.event_id_counter,
+            (ctypes.c_uint64 * 1)(block_hash),
GuanLuo's avatar
GuanLuo committed
544
545
546
+            1,
+        )
+
Neelay Shah's avatar
Neelay Shah committed
547
+        if result == DynamoResult.OK:
548
549
550
551
552
553
+            logger.debug(f"Remove - Published KV Event: {block_hash}")
+        else:
+            logger.debug(f"Remove - Failed to Publish KV Event: {block_hash}")
+
+        self.event_id_counter += 1
diff --git a/vllm/core/scheduler.py b/vllm/core/scheduler.py
554
index f507847ad..3f3cba766 100644
555
556
--- a/vllm/core/scheduler.py
+++ b/vllm/core/scheduler.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
@@ -1,25 +1,38 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 enum
Neelay Shah's avatar
Neelay Shah committed
574
575
576
577
578
 import os
 import random
 import time
+import copy
 from collections import deque
ptarasiewiczNV's avatar
ptarasiewiczNV committed
579
580
 from dataclasses import dataclass, field
 from typing import Callable, Deque, Dict, Iterable, List, Optional
581
 from typing import Sequence as GenericSequence
ptarasiewiczNV's avatar
ptarasiewiczNV committed
582
583
-from typing import Set, Tuple, Union
+from typing import Set, Tuple, Union, Any
584
585
586
587
588
589
 
-from vllm.config import CacheConfig, LoRAConfig, SchedulerConfig
+from vllm.config import ModelConfig, CacheConfig, LoRAConfig, SchedulerConfig
 from vllm.core.interfaces import AllocStatus, BlockSpaceManager
 from vllm.logger import init_logger
 from vllm.lora.request import LoRARequest
ptarasiewiczNV's avatar
ptarasiewiczNV committed
590
591
592
593
594
595
596
597
598
599
 from vllm.prompt_adapter.request import PromptAdapterRequest
 from vllm.sequence import (Sequence, SequenceData, SequenceGroup,
                            SequenceGroupMetadata, SequenceGroupMetadataDelta,
-                           SequenceStatus)
+                           SequenceStatus, SequenceStage)
 from vllm.utils import Device, PyObjectCache
-
 logger = init_logger(__name__)
 
 # Test-only. If configured, decode is preempted with
600
@@ -285,6 +298,7 @@ class SchedulerPrefillOutputs:
601
602
603
604
605
606
607
     # Ignored sequence groups.
     ignored_seq_groups: List[SequenceGroup]
     num_lookahead_slots: int
+    num_remote_prefill_groups: int
 
     @classmethod
     def create_empty(cls) -> "SchedulerPrefillOutputs":
608
@@ -292,6 +306,7 @@ class SchedulerPrefillOutputs:
609
610
611
612
613
614
615
             seq_groups=[],
             ignored_seq_groups=[],
             num_lookahead_slots=0,
+            num_remote_prefill_groups=0,
         )
 
 
616
@@ -325,12 +340,14 @@ class Scheduler:
617
618
619
620
621
622
623
624
625
626
627
628
629
630
 
     def __init__(
         self,
+        model_config: ModelConfig,
         scheduler_config: SchedulerConfig,
         cache_config: CacheConfig,
         lora_config: Optional[LoRAConfig],
         pipeline_parallel_size: int = 1,
         output_proc_callback: Optional[Callable] = None,
     ) -> None:
+        self.model_config = model_config
         self.scheduler_config = scheduler_config
         self.cache_config = cache_config
         # Note for LoRA scheduling: the current policy is extremely
631
@@ -356,6 +373,7 @@ class Scheduler:
632
633
634
635
636
637
638
 
         # Create the block space manager.
         self.block_manager = BlockSpaceManagerImpl(
+            model_name=self.model_config.served_model_name,
             block_size=self.cache_config.block_size,
             num_gpu_blocks=num_gpu_blocks,
             num_cpu_blocks=num_cpu_blocks,
639
@@ -371,6 +389,16 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
640
641
642
643
644
645
646
         # Sequence groups in the SWAPPED state.
         # Contain decode requests that are swapped out.
         self.swapped: Deque[SequenceGroup] = deque()
+
+        # Sequence groups in the REMOTE_PREFILLING state.
+        # Contain requests that are being prefilled by a remote worker.
+        self.remote_prefilling: Deque[SequenceGroup] = deque()
Neelay Shah's avatar
Neelay Shah committed
647
648
+        # Contain requests that are being prefilled by a local worker.
+        self.prefill_sending: Deque[SequenceGroup] = deque()
ptarasiewiczNV's avatar
ptarasiewiczNV committed
649
650
651
652
653
654
655
+
+        self._remote_prefill_outputs: Dict[str, int] = {}
+
+
         # Sequence groups finished requests ids since last step iteration.
         # It lets the model know that any state associated with these requests
         # can and must be released after the current step.
656
@@ -501,7 +529,7 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
657
658
659
660
 
     def has_unfinished_seqs(self) -> bool:
         return len(self.waiting) != 0 or len(self.running) != 0 or len(
-            self.swapped) != 0
Neelay Shah's avatar
Neelay Shah committed
661
+            self.swapped) != 0 or len(self.remote_prefilling) != 0 or len(self.prefill_sending) != 0
ptarasiewiczNV's avatar
ptarasiewiczNV committed
662
663
664
 
     def get_prefix_cache_hit_rate(self, device: Device) -> float:
         return self.block_manager.get_prefix_cache_hit_rate(device)
665
@@ -523,6 +551,8 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
666
667
668
         budget: SchedulingBudget,
         curr_loras: Optional[Set[int]],
         enable_chunking: bool = False,
Neelay Shah's avatar
Neelay Shah committed
669
670
+        finished_prefills: Optional[Set[str]] = None,
+        finished_transfers: Optional[Set[str]] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
671
672
673
     ) -> SchedulerRunningOutputs:
         """Schedule sequence groups that are running.
 
674
@@ -537,6 +567,8 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
675
676
677
678
679
680
681
682
                 chunked number of tokens are scheduled  if
                 `budget.num_batched_tokens` has not enough capacity to schedule
                 all tokens.
+            finished_remote_prefill_request_ids: Set of request ids of remote
+                prefills that have finished.
     
         Returns:
             SchedulerRunningOutputs.
683
@@ -566,6 +598,38 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
684
685
686
687
688
689
690
691
692
693
         preempted: List[SequenceGroup] = ret.preempted
         swapped_out: List[SequenceGroup] = ret.swapped_out
 
+        remote_prefilling_queue = self.remote_prefilling
+        leftover_remote_prefilling_sequences: Deque[SequenceGroup] = deque()
+        while remote_prefilling_queue:
+            seq_group = remote_prefilling_queue.popleft()
+            if seq_group.request_id not in finished_prefills:
+                leftover_remote_prefilling_sequences.append(seq_group)
+                continue
Neelay Shah's avatar
Neelay Shah committed
694
+                
ptarasiewiczNV's avatar
ptarasiewiczNV committed
695
696
697
698
699
700
701
702
703
704
+            else:
+                finished_prefills.remove(seq_group.request_id)
+                assert len(seq_group.seqs) == 1
+                seq = seq_group.seqs[0]
+                # we computed all but the last token in prefill, we need to decode the first token on decode
+                seq_group.update_num_computed_tokens(seq.get_len() - 1)
+                seq.status = SequenceStatus.RUNNING
+                seq.data._stage = SequenceStage.DECODE
+                self.running.appendleft(seq_group)
+        remote_prefilling_queue.extendleft(leftover_remote_prefilling_sequences)
Neelay Shah's avatar
Neelay Shah committed
705
706
707
708
709
710
711
712
713
714
715
716
717
+
+        remote_transfers_queue = self.prefill_sending
+        leftover_remote_transfers_sequences: Deque[SequenceGroup] = deque()
+        while remote_transfers_queue:
+            seq_group = remote_transfers_queue.popleft()
+            if seq_group.request_id not in finished_transfers:
+                leftover_remote_transfers_sequences.append(seq_group)
+            else:
+                finished_transfers.remove(seq_group.request_id)
+                assert len(seq_group.seqs) == 1
+                seq = seq_group.seqs[0]
+                self.free_seq(seq)
+        remote_transfers_queue.extendleft(leftover_remote_transfers_sequences)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
718
719
720
721
+
         running_queue = self.running
         assert len(self._async_stopped) == 0
         while running_queue:
722
@@ -925,6 +989,7 @@ class Scheduler:
723
724
725
726
727
728
729
         seq_groups: List[ScheduledSequenceGroup] = []
 
         waiting_queue = self.waiting
+        num_remote_prefill_groups = 0
 
         leftover_waiting_sequences: Deque[SequenceGroup] = deque()
         while self._passed_delay(time.time()) and waiting_queue:
730
@@ -961,8 +1026,10 @@ class Scheduler:
731
732
733
734
735
736
737
738
739
740
741
                     True, enable_chunking)
 
             # If the sequence group cannot be allocated, stop.
+            is_remote_decode = seq_group.remote_prefill_params is not None and seq_group.remote_prefill_params.is_remote_decode
             can_allocate = self.block_manager.can_allocate(
-                seq_group, num_lookahead_slots=num_lookahead_slots)
+                seq_group, num_lookahead_slots=num_lookahead_slots,
+                is_remote_decode=is_remote_decode)
             if can_allocate == AllocStatus.LATER:
                 break
             elif can_allocate == AllocStatus.NEVER:
742
@@ -1008,7 +1075,18 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
743
744
745
746
             if curr_loras is not None and lora_int_id > 0:
                 curr_loras.add(lora_int_id)
             waiting_queue.popleft()
-            self._allocate_and_set_running(seq_group)
Neelay Shah's avatar
Neelay Shah committed
747
748
749
750
751
752
+
+            seq_group_copy = copy.deepcopy(seq_group)
+            seq_group_copy.seqs[0].seq_id = seq_group.seqs[0].seq_id + 1
+
+            logger.debug("Allocating and setting running or remote prefill for seq_group %s", seq_group.request_id)
+            logger.debug("Seq id: %s", seq_group.seqs[0].seq_id)
753
754
+            is_remote_prefill = self._allocate_and_set_running_or_remote_prefill(seq_group)
+            num_remote_prefill_groups += is_remote_prefill
755
+            if is_remote_decode:
Neelay Shah's avatar
Neelay Shah committed
756
757
758
+                logger.debug("Seq id: %s", seq_group_copy.seqs[0].seq_id)
+                self._allocate_and_set_running_or_remote_prefill(seq_group_copy)
+                self.prefill_sending.append(seq_group_copy)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
759
760
761
 
             if enable_chunking and self.scheduler_config.is_multi_step:
                 blocks_to_copy: List[Tuple[int, int]] = []
762
@@ -1046,9 +1124,11 @@ class Scheduler:
763
764
             seq_groups=seq_groups,
             ignored_seq_groups=ignored_seq_groups,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
765
             num_lookahead_slots=self._get_num_lookahead_slots(
766
767
768
769
-                is_prefill=True, enable_chunking=enable_chunking))
+                is_prefill=True, enable_chunking=enable_chunking),
+            num_remote_prefill_groups=num_remote_prefill_groups
+        )
ptarasiewiczNV's avatar
ptarasiewiczNV committed
770
771
 
-    def _schedule_default(self) -> SchedulerOutputs:
Neelay Shah's avatar
Neelay Shah committed
772
+    def _schedule_default(self, finished_prefills: Optional[Set[str]] = None, finished_transfers: Optional[Set[str]] = None) -> SchedulerOutputs:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
773
774
775
         """Schedule queued requests.
         
         The current policy is designed to optimize the throughput. First,
776
@@ -1066,9 +1146,13 @@ class Scheduler:
777
778
779
         for seq_group in self.running:
             budget.add_num_seqs(seq_group.request_id,
                                 seq_group.get_max_num_running_seqs())
780
781
-        curr_loras = set(
+        for seq_group in self.remote_prefilling:
782
783
+            budget.add_num_seqs(seq_group.request_id,
+                                seq_group.get_max_num_running_seqs())
784
785
+            
+        curr_loras = (set(
786
             seq_group.lora_int_id for seq_group in self.running
787
788
789
790
791
-            if seq_group.lora_int_id > 0) if self.lora_enabled else None
+            if seq_group.lora_int_id > 0) if self.lora_enabled else None)
 
         prefills = SchedulerPrefillOutputs.create_empty()
         running_scheduled = SchedulerRunningOutputs.create_empty()
792
@@ -1090,7 +1174,9 @@ class Scheduler:
793
         if len(prefills.seq_groups) == 0:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
794
795
796
797
             running_scheduled = self._schedule_running(budget,
                                                        curr_loras,
-                                                       enable_chunking=False)
+                                                       enable_chunking=False,
Neelay Shah's avatar
Neelay Shah committed
798
799
+                                                       finished_prefills=finished_prefills,
+                                                       finished_transfers=finished_transfers)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
800
801
802
 
             # If any sequence group is preempted, do not swap in any sequence
             # group. because it means there's no slot for new running requests.
803
@@ -1106,7 +1192,12 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
804
805
806
807
808
809
810
811
812
813
814
815
816
         self.waiting.extendleft(running_scheduled.preempted)
         # Update new running requests.
         if len(prefills.seq_groups) > 0:
-            self.running.extend([s.seq_group for s in prefills.seq_groups])
+            for s in prefills.seq_groups:
+                seq_group = s.seq_group
+                if seq_group.remote_prefill_params is not None and seq_group.remote_prefill_params.is_remote_prefill:
+                    self.remote_prefilling.append(seq_group)
+                else:
+                    self.running.append(seq_group)
 
         self.running.extend(running_scheduled.decode_seq_groups_list)
 
817
@@ -1248,12 +1339,14 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
818
819
820
821
                        len(running_scheduled.swapped_out)),
         )
 
-    def _schedule(self) -> SchedulerOutputs:
Neelay Shah's avatar
Neelay Shah committed
822
+    def _schedule(self, finished_prefills: Optional[Set[str]] = None, finished_transfers: Optional[Set[str]] = None) -> SchedulerOutputs:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
823
824
         """Schedule queued requests."""
         if self.scheduler_config.chunked_prefill_enabled:
Neelay Shah's avatar
Neelay Shah committed
825
+            if finished_prefills or finished_transfers:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
826
827
828
829
+                raise ValueError("Chunked prefill does not support remote prefills")
             return self._schedule_chunked_prefill()
         else:
-            return self._schedule_default()
Neelay Shah's avatar
Neelay Shah committed
830
+            return self._schedule_default(finished_prefills, finished_transfers)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
831
832
833
 
     def _can_append_slots(self, seq_group: SequenceGroup,
                           enable_chunking: bool) -> bool:
834
@@ -1287,14 +1380,16 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
835
836
837
838
839
         return no_single_seq
 
     def schedule(
-            self
+            self,
Neelay Shah's avatar
Neelay Shah committed
840
841
+            finished_prefills: Optional[Set[str]] = None,
+            finished_transfers: Optional[Set[str]] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
842
843
844
845
846
847
848
849
     ) -> Tuple[List[SequenceGroupMetadata], SchedulerOutputs, bool]:
         # Schedule sequence groups.
         # This function call changes the internal states of the scheduler
         # such as self.running, self.swapped, and self.waiting.
-        scheduler_start_time = time.perf_counter()
 
-        scheduler_outputs: SchedulerOutputs = self._schedule()
+        scheduler_start_time = time.perf_counter()
Neelay Shah's avatar
Neelay Shah committed
850
+        scheduler_outputs: SchedulerOutputs = self._schedule(finished_prefills, finished_transfers)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
851
852
853
         now = time.time()
 
         if not self.cache_config.enable_prefix_caching:
854
@@ -1333,7 +1428,8 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
855
856
857
858
859
860
861
862
863
                 encoder_seq_data = None
                 cross_block_table = None
 
-            for seq in seq_group.get_seqs(status=SequenceStatus.RUNNING):
+            running_or_remote_prefilling_seqs = seq_group.get_seqs(status=SequenceStatus.RUNNING) + seq_group.get_seqs(status=SequenceStatus.REMOTE_PREFILLING)
+            for seq in running_or_remote_prefilling_seqs:
                 seq_id = seq.seq_id
                 seq_data[seq_id] = seq.data
                 block_tables[seq_id] = self.block_manager.get_block_table(seq)
864
@@ -1342,7 +1438,9 @@ class Scheduler:
865
866
867
868
869
870
871
872
873
874
             if self.cache_config.enable_prefix_caching:
                 common_computed_block_nums = (
                     self.block_manager.get_common_computed_block_ids(
-                        seq_group.get_seqs(status=SequenceStatus.RUNNING)))
+                        running_or_remote_prefilling_seqs
+                    )
+                )
 
             do_sample = True
             is_prompt = seq_group.is_prefill()
875
@@ -1364,9 +1462,30 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
876
877
878
879
880
881
                         < seqs[0].data.get_len()):
                     do_sample = False
 
+            is_remote_prefill = False
+            if is_first_prefill and seq_group.remote_prefill_params is not None and seq_group.remote_prefill_params.is_remote_prefill:
+                is_remote_prefill = True
882
+                logger.debug("Remote prefill, computed block nums: %s", common_computed_block_nums)
Neelay Shah's avatar
Neelay Shah committed
883
884
+            if is_first_prefill and seq_group.remote_prefill_params is not None and seq_group.remote_prefill_params.is_remote_decode:
+                block_tables[seq_group.seqs[0].seq_id + 1] = self.block_manager.block_tables[seq.seq_id + 1].physical_block_ids
885
886
887
888
889
890
891
892
893
894
895
896
897
+
+                # Since we know that prefill is scheduled we can
+                # assume that the blocks computed on decode
+                # will be fetched by the time we run prefill
+                logger.debug("Computed decode blocks: %s", seq_group.remote_prefill_params.decode_computed_block_ids)
+                if seq_group.remote_prefill_params.decode_computed_block_ids:
+                    computed_block_ids = set(seq_group.remote_prefill_params.decode_computed_block_ids)
+                    prefill_block_ids = block_tables[seq_group.seqs[0].seq_id]
+                    prefill_fetched_block_ids = [prefill_block_ids[i] for i, block_id in enumerate(seq_group.remote_prefill_params.decode_block_ids) if block_id in computed_block_ids and i < len(prefill_block_ids)]
+                    
+                    assert len(common_computed_block_nums) == 0, "common_computed_block_nums should be empty for remote prefill as it doesn't suport prefix caching"
+                    common_computed_block_nums = prefill_fetched_block_ids
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
898
899
900
901
+
             # It assumes the scheduled_seq_groups is ordered by
             # prefill < decoding.
             if is_first_prefill or not self.scheduler_config.send_delta_data:
Neelay Shah's avatar
Neelay Shah committed
902
903
904
905
+                logger.debug("Assinged blocks: %s", block_tables)
                 seq_group_metadata = SequenceGroupMetadata(
                     request_id=seq_group.request_id,
                     is_prompt=is_prompt,
906
@@ -1392,6 +1511,7 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
907
908
909
910
911
912
913
                     if scheduler_outputs.num_prefill_groups > 0 else None,
                     mm_processor_kwargs=seq_group.mm_processor_kwargs,
                     prompt_adapter_request=seq_group.prompt_adapter_request,
+                    do_remote_prefill=is_remote_prefill,
                 )
             else:
                 # When SPMD mode is enabled, we only send delta data except for
914
@@ -1490,11 +1610,17 @@ class Scheduler:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
915
916
917
918
 
             self._async_stopped.clear()
 
-    def _allocate_and_set_running(self, seq_group: SequenceGroup) -> None:
919
+    def _allocate_and_set_running_or_remote_prefill(self, seq_group: SequenceGroup) -> bool:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
920
         self.block_manager.allocate(seq_group)
921
+        is_remote_prefill = False
ptarasiewiczNV's avatar
ptarasiewiczNV committed
922
923
         for seq in seq_group.get_seqs(status=SequenceStatus.WAITING):
-            seq.status = SequenceStatus.RUNNING
924
-
ptarasiewiczNV's avatar
ptarasiewiczNV committed
925
926
+            if seq_group.remote_prefill_params is not None and seq_group.remote_prefill_params.is_remote_prefill:
+                seq.status = SequenceStatus.REMOTE_PREFILLING
927
+                is_remote_prefill = True
ptarasiewiczNV's avatar
ptarasiewiczNV committed
928
929
+            else:
+                seq.status = SequenceStatus.RUNNING
930
931
+        return is_remote_prefill
+    
ptarasiewiczNV's avatar
ptarasiewiczNV committed
932
933
     def _append_slots(self,
                       seq_group: SequenceGroup,
934
                       blocks_to_copy: List[Tuple[int, int]],
Neelay Shah's avatar
Neelay Shah committed
935
936
diff --git a/vllm/distributed/device_communicators/kv_rearrange.py b/vllm/distributed/device_communicators/kv_rearrange.py
new file mode 100644
937
index 000000000..a2f9ce99e
Neelay Shah's avatar
Neelay Shah committed
938
939
--- /dev/null
+++ b/vllm/distributed/device_communicators/kv_rearrange.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
@@ -0,0 +1,125 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
Neelay Shah's avatar
Neelay Shah committed
956
957
958
959
960
+import torch
+import triton
+import triton.language as tl
+
+@triton.jit
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
+def rearrange_kernel_read(
+    t1_ptr,
+    t2_ptr,
+    N,
+    B,
+    H,
+    C,
+    d,
+    tensor_subset_size,
+    block_size,
+    token_size,
+    BLOCK_SIZE: tl.constexpr,
+):
+    pid = tl.program_id(0)
+    
+    block_start = pid * BLOCK_SIZE
+    offsets = block_start + tl.arange(0, BLOCK_SIZE)
+
+    curr_n = offsets // block_size
+    curr_b = offsets // token_size % B
+    curr_h = offsets // C % H 
+    curr_c = offsets % C
+
+    src_pos = offsets
+
+    tp_group = curr_h * d // H
+    dst_h = curr_h % (H // d)
+    tp_group_offset = curr_n * (block_size // d) + curr_b * (H // d) * C + dst_h * C + curr_c
+
+    dst_pos = tensor_subset_size * tp_group + tp_group_offset
+    
+    tl.store(t1_ptr + src_pos, tl.load(t2_ptr + dst_pos))
+
+@triton.jit
+def rearrange_kernel_write(
Neelay Shah's avatar
Neelay Shah committed
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
+    t1_ptr,
+    t2_ptr,
+    N,
+    B,
+    H,
+    C,
+    d,
+    tensor_subset_size,
+    block_size,
+    token_size,
+    BLOCK_SIZE: tl.constexpr,
+):
+    pid = tl.program_id(0)
+    
+    block_start = pid * BLOCK_SIZE
+    offsets = block_start + tl.arange(0, BLOCK_SIZE)
+
+    curr_n = offsets // block_size
+    curr_b = offsets // token_size % B
+    curr_h = offsets // C % H 
+    curr_c = offsets % C
+
+    src_pos = offsets
+
+    tp_group = curr_h * d // H
+    dst_h = curr_h % (H // d)
+    tp_group_offset = curr_n * (block_size // d) + curr_b * (H // d) * C + dst_h * C + curr_c
+
+    dst_pos = tensor_subset_size * tp_group + tp_group_offset
+    
+    tl.store(t2_ptr + dst_pos, tl.load(t1_ptr + src_pos))
1027
1028
+    
+
Neelay Shah's avatar
Neelay Shah committed
1029
+
1030
+def rearrange_tensors(t1: torch.Tensor, t2: torch.Tensor, d: int, direction: str):
Neelay Shah's avatar
Neelay Shah committed
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
+    N, B, H, C = t1.shape
+    
+    assert t2.shape == (N, B, H, C), "Destination tensor must have same shape as source"
+    assert H % d == 0, "H must be divisible by d"
+
+    block_size = B * H * C
+    token_size = H * C
+    tensor_size = N * block_size
+    tensor_subset_size = tensor_size // d
+    
+    BLOCK_SIZE = 1024
+    grid = ((N * B * H * C + BLOCK_SIZE - 1) // BLOCK_SIZE,)
+    
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
+    if direction == "read":
+        rearrange_kernel_read[grid](
+            t1, t2,
+            N, B, H, C,
+            d,
+            tensor_subset_size,
+            block_size,
+            token_size,
+            BLOCK_SIZE=BLOCK_SIZE
+        )
+    elif direction == "write":
+        rearrange_kernel_write[grid](
+            t1, t2,
+            N, B, H, C,
+            d,
+            tensor_subset_size,
+            block_size,
+            token_size,
+            BLOCK_SIZE=BLOCK_SIZE
+        )
+    else:
+        raise ValueError(f"Invalid direction: {direction}")
Neelay Shah's avatar
Neelay Shah committed
1066
\ No newline at end of file
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1067
1068
diff --git a/vllm/distributed/device_communicators/nixl.py b/vllm/distributed/device_communicators/nixl.py
new file mode 100644
1069
index 000000000..136a0bd37
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1070
1071
--- /dev/null
+++ b/vllm/distributed/device_communicators/nixl.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
@@ -0,0 +1,394 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1088
1089
1090
1091
1092
1093
1094
+import torch
+from typing import List, Tuple
+from vllm.config import VllmConfig
+from vllm.logger import init_logger
+import msgspec
+import time
+import uuid
Neelay Shah's avatar
Neelay Shah committed
1095
1096
+from collections import defaultdict
+from .kv_rearrange import rearrange_tensors
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1097
1098
1099
+
+logger = init_logger(__name__)
+
Neelay Shah's avatar
Neelay Shah committed
1100
1101
+# Lazy import nixl_wrapper to avoid loading nixl_bindings if nixl is not used
+try:
1102
+    from nixl._api import nixl_agent as NixlWrapper
Neelay Shah's avatar
Neelay Shah committed
1103
1104
1105
1106
+    logger.info("NIXL is available")
+except ImportError:
+    logger.warning("NIXL is not available")
+    NixlWrapper = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1107
1108
1109
1110
1111
1112
1113
1114
1115
+
+class NixlMetadata(
+        msgspec.Struct,
+        omit_defaults=True,  # type: ignore[call-arg]
+        # required for @cached_property.
+        dict=True):
+    engine_id: str
+    agent_metadata: List[bytes]
+    kv_caches_base_addr: List[List[Tuple[int, int]]] # base address for each rank for each layer for keys and values
1116
+    num_blocks: int
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1117
1118
+
+
Neelay Shah's avatar
Neelay Shah committed
1119
+class DynamoNixlConnector:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1120
1121
+    def __init__(self, vllm_config: VllmConfig, engine_id: str, rank: int):
+        self.vllm_config = vllm_config
Neelay Shah's avatar
Neelay Shah committed
1122
1123
1124
1125
+        if NixlWrapper is None:
+            logger.error("NIXL is not available")
+            raise RuntimeError("NIXL is not available")
+        logger.info("Initializing NIXL wrapper")
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1126
1127
+        self.nixl_wrapper = NixlWrapper(str(uuid.uuid4()), None)
+
1128
1129
+        self.use_prepped_xfer = vllm_config.kv_transfer_config.use_prepped_xfer
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1130
1131
+        self.num_layers = None
+        self.num_blocks = None
Neelay Shah's avatar
Neelay Shah committed
1132
+        self.num_heads = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1133
+        self.block_len = None
Neelay Shah's avatar
Neelay Shah committed
1134
+        self.kv_caches = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1135
1136
1137
1138
1139
1140
1141
+        self.kv_caches_base_addr = {}
+        self.kv_cache_shape = {}
+
+        self._registered_descs = []
+        self._remote_agents = {}
+        self.engine_id = engine_id
+        self.rank = rank
Neelay Shah's avatar
Neelay Shah committed
1142
+        self._tp_size = {}
1143
1144
1145
+        self.src_xfer_side_handles = {}
+        self.dst_xfer_side_handles = defaultdict(dict)
+        self.dst_num_blocks = {}
Neelay Shah's avatar
Neelay Shah committed
1146
1147
1148
1149
1150
1151
+
+        self._transfers = defaultdict(list)
+
+
+        self._tp_size[engine_id] = vllm_config.parallel_config.tensor_parallel_size
+        
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1152
1153
1154
1155
1156
1157
+
+    @property
+    def agent_name(self):
+        return self.nixl_wrapper.name
+
+    def register_kv_caches(self, kv_caches: List[torch.Tensor]):
Neelay Shah's avatar
Neelay Shah committed
1158
+        _, num_blocks, block_size, num_heads, head_dim = kv_caches[0].shape
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1159
1160
+        self.block_len = block_size * num_heads * head_dim * kv_caches[0].element_size()
+        logger.debug("Per layer kv cache size: %s", kv_caches[0].shape)
Neelay Shah's avatar
Neelay Shah committed
1161
1162
1163
1164
+        self.num_layers = len(kv_caches)
+        self.num_blocks = num_blocks
+        self.num_heads = num_heads
+        self.kv_caches = kv_caches
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1165
+        kv_caches_base_addr = []
Neelay Shah's avatar
Neelay Shah committed
1166
+        caches_data = []
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1167
+        for key_cache, value_cache in kv_caches:
1168
1169
+            base_addr = key_cache.data_ptr()
+            region_len = 2 * num_blocks * self.block_len
1170
+            caches_data.append((base_addr, region_len, self.rank, ""))
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1171
+            kv_caches_base_addr.append((key_cache.data_ptr(), value_cache.data_ptr()))
1172
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1173
1174
+        self.kv_caches_base_addr[self.engine_id] = kv_caches_base_addr
+
1175
+        descs = self.nixl_wrapper.get_reg_descs(caches_data, "VRAM")
Neelay Shah's avatar
Neelay Shah committed
1176
+        logger.debug("Registering descs: %s", caches_data)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1177
1178
1179
1180
1181
1182
1183
1184
1185
+        self.nixl_wrapper.register_memory(descs)
+        self._registered_descs.append(descs)
+
+    def get_agent_metadata(self):
+        return self.nixl_wrapper.get_agent_metadata()
+    
+    def shutdown(self):
+        for descs_list in self._registered_descs:
+            self.nixl_wrapper.deregister_memory(descs_list)
1186
1187
1188
1189
+        for agent_names in self._remote_agents.values():
+            for agent_name in agent_names:
+                self.nixl_wrapper.remove_remote_agent(agent_name)
+        for src_xfer_side_handle in self.src_xfer_side_handles.values():
1190
+            self.nixl_wrapper.release_dlist_handle(src_xfer_side_handle)
1191
1192
+        for dst_xfer_side_handles in self.dst_xfer_side_handles.values():
+            for dst_xfer_side_handle in dst_xfer_side_handles.values():
1193
+                self.nixl_wrapper.delete_xfer_side(dst_xfer_side_handle)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1194
1195
1196
1197
1198
1199
1200
1201
+
+    def _get_ranges(self, block_ids):
+        # This function should return a list of ranges of block ids that are contiguous
+        # For example, if block_ids is [0, 1, 2, 4, 5, 6], the function should return [[0, 2], [4, 6]]
+        # The ranges are sorted by the starting block id
+        # The function should also make sure that the block ids are contiguous
+        # If the block ids are not contiguous, the function should raise an error
+        ranges = []
1202
1203
1204
+        for i in range(len(block_ids)):
+            if i == 0 or block_ids[i] != block_ids[i-1] + 1:
+                ranges.append([block_ids[i], block_ids[i]])
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1205
+            else:
1206
+                ranges[-1][1] = block_ids[i]
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1207
1208
+        return ranges
+
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
+    def _get_block_descs_ids(self, engine_id, layer_ids, block_ids, i=None, tp_multiplier=1, staging_ranges=None):
+
+        if layer_ids == "all":
+            layer_ids = list(range(self.num_layers))
+        if block_ids == "all":
+            block_ids = list(range(self.num_blocks))
+
+        descs_ids = []
+
+
+        if i is not None:
+            num_blocks = self.num_blocks
+            for layer_id in layer_ids:
+                for is_value in [0, 1]:
+                    staging_range_idx = 0
+                    for block_id in block_ids:
+                        if block_id > staging_ranges[staging_range_idx][1] or block_id < staging_ranges[staging_range_idx][0]:
+                            staging_range_idx += 1
+                        start_offset = staging_ranges[staging_range_idx][0]
+                        i_offset = i * (staging_ranges[staging_range_idx][-1] - start_offset + 1)
+                        descs_ids.append(layer_id * 2 * num_blocks * tp_multiplier + is_value * num_blocks * tp_multiplier + start_offset * tp_multiplier + i_offset + (block_id - start_offset))
+        else:
+            num_blocks = self.dst_num_blocks[engine_id]
+            for layer_id in layer_ids:
+                for is_value in [0, 1]:
+                    for block_id in block_ids:
+                        descs_ids.append(layer_id * 2 * num_blocks + is_value * num_blocks + block_id)
+        return descs_ids
+
1238
+    def _get_same_length_ranges(self, src_ranges, dst_ranges, return_original_src_ranges=False):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1239
1240
1241
1242
+        # This function should return a list of ranges for both src and dst so that corresponding ranges are the same length
+        # For example, if src_ranges is [[0, 2] [4, 8]] and dst_ranges is [[1, 3], [5, 7], [9, 10]]
+        # The function should return ([[0, 2], [4, 6], [7, 8]], [[1, 3], [5, 7], [9, 10]])
+        src_overlapping_ranges, dst_overlapping_ranges = [], []
1243
1244
1245
+
+        original_src_ranges = []
+        org_src_range = tuple(src_ranges[0])
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
+        
+        src_idx, dst_idx = 0, 0
+        while src_idx < len(src_ranges) and dst_idx < len(dst_ranges):
+            src_range = src_ranges[src_idx]
+            dst_range = dst_ranges[dst_idx]
+            
+            # Calculate the length of each range
+            src_len = src_range[-1] - src_range[0] + 1
+            dst_len = dst_range[-1] - dst_range[0] + 1
+            
+            # If ranges have the same length, add them directly
+            if src_len == dst_len:
+                src_overlapping_ranges.append([src_range[0], src_range[-1]])
+                dst_overlapping_ranges.append([dst_range[0], dst_range[-1]])
1260
+                original_src_ranges.append(org_src_range)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1261
1262
+                src_idx += 1
+                dst_idx += 1
1263
1264
+                if src_idx < len(src_ranges):
+                    org_src_range = tuple(src_ranges[src_idx])
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1265
1266
1267
1268
+            # If source range is longer, split it
+            elif src_len > dst_len:
+                src_overlapping_ranges.append([src_range[0], src_range[0] + dst_len - 1])
+                dst_overlapping_ranges.append([dst_range[0], dst_range[-1]])
1269
+                original_src_ranges.append(org_src_range)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1270
1271
1272
1273
1274
1275
1276
+                # Update source range for next iteration
+                src_ranges[src_idx] = [src_range[0] + dst_len, src_range[-1]]
+                dst_idx += 1
+            # If destination range is longer, split it
+            else:  # src_len < dst_len
+                src_overlapping_ranges.append([src_range[0], src_range[-1]])
+                dst_overlapping_ranges.append([dst_range[0], dst_range[0] + src_len - 1])
1277
+                original_src_ranges.append(org_src_range)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1278
1279
1280
+                # Update destination range for next iteration
+                dst_ranges[dst_idx] = [dst_range[0] + src_len, dst_range[-1]]
+                src_idx += 1
1281
1282
1283
1284
+                if src_idx < len(src_ranges):
+                    org_src_range = tuple(src_ranges[src_idx])
+        if return_original_src_ranges:
+            return src_overlapping_ranges, dst_overlapping_ranges, original_src_ranges
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1285
+        return src_overlapping_ranges, dst_overlapping_ranges
Neelay Shah's avatar
Neelay Shah committed
1286
+
1287
1288
+    def read_blocks(self, local_block_ids, staging_block_ids, remote_block_ids, dst_engine_id):
+        logger.debug("Reading %d blocks from %s to %s", len(local_block_ids), self.agent_name, dst_engine_id)
Neelay Shah's avatar
Neelay Shah committed
1289
+
1290
+        assert len(local_block_ids) == len(staging_block_ids) == len(remote_block_ids)
1291
+
1292
1293
1294
+        if len(local_block_ids) == 0:
+            logger.debug("No blocks to read")
+            return
1295
+
1296
1297
1298
1299
+        start_time = time.perf_counter()
+
+        local_ranges = self._get_ranges(local_block_ids)
+        staging_ranges = self._get_ranges(staging_block_ids)
1300
+
1301
+        local_rearranging_ranges, staging_rearranging_ranges = self._get_same_length_ranges(local_ranges, staging_ranges)
1302
+
1303
1304
1305
1306
+        tp_multiplier = self._tp_size[dst_engine_id] // self._tp_size[self.engine_id]
+        remote_block_descs_ids = self._get_block_descs_ids(dst_engine_id, "all", remote_block_ids)
+        local_xfer_side_handle = self.src_xfer_side_handles[tp_multiplier]
+        handles = []
1307
+
1308
1309
+        logger.debug("Time to get block descs ids: %s ms", (time.perf_counter() - start_time) * 1000)
+        create_xfer_start_time = time.perf_counter()
1310
+
1311
1312
1313
1314
1315
1316
1317
1318
1319
+        for i in range(tp_multiplier):
+            staging_block_descs_ids = self._get_block_descs_ids(self.engine_id, "all", staging_block_ids, i=i, tp_multiplier=tp_multiplier, staging_ranges=staging_rearranging_ranges)
+            assert len(staging_block_descs_ids) == len(remote_block_descs_ids)
+            remote_xfer_side_handle = self.dst_xfer_side_handles[dst_engine_id][i]
+            handle = self.nixl_wrapper.make_prepped_xfer("READ", local_xfer_side_handle, staging_block_descs_ids, 
+                                                        remote_xfer_side_handle, remote_block_descs_ids, 
+                                                        "")
+            handles.append(handle)
+            status = self.nixl_wrapper.transfer(handle)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1320
+
1321
+        logger.debug("Time to create xfer: %s ms", (time.perf_counter() - create_xfer_start_time) * 1000)
1322
+
1323
+        transfer_start_time = time.perf_counter()
1324
+
1325
1326
1327
1328
1329
1330
1331
+        for handle in handles:
+            while (status := self.nixl_wrapper.check_xfer_state(handle)) != "DONE":
+                if status == "PROC":
+                    time.sleep(0.001)
+                else:
+                    raise RuntimeError("Read transfer failed with state %s", status)
+            # self.nixl_wrapper.abort_xfer(handle) # TODO ptarasiewicz: why abort is throwing errors?
Neelay Shah's avatar
Neelay Shah committed
1332
+
1333
+        logger.debug("Time to transfer: %s ms", (time.perf_counter() - transfer_start_time) * 1000)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1334
+
1335
+        rearrange_start_time = time.perf_counter()
Neelay Shah's avatar
Neelay Shah committed
1336
+
1337
1338
1339
1340
1341
+        for local_range, staging_range in zip(local_rearranging_ranges, staging_rearranging_ranges):
+            logger.debug("Rearranging tensors for cache: %s, local_range: %s, staging_range: %s", self.kv_caches[0].shape, local_range, staging_range)
+            for kv_cache in self.kv_caches:
+                for cache in kv_cache:
+                    rearrange_tensors(cache[local_range[0]:local_range[1] + 1], cache[staging_range[0]:staging_range[1] + 1], tp_multiplier, "read")
1342
+
1343
1344
1345
1346
1347
+        logger.debug("Time to rearrange tensors: %s ms", (time.perf_counter() - rearrange_start_time) * 1000)
+        logger.debug("Total time for read: %s ms", (time.perf_counter() - start_time) * 1000)
+
+    def write_blocks(self, local_block_ids, staging_block_ids, remote_block_ids, dst_engine_id, notify_msg):
+        logger.debug("Writing %d blocks to %s from %s with notify message %s", len(local_block_ids), dst_engine_id, self.agent_name, notify_msg)
1348
1349
1350
1351
1352
+
+        # hongkuanz: we send isl[:-1] tokens to the prefill where the kv for the last
+        # isl[-1] token is calculated in the first iteration in decode.
+        # If isl equals to a multiple of tokens_per_block + 1, prefill engine will have \
+        # one less block due to the missing last token.
1353
+        remote_block_ids = remote_block_ids[:len(local_block_ids)]
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1354
+
1355
+        assert len(staging_block_ids) == len(local_block_ids)
Neelay Shah's avatar
Neelay Shah committed
1356
+        tp_multiplier = self._tp_size[dst_engine_id] // self._tp_size[self.engine_id]
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
+
+        if len(local_block_ids) == 0:
+            logger.debug("No blocks to write")
+            for i in range(tp_multiplier):
+                self.nixl_wrapper.send_notif(self._remote_agents[dst_engine_id][self.rank * tp_multiplier + i], notify_msg)
+            return
+        
+        start_time = time.perf_counter()
+
+        local_ranges = self._get_ranges(local_block_ids)
+        staging_ranges = self._get_ranges(staging_block_ids)
+
+        local_rearranging_ranges, staging_rearranging_ranges = self._get_same_length_ranges(local_ranges, staging_ranges)
Neelay Shah's avatar
Neelay Shah committed
1370
+        
1371
1372
+        for local_range, staging_range in zip(local_rearranging_ranges, staging_rearranging_ranges):
+            logger.debug("Rearranging tensors for cache: %s, local_range: %s, staging_range: %s", self.kv_caches[0].shape, local_range, staging_range)
1373
1374
+            for kv_cache in self.kv_caches:
+                for cache in kv_cache:
1375
+                    rearrange_tensors(cache[local_range[0]:local_range[1] + 1], cache[staging_range[0]:staging_range[1] + 1], tp_multiplier, "write")
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1376
+
1377
+        logger.debug("Time to rearrange tensors: %s ms", (time.perf_counter() - start_time) * 1000)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1378
+
1379
+        create_xfer_start_time = time.perf_counter()
1380
+
1381
1382
1383
1384
+        # getting block descs ids
+        remote_block_descs_ids = self._get_block_descs_ids(dst_engine_id, "all", remote_block_ids)
+        local_xfer_side_handle = self.src_xfer_side_handles[tp_multiplier]
+        
Neelay Shah's avatar
Neelay Shah committed
1385
+        for i in range(tp_multiplier):
1386
1387
1388
1389
1390
+            staging_block_descs_ids = self._get_block_descs_ids(self.engine_id, "all", staging_block_ids, i=i, tp_multiplier=tp_multiplier, staging_ranges=staging_rearranging_ranges)
+            assert len(staging_block_descs_ids) == len(remote_block_descs_ids)
+            remote_xfer_side_handle = self.dst_xfer_side_handles[dst_engine_id][i]
+            handle = self.nixl_wrapper.make_prepped_xfer("WRITE", local_xfer_side_handle, staging_block_descs_ids,
+                                                        remote_xfer_side_handle, remote_block_descs_ids, 
1391
+                                                        notify_msg)
Neelay Shah's avatar
Neelay Shah committed
1392
1393
+            self._transfers[notify_msg].append(handle)
+            status = self.nixl_wrapper.transfer(handle)
1394
1395
1396
1397
1398
+
+        logger.debug("Time to create xfer: %s ms", (time.perf_counter() - create_xfer_start_time) * 1000)
+
+        transfer_start_time = time.perf_counter()
+        logger.debug("Total time for write: %s ms", (time.perf_counter() - start_time) * 1000)
1399
+                
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1400
+    def get_notifs(self):
1401
+        return self.nixl_wrapper.update_notifs()
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1402
1403
+    
+    def get_new_notifs(self):
1404
1405
1406
1407
1408
1409
1410
1411
1412
+        return self.nixl_wrapper.get_new_notifs()
+
+    def add_remote_agent(self, engine_id, agent_metadata, agent_tp, kv_caches_base_addr, num_blocks):
+        self._tp_size[engine_id] = agent_tp
+        agent_names = []
+        for agent_meta in agent_metadata:
+            agent_name = self.nixl_wrapper.add_remote_agent(agent_meta)
+            agent_names.append(agent_name)
+        self._remote_agents[engine_id] = agent_names
ptarasiewiczNV's avatar
ptarasiewiczNV committed
1413
+        self.kv_caches_base_addr[engine_id] = kv_caches_base_addr
1414
+
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
+        tp_multiplier = self._tp_size[engine_id] // self._tp_size[self.engine_id]
+        assert tp_multiplier > 0, f"Decode TP cannot be smaller than prefill TP, got {self._tp_size[engine_id]} and {self._tp_size[self.engine_id]}"
+
+        logger.debug("Creating src xfer side handles for engine %s, tp_multiplier: %s", engine_id, tp_multiplier)
+        dst_block_len = self.block_len // tp_multiplier
+        if tp_multiplier not in self.src_xfer_side_handles:
+            # create descs and xfer side handles
+            blocks_data = []
+            for layer_id in range(self.num_layers):
+                for base_addr in self.kv_caches_base_addr[self.engine_id][layer_id]:
+                    for block_id in range(self.num_blocks):
+                            block_offset = block_id * self.block_len
+                            for i in range(tp_multiplier):
+                                tp_multiplier_offset = i * dst_block_len
+                                blocks_data.append((base_addr + block_offset + tp_multiplier_offset, dst_block_len, self.rank))
+            logger.debug("Created %s blocks for src engine %s and rank %s", len(blocks_data), self.engine_id, self.rank * tp_multiplier + i)
1431
+            descs = self.nixl_wrapper.get_xfer_descs(blocks_data, "VRAM")
1432
+            self.src_xfer_side_handles[tp_multiplier] = self.nixl_wrapper.prep_xfer_dlist("", descs)
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
+
+        # create dst xfer side handles
+        self.dst_num_blocks[engine_id] = num_blocks
+        for i in range(tp_multiplier):
+            blocks_data = []
+            for layer_id in range(self.num_layers):
+                for base_addr in self.kv_caches_base_addr[engine_id][self.rank * tp_multiplier + i][layer_id]:
+                    for block_id in range(num_blocks):
+                        block_offset = block_id * dst_block_len
+                        blocks_data.append((base_addr + block_offset, dst_block_len, self.rank * tp_multiplier + i))
+            logger.debug("Created %s blocks for dst engine %s and rank %s", len(blocks_data), engine_id, self.rank * tp_multiplier + i)
1444
+            descs = self.nixl_wrapper.get_xfer_descs(blocks_data, "VRAM")
1445
+            self.dst_xfer_side_handles[engine_id][i] = self.nixl_wrapper.prep_xfer_dlist(self._remote_agents[engine_id][self.rank * tp_multiplier + i], descs)
1446
1447
1448
+
+        return agent_names
+
Neelay Shah's avatar
Neelay Shah committed
1449
1450
1451
1452
1453
1454
1455
+    def get_done_tranfers(self) -> List[str]:
+        done_req_ids = []
+        for req_id, handles in self._transfers.items():
+            running_reqs = []
+            for handle in handles:
+                xfer_state = self.nixl_wrapper.check_xfer_state(handle)
+                if xfer_state == "DONE":
1456
+                    # self.nixl_wrapper.release_xfer_handle(handle) # TODO ptarasiewicz: why abort is throwing errors?
Neelay Shah's avatar
Neelay Shah committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
+                    continue
+                if xfer_state == "PROC":
+                    running_reqs.append(handle)
+                else:
+                    raise RuntimeError("Transfer failed with state %s", xfer_state)
+            if len(running_reqs) == 0:
+                done_req_ids.append(req_id)
+            else:
+                self._transfers[req_id] = running_reqs
+        return done_req_ids
Neelay Shah's avatar
Neelay Shah committed
1467
diff --git a/vllm/distributed/kv_transfer/kv_connector/dynamo_connector.py b/vllm/distributed/kv_transfer/kv_connector/dynamo_connector.py
Neelay Shah's avatar
Neelay Shah committed
1468
new file mode 100644
1469
index 000000000..418fc7154
Neelay Shah's avatar
Neelay Shah committed
1470
--- /dev/null
Neelay Shah's avatar
Neelay Shah committed
1471
+++ b/vllm/distributed/kv_transfer/kv_connector/dynamo_connector.py
1472
1473
@@ -0,0 +1,363 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Neelay Shah's avatar
Neelay Shah committed
1474
+# SPDX-License-Identifier: Apache-2.0
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
+#
+# 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.
Neelay Shah's avatar
Neelay Shah committed
1487
1488
1489
1490
1491
1492
1493
1494
1495
+"""
+Simple KV Cache Connector for Distributed Machine Learning Inference
+
+The SimpleConnector transfers KV caches between prefill vLLM worker (KV cache 
+producer) and decode vLLM worker (KV cache consumer) using PyNcclPipe or
+MooncakePipe.
+
+But the logic can be extended to support other pipe and lookup buffer.
+"""
1496
+import re
Neelay Shah's avatar
Neelay Shah committed
1497
1498
1499
1500
1501
+from typing import TYPE_CHECKING, List, Optional, Tuple, Union
+
+import torch
+
+from vllm import _custom_ops as ops
1502
+from vllm.config import VllmConfig, KVTransferConfig
Neelay Shah's avatar
Neelay Shah committed
1503
+from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBase
1504
+from vllm.distributed.utils import StatelessProcessGroup
Neelay Shah's avatar
Neelay Shah committed
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
+from vllm.distributed.kv_transfer.kv_lookup_buffer.simple_buffer import (
+    SimpleBuffer)
+from vllm.logger import init_logger
+from vllm.sequence import IntermediateTensors
+
+if TYPE_CHECKING:
+    from vllm.worker.model_runner import ModelInputForGPUWithSamplingMetadata
+
+logger = init_logger(__name__)
+
+
Neelay Shah's avatar
Neelay Shah committed
1516
+class DynamoConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
1517
1518
1519
1520
1521
1522
+
+    def __init__(
+        self,
+        rank: int,
+        local_rank: int,
+        config: VllmConfig,
1523
+        world_group,
Neelay Shah's avatar
Neelay Shah committed
1524
1525
1526
1527
1528
1529
+    ):
+
+        self.config = config.kv_transfer_config
+        self.tp_size = config.parallel_config.tensor_parallel_size
+        self.rank = rank
+
Neelay Shah's avatar
Neelay Shah committed
1530
1531
+        if self.config.kv_connector != "DynamoNcclConnector":
+            raise NotImplementedError("Only DynamoNcclConnector is supported by the DynamoConnector class")
Neelay Shah's avatar
Neelay Shah committed
1532
1533
1534
+
+        from vllm.distributed.kv_transfer.kv_pipe.pynccl_pipe import (
+            PyNcclPipe)
Neelay Shah's avatar
Neelay Shah committed
1535
1536
+        from vllm.distributed.kv_transfer.kv_pipe.dynamo_nccl_pipe import (
+            DynamoNcclDataPlane)
Neelay Shah's avatar
Neelay Shah committed
1537
1538
+        
+        logger.info(
Neelay Shah's avatar
Neelay Shah committed
1539
+            "Initializing DynamoNcclConnector under kv_transfer_config %s",
Neelay Shah's avatar
Neelay Shah committed
1540
1541
1542
1543
1544
1545
1546
1547
1548
+            self.config)
+
+        self.lookup_buffer_size = self.config.kv_buffer_size
+
+        self.producer_data_pipe: PyNcclPipe
+        self.consumer_data_pipe: PyNcclPipe
+        self.producer_signal_pipe: PyNcclPipe
+        self.consumer_signal_pipe: PyNcclPipe
+
1549
1550
1551
1552
1553
+        self._broadcast_and_enhance_kv_config(rank, config, world_group)
+
+        self.kv_group_rank = self._get_kv_group_rank(self.config.kv_rank, rank, self.config)
+        self.tp_size = config.parallel_config.tensor_parallel_size
+
Neelay Shah's avatar
Neelay Shah committed
1554
+        # 2 pipes for every rank in the world
1555
+        if self.config.is_kv_producer:
Neelay Shah's avatar
Neelay Shah committed
1556
+            port_offset_base = rank + 1
1557
+        else:
Neelay Shah's avatar
Neelay Shah committed
1558
1559
1560
+            port_offset_base = rank // self.config.tensor_parallel_multiplier + 1
+
+
1561
+        self.local_kv_rank = rank % self.config.tensor_parallel_multiplier
Neelay Shah's avatar
Neelay Shah committed
1562
+        self.global_kv_rank = self._get_global_kv_rank(self.config.kv_rank, rank, self.config)
1563
+
Neelay Shah's avatar
Neelay Shah committed
1564
1565
1566
1567
1568
1569
+        self.data_pipe = PyNcclPipe(
+            kv_group_rank=self.kv_group_rank,
+            local_rank=local_rank,
+            config=self.config,
+            port_offset=port_offset_base,
+        )
1570
+
Neelay Shah's avatar
Neelay Shah committed
1571
+        self.data_plane = DynamoNcclDataPlane(
Neelay Shah's avatar
Neelay Shah committed
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
+            data_pipe=self.data_pipe,
+            port=self._get_data_plane_port(self.global_kv_rank),
+        )
+
+    def send_kv_caches_and_hidden_states(
+        self,
+        model_executable: torch.nn.Module,
+        model_input: "ModelInputForGPUWithSamplingMetadata",
+        kv_caches: List[torch.Tensor],
+        hidden_or_intermediate_states: Union[torch.Tensor,
+                                             IntermediateTensors],
+    ) -> None:
+
+        input_tokens_tensor = model_input.input_tokens
+        seq_lens = model_input.attn_metadata.seq_lens
+        slot_mapping_flat = model_input.attn_metadata.slot_mapping.flatten()
+        start_layer = model_executable.model.start_layer
+        end_layer = model_executable.model.end_layer
1590
+        request_ids = list(model_input.request_ids_to_seq_ids.keys())
Neelay Shah's avatar
Neelay Shah committed
1591
1592
+
+        model_config = model_executable.model.config
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
+        is_deepseek = "deepseek" in model_config.architectures[0].lower()
+        if not is_deepseek:
+            num_heads = int(model_config.num_key_value_heads / self.tp_size)
+            hidden_size = model_config.hidden_size
+            num_attention_heads = model_config.num_attention_heads
+            head_size = int(hidden_size / num_attention_heads)
+        else:
+            num_heads = int(model_config.num_key_value_heads / self.tp_size)
+            hidden_size = model_config.hidden_size
+            num_attention_heads = model_config.num_attention_heads
+            head_size = int(4.5 * hidden_size / num_attention_heads)
Neelay Shah's avatar
Neelay Shah committed
1604
1605
1606
1607
1608
1609
1610
1611
+
+        # query_lens contains new KV caches that are added to vLLM.
+        # so we will send them to decode instance
+        # FIXME(Kuntai): This assume that all requests are prefill.
+        for idx, slen in enumerate(seq_lens):
+            start_pos = sum(seq_lens[:idx])
+            end_pos = start_pos + slen
+            current_tokens = input_tokens_tensor[start_pos:end_pos]
1612
+            current_request_id = request_ids[idx]
Neelay Shah's avatar
Neelay Shah committed
1613
1614
+            decode_hostname, decode_kv_rank = self.parse_request_id(current_request_id)
+            decode_first_global_rank = self._get_global_kv_rank(decode_kv_rank, self.rank * self.config.tensor_parallel_multiplier, self.config)
1615
1616
+
+            for target_rank in range(self.config.tensor_parallel_multiplier):
Neelay Shah's avatar
Neelay Shah committed
1617
+
1618
+                keys, values = [], []
Neelay Shah's avatar
Neelay Shah committed
1619
+
1620
1621
+                for layer_id in range(start_layer, end_layer):
+                    kv_cache = kv_caches[layer_id - start_layer]
Neelay Shah's avatar
Neelay Shah committed
1622
+
1623
+                    current_slot_mapping = slot_mapping_flat[start_pos:end_pos]
Neelay Shah's avatar
Neelay Shah committed
1624
+
1625
1626
1627
+                    num_heads_per_rank = num_heads // self.config.tensor_parallel_multiplier
+                    head_start = target_rank * num_heads_per_rank
+                    head_end = head_start + num_heads_per_rank
Neelay Shah's avatar
Neelay Shah committed
1628
+
1629
1630
1631
1632
1633
1634
1635
1636
1637
+                    if not is_deepseek:
+                        key_cache = kv_cache[0].reshape(-1, num_heads, head_size)
+                        value_cache = kv_cache[1].reshape(-1, num_heads, head_size)
+                        keys.append(key_cache[current_slot_mapping, head_start:head_end].unsqueeze(0))
+                        values.append(value_cache[current_slot_mapping, head_start:head_end].unsqueeze(0))
+                    else:
+                        key_cache = kv_cache
+                        keys.append(key_cache[current_slot_mapping].unsqueeze(0))
+                        values.append(torch.empty(0))
Neelay Shah's avatar
Neelay Shah committed
1638
+
1639
1640
+                keys = torch.cat(keys, dim=0)
+                values = torch.cat(values, dim=0)
Neelay Shah's avatar
Neelay Shah committed
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
+
+                decode_global_rank = decode_first_global_rank + target_rank
+                decode_port = self._get_data_plane_port(decode_global_rank)
+                partial_hidden_or_intermediate_states = hidden_or_intermediate_states[start_pos:end_pos]
+                self._send(decode_hostname, decode_port, current_request_id, keys, values,
+                            partial_hidden_or_intermediate_states)
+
+        logger.debug("[rank%d]: KV send DONE.", torch.distributed.get_rank())
+
+    def recv_kv_caches_and_hidden_states(
+        self, model_executable: torch.nn.Module,
+        model_input: "ModelInputForGPUWithSamplingMetadata",
+        kv_caches: List[torch.Tensor]
+    ) -> Tuple[Union[torch.Tensor, IntermediateTensors], bool,
+               "ModelInputForGPUWithSamplingMetadata"]:
+
+        # When bypass_model_exec is set to False, it means that at least for one
+        # request its corresponding KV cache or hidden state is missing.
+        # In this case we need to do prefilling to recompute missing KV cache
+        # and hidden states.
+        bypass_model_exec = True
+
+        input_tokens_tensor = model_input.input_tokens
+        seq_lens = model_input.attn_metadata.seq_lens
+        slot_mapping = model_input.attn_metadata.slot_mapping.flatten()
1666
+        request_ids = list(model_input.request_ids_to_seq_ids.keys())
Neelay Shah's avatar
Neelay Shah committed
1667
1668
1669
1670
1671
1672
+
+        hidden_or_intermediate_states_for_one_req = []
+
+        input_tokens_list = []
+        start_pos_list = []
+
1673
1674
1675
+        model_config = model_executable.model.config
+        is_deepseek = "deepseek" in model_config.architectures[0].lower()
+
Neelay Shah's avatar
Neelay Shah committed
1676
1677
1678
1679
1680
1681
1682
+        # enumerate different requests
+        # FIXME(Kuntai): This impl assumes that all requests are prefill.
+        for idx, slen in enumerate(seq_lens):
+
+            start_pos = sum(seq_lens[:idx])
+            end_pos = start_pos + slen
+            current_tokens = input_tokens_tensor[start_pos:end_pos]
1683
+            current_request_id = request_ids[idx]
Neelay Shah's avatar
Neelay Shah committed
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
+            num_tokens = slen
+
+            # collecting data for rebuilding the input
+            input_tokens_list.append(current_tokens)
+            start_pos_list.append(start_pos)
+
+            ret = self._recv(current_request_id)
+            keys: torch.Tensor = ret[0]
+            values: torch.Tensor = ret[1]
+            hidden: torch.Tensor = ret[2]
+
+            # put received KV caches into paged memory
+            for i in range(model_executable.model.start_layer,
+                           model_executable.model.end_layer):
+
+                kv_cache = kv_caches[i - model_executable.model.start_layer]
+                layer = model_executable.model.layers[i]
+
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
+                if not is_deepseek:
+                    key_cache, value_cache = kv_cache[0], kv_cache[1]
+                    ops.reshape_and_cache_flash(
+                        keys[i - model_executable.model.start_layer].to(
+                            key_cache.device),
+                        values[i - model_executable.model.start_layer].to(
+                            value_cache.device),
+                        key_cache,
+                        value_cache,
+                        slot_mapping[start_pos:end_pos],
+                        layer.self_attn.attn.kv_cache_dtype,
+                        layer.self_attn.attn._k_scale,
+                        layer.self_attn.attn._v_scale,
+                    )
+                else:
+                    key_cache = kv_cache
+                    copy_from =keys[i - model_executable.model.start_layer].to(
+                            key_cache.device)
+                    kv_cache[slot_mapping[start_pos:end_pos]] = copy_from
Neelay Shah's avatar
Neelay Shah committed
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
+
+            hidden_or_intermediate_states_for_one_req.append(hidden)
+
+        if not bypass_model_exec:
+            # Some of the KV cache is not retrieved
+            # Here we will fall back to normal model forwarding
+            # But optionally you can adjust model_input so that you only do
+            # prefilling on those tokens that are missing KV caches.
+            logger.debug(
+                "[rank%d]: Failed to receive all KVs and hidden "
+                "states, redo model forwarding.", torch.distributed.get_rank())
+            hidden_or_intermediate_states = None
+
+        else:
+            logger.debug(
+                "[rank%d]: Successfully received all KVs and hidden "
+                "states, skip model forwarding.", torch.distributed.get_rank())
+            hidden_or_intermediate_states = torch.cat(
+                hidden_or_intermediate_states_for_one_req, dim=0)
+
+        return hidden_or_intermediate_states, bypass_model_exec, model_input
+
+    def close(self):
+        self.data_pipe.close()
+        # self.data_plane.close()
1746
1747
+
+    @staticmethod
Neelay Shah's avatar
Neelay Shah committed
1748
1749
1750
+    def parse_request_id(request_id: str) -> Tuple[str, int]:
+        # Regular expression to match the string hostname and integer decode_kv_rank
+        pattern = r"___decode_hostname_(.*)___decode_kv_rank_(\d+)"
1751
1752
1753
1754
1755
+        
+        # Use re.search to find the pattern in the request_id
+        match = re.search(pattern, request_id)
+        if match:
+            # Extract the ranks
Neelay Shah's avatar
Neelay Shah committed
1756
+            decode_hostname = match.group(1)
1757
1758
+            decode_rank = int(match.group(2))
+            
Neelay Shah's avatar
Neelay Shah committed
1759
1760
+            return decode_hostname, decode_rank
+        raise ValueError(f"Request id {request_id} does not contain hostname and decode_kv_rank")
1761
+
Neelay Shah's avatar
Neelay Shah committed
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
+    def _send(self, hostname: str, port: int, request_id: str, keys: torch.Tensor, values: torch.Tensor, hidden: torch.Tensor):
+        remote_address = f"{hostname}:{port}"
+        self.data_plane.send_tensor(keys, f"{request_id}_keys", remote_address)
+        self.data_plane.send_tensor(values, f"{request_id}_values", remote_address)
+        self.data_plane.send_tensor(hidden, f"{request_id}_hidden", remote_address)
+
+    def _recv(self, request_id: str) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+        keys = self.data_plane.recv_tensor(f"{request_id}_keys")
+        values = self.data_plane.recv_tensor(f"{request_id}_values")
+        hidden = self.data_plane.recv_tensor(f"{request_id}_hidden")
+        return keys, values, hidden
1773
1774
1775
1776
1777
1778
1779
+
+    def _get_kv_group_rank(self, kv_rank: int, rank: int, config: KVTransferConfig) -> int:
+        if kv_rank < config.kv_producers_parallel_size:
+            return kv_rank
+        
+        kv_consumer_rank = kv_rank - config.kv_producers_parallel_size
+        return config.kv_producers_parallel_size + kv_consumer_rank * config.tensor_parallel_multiplier + rank % config.tensor_parallel_multiplier
Neelay Shah's avatar
Neelay Shah committed
1780
+    
1781
+
Neelay Shah's avatar
Neelay Shah committed
1782
1783
1784
1785
1786
1787
+    def _get_global_kv_rank(self, kv_rank: int, rank: int, config: KVTransferConfig) -> int:
+        if kv_rank <= config.kv_producers_parallel_size:
+            return kv_rank * config.kv_producers_tensor_parallel_size + rank
+        
+        kv_consumer_rank = kv_rank - config.kv_producers_parallel_size
+        return config.kv_producers_parallel_size * config.kv_producers_tensor_parallel_size + kv_consumer_rank * config.kv_consumers_tensor_parallel_size + rank
1788
+
Neelay Shah's avatar
Neelay Shah committed
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
+
+    def _get_data_plane_port(self, global_kv_rank: int) -> int:
+        return self.config.kv_port + self.config.kv_producers_tensor_parallel_size + 1 + global_kv_rank
+
+    def _broadcast_and_enhance_kv_config(self, rank: int, config: VllmConfig, world_group):
+        if rank == 0:
+            config_group = StatelessProcessGroup.create(
+                host=self.config.kv_ip,
+                port=self.config.kv_port,
+                rank=self.config.kv_rank,
+                world_size=self.config.kv_parallel_size,
+            )
+            parallel_configs = config_group.all_gather_obj({
+                "kv_role": self.config.kv_role,
+                "tensor_parallel_size": config.parallel_config.tensor_parallel_size,
+                "pipeline_parallel_size": config.parallel_config.pipeline_parallel_size,
+            })
+            logger.debug("parallel_configs: %s", parallel_configs)
+            kv_config_enhanced = {
+                "kv_producers_tensor_parallel_size": None,
+                "kv_consumers_tensor_parallel_size": None,
+                "kv_producers_pipeline_parallel_size": None,
+                "kv_consumers_pipeline_parallel_size": None,
+                "kv_producers_parallel_size": 0,
+            }
+            for parallel_config in parallel_configs:
+                kv_role = parallel_config["kv_role"]
+                assert parallel_config["pipeline_parallel_size"] == 1, f"Only pipeline parallel size 1 is supported for kv transfer instances"
+                
+                if kv_role == "kv_producer":
+                    kv_config_enhanced["kv_producers_parallel_size"] += 1
+                if kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] is None:
+                    kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] = parallel_config["tensor_parallel_size"]
+                    kv_config_enhanced[f"{kv_role}s_pipeline_parallel_size"] = parallel_config["pipeline_parallel_size"]
+                else:
+                    assert kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] == parallel_config["tensor_parallel_size"], f"All kv {kv_role}s should have the same tensor parallel size"
+                    assert kv_config_enhanced[f"{kv_role}s_pipeline_parallel_size"] == parallel_config["pipeline_parallel_size"], f"All kv {kv_role}s should have the same pipeline parallel size"
+            world_group.broadcast_object(kv_config_enhanced)
1827
1828
1829
1830
1831
1832
1833
1834
1835
+        else:
+            kv_config_enhanced = world_group.broadcast_object()
+        logger.info("kv_config_enhanced: %s", kv_config_enhanced)
+
+        self.config.kv_producers_tensor_parallel_size = kv_config_enhanced["kv_producers_tensor_parallel_size"]
+        self.config.kv_consumers_tensor_parallel_size = kv_config_enhanced["kv_consumers_tensor_parallel_size"]
+        self.config.kv_producers_pipeline_parallel_size = kv_config_enhanced["kv_producers_pipeline_parallel_size"]
+        self.config.kv_consumers_pipeline_parallel_size = kv_config_enhanced["kv_consumers_pipeline_parallel_size"]
+        self.config.kv_producers_parallel_size = kv_config_enhanced["kv_producers_parallel_size"]
Neelay Shah's avatar
Neelay Shah committed
1836
diff --git a/vllm/distributed/kv_transfer/kv_connector/factory.py b/vllm/distributed/kv_transfer/kv_connector/factory.py
1837
index fe4805334..0e16f0b31 100644
Neelay Shah's avatar
Neelay Shah committed
1838
1839
--- a/vllm/distributed/kv_transfer/kv_connector/factory.py
+++ b/vllm/distributed/kv_transfer/kv_connector/factory.py
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 importlib
 from typing import TYPE_CHECKING, Callable, Dict, Type
@@ -27,13 +40,13 @@ class KVConnectorFactory:
Neelay Shah's avatar
Neelay Shah committed
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
 
     @classmethod
     def create_connector(cls, rank: int, local_rank: int,
-                         config: "VllmConfig") -> KVConnectorBase:
+                         config: "VllmConfig", world_group) -> KVConnectorBase:
         connector_name = config.kv_transfer_config.kv_connector
         if connector_name not in cls._registry:
             raise ValueError(f"Unsupported connector type: {connector_name}")
 
         connector_cls = cls._registry[connector_name]()
-        return connector_cls(rank, local_rank, config)
+        return connector_cls(rank, local_rank, config, world_group)
 
 
 # Register various connectors here.
1874
@@ -48,3 +61,8 @@ KVConnectorFactory.register_connector(
Neelay Shah's avatar
Neelay Shah committed
1875
1876
1877
     "MooncakeConnector",
     "vllm.distributed.kv_transfer.kv_connector.simple_connector",
     "SimpleConnector")
1878
+
Neelay Shah's avatar
Neelay Shah committed
1879
+KVConnectorFactory.register_connector(
Neelay Shah's avatar
Neelay Shah committed
1880
1881
1882
+    "DynamoNcclConnector",
+    "vllm.distributed.kv_transfer.kv_connector.dynamo_connector",
+    "DynamoConnector")
Neelay Shah's avatar
Neelay Shah committed
1883
diff --git a/vllm/distributed/kv_transfer/kv_connector/simple_connector.py b/vllm/distributed/kv_transfer/kv_connector/simple_connector.py
1884
index 2033e9762..983bc69a3 100644
Neelay Shah's avatar
Neelay Shah committed
1885
1886
--- a/vllm/distributed/kv_transfer/kv_connector/simple_connector.py
+++ b/vllm/distributed/kv_transfer/kv_connector/simple_connector.py
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """
 Simple KV Cache Connector for Distributed Machine Learning Inference
 
@@ -8,13 +21,15 @@ MooncakePipe.
Neelay Shah's avatar
Neelay Shah committed
1906
1907
1908
 
 But the logic can be extended to support other pipe and lookup buffer.
 """
1909
+import re
Neelay Shah's avatar
Neelay Shah committed
1910
1911
1912
1913
1914
1915
 from typing import TYPE_CHECKING, List, Optional, Tuple, Union
 
 import torch
 
 from vllm import _custom_ops as ops
-from vllm.config import VllmConfig
1916
+from vllm.config import VllmConfig, KVTransferConfig
Neelay Shah's avatar
Neelay Shah committed
1917
 from vllm.distributed.kv_transfer.kv_connector.base import KVConnectorBase
1918
+from vllm.distributed.utils import StatelessProcessGroup
Neelay Shah's avatar
Neelay Shah committed
1919
1920
1921
 from vllm.distributed.kv_transfer.kv_lookup_buffer.simple_buffer import (
     SimpleBuffer)
 from vllm.logger import init_logger
1922
@@ -33,6 +48,7 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
1923
1924
1925
         rank: int,
         local_rank: int,
         config: VllmConfig,
1926
+        world_group,
Neelay Shah's avatar
Neelay Shah committed
1927
1928
1929
     ):
 
         self.config = config.kv_transfer_config
1930
@@ -71,20 +87,31 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
1931
1932
1933
         self.producer_signal_pipe: Union[PyNcclPipe, MooncakePipe]
         self.consumer_signal_pipe: Union[PyNcclPipe, MooncakePipe]
 
1934
1935
1936
1937
1938
+        self._broadcast_and_enhance_kv_config(rank, config, world_group)
+
+        self.kv_group_rank = self._get_kv_group_rank(self.config.kv_rank, rank, self.config)
+        self.tp_size = config.parallel_config.tensor_parallel_size
+
Neelay Shah's avatar
Neelay Shah committed
1939
1940
         # 2 pipes for every rank in the world
-        port_offset_base = 2 * rank
1941
+        if self.config.is_kv_producer:
Neelay Shah's avatar
Neelay Shah committed
1942
+            port_offset_base = 2 * rank + 1
1943
+        else:
Neelay Shah's avatar
Neelay Shah committed
1944
1945
+            port_offset_base = 2 * (rank // self.config.tensor_parallel_multiplier) + 1
 
1946
+        self.local_kv_rank = rank % self.config.tensor_parallel_multiplier
Neelay Shah's avatar
Neelay Shah committed
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
         # In disaggregated prefill, the prefill vLLM only uses send pipe
         # and the decode vLLM only uses recv pipe
         if self.config.is_kv_producer:
 
             if self.config.kv_connector == "PyNcclConnector":
                 self.producer_data_pipe = PyNcclPipe(
+                    kv_group_rank=self.kv_group_rank,
                     local_rank=local_rank,
                     config=self.config,
                     port_offset=port_offset_base,
                 )
                 self.producer_signal_pipe = PyNcclPipe(
+                    kv_group_rank=self.kv_group_rank,
                     local_rank=local_rank,
                     config=self.config,
                     port_offset=port_offset_base + 1,
1963
@@ -108,11 +135,13 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
             # its recv pipe to the send pipe of KV producder
             if self.config.kv_connector == "PyNcclConnector":
                 self.consumer_data_pipe = PyNcclPipe(
+                    kv_group_rank=self.kv_group_rank,
                     local_rank=local_rank,
                     config=self.config,
                     port_offset=port_offset_base,
                 )
                 self.consumer_signal_pipe = PyNcclPipe(
+                    kv_group_rank=self.kv_group_rank,
                     local_rank=local_rank,
                     config=self.config,
                     port_offset=port_offset_base + 1,
1977
@@ -131,21 +160,25 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
1978
1979
1980
1981
1982
1983
1984
1985
                 self.config.kv_buffer_size,
             )
 
-    def select(self, input_tokens: Optional[torch.Tensor],
+    def select(self, source_rank: int, input_tokens: Optional[torch.Tensor],
                roi: Optional[torch.Tensor]) -> List[Optional[torch.Tensor]]:
 
+        logger.info("Selecting KV caches and hidden states for source rank %d", source_rank)
1986
+
Neelay Shah's avatar
Neelay Shah committed
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
         assert self.consumer_buffer is not None, "Please initialize the "\
             "consumer buffer before calling select."
-        return self.consumer_buffer.drop_select(input_tokens, roi)
+        return self.consumer_buffer.drop_select(source_rank, self.local_kv_rank, input_tokens, roi)
 
-    def insert(self, input_tokens: torch.Tensor, roi: torch.Tensor,
+    def insert(self, kv_group_rank: int, target_rank: int, input_tokens: torch.Tensor, roi: torch.Tensor,
                key: torch.Tensor, value: torch.Tensor,
                hidden: torch.Tensor) -> None:
 
+        logger.info("Inserting KV caches and hidden states for kv_group_rank %d, target rank %d", kv_group_rank, target_rank)
1998
+
Neelay Shah's avatar
Neelay Shah committed
1999
2000
2001
2002
2003
2004
2005
2006
         assert self.producer_buffer is not None, "Please initialize the "\
             "producer buffer before calling insert."
 
-        self.producer_buffer.insert(input_tokens, roi, key, value, hidden)
+        self.producer_buffer.insert(kv_group_rank, target_rank, input_tokens, roi, key, value, hidden)
 
     def send_kv_caches_and_hidden_states(
         self,
2007
@@ -161,12 +194,20 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2008
2009
2010
         slot_mapping_flat = model_input.attn_metadata.slot_mapping.flatten()
         start_layer = model_executable.model.start_layer
         end_layer = model_executable.model.end_layer
2011
+        request_ids = list(model_input.request_ids_to_seq_ids.keys())
Neelay Shah's avatar
Neelay Shah committed
2012
2013
2014
2015
2016
2017
 
         model_config = model_executable.model.config
-        num_heads = int(model_config.num_key_value_heads / self.tp_size)
-        hidden_size = model_config.hidden_size
-        num_attention_heads = model_config.num_attention_heads
-        head_size = int(hidden_size / num_attention_heads)
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
+        is_deepseek = "deepseek" in model_config.architectures[0].lower()
+        if not is_deepseek:
+            num_heads = int(model_config.num_key_value_heads / self.tp_size)
+            hidden_size = model_config.hidden_size
+            num_attention_heads = model_config.num_attention_heads
+            head_size = int(hidden_size / num_attention_heads)
+        else:
+            num_heads = int(model_config.num_key_value_heads / self.tp_size)
+            hidden_size = model_config.hidden_size
+            num_attention_heads = model_config.num_attention_heads
+            head_size = int(4.5 * hidden_size / num_attention_heads)
Neelay Shah's avatar
Neelay Shah committed
2029
2030
2031
 
         # query_lens contains new KV caches that are added to vLLM.
         # so we will send them to decode instance
2032
@@ -175,27 +216,40 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2033
2034
2035
             start_pos = sum(seq_lens[:idx])
             end_pos = start_pos + slen
             current_tokens = input_tokens_tensor[start_pos:end_pos]
2036
+            current_request_id = request_ids[idx]
Neelay Shah's avatar
Neelay Shah committed
2037
2038
+            _, decode_kv_rank = self.parse_request_id(current_request_id)
+            starting_kv_group_rank = self._get_kv_group_rank(decode_kv_rank, 0, self.config)
2039
2040
+
+            for target_rank in range(self.config.tensor_parallel_multiplier):
Neelay Shah's avatar
Neelay Shah committed
2041
2042
 
-            keys, values = [], []
2043
+                keys, values = [], []
Neelay Shah's avatar
Neelay Shah committed
2044
2045
2046
 
-            for layer_id in range(start_layer, end_layer):
-                kv_cache = kv_caches[layer_id - start_layer]
2047
2048
+                for layer_id in range(start_layer, end_layer):
+                    kv_cache = kv_caches[layer_id - start_layer]
Neelay Shah's avatar
Neelay Shah committed
2049
2050
2051
 
-                key_cache = kv_cache[0].reshape(-1, num_heads, head_size)
-                value_cache = kv_cache[1].reshape(-1, num_heads, head_size)
2052
+                    current_slot_mapping = slot_mapping_flat[start_pos:end_pos]
Neelay Shah's avatar
Neelay Shah committed
2053
2054
 
-                current_slot_mapping = slot_mapping_flat[start_pos:end_pos]
2055
2056
2057
+                    num_heads_per_rank = num_heads // self.config.tensor_parallel_multiplier
+                    head_start = target_rank * num_heads_per_rank
+                    head_end = head_start + num_heads_per_rank
Neelay Shah's avatar
Neelay Shah committed
2058
2059
2060
 
-                keys.append(key_cache[current_slot_mapping].unsqueeze(0))
-                values.append(value_cache[current_slot_mapping].unsqueeze(0))
2061
2062
2063
2064
2065
2066
2067
2068
2069
+                    if not is_deepseek:
+                        key_cache = kv_cache[0].reshape(-1, num_heads, head_size)
+                        value_cache = kv_cache[1].reshape(-1, num_heads, head_size)
+                        keys.append(key_cache[current_slot_mapping, head_start:head_end].unsqueeze(0))
+                        values.append(value_cache[current_slot_mapping, head_start:head_end].unsqueeze(0))
+                    else:
+                        key_cache = kv_cache
+                        keys.append(key_cache[current_slot_mapping].unsqueeze(0))
+                        values.append(torch.empty(0))
Neelay Shah's avatar
Neelay Shah committed
2070
2071
2072
 
-            keys = torch.cat(keys, dim=0)
-            values = torch.cat(values, dim=0)
2073
2074
+                keys = torch.cat(keys, dim=0)
+                values = torch.cat(values, dim=0)
Neelay Shah's avatar
Neelay Shah committed
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
 
-            self.insert(current_tokens,
-                        torch.ones_like(current_tokens,
-                                        dtype=bool), keys, values,
-                        hidden_or_intermediate_states[start_pos:end_pos])
+                self.insert(starting_kv_group_rank, target_rank, current_tokens,
+                            torch.ones_like(current_tokens,
+                                            dtype=bool), keys, values,
+                            hidden_or_intermediate_states[start_pos:end_pos])
 
         logger.debug("[rank%d]: KV send DONE.", torch.distributed.get_rank())
 
2087
@@ -215,6 +269,7 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2088
2089
2090
         input_tokens_tensor = model_input.input_tokens
         seq_lens = model_input.attn_metadata.seq_lens
         slot_mapping = model_input.attn_metadata.slot_mapping.flatten()
2091
+        request_ids = list(model_input.request_ids_to_seq_ids.keys())
Neelay Shah's avatar
Neelay Shah committed
2092
2093
2094
 
         hidden_or_intermediate_states_for_one_req = []
 
2095
@@ -222,6 +277,9 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2096
2097
2098
         num_computed_tokens_list = []
         start_pos_list = []
 
2099
2100
2101
+        model_config = model_executable.model.config
+        is_deepseek = "deepseek" in model_config.architectures[0].lower()
+
Neelay Shah's avatar
Neelay Shah committed
2102
2103
2104
         # enumerate different requests
         # FIXME(Kuntai): This impl assumes that all requests are prefill.
         for idx, slen in enumerate(seq_lens):
2105
@@ -229,13 +287,15 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2106
2107
2108
             start_pos = sum(seq_lens[:idx])
             end_pos = start_pos + slen
             current_tokens = input_tokens_tensor[start_pos:end_pos]
2109
+            current_request_id = request_ids[idx]
Neelay Shah's avatar
Neelay Shah committed
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
+            prefill_rank, _ = self.parse_request_id(current_request_id)
             num_tokens = slen
 
             # collecting data for rebuilding the input
             input_tokens_list.append(current_tokens)
             start_pos_list.append(start_pos)
 
-            ret = self.select(current_tokens,
+            ret = self.select(prefill_rank, current_tokens,
                               torch.ones_like(current_tokens, dtype=bool))
             if ret[0] is None:
                 # didn't find any match.
2122
@@ -267,19 +327,25 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
                 kv_cache = kv_caches[i - model_executable.model.start_layer]
                 layer = model_executable.model.layers[i]
 
-                key_cache, value_cache = kv_cache[0], kv_cache[1]
-                ops.reshape_and_cache_flash(
-                    keys[i - model_executable.model.start_layer].to(
-                        key_cache.device),
-                    values[i - model_executable.model.start_layer].to(
-                        value_cache.device),
-                    key_cache,
-                    value_cache,
-                    slot_mapping[start_pos:end_pos],
-                    layer.self_attn.attn.kv_cache_dtype,
-                    layer.self_attn.attn._k_scale,
-                    layer.self_attn.attn._v_scale,
-                )
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
+                if not is_deepseek:
+                    key_cache, value_cache = kv_cache[0], kv_cache[1]
+                    ops.reshape_and_cache_flash(
+                        keys[i - model_executable.model.start_layer].to(
+                            key_cache.device),
+                        values[i - model_executable.model.start_layer].to(
+                            value_cache.device),
+                        key_cache,
+                        value_cache,
+                        slot_mapping[start_pos:end_pos],
+                        layer.self_attn.attn.kv_cache_dtype,
+                        layer.self_attn.attn._k_scale,
+                        layer.self_attn.attn._v_scale,
+                    )
+                else:
+                    key_cache = kv_cache
+                    copy_from =keys[i - model_executable.model.start_layer].to(
+                            key_cache.device)
+                    kv_cache[slot_mapping[start_pos:end_pos]] = copy_from
Neelay Shah's avatar
Neelay Shah committed
2158
2159
2160
 
             hidden_or_intermediate_states_for_one_req.append(hidden)
 
2161
@@ -312,3 +378,77 @@ class SimpleConnector(KVConnectorBase):
Neelay Shah's avatar
Neelay Shah committed
2162
2163
2164
             # MooncakePipe reuses data_pipe for signal_pipe, so we only have to
             # close the data_pipe.
             pass
2165
2166
+
+    @staticmethod
Neelay Shah's avatar
Neelay Shah committed
2167
2168
2169
+    def parse_request_id(request_id):
+        # Regular expression to match the ranks
+        pattern = r"___prefill_kv_rank_(\d+)___decode_kv_rank_(\d+)"
2170
2171
2172
+        
+        # Use re.search to find the pattern in the request_id
+        match = re.search(pattern, request_id)
Neelay Shah's avatar
Neelay Shah committed
2173
+        
2174
2175
+        if match:
+            # Extract the ranks
Neelay Shah's avatar
Neelay Shah committed
2176
+            prefill_rank = int(match.group(1))
2177
+            decode_rank = int(match.group(2))
Neelay Shah's avatar
Neelay Shah committed
2178
2179
2180
2181
+            
+            return prefill_rank, decode_rank
+        else:
+            return None, None
2182
+
Neelay Shah's avatar
Neelay Shah committed
2183
+    
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
+
+    def _get_kv_group_rank(self, kv_rank: int, rank: int, config: KVTransferConfig) -> int:
+        if kv_rank < config.kv_producers_parallel_size:
+            return kv_rank
+        
+        kv_consumer_rank = kv_rank - config.kv_producers_parallel_size
+        return config.kv_producers_parallel_size + kv_consumer_rank * config.tensor_parallel_multiplier + rank % config.tensor_parallel_multiplier
+
+    def _broadcast_and_enhance_kv_config(self, rank: int, config: VllmConfig, world_group):
+        if rank == 0:
Neelay Shah's avatar
Neelay Shah committed
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
+            if self.config.kv_connector == "PyNcclConnector":
+                config_group = StatelessProcessGroup.create(
+                    host=self.config.kv_ip,
+                    port=self.config.kv_port,
+                    rank=self.config.kv_rank,
+                    world_size=self.config.kv_parallel_size,
+                )
+                parallel_configs = config_group.all_gather_obj({
+                    "kv_role": self.config.kv_role,
+                    "tensor_parallel_size": config.parallel_config.tensor_parallel_size,
+                    "pipeline_parallel_size": config.parallel_config.pipeline_parallel_size,
+                })
+                logger.debug("parallel_configs: %s", parallel_configs)
+                kv_config_enhanced = {
+                    "kv_producers_tensor_parallel_size": None,
+                    "kv_consumers_tensor_parallel_size": None,
+                    "kv_producers_pipeline_parallel_size": None,
+                    "kv_consumers_pipeline_parallel_size": None,
+                    "kv_producers_parallel_size": 0,
+                }
+                for parallel_config in parallel_configs:
+                    kv_role = parallel_config["kv_role"]
+                    assert parallel_config["pipeline_parallel_size"] == 1, f"Only pipeline parallel size 1 is supported for kv transfer instances"
+                    
+                    if kv_role == "kv_producer":
+                        kv_config_enhanced["kv_producers_parallel_size"] += 1
+                    if kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] is None:
+                        kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] = parallel_config["tensor_parallel_size"]
+                        kv_config_enhanced[f"{kv_role}s_pipeline_parallel_size"] = parallel_config["pipeline_parallel_size"]
+                    else:
+                        assert kv_config_enhanced[f"{kv_role}s_tensor_parallel_size"] == parallel_config["tensor_parallel_size"], f"All kv {kv_role}s should have the same tensor parallel size"
+                        assert kv_config_enhanced[f"{kv_role}s_pipeline_parallel_size"] == parallel_config["pipeline_parallel_size"], f"All kv {kv_role}s should have the same pipeline parallel size"
+                world_group.broadcast_object(kv_config_enhanced)
+
+            else:
Neelay Shah's avatar
Neelay Shah committed
2229
+                raise NotImplementedError("MooncakeConnector is not supported in Dynamo patch")
2230
2231
2232
2233
2234
2235
2236
2237
2238
+        else:
+            kv_config_enhanced = world_group.broadcast_object()
+        logger.info("kv_config_enhanced: %s", kv_config_enhanced)
+
+        self.config.kv_producers_tensor_parallel_size = kv_config_enhanced["kv_producers_tensor_parallel_size"]
+        self.config.kv_consumers_tensor_parallel_size = kv_config_enhanced["kv_consumers_tensor_parallel_size"]
+        self.config.kv_producers_pipeline_parallel_size = kv_config_enhanced["kv_producers_pipeline_parallel_size"]
+        self.config.kv_consumers_pipeline_parallel_size = kv_config_enhanced["kv_consumers_pipeline_parallel_size"]
+        self.config.kv_producers_parallel_size = kv_config_enhanced["kv_producers_parallel_size"]
2239
diff --git a/vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py b/vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py
2240
index 5e1b62352..7b4cb406e 100644
2241
2242
--- a/vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py
+++ b/vllm/distributed/kv_transfer/kv_lookup_buffer/simple_buffer.py
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """
     Implements a distributed key-value (KV) cache transfer mechanism.
 
@@ -12,7 +25,8 @@
2262
2263
2264
2265
2266
2267
2268
2269
2270
 import threading
 import time
 from collections import deque
-from typing import Deque, List, Optional, Union
+from concurrent.futures import ThreadPoolExecutor
+from typing import Deque, List, Optional, Union, Dict
 
 import torch
 
2271
@@ -46,7 +60,7 @@ class SimpleBuffer(KVLookupBufferBase):
2272
2273
2274
2275
2276
2277
2278
2279
         self.buffer_lock = threading.Lock()
         self.signal_pipe = signal_pipe
         self.data_pipe = data_pipe
-        self.request_handling_thread: Optional[threading.Thread] = None
+        self.request_handling_thread: Optional[ThreadPoolExecutor] = None
 
         self.normal_signal = torch.tensor([0], device="cpu")
         self.end_signal = None
2280
@@ -57,10 +71,16 @@ class SimpleBuffer(KVLookupBufferBase):
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
         # tokens_roi_sender: tokens and roi of the producer (in the buffer)
         # tokens_roi_recver: tokens and roi of the consumer (query)
 
-        tokens_sender = tokens_roi_sender[0]
-        tokens_recver = tokens_roi_recver[0]
-        roi_sender = tokens_roi_sender[1]
-        roi_recver = tokens_roi_recver[1]
+        target_rank_sender = tokens_roi_sender[0]
+        target_rank_recver = tokens_roi_recver[0]
+
+        if target_rank_sender.item() != target_rank_recver.item():
+            return 0
+        
+        tokens_sender = tokens_roi_sender[1]
+        tokens_recver = tokens_roi_recver[1]
+        roi_sender = tokens_roi_sender[2]
+        roi_recver = tokens_roi_recver[2]
 
         if tokens_recver is None:
             # consumer sends an empty request
2301
@@ -80,14 +100,14 @@ class SimpleBuffer(KVLookupBufferBase):
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
 
         return 0
 
-    def _send_tensor_and_dec_size(self,
-                                  tensor: Optional[torch.Tensor]) -> None:
+    def _send_tensor_and_dec_size(self, tensor: Optional[torch.Tensor],
+                                  target_rank: int) -> None:
 
         assert tensor is not None, "Use self.data_pipe.send(None) instead"
         self.buffer_size -= tensor.element_size() * tensor.numel()
         if tensor.dtype == torch.bool:
             tensor = tensor.float()
-        self.data_pipe.send_tensor(tensor)
+        self.data_pipe.send_tensor(tensor, target_rank)
 
     def _get_element_size(self, data: Optional[Union[List, torch.Tensor]]):
 
2319
@@ -100,7 +120,7 @@ class SimpleBuffer(KVLookupBufferBase):
2320
2321
2322
2323
2324
2325
2326
2327
 
         raise AssertionError(f"Unknown data type {type(data)}")
 
-    def _add_to_buffer(self, input_tokens: torch.Tensor, roi: torch.Tensor,
+    def _add_to_buffer(self, target_rank: int, input_tokens: torch.Tensor, roi: torch.Tensor,
                        key: torch.Tensor, value: torch.Tensor,
                        hidden: torch.Tensor):
 
2328
@@ -115,7 +135,7 @@ class SimpleBuffer(KVLookupBufferBase):
2329
2330
2331
2332
2333
2334
2335
2336
         if isinstance(hidden, torch.Tensor):
             hidden = hidden.clone()
 
-        buffer_item = [input_tokens, roi, key, value, hidden]
+        buffer_item = [torch.tensor(target_rank), input_tokens, roi, key, value, hidden]
 
         with self.buffer_lock:
             for data in buffer_item:
2337
@@ -125,53 +145,54 @@ class SimpleBuffer(KVLookupBufferBase):
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
     def _is_end_signal(self, signal):
         return signal is None
 
-    def drop_select_handler(self):
+    def drop_select_handler(self, rank: int):
 
         try:
 
-            while True:
-                signal = self.signal_pipe.recv_tensor()
-                if self._is_end_signal(signal):
-                    logger.info("Received end signal!")
-                    break
-
-                input_tokens = self.data_pipe.recv_tensor()
-
-                roi = self.data_pipe.recv_tensor()
-                assert roi is not None, "Please provide the roi when sending "\
-                    "drop-select request"
-                roi = (roi > 0.5)
-                tokens_roi_recver = [input_tokens, roi]
-
-                matched_length = 0
-
-                # perform input tokens and roi matching
-                # FIXME: this matching is O(n), ideally it should be O(1)
-                # but this buffer size won't (and shouldn't) be too large so
-                # the fix is not urgent.
-                with self.buffer_lock:
-
-                    for _ in range(len(self.buffer)):
-
-                        temp_length = self._matches(self.buffer[0],
-                                                    tokens_roi_recver)
-                        if temp_length > 0:
-                            matched_length = temp_length
-                            break
-                        # rotate the element we just accessed to the end
-                        self.buffer.rotate(-1)
-
-                    if matched_length > 0:
-                        # need to clone the tensor
-                        # in case the tensor is freed before sending finishes
-                        matched_item = self.buffer.popleft()
-                        for tensor in matched_item:
-                            self._send_tensor_and_dec_size(tensor)
-
-                    else:
-                        # no match, just send None
-                        for _ in range(5):
-                            self.data_pipe.send_tensor(None)
+            signal = self.signal_pipe.recv_tensor(rank)
+            if self._is_end_signal(signal):
+                logger.info("Received end signal!")
+                return
+            target_kv_rank = self.data_pipe.recv_tensor(rank)
+            # assert target_rank.item() == rank, "Target rank does not match"\
+            #     "the rank of the drop-select handler"
+            input_tokens = self.data_pipe.recv_tensor(rank)
+            roi = self.data_pipe.recv_tensor(rank)
+            assert roi is not None, "Please provide the roi when sending "\
+                "drop-select request"
+            roi = (roi > 0.5)
+            tokens_roi_recver = [target_kv_rank, input_tokens, roi]
+
+            matched_length = 0
+
+            # perform input tokens and roi matching
+            # FIXME: this matching is O(n), ideally it should be O(1)
+            # but this buffer size won't (and shouldn't) be too large so
+            # the fix is not urgent.
+            with self.buffer_lock:
+
+                for _ in range(len(self.buffer)):
+
+                    temp_length = self._matches(self.buffer[0],
+                                                tokens_roi_recver)
+                    if temp_length > 0:
+                        matched_length = temp_length
+                        break
+                    # rotate the element we just accessed to the end
+                    self.buffer.rotate(-1)
+
+                if matched_length > 0:
+                    # need to clone the tensor
+                    # in case the tensor is freed before sending finishes
+                    matched_item = self.buffer.popleft()
+                    target_rank = matched_item[0].item()
+                    for tensor in matched_item[1:]:
+                        self._send_tensor_and_dec_size(tensor, rank)
+
+                else:
+                    # no match, just send None
+                    for _ in range(5):
+                        self.data_pipe.send_tensor(None, rank)
 
         except RuntimeError as e:
             if 'Connection closed by peer' not in str(e):
2436
@@ -180,10 +201,10 @@ class SimpleBuffer(KVLookupBufferBase):
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
         logger.debug("Closing drop_select_handler")
 
     def drop_select(
-            self, input_tokens: Optional[torch.Tensor],
+            self, rank: int, kv_rank: int, input_tokens: Optional[torch.Tensor],
             roi: Optional[torch.Tensor]) -> List[Optional[torch.Tensor]]:
 
-        assert self.request_handling_thread is None, \
+        assert not self.request_handling_thread, \
             "drop_select should be called by the KV cache consumer "\
             "(e.g. the decode vLLM instance)"
 
2449
@@ -192,26 +213,28 @@ class SimpleBuffer(KVLookupBufferBase):
2450
2451
2452
2453
2454
2455
2456
2457
         if isinstance(roi, torch.Tensor):
             roi = roi.clone().float()
 
-        self.signal_pipe.send_tensor(self.normal_signal)
-        self.data_pipe.send_tensor(input_tokens)
-        self.data_pipe.send_tensor(roi)
+        self.signal_pipe.send_tensor(self.normal_signal, rank)
+
Neelay Shah's avatar
Neelay Shah committed
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
+        self.data_pipe.send_tensor(torch.tensor(kv_rank), rank)
+        self.data_pipe.send_tensor(input_tokens, rank)
+        self.data_pipe.send_tensor(roi, rank)
 
-        input_tokens = self.data_pipe.recv_tensor()
-        roi = self.data_pipe.recv_tensor()
+        input_tokens = self.data_pipe.recv_tensor(rank)
+        roi = self.data_pipe.recv_tensor(rank)
         if roi is not None:
             # convert from float tensor to bool tensor
             # as PyNccl does not support sending bool tensor
             roi = (roi > 0.5)
-        key = self.data_pipe.recv_tensor()
-        value = self.data_pipe.recv_tensor()
-        hidden = self.data_pipe.recv_tensor()
+        key = self.data_pipe.recv_tensor(rank)
+        value = self.data_pipe.recv_tensor(rank)
+        hidden = self.data_pipe.recv_tensor(rank)
 
         return [input_tokens, roi, key, value, hidden]
 
     def full_handler(self):
         time.sleep(0.001)
 
-    def insert(self, input_tokens: torch.Tensor, roi: torch.Tensor,
+    def insert(self, kv_group_rank: int, target_rank: int, input_tokens: torch.Tensor, roi: torch.Tensor,
                key: torch.Tensor, value: torch.Tensor,
                hidden: torch.Tensor) -> None:
 
2487
@@ -222,20 +245,19 @@ class SimpleBuffer(KVLookupBufferBase):
Neelay Shah's avatar
Neelay Shah committed
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
         while self.buffer_size > self.buffer_size_threshold:
             self.full_handler()
 
-        self._add_to_buffer(input_tokens, roi, key, value, hidden)
+        self._add_to_buffer(target_rank, input_tokens, roi, key, value, hidden)
 
         # when calling the insert, the current process is a sender
         # need to launch the request handler and start listening to request.
+        target_rank_global = target_rank + kv_group_rank
         if self.request_handling_thread is None:
-            self.request_handling_thread = threading.Thread(
-                target=self.drop_select_handler)
-            self.request_handling_thread.start()
+            self.request_handling_thread = ThreadPoolExecutor(max_workers=1)
+        self.request_handling_thread.submit(self.drop_select_handler, target_rank_global)
 
     def close(self):
 
-        if hasattr(self, "request_handling_thread"
-                   ) and self.request_handling_thread is not None:
-            self.request_handling_thread.join()
+        if hasattr(self, "request_handling_thread") and self.request_handling_thread:
+            self.request_handling_thread.shutdown()
 
         else:
             # TODO: have a explicit close signal and have a explicit way to
diff --git a/vllm/distributed/kv_transfer/kv_pipe/base.py b/vllm/distributed/kv_transfer/kv_pipe/base.py
2515
index 40589fb3e..a3991c39d 100644
Neelay Shah's avatar
Neelay Shah committed
2516
2517
--- a/vllm/distributed/kv_transfer/kv_pipe/base.py
+++ b/vllm/distributed/kv_transfer/kv_pipe/base.py
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """
 This file defines an interface `KVPipeBase`
 that provides an abstraction for sending and receiving tensors, or None, via
@@ -23,7 +36,7 @@ class KVPipeBase(ABC):
Neelay Shah's avatar
Neelay Shah committed
2537
2538
2539
2540
2541
2542
2543
2544
     """
 
     @abstractmethod
-    def send_tensor(self, tensor: Optional[torch.Tensor]) -> None:
+    def send_tensor(self, tensor: Optional[torch.Tensor], target_rank: int = 0) -> None:
         """Send a tensor, or None, via the pipe.
         
         Need to support sending None -- important for error handling.
2545
@@ -41,7 +54,7 @@ class KVPipeBase(ABC):
Neelay Shah's avatar
Neelay Shah committed
2546
2547
2548
2549
2550
2551
2552
2553
         raise NotImplementedError
 
     @abstractmethod
-    def recv_tensor(self) -> Optional[torch.Tensor]:
+    def recv_tensor(self, src_rank: int) -> Optional[torch.Tensor]:
         """Receive a tensor (can be None) from the pipeline.
 
         Returns:
Neelay Shah's avatar
Neelay Shah committed
2554
diff --git a/vllm/distributed/kv_transfer/kv_pipe/dynamo_nccl_pipe.py b/vllm/distributed/kv_transfer/kv_pipe/dynamo_nccl_pipe.py
Neelay Shah's avatar
Neelay Shah committed
2555
new file mode 100644
2556
index 000000000..ca5345359
Neelay Shah's avatar
Neelay Shah committed
2557
--- /dev/null
Neelay Shah's avatar
Neelay Shah committed
2558
+++ b/vllm/distributed/kv_transfer/kv_pipe/dynamo_nccl_pipe.py
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
@@ -0,0 +1,139 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
Neelay Shah's avatar
Neelay Shah committed
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
+import logging
+import threading
+import typing
+import zmq
+import socket
+import time
+import torch
+
+from vllm.distributed.kv_transfer.kv_pipe.pynccl_pipe import PyNcclPipe
+
+
+logger = logging.getLogger(__name__)
+
+
Neelay Shah's avatar
Neelay Shah committed
2589
+class DynamoNcclDataPlane:
Neelay Shah's avatar
Neelay Shah committed
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
+    def __init__(
+        self,
+        data_pipe: PyNcclPipe,
+        hostname: str = "",
+        port: int = 0,
+    ) -> None:
+        
+        self.data_pipe = data_pipe
+        if not hostname:
+            hostname = socket.gethostname()
+        if port == 0:
+            raise ValueError("Port cannot be 0")
+        self._hostname = hostname
+        self._port = port
+        self.store = {}
+        self.context = zmq.Context()
+        self.rep_socket = self.context.socket(zmq.REP)
+        logger.info(f"Rank {self.rank} binding to {self._hostname}:{self._port}")
+        self.rep_socket.bind(f"tcp://{self._hostname}:{self._port}")
+        self._listener_thread = threading.Thread(target=self.listen_for_requests, daemon=True)
+        self._listener_thread.start()
+        self.req_sockets = {}
+        logger.info(f"Rank {self.rank} connected to the server")
+
+    @property
+    def rank(self):
+        return self.data_pipe.kv_group_rank
+    
+    def send_tensor(
+        self,
+        tensor: torch.Tensor,
+        tensor_id: str,
+        remote_address: typing.Optional[str] = None,
+    ):
+        logger.debug(f"Rank {self.rank} sending tensor {tensor_id} to {remote_address}")
+        return self._send_tensor(tensor, tensor_id, remote_address)
+
+    def recv_tensor(
+        self,
+        tensor_id: str,
+        remote_address: typing.Optional[str] = None,
+    ) -> torch.Tensor:
+        ret = self._recv_tensor(tensor_id, remote_address)
+        return ret
+
+    def _send_tensor(
+        self,
+        tensor: torch.Tensor,
+        tensor_id: str,
+        remote_address: typing.Optional[str] = None,
+    ):
+        logger.debug(f"Rank {self.rank} storing tensor with id {tensor_id} of shape {tensor.shape} and dtype {tensor.dtype}")
+        if remote_address is None:
+            self.store[tensor_id] = tensor
+        else:
+            # tensor_shape = "_".join(str(dim) for dim in tensor.shape)
+            # tensor_dtype = str(tensor.dtype)
+            if remote_address not in self.req_sockets:
+                self.req_sockets[remote_address] = self.context.socket(zmq.REQ)
+                self.req_sockets[remote_address].connect(f"tcp://{remote_address}")
+
+            req_socket = self.req_sockets[remote_address]
+            # req_socket.connect(f"tcp://{remote_address}")
+            req_socket.send_string(f"PUT {self.rank} {tensor_id}")
+            dst_rank = req_socket.recv_string()
+            logger.debug(f"Rank {self.rank} sending tensor {tensor_id} to rank {dst_rank}")
+            self.data_pipe.send_tensor(tensor, int(dst_rank))
+
+    def _recv_tensor(
+        self,
+        tensor_id: str,
+        remote_address: typing.Optional[str] = None,
+    ) -> torch.Tensor:
+        logger.debug(f"Rank {self.rank} receiving tensor")
+        if remote_address is not None:
+            raise NotImplementedError("Getting tensor from remote rank not implemented")
+        if tensor_id in self.store:
+            logger.debug(f"Popping tensor {tensor_id} from store")
+            future = self.store.pop(tensor_id)
+            tensor = future.result() # TODO ptarasiewicz we should run other request instead of wait
+            logger.debug(f"Rank {self.rank} received tensor")
+            return tensor
+            
+        logger.debug(f"Rank {self.rank} waiting for tensor {tensor_id}")
+        time.sleep(0.001)
+        return self._recv_tensor(tensor_id, remote_address)
+        # raise NotImplementedError("Tensor not found in store")
+
+    def _receive_tensor(
+        self,
+        tensor_id: str,
+        rank: int,
+    ):
+        future = self.data_pipe.recv_tensor(rank)
+        logger.debug(f"Rank {self.rank} storing tensor {tensor_id} in store")
+        self.store[tensor_id] = future
+
+    def listen_for_requests(self):
+        while True:
+            cmd, rank, tensor_id = self.rep_socket.recv_string().split()
+            logger.debug(f"Rank {self.rank} received request for tensor {tensor_id}")
+            self.rep_socket.send_string(f"{self.rank}")
+            if cmd == "GET":
+                raise NotImplementedError("Getting tensor from remote rank not implemented")
+            elif cmd == "PUT":
+                rank = int(rank)
+                # shape = [int(dim) for dim in shape.split("_")]
+                # dtype = getattr(torch, dtype)
+                self._receive_tensor(tensor_id, rank)
2699
diff --git a/vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py b/vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py
2700
index 7aa53d07a..8fb256aff 100644
2701
2702
--- a/vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py
+++ b/vllm/distributed/kv_transfer/kv_pipe/pynccl_pipe.py
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """
     This module implements a PyNccl pipe for sending and receiving 
     Optional[torch.Tensor] between distributed ranks with advanced 
@@ -45,33 +58,33 @@ class PyNcclPipe(KVPipeBase):
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
     METADATA_DTYPE = torch.int64
 
     def __init__(self,
+                 kv_group_rank: int,
                  local_rank: int,
                  config: KVTransferConfig,
                  device: Optional[str] = None,
                  port_offset: int = 0):
         self.config = config
         self.local_rank = local_rank
-        self.kv_rank = self.config.kv_rank
+        self.kv_group_rank = kv_group_rank
         self.kv_parallel_size = self.config.kv_parallel_size
+        self.kv_world_size = self.config.kv_world_size
         if device is None:
             self.device = self._select_device(self.config.kv_buffer_device)
         else:
             self.device = self._select_device(device)
 
         # build distributed connection and send/recv implementation
+        logger.info("Creating process group for kv transfer with rank %d and world size %d, ip: %s, port: %d", self.kv_group_rank, self.kv_world_size, self.config.kv_ip, self.config.kv_port + port_offset)
         self.group = StatelessProcessGroup.create(
             host=self.config.kv_ip,
             port=self.config.kv_port + port_offset,
-            rank=self.kv_rank,
-            world_size=self.kv_parallel_size,
+            rank=self.kv_group_rank,
+            world_size=self.kv_world_size,
         )
         # add a barrier to make sure the connection is initiated properly
         self.group.barrier()
         impl = self._get_device_send_recv_impl(self.group)
         self.device_send_func, self.device_recv_func = impl
-        # set target rank
-        self.target_rank_for_send = (self.kv_rank + 1) % self.kv_parallel_size
-        self.target_rank_for_recv = (self.kv_rank - 1) % self.kv_parallel_size
 
         # transportation-related variables
         self.transport_thread: Optional[ThreadPoolExecutor] = None
2761
@@ -145,16 +158,16 @@ class PyNcclPipe(KVPipeBase):
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
                            dtype=metadata["dtype"],
                            device=self.device)
 
-    def _send_metadata(self, metadata: Metadata):
+    def _send_metadata(self, metadata: Metadata, target_rank: int):
         """
         Send the metadata dictionary to the target rank.
 
         Parameters:
             - metadata: A dictionary with keys "dtype" and "shape".
         """
-        self.group.send_obj(metadata, self.target_rank_for_send)
+        self.group.send_obj(metadata, target_rank)
 
-    def _recv_metadata(self) -> Metadata:
+    def _recv_metadata(self, src_rank: int) -> Metadata:
         """
         Receive the metadata dictionary from the target rank.
 
2781
@@ -162,9 +175,9 @@ class PyNcclPipe(KVPipeBase):
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
             - metadata: A dictionary with keys "dtype" and "shape" describing 
               the tensor.
         """
-        return self.group.recv_obj(self.target_rank_for_recv)
+        return self.group.recv_obj(src_rank)
 
-    def _send_impl(self, tensor: Optional[torch.Tensor]) -> None:
+    def _send_impl(self, tensor: Optional[torch.Tensor], target_rank: int) -> None:
         """
         The actual implementation of sending the tensor and its metadata to the 
         target rank.
2793
@@ -174,12 +187,12 @@ class PyNcclPipe(KVPipeBase):
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
               being sent.
         """
         metadata = self._make_metadata(tensor)
-        self._send_metadata(metadata)
+        self._send_metadata(metadata, target_rank)
         if tensor is not None:
             self.device_send_func(tensor.to(self.device),
-                                  self.target_rank_for_send)
+                                  target_rank)
 
-    def _recv_impl(self) -> Optional[torch.Tensor]:
+    def _recv_impl(self, src_rank: int) -> Optional[torch.Tensor]:
         """
         The actual implementation of receiving a tensor and its metadata from 
         the target rank.
2809
@@ -187,21 +200,22 @@ class PyNcclPipe(KVPipeBase):
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
         Returns:
             - buffer: The received tensor, or None if no tensor is received.
         """
-        metadata = self._recv_metadata()
+        metadata = self._recv_metadata(src_rank)
         if metadata["dtype"] is None:
             return None
         buffer = self._prepare_recv_buffer(metadata)
-        self.device_recv_func(buffer, self.target_rank_for_recv)
+        self.device_recv_func(buffer, src_rank)
 
         return buffer
 
     def send_tensor_wrapper(self, tensor: Optional[torch.Tensor],
-                            tensor_size: int) -> None:
+                            tensor_size: int,
+                            target_rank: int) -> None:
         """
         Wrapper for _send_impl to handle exceptions and update buffer size.
         """
         try:
-            self._send_impl(tensor)
+            self._send_impl(tensor, target_rank)
 
             with self.buffer_size_lock:
                 self.buffer_size -= tensor_size
2836
@@ -220,7 +234,7 @@ class PyNcclPipe(KVPipeBase):
2837
2838
2839
2840
2841
2842
2843
2844
             logger.debug("KV cache transfer pipe is full. Waiting...")
             time.sleep(0.05)
 
-    def send_tensor(self, tensor: Optional[torch.Tensor]) -> None:
+    def send_tensor(self, tensor: Optional[torch.Tensor], target_rank: int) -> None:
         """
         Sends a tensor and its metadata to the destination rank in a 
         non-blocking way.
2845
@@ -228,6 +242,7 @@ class PyNcclPipe(KVPipeBase):
2846
2847
2848
2849
2850
2851
2852
         Parameters:
             - tensor: The tensor to send, or None if no tensor is being sent.
         """
+        logger.debug("Rank %d sending tensor of shape %s dtype %s to rank %d", self.kv_group_rank, tensor.shape if tensor is not None else "None", tensor.dtype if tensor is not None else "None", target_rank)
         if self.transport_thread is None:
             self.transport_thread = ThreadPoolExecutor(max_workers=1)
 
2853
@@ -241,32 +256,39 @@ class PyNcclPipe(KVPipeBase):
2854
         with self.buffer_size_lock:
2855
2856
             self.buffer_size += tensor_size
 
2857
-        self.transport_thread.submit(self.send_tensor_wrapper, tensor,
2858
-                                     tensor_size)
2859
+        future = self.transport_thread.submit(self.send_tensor_wrapper, tensor,
2860
2861
+                                     tensor_size,
+                                     target_rank)
2862
+        return future
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
 
-    def recv_tensor(self) -> Optional[torch.Tensor]:
+    def recv_tensor(self, src_rank: int) -> Optional[torch.Tensor]:
         """
         Receives a tensor and its metadata from the source rank. Blocking call.
 
         Returns:
             - tensor: The received tensor, or None if no tensor is received.
         """
+
+        logger.debug("Rank %d receiving tensor from rank %d", self.kv_group_rank, src_rank)
+
         if self.transport_thread is None:
             self.transport_thread = ThreadPoolExecutor(max_workers=1)
 
-        future = self.transport_thread.submit(self._recv_impl)
+        future = self.transport_thread.submit(self._recv_impl, src_rank)
 
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
-        try:
-            tensor = future.result()
-        except Exception as e:
-            logger.error("Encountering exception in KV receiving thread")
-            logger.error("%s", e)
-            logger.error("My device: %s", self.device)
-            import traceback
-            traceback.print_exc()
-            raise e
+        return future
+
+        # try:
+        #     tensor = future.result()
+        # except Exception as e:
+        #     logger.error("Encountering exception in KV receiving thread")
+        #     logger.error("%s", e)
+        #     logger.error("My device: %s", self.device)
+        #     import traceback
+        #     traceback.print_exc()
+        #     raise e
 
-        return tensor
+        # return tensor
 
     def close(self):
         """
2907
diff --git a/vllm/distributed/kv_transfer/kv_transfer_agent.py b/vllm/distributed/kv_transfer/kv_transfer_agent.py
2908
index 1e80e0bd7..f06c7a5f6 100644
2909
2910
--- a/vllm/distributed/kv_transfer/kv_transfer_agent.py
+++ b/vllm/distributed/kv_transfer/kv_transfer_agent.py
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 """A centralized entrypoint to perform distributed KV cache transfer.
 
 This implementation is a shim wrapper on two APIs exposed by `kv_connector`:
@@ -35,6 +48,7 @@ class KVTransferAgent:
2930
2931
2932
2933
2934
2935
2936
         rank: int,
         local_rank: int,
         config: "VllmConfig",
+        world_group,
     ):
 
         self.config = config
2937
@@ -47,7 +61,7 @@ class KVTransferAgent:
2938
2939
2940
2941
2942
2943
2944
2945
2946
             "TransferAgent should only be used when kv_connector is set."
 
         self.connector = KVConnectorFactory.create_connector(
-            rank, local_rank, config)
+            rank, local_rank, config, world_group)
 
     def send_kv_caches_and_hidden_states(
         self,
diff --git a/vllm/distributed/parallel_state.py b/vllm/distributed/parallel_state.py
2947
index 321902d11..03409899e 100644
2948
2949
--- a/vllm/distributed/parallel_state.py
+++ b/vllm/distributed/parallel_state.py
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 
 # Copyright 2023 The vLLM team.
 # Adapted from
@@ -1085,7 +1098,8 @@ def ensure_kv_transfer_initialized(vllm_config: "VllmConfig") -> None:
2969
2970
2971
2972
2973
2974
2975
2976
2977
         _KV_TRANSFER = kv_transfer.KVTransferAgent(
             rank=get_world_group().rank,
             local_rank=get_world_group().local_rank,
-            config=vllm_config)
+            config=vllm_config,
+            world_group=get_world_group())
 
 
 def ensure_model_parallel_initialized(
2978
diff --git a/vllm/engine/llm_engine.py b/vllm/engine/llm_engine.py
2979
index d82d9ad9d..61c1e429d 100644
2980
2981
--- a/vllm/engine/llm_engine.py
+++ b/vllm/engine/llm_engine.py
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
@@ -1,14 +1,31 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
ptarasiewiczNV's avatar
ptarasiewiczNV committed
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
 
 import copy
 import time
+import pickle
+import uuid
 from collections import Counter as collectionsCounter
 from collections import deque
+from collections import defaultdict
 from contextlib import contextmanager
 from dataclasses import dataclass
+from concurrent.futures import ThreadPoolExecutor
 from functools import partial
 from typing import (TYPE_CHECKING, Callable, ClassVar, Deque, Dict, Iterable,
-                    List, Mapping, NamedTuple, Optional)
+                    List, Mapping, NamedTuple, Optional, Tuple)
 from typing import Sequence as GenericSequence
 from typing import Set, Type, Union, cast, overload
 
3015
@@ -60,6 +77,9 @@ from vllm.usage.usage_lib import (UsageContext, is_usage_stats_enabled,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3016
3017
3018
                                   usage_message)
 from vllm.utils import Counter, Device, deprecate_kwargs, weak_bind
 from vllm.version import __version__ as VLLM_VERSION
3019
+from vllm.remote_prefill import RemotePrefillRequest, RemotePrefillParams, MemoryTransferRequest, MemoryOpType
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3020
3021
3022
3023
3024
+from vllm.distributed.device_communicators.nixl import NixlMetadata
+
 
 logger = init_logger(__name__)
 _LOCAL_LOGGING_INTERVAL_SEC = 5
3025
@@ -90,7 +110,7 @@ class OutputData(NamedTuple):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3026
3027
3028
3029
3030
3031
3032
3033
     # outputs from multiple steps.
     is_first_step_output: Optional[bool]
     skip: List[int]
-
+    remote_prefill_requests: Optional[List[RemotePrefillRequest]]
 
 class SchedulerContext:
 
3034
@@ -104,11 +124,14 @@ class SchedulerContext:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
 
         self.multi_step_stream_outputs: bool = multi_step_stream_outputs
 
+        self.remote_prefill_requests: List[RemotePrefillRequest] = []
+
     def append_output(self, outputs: List[SamplerOutput],
                       seq_group_metadata_list: List[SequenceGroupMetadata],
                       scheduler_outputs: SchedulerOutputs, is_async: bool,
                       is_last_step: bool,
-                      is_first_step_output: Optional[bool]):
+                      is_first_step_output: Optional[bool],
+                      remote_prefill_requests: Optional[List[RemotePrefillRequest]] = None):
         self.output_queue.append(
             OutputData(outputs=outputs,
                        seq_group_metadata_list=seq_group_metadata_list,
3050
@@ -116,7 +139,9 @@ class SchedulerContext:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
                        is_async=is_async,
                        is_last_step=is_last_step,
                        is_first_step_output=is_first_step_output,
-                       skip=[]))
+                       skip=[],
+                       remote_prefill_requests=remote_prefill_requests))
+
 
 
 class LLMEngine:
3061
@@ -348,7 +373,7 @@ class LLMEngine:
3062
3063
3064
3065
3066
3067
3068
3069
         # GPU and CPU blocks, which are profiled in the distributed executor.
         self.scheduler = [
             Scheduler(
-                self.scheduler_config, self.cache_config, self.lora_config,
+                self.model_config, self.scheduler_config, self.cache_config, self.lora_config,
                 self.parallel_config.pipeline_parallel_size,
                 self.async_callbacks[v_id]
                 if self.model_config.use_async_output_proc else None)
3070
@@ -405,6 +430,40 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3071
3072
3073
3074
3075
 
         self.seq_id_to_seq_group: Dict[str, SequenceGroupBase] = {}
 
+        self.engine_id = str(uuid.uuid4())
+        self._nixl_agents_names: Optional[List[str]] = None
Neelay Shah's avatar
Neelay Shah committed
3076
+        if self.vllm_config.kv_transfer_config is not None and self.vllm_config.kv_transfer_config.kv_connector == "DynamoNixlConnector":
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3077
3078
3079
+            self._nixl_agents_names = self._initialize_nixl()
+
+        self._request_notif_counter = defaultdict(lambda: -self.parallel_config.tensor_parallel_size)
Neelay Shah's avatar
Neelay Shah committed
3080
+        self._request_done_counter = defaultdict(lambda: -self.parallel_config.tensor_parallel_size)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3081
+        self._finished_prefills = set()
Neelay Shah's avatar
Neelay Shah committed
3082
+        self._finished_transfers = set()
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3083
3084
3085
+
+    @property
+    def is_nixl_initialized(self) -> bool:
3086
+        return getattr(self, "_nixl_agents_names", None) is not None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3087
3088
3089
3090
3091
3092
+
+    def get_nixl_metadata(self) -> NixlMetadata:
+        if not self.is_nixl_initialized:
+            raise RuntimeError("Nixl is not initialized")
+        agent_metadata = self.model_executor.collective_rpc("get_nixl_agent_metadata")
+        kv_caches_base_addr = self.model_executor.collective_rpc("get_nixl_kv_caches_base_addr")
3093
+        return NixlMetadata(engine_id=self.engine_id, agent_metadata=agent_metadata, kv_caches_base_addr=kv_caches_base_addr, num_blocks=self.cache_config.num_gpu_blocks)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3094
3095
3096
3097
3098
3099
3100
+    
+    def add_remote_nixl_metadata(self, nixl_metadata: NixlMetadata) -> List[str]:
+        if not self.is_nixl_initialized:
+            raise RuntimeError("Nixl is not initialized")
+        engine_id = nixl_metadata.engine_id
+        agents_metadata = nixl_metadata.agent_metadata
+        kv_caches_base_addr = nixl_metadata.kv_caches_base_addr
3101
3102
+        num_blocks = nixl_metadata.num_blocks
+        return self.model_executor.collective_rpc("add_remote_nixl_metadata", args=(engine_id, agents_metadata, kv_caches_base_addr, num_blocks))
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3103
3104
3105
3106
3107
3108
3109
3110
+
+    def _initialize_nixl(self) -> List[bytes]:
+        agents_names = self.model_executor.collective_rpc("initialize_nixl", args=(self.engine_id,))
+        return agents_names
+
     def _initialize_kv_caches(self) -> None:
         """Initialize the KV cache in the worker(s).
 
3111
@@ -500,6 +559,8 @@ class LLMEngine:
3112
3113
3114
3115
3116
3117
3118
3119
         # Shutdown model executor when engine is garbage collected
         # Use getattr since __init__ can fail before the field is set
         if model_executor := getattr(self, "model_executor", None):
+            if self.is_nixl_initialized:
+                model_executor.collective_rpc("shutdown_nixl")
             model_executor.shutdown()
 
     def get_tokenizer_group(
3120
@@ -552,11 +613,14 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
         prompt_adapter_request: Optional[PromptAdapterRequest],
         trace_headers: Optional[Mapping[str, str]] = None,
         priority: int = 0,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> Optional[SequenceGroup]:
         """Add a processed request to the engine's request pool.
         return the created sequence group.
         """
         if isinstance(params, SamplingParams) and params.n > 1:
+            if remote_prefill_params is not None:
+                raise ValueError("Remote prefill params are not supported for multi-step sampling")
             ParallelSampleSequenceGroup.add_request(
                 request_id,
                 self,
3135
@@ -574,6 +638,8 @@ class LLMEngine:
Neelay Shah's avatar
Neelay Shah committed
3136
3137
3138
3139
3140
3141
3142
3143
         # Create the sequences.
         block_size = self.cache_config.block_size
         seq_id = next(self.seq_counter)
+        if remote_prefill_params is not None and remote_prefill_params.is_remote_decode:
+            next(self.seq_counter) # empty sequence for staging
         eos_token_id = self.input_preprocessor.get_eos_token_id(lora_request)
 
         if is_encoder_decoder_inputs(processed_inputs):
3144
@@ -584,7 +650,7 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3145
3146
3147
3148
3149
3150
3151
3152
             encoder_inputs = None
 
         seq = Sequence(seq_id, decoder_inputs, block_size, eos_token_id,
-                       lora_request, prompt_adapter_request)
+                       lora_request, prompt_adapter_request, remote_prefill_params)
 
         encoder_seq = (None if encoder_inputs is None else Sequence(
             seq_id, encoder_inputs, block_size, eos_token_id, lora_request,
3153
@@ -601,8 +667,12 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
                 trace_headers=trace_headers,
                 prompt_adapter_request=prompt_adapter_request,
                 encoder_seq=encoder_seq,
-                priority=priority)
+                priority=priority,
+                remote_prefill_params=remote_prefill_params,
+            )
         elif isinstance(params, PoolingParams):
+            if remote_prefill_params is not None:
+                raise ValueError("Remote prefill params are not supported for pooling")
             seq_group = self._create_sequence_group_with_pooling(
                 request_id,
                 seq,
3167
@@ -673,6 +743,7 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3168
3169
3170
3171
3172
3173
3174
             trace_headers: Optional[Mapping[str, str]] = None,
             prompt_adapter_request: Optional[PromptAdapterRequest] = None,
             priority: int = 0,
+            remote_prefill_params: Optional[RemotePrefillParams] = None,
             *,
             inputs: Optional[PromptType] = None,  # DEPRECATED
     ) -> None:
3175
@@ -765,6 +836,7 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3176
3177
3178
3179
3180
3181
3182
             prompt_adapter_request=prompt_adapter_request,
             trace_headers=trace_headers,
             priority=priority,
+            remote_prefill_params=remote_prefill_params,
         )
 
     def _validate_token_prompt(self, prompt: PromptType,
3183
@@ -799,6 +871,7 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3184
3185
3186
3187
3188
3189
3190
         prompt_adapter_request: Optional[PromptAdapterRequest] = None,
         encoder_seq: Optional[Sequence] = None,
         priority: int = 0,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> SequenceGroup:
         """Creates a SequenceGroup with SamplingParams."""
         max_logprobs = self.get_model_config().max_logprobs
3191
@@ -829,7 +902,9 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
             trace_headers=trace_headers,
             prompt_adapter_request=prompt_adapter_request,
             encoder_seq=encoder_seq,
-            priority=priority)
+            priority=priority,
+            remote_prefill_params=remote_prefill_params
+        )
 
         return seq_group
 
3202
@@ -995,11 +1070,11 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
             # When we process only one request, no pop is required
             # (since later we will process all of the rest)
             (outputs, seq_group_metadata_list, scheduler_outputs, is_async,
-             is_last_step, is_first_step_output, skip) = ctx.output_queue[0]
+             is_last_step, is_first_step_output, skip, remote_prefill_requests) = ctx.output_queue[0]
         else:
             (outputs, seq_group_metadata_list, scheduler_outputs, is_async,
              is_last_step, is_first_step_output,
-             skip) = ctx.output_queue.popleft()
+             skip, remote_prefill_requests) = ctx.output_queue.popleft()
 
         # Sanity check
         assert len(seq_group_metadata_list) == len(
3216
@@ -1325,15 +1400,55 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
 
         # Clear outputs for each new scheduler iteration
         ctx.request_outputs.clear()
+        ctx.remote_prefill_requests.clear()
 
         # Skip the scheduler if there are any remaining steps in the seq groups.
         # This ensures that the scheduler is only called again when the current
         # batch has completed.
+        remote_prefill_seq_group_metadata_list: List[SequenceGroupMetadata] = []
+        running_seq_group_metadata_list: List[SequenceGroupMetadata] = []
+        remote_prefill_scheduled_seq_groups: List[ScheduledSequenceGroup] = []
+        running_scheduled_seq_groups: List[ScheduledSequenceGroup] = []
+        
         if not self._has_remaining_steps(seq_group_metadata_list):
-            # Schedule iteration
+
             (seq_group_metadata_list, scheduler_outputs,
              allow_async_output_proc
-             ) = self.scheduler[virtual_engine].schedule()
Neelay Shah's avatar
Neelay Shah committed
3236
+             ) = self.scheduler[virtual_engine].schedule(self._finished_prefills, self._finished_transfers)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
+            
+
+            # Separate remote prefill and running seq groups
+            for seq_group_metadata, scheduled_seq_group in zip(seq_group_metadata_list, scheduler_outputs.scheduled_seq_groups):
+                if seq_group_metadata.do_remote_prefill:
+                    remote_prefill_seq_group_metadata_list.append(seq_group_metadata)
+                    remote_prefill_scheduled_seq_groups.append(scheduled_seq_group)
+                else:
+                    running_seq_group_metadata_list.append(seq_group_metadata)
+                    running_scheduled_seq_groups.append(scheduled_seq_group)
+
+            seq_group_metadata_list = running_seq_group_metadata_list
+            scheduler_outputs.scheduled_seq_groups = running_scheduled_seq_groups
+            
+            # Send remote prefill requests before model execution
+            for seq_group_metadata, scheduled_seq_group in zip(remote_prefill_seq_group_metadata_list, remote_prefill_scheduled_seq_groups):
+                assert len(scheduled_seq_group.seq_group.seqs) == 1
+                assert self._nixl_agents_names
+                seq_id = scheduled_seq_group.seq_group.seqs[0].seq_id
+                block_table = seq_group_metadata.block_tables[seq_id]
3257
3258
3259
3260
+                if len(block_table) == len(seq_group_metadata.computed_block_nums):
+                    logger.debug("No blocks to prefill")
+                    self._finished_prefills.add(seq_group_metadata.request_id)
+                    continue
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3261
3262
+                remote_prefill_request = RemotePrefillRequest(
+                    request_id=seq_group_metadata.request_id,
3263
3264
+                    # prompt_token_ids=scheduled_seq_group.seq_group.seqs[0].inputs.prompt_token_ids[:-1], # last one will be decoded on decode for sampling anyway
+                    prompt_token_ids=scheduled_seq_group.seq_group.seqs[0].inputs.prompt_token_ids, # TODO ptarasiewicz do not send the last token when NIXL fixes send notif (needed for writing 0 blocks)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3265
3266
3267
+                    sampling_params=scheduled_seq_group.seq_group.sampling_params,
+                    block_ids=block_table,
+                    engine_id=self.engine_id,
3268
+                    computed_block_ids=seq_group_metadata.computed_block_nums,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3269
3270
3271
3272
3273
+                )
+                scheduled_seq_group.seq_group.remote_prefill_params.remote_prefill_request_callback(remote_prefill_request)
 
             ctx.seq_group_metadata_list = seq_group_metadata_list
             ctx.scheduler_outputs = scheduler_outputs
3274
@@ -1383,9 +1498,46 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
                 execute_model_req.async_callback = self.async_callbacks[
                     virtual_engine]
 
-            outputs = self.model_executor.execute_model(
+            # After model execution, we need to transfer the memory from the prefill to the decode
+            memory_transfer_reqs = []
+            for scheduled_seq_group, seq_group_metadata in zip(scheduler_outputs.scheduled_seq_groups, seq_group_metadata_list):
+                remote_prefill_params = scheduled_seq_group.seq_group.remote_prefill_params
+                if remote_prefill_params is not None and remote_prefill_params.is_remote_decode:
+                    assert len(scheduled_seq_group.seq_group.seqs) == 1
+                    req_id = scheduled_seq_group.seq_group.request_id
+                    seq_id = scheduled_seq_group.seq_group.seqs[0].seq_id
+                    block_table = seq_group_metadata.block_tables[seq_id]
Neelay Shah's avatar
Neelay Shah committed
3288
+                    staging_block_ids = seq_group_metadata.block_tables[seq_id + 1]
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
+
+                    num_computed_blocks = len(seq_group_metadata.computed_block_nums)
+                    computed_decode_block_ids = remote_prefill_params.decode_block_ids[:num_computed_blocks]
+
+                    if computed_decode_block_ids:
+                        kv_recv_req = MemoryTransferRequest(
+                            request_id=req_id,
+                            local_block_ids=block_table[:num_computed_blocks],
+                            staging_block_ids=staging_block_ids[:num_computed_blocks],
+                            remote_block_ids=computed_decode_block_ids,
+                            remote_engine_id=remote_prefill_params.decode_engine_id,
+                            notify_msg=req_id,
+                            op_type=MemoryOpType.READ
+                        )
+                        memory_transfer_reqs.append(kv_recv_req)
+
+                    kv_send_req = MemoryTransferRequest(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3306
+                        request_id=req_id,
3307
3308
3309
3310
+                        local_block_ids=block_table[num_computed_blocks:],
+                        staging_block_ids=staging_block_ids[num_computed_blocks:],
+                        remote_block_ids=remote_prefill_params.decode_block_ids[num_computed_blocks:],
+                        remote_engine_id=remote_prefill_params.decode_engine_id,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3311
+                        notify_msg=req_id,
3312
+                        op_type=MemoryOpType.WRITE
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3313
+                    )
3314
+                    memory_transfer_reqs.append(kv_send_req)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3315
3316
+            execute_model_req.memory_transfer_requests = memory_transfer_reqs
+
Neelay Shah's avatar
Neelay Shah committed
3317
+            outputs, request_notif_counter, request_done_counter = self.model_executor.execute_model(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3318
3319
3320
3321
3322
                 execute_model_req=execute_model_req)
-
             # We need to do this here so that last step's sampled_token_ids can
             # be passed to the next iteration for PP.
             if self.scheduler_config.is_multi_step:
3323
@@ -1396,7 +1548,26 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
             if len(ctx.output_queue) > 0:
                 self._process_model_outputs(ctx=ctx)
             # No outputs in this case
-            outputs = []
+            execute_model_req = ExecuteModelRequest(
+                seq_group_metadata_list=[],
+                blocks_to_swap_in=[],
+                blocks_to_swap_out=[],
+                blocks_to_copy=[])
+
Neelay Shah's avatar
Neelay Shah committed
3334
+            outputs, request_notif_counter, request_done_counter = self.model_executor.execute_model(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3335
3336
3337
3338
3339
3340
3341
+                execute_model_req=execute_model_req)
+            
+        for req_id, notif_count in request_notif_counter.items():
+            self._request_notif_counter[req_id] += notif_count
+            if self._request_notif_counter[req_id] > -1:
+                self._finished_prefills.add(req_id)
+                del self._request_notif_counter[req_id]
Neelay Shah's avatar
Neelay Shah committed
3342
3343
3344
3345
3346
3347
+
+        for req_id, done_count in request_done_counter.items():
+            self._request_done_counter[req_id] += done_count
+            if self._request_done_counter[req_id] > -1:
+                self._finished_transfers.add(req_id)
+                del self._request_done_counter[req_id]
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3348
3349
3350
 
         # Finish the current step for all the sequence groups.
         if self.scheduler_config.is_multi_step:
3351
@@ -1456,7 +1627,7 @@ class LLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3352
3353
3354
3355
3356
3357
3358
3359
             # queued control plane messages, such as add/remove lora adapters.
             logger.debug("Stopping remote worker execution loop.")
             self.model_executor.stop_remote_worker_execution_loop()
-
+            
         return ctx.request_outputs
 
     def _has_remaining_steps(
GuanLuo's avatar
GuanLuo committed
3360
diff --git a/vllm/engine/multiprocessing/__init__.py b/vllm/engine/multiprocessing/__init__.py
3361
index 3cf1850ee..d20a5f20b 100644
GuanLuo's avatar
GuanLuo committed
3362
3363
--- a/vllm/engine/multiprocessing/__init__.py
+++ b/vllm/engine/multiprocessing/__init__.py
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 uuid
 from dataclasses import dataclass, field
@@ -14,13 +27,17 @@ from vllm.outputs import RequestOutput
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3383
3384
3385
3386
3387
3388
3389
3390
3391
 from vllm.prompt_adapter.request import PromptAdapterRequest
 from vllm.sampling_params import SamplingParams
 from vllm.utils import deprecate_kwargs
-
+from vllm.remote_prefill import RemotePrefillParams
+from vllm.distributed.device_communicators.nixl import NixlMetadata
 VLLM_RPC_SUCCESS_STR = "SUCCESS"
 
 IPC_INPUT_EXT = "_input_socket"
GuanLuo's avatar
GuanLuo committed
3392
3393
3394
 IPC_OUTPUT_EXT = "_output_socket"
 IPC_HEALTH_EXT = "_health_socket"
 IPC_DATA_EXT = "_data_socket"
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3395
3396
+IPC_REMOTE_PREFILL_REQUEST_EXT = "_remote_prefill_request_socket"
+IPC_REMOTE_NIXL_METADATA_EXT = "_remote_nixl_metadata_socket"
GuanLuo's avatar
GuanLuo committed
3397
3398
3399
3400
+IPC_METRICS_EXT = "_metrics_socket"
 
 
 class MQEngineDeadError(RuntimeError):
3401
@@ -36,6 +53,7 @@ class RPCProcessRequest:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3402
3403
3404
3405
3406
3407
3408
     trace_headers: Optional[Mapping[str, str]] = None
     prompt_adapter_request: Optional[PromptAdapterRequest] = None
     priority: int = 0
+    remote_prefill_params: Optional[RemotePrefillParams] = None
 
     @overload
     def __init__(
3409
@@ -78,6 +96,7 @@ class RPCProcessRequest:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3410
3411
3412
3413
3414
3415
3416
             trace_headers: Optional[Mapping[str, str]] = None,
             prompt_adapter_request: Optional[PromptAdapterRequest] = None,
             priority: int = 0,
+            remote_prefill_params: Optional[RemotePrefillParams] = None,
             *,
             inputs: Optional[PromptType] = None,  # DEPRECATED
     ) -> None:
3417
@@ -95,7 +114,7 @@ class RPCProcessRequest:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3418
3419
3420
3421
3422
3423
3424
3425
         self.trace_headers = trace_headers
         self.prompt_adapter_request = prompt_adapter_request
         self.priority = priority
-
+        self.remote_prefill_params = remote_prefill_params
 
 @dataclass
 class RPCError:
3426
@@ -116,7 +135,7 @@ class RPCStartupRequest(Enum):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3427
3428
3429
3430
3431
3432
3433
3434
 @dataclass
 class RPCStartupResponse:
     tracing_enabled: bool
-
+    nixl_metadata: Optional[bytes] = None
 
 class RPCUProfileRequest(Enum):
     START_PROFILE = 1
3435
@@ -157,3 +176,13 @@ def ENGINE_DEAD_ERROR(
GuanLuo's avatar
GuanLuo committed
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
     return MQEngineDeadError(
         "Engine loop is not running. Inspect the stacktrace to "
         f"find the original error: {repr(error)}.")
+
+@dataclass
+class KvMetrics:
+    request_active_slots: int
+    request_total_slots: int
+    kv_active_blocks: int
+    kv_total_blocks: int
3446
3447
3448
+    num_requests_waiting: int
+    gpu_cache_usage_perc: float
+    gpu_prefix_cache_hit_rate: float
GuanLuo's avatar
GuanLuo committed
3449
diff --git a/vllm/engine/multiprocessing/client.py b/vllm/engine/multiprocessing/client.py
3450
index 85b5f31e3..c53b9eced 100644
GuanLuo's avatar
GuanLuo committed
3451
3452
--- a/vllm/engine/multiprocessing/client.py
+++ b/vllm/engine/multiprocessing/client.py
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 asyncio
 import copy
@@ -8,6 +21,7 @@ from typing import (Any, AsyncGenerator, Dict, Iterator, List, Mapping,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3472
3473
3474
3475
3476
3477
3478
                     Optional, Union, cast, overload)
 
 import cloudpickle
+import msgspec
 import psutil
 import zmq
 import zmq.asyncio
3479
@@ -19,20 +33,23 @@ from vllm import PoolingParams
3480
3481
3482
3483
3484
3485
3486
 from vllm.config import DecodingConfig, ModelConfig, VllmConfig
 from vllm.core.scheduler import SchedulerOutputs
 from vllm.engine.arg_utils import AsyncEngineArgs
+from vllm.engine.metrics import Stats
 # yapf conflicts with isort for this block
 # yapf: disable
 from vllm.engine.async_llm_engine import (
GuanLuo's avatar
GuanLuo committed
3487
3488
3489
3490
     build_guided_decoding_logits_processor_async)
 from vllm.engine.multiprocessing import (ENGINE_DEAD_ERROR, IPC_DATA_EXT,
                                          IPC_HEALTH_EXT, IPC_INPUT_EXT,
-                                         IPC_OUTPUT_EXT, RPC_REQUEST_T,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3491
3492
-                                         VLLM_RPC_SUCCESS_STR, RPCAbortRequest,
+                                         IPC_OUTPUT_EXT, IPC_REMOTE_PREFILL_REQUEST_EXT,
GuanLuo's avatar
GuanLuo committed
3493
+                                         RPC_REQUEST_T,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3494
3495
+                                         VLLM_RPC_SUCCESS_STR, IPC_REMOTE_NIXL_METADATA_EXT, RPCAbortRequest,
+                                         IPC_METRICS_EXT,
GuanLuo's avatar
GuanLuo committed
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
                                          RPCAdapterLoadedResponse, RPCError,
                                          RPCLoadAdapterRequest,
                                          RPCProcessRequest,
                                          RPCResetPrefixCacheRequest,
                                          RPCStartupRequest, RPCStartupResponse,
-                                         RPCUProfileRequest)
+                                         RPCUProfileRequest, KvMetrics)
 from vllm.engine.protocol import EngineClient
 # yapf: enable
 from vllm.envs import VLLM_RPC_TIMEOUT
3506
@@ -46,6 +63,8 @@ from vllm.prompt_adapter.request import PromptAdapterRequest
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3507
3508
3509
3510
3511
3512
3513
3514
 from vllm.sampling_params import SamplingParams
 from vllm.transformers_utils.tokenizer_group import init_tokenizer_from_configs
 from vllm.utils import deprecate_kwargs
+from vllm.remote_prefill import RemotePrefillParams, RemotePrefillRequest, RemotePrefillRequestCallback
+from vllm.distributed.device_communicators.nixl import NixlMetadata
 
 logger = init_logger(__name__)
 
3515
@@ -91,6 +110,7 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3516
3517
3518
3519
3520
3521
3522
         self._errored_with: Optional[BaseException] = None
 
         # Get the configs.
+        self.vllm_config = engine_config
         self.model_config = engine_config.model_config
         self.decoding_config = engine_config.decoding_config
 
3523
@@ -115,6 +135,10 @@ class MQLLMEngineClient(EngineClient):
GuanLuo's avatar
GuanLuo committed
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
         self.heartbeat_socket: Socket = self.context.socket(zmq.constants.PULL)
         self.heartbeat_socket.connect(f"{ipc_path}{IPC_HEALTH_EXT}")
 
+        # Metrics.
+        self.metrics_socket: Socket = self.context.socket(zmq.constants.PULL)
+        self.metrics_socket.connect(f"{ipc_path}{IPC_METRICS_EXT}")
+
         # IPC path for the data socket.
         self.data_ipc_path = f"{ipc_path}{IPC_DATA_EXT}"
 
3534
@@ -129,8 +153,27 @@ class MQLLMEngineClient(EngineClient):
GuanLuo's avatar
GuanLuo committed
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
         # Loop to check health of the LLMEngine periodically.
         # Started after the MQLLMEngine is ready.
         self.health_loop: Optional[asyncio.Task] = None
+
+        # Loop to check metrics of the LLMEngine periodically.
+        # Started after the MQLLMEngine is ready.
+        self.metrics_loop: Optional[asyncio.Task] = None
+        self.metrics_publisher = None
+
         self._engine_process = psutil.Process(engine_pid)
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
+        self.nixl_metadata: Optional[NixlMetadata] = None
+        self.remote_prefill_request_socket: Socket = self.context.socket(zmq.constants.PULL)
+        self.remote_nixl_metadata_socket: Socket = self.context.socket(zmq.constants.PUSH)
+        self.remote_prefill_requests_callback: Dict[str, RemotePrefillRequestCallback] = {}
+        if self.using_nixl_connector:
+            self.remote_prefill_request_socket.connect(f"{ipc_path}{IPC_REMOTE_PREFILL_REQUEST_EXT}")
+            self.remote_nixl_metadata_socket.connect(f"{ipc_path}{IPC_REMOTE_NIXL_METADATA_EXT}")
+
+    
+    @property
+    def using_nixl_connector(self) -> bool:
Neelay Shah's avatar
Neelay Shah committed
3557
+        return self.vllm_config.kv_transfer_config is not None and self.vllm_config.kv_transfer_config.kv_connector == "DynamoNixlConnector"
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3558
+
GuanLuo's avatar
GuanLuo committed
3559
     @staticmethod
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3560
3561
     def is_unsupported_config(engine_args: AsyncEngineArgs):
         # Pipeline parallel not yet supported
3562
@@ -180,6 +223,61 @@ class MQLLMEngineClient(EngineClient):
GuanLuo's avatar
GuanLuo committed
3563
3564
3565
         except Exception as e:
             self._set_errored(e)
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
+    async def run_remote_prefill_request_handler_loop(self):
+        try:
+            while True:
+                if await self.remote_prefill_request_socket.poll(timeout=VLLM_RPC_TIMEOUT):
+                    frames = await self.remote_prefill_request_socket.recv(copy=False)
+                    remote_prefill_request = msgspec.msgpack.decode(frames.buffer, type=RemotePrefillRequest)
+                    await self.remote_prefill_requests_callback[remote_prefill_request.request_id](remote_prefill_request)
+        except asyncio.CancelledError:
+            logger.debug("Shutting down MQLLMEngineClient remote prefill request handler loop.")
+            
GuanLuo's avatar
GuanLuo committed
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
+    async def run_metrics_loop(self, timeout: int):
+        """Background loop that continually checks to ensure the engine process
+        is still alive.
+        """
+        try:
+            while True:
+                # Check if the engine process is running:
+                if not self._engine_process.is_running() or (
+                        self._engine_process.status() == psutil.STATUS_ZOMBIE):
+                    # NB: is_running() returns True for zombies
+                    self._set_errored(
+                        RuntimeError(
+                            f"Engine process (pid {self._engine_process.pid}) "
+                            "died."))
+                    break
+
+                if await self.metrics_socket.poll(timeout=timeout):
+                    # Metrics received- check the message
+                    message: Frame = await self.metrics_socket.recv(copy=False)
3595
+                    metrics = pickle.loads(message.buffer)
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
+                    if self.metrics_publisher is not None and isinstance(
+                        metrics, KvMetrics
+                    ):
+                        self.metrics_publisher.publish(metrics.request_active_slots,
+                                                    metrics.request_total_slots,
+                                                    metrics.kv_active_blocks,
+                                                    metrics.kv_total_blocks,
+                                                    metrics.num_requests_waiting, 
+                                                    metrics.gpu_cache_usage_perc, 
+                                                    metrics.gpu_prefix_cache_hit_rate)
+                        logger.debug("Metrics successful.")
+
+                    # TODO: Investigate sending whole stats object
GuanLuo's avatar
GuanLuo committed
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
+
+        except asyncio.CancelledError:
+            logger.debug("Shutting down MQLLMEngineClient check metrics loop.")
+
+        except psutil.NoSuchProcess:
+            self._set_errored(
+                RuntimeError(
+                    f"Engine process (pid {self._engine_process.pid}) died."))
+
+        except Exception as e:
+            self._set_errored(e)
+
     async def run_output_handler_loop(self):
         """Get RequestOutputs from Engine and stream to Request Queues"""
 
3624
@@ -278,12 +376,26 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
             # Wait until server is ready.
             response = await self._wait_for_server_rpc(socket)
 
+            if response.nixl_metadata is not None:
+                assert self.using_nixl_connector
+                self.nixl_metadata = msgspec.msgpack.decode(response.nixl_metadata, type=NixlMetadata)
+
             self.tracing_flag = response.tracing_enabled
 
             # Start health_loop.
GuanLuo's avatar
GuanLuo committed
3635
3636
3637
3638
             if self.health_loop is None:
                 self.health_loop = asyncio.create_task(
                     self.run_heartbeat_loop(timeout=VLLM_RPC_TIMEOUT))
+                
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3639
3640
3641
3642
+            if self.using_nixl_connector:
+                self.remote_prefill_loop = asyncio.create_task(
+                    self.run_remote_prefill_request_handler_loop())
+                    
GuanLuo's avatar
GuanLuo committed
3643
3644
3645
3646
3647
3648
3649
3650
+            # Start metrics_loop.
+            if self.metrics_loop is None:
+                self.metrics_loop = asyncio.create_task(
+                    self.run_metrics_loop(timeout=VLLM_RPC_TIMEOUT))
+
 
     def close(self):
         """Destroy the ZeroMQ Context."""
3651
@@ -293,6 +405,8 @@ class MQLLMEngineClient(EngineClient):
GuanLuo's avatar
GuanLuo committed
3652
3653
3654
3655
3656
3657
3658
3659
         # Cancel background tasks.
         if self.health_loop is not None:
             self.health_loop.cancel()
+        if self.metrics_loop is not None:
+            self.metrics_loop.cancel()
         if self.output_loop is not None:
             self.output_loop.cancel()
 
3660
@@ -415,6 +529,9 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3661
3662
3663
3664
3665
3666
3667
3668
3669
         """
         if self._errored_with is not None:
             raise self._errored_with
+        
+    async def add_remote_nixl_metadata(self, nixl_metadata: NixlMetadata):
+        await self.remote_nixl_metadata_socket.send(msgspec.msgpack.encode(nixl_metadata), copy=False)
 
     @property
     def is_running(self) -> bool:
3670
@@ -473,6 +590,7 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3671
3672
3673
3674
3675
3676
3677
         trace_headers: Optional[Mapping[str, str]] = None,
         prompt_adapter_request: Optional[PromptAdapterRequest] = None,
         priority: int = 0,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
         *,
         inputs: Optional[PromptType] = None  # DEPRECATED
     ) -> AsyncGenerator[RequestOutput, None]:
3678
@@ -502,7 +620,8 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3679
3680
3681
3682
3683
3684
3685
3686
3687
 
         return self._process_request(prompt, sampling_params, request_id,
                                      lora_request, trace_headers,
-                                     prompt_adapter_request, priority)
+                                     prompt_adapter_request, priority,
+                                     remote_prefill_params)
 
     @overload
     def encode(
3688
@@ -586,6 +705,7 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3689
3690
3691
3692
3693
3694
3695
         trace_headers: Optional[Mapping[str, str]] = None,
         prompt_adapter_request: Optional[PromptAdapterRequest] = None,
         priority: int = 0,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> Union[AsyncGenerator[RequestOutput, None], AsyncGenerator[
             PoolingRequestOutput, None]]:
         """Send an RPCGenerateRequest to the RPCServer and stream responses."""
3696
@@ -630,6 +750,12 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
             else:
                 lp_bytes = None
 
+            if remote_prefill_params is not None:
+                self.remote_prefill_requests_callback[request_id] = remote_prefill_params.remote_prefill_request_callback
+                remote_prefill_params.remote_prefill_request_callback = None
+            else:
+                remote_prefill_request_callback = None
+
             request_bytes = pickle.dumps(
                 RPCProcessRequest(
                     prompt=prompt,
3709
@@ -639,11 +765,11 @@ class MQLLMEngineClient(EngineClient):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
                     trace_headers=trace_headers,
                     prompt_adapter_request=prompt_adapter_request,
                     priority=priority,
+                    remote_prefill_params=remote_prefill_params,
                 ))
 
             # 3) Send the RPCGenerateRequest to the MQLLMEngine.
-            parts = (request_bytes,
-                     lp_bytes) if lp_bytes else (request_bytes, )
+            parts = (request_bytes, lp_bytes) if lp_bytes else (request_bytes,)
             await self.input_socket.send_multipart(parts, copy=False)
 
             # 4) Stream the RequestOutputs from the output queue. Note
3723
@@ -705,3 +831,6 @@ class MQLLMEngineClient(EngineClient):
GuanLuo's avatar
GuanLuo committed
3724
3725
3726
3727
3728
3729
3730
         # Raise on error, otherwise happily return None
         if isinstance(request_output, BaseException):
             raise request_output
+
+    def set_metrics_publisher(self, metrics_publisher):
+        self.metrics_publisher = metrics_publisher
diff --git a/vllm/engine/multiprocessing/engine.py b/vllm/engine/multiprocessing/engine.py
3731
index a0dd79586..ea0d2cd68 100644
GuanLuo's avatar
GuanLuo committed
3732
3733
--- a/vllm/engine/multiprocessing/engine.py
+++ b/vllm/engine/multiprocessing/engine.py
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
@@ -1,37 +1,130 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
 import pickle
 import signal
 from contextlib import contextmanager
-from typing import Iterator, List, Optional, Union
+from typing import Iterator, List, Optional, Union, Dict
 
 import cloudpickle
+import time
 import zmq
-
+import msgspec
 from vllm import AsyncEngineArgs, SamplingParams
 from vllm.engine.llm_engine import LLMEngine
 # yapf conflicts with isort for this block
GuanLuo's avatar
GuanLuo committed
3764
3765
3766
3767
 # yapf: disable
 from vllm.engine.multiprocessing import (ENGINE_DEAD_ERROR, IPC_DATA_EXT,
                                          IPC_HEALTH_EXT, IPC_INPUT_EXT,
-                                         IPC_OUTPUT_EXT, REQUEST_OUTPUTS_T,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3768
-                                         VLLM_RPC_SUCCESS_STR, RPCAbortRequest,
GuanLuo's avatar
GuanLuo committed
3769
+                                         REQUEST_OUTPUTS_T,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3770
3771
3772
+                                         VLLM_RPC_SUCCESS_STR, IPC_REMOTE_PREFILL_REQUEST_EXT,
+                                         RPCAbortRequest,
+                                         IPC_OUTPUT_EXT, IPC_METRICS_EXT,
GuanLuo's avatar
GuanLuo committed
3773
3774
3775
3776
3777
3778
                                          RPCAdapterLoadedResponse, RPCError,
                                          RPCLoadAdapterRequest,
                                          RPCProcessRequest,
                                          RPCResetPrefixCacheRequest,
                                          RPCStartupRequest, RPCStartupResponse,
-                                         RPCUProfileRequest)
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3779
3780
+                                         RPCUProfileRequest, IPC_REMOTE_NIXL_METADATA_EXT,
+                                         KvMetrics)
GuanLuo's avatar
GuanLuo committed
3781
3782
3783
3784
 # yapf: enable
 from vllm.logger import init_logger
 from vllm.outputs import RequestOutput
 from vllm.usage.usage_lib import UsageContext
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3785
3786
3787
+from vllm.remote_prefill import RemotePrefillRequest
+from vllm.distributed.device_communicators.nixl import NixlMetadata
+
GuanLuo's avatar
GuanLuo committed
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
+from vllm.engine.metrics_types import StatLoggerBase, Stats, SupportsMetricsInfo
+from dataclasses import dataclass, field
 
 logger = init_logger(__name__)
 
 POLLING_TIMEOUT_MS = 10000
 HEALTHY_RESPONSE = (pickle.dumps(VLLM_RPC_SUCCESS_STR), )
 
+class KvStatLogger(StatLoggerBase):
+    def __init__(
+        self,
+        max_num_seqs: int,
+        num_total_gpu_blocks: int,
+        metrics_socket
+    ):
+        # Must query initialized scheduler for max infos
+        self.request_total_slots = max_num_seqs
+        self.kv_total_blocks = num_total_gpu_blocks
+        self.metrics_socket = metrics_socket
+
+        # KV metrics
3809
+        self._send_kv_metrics(0, 0, 0, 0.0, 0.0)
GuanLuo's avatar
GuanLuo committed
3810
3811
3812
3813
+
+    def log(self, stats: Stats) -> None:
+        self._send_kv_metrics(
+            stats.num_running_sys,
3814
3815
3816
3817
+            int(stats.gpu_cache_usage_sys * self.kv_total_blocks),
+            stats.num_waiting_sys,
+            stats.gpu_cache_usage_sys,
+            stats.gpu_prefix_cache_hit_rate
GuanLuo's avatar
GuanLuo committed
3818
3819
3820
3821
3822
+        )
+
+    def info(self, type: str, obj: SupportsMetricsInfo) -> None:
+        pass
+
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
+    def _send_kv_metrics(
+        self,
+        active_slots,
+        active_kv_blocks,
+        num_requests_waiting,
+        gpu_cache_usage_perc,
+        gpu_prefix_cache_hit_rate,
+    ):
+        if not self.metrics_socket.closed:
+            metrics_bytes = pickle.dumps(
+                KvMetrics(
+                    active_slots,
+                    self.request_total_slots,
+                    active_kv_blocks,
+                    self.kv_total_blocks,
+                    num_requests_waiting,
+                    gpu_cache_usage_perc,
+                    gpu_prefix_cache_hit_rate,
+                )
+            )
+            self.metrics_socket.send_multipart((metrics_bytes, ), copy=False)
+
+# TODO: Send entire stats object to the client
3846
3847
3848
3849
3850
3851
+# class StatLogger(StatLoggerBase):
+#     def __init__(
+#         self,
+#         metrics_socket
+#     ):
+#         self.metrics_socket = metrics_socket
3852
+
3853
3854
+#     def log(self, stats: Stats) -> None:
+#         self._send_metrics(stats)
3855
+
3856
3857
+#     def info(self, type: str, obj: SupportsMetricsInfo) -> None:
+#         pass
3858
+
3859
3860
3861
3862
+#     def _send_metrics(self, stats: Stats):
+#         if not self.metrics_socket.closed:
+#             metrics_bytes = pickle.dumps(stats)
+#             self.metrics_socket.send_multipart((metrics_bytes, ), copy=False)
3863
3864
3865
+
+
+
GuanLuo's avatar
GuanLuo committed
3866
3867
3868
3869
+
 
 class MQLLMEngine:
     """A multiprocessing wrapper for :class:`LLMEngine`.
3870
@@ -94,12 +187,37 @@ class MQLLMEngine:
GuanLuo's avatar
GuanLuo committed
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
         self.heartbeat_socket = self.ctx.socket(zmq.constants.PUSH)
         self.heartbeat_socket.bind(f"{ipc_path}{IPC_HEALTH_EXT}")
 
+        # Send metrics back to client.
+        self.metrics_socket = self.ctx.socket(zmq.constants.PUSH)
+        self.metrics_socket.bind(f"{ipc_path}{IPC_METRICS_EXT}")
+
         # IPC path for the data socket.
         self.data_ipc_path = f"{ipc_path}{IPC_DATA_EXT}"
 
         # Error state.
         self._errored_with: Optional[BaseException] = None
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3884
3885
3886
3887
3888
3889
3890
+        self.remote_prefill_request_socket = self.ctx.socket(zmq.constants.PUSH)
+        self.remote_nixl_metadata_socket = self.ctx.socket(zmq.constants.PULL)
+        if self.engine.is_nixl_initialized:
+            self.remote_prefill_request_socket.bind(f"{ipc_path}{IPC_REMOTE_PREFILL_REQUEST_EXT}")
+            self.remote_nixl_metadata_socket.bind(f"{ipc_path}{IPC_REMOTE_NIXL_METADATA_EXT}")
+
+
GuanLuo's avatar
GuanLuo committed
3891
+        # Attach logger for continuous metrics publishing
3892
+        self.kv_stat_logger = KvStatLogger(
GuanLuo's avatar
GuanLuo committed
3893
3894
3895
3896
+            self.engine.scheduler_config.max_num_seqs,
+            self.engine.cache_config.num_gpu_blocks,
+            self.metrics_socket
+        )
3897
+        self.engine.add_logger("kv_metrics", self.kv_stat_logger)
3898
3899
3900
3901
3902
3903
+        
+        # TODO investigate sending whole stats object
+        # self.general_stat_logger = StatLogger(
+        #     self.metrics_socket
+        # )
+        # self.engine.add_logger("general_metrics", self.general_stat_logger)
GuanLuo's avatar
GuanLuo committed
3904
3905
3906
3907
+
     @property
     def dead_error(self) -> BaseException:
         if self._errored_with is not None:
3908
@@ -171,8 +289,17 @@ class MQLLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
                 # Handle the query from the Client.
                 if request == RPCStartupRequest.IS_SERVER_READY:
                     tracing_enabled = self.engine.is_tracing_enabled()
-                    response = RPCStartupResponse(
-                        tracing_enabled=tracing_enabled)
+            
+                    # Send nixl metadata to the client
+                    if self.engine.is_nixl_initialized:
+                        nixl_metadata = self.engine.get_nixl_metadata()
+                        encoded_nixl_metadata = msgspec.msgpack.encode(nixl_metadata)
+                        response = RPCStartupResponse(
+                            tracing_enabled=tracing_enabled,
+                            nixl_metadata=encoded_nixl_metadata)
+                    else:
+                        response = RPCStartupResponse(
+                            tracing_enabled=tracing_enabled)
 
             except Exception as e:
                 response = e
3928
@@ -185,6 +312,7 @@ class MQLLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3929
3930
3931
3932
3933
3934
3935
 
         while True:
             if not self.engine.has_unfinished_requests():
+                logger.debug("No unfinished requests")
                 # Poll until there is work to do.
                 while self.input_socket.poll(timeout=POLLING_TIMEOUT_MS) == 0:
                     # When there's no work, check on engine health and send
3936
@@ -220,6 +348,13 @@ class MQLLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
     def handle_new_input(self):
         """Handle new input from the socket"""
         try:
+            if self.engine.is_nixl_initialized:
+                while self.remote_nixl_metadata_socket.poll(timeout=0) != 0:
+                    frames = self.remote_nixl_metadata_socket.recv(copy=False)
+                    nixl_metadata = msgspec.msgpack.decode(frames.buffer, type=NixlMetadata)
+                    logger.debug("Adding remote nixl metadata for engine: %s", nixl_metadata.engine_id)
+                    self.engine.add_remote_nixl_metadata(nixl_metadata)
+
             while self.input_socket.poll(timeout=0) != 0:
                 frames = self.input_socket.recv_multipart(copy=False)
                 request = pickle.loads(frames[0].buffer)
3950
@@ -262,6 +397,11 @@ class MQLLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
             self._send_outputs(rpc_err)
 
         try:
+            if request.remote_prefill_params is not None and request.remote_prefill_params.is_remote_prefill:
+                def remote_prefill_request_callback(request: RemotePrefillRequest):
+                    logger.debug("Sending remote prefill request: %s", request.request_id)
+                    self.remote_prefill_request_socket.send(msgspec.msgpack.encode(request), copy=False)
+                request.remote_prefill_params.remote_prefill_request_callback = remote_prefill_request_callback
             self.engine.add_request(
                 request_id=request_id,
                 prompt=request.prompt,
3962
@@ -269,7 +409,9 @@ class MQLLMEngine:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
                 lora_request=request.lora_request,
                 trace_headers=request.trace_headers,
                 prompt_adapter_request=request.prompt_adapter_request,
-                priority=request.priority)
+                priority=request.priority,
+                remote_prefill_params=request.remote_prefill_params,
+            )
 
             if self.log_requests:
                 logger.info("Added request %s.", request.request_id)
diff --git a/vllm/entrypoints/openai/serving_chat.py b/vllm/entrypoints/openai/serving_chat.py
3974
index 107220d54..e0e0590b6 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3975
3976
--- a/vllm/entrypoints/openai/serving_chat.py
+++ b/vllm/entrypoints/openai/serving_chat.py
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 asyncio
 import json
@@ -34,6 +47,7 @@ from vllm.sampling_params import BeamSearchParams, SamplingParams
ptarasiewiczNV's avatar
ptarasiewiczNV committed
3996
3997
3998
3999
4000
4001
4002
 from vllm.sequence import Logprob
 from vllm.transformers_utils.tokenizer import AnyTokenizer, MistralTokenizer
 from vllm.transformers_utils.tokenizers import maybe_serialize_tool_calls
+from vllm.remote_prefill import RemotePrefillParams
 
 logger = init_logger(__name__)
 
4003
@@ -112,6 +126,7 @@ class OpenAIServingChat(OpenAIServing):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4004
4005
4006
4007
4008
4009
4010
         self,
         request: ChatCompletionRequest,
         raw_request: Optional[Request] = None,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> Union[AsyncGenerator[str, None], ChatCompletionResponse,
                ErrorResponse]:
         """
4011
@@ -243,6 +258,7 @@ class OpenAIServingChat(OpenAIServing):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4012
4013
4014
4015
4016
4017
4018
                         trace_headers=trace_headers,
                         prompt_adapter_request=prompt_adapter_request,
                         priority=request.priority,
+                        remote_prefill_params=remote_prefill_params,
                     )
 
                 generators.append(generator)
4019
diff --git a/vllm/envs.py b/vllm/envs.py
4020
index 745b068b7..0f1a022fb 100644
4021
4022
--- a/vllm/envs.py
+++ b/vllm/envs.py
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 tempfile
@@ -87,6 +100,10 @@ if TYPE_CHECKING:
4042
4043
4044
4045
     VLLM_ENABLE_MOE_ALIGN_BLOCK_SIZE_TRITON: bool = False
     VLLM_RAY_PER_WORKER_GPUS: float = 1.0
     VLLM_RAY_BUNDLE_INDICES: str = ""
+    VLLM_KV_CAPI_PATH: Optional[str] = None
GuanLuo's avatar
GuanLuo committed
4046
4047
4048
+    VLLM_KV_NAMESPACE: Optional[str] = None
+    VLLM_KV_COMPONENT: Optional[str] = None
+    VLLM_WORKER_ID: Optional[int] = None
4049
4050
4051
 
 
 def get_default_cache_root():
4052
@@ -572,6 +589,21 @@ environment_variables: Dict[str, Callable[[], Any]] = {
4053
4054
4055
4056
4057
4058
4059
4060
     # models the alignment is already naturally aligned to 256 bytes.
     "VLLM_CUDA_MEM_ALIGN_KV_CACHE":
     lambda: bool(int(os.getenv("VLLM_CUDA_MEM_ALIGN_KV_CACHE", "1"))),
+
+    # Path to the C API Library
+    "VLLM_KV_CAPI_PATH":
+    lambda: os.environ.get("VLLM_KV_CAPI_PATH", None),
+
GuanLuo's avatar
GuanLuo committed
4061
4062
4063
4064
4065
4066
+    # Identifiers to publish KV related information
+    "VLLM_KV_NAMESPACE":
+    lambda: os.environ.get("VLLM_KV_NAMESPACE", None),
+    "VLLM_KV_COMPONENT":
+    lambda: os.environ.get("VLLM_KV_COMPONENT", None),
+
4067
4068
+    # Worker ID used for identifying workers in distributed settings
+    "VLLM_WORKER_ID":
GuanLuo's avatar
GuanLuo committed
4069
4070
+    lambda: int(os.getenv("VLLM_WORKER_ID", "0"))
+    if "VLLM_WORKER_ID" in os.environ else None,
4071
4072
4073
 }
 
 # end-env-vars-definition
4074
diff --git a/vllm/model_executor/models/deepseek_v2.py b/vllm/model_executor/models/deepseek_v2.py
4075
index 773f5abe7..365685e13 100644
4076
4077
--- a/vllm/model_executor/models/deepseek_v2.py
+++ b/vllm/model_executor/models/deepseek_v2.py
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
 
 # Adapted from
 # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
@@ -585,6 +598,8 @@ class DeepseekV2Model(nn.Module):
4097
4098
4099
4100
4101
4102
4103
4104
         cache_config = vllm_config.cache_config
         quant_config = vllm_config.quant_config
 
+        self.config = config
+
         self.padding_idx = config.pad_token_id
         self.vocab_size = config.vocab_size
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4105
diff --git a/vllm/outputs.py b/vllm/outputs.py
4106
index 786380c37..e9c3a5e16 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4107
4108
--- a/vllm/outputs.py
+++ b/vllm/outputs.py
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 time
 from dataclasses import dataclass
@@ -6,16 +19,16 @@ from typing import Dict, Generic, List, MutableSequence, Optional
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
 from typing import Sequence as GenericSequence
 from typing import Union
 
+import msgspec
 import torch
 from typing_extensions import TypeVar, deprecated
 
 from vllm.lora.request import LoRARequest
 from vllm.multimodal.inputs import MultiModalPlaceholderDict
-from vllm.sampling_params import RequestOutputKind
+from vllm.sampling_params import RequestOutputKind, SamplingParams
 from vllm.sequence import (PromptLogprobs, RequestMetrics, SampleLogprobs,
                            SequenceGroup, SequenceGroupBase, SequenceStatus)
 
-
 @dataclass
 class CompletionOutput:
     """The output data of one completion output of a request.
diff --git a/vllm/remote_prefill.py b/vllm/remote_prefill.py
new file mode 100644
4148
index 000000000..83f6cd575
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4149
4150
--- /dev/null
+++ b/vllm/remote_prefill.py
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
@@ -0,0 +1,82 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4167
+from dataclasses import dataclass
4168
4169
+from typing import Callable, Optional, List
+from enum import Enum
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
+
+import msgspec
+
+from vllm.sampling_params import SamplingParams
+
+
+class RemotePrefillRequest(
+        msgspec.Struct,
+        omit_defaults=True,  # type: ignore[call-arg]
+        # required for @cached_property.
+        dict=True):
+    """The request data of one remote prefill output of a request.
+
+    Args:
4184
+        engine_id: The unique ID of the engine.
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4185
+        request_id: The unique ID of the request.
4186
4187
4188
4189
+        prompt_token_ids: The token IDs of the prompt.
+        sampling_params: The sampling parameters.
+        block_ids: The block IDs of the request.
+        computed_block_ids: The computed block IDs of the request.
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4190
+    """
4191
+    engine_id: str
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4192
4193
4194
4195
+    request_id: str
+    prompt_token_ids: List[int]
+    sampling_params: SamplingParams
+    block_ids: List[int]
4196
4197
4198
4199
4200
4201
+    computed_block_ids: List[int]
+
+
+class MemoryOpType(str, Enum):
+    WRITE = "WRITE"
+    READ = "READ"
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
+
+
+class MemoryTransferRequest(
+        msgspec.Struct,
+        array_like=True,  # type: ignore[call-arg]
+        omit_defaults=True):  # type: ignore[call-arg]
+    """The request data of one memory transfer output of a request.
+
+    Args:
+        request_id: The unique ID of the request.
+    """
+    request_id: str
4214
+    local_block_ids: List[int]
Neelay Shah's avatar
Neelay Shah committed
4215
+    staging_block_ids: List[int]
4216
4217
+    remote_block_ids: List[int]
+    remote_engine_id: str
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4218
+    notify_msg: str
4219
+    op_type: MemoryOpType
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
+
+
+RemotePrefillRequestCallback = Callable[[RemotePrefillRequest], None]
+
+
+@dataclass
+class RemotePrefillParams:
+    """Remote prefill parameters for text generation."""
+    is_remote_prefill: bool = False
+    is_remote_decode: bool = False
+    decode_block_ids: Optional[List[int]] = None
4231
+    decode_computed_block_ids: Optional[List[int]] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4232
4233
4234
4235
+    decode_engine_id: Optional[str] = None
+    remote_prefill_request_callback: Optional[RemotePrefillRequestCallback] = None
\ No newline at end of file
diff --git a/vllm/sampling_params.py b/vllm/sampling_params.py
4236
index 97f9e2129..5849befba 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4237
4238
--- a/vllm/sampling_params.py
+++ b/vllm/sampling_params.py
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
@@ -1,4 +1,18 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
 """Sampling parameters for text generation."""
 import copy
 from dataclasses import dataclass
@@ -83,7 +97,7 @@ class RequestOutputKind(Enum):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4259
4260
4261
4262
4263
4264
4265
4266
4267
     DELTA = 1
     # Do not return intermediate RequestOuputs
     FINAL_ONLY = 2
-
+    
 
 class SamplingParams(
         msgspec.Struct,
diff --git a/vllm/sequence.py b/vllm/sequence.py
4268
index 534b9e606..c33bbde1c 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4269
4270
--- a/vllm/sequence.py
+++ b/vllm/sequence.py
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
@@ -1,4 +1,18 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
 """Sequence and its related classes."""
 import copy
 import enum
@@ -20,6 +34,7 @@ from vllm.multimodal import MultiModalDataDict, MultiModalPlaceholderDict
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4291
4292
4293
4294
4295
4296
4297
 from vllm.pooling_params import PoolingParams
 from vllm.prompt_adapter.request import PromptAdapterRequest
 from vllm.sampling_params import RequestOutputKind, SamplingParams
+from vllm.remote_prefill import RemotePrefillParams, MemoryTransferRequest
 
 VLLM_TOKEN_ID_ARRAY_TYPE = "l"
 
4298
@@ -59,13 +74,14 @@ class SequenceStatus(enum.IntEnum):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
     """Status of a sequence."""
     WAITING = 0
     RUNNING = 1
-    SWAPPED = 2
-    # Note: anything after SWAPPED (2) will be considered
+    REMOTE_PREFILLING = 2
+    SWAPPED = 3
+    # Note: anything after SWAPPED (3) will be considered
     # as a finished status.
-    FINISHED_STOPPED = 3
-    FINISHED_LENGTH_CAPPED = 4
-    FINISHED_ABORTED = 5
-    FINISHED_IGNORED = 6
+    FINISHED_STOPPED = 4
+    FINISHED_LENGTH_CAPPED = 5
+    FINISHED_ABORTED = 6
+    FINISHED_IGNORED = 7
 
     @staticmethod
     def is_finished(status: "SequenceStatus") -> bool:
4319
@@ -409,6 +425,7 @@ class Sequence:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4320
4321
4322
4323
4324
4325
4326
         eos_token_id: Optional[int] = None,
         lora_request: Optional[LoRARequest] = None,
         prompt_adapter_request: Optional[PromptAdapterRequest] = None,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> None:
         self.seq_id = seq_id
         self.inputs = SingletonInputsAdapter(inputs)
4327
@@ -416,7 +433,7 @@ class Sequence:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4328
4329
4330
4331
4332
4333
4334
4335
         self.eos_token_id = eos_token_id
         self.lora_request = lora_request
         self.prompt_adapter_request = prompt_adapter_request
-
+        self.remote_prefill_params = remote_prefill_params
         self.data = SequenceData.from_seqs(self.prompt_token_ids)
         self.output_logprobs: SampleLogprobs = []
         self.output_text = ""
4336
@@ -639,6 +656,7 @@ class SequenceGroup:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4337
4338
4339
4340
4341
4342
4343
         trace_headers: OpenTelemetry trace headers.
         prompt_adapter_request: Prompt Adapter request.
         priority: User-defined priority of the request.
+        remote_prefill_params: Remote prefill parameters.
     """
 
     def __init__(
4344
@@ -654,6 +672,7 @@ class SequenceGroup:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4345
4346
4347
4348
4349
4350
4351
         trace_headers: Optional[Mapping[str, str]] = None,
         prompt_adapter_request: Optional[PromptAdapterRequest] = None,
         priority: int = 0,
+        remote_prefill_params: Optional[RemotePrefillParams] = None,
     ) -> None:
         self.request_id = request_id
         self.seqs = seqs
4352
@@ -678,7 +697,7 @@ class SequenceGroup:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4353
4354
4355
4356
4357
4358
4359
4360
         self.encoder_seq = encoder_seq
         self.trace_headers = trace_headers
         self.priority = priority
-
+        self.remote_prefill_params = remote_prefill_params
         self.cached_request_output = None
 
     @property
4361
@@ -927,6 +946,9 @@ class SequenceGroupMetadata(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4362
4363
4364
4365
4366
4367
4368
4369
4370
             query tokens for prefill, we don't need sampling.
         token_chunk_size: The number of tokens to be processed (per sequence).
             None if chunking is not required.
+        do_remote_prefill: True if remote prefill is required.
+        do_remote_decode: True if remote decode is required.
+        decode_memory_desc: The memory descriptor for the decoder blocks.
         lora_request: LoRA request.
         computed_block_nums: The block numbers that are already computed,
             used in prefix caching.
4371
@@ -966,6 +988,9 @@ class SequenceGroupMetadata(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4372
4373
4374
4375
4376
4377
4378
4379
4380
     cross_block_table: Optional[List[int]] = None
     prompt_adapter_request: Optional[PromptAdapterRequest] = None
     token_chunk_size: Optional[int] = None
+    do_remote_prefill: bool = False
+    do_remote_decode: bool = False
+    decode_memory_desc: Optional[bytes] = None
 
     ### Stateful fields that are lazily defined. ###
     # The number of speculative tokens adopted in this request.
4381
@@ -1310,6 +1335,8 @@ class ExecuteModelRequest(
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4382
4383
4384
4385
4386
4387
4388
4389
4390
     last_sampled_token_ids: Optional[torch.Tensor] = None
     # Async callback
     async_callback: Optional[Callable] = None
+    # The memory transfer requests.
+    memory_transfer_requests: Optional[List[MemoryTransferRequest]] = None
 
     @property
     def is_first_multi_step(self) -> bool:
diff --git a/vllm/worker/model_runner.py b/vllm/worker/model_runner.py
4391
index 12baecde6..11034b391 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4392
4393
--- a/vllm/worker/model_runner.py
+++ b/vllm/worker/model_runner.py
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
@@ -1,4 +1,17 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 dataclasses
 import gc
@@ -1824,6 +1837,9 @@ class ModelRunner(GPUModelRunnerBase[ModelInputForGPUWithSamplingMetadata]):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4413
4414
4415
4416
 
         if self.vllm_config.kv_transfer_config is None:
             return False
+        
Neelay Shah's avatar
Neelay Shah committed
4417
+        if self.vllm_config.kv_transfer_config.kv_connector == "DynamoNixlConnector":
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4418
4419
4420
4421
+            return False
 
         prefill_meta = model_input.attn_metadata.prefill_metadata
 
4422
@@ -1849,6 +1865,9 @@ class ModelRunner(GPUModelRunnerBase[ModelInputForGPUWithSamplingMetadata]):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4423
4424
4425
4426
 
         if self.vllm_config.kv_transfer_config is None:
             return False
+        
Neelay Shah's avatar
Neelay Shah committed
4427
+        if self.vllm_config.kv_transfer_config.kv_connector == "DynamoNixlConnector":
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4428
4429
4430
4431
4432
+            return False
 
         prefill_meta = model_input.attn_metadata.prefill_metadata
 
diff --git a/vllm/worker/worker.py b/vllm/worker/worker.py
4433
index 582aa460e..0be784a40 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4434
4435
--- a/vllm/worker/worker.py
+++ b/vllm/worker/worker.py
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
@@ -1,8 +1,22 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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.
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4452
4453
4454
4455
4456
4457
4458
4459
 """A GPU worker class."""
 import gc
 import os
-from typing import Dict, List, Optional, Set, Tuple, Type, Union
+from typing import Dict, List, Optional, Set, Tuple, Type, Union, TYPE_CHECKING, Any
 
 import torch
 import torch.distributed
4460
@@ -31,6 +45,9 @@ from vllm.worker.model_runner import GPUModelRunnerBase, ModelRunner
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4461
4462
4463
 from vllm.worker.pooling_model_runner import PoolingModelRunner
 from vllm.worker.worker_base import (LocalOrDistributedWorkerBase, WorkerBase,
                                      WorkerInput)
Neelay Shah's avatar
Neelay Shah committed
4464
+from vllm.distributed.device_communicators.nixl import DynamoNixlConnector
4465
+from vllm.remote_prefill import MemoryOpType
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4466
4467
4468
4469
+
 
 logger = init_logger(__name__)
 
4470
@@ -306,6 +323,46 @@ class Worker(LocalOrDistributedWorkerBase):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4471
4472
4473
4474
4475
4476
4477
4478
             self._init_cache_engine()
         self._warm_up_model()
 
+    def initialize_nixl(self, engine_id: str) -> List[bytes]:
+
+        # TODO ptarasiewicz nixl can also support DRAM
+        assert self.device_config.device_type == "cuda", "Currently only CUDA is supported for Nixl connector"
+
Neelay Shah's avatar
Neelay Shah committed
4479
+        self.nixl_connector = DynamoNixlConnector(self.vllm_config, engine_id, self.local_rank) # TODO ptarasiewicz: rank or local_rank?
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4480
4481
4482
4483
4484
4485
4486
4487
+        assert len(self.cache_engine) == 1, "Only one cache engine is supported for now"
+        self.nixl_connector.register_kv_caches(self.cache_engine[0].gpu_cache)
+        return self.nixl_connector.agent_name
+    
+    def get_nixl_agent_metadata(self) -> bytes:
+        assert self.nixl_connector is not None, "Nixl connector is not initialized"
+        return self.nixl_connector.get_agent_metadata()
+
4488
+    def add_remote_nixl_metadata(self, engine_id: str, agents_metadata: List[bytes], kv_caches_base_addr: List[List[Tuple[int, int]]], num_blocks: int) -> str:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4489
+        assert self.nixl_connector is not None, "Nixl connector is not initialized"
4490
+        agent_name = self.nixl_connector.add_remote_agent(engine_id, agents_metadata, len(agents_metadata), kv_caches_base_addr, num_blocks) # TODO ptarasiewicz: rank or local_rank?
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4491
4492
4493
4494
4495
4496
+        return agent_name
+    
+    def get_nixl_kv_caches_base_addr(self) -> List[bytes]:
+        assert self.nixl_connector is not None, "Nixl connector is not initialized"
+        return self.nixl_connector.kv_caches_base_addr[self.nixl_connector.engine_id]
+        
4497
4498
4499
4500
4501
4502
+    def _read_blocks(self, worker_input: WorkerInput) -> None:
+        for i, op_type in enumerate(worker_input.op_type):
+            if op_type == MemoryOpType.READ:
+                self.nixl_connector.read_blocks(worker_input.local_block_ids[i], worker_input.staging_block_ids[i], worker_input.remote_block_ids[i], worker_input.remote_engine_id[i])
+
+    def _write_blocks(self, worker_input: WorkerInput) -> None:
4503
4504
4505
+        if not self.is_driver_worker:
+            torch.cuda.synchronize() # to make sure that the blocks are ready, on driver worker we transfer after sampling, so there's no need to synchronize
+
4506
4507
4508
+        for i, op_type in enumerate(worker_input.op_type):
+            if op_type == MemoryOpType.WRITE:
+                self.nixl_connector.write_blocks(worker_input.local_block_ids[i], worker_input.staging_block_ids[i], worker_input.remote_block_ids[i], worker_input.remote_engine_id[i], worker_input.notify_msg[i])
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4509
4510
4511
4512
4513
4514
4515
4516
+
+    def shutdown_nixl(self) -> None:
+        assert self.nixl_connector is not None, "Nixl connector is not initialized"
+        self.nixl_connector.shutdown()
+
     def _init_cache_engine(self):
         assert self.cache_config.num_gpu_blocks is not None
         self.cache_engine = [
4517
@@ -367,6 +424,8 @@ class Worker(LocalOrDistributedWorkerBase):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4518
4519
4520
4521
4522
4523
4524
4525
         blocks_to_copy = torch.tensor(execute_model_req.blocks_to_copy,
                                       device=self.device,
                                       dtype=torch.int64).view(-1, 2)
+        
+        mem_transfer_reqs = execute_model_req.memory_transfer_requests or []
 
         return WorkerInput(
             num_seq_groups=num_seq_groups,
4526
@@ -375,6 +434,12 @@ class Worker(LocalOrDistributedWorkerBase):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4527
4528
4529
             blocks_to_copy=blocks_to_copy,
             virtual_engine=virtual_engine,
             num_steps=num_steps,
4530
+            local_block_ids=[r.local_block_ids for r in mem_transfer_reqs],
Neelay Shah's avatar
Neelay Shah committed
4531
+            staging_block_ids=[r.staging_block_ids for r in mem_transfer_reqs],
4532
4533
+            remote_block_ids=[r.remote_block_ids for r in mem_transfer_reqs],
+            remote_engine_id=[r.remote_engine_id for r in mem_transfer_reqs],
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4534
+            notify_msg=[r.notify_msg for r in mem_transfer_reqs],
4535
+            op_type=[r.op_type for r in mem_transfer_reqs],
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4536
4537
4538
4539
         )
 
     @torch.inference_mode()
diff --git a/vllm/worker/worker_base.py b/vllm/worker/worker_base.py
4540
index 819b81fbf..7d1b1836d 100644
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4541
4542
--- a/vllm/worker/worker_base.py
+++ b/vllm/worker/worker_base.py
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
@@ -1,4 +1,18 @@
+# SPDX-FileCopyrightText: Copyright (c) 2025 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 dataclasses
 import os
@@ -9,6 +23,7 @@ from typing import Any, Dict, List, Optional, Set, Tuple, Type, Union
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4563
4564
4565
4566
4567
4568
4569
 import cloudpickle
 import torch
 import torch.nn as nn
+from collections import defaultdict
 
 from vllm.config import (ObservabilityConfig, VllmConfig,
                          set_current_vllm_config)
4570
@@ -23,6 +38,9 @@ from vllm.utils import (enable_trace_function_call_for_thread,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4571
4572
4573
 from vllm.worker.model_runner_base import (BroadcastableModelInput,
                                            ModelRunnerBase,
                                            ModelRunnerInputBase)
Neelay Shah's avatar
Neelay Shah committed
4574
+from vllm.distributed.device_communicators.nixl import DynamoNixlConnector
4575
4576
+from vllm.remote_prefill import MemoryOpType
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4577
4578
4579
 
 logger = init_logger(__name__)
 
4580
@@ -53,6 +71,8 @@ class WorkerBase(ABC):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4581
4582
4583
         from vllm.platforms import current_platform
         self.current_platform = current_platform
 
Neelay Shah's avatar
Neelay Shah committed
4584
+        self.nixl_connector: Optional[DynamoNixlConnector] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4585
4586
4587
4588
+
     @abstractmethod
     def init_device(self) -> None:
         """Initialize device state, such as loading the model or other on-device
4589
@@ -216,6 +236,13 @@ class WorkerInput:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4590
4591
4592
     virtual_engine: int = 0
     num_steps: int = 1
 
4593
+    local_block_ids: Optional[List[List[int]]] = None
Neelay Shah's avatar
Neelay Shah committed
4594
+    staging_block_ids: Optional[List[List[int]]] = None
4595
4596
+    remote_block_ids: Optional[List[List[int]]] = None
+    remote_engine_id: Optional[List[str]] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4597
+    notify_msg: Optional[List[str]] = None
4598
+    op_type: Optional[List[MemoryOpType]] = None
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4599
4600
4601
4602
+
     @classmethod
     def from_broadcasted_tensor_dict(
         cls: Type["WorkerInput"],
4603
@@ -232,6 +259,12 @@ class WorkerInput:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4604
4605
4606
             blocks_to_copy=tensor_dict.pop("blocks_to_copy"),
             virtual_engine=tensor_dict["virtual_engine"],
             num_steps=tensor_dict.pop("num_steps"),
4607
+            local_block_ids=tensor_dict.pop("local_block_ids"),
Neelay Shah's avatar
Neelay Shah committed
4608
+            staging_block_ids=tensor_dict.pop("staging_block_ids"),
4609
4610
+            remote_block_ids=tensor_dict.pop("remote_block_ids"),
+            remote_engine_id=tensor_dict.pop("remote_engine_id"),
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4611
+            notify_msg=tensor_dict.pop("notify_msg"),
4612
+            op_type=tensor_dict.pop("op_type"),
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4613
4614
4615
         )
 
     def as_broadcastable_tensor_dict(
4616
@@ -246,6 +279,12 @@ class WorkerInput:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4617
4618
4619
             "blocks_to_copy": self.blocks_to_copy,
             "virtual_engine": self.virtual_engine,
             "num_steps": self.num_steps,
4620
+            "local_block_ids": self.local_block_ids,
Neelay Shah's avatar
Neelay Shah committed
4621
+            "staging_block_ids": self.staging_block_ids,
4622
4623
+            "remote_block_ids": self.remote_block_ids,
+            "remote_engine_id": self.remote_engine_id,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4624
+            "notify_msg": self.notify_msg,
4625
+            "op_type": self.op_type,
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4626
4627
4628
         }
 
         return tensor_dict
4629
@@ -316,13 +355,16 @@ class LocalOrDistributedWorkerBase(WorkerBase):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
             return None
 
         worker_input = WorkerInput.from_broadcasted_tensor_dict(broadcast_data)
-        model_input = (
-            self.model_runner.make_model_input_from_broadcasted_tensor_dict(
-                broadcast_data))
+        if worker_input.num_seq_groups > 0:
+            model_input = (
+                self.model_runner.make_model_input_from_broadcasted_tensor_dict(
+                    broadcast_data))
 
-        kwargs = extract_previous_hidden_states(broadcast_data)
+            kwargs = extract_previous_hidden_states(broadcast_data)
 
-        return model_input, worker_input, kwargs
+            return model_input, worker_input, kwargs
+        else:
+            return None, worker_input, {}
 
     def _get_driver_input_and_broadcast(
         self, execute_model_req: ExecuteModelRequest
4651
@@ -396,49 +438,88 @@ class LocalOrDistributedWorkerBase(WorkerBase):
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
         self.execute_worker(worker_input)
 
         # If there is no input, we don't need to execute the model.
-        if worker_input.num_seq_groups == 0:
-            return []
-
-        intermediate_tensors = None
-        orig_model_execute_time = 0.0
-        if not get_pp_group().is_first_rank:
-            intermediate_tensors = IntermediateTensors(
-                get_pp_group().recv_tensor_dict(
-                    all_gather_group=get_tp_group()))
+        if worker_input.num_seq_groups > 0:
+
4666
4667
+            self._read_blocks(worker_input)
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
+            intermediate_tensors = None
+            orig_model_execute_time = 0.0
+            if not get_pp_group().is_first_rank:
+                intermediate_tensors = IntermediateTensors(
+                    get_pp_group().recv_tensor_dict(
+                        all_gather_group=get_tp_group()))
+                if (self.observability_config is not None
+                        and self.observability_config.collect_model_execute_time):
+                    orig_model_execute_time = intermediate_tensors.tensors.get(
+                        "model_execute_time", torch.tensor(0)).item()
+
+            output = self.model_runner.execute_model(
+                model_input=model_input,
+                kv_caches=self.kv_cache[worker_input.virtual_engine]
+                if self.kv_cache is not None else None,
+                intermediate_tensors=intermediate_tensors,
+                num_steps=num_steps,
+                **kwargs,
+            )
+
+            model_execute_time = time.perf_counter() - start_time
+            if not get_pp_group().is_last_rank:
+                # output is IntermediateTensors
+                assert isinstance(output, IntermediateTensors)
+                if (self.observability_config is not None
+                        and self.observability_config.collect_model_execute_time):
+                    output.tensors["model_execute_time"] = torch.tensor(
+                        model_execute_time + orig_model_execute_time)
+                get_pp_group().send_tensor_dict(output.tensors,
+                                                all_gather_group=get_tp_group())
+                return [None]
             if (self.observability_config is not None
-                    and self.observability_config.collect_model_execute_time):
-                orig_model_execute_time = intermediate_tensors.tensors.get(
-                    "model_execute_time", torch.tensor(0)).item()
4703
4704
4705
4706
4707
4708
+                    and self.observability_config.collect_model_execute_time
+                    and output is not None):
+                for o in output:
+                    o.model_execute_time = (orig_model_execute_time +
+                                            model_execute_time)
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4709
4710
4711
4712
4713
4714
4715
4716
-        output = self.model_runner.execute_model(
-            model_input=model_input,
-            kv_caches=self.kv_cache[worker_input.virtual_engine]
-            if self.kv_cache is not None else None,
-            intermediate_tensors=intermediate_tensors,
-            num_steps=num_steps,
-            **kwargs,
-        )
4717
-
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
-        model_execute_time = time.perf_counter() - start_time
-        if not get_pp_group().is_last_rank:
-            # output is IntermediateTensors
-            assert isinstance(output, IntermediateTensors)
-            if (self.observability_config is not None
-                    and self.observability_config.collect_model_execute_time):
-                output.tensors["model_execute_time"] = torch.tensor(
-                    model_execute_time + orig_model_execute_time)
-            get_pp_group().send_tensor_dict(output.tensors,
-                                            all_gather_group=get_tp_group())
-            return [None]
-        if (self.observability_config is not None
-                and self.observability_config.collect_model_execute_time
-                and output is not None):
-            for o in output:
-                o.model_execute_time = (orig_model_execute_time +
-                                        model_execute_time)
4735
4736
+            self._write_blocks(worker_input)
 
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
+        else:
+            output = []
+
+        # collect kv transfer notifications from non driver workers
+
+        if self.nixl_connector is not None:
+            new_notifs = self.nixl_connector.get_new_notifs()
+            rank = get_tp_group().rank
+            all_new_notifs = [new_notifs]
+            if rank > 0:
+                get_tp_group().send_object(new_notifs, dst=0)
+            else:
+                for i in range(1, get_tp_group().world_size):
+                    all_new_notifs.append(get_tp_group().recv_object(src=i))
4751
+
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4752
4753
4754
4755
+            request_notif_counter = defaultdict(int)
+            for notifs in all_new_notifs:
+                for req_ids in notifs.values():
+                    for req_id in req_ids:
4756
+                        request_notif_counter[req_id.decode("utf-8")] += 1
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4757
4758
4759
+
+            if request_notif_counter:
+                logger.debug("Request notif counter: %s", request_notif_counter)
Neelay Shah's avatar
Neelay Shah committed
4760
4761
4762
4763
+
+            request_done_counter = defaultdict(int)
+            for req_id in self.nixl_connector.get_done_tranfers():
+                request_done_counter[req_id] += 1
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4764
4765
+        else:
+            request_notif_counter = {}
Neelay Shah's avatar
Neelay Shah committed
4766
+            request_done_counter = {}
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4767
4768
         # output is List[SamplerOutput]
-        return output
Neelay Shah's avatar
Neelay Shah committed
4769
+        return output, request_notif_counter, request_done_counter
4770
4771
4772
4773
4774
+
+    def _read_blocks(self, worker_input: WorkerInput) -> None:
+        pass
+
+    def _write_blocks(self, worker_input: WorkerInput) -> None:
ptarasiewiczNV's avatar
ptarasiewiczNV committed
4775
4776
4777
4778
+        pass
 
     def _execute_model_spmd(
         self,