Skip to content

vllm.distributed.kv_transfer.kv_connector.v1.hisparse.worker

HiSparse worker-side host/hot state and data movement.

Classes:

HiSparseConnectorWorker

Own HiSparse host/hot state and execute its worker-side transfers.

Methods:

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 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
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
class HiSparseConnectorWorker:
    """Own HiSparse host/hot state and execute its worker-side transfers."""

    _in_step = False
    kv_sharing_handles: tuple[HiSparseCacheHandle, ...] = ()

    def __init__(self, vllm_config: VllmConfig, kv_cache_config: KVCacheConfig) -> None:
        self.backend = get_hisparse_backend()
        self.vllm_config = vllm_config
        self.kv_cache_config = kv_cache_config
        self._initialized = False

    def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]) -> None:
        forward_context = self.vllm_config.compilation_config.static_forward_context
        cache_handles: list[HiSparseCacheHandle] = []
        cache_layer_names: list[str] = []
        for group in self.kv_cache_config.kv_cache_groups:
            if not issubclass(group.manager_cls, HiSparseHotManager):
                continue
            for cache_name in group.layer_names:
                assert cache_name.endswith(HISPARSE_HOT_SUFFIX)
                layer_name = cache_name[: -len(HISPARSE_HOT_SUFFIX)]
                cache_handles.append(_get_hisparse_cache(forward_context, layer_name))
                cache_layer_names.append(layer_name)

        if not cache_handles:
            raise RuntimeError("HiSparse connector found no hot-cache handles.")
        self.kv_sharing_handles = tuple(
            chain.from_iterable(get_kv_sharing_readers(forward_context).values())
        )
        hot_backings: dict[int, torch.Tensor] = {}
        host_pools: dict[int, HiSparseHostPool] = {}
        for cache in cache_handles:
            hot_backing = cache.runtime.hot_backing
            hot_backings[hot_backing.untyped_storage().data_ptr()] = hot_backing
            assert cache.runtime.host_pool is not None
            host_pools[id(cache.runtime.host_pool)] = cache.runtime.host_pool
        if len(hot_backings) != 1:
            raise RuntimeError("HiSparse hot tensors must share one GPU backing.")
        hot_backing = next(iter(hot_backings.values()))
        if len(host_pools) != 1:
            raise RuntimeError("HiSparse caches must share one host pool.")
        host_pool = next(iter(host_pools.values()))
        shared_host_region = host_pool.shared_region
        pinned_host_pools = host_pool.pinned
        host_leader_rank = get_hisparse_host_leader_rank(self.vllm_config)
        is_host_writer = (
            shared_host_region is None
            or get_tensor_model_parallel_rank() == host_leader_rank
        )
        host_num_blocks = self.kv_cache_config.hisparse_host_num_blocks
        assert host_num_blocks is not None
        try:
            self.initialize(
                cache_handles,
                cache_layer_names,
                self.vllm_config.scheduler_config.max_num_seqs,
                host_num_blocks,
                hot_backing.device,
                pinned_host_pools,
                shared_host_region=shared_host_region,
                is_host_writer=is_host_writer,
                host_leader_rank=host_leader_rank,
            )
        except Exception:
            release_pinned_state(
                pinned_host_pools,
                shared_host_region,
            )
            for cache in cache_handles:
                cache.unbind_cache()
            drop_hisparse_host_pool(self.vllm_config)
            raise

    def initialize(
        self,
        cache_handles: list[HiSparseCacheHandle],
        cache_layer_names: list[str],
        max_num_reqs: int,
        host_num_blocks: int,
        device: torch.device,
        pinned_host_pools: list[torch.Tensor],
        *,
        shared_host_region: SharedOffloadRegion | None = None,
        is_host_writer: bool = True,
        host_leader_rank: int = 0,
    ) -> None:
        if self._initialized:
            raise RuntimeError("HiSparse connector worker is already initialized.")
        resident = cache_handles[0].view
        assert resident is not None
        self.kernel_block_size = resident.block_size
        self._block_row_offsets = torch.arange(
            self.kernel_block_size, dtype=torch.int32, device=device
        )
        self.host_num_blocks = host_num_blocks
        self.pinned_host_pools = pinned_host_pools
        self.shared_host_region = shared_host_region
        self.is_host_writer = is_host_writer
        self.dma_stream = torch.Stream(device=device) if self.is_host_writer else None
        self._slot_mapping_staging = None
        if self.is_host_writer:
            max_mirror_rows = (
                self.vllm_config.scheduler_config.max_num_batched_tokens
                + max_num_reqs * (self.vllm_config.num_lookahead_tokens + 1)
            )
            self._slot_mapping_staging = _SlotMappingStaging(
                stream=torch.Stream(device=device),
                event=torch.Event(),
                slots=torch.empty(
                    max_mirror_rows,
                    dtype=torch.int64,
                    pin_memory=True,
                ),
            )
        self._dma_free_descriptors: list[_DMADescriptors] = []
        self._pending_dma_descriptors: deque[tuple[torch.Event, _DMADescriptors]] = (
            deque()
        )
        self._dma_submitted = False
        self._per_layer_mirrored: set[int] = set()
        self._in_step = False
        self._submitted_mirror_layers: set[int] = set()
        self._layer_ready_events = tuple(torch.Event() for _ in cache_handles)
        self._forward_ready_event = torch.Event()
        self._draft_layers = tuple(
            index for index, cache in enumerate(cache_handles) if cache.draft_layer
        )
        self._draft_mirror_pending = False
        self._set_row_mirrors(())
        self._group_leaders = tuple(
            (layer_name, cache)
            for layer_name, cache in zip(cache_layer_names, cache_handles, strict=True)
            if cache.runtime.is_group_leader
        )
        self.host_write_events = _create_hisparse_host_events(
            shared_host_region, is_host_writer, host_leader_rank, device
        )
        self.host_write_event = self.host_write_events[1]
        self._next_host_write_event = 0
        self.cache_handles = cache_handles
        self.leader_runtimes = [cache.runtime for _, cache in self._group_leaders]
        request_state_indices = {
            indices.data_ptr(): indices
            for cache in cache_handles
            if (indices := cache.runtime.request_state_indices) is not None
        }
        if len(request_state_indices) != 1:
            raise RuntimeError(
                "HiSparse runtimes must share one request-state mapping."
            )
        self.request_state_indices = next(iter(request_state_indices.values()))
        if self.request_state_indices.numel() != max_num_reqs:
            raise RuntimeError(
                "HiSparse request-state mapping does not match max_num_seqs."
            )
        self._invalidate_written_slots = HiSparseSlotInvalidator(
            self.request_state_indices
        )
        self.residency: torch.Tensor | None = next(
            (cache.residency for cache in cache_handles if cache.residency is not None),
            None,
        )
        self._pending_invalid_block_ids: list[int] = []
        # Destination block ids of host copies this worker has run.
        self._completed_host_copy_dst_ids: list[int] = []
        self._post_forward_transfers: list[SparseKVPageTransfer] = []
        self._enqueued_transfer_ids: list[int] = []
        self._pending_transfer_events: deque[tuple[torch.Event, tuple[int, ...]]] = (
            deque()
        )
        self._metrics_calls = 0
        self._metrics_event = torch.Event()
        self._metrics_pending = False
        self._init_dma()
        if self.is_host_writer:
            for layer_index, handle in enumerate(cache_handles):
                # Draft layers are mirrored once in the next start_step instead.
                if not handle.draft_layer:
                    handle.submit_layer_mirror = partial(
                        self._enqueue_layer_mirror, layer_index
                    )
        self._initialized = True

    def set_request_state_indices(self, indices: torch.Tensor) -> None:
        if indices.numel() > self.request_state_indices.numel():
            raise ValueError(
                "HiSparse request-state mapping exceeds max_num_seqs: "
                f"{indices.numel()} > {self.request_state_indices.numel()}."
            )
        if self.backend.is_current_stream_capturing():
            return
        # Attention indexes persistent request state by input-batch row. Refresh
        # that indirection after every batch compaction or reorder.
        self.request_state_indices.fill_(-1)
        self.request_state_indices[: indices.numel()].copy_(indices)
        if self._pending_invalid_block_ids:
            self.invalidate_blocks(self._pending_invalid_block_ids, indices)
            self._pending_invalid_block_ids.clear()

    def _init_dma(self) -> None:
        host_caches = tuple(cache.runtime.host_cache for cache in self.cache_handles)
        resident_caches = []
        for cache in self.cache_handles:
            assert cache.view is not None and cache.slot_mapping is not None
            resident_caches.append(cache.view.cache)
        self.host_caches = host_caches
        self.resident_caches = tuple(resident_caches)

        for resident_cache, host_cache in zip(resident_caches, host_caches):
            row_bytes = resident_cache.shape[-1] * resident_cache.element_size()
            if (
                resident_cache.ndim != 3
                or resident_cache.shape[1] != self.kernel_block_size
                or resident_cache.stride(1) * resident_cache.element_size() != row_bytes
            ):
                raise RuntimeError("HiSparse DMA requires contiguous resident rows.")
            if (
                host_cache.ndim != 2
                or not host_cache.is_contiguous()
                or host_cache.shape[1] * host_cache.element_size() != row_bytes
            ):
                raise RuntimeError("HiSparse DMA requires contiguous host rows.")

    def start_step(
        self,
        metadata: HiSparseConnectorMetadata,
        request_state_indices: torch.Tensor | None,
        request_ids: list[str] | None = None,
        num_tokens: int = 0,
    ) -> None:
        self._stage_row_mirror_mapping(num_tokens)
        self._finish_previous_step()
        previous_host_write_event = self.host_write_event
        self.host_write_event = self.host_write_events[self._next_host_write_event]
        self._next_host_write_event ^= 1
        torch.accelerator.current_stream().wait_event(previous_host_write_event)
        if self.shared_host_region is not None and not num_tokens:
            # Without a forward, no TP collective keeps rank 0 from recording
            # a shared event again before every rank has issued its wait.
            get_tp_group().barrier()
        self._release_completed_dma_descriptors()
        self._dma_submitted = False
        mirrors = _flatten_row_mirrors(metadata.row_mirrors, request_ids)
        if self._slot_mapping_staging is not None:
            self._slot_mapping_staging.candidates = mirrors
        self._set_row_mirrors(mirrors)
        self._clear_forward_mirror_state()
        self._in_step = True
        for handle in self.cache_handles:
            handle.all_context_pages_resident = metadata.all_context_pages_resident
        for handle in self.kv_sharing_handles:
            handle.all_context_pages_resident = metadata.all_context_pages_resident
        self._copy_host_blocks(metadata.host_block_copies, previous_host_write_event)
        transfers = (
            metadata.command.page_transfers if metadata.command is not None else []
        )
        self._restore_pages([transfer for transfer in transfers if transfer.restore])
        self._post_forward_transfers = [
            transfer for transfer in transfers if not transfer.restore
        ]
        self._pending_invalid_block_ids.extend(metadata.source_block_ids)
        if request_state_indices is not None:
            self.set_request_state_indices(request_state_indices)
        if metadata.residency_updates:
            assert self.residency is not None
            assert request_state_indices is not None and request_ids is not None
            update_hisparse_residency(
                self.residency,
                metadata.residency_updates,
                request_ids,
                request_state_indices,
            )

    def _clear_forward_mirror_state(self) -> None:
        self._per_layer_mirrored.clear()
        self._submitted_mirror_layers.clear()
        for handle in self.cache_handles:
            handle.decode_batch = False
            handle.host_mirror_required = False
            handle.num_actual_tokens = 0
            handle.num_decode_tokens = 0
            handle.req_id_per_token = None

    def prepare_forward(self, attn_metadata: Mapping[str, Any] | None) -> None:
        if attn_metadata is None:
            return
        for layer_name, handle in self._group_leaders:
            metadata = attn_metadata.get(layer_name)
            if metadata is not None:
                handle.prepare_group_for_batch(metadata)

    def _stage_row_mirror_mapping(self, num_tokens: int) -> None:
        """Snapshot the rows this forward will write, off the compute stream.

        The resident slot mapping is a persistent view bound at registration
        time, so the rows are already staged by the time the forward launches.
        """
        state = self._slot_mapping_staging
        if state is None or not num_tokens:
            return
        handle = self.cache_handles[0]
        slots = handle.slot_mapping
        assert slots is not None
        source_index = handle.runtime.resident_source_index
        start = state.num_tokens
        end = start + num_tokens
        if end > state.slots.shape[0]:
            raise ValueError(
                "HiSparse row mapping exceeds staging capacity: "
                f"{end} > {state.slots.shape[0]}."
            )
        main_stream = torch.accelerator.current_stream()
        state.stream.wait_stream(main_stream)
        with state.stream:
            state.slots[start:end].copy_(
                slots[:num_tokens],
                non_blocking=True,
            )
            state.event.record(state.stream)
        state.num_tokens = end
        state.source_index = source_index

    def _resolve_row_mirrors(self, state: _SlotMappingStaging) -> None:
        """Compute the final row mirrors from the staged GPU slot mapping."""
        self._set_row_mirrors(
            _select_written_row_mirrors(
                state.candidates,
                state.slots[: state.num_tokens].numpy(),
                state.source_index,
            )
        )
        state.num_tokens = 0

    def _copy_host_blocks(
        self,
        host_block_copies: Sequence[KVCacheBlockCopy],
        previous_host_write_event: torch.Event,
    ) -> None:
        if not host_block_copies:
            return
        self._completed_host_copy_dst_ids.extend(
            copy.dst_block_id for copy in host_block_copies
        )
        if self.is_host_writer:
            previous_host_write_event.synchronize()
            copy_kv_cache_blocks_inplace(
                self.host_caches,
                self.host_num_blocks,
                host_block_copies,
            )
        if self.shared_host_region is not None:
            get_tp_group().barrier()

    def invalidate_blocks(
        self, block_ids: list[int], request_state_indices: torch.Tensor
    ) -> None:
        """Invalidate recycled host slots in this worker's leader runtimes."""
        if not block_ids:
            return
        device = self.cache_handles[0].runtime.device
        staging = torch.tensor(block_ids, dtype=torch.int32, pin_memory=True)
        blocks = staging.to(device, dtype=torch.int32, non_blocking=True)
        slots = (
            blocks[:, None] * self.kernel_block_size + self._block_row_offsets
        ).flatten()
        sorted_slots = torch.sort(slots).values
        state_indices = request_state_indices.to(device=device, dtype=torch.long)
        for runtime in self.leader_runtimes:
            runtime.invalidate_sorted_slots(sorted_slots, state_indices)

    def reset_hot_state(self) -> None:
        for runtime in self.leader_runtimes:
            runtime.reset_hot_state()

    def get_kv_connector_stats(self) -> HiSparseKVConnectorStats | None:
        stats = None
        if self._metrics_pending and self._metrics_event.query():
            stats = HiSparseKVConnectorStats()
            for runtime in self.leader_runtimes:
                group = runtime.index_group
                hits, misses = group.swap_stats_host.tolist()
                if hits or misses:
                    stats.record_snapshot(hits, misses, misses * group.stats_row_bytes)
            self._metrics_pending = False
            if stats.is_empty():
                stats = None

        self._metrics_calls += 1
        if (
            self._metrics_calls % _METRICS_INTERVAL == 0
            and not self._metrics_pending
            and not self.backend.is_current_stream_capturing()
        ):
            compute_stream = torch.accelerator.current_stream()
            for runtime in self.leader_runtimes:
                group = runtime.index_group
                compute_stream.wait_stream(group.copy_stream)
                group.swap_stats_host.copy_(group.swap_stats, non_blocking=True)
                group.swap_stats.zero_()
                group.copy_stream.wait_stream(compute_stream)
            self._metrics_event.record()
            self._metrics_pending = True
        return stats

    def _release_completed_dma_descriptors(self) -> None:
        pending = self._pending_dma_descriptors
        while pending and pending[0][0].query():
            _, descriptors = pending.popleft()
            self._dma_free_descriptors.append(descriptors)

    def _acquire_dma_descriptors(self, size: int) -> _DMADescriptors:
        for index, descriptors in enumerate(self._dma_free_descriptors):
            if descriptors.src.numel() >= size:
                return self._dma_free_descriptors.pop(index)
        return _allocate_dma_descriptors(size)

    def _submit_dma_descriptors(
        self,
        descriptors: _DMADescriptors,
        descriptor_count: int,
        transfer_ids: tuple[int, ...] = (),
        ready_event: torch.Event | None = None,
    ) -> None:
        stream = self.dma_stream
        assert stream is not None
        if ready_event is None:
            stream.wait_stream(torch.accelerator.current_stream())
        else:
            stream.wait_event(ready_event)
        completion_event = torch.Event()
        with stream:
            self.backend.swap_blocks_batch(
                descriptors.src[:descriptor_count],
                descriptors.dst[:descriptor_count],
                descriptors.sizes[:descriptor_count],
            )
            self.host_write_event.record(stream)
            completion_event.record(stream)
        self._pending_dma_descriptors.append((completion_event, descriptors))
        self._dma_submitted = True
        if transfer_ids:
            self._pending_transfer_events.append((completion_event, transfer_ids))
            self._enqueued_transfer_ids.extend(transfer_ids)

    def _set_row_mirrors(self, mirrors: tuple[SparseKVRowMirror, ...]) -> None:
        self._row_mirrors = mirrors
        self._row_mirror_destination_starts = np.fromiter(
            (mirror.destination_start for mirror in mirrors),
            dtype=np.int64,
            count=len(mirrors),
        )
        self._row_mirror_counts = np.fromiter(
            (mirror.num_rows for mirror in mirrors),
            dtype=np.int64,
            count=len(mirrors),
        )
        if mirrors:
            self._row_mirror_source_starts = np.asarray(
                [mirror.source_starts for mirror in mirrors], dtype=np.int64
            )
            if self._row_mirror_source_starts.ndim != 2:
                raise RuntimeError("HiSparse DMA source mappings must be rectangular.")
        else:
            self._row_mirror_source_starts = np.empty((0, 0), dtype=np.int64)
        self._row_mirror_num_rows = int(self._row_mirror_counts.sum())

    def _enqueue_row_dma(
        self, layer_indices: Sequence[int], ready_event: torch.Event | None = None
    ) -> None:
        if (
            not layer_indices
            or not self._row_mirror_num_rows
            or not self.is_host_writer
        ):
            return
        mirrors = self._row_mirrors
        num_layers = len(layer_indices)
        descriptor_count = len(mirrors) * num_layers
        descriptors = self._acquire_dma_descriptors(descriptor_count)
        destination_starts = self._row_mirror_destination_starts
        row_counts = self._row_mirror_counts
        for descriptor_offset, layer_index in enumerate(layer_indices):
            cache = self.cache_handles[layer_index]
            source_index = cache.runtime.resident_source_index
            if source_index >= self._row_mirror_source_starts.shape[1]:
                raise RuntimeError("HiSparse row DMA source index is out of range.")
            source_rows = self._row_mirror_source_starts[:, source_index]
            source = self.resident_caches[layer_index]
            destination = self.host_caches[layer_index]
            row_bytes = source.shape[-1] * source.element_size()
            source_blocks, source_row_offsets = np.divmod(
                source_rows, self.kernel_block_size
            )
            source_out_of_range = (
                np.any(source_blocks < 0)
                or np.any(source_blocks >= source.shape[0])
                or np.any(source_row_offsets + row_counts > self.kernel_block_size)
            )
            if source_out_of_range:
                raise RuntimeError("HiSparse row DMA source is out of range.")
            if np.any(destination_starts < 0) or np.any(
                destination_starts + row_counts > destination.shape[0]
            ):
                raise RuntimeError("HiSparse row DMA index is out of range.")
            descriptor_slice = slice(descriptor_offset, descriptor_count, num_layers)
            descriptors.src_np[descriptor_slice] = (
                source.data_ptr()
                + source_blocks * source.stride(0) * source.element_size()
                + source_row_offsets * row_bytes
            )
            descriptors.dst_np[descriptor_slice] = (
                destination.data_ptr() + destination_starts * row_bytes
            )
            descriptors.sizes_np[descriptor_slice] = row_counts * row_bytes

        self._submit_dma_descriptors(
            descriptors, descriptor_count, ready_event=ready_event
        )

    def _enqueue_layer_mirror(self, layer_index: int) -> None:
        handle = self.cache_handles[layer_index]
        if not self._in_step or not handle.host_mirror_required:
            return
        if layer_index in self._per_layer_mirrored:
            raise RuntimeError(f"HiSparse layer {layer_index} mirrored twice.")
        state = self._slot_mapping_staging
        if state is not None and state.num_tokens:
            # The staging stream waited on the compute stream before the
            # forward launched, so this only drains pre-forward work that is
            # already queued ahead of the layer kernels: no GPU bubble.
            state.event.synchronize()
            self._resolve_row_mirrors(state)
        self._per_layer_mirrored.add(layer_index)
        next_layer = layer_index + 1
        if (
            next_layer < len(self.cache_handles)
            and self.cache_handles[next_layer].runtime.resident_source_index
            == handle.runtime.resident_source_index
        ):
            return
        ready_event = self._layer_ready_events[layer_index]
        ready_event.record()
        pending_layers = tuple(
            sorted(self._per_layer_mirrored - self._submitted_mirror_layers)
        )
        self._enqueue_row_dma(
            pending_layers,
            ready_event=ready_event,
        )
        self._submitted_mirror_layers.update(pending_layers)

    def _record_transfer_completion(
        self,
        transfers: list[SparseKVPageTransfer],
        *,
        stream: torch.Stream | None = None,
    ) -> None:
        if not transfers:
            return
        if stream is None:
            if not self.is_host_writer:
                return
            stream = self.dma_stream
        assert stream is not None
        completion_event = torch.Event()
        completion_event.record(stream)
        transfer_ids = tuple(transfer.transfer_id for transfer in transfers)
        self._pending_transfer_events.append((completion_event, transfer_ids))
        self._enqueued_transfer_ids.extend(transfer_ids)

    def _restore_pages(self, transfers: list[SparseKVPageTransfer]) -> None:
        """Copy host pages into resident pages on every rank before its forward.

        Covers imported tails and promoted imports. One batched H2D call per
        step, instead of one copy per page and layer, keeps a long promoted
        import from flooding the stream with launches.
        """
        if not transfers:
            return
        num_layers = len(self.cache_handles)
        descriptor_count = len(transfers) * num_layers
        descriptors = self._acquire_dma_descriptors(descriptor_count)
        host_rows = np.fromiter(
            (transfer.host_block_id * self.kernel_block_size for transfer in transfers),
            dtype=np.int64,
            count=len(transfers),
        )
        resident_blocks_by_transfer = np.asarray(
            [transfer.resident_block_ids for transfer in transfers], dtype=np.int64
        )
        for layer_index, cache in enumerate(self.cache_handles):
            resident_blocks = resident_blocks_by_transfer[
                :, cache.runtime.resident_source_index
            ]
            source = self.host_caches[layer_index]
            destination = self.resident_caches[layer_index]
            if np.any(resident_blocks < 0) or np.any(
                resident_blocks >= destination.shape[0]
            ):
                raise RuntimeError("HiSparse restore destination is out of range.")
            if np.any(host_rows < 0) or np.any(
                host_rows + self.kernel_block_size > source.shape[0]
            ):
                raise RuntimeError("HiSparse restore source is out of range.")
            row_bytes = destination.shape[-1] * destination.element_size()
            descriptor_slice = slice(layer_index, descriptor_count, num_layers)
            descriptors.src_np[descriptor_slice] = (
                source.data_ptr() + host_rows * row_bytes
            )
            descriptors.dst_np[descriptor_slice] = (
                destination.data_ptr()
                + resident_blocks * destination.stride(0) * destination.element_size()
            )
            descriptors.sizes_np[descriptor_slice] = self.kernel_block_size * row_bytes
        stream = torch.accelerator.current_stream()
        self.backend.swap_blocks_batch(
            descriptors.src[:descriptor_count],
            descriptors.dst[:descriptor_count],
            descriptors.sizes[:descriptor_count],
        )
        completion_event = torch.Event()
        completion_event.record(stream)
        self._pending_dma_descriptors.append((completion_event, descriptors))
        self._record_transfer_completion(transfers, stream=stream)

    def _submit_transfers(self, transfers: list[SparseKVPageTransfer]) -> None:
        if self.cache_handles[0].runtime.eager_host_mirror:
            self._record_transfer_completion(transfers)
        else:
            self._enqueue_transfers(transfers)

    def _enqueue_transfers(self, transfers: list[SparseKVPageTransfer]) -> None:
        if not transfers or not self.is_host_writer:
            return
        num_layers = len(self.cache_handles)
        descriptor_count = len(transfers) * num_layers
        descriptors = self._acquire_dma_descriptors(descriptor_count)
        destination_rows = np.fromiter(
            (transfer.host_block_id * self.kernel_block_size for transfer in transfers),
            dtype=np.int64,
            count=len(transfers),
        )
        source_blocks_by_transfer = np.asarray(
            [transfer.resident_block_ids for transfer in transfers], dtype=np.int64
        )
        if source_blocks_by_transfer.ndim != 2:
            raise RuntimeError(
                "HiSparse spill DMA source mappings must be rectangular."
            )
        for layer_index, cache in enumerate(self.cache_handles):
            source_index = cache.runtime.resident_source_index
            if source_index >= source_blocks_by_transfer.shape[1]:
                raise RuntimeError("HiSparse spill DMA source index is out of range.")
            source_blocks = source_blocks_by_transfer[:, source_index]
            source = self.resident_caches[layer_index]
            destination = self.host_caches[layer_index]
            if np.any(source_blocks < 0) or np.any(source_blocks >= source.shape[0]):
                raise RuntimeError("HiSparse spill DMA source is out of range.")
            if np.any(destination_rows < 0) or np.any(
                destination_rows + self.kernel_block_size > destination.shape[0]
            ):
                raise RuntimeError("HiSparse spill DMA destination is out of range.")
            row_bytes = source.shape[-1] * source.element_size()
            descriptor_slice = slice(layer_index, descriptor_count, num_layers)
            descriptors.src_np[descriptor_slice] = (
                source.data_ptr()
                + source_blocks * source.stride(0) * source.element_size()
            )
            descriptors.dst_np[descriptor_slice] = (
                destination.data_ptr() + destination_rows * row_bytes
            )
            descriptors.sizes_np[descriptor_slice] = self.kernel_block_size * row_bytes
        self._submit_dma_descriptors(
            descriptors,
            descriptor_count,
            transfer_ids=tuple(transfer.transfer_id for transfer in transfers),
        )

    def _enqueue_host_mirror(
        self,
        ready_event: torch.Event | None = None,
    ) -> None:
        active = [
            (index, handle)
            for index, handle in enumerate(self.cache_handles)
            if handle.num_actual_tokens != 0
        ]
        if not active:
            return

        def mirror_key(handle: HiSparseCacheHandle) -> tuple:
            slots = handle.mirror_slot_mapping
            return (
                handle.num_actual_tokens,
                handle.num_decode_tokens,
                handle.decode_batch,
                handle.host_mirror_required,
                handle.runtime.eager_host_mirror,
                None if slots is None else slots.data_ptr(),
            )

        keys = {mirror_key(handle) for _, handle in active}
        if len(keys) > 1:
            raise RuntimeError(
                f"HiSparse cache layers disagree on mirror metadata: {list(keys)}."
            )
        cache = active[0][1]
        if not cache.host_mirror_required:
            return
        dst_slots = cache.mirror_slot_mapping
        if dst_slots is None:
            raise RuntimeError("HiSparse host mirror has no source slot mapping.")
        num_rows = min(cache.num_actual_tokens, dst_slots.numel())
        if num_rows == 0:
            return
        if self.is_host_writer:
            # The drafter has not written its layers' rows yet; the next
            # start_step mirrors them after it runs.
            self._draft_mirror_pending = bool(self._draft_layers)
            expected_layers = {index for index, _ in active}.difference(
                self._draft_layers
            )
            if self._per_layer_mirrored and self._per_layer_mirrored != expected_layers:
                raise RuntimeError(
                    "HiSparse per-layer DMA did not mirror every active layer: "
                    f"expected {sorted(expected_layers)}, got "
                    f"{sorted(self._per_layer_mirrored)}."
                )
            pending_layers = tuple(
                sorted(expected_layers - self._submitted_mirror_layers)
            )
            if pending_layers:
                self._enqueue_row_dma(pending_layers, ready_event=ready_event)
                self._submitted_mirror_layers.update(pending_layers)
        assert cache.req_id_per_token is not None
        self._invalidate_written_slots(
            [handle.runtime for _, handle in active if handle.runtime.is_group_leader],
            dst_slots[:num_rows],
            cache.req_id_per_token[:num_rows],
        )

    def _finish_mirror_phase(self, ready_event: torch.Event | None = None) -> None:
        state = self._slot_mapping_staging
        if state is not None and state.num_tokens:
            # Measured free: blocking here costs no throughput (26.7 vs 27.6
            # gen tok/s) and lets every step mirror exactly the written rows.
            state.event.synchronize()
            self._resolve_row_mirrors(state)
        self._enqueue_host_mirror(ready_event)
        self._clear_forward_mirror_state()
        self._in_step = False

    def finish_forward(self) -> None:
        compute_stream = torch.accelerator.current_stream()
        self._forward_ready_event.record()
        self._finish_mirror_phase(self._forward_ready_event)
        self._in_step = False
        if self.is_host_writer:
            if self._dma_submitted:
                compute_stream.wait_event(self.host_write_event)
                self._dma_submitted = False
            else:
                self.host_write_event.record(compute_stream)
        self._release_completed_dma_descriptors()

    def _finish_previous_step(self) -> None:
        """Mirror the previous step's draft-layer rows, then hand its pages over.

        Runs before this step's work, so after the previous step's drafter.
        Post-forward transfers are ordered behind the draft mirror, so a page is
        never reported clean, and its resident block never released, before
        its draft-layer rows reach the host. Both land in the previous step's
        host write event, which this step waits on before its forward and its
        host copies, since the scheduler may already have reused the
        finished requests' blocks they read and write.
        """
        if self._draft_mirror_pending:
            self._draft_mirror_pending = False
            self._enqueue_row_dma(self._draft_layers)
        transfers = self._post_forward_transfers
        self._post_forward_transfers = []
        self._submit_transfers(transfers)

    def take_completed_host_copies(self) -> list[int]:
        """Drain host copies this worker has enqueued for this step."""
        completed = self._completed_host_copy_dst_ids
        self._completed_host_copy_dst_ids = []
        return completed

    def take_transfer_updates(self) -> tuple[list[int], list[int]]:
        enqueued = self._enqueued_transfer_ids
        self._enqueued_transfer_ids = []
        completed: list[int] = []
        while self._pending_transfer_events:
            event, transfer_ids = self._pending_transfer_events[0]
            if not event.query():
                break
            self._pending_transfer_events.popleft()
            completed.extend(transfer_ids)
        return enqueued, completed

    def shutdown(self) -> None:
        if not self._initialized:
            return
        if self._slot_mapping_staging is not None:
            self._slot_mapping_staging.stream.synchronize()
        if self.dma_stream is not None:
            self.dma_stream.synchronize()
        release_pinned_state(
            self.pinned_host_pools,
            self.shared_host_region,
        )
        for cache in self.cache_handles:
            cache.unbind_cache()
        drop_hisparse_host_pool(self.vllm_config)
        self._initialized = False

_finish_previous_step()

Mirror the previous step's draft-layer rows, then hand its pages over.

Runs before this step's work, so after the previous step's drafter. Post-forward transfers are ordered behind the draft mirror, so a page is never reported clean, and its resident block never released, before its draft-layer rows reach the host. Both land in the previous step's host write event, which this step waits on before its forward and its host copies, since the scheduler may already have reused the finished requests' blocks they read and write.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def _finish_previous_step(self) -> None:
    """Mirror the previous step's draft-layer rows, then hand its pages over.

    Runs before this step's work, so after the previous step's drafter.
    Post-forward transfers are ordered behind the draft mirror, so a page is
    never reported clean, and its resident block never released, before
    its draft-layer rows reach the host. Both land in the previous step's
    host write event, which this step waits on before its forward and its
    host copies, since the scheduler may already have reused the
    finished requests' blocks they read and write.
    """
    if self._draft_mirror_pending:
        self._draft_mirror_pending = False
        self._enqueue_row_dma(self._draft_layers)
    transfers = self._post_forward_transfers
    self._post_forward_transfers = []
    self._submit_transfers(transfers)

_resolve_row_mirrors(state)

Compute the final row mirrors from the staged GPU slot mapping.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def _resolve_row_mirrors(self, state: _SlotMappingStaging) -> None:
    """Compute the final row mirrors from the staged GPU slot mapping."""
    self._set_row_mirrors(
        _select_written_row_mirrors(
            state.candidates,
            state.slots[: state.num_tokens].numpy(),
            state.source_index,
        )
    )
    state.num_tokens = 0

_restore_pages(transfers)

Copy host pages into resident pages on every rank before its forward.

Covers imported tails and promoted imports. One batched H2D call per step, instead of one copy per page and layer, keeps a long promoted import from flooding the stream with launches.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def _restore_pages(self, transfers: list[SparseKVPageTransfer]) -> None:
    """Copy host pages into resident pages on every rank before its forward.

    Covers imported tails and promoted imports. One batched H2D call per
    step, instead of one copy per page and layer, keeps a long promoted
    import from flooding the stream with launches.
    """
    if not transfers:
        return
    num_layers = len(self.cache_handles)
    descriptor_count = len(transfers) * num_layers
    descriptors = self._acquire_dma_descriptors(descriptor_count)
    host_rows = np.fromiter(
        (transfer.host_block_id * self.kernel_block_size for transfer in transfers),
        dtype=np.int64,
        count=len(transfers),
    )
    resident_blocks_by_transfer = np.asarray(
        [transfer.resident_block_ids for transfer in transfers], dtype=np.int64
    )
    for layer_index, cache in enumerate(self.cache_handles):
        resident_blocks = resident_blocks_by_transfer[
            :, cache.runtime.resident_source_index
        ]
        source = self.host_caches[layer_index]
        destination = self.resident_caches[layer_index]
        if np.any(resident_blocks < 0) or np.any(
            resident_blocks >= destination.shape[0]
        ):
            raise RuntimeError("HiSparse restore destination is out of range.")
        if np.any(host_rows < 0) or np.any(
            host_rows + self.kernel_block_size > source.shape[0]
        ):
            raise RuntimeError("HiSparse restore source is out of range.")
        row_bytes = destination.shape[-1] * destination.element_size()
        descriptor_slice = slice(layer_index, descriptor_count, num_layers)
        descriptors.src_np[descriptor_slice] = (
            source.data_ptr() + host_rows * row_bytes
        )
        descriptors.dst_np[descriptor_slice] = (
            destination.data_ptr()
            + resident_blocks * destination.stride(0) * destination.element_size()
        )
        descriptors.sizes_np[descriptor_slice] = self.kernel_block_size * row_bytes
    stream = torch.accelerator.current_stream()
    self.backend.swap_blocks_batch(
        descriptors.src[:descriptor_count],
        descriptors.dst[:descriptor_count],
        descriptors.sizes[:descriptor_count],
    )
    completion_event = torch.Event()
    completion_event.record(stream)
    self._pending_dma_descriptors.append((completion_event, descriptors))
    self._record_transfer_completion(transfers, stream=stream)

_stage_row_mirror_mapping(num_tokens)

Snapshot the rows this forward will write, off the compute stream.

The resident slot mapping is a persistent view bound at registration time, so the rows are already staged by the time the forward launches.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def _stage_row_mirror_mapping(self, num_tokens: int) -> None:
    """Snapshot the rows this forward will write, off the compute stream.

    The resident slot mapping is a persistent view bound at registration
    time, so the rows are already staged by the time the forward launches.
    """
    state = self._slot_mapping_staging
    if state is None or not num_tokens:
        return
    handle = self.cache_handles[0]
    slots = handle.slot_mapping
    assert slots is not None
    source_index = handle.runtime.resident_source_index
    start = state.num_tokens
    end = start + num_tokens
    if end > state.slots.shape[0]:
        raise ValueError(
            "HiSparse row mapping exceeds staging capacity: "
            f"{end} > {state.slots.shape[0]}."
        )
    main_stream = torch.accelerator.current_stream()
    state.stream.wait_stream(main_stream)
    with state.stream:
        state.slots[start:end].copy_(
            slots[:num_tokens],
            non_blocking=True,
        )
        state.event.record(state.stream)
    state.num_tokens = end
    state.source_index = source_index

invalidate_blocks(block_ids, request_state_indices)

Invalidate recycled host slots in this worker's leader runtimes.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def invalidate_blocks(
    self, block_ids: list[int], request_state_indices: torch.Tensor
) -> None:
    """Invalidate recycled host slots in this worker's leader runtimes."""
    if not block_ids:
        return
    device = self.cache_handles[0].runtime.device
    staging = torch.tensor(block_ids, dtype=torch.int32, pin_memory=True)
    blocks = staging.to(device, dtype=torch.int32, non_blocking=True)
    slots = (
        blocks[:, None] * self.kernel_block_size + self._block_row_offsets
    ).flatten()
    sorted_slots = torch.sort(slots).values
    state_indices = request_state_indices.to(device=device, dtype=torch.long)
    for runtime in self.leader_runtimes:
        runtime.invalidate_sorted_slots(sorted_slots, state_indices)

take_completed_host_copies()

Drain host copies this worker has enqueued for this step.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def take_completed_host_copies(self) -> list[int]:
    """Drain host copies this worker has enqueued for this step."""
    completed = self._completed_host_copy_dst_ids
    self._completed_host_copy_dst_ids = []
    return completed

_select_written_row_mirrors(candidates, source_slots, source_index)

Select and coalesce GPU-written rows from a scheduler-owned envelope.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/hisparse/worker.py
def _select_written_row_mirrors(
    candidates: tuple[SparseKVRowMirror, ...],
    source_slots: np.ndarray,
    source_index: int,
) -> tuple[SparseKVRowMirror, ...]:
    """Select and coalesce GPU-written rows from a scheduler-owned envelope."""
    source_slots = source_slots[source_slots >= 0]
    if source_slots.size == 0 or not candidates:
        return ()
    starts = np.asarray([mirror.source_starts for mirror in candidates], dtype=np.int64)
    counts = np.fromiter((mirror.num_rows for mirror in candidates), dtype=np.int64)
    destinations = np.fromiter(
        [mirror.destination_start for mirror in candidates], dtype=np.int64
    )
    if source_index >= starts.shape[1]:
        raise RuntimeError("HiSparse row-mirror source index is out of range.")
    source_starts = starts[:, source_index]
    order = np.argsort(source_starts)
    matches = np.searchsorted(source_starts[order], source_slots, side="right") - 1
    candidate_ids = order[np.maximum(matches, 0)]
    offsets = source_slots - source_starts[candidate_ids]
    valid = (matches >= 0) & (offsets < counts[candidate_ids])
    if not np.all(valid):
        # A page the scheduler could not map has no host destination, so its
        # rows are simply not mirrorable this step.
        source_slots = source_slots[valid]
        candidate_ids = candidate_ids[valid]
        offsets = offsets[valid]
        if source_slots.size == 0:
            return ()
    sources = starts[candidate_ids] + offsets[:, None]
    destinations = destinations[candidate_ids] + offsets
    boundaries = (
        np.flatnonzero(
            (candidate_ids[1:] != candidate_ids[:-1])
            | (np.diff(destinations) != 1)
            | np.any(np.diff(sources, axis=0) != 1, axis=1)
        )
        + 1
    )
    run_starts = np.concatenate(([0], boundaries))
    run_ends = np.concatenate((boundaries, [destinations.size]))
    return tuple(
        SparseKVRowMirror(
            source_starts=tuple(int(value) for value in sources[start]),
            destination_start=int(destinations[start]),
            num_rows=int(end - start),
        )
        for start, end in zip(run_starts, run_ends, strict=True)
    )