Skip to content

vllm.distributed.kv_transfer.kv_connector.v1.moriio.moriio_connector

Classes:

MoRIIOConnector

Bases: KVConnectorBase_V1

Methods:

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
class MoRIIOConnector(KVConnectorBase_V1):
    def __init__(
        self,
        vllm_config: VllmConfig,
        role: KVConnectorRole,
        kv_cache_config: "KVCacheConfig",
    ):
        super().__init__(vllm_config, role, kv_cache_config)
        assert vllm_config.kv_transfer_config is not None, (
            "kv_transfer_config must be set for MoRIIOConnector"
        )

        self.kv_transfer_config = vllm_config.kv_transfer_config
        self._set_port_defaults(vllm_config)

        self.engine_id = (
            str(resolve_host_ip(self.kv_transfer_config.kv_connector_extra_config))
            + ":"
            + str(self.kv_transfer_config.kv_connector_extra_config["handshake_port"])
        )
        self.mode = get_moriio_mode(self.kv_transfer_config)
        if (
            self.mode == MoRIIOMode.READ
            and self.kv_transfer_config.is_kv_consumer
            and vllm_config.compilation_config.cudagraph_mode.has_full_cudagraphs()
        ):
            # warn only; kv-read barrier requires PIECEWISE cudagraph mode
            logger.warning_once(
                "MoRIIO READ mode is running with %s CUDA graphs: per-layer "
                "KV-read barrier can't fire inside full graph; accuracy may "
                "degrade at high concurrency. Set cudagraph_mode=PIECEWISE "
                "in --compilation-config.",
                vllm_config.compilation_config.cudagraph_mode.name,
            )
        if role == KVConnectorRole.SCHEDULER:
            self.connector_scheduler: MoRIIOConnectorScheduler | None = (
                MoRIIOConnectorScheduler(vllm_config, self.engine_id)
            )
            self.connector_worker: MoRIIOConnectorWorker | None = None
        elif role == KVConnectorRole.WORKER:
            self.connector_scheduler = None
            self.connector_worker = MoRIIOConnectorWorker(
                vllm_config, self.engine_id, kv_cache_config
            )
        logger.info(
            "Initialized MoRIIO Connector,engine_id:%s,role: %s",
            self.engine_id,
            role.value,
        )

    ############################################################
    # Scheduler Side Methods
    ############################################################

    def _set_port_defaults(self, vllm_config: VllmConfig):
        assert vllm_config.kv_transfer_config is not None, (
            "kv_transfer_config must be set for MoRIIOConnector"
        )
        kv_transfer_config = vllm_config.kv_transfer_config
        extra_config = kv_transfer_config.kv_connector_extra_config

        if "handshake_port" not in extra_config or not extra_config["handshake_port"]:
            extra_config["handshake_port"] = MoRIIOConstants.DEFAULT_HANDSHAKE_PORT

        if "notify_port" not in extra_config or not extra_config["notify_port"]:
            extra_config["notify_port"] = MoRIIOConstants.DEFAULT_NOTIFY_PORT

    def get_num_new_matched_tokens(
        self, request: "Request", num_computed_tokens: int
    ) -> tuple[int, bool]:
        assert self.connector_scheduler is not None
        return self.connector_scheduler.get_num_new_matched_tokens(
            request, num_computed_tokens
        )

    def update_state_after_alloc(
        self, request: "Request", blocks: "KVCacheBlocks", num_external_tokens: int
    ):
        assert self.connector_scheduler is not None
        return self.connector_scheduler.update_state_after_alloc(
            request, blocks, num_external_tokens, self.connector_worker
        )

    def build_connector_meta(
        self,
        scheduler_output: SchedulerOutput,
    ) -> KVConnectorMetadata:
        assert self.connector_scheduler is not None
        return self.connector_scheduler.build_connector_meta(scheduler_output)

    def request_finished(
        self,
        request: "Request",
        block_ids: list[int],
    ) -> tuple[bool, dict[str, Any] | None]:
        assert self.connector_scheduler is not None
        return self.connector_scheduler.request_finished(request, block_ids)

    def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
        assert self.connector_scheduler is not None
        self.connector_scheduler.update_connector_output(connector_output)

    ############################################################
    # Worker Side Methods
    ############################################################
    def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
        assert self.connector_worker is not None
        self.connector_worker.register_kv_caches(kv_caches)

    def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]:
        """Get the finished recving and sending requests."""
        assert self.connector_worker is not None
        return self.connector_worker.get_finished()

    def start_load_kv(self, forward_context: "ForwardContext", **kwargs) -> None:
        assert self.connector_worker is not None
        if self.mode == MoRIIOMode.WRITE and get_role() == ROLE.CONSUMER:
            self.connector_worker.moriio_wrapper.async_wait_reqid()

        assert isinstance(self._connector_metadata, MoRIIOConnectorMetadata)
        self.connector_worker.start_load_kv(self._connector_metadata)

    def wait_for_layer_load(self, layer_name: str) -> None:
        assert self.connector_worker is not None
        self.connector_worker.wait_for_layer_load(layer_name)

    def save_kv_layer(
        self,
        layer_name: str,
        kv_layer: torch.Tensor,
        attn_metadata: "AttentionMetadata",
        **kwargs,
    ) -> None:
        # Only producer/prefill saves KV Cache
        if get_role() == ROLE.CONSUMER:
            return
        assert self.connector_worker is not None, (
            "save_kv_layer called on scheduler role"
        )

        assert isinstance(self._connector_metadata, MoRIIOConnectorMetadata), (
            "Connector metadata not initialized yet"
        )
        self.connector_worker.save_kv_layer(
            self._connector_metadata, layer_name, kv_layer, attn_metadata, **kwargs
        )

        return None

    def wait_for_save(self):
        if self.mode != MoRIIOMode.WRITE or get_role() != ROLE.PRODUCER:
            return
        assert self.connector_worker is not None
        assert isinstance(self._connector_metadata, MoRIIOConnectorMetadata), (
            "Connector metadata not initialized yet"
        )
        self.connector_worker.wait_for_save(self._connector_metadata)

    def shutdown(self):
        if self.connector_worker is not None:
            self.connector_worker.shutdown()
        if self.connector_scheduler is not None:
            self.connector_scheduler.shutdown()

    def has_connector_metadata(self) -> bool:
        """Check whether the connector metadata is currently set.

        Returns:
            bool: True if connector metadata exists, False otherwise.
        """
        try:
            return self._connector_metadata is not None
        except AttributeError:
            return False

get_finished(finished_req_ids)

Get the finished recving and sending requests.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def get_finished(self, finished_req_ids: set[str]) -> tuple[set[str], set[str]]:
    """Get the finished recving and sending requests."""
    assert self.connector_worker is not None
    return self.connector_worker.get_finished()

has_connector_metadata()

Check whether the connector metadata is currently set.

Returns:

  • bool ( bool ) –

    True if connector metadata exists, False otherwise.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def has_connector_metadata(self) -> bool:
    """Check whether the connector metadata is currently set.

    Returns:
        bool: True if connector metadata exists, False otherwise.
    """
    try:
        return self._connector_metadata is not None
    except AttributeError:
        return False

MoRIIOConnectorScheduler

Implementation of Scheduler side methods

Methods:

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
 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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
class MoRIIOConnectorScheduler:
    """Implementation of Scheduler side methods"""

    def __init__(self, vllm_config: VllmConfig, engine_id: str):
        self.vllm_config = vllm_config

        assert vllm_config.kv_transfer_config is not None, (
            "kv_transfer_config must be set for MoRIIOConnector"
        )
        self.kv_transfer_config = vllm_config.kv_transfer_config
        self.block_size = vllm_config.cache_config.block_size
        self.engine_id: EngineId = engine_id
        self.mode = get_moriio_mode(self.kv_transfer_config)
        self.host_ip = resolve_host_ip(
            self.kv_transfer_config.kv_connector_extra_config
        )
        self.handshake_port = self.kv_transfer_config.kv_connector_extra_config[
            "handshake_port"
        ]
        logger.info("Initializing MoRIIO Scheduler engine_id = %s", engine_id)

        self.side_notify_port = self.kv_transfer_config.kv_connector_extra_config[
            "notify_port"
        ]
        self.tp_size = self.vllm_config.parallel_config.tensor_parallel_size
        # Local DP rank (0..dp_local-1) for port arithmetic; fold_local_rank
        # handles the external-DP sentinel (dp_local==0) so the arithmetic
        # can't ZeroDivisionError at init.
        _pc = self.vllm_config.parallel_config
        self.dp_rank = fold_local_rank(
            _pc.data_parallel_rank, _pc.data_parallel_size_local
        )
        # Only first-pod ranks originate notify to avoid duplicates. Guarding
        # via pod_index keeps _is_kv_master True for the external-DP sentinel
        # (single pod) instead of being silently stuck False.
        self._is_kv_master = (
            pod_index(_pc.data_parallel_rank, _pc.data_parallel_size_local) == 0
        )
        # Global DP rank for pinned request ownership check.
        self._global_dp_rank = self.vllm_config.parallel_config.data_parallel_rank
        self.is_producer = self.kv_transfer_config.kv_role == "kv_producer"
        # Requests that need to start recv/send.
        # New requests are added by update_state_after_alloc in
        # the scheduler. Used to make metadata passed to Worker.
        self._reqs_need_recv: dict[ReqId, tuple[Request, list[int]]] = {}
        self._reqs_need_save: dict[ReqId, tuple[Request, list[int]]] = {}
        # Snapshot of kv_transfer_params for chunked prefill recovery.
        self._req_kv_params: dict[ReqId, dict] = {}

        # For chunked prefill, we perform layer-wise access within the final chunk.
        # TODO: Perform transfer at end chunk.
        self._reqs_need_pending_save: dict[ReqId, tuple[Request, list[int]]] = {}

        if self.is_producer:
            set_role(ROLE.PRODUCER)
        else:
            set_role(ROLE.CONSUMER)
        # Reqs to send and their expiration time
        self._reqs_need_send: dict[ReqId, float] = {}
        # Deadlines for requests whose block freeing was deferred.
        # Survives across scheduler steps. If the worker never reports
        # finished_sending before the deadline, we inject them into
        # connector_output.finished_sending so the scheduler frees the blocks to avoid
        # hanging indefinitely waiting for a free notification that never comes.
        # Value: (deadline, transfer_id) for unmapping after mutation.
        self._deferred_send_deadlines: dict[ReqId, tuple[float, TransferId | None]] = {}
        self._defer_timeout = float(
            self.kv_transfer_config.kv_connector_extra_config.get(
                "defer_timeout", MoRIIOConstants.DEFAULT_DEFER_TIMEOUT
            )
        )
        # Buffer for early ACKs that arrive before request_finished.
        self._pending_sent_acks: dict[ReqId, float] = {}
        self.paths: dict[str, zmq.Socket] = {}
        self.transfer_id_to_request_id: dict[TransferId, ReqId] = {}
        self.request_id_to_transfer_id: dict[ReqId, TransferId] = {}

    def map_request_id(self, request_id: ReqId, transfer_id: TransferId):
        self.transfer_id_to_request_id[transfer_id] = request_id
        self.request_id_to_transfer_id[request_id] = transfer_id

    def unmap_request_id(
        self, request_id: ReqId, transfer_id: TransferId | None = None
    ):
        """Unmap request_id/transfer_id. Uses transfer_id for lookup if
        exact request_id match fails (handles input_processor mutation)."""
        if request_id in self.request_id_to_transfer_id:
            tid = self.request_id_to_transfer_id[request_id]
            del self.request_id_to_transfer_id[request_id]
            if tid in self.transfer_id_to_request_id:
                del self.transfer_id_to_request_id[tid]
            return

        # Fallback: use transfer_id to find original request_id.
        if transfer_id is not None and transfer_id in self.transfer_id_to_request_id:
            original_rid = self.transfer_id_to_request_id[transfer_id]
            if original_rid != request_id:
                logger.debug(
                    "MoRI-IO unmap via transfer_id: %r -> %r", request_id, original_rid
                )
            if original_rid in self.request_id_to_transfer_id:
                del self.request_id_to_transfer_id[original_rid]
            del self.transfer_id_to_request_id[transfer_id]
            return

        logger.warning(
            "MoRI-IO unmap MISS: rid=%r transfer_id=%r table_size=%d",
            request_id,
            transfer_id,
            len(self.request_id_to_transfer_id),
        )

    def get_num_new_matched_tokens(
        self,
        request: "Request",
        num_computed_tokens: int,
    ) -> tuple[int, bool]:
        """
        For remote prefill, pull all prompt blocks from remote
        asynchronously relative to engine execution.

        Args:
            request (Request): the request object.
            num_computed_tokens (int): the number of locally
                computed tokens for this request
        Returns:
            * the number of tokens that can be loaded from the
              external KV cache beyond what is already computed.
            * true if the external KV cache tokens will be loaded
              asynchronously (between scheduler steps).
        """
        if self.is_producer:
            return 0, False

        token_ids = request.prompt_token_ids or []
        if self.mode == MoRIIOMode.WRITE:
            # MoriiO in write mode, no remote prefill

            return len(token_ids) - num_computed_tokens, True

        return len(token_ids) - 1 - num_computed_tokens, False

    def send_notify_block(
        self,
        req_id: ReqId,
        transfer_id: TransferId,
        block_notify_list: list[int],
        host=None,
        port=None,
    ):
        path = make_zmq_path("tcp", host, port)
        if path not in self.paths:
            ctx = zmq.Context.instance()
            sock = make_zmq_socket(
                ctx=ctx, path=path, socket_type=zmq.DEALER, bind=False
            )
            self.paths[path] = sock

        data = {
            "req_id": req_id,
            "transfer_id": transfer_id,
            "block_notify_list": block_notify_list or [],
            # GLOBAL decode dp rank: producer derives the per-pod notify offset
            # (% dp_local), owning pod index (// dp_local), and write-target
            # from it. Sending the LOCAL rank made child-pod consumers look
            # like master rank 0 and hang in WAITING_FOR_REMOTE_KVS. Single-pod:
            # local == global.
            "decode_rank": self._global_dp_rank,
            "type": "remote_blocks",
        }
        serialized_data = msgpack.dumps(data)
        self.paths[path].send(serialized_data)

    def _send_transfer_release(self, transfer_id: TransferId, host: str, port: int):
        path = make_zmq_path("tcp", host, port)
        if path not in self.paths:
            ctx = zmq.Context.instance()
            sock = make_zmq_socket(
                ctx=ctx, path=path, socket_type=zmq.DEALER, bind=False
            )
            self.paths[path] = sock

        # Advertise the consumer (decode) TP size so prefill counts the right
        # number of ACKs (get_moriio_expected_ack_count; see the upstream
        # READ-mode release in _pop_done_transfers). Resolves to 1 for our
        # homogeneous TP=1 configs; only matters under heterogeneous-TP fan-in.
        self.paths[path].send(
            msgpack.dumps(
                {
                    "type": "release",
                    "transfer_id": transfer_id,
                    "consumer_tp_size": self.tp_size,
                }
            )
        )

    def _release_write_prefill_blocks(self, request_id: ReqId, params: dict[str, Any]):
        transfer_id = params.get("transfer_id")
        if transfer_id is None:
            logger.warning(
                "Cannot release WRITE prefill blocks for request %s: "
                "missing transfer_id",
                request_id,
            )
            return

        remote_dp_rank = params.get("remote_dp_rank", 0)
        remote_host = params.get("remote_host")
        remote_notify_port = params.get("remote_notify_port")
        if remote_host is None or remote_notify_port is None:
            try:
                peer_zmq = get_peer_zmq_from_request_id(request_id, is_producer=False)
                if peer_zmq is None:
                    raise ValueError("no peer zmq address for request")
                remote_host, _, remote_notify_port = parse_moriio_zmq_address(peer_zmq)
            except ValueError:
                logger.warning(
                    "Cannot release WRITE prefill blocks for request %s: "
                    "missing remote notify address",
                    request_id,
                )
                return

        remote_notify_port = int(remote_notify_port)
        for tp_index in range(self.tp_size):
            target_port = remote_notify_port + get_port_offset(remote_dp_rank, tp_index)
            self._send_transfer_release(transfer_id, remote_host, target_port)

    def update_state_after_alloc(
        self,
        request: "Request",
        blocks: "KVCacheBlocks",
        num_external_tokens: int,
        connector_worker: "MoRIIOConnectorWorker | None" = None,
    ):
        """Scheduler-side post-allocation hook (decode leg in WRITE mode).

        In WRITE mode this fires the decode->prefill "blocks ready" notify
        that lets the producer RDMA-Write its KV into the freshly allocated
        decode blocks.

        DP-rank routing contract (router-authoritative)
        ------------------------------------------------
        Both legs of a disagg pair must agree on a single prefill DP rank,
        otherwise the notify lands on a rank that never handshook and the
        request hangs until ``VLLM_MORIIO_DEFERRED_TIMEOUT_S``.

        The routing authority is the external router/sidecar, NOT the
        connector. The llm-d routing sidecar computes ``H = pickDPRank(uuid,
        dp_size)`` (see ``dp_rank.go``) once and pins BOTH legs to ``H`` two
        ways: the ``X-data-parallel-rank`` dispatch header (which vLLM engine
        the leg lands on) and ``kv_transfer_params.remote_dp_rank=H`` (which
        prefill rank this notify targets), with ``remote_dp_rank_override=True``.

        The connector consumes ``remote_dp_rank`` verbatim and does NOT
        self-derive a rank: an independent hash here could disagree with the
        router's dispatch pin and misroute the notify. For the returnable paths
        (READ / serial WRITE) the prefill leg also echoes back the rank it ran
        on via ``request_finished`` so routing is pure propagation.

        The owning rank is the only one that originates the notify
        (``remote_dp_rank_override`` -> global-rank match; otherwise the
        ``_is_kv_master`` anti-duplicate gate). See the inline comments
        below for the exactly-once-across-pods reasoning.
        """
        params = request.kv_transfer_params
        if not params:
            return
        # LLM-D sidecar compat: the nixlv2 routing sidecar emits NIXL-shaped
        # kv_transfer_params without MoRI-IO's transfer_id. Synthesize one
        # deterministically from request_id so producer and consumer agree
        # without a sidecar wire-protocol change.
        transfer_id = params.get("transfer_id") or f"sidecar-{request.request_id}"
        params.setdefault("transfer_id", transfer_id)
        request_id = request.request_id
        self.map_request_id(request_id, transfer_id)
        if params.get("do_remote_decode"):
            local_block_ids = blocks.get_block_ids()[0]
            self._reqs_need_save[request.request_id] = (request, local_block_ids)
            # Snapshot params now so chunked-prefill build_connector_meta
            # can recover them on the final chunk even if the live
            # request.kv_transfer_params has been mutated/cleared.
            self._req_kv_params[request.request_id] = dict(params)

        if params is not None and params.get("do_remote_prefill"):
            if self.mode == MoRIIOMode.READ:
                if remote_block_ids := params.get("remote_block_ids"):
                    # remote_engine_id is returned by the prefill's request_finished.
                    # host/ports come from the request_id (parsed in add_new_req).
                    if "remote_engine_id" in params:
                        if num_external_tokens > 0:
                            # Get unhashed blocks to pull from remote.
                            local_block_ids = blocks.get_block_ids()[0]
                            assert len(local_block_ids) <= len(remote_block_ids)
                            if len(local_block_ids) != len(remote_block_ids):
                                local_block_ids = remote_block_ids[
                                    -len(local_block_ids) :
                                ]
                        else:
                            # If remote_blocks and num_external_tokens = 0, we have
                            # a full prefix cache hit on the D worker. We need to call
                            # send_notify in _read_blocks to free the memory on the P.
                            local_block_ids = []

                        self._reqs_need_recv[request.request_id] = (
                            request,
                            local_block_ids,
                        )
                        # Snapshot params for chunked prefill consumption
                        # in build_connector_meta (see comment above).
                        self._req_kv_params[request.request_id] = dict(params)
                    else:
                        logger.warning(
                            "Got invalid KVTransferParams: %s. This "
                            "request will not utilize KVTransfer",
                            params,
                        )

            else:
                # WRITE mode, decode side: notify P that blocks are ready
                assert request.kv_transfer_params is not None, (
                    "kv_transfer_params should not be None"
                )

                remote_dp_rank = request.kv_transfer_params.get("remote_dp_rank", 0)

                # Effective DP fan-out for the per-pod port/host math below
                # (see _remote_dp_rank_for_port / _pod_idx). Capped to the
                # per-pod local size when the router advertises it (Wide-EP).
                _dp_size = int(request.kv_transfer_params.get("remote_dp_size", 1) or 1)
                try:
                    _dp_local = int(
                        request.kv_transfer_params.get("remote_dp_size_local", 0) or 0
                    )
                    if _dp_local > 0:
                        _dp_size = min(_dp_size, _dp_local)
                except (TypeError, ValueError):
                    _dp_local = 0

                # Rank routing is ROUTER-AUTHORITATIVE: honor the router-pinned
                # remote_dp_rank (matched to the X-data-parallel-rank dispatch
                # pin). Self-deriving a rank could disagree and notify a rank
                # that never served the request. If unpinned in a multi-rank
                # deployment, warn instead of guessing.
                if (
                    _dp_size > 1
                    and "remote_dp_rank" not in request.kv_transfer_params
                    and "is_request_leader" not in request.kv_transfer_params
                ):
                    logger.warning(
                        "MoRI-IO decode notify: remote_dp_size=%d but the router "
                        "did not pin remote_dp_rank for request %s; defaulting to "
                        "rank 0. The router must set remote_dp_rank (and the "
                        "X-data-parallel-rank dispatch header) so the prefill and "
                        "decode legs agree on the same rank.",
                        _dp_size,
                        request.request_id,
                    )

                # Only the owning rank originates notify (exactly-once).
                # Priority: is_request_leader > remote_dp_rank_override > _is_kv_master
                _leader_flag = request.kv_transfer_params.get("is_request_leader")
                if _leader_flag is not None:
                    _should_notify = bool(_leader_flag)
                elif request.kv_transfer_params.get("remote_dp_rank_override"):
                    _should_notify = self._global_dp_rank == remote_dp_rank
                else:
                    _should_notify = self._is_kv_master
                if _should_notify:
                    peer_zmq = get_peer_zmq_from_request_id(
                        request.request_id, is_producer=False
                    )
                    if peer_zmq is not None:
                        remote_host, _, remote_notify_port = parse_moriio_zmq_address(
                            peer_zmq
                        )
                    else:
                        # Sidecar fallback: use explicit params fields.
                        params = request.kv_transfer_params or {}
                        remote_host = params.get("remote_host") or ""
                        try:
                            remote_notify_port = int(
                                params.get("remote_notify_port") or 0
                            )
                        except (TypeError, ValueError):
                            remote_notify_port = 0
                        if not remote_host or not remote_notify_port:
                            raise ValueError(
                                f"request {request.request_id!r}: "
                                f"request_id has no embedded peer "
                                f"zmq_address and kv_transfer_params is "
                                f"missing remote_host / remote_notify_port "
                                f"(got remote_host={remote_host!r}, "
                                f"remote_notify_port={remote_notify_port!r})"
                            )

                    # num_external_tokens == 0: nothing to push, so don't tell
                    # the producer to write into these blocks.
                    block_notify_list = (
                        blocks.get_block_ids()[0] if num_external_tokens > 0 else []
                    )

                    # Wide-EP multi-pod: a pod binds notify sockets only for
                    # its LOCAL ranks, so the port offset must use the per-pod
                    # local rank (% dp_local), not the global rank. Single-pod
                    # is bit-identical (modulus is a no-op).
                    _remote_dp_rank_for_port = fold_local_rank(
                        remote_dp_rank, _dp_local
                    )
                    # The target rank may live on a child pod at a different IP,
                    # so resolve the per-pod host (pod_idx = global // dp_local).
                    # Otherwise a notify for child ranks lands on the master
                    # pod and the request hangs in WAITING_FOR_REMOTE_KVS.
                    _notify_host = remote_host
                    _kvp = request.kv_transfer_params or {}
                    _remote_hosts = _kvp.get("remote_hosts") or []
                    if _dp_local > 0 and _remote_hosts:
                        _pod_idx = pod_index(remote_dp_rank, _dp_local)
                        if 0 <= _pod_idx < len(_remote_hosts):
                            _notify_host = _remote_hosts[_pod_idx]
                    for tp_index in range(self.tp_size):
                        target_port = remote_notify_port + get_port_offset(
                            _remote_dp_rank_for_port, tp_index
                        )

                        self.send_notify_block(
                            req_id=request.request_id,
                            transfer_id=request.kv_transfer_params["transfer_id"],
                            block_notify_list=block_notify_list,
                            host=_notify_host,
                            port=target_port,
                        )

            # Only trigger 1 KV transfer per request.

            params["do_remote_prefill"] = False

    def build_connector_meta(
        self,
        scheduler_output: SchedulerOutput,
    ) -> KVConnectorMetadata:
        meta = MoRIIOConnectorMetadata()
        meta.transfer_id_to_request_id = self.transfer_id_to_request_id

        if self.mode == MoRIIOMode.WRITE and get_role() == ROLE.PRODUCER:
            # This is the logic for checking against chunked prefill.
            # When the last chunk is identified,
            # It places the request metadata into the saving queue.

            for i, req_id in enumerate(scheduler_output.scheduled_cached_reqs.req_ids):
                new_block_ids = scheduler_output.scheduled_cached_reqs.new_block_ids[i]

                if new_block_ids is not None:
                    block_ids = new_block_ids[0]
                    # TODO : hybrid attn, etc
                    # A non-disagg request (no kv_transfer_params, e.g. smoke
                    # test) is never registered in _reqs_need_pending_save;
                    # indexing it unconditionally would KeyError and crash the
                    # EngineCore. Skip it silently.
                    if req_id not in self._reqs_need_pending_save:
                        continue
                    req, existing_blocks = self._reqs_need_pending_save[req_id]
                    updated_blocks = list(existing_blocks) + (block_ids)
                    self._reqs_need_pending_save[req_id] = (req, updated_blocks)
                    if (
                        len(self._reqs_need_pending_save[req_id][1]) * self.block_size
                        >= req.num_prompt_tokens
                    ):
                        # Final chunk: live kv_transfer_params may be cleared,
                        # so prefer the snapshot from update_state_after_alloc.
                        kv_params = self._req_kv_params.pop(
                            req_id, req.kv_transfer_params or {}
                        )
                        meta.add_new_req(
                            request_id=req_id,
                            local_block_ids=self._reqs_need_pending_save[req_id][1],
                            kv_transfer_params=kv_params,
                            write_mode=True,
                        )
                        del self._reqs_need_pending_save[req_id]

        # Loop through scheduled reqs and convert to ReqMeta.
        for req_id, (req, block_ids) in self._reqs_need_recv.items():
            kv_params = self._req_kv_params.get(req_id, req.kv_transfer_params or {})
            meta.add_new_req(
                request_id=req_id,
                local_block_ids=block_ids,
                kv_transfer_params=kv_params,
            )

        for req_id, (req, block_ids) in self._reqs_need_save.items():
            kv_params = self._req_kv_params.get(req_id, req.kv_transfer_params or {})
            if req.num_prompt_tokens > len(block_ids) * self.block_size:
                # not last chunk prefill
                self._reqs_need_pending_save[req_id] = (req, block_ids)
                continue
            meta.add_new_req(
                request_id=req_id,
                local_block_ids=block_ids,
                kv_transfer_params=kv_params,
                write_mode=True,
            )
        # Clear the list once workers start the transfers

        meta.reqs_to_send = self._reqs_need_send

        # Reclaim snapshot cache entries that completed this step. Keep
        # entries that are still pending (chunked prefill not yet at the
        # final chunk) — those will be popped above on the final chunk.
        for req_id in self._reqs_need_recv:
            self._req_kv_params.pop(req_id, None)
        for req_id in self._reqs_need_save:
            if req_id not in self._reqs_need_pending_save:
                self._req_kv_params.pop(req_id, None)

        self._reqs_need_recv.clear()
        self._reqs_need_save.clear()
        self._reqs_need_send = {}

        return meta

    def shutdown(self):
        for path, sock in self.paths.items():
            try:
                sock.close(linger=0)
                logger.debug("Closed ZMQ socket for path: %s", path)
            except Exception as e:
                logger.warning("Error closing ZMQ socket for path %s: %s", path, e)
        self.paths.clear()

    def request_finished(
        self,
        request: "Request",
        block_ids: list[int],
    ) -> tuple[bool, dict[str, Any] | None]:
        """
        Once a request is finished, determine whether request blocks
        should be freed now or will be sent asynchronously and freed later.
        """

        request_id = request.request_id
        params = request.kv_transfer_params
        # Consumer: can unmap transfer_id<->request_id immediately since done_recving
        #   has fired at this point (i.e. KV has been transferred)
        # Producer: must keep the mapping until we get notification that blocks can
        #   be freed, which may be several scheduler steps later.
        if not self.is_producer:
            transfer_id = params.get("transfer_id") if params else None
            self.unmap_request_id(request_id, transfer_id=transfer_id)
        logger.debug(
            "MoriioConnector request_finished, request_status=%s, "
            "kv_transfer_params=%s",
            request.status,
            params,
        )
        if not params:
            return False, None

        if params.get("do_remote_prefill"):
            # If do_remote_prefill is still True when the request is finished,
            # update_state_after_alloc must not have been called (the request
            # must have been aborted before it was scheduled).
            # To avoid stranding the prefill blocks in the prefill instance,
            # READ mode adds empty block_ids to _reqs_need_recv so the worker
            # side notifies the prefill instance. WRITE mode should notify the
            # producer directly: there is no decode allocation for the producer
            # to write into, and a plain request_id may not contain router-
            # embedded MoRIIO ZMQ addresses.
            if self.mode == MoRIIOMode.WRITE:
                self._release_write_prefill_blocks(request.request_id, params)
            else:
                self._reqs_need_recv[request.request_id] = (request, [])
            params["do_remote_prefill"] = False
            return False, None

        if (
            not params.get("do_remote_decode")
            or request.status != RequestStatus.FINISHED_LENGTH_CAPPED
        ):
            return False, None

        # computed_block_ids = block_ids if all_full else block_ids[:-1]
        computed_block_ids = block_ids
        # If prompt < block_size, no xfer so free blocks immediately.
        delay_free_blocks = len(computed_block_ids) > 0

        if delay_free_blocks:
            # Prefill request on remote. It will be read from D upon completion
            self._reqs_need_send[request.request_id] = (
                time.perf_counter()
                + MoRIIOConstants.VLLM_MORI_READ_ABORT_REQUEST_TIMEOUT
            )
            self._deferred_send_deadlines[request.request_id] = (
                time.monotonic() + self._defer_timeout,
                params.get("transfer_id") if params else None,
            )

        # Return KV transfer params forwarded verbatim to the decode instance by
        # the router. remote_dp_rank is the rank THIS prefill leg actually ran
        # on: on the returnable paths (READ / serial WRITE) the router forwards
        # it to the decode leg, so the decode->prefill notify is routed by pure
        # propagation of the producer's real rank -- no hashing, no reliance on
        # the router independently pinning the same rank. remote_dp_rank_override
        # makes the decode side honor it via the global-rank match gate.
        return delay_free_blocks, dict(
            do_remote_prefill=True,
            do_remote_decode=False,
            remote_block_ids=computed_block_ids,
            remote_engine_id=self.engine_id,
            remote_host=self.host_ip,
            remote_handshake_port=self.handshake_port,
            remote_notify_port=self.side_notify_port,
            remote_dp_rank=self._global_dp_rank,
            remote_dp_rank_override=True,
            remote_dp_size=self.vllm_config.parallel_config.data_parallel_size,
            remote_dp_size_local=(
                self.vllm_config.parallel_config.data_parallel_size_local
            ),
            tp_size=self.vllm_config.parallel_config.tensor_parallel_size,
            transfer_id=params["transfer_id"],
        )

    def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
        """Reconcile worker finished_sending ACKs with the producer lifecycle.

        Called every scheduler step (when there is KV connector output),
        BEFORE the scheduler's finished_sending free loop. We rewrite
        ``connector_output.finished_sending`` in place so it contains
        exactly the producer requests that are safe for the scheduler to
        free this step, letting the scheduler keep the plain upstream
        ``assert req_id in self.requests`` + ``_free_blocks`` path:

        * An ACK whose request is in ``_deferred_send_deadlines``
          (request_finished ran with delay_free_blocks=True, so the
          scheduler is holding its blocks) is surfaced -> freed now.
        * An ACK that arrives BEFORE its request finished is parked in
          ``_pending_sent_acks`` and released on a later step once the
          request enters ``_deferred_send_deadlines``.
        * A deferred send whose ACK never arrives is reaped after
          ``_defer_timeout`` and surfaced, so leaked blocks are freed.
        * A parked ACK that never matches a deferral before its own
          deadline is a stale duplicate (e.g. a real ACK landing after the
          send was already reaped) and is dropped.

        Consumers never populate finished_sending (they report
        finished_recving), and they unmap in request_finished, so this is a
        no-op for them.
        """
        if not self.is_producer:
            return

        incoming = set(connector_output.finished_sending or ())
        now = time.monotonic()

        # Surface ACKs whose request is already finished (blocks held for
        # delayed free); park the rest until their request finishes.
        safe: set[ReqId] = set()
        for req_id in incoming:
            if req_id in self._deferred_send_deadlines:
                safe.add(req_id)
            else:
                self._pending_sent_acks.setdefault(req_id, now + self._defer_timeout)

        # Release previously parked ACKs whose request has since finished.
        for req_id in self._pending_sent_acks:
            if req_id in self._deferred_send_deadlines:
                safe.add(req_id)

        # Reap deferred sends whose ACK never arrived (avoid leaking blocks).
        expired = [
            req_id
            for req_id, (deadline, _) in self._deferred_send_deadlines.items()
            if now >= deadline
        ]
        if expired:
            safe.update(expired)
            logger.warning(
                "Reaped %d deferred sends with no finished_sending "
                "notification after %.0fs. This indicates lost async KV "
                "completion notifications from the KV connector.",
                len(expired),
                self._defer_timeout,
            )

        # Finalize the requests we are surfacing: drop their deferral/park
        # bookkeeping and unmap their transfer ids.
        for req_id in safe:
            deferred_info = self._deferred_send_deadlines.pop(req_id, None)
            transfer_id = deferred_info[1] if deferred_info else None
            self._pending_sent_acks.pop(req_id, None)
            self.unmap_request_id(req_id, transfer_id=transfer_id)

        # Drop stale parked ACKs that never matched a deferral in time.
        stale = [
            req_id
            for req_id, deadline in self._pending_sent_acks.items()
            if now >= deadline
        ]
        for req_id in stale:
            self._pending_sent_acks.pop(req_id, None)

        connector_output.finished_sending = safe or None

get_num_new_matched_tokens(request, num_computed_tokens)

For remote prefill, pull all prompt blocks from remote asynchronously relative to engine execution.

Parameters:

  • request

    (Request) –

    the request object.

  • num_computed_tokens

    (int) –

    the number of locally computed tokens for this request

Returns: * the number of tokens that can be loaded from the external KV cache beyond what is already computed. * true if the external KV cache tokens will be loaded asynchronously (between scheduler steps).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def get_num_new_matched_tokens(
    self,
    request: "Request",
    num_computed_tokens: int,
) -> tuple[int, bool]:
    """
    For remote prefill, pull all prompt blocks from remote
    asynchronously relative to engine execution.

    Args:
        request (Request): the request object.
        num_computed_tokens (int): the number of locally
            computed tokens for this request
    Returns:
        * the number of tokens that can be loaded from the
          external KV cache beyond what is already computed.
        * true if the external KV cache tokens will be loaded
          asynchronously (between scheduler steps).
    """
    if self.is_producer:
        return 0, False

    token_ids = request.prompt_token_ids or []
    if self.mode == MoRIIOMode.WRITE:
        # MoriiO in write mode, no remote prefill

        return len(token_ids) - num_computed_tokens, True

    return len(token_ids) - 1 - num_computed_tokens, False

request_finished(request, block_ids)

Once a request is finished, determine whether request blocks should be freed now or will be sent asynchronously and freed later.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def request_finished(
    self,
    request: "Request",
    block_ids: list[int],
) -> tuple[bool, dict[str, Any] | None]:
    """
    Once a request is finished, determine whether request blocks
    should be freed now or will be sent asynchronously and freed later.
    """

    request_id = request.request_id
    params = request.kv_transfer_params
    # Consumer: can unmap transfer_id<->request_id immediately since done_recving
    #   has fired at this point (i.e. KV has been transferred)
    # Producer: must keep the mapping until we get notification that blocks can
    #   be freed, which may be several scheduler steps later.
    if not self.is_producer:
        transfer_id = params.get("transfer_id") if params else None
        self.unmap_request_id(request_id, transfer_id=transfer_id)
    logger.debug(
        "MoriioConnector request_finished, request_status=%s, "
        "kv_transfer_params=%s",
        request.status,
        params,
    )
    if not params:
        return False, None

    if params.get("do_remote_prefill"):
        # If do_remote_prefill is still True when the request is finished,
        # update_state_after_alloc must not have been called (the request
        # must have been aborted before it was scheduled).
        # To avoid stranding the prefill blocks in the prefill instance,
        # READ mode adds empty block_ids to _reqs_need_recv so the worker
        # side notifies the prefill instance. WRITE mode should notify the
        # producer directly: there is no decode allocation for the producer
        # to write into, and a plain request_id may not contain router-
        # embedded MoRIIO ZMQ addresses.
        if self.mode == MoRIIOMode.WRITE:
            self._release_write_prefill_blocks(request.request_id, params)
        else:
            self._reqs_need_recv[request.request_id] = (request, [])
        params["do_remote_prefill"] = False
        return False, None

    if (
        not params.get("do_remote_decode")
        or request.status != RequestStatus.FINISHED_LENGTH_CAPPED
    ):
        return False, None

    # computed_block_ids = block_ids if all_full else block_ids[:-1]
    computed_block_ids = block_ids
    # If prompt < block_size, no xfer so free blocks immediately.
    delay_free_blocks = len(computed_block_ids) > 0

    if delay_free_blocks:
        # Prefill request on remote. It will be read from D upon completion
        self._reqs_need_send[request.request_id] = (
            time.perf_counter()
            + MoRIIOConstants.VLLM_MORI_READ_ABORT_REQUEST_TIMEOUT
        )
        self._deferred_send_deadlines[request.request_id] = (
            time.monotonic() + self._defer_timeout,
            params.get("transfer_id") if params else None,
        )

    # Return KV transfer params forwarded verbatim to the decode instance by
    # the router. remote_dp_rank is the rank THIS prefill leg actually ran
    # on: on the returnable paths (READ / serial WRITE) the router forwards
    # it to the decode leg, so the decode->prefill notify is routed by pure
    # propagation of the producer's real rank -- no hashing, no reliance on
    # the router independently pinning the same rank. remote_dp_rank_override
    # makes the decode side honor it via the global-rank match gate.
    return delay_free_blocks, dict(
        do_remote_prefill=True,
        do_remote_decode=False,
        remote_block_ids=computed_block_ids,
        remote_engine_id=self.engine_id,
        remote_host=self.host_ip,
        remote_handshake_port=self.handshake_port,
        remote_notify_port=self.side_notify_port,
        remote_dp_rank=self._global_dp_rank,
        remote_dp_rank_override=True,
        remote_dp_size=self.vllm_config.parallel_config.data_parallel_size,
        remote_dp_size_local=(
            self.vllm_config.parallel_config.data_parallel_size_local
        ),
        tp_size=self.vllm_config.parallel_config.tensor_parallel_size,
        transfer_id=params["transfer_id"],
    )

unmap_request_id(request_id, transfer_id=None)

Unmap request_id/transfer_id. Uses transfer_id for lookup if exact request_id match fails (handles input_processor mutation).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def unmap_request_id(
    self, request_id: ReqId, transfer_id: TransferId | None = None
):
    """Unmap request_id/transfer_id. Uses transfer_id for lookup if
    exact request_id match fails (handles input_processor mutation)."""
    if request_id in self.request_id_to_transfer_id:
        tid = self.request_id_to_transfer_id[request_id]
        del self.request_id_to_transfer_id[request_id]
        if tid in self.transfer_id_to_request_id:
            del self.transfer_id_to_request_id[tid]
        return

    # Fallback: use transfer_id to find original request_id.
    if transfer_id is not None and transfer_id in self.transfer_id_to_request_id:
        original_rid = self.transfer_id_to_request_id[transfer_id]
        if original_rid != request_id:
            logger.debug(
                "MoRI-IO unmap via transfer_id: %r -> %r", request_id, original_rid
            )
        if original_rid in self.request_id_to_transfer_id:
            del self.request_id_to_transfer_id[original_rid]
        del self.transfer_id_to_request_id[transfer_id]
        return

    logger.warning(
        "MoRI-IO unmap MISS: rid=%r transfer_id=%r table_size=%d",
        request_id,
        transfer_id,
        len(self.request_id_to_transfer_id),
    )

update_connector_output(connector_output)

Reconcile worker finished_sending ACKs with the producer lifecycle.

Called every scheduler step (when there is KV connector output), BEFORE the scheduler's finished_sending free loop. We rewrite connector_output.finished_sending in place so it contains exactly the producer requests that are safe for the scheduler to free this step, letting the scheduler keep the plain upstream assert req_id in self.requests + _free_blocks path:

  • An ACK whose request is in _deferred_send_deadlines (request_finished ran with delay_free_blocks=True, so the scheduler is holding its blocks) is surfaced -> freed now.
  • An ACK that arrives BEFORE its request finished is parked in _pending_sent_acks and released on a later step once the request enters _deferred_send_deadlines.
  • A deferred send whose ACK never arrives is reaped after _defer_timeout and surfaced, so leaked blocks are freed.
  • A parked ACK that never matches a deferral before its own deadline is a stale duplicate (e.g. a real ACK landing after the send was already reaped) and is dropped.

Consumers never populate finished_sending (they report finished_recving), and they unmap in request_finished, so this is a no-op for them.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def update_connector_output(self, connector_output: KVConnectorOutput) -> None:
    """Reconcile worker finished_sending ACKs with the producer lifecycle.

    Called every scheduler step (when there is KV connector output),
    BEFORE the scheduler's finished_sending free loop. We rewrite
    ``connector_output.finished_sending`` in place so it contains
    exactly the producer requests that are safe for the scheduler to
    free this step, letting the scheduler keep the plain upstream
    ``assert req_id in self.requests`` + ``_free_blocks`` path:

    * An ACK whose request is in ``_deferred_send_deadlines``
      (request_finished ran with delay_free_blocks=True, so the
      scheduler is holding its blocks) is surfaced -> freed now.
    * An ACK that arrives BEFORE its request finished is parked in
      ``_pending_sent_acks`` and released on a later step once the
      request enters ``_deferred_send_deadlines``.
    * A deferred send whose ACK never arrives is reaped after
      ``_defer_timeout`` and surfaced, so leaked blocks are freed.
    * A parked ACK that never matches a deferral before its own
      deadline is a stale duplicate (e.g. a real ACK landing after the
      send was already reaped) and is dropped.

    Consumers never populate finished_sending (they report
    finished_recving), and they unmap in request_finished, so this is a
    no-op for them.
    """
    if not self.is_producer:
        return

    incoming = set(connector_output.finished_sending or ())
    now = time.monotonic()

    # Surface ACKs whose request is already finished (blocks held for
    # delayed free); park the rest until their request finishes.
    safe: set[ReqId] = set()
    for req_id in incoming:
        if req_id in self._deferred_send_deadlines:
            safe.add(req_id)
        else:
            self._pending_sent_acks.setdefault(req_id, now + self._defer_timeout)

    # Release previously parked ACKs whose request has since finished.
    for req_id in self._pending_sent_acks:
        if req_id in self._deferred_send_deadlines:
            safe.add(req_id)

    # Reap deferred sends whose ACK never arrived (avoid leaking blocks).
    expired = [
        req_id
        for req_id, (deadline, _) in self._deferred_send_deadlines.items()
        if now >= deadline
    ]
    if expired:
        safe.update(expired)
        logger.warning(
            "Reaped %d deferred sends with no finished_sending "
            "notification after %.0fs. This indicates lost async KV "
            "completion notifications from the KV connector.",
            len(expired),
            self._defer_timeout,
        )

    # Finalize the requests we are surfacing: drop their deferral/park
    # bookkeeping and unmap their transfer ids.
    for req_id in safe:
        deferred_info = self._deferred_send_deadlines.pop(req_id, None)
        transfer_id = deferred_info[1] if deferred_info else None
        self._pending_sent_acks.pop(req_id, None)
        self.unmap_request_id(req_id, transfer_id=transfer_id)

    # Drop stale parked ACKs that never matched a deferral in time.
    stale = [
        req_id
        for req_id, deadline in self._pending_sent_acks.items()
        if now >= deadline
    ]
    for req_id in stale:
        self._pending_sent_acks.pop(req_id, None)

    connector_output.finished_sending = safe or None

update_state_after_alloc(request, blocks, num_external_tokens, connector_worker=None)

Scheduler-side post-allocation hook (decode leg in WRITE mode).

In WRITE mode this fires the decode->prefill "blocks ready" notify that lets the producer RDMA-Write its KV into the freshly allocated decode blocks.

DP-rank routing contract (router-authoritative)

Both legs of a disagg pair must agree on a single prefill DP rank, otherwise the notify lands on a rank that never handshook and the request hangs until VLLM_MORIIO_DEFERRED_TIMEOUT_S.

The routing authority is the external router/sidecar, NOT the connector. The llm-d routing sidecar computes H = pickDPRank(uuid, dp_size) (see dp_rank.go) once and pins BOTH legs to H two ways: the X-data-parallel-rank dispatch header (which vLLM engine the leg lands on) and kv_transfer_params.remote_dp_rank=H (which prefill rank this notify targets), with remote_dp_rank_override=True.

The connector consumes remote_dp_rank verbatim and does NOT self-derive a rank: an independent hash here could disagree with the router's dispatch pin and misroute the notify. For the returnable paths (READ / serial WRITE) the prefill leg also echoes back the rank it ran on via request_finished so routing is pure propagation.

The owning rank is the only one that originates the notify (remote_dp_rank_override -> global-rank match; otherwise the _is_kv_master anti-duplicate gate). See the inline comments below for the exactly-once-across-pods reasoning.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def update_state_after_alloc(
    self,
    request: "Request",
    blocks: "KVCacheBlocks",
    num_external_tokens: int,
    connector_worker: "MoRIIOConnectorWorker | None" = None,
):
    """Scheduler-side post-allocation hook (decode leg in WRITE mode).

    In WRITE mode this fires the decode->prefill "blocks ready" notify
    that lets the producer RDMA-Write its KV into the freshly allocated
    decode blocks.

    DP-rank routing contract (router-authoritative)
    ------------------------------------------------
    Both legs of a disagg pair must agree on a single prefill DP rank,
    otherwise the notify lands on a rank that never handshook and the
    request hangs until ``VLLM_MORIIO_DEFERRED_TIMEOUT_S``.

    The routing authority is the external router/sidecar, NOT the
    connector. The llm-d routing sidecar computes ``H = pickDPRank(uuid,
    dp_size)`` (see ``dp_rank.go``) once and pins BOTH legs to ``H`` two
    ways: the ``X-data-parallel-rank`` dispatch header (which vLLM engine
    the leg lands on) and ``kv_transfer_params.remote_dp_rank=H`` (which
    prefill rank this notify targets), with ``remote_dp_rank_override=True``.

    The connector consumes ``remote_dp_rank`` verbatim and does NOT
    self-derive a rank: an independent hash here could disagree with the
    router's dispatch pin and misroute the notify. For the returnable paths
    (READ / serial WRITE) the prefill leg also echoes back the rank it ran
    on via ``request_finished`` so routing is pure propagation.

    The owning rank is the only one that originates the notify
    (``remote_dp_rank_override`` -> global-rank match; otherwise the
    ``_is_kv_master`` anti-duplicate gate). See the inline comments
    below for the exactly-once-across-pods reasoning.
    """
    params = request.kv_transfer_params
    if not params:
        return
    # LLM-D sidecar compat: the nixlv2 routing sidecar emits NIXL-shaped
    # kv_transfer_params without MoRI-IO's transfer_id. Synthesize one
    # deterministically from request_id so producer and consumer agree
    # without a sidecar wire-protocol change.
    transfer_id = params.get("transfer_id") or f"sidecar-{request.request_id}"
    params.setdefault("transfer_id", transfer_id)
    request_id = request.request_id
    self.map_request_id(request_id, transfer_id)
    if params.get("do_remote_decode"):
        local_block_ids = blocks.get_block_ids()[0]
        self._reqs_need_save[request.request_id] = (request, local_block_ids)
        # Snapshot params now so chunked-prefill build_connector_meta
        # can recover them on the final chunk even if the live
        # request.kv_transfer_params has been mutated/cleared.
        self._req_kv_params[request.request_id] = dict(params)

    if params is not None and params.get("do_remote_prefill"):
        if self.mode == MoRIIOMode.READ:
            if remote_block_ids := params.get("remote_block_ids"):
                # remote_engine_id is returned by the prefill's request_finished.
                # host/ports come from the request_id (parsed in add_new_req).
                if "remote_engine_id" in params:
                    if num_external_tokens > 0:
                        # Get unhashed blocks to pull from remote.
                        local_block_ids = blocks.get_block_ids()[0]
                        assert len(local_block_ids) <= len(remote_block_ids)
                        if len(local_block_ids) != len(remote_block_ids):
                            local_block_ids = remote_block_ids[
                                -len(local_block_ids) :
                            ]
                    else:
                        # If remote_blocks and num_external_tokens = 0, we have
                        # a full prefix cache hit on the D worker. We need to call
                        # send_notify in _read_blocks to free the memory on the P.
                        local_block_ids = []

                    self._reqs_need_recv[request.request_id] = (
                        request,
                        local_block_ids,
                    )
                    # Snapshot params for chunked prefill consumption
                    # in build_connector_meta (see comment above).
                    self._req_kv_params[request.request_id] = dict(params)
                else:
                    logger.warning(
                        "Got invalid KVTransferParams: %s. This "
                        "request will not utilize KVTransfer",
                        params,
                    )

        else:
            # WRITE mode, decode side: notify P that blocks are ready
            assert request.kv_transfer_params is not None, (
                "kv_transfer_params should not be None"
            )

            remote_dp_rank = request.kv_transfer_params.get("remote_dp_rank", 0)

            # Effective DP fan-out for the per-pod port/host math below
            # (see _remote_dp_rank_for_port / _pod_idx). Capped to the
            # per-pod local size when the router advertises it (Wide-EP).
            _dp_size = int(request.kv_transfer_params.get("remote_dp_size", 1) or 1)
            try:
                _dp_local = int(
                    request.kv_transfer_params.get("remote_dp_size_local", 0) or 0
                )
                if _dp_local > 0:
                    _dp_size = min(_dp_size, _dp_local)
            except (TypeError, ValueError):
                _dp_local = 0

            # Rank routing is ROUTER-AUTHORITATIVE: honor the router-pinned
            # remote_dp_rank (matched to the X-data-parallel-rank dispatch
            # pin). Self-deriving a rank could disagree and notify a rank
            # that never served the request. If unpinned in a multi-rank
            # deployment, warn instead of guessing.
            if (
                _dp_size > 1
                and "remote_dp_rank" not in request.kv_transfer_params
                and "is_request_leader" not in request.kv_transfer_params
            ):
                logger.warning(
                    "MoRI-IO decode notify: remote_dp_size=%d but the router "
                    "did not pin remote_dp_rank for request %s; defaulting to "
                    "rank 0. The router must set remote_dp_rank (and the "
                    "X-data-parallel-rank dispatch header) so the prefill and "
                    "decode legs agree on the same rank.",
                    _dp_size,
                    request.request_id,
                )

            # Only the owning rank originates notify (exactly-once).
            # Priority: is_request_leader > remote_dp_rank_override > _is_kv_master
            _leader_flag = request.kv_transfer_params.get("is_request_leader")
            if _leader_flag is not None:
                _should_notify = bool(_leader_flag)
            elif request.kv_transfer_params.get("remote_dp_rank_override"):
                _should_notify = self._global_dp_rank == remote_dp_rank
            else:
                _should_notify = self._is_kv_master
            if _should_notify:
                peer_zmq = get_peer_zmq_from_request_id(
                    request.request_id, is_producer=False
                )
                if peer_zmq is not None:
                    remote_host, _, remote_notify_port = parse_moriio_zmq_address(
                        peer_zmq
                    )
                else:
                    # Sidecar fallback: use explicit params fields.
                    params = request.kv_transfer_params or {}
                    remote_host = params.get("remote_host") or ""
                    try:
                        remote_notify_port = int(
                            params.get("remote_notify_port") or 0
                        )
                    except (TypeError, ValueError):
                        remote_notify_port = 0
                    if not remote_host or not remote_notify_port:
                        raise ValueError(
                            f"request {request.request_id!r}: "
                            f"request_id has no embedded peer "
                            f"zmq_address and kv_transfer_params is "
                            f"missing remote_host / remote_notify_port "
                            f"(got remote_host={remote_host!r}, "
                            f"remote_notify_port={remote_notify_port!r})"
                        )

                # num_external_tokens == 0: nothing to push, so don't tell
                # the producer to write into these blocks.
                block_notify_list = (
                    blocks.get_block_ids()[0] if num_external_tokens > 0 else []
                )

                # Wide-EP multi-pod: a pod binds notify sockets only for
                # its LOCAL ranks, so the port offset must use the per-pod
                # local rank (% dp_local), not the global rank. Single-pod
                # is bit-identical (modulus is a no-op).
                _remote_dp_rank_for_port = fold_local_rank(
                    remote_dp_rank, _dp_local
                )
                # The target rank may live on a child pod at a different IP,
                # so resolve the per-pod host (pod_idx = global // dp_local).
                # Otherwise a notify for child ranks lands on the master
                # pod and the request hangs in WAITING_FOR_REMOTE_KVS.
                _notify_host = remote_host
                _kvp = request.kv_transfer_params or {}
                _remote_hosts = _kvp.get("remote_hosts") or []
                if _dp_local > 0 and _remote_hosts:
                    _pod_idx = pod_index(remote_dp_rank, _dp_local)
                    if 0 <= _pod_idx < len(_remote_hosts):
                        _notify_host = _remote_hosts[_pod_idx]
                for tp_index in range(self.tp_size):
                    target_port = remote_notify_port + get_port_offset(
                        _remote_dp_rank_for_port, tp_index
                    )

                    self.send_notify_block(
                        req_id=request.request_id,
                        transfer_id=request.kv_transfer_params["transfer_id"],
                        block_notify_list=block_notify_list,
                        host=_notify_host,
                        port=target_port,
                    )

        # Only trigger 1 KV transfer per request.

        params["do_remote_prefill"] = False

MoRIIOConnectorWorker

Implementation of Worker side methods

Methods:

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
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
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
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
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
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
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
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
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
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
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
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
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
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
2487
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
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
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
class MoRIIOConnectorWorker:
    """Implementation of Worker side methods"""

    def __init__(
        self,
        vllm_config: VllmConfig,
        engine_id: str,
        kv_cache_config: "KVCacheConfig",
    ):
        if not is_moriio_available():
            raise RuntimeError(
                "MoRIIO is not available. Please ensure the 'mori' package "
                "is installed and properly configured."
            )

        assert vllm_config.kv_transfer_config is not None
        self.moriio_config = MoRIIOConfig.from_vllm_config(vllm_config)
        self.mode = (
            MoRIIOMode.READ if self.moriio_config.read_mode else MoRIIOMode.WRITE
        )

        logger.info("Initializing MoRIIO worker %s", engine_id)

        logging.getLogger("aiter").disabled = True

        # Config.
        self.vllm_config = vllm_config
        assert vllm_config.kv_transfer_config is not None, (
            "kv_transfer_config must be set for MoRIIOConnector"
        )
        self.kv_transfer_config = vllm_config.kv_transfer_config
        self.is_producer = self.kv_transfer_config.is_kv_producer
        self.layer_to_spec = build_layer_to_spec(kv_cache_config)

        if self.is_producer:
            set_role(ROLE.PRODUCER)
        else:
            set_role(ROLE.CONSUMER)
        # mori engine
        self._rank = get_world_group().rank
        self._local_rank = get_world_group().local_rank
        self.tp_rank = self.moriio_config.tp_rank
        self.dp_rank = self.moriio_config.dp_rank

        self.local_ip = self.moriio_config.local_ip
        self.local_kv_port = self.moriio_config.local_kv_port
        self.proxy_ip = self.moriio_config.proxy_ip
        self.local_ping_port = self.moriio_config.local_ping_port
        self.proxy_ping_port = self.moriio_config.proxy_ping_port
        self.http_port = self.moriio_config.http_port
        self.handshake_port = self.moriio_config.handshake_port
        self.notify_port = self.moriio_config.notify_port

        self.zmq_context = zmq.Context()
        self.metadata_address = (
            f"{self.moriio_config.local_ip}:{self.moriio_config.local_ping_port}"
        )
        self.request_address = (
            f"{self.moriio_config.local_ip}:{self.moriio_config.http_port}"
        )

        self.moriio_engine = None
        self._handle_request_thread = None
        self._ping_thread = None
        self._writer = MoRIIOWriter(self)
        # Completions that arrived before transfer_id_to_request_id was populated.
        # Retried each step until the mapping is established.
        self._unmatched_write_completions: set[str] = set()
        # Producer-side READ-mode ACK fan-in. When decode TP is larger than
        # prefill TP, multiple decode ranks can read from one prefill rank and
        # notify the same transfer_id. Blocks are reusable only after all ACKs.
        self._consumer_notification_counts: dict[TransferId, int] = {}
        self._completed_consumer_notifications: set[TransferId] = set()

        role = "producer" if self.is_producer else "consumer"
        engine_suffix = (
            f"{self.moriio_config.local_ip}:{self.moriio_config.handshake_port}:"
            f"tp{self.tp_rank}:dp{self.dp_rank}"
        )
        self.moriio_engine = IOEngine(
            f"{role}:{engine_suffix}",
            IOEngineConfig(
                self.moriio_config.local_ip, self.moriio_config.local_kv_port
            ),
        )
        logger.debug(
            "build MORI IOEngine %s (ip=%s port=%s)",
            f"{role}:{engine_suffix}",
            self.moriio_config.local_ip,
            self.moriio_config.local_kv_port,
        )

        if self._rank == 0 and self.moriio_config.proxy_ip:
            self._ping_thread = threading.Thread(
                target=self._ping, args=(self.zmq_context,), daemon=True
            )
            self._ping_thread.start()

        logger.info(
            "Initializing MoRIIO Engine, engine = %s, role = %s",
            self.moriio_engine,
            "producer" if self.is_producer else "consumer",
        )

        # Agent.
        self.moriio_wrapper = MoRIIOWrapper(
            tp_rank=self.tp_rank,
            dp_rank=self.dp_rank,
            transfer_timeout=self.moriio_config.transfer_timeout,
        )
        self.moriio_wrapper.set_moriio_engine(self.moriio_engine)
        backend = (
            BackendType.XGMI
            if self.moriio_config.backend == "xgmi"
            else BackendType.RDMA
        )
        self.moriio_wrapper.set_backend_type(
            backend,
            qp_per_transfer=self.moriio_config.qp_per_transfer,
            post_batch_size=self.moriio_config.post_batch_size,
            num_workers=self.moriio_config.num_workers,
        )
        self.moriio_wrapper.notify_port = self.moriio_config.notify_port
        self.local_kv_cache_metadata: list[bytes] = []
        self.local_kv_cache_size: list[int] = []
        self.layer_name_to_local_kv_cache_metadata: dict[str, list[bytes]] = {}

        self.remote_kv_cache_metadata: list[bytes] = []
        self.remote_kv_cache_size: list[int] = []
        self.layer_name_to_remote_kv_cache_metadata: dict[str, dict[str, list[Any]]] = (
            dict()
        )
        self.remote_moriio_metadata: dict[EngineId, MoRIIOAgentMetadata] = {}
        self.slot_size_bytes = 0

        self.load_ready_flag: dict[str, bool] = {}
        self.write_ready_flags: dict[str, bool] = {}
        self.kv_cache_shape = None
        self.block_shape = None
        self.kv_element_size = 0
        self.kv_cache_shapes: dict[str, torch.Size] = {}
        self.block_lens: dict[str, int] = {}

        # Map of engine_id -> {agent_name0, agent_name1..}.
        self._remote_agents: dict[EngineId, set[str]] = {}

        self.side_channel_port: int = (
            self.moriio_config.handshake_port
            + get_port_offset(self.dp_rank, self.tp_rank)
        )
        self.engine_id: EngineId = engine_id

        self.world_size = get_tensor_model_parallel_world_size()
        self.tp_group = get_tp_group()

        # KV Caches and moriio tracking data.
        self.kv_caches: dict[str, torch.Tensor] = {}

        # Map of engine_id -> kv_caches_base_addr. For TP case, each local
        # rank will still only pull from a single remote TP worker.
        self.kv_caches_base_addr: dict[EngineId, list[int]] = {}

        # Number of MoRIIO regions. Currently one region per cache
        # (so 1 per layer for MLA, otherwise 2 per layer)
        self.num_regions = 0
        self.num_layers = 0

        # Map of engine_id -> num_blocks. All ranks in the same deployment will
        # have the same number of blocks.
        self.dst_num_blocks: dict[EngineId, int] = {}
        # In-progress READ transfers: req_id -> {layer_name: status}.
        self._recving_transfers: defaultdict[ReqId, dict] = defaultdict(dict)
        # Values are (remote_host, remote_notify_port, transfer_id).
        self._recving_transfers_callback_addr: dict[ReqId, tuple[str, str, str]] = {}
        # Monotonic-clock start times for each in-flight recv transfer.
        # Used by _pop_done_transfers to abort transfers whose RDMA
        # completion is lost, instead of hanging forever.
        self._recving_transfers_start: dict[str, float] = {}

        # Track the expiration time of requests that are waiting to be sent.
        self._reqs_to_send: dict[ReqId, float] = {}

        # Background thread for handling new handshake requests.
        self._moriio_handshake_listener_t: threading.Thread | None = None
        # Background thread for initializing new MoRIIO handshakes.
        self._handshake_initiation_executor = ThreadPoolExecutor(
            # MoRIIO is not guaranteed to be thread-safe, limit 1 worker.
            max_workers=1,
            thread_name_prefix="vllm-moriio-handshake-initiator",
        )
        self._ready_requests = queue.Queue[tuple[ReqId, ReqMeta]]()
        self._handshake_futures: dict[EngineId, Future[set[str]]] = {}
        # Protects _handshake_futures and _remote_agents.
        self._handshake_lock = threading.RLock()
        # Remote engines already covered by the eager pre-forward handshake.
        self._eager_handshaked_engines: set[EngineId] = set()

        self.block_size = vllm_config.cache_config.block_size
        self.model_config = vllm_config.model_config
        self.cache_config = vllm_config.cache_config

        self.block_window_per_layer: list[int | None] = []
        self.use_mla = self.model_config.use_mla
        self.built_session = False
        self.built_write_session: defaultdict[str, list] = defaultdict(list)
        backend = get_attn_backend(
            self.model_config.get_head_size(),
            self.model_config.dtype,
            self.cache_config.cache_dtype,
            use_mla=self.use_mla,
        )
        self.transfer_id_to_request_id: dict[TransferId, ReqId] = {}
        # READ-mode producer: a decode release-ACK can arrive BEFORE
        # start_load_kv populates transfer_id_to_request_id (the notify races
        # ahead of the scheduler->worker sync). Buffer such ACKs and retry them
        # next get_finished tick instead of dropping them -- dropping loses the
        # completion, so the request is never marked done_sending, its KV blocks
        # leak, and the prefill KV cache wedges at high concurrency. Buffered
        # BEFORE resolve_moriio_transfer_ack, so each ACK is counted exactly once
        # (on the tick its mapping exists) -- the heterogeneous-TP ack-counting
        # is preserved.
        self._pending_unmapped_acks: list = []

        # TODO: consider the integration of flashinfer or other backends.
        self.backend_name = backend.get_name()
        logger.debug("Detected attention backend %s", self.backend_name)

    def schedule_write_blocks(
        self,
        request_id: ReqId,
        transfer_id: TransferId,
        dst_engine_id: str,
        local_block_ids: list[int],
        remote_block_ids: list[int] | None,
        layer_name: str,
        kv_layer: torch.Tensor,
        remote_notify_port: int,
        remote_ip: str,
    ) -> None:
        """Schedule a block write operation.

        Args:
            request_id: Unique identifier for the request
            transfer_id: Unique identifier for the transfer
            dst_engine_id: Destination engine ID
            local_block_ids: Local block IDs to transfer
            remote_block_ids: Hint for remote block IDs
            layer_name: Name of the layer
            kv_layer: KV cache tensor
            remote_notify_port: Port for completion notification
            remote_ip: IP address of remote node
        """

        # synchronization to prevent dirty reads between
        # transfer and attention operations
        # we can consider removing this synchronization after ibgda is enabled.
        # when mori-io supports ibgda functionality

        stream = torch.cuda.current_stream()
        event = torch.cuda.Event()
        event.record(stream)

        task = WriteTask(
            request_id=request_id,
            transfer_id=transfer_id,
            dst_engine_id=dst_engine_id,
            local_block_ids=local_block_ids,
            remote_block_ids_hint=remote_block_ids,
            layer_name=layer_name,
            event=event,
            remote_notify_port=remote_notify_port,
            remote_ip=remote_ip,
        )
        self._writer.schedule_write(task)

    def _get_built_session(self, remote_engine_id):
        if remote_engine_id not in self.built_write_session:
            cur_remote_engine_sessions = []
            for ln, local_meta in self.layer_name_to_local_kv_cache_metadata.items():
                unpacked_local_memory_meta = (
                    self.moriio_wrapper.get_unpack_memory_metadata(local_meta[0])
                )
                unpacked_remote_memory_meta = (
                    self.moriio_wrapper.get_unpack_memory_metadata(
                        self.layer_name_to_remote_kv_cache_metadata[remote_engine_id][
                            ln
                        ][0]
                    )
                )
                cur_remote_engine_sessions.append(
                    self.moriio_wrapper.build_session(
                        unpacked_local_memory_meta, unpacked_remote_memory_meta
                    )
                )
            self.built_write_session[remote_engine_id] = cur_remote_engine_sessions
        return self.built_write_session[remote_engine_id], self.remote_moriio_metadata[
            remote_engine_id
        ]

    def _ping(self, zmq_context):
        # Use host:port format for http_address (compatible with official router)
        http_address = f"{self.request_address}"
        # Include host so the router embeds it in the request_id; the connector
        # on the other side parses host/ports from there.
        zmq_address = (
            f"host:{self.local_ip},"
            f"handshake:{self.handshake_port},"
            f"notify:{self.notify_port}"
        )
        role = "P" if self.is_producer else "D"

        retry_count = 0
        index = 1
        with zmq_context.socket(zmq.DEALER) as sock:
            sock.connect(f"tcp://{self.proxy_ip}:{self.proxy_ping_port}")

            while True:
                try:
                    data = {
                        "type": role,  # "P" or "D"
                        "http_address": http_address,
                        "zmq_address": zmq_address,
                        # dp_size/tp_size are not used by the official vLLM router
                        # (routing operates at the http_address level); they are
                        # consumed only by the toy proxy server.
                        "dp_size": self.moriio_config.dp_size,
                        "tp_size": self.moriio_config.tp_size,
                        # transfer_mode is included so the router can distinguish
                        # READ (prefill-then-decode, sequential) from WRITE (concurrent)
                        # scheduling.
                        "transfer_mode": self.mode.name,
                    }

                    sock.send(msgpack.dumps(data))
                    # logger.debug(f"Successfully sent ping message #{index}")
                    retry_count = 0

                except ConnectionRefusedError:
                    logger.info(
                        "Connection refused: %s:%s -> %s:%s",
                        self.local_ip,
                        self.local_ping_port,
                        self.proxy_ip,
                        self.proxy_ping_port,
                    )
                    retry_count += 1

                except OSError as e:
                    logger.info("OS error when sending ping: %s", e)
                    retry_count += 1

                except Exception as e:
                    logger.info("Unexpected error when sending ping: %s", e)
                    retry_count += 1
                    if retry_count >= MoRIIOConstants.MAX_PING_RETRIES:
                        logger.error(
                            "Max retries (%s) exceeded. Stopping ping loop.",
                            MoRIIOConstants.MAX_PING_RETRIES,
                        )
                        raise RuntimeError(
                            f"Ping failed after {retry_count} retries"
                        ) from e

                finally:
                    time.sleep(MoRIIOConstants.PING_INTERVAL)
                    index += 1

    def shutdown(self):
        if hasattr(self, "moriio_wrapper") and self.moriio_wrapper:
            self.moriio_wrapper.shutdown()

        if hasattr(self, "_handshake_initiation_executor"):
            self._handshake_initiation_executor.shutdown(wait=False)

        if (
            hasattr(self, "_moriio_handshake_listener_t")
            and self._moriio_handshake_listener_t
        ):
            self._moriio_handshake_listener_t.join(timeout=0)

        if hasattr(self, "zmq_context") and self.zmq_context:
            self.zmq_context.destroy(linger=0)
            self.zmq_context = None

    def __del__(self):
        self.shutdown()

    @staticmethod
    def _moriio_handshake_listener(
        metadata: MoRIIOAgentMetadata,
        ready_event: threading.Event,
        base_port: int,
        tp_rank: int,
        dp_rank: int,
        layer_name_to_local_kv_cache_metadata: dict,
    ):
        """Background thread for getting new MoRIIO handshakes."""

        encoder = msgspec.msgpack.Encoder()
        encoded_data = encoder.encode(metadata)
        size_in_bytes = len(encoded_data)
        logger.debug(
            "Size of encoded MoRIIOAgentMetadata: %s bytes", str(size_in_bytes)
        )

        # Listen for new requests for metadata.
        host = "*"

        path = make_zmq_path("tcp", host, base_port)
        logger.debug("mori handshake starting listening on path: %s", path)

        with zmq_ctx(zmq.ROUTER, path) as sock:
            ready_event.set()
            while True:
                identity, msg = sock.recv_multipart()
                if (
                    msg != MoRIIOConstants.GET_META_MSG
                    and msg != MoRIIOConstants.POP_DONE_RECV
                ):
                    logger.error("Connection listener got unexpected message")
                    raise HandshakeError("handshake failed, unexpected msg type")
                elif msg == MoRIIOConstants.GET_META_MSG:
                    sock.send_multipart(
                        (identity, b"", encoded_data)
                    )  # send local mori io engine meta data
                    logger.debug("MoRIIO handshake listener sent metadata")
                    # now we send tensor meta data for each block
                    buf = msgpack.dumps(layer_name_to_local_kv_cache_metadata)
                    sock.send_multipart((identity, b"", buf))
                elif msg == MoRIIOConstants.POP_DONE_RECV:
                    _, req_id = sock.recv_multipart()
                    logger.debug(
                        "MoRIIO handshake listener received done recv for req",
                        req_id.decode(),
                    )

    def _moriio_handshake(
        self,
        host: str,
        port: int,
        remote_tp_size: int,
        expected_engine_id: str,
        remote_dp_rank: int = 0,
        remote_tp_rank: int | None = None,
    ) -> set[str]:
        """Do a MoRIIO handshake with a remote instance.

        remote_tp_rank: explicit remote TP index to dial. Flexible-read callers
        pass the chosen prefill TP rank so the handshake, the (dp, tp) session
        key and the notify port all address the SAME rank. None falls back to the
        local-rank mapping _remote_tp_rank -- byte-identical for callers not yet
        TP-aware.
        """

        start_time = time.perf_counter()

        # NOTE(rob): we need each rank to have a unique port. This is
        # a hack to keep us moving. We will switch when moving to etcd
        # or where we have a single ZMQ socket in the scheduler.

        dial_tp_rank = (
            self._remote_tp_rank(remote_tp_size)
            if remote_tp_rank is None
            else int(remote_tp_rank)
        )
        port_offset = get_port_offset(remote_dp_rank, dial_tp_rank, remote_tp_size)
        path = make_zmq_path("tcp", host, port + port_offset)
        logger.debug("handshake Querying metadata on path: %s", path)

        # Send query for the request.
        with zmq_ctx(zmq.DEALER, path) as sock:
            logger.debug("prepare send msg INSTAZNCE: %s", path)
            sock.send(MoRIIOConstants.GET_META_MSG)
            received_frame = sock.recv_multipart()
            if len(received_frame) != 2 or received_frame[0] != b"":
                raise HandshakeError(f"Unexpected frame! {received_frame = }")

            metadata_bytes = received_frame[1]
            decoder = msgspec.msgpack.Decoder(MoRIIOAgentMetadata)
            metadata = decoder.decode(metadata_bytes)
            got_metadata_time = time.perf_counter()
            logger.info(
                "MoRIIO handshake: get metadata took: %s",
                got_metadata_time - start_time,
            )

            self.moriio_wrapper.remote_engine_ip = host
            remote_agent_name = self.moriio_wrapper.register_remote_engine(
                metadata.agent_metadata
            )

            logger.debug(
                "MoRIIO handshake: registered"
                "remote agent %s for engine ID %s, path = %s",
                remote_agent_name,
                expected_engine_id,
                path,
            )

            if len(self.local_kv_cache_metadata) > 0:
                logger.warning(
                    "len(self.local_kv_cache_metadata) = %s,"
                    "maybe you didnt clear this buffer correctly",
                    len(self.local_kv_cache_metadata),
                )
                self.local_kv_cache_metadata = []
            if len(self.remote_kv_cache_metadata) > 0:
                logger.warning(
                    "len(self.remote_kv_cache_metadata) = %s,"
                    "maybe you didnt clear this buffer correctly",
                    len(self.remote_kv_cache_metadata),
                )
                self.remote_kv_cache_metadata = []

            received_frame = sock.recv_multipart()
            if len(received_frame) != 2 or received_frame[0] != b"":
                raise HandshakeError(f"unexpected frame! {received_frame = }")
            buf = received_frame[1]
            self.layer_name_to_remote_kv_cache_metadata[expected_engine_id] = (
                msgpack.loads(buf)
            )
            self.remote_moriio_metadata[expected_engine_id] = metadata
            setup_agent_time = time.perf_counter()
            logger.debug(
                "MoRIIO handshake: add agent took: %s",
                setup_agent_time - got_metadata_time,
            )

        return {remote_agent_name}

    def _remote_tp_rank(self, remote_tp_size: int) -> int:
        # 0/unknown remote TP == homogeneous (avoids collapsing all ranks to 0).
        if remote_tp_size == 0:
            remote_tp_size = self.world_size
        return get_moriio_remote_tp_rank(self.tp_rank, self.world_size, remote_tp_size)

    def _background_moriio_handshake(
        self, req_id: ReqId, remote_engine_id: EngineId, meta: ReqMeta
    ):
        # Do MoRIIO handshake in background and add to _ready_requests when done.
        fut = None
        if remote_engine_id is not None:
            fut = self._handshake_futures.get(remote_engine_id)
        if fut is None:
            host = meta.remote_host
            port = int(meta.remote_handshake_port)
            tp_size = int(meta.tp_size)
            remote_dp_size = int(meta.remote_dp_size)
            # Wide-EP multi-pod: remote DP ranks span pods at different IPs
            # (ranks per pod = dp_local), so resolve the host per cur_dp_rank
            # below instead of using a single host for all ranks.
            pod_hosts = list(meta.multi_pod_hosts) if meta.multi_pod_hosts else [host]
            remote_dp_size_local = int(meta.remote_dp_size_local) or remote_dp_size

        def request_ready(_f: Future[Any], entry=(req_id, meta)):
            logger.info("MoRIIO handshake done for request %s", req_id)
            self._ready_requests.put(entry)
            self.load_ready_flag[remote_engine_id] = True
            self.write_ready_flags[remote_engine_id] = True

        fut_list = []

        # In dp(prefill)<->dp(decode) communication, we require an all-to-all handshake.

        for cur_dp_rank in range(remote_dp_size):
            dp_engine_id = self.get_engine_name_with_dp(remote_engine_id, cur_dp_rank)
            _pod_idx = pod_index(cur_dp_rank, remote_dp_size_local)
            if _pod_idx >= len(pod_hosts):
                _pod_idx = 0
            _per_rank_host = pod_hosts[_pod_idx]
            # The handshake port offset must use the per-pod local rank, since
            # each pod binds sockets only for its local ranks; dp_engine_id
            # keeps the global rank for uniqueness. Single-pod is bit-identical.
            _per_rank_local_dp = fold_local_rank(cur_dp_rank, remote_dp_size_local)
            future = self._handshake_initiation_executor.submit(
                self._moriio_handshake,
                _per_rank_host,
                port,
                tp_size,
                dp_engine_id,
                _per_rank_local_dp,
            )
            fut_list.append(future)

            def done_callback(f: Future[set[str]], eid=dp_engine_id):
                with self._handshake_lock:
                    self._handshake_futures.pop(eid, None)
                    try:
                        self._remote_agents[eid] = f.result()
                    except Exception:
                        logger.exception("Handshake with %s failed", eid)

            future.add_done_callback(done_callback)
            self._handshake_futures[dp_engine_id] = future

        # fut = fut_list
        def wait_all_dp():
            for future in fut_list:
                future.result()
            return True

        all_done_future = self._handshake_initiation_executor.submit(wait_all_dp)
        all_done_future.add_done_callback(request_ready)

    def _is_mla_cache_layer(self, layer_name: str) -> bool:
        return is_mla_cache_layer(self.layer_to_spec, layer_name)

    def _get_layer_transfer_geometry(
        self, layer_name: str, remote_num_blocks: int | None = None
    ) -> LayerTransferGeometry:
        return get_layer_transfer_geometry(
            layer_name,
            self.kv_caches[layer_name],
            self.layer_to_spec,
            remote_num_blocks,
        )

    def _iter_layer_registration_regions(
        self, layer_name: str
    ) -> list[tuple[torch.Tensor, int]]:
        return iter_layer_registration_regions(
            layer_name,
            self.kv_caches[layer_name],
            self.layer_to_spec,
        )

    def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
        """Register the KV Cache data in moriio."""

        self.kv_caches = kv_caches  # layer name to kv cache
        self.kv_cache_shapes = {
            layer_name: kv_cache.shape for layer_name, kv_cache in kv_caches.items()
        }

        first_layer_name, first_kv_cache = next(
            (
                (layer_name, kv_cache)
                for layer_name, kv_cache in kv_caches.items()
                if (
                    not self._is_mla_cache_layer(layer_name)
                    and len(kv_cache.shape) == 5
                    and (kv_cache.shape[0] == 2 or kv_cache.shape[1] == 2)
                )
            ),
            next(iter(kv_caches.items())),
        )
        kv_elem_size = first_kv_cache.element_size()

        use_mla = self._is_mla_cache_layer(first_layer_name)
        first_geometry = self._get_layer_transfer_geometry(first_layer_name)

        if use_mla:
            # MLA case.
            block_rank = 2  # [block_size, latent_dim]
            block_shape = first_kv_cache.shape[-block_rank:]
        else:
            # [2, num_blocks, ...] or [num_blocks, 2, ...]
            block_rank = 3  # [block_size, kv_heads, head_dim]
            block_shape = first_kv_cache.shape[-block_rank:]
        self.num_blocks = first_geometry.num_blocks
        self.slot_size_bytes = first_geometry.slot_size_bytes
        if first_geometry.block_size != self.block_size:
            # DeepSeek-V3 / MLA backends (e.g. FlashMLA) override the
            # configured block_size at attention-layer creation time, so
            # the KV cache tensor is laid out with a different (usually
            # larger) block_size than vllm_config.cache_config.block_size.
            # Trust the actual tensor shape and reconcile.
            logger.info(
                "KV cache block_size=%d differs from config block_size=%d; "
                "using actual tensor shape (attention backend override).",
                first_geometry.block_size,
                self.block_size,
            )
            self.block_size = first_geometry.block_size
        # TODO(tms): self.block_len needs to be per-layer for sliding window,
        # hybrid attn, etc
        # block size in bytes
        self.block_len = first_geometry.block_len
        self.kv_cache_shape = first_kv_cache.shape
        self.block_shape = block_shape
        self.kv_element_size = kv_elem_size

        self.dst_num_blocks[self.engine_id] = self.num_blocks
        kv_caches_base_addr = []
        caches_data = []

        for layer_name in kv_caches:
            geometry = self._get_layer_transfer_geometry(layer_name)
            if geometry.block_size != self.block_size:
                raise ValueError(
                    "MoRIIO KV cache block size mismatch for layer "
                    f"{layer_name}: {geometry.block_size} != {self.block_size}"
                )
            self.block_lens[layer_name] = geometry.block_len
            for cache, region_len in self._iter_layer_registration_regions(layer_name):
                base_addr = cache.data_ptr()
                caches_data.append((base_addr, region_len, cache.device.index, ""))
                kv_caches_base_addr.append(base_addr)

        for layer_name, kv_cache in kv_caches.items():
            if layer_name not in self.layer_name_to_local_kv_cache_metadata:
                self.layer_name_to_local_kv_cache_metadata[layer_name] = []

            moriio_mem_metadata = self.moriio_wrapper.register_local_tensor(kv_cache)
            self.layer_name_to_local_kv_cache_metadata[layer_name].append(
                moriio_mem_metadata
            )

            self.local_kv_cache_size.append(
                kv_cache.nelement() * kv_cache.element_size()
            )

        self.kv_caches_base_addr[self.engine_id] = kv_caches_base_addr
        self.num_regions = len(caches_data)
        self.num_layers = len(self.kv_caches.keys())

        # Optimization for models with local attention (Llama 4)
        if self.vllm_config.model_config.hf_config.model_type == "llama4":
            from transformers import Llama4TextConfig

            assert isinstance(
                self.vllm_config.model_config.hf_text_config, Llama4TextConfig
            )
            llama4_config = self.vllm_config.model_config.hf_text_config
            no_rope_layers = llama4_config.no_rope_layers
            chunk_size = llama4_config.attention_chunk_size
            chunk_block_size = math.ceil(chunk_size / self.block_size)
            for layer_idx in range(self.num_layers):
                # no_rope_layers[layer_idx] == 0 means NoPE (global)
                # Any other value means RoPE (local chunked)
                is_local_attention = no_rope_layers[layer_idx] != 0
                block_window = chunk_block_size if is_local_attention else None
                self.block_window_per_layer.append(block_window)
            logger.debug(
                "Llama 4 block window per layer mapping: %s",
                self.block_window_per_layer,
            )
            assert len(self.block_window_per_layer) == self.num_layers

        metadata = MoRIIOAgentMetadata(
            engine_id=self.engine_id,
            agent_metadata=self.moriio_wrapper.get_agent_metadata(),
            kv_caches_base_addr=self.kv_caches_base_addr[self.engine_id],
            num_blocks=self.num_blocks,
            block_len=self.block_len,
            attn_backend_name=self.backend_name,
        )
        ready_event = threading.Event()
        self._moriio_handshake_listener_t = threading.Thread(
            target=self._moriio_handshake_listener,
            args=(
                metadata,
                ready_event,
                self.side_channel_port,
                self.tp_rank,
                self.dp_rank,
                self.layer_name_to_local_kv_cache_metadata,
            ),
            daemon=True,
            name="moriio_handshake_listener",
        )
        self._moriio_handshake_listener_t.start()
        ready_event.wait()  # Wait for listener ZMQ socket to be ready.
        self.moriio_wrapper.async_wait_reqid()

    def get_finished(self) -> tuple[set[str], set[str]]:
        """
        Get requests that are done sending or recving on this specific worker.
        The scheduler process (via the MultiprocExecutor) will use this output
        to track which workers are done.
        """

        done_sending, done_recving = set(), set()

        if self.is_producer:
            # pop_finished_req_ids returns release ACKs sent by decode. Keep
            # duplicate ACKs because heterogeneous TP can fan multiple decode
            # ranks into one prefill rank for the same transfer_id.
            # Combine freshly-arrived ACKs with any buffered from prior ticks
            # whose transfer_id wasn't mapped yet (notify raced ahead of
            # start_load_kv); retry the lookup every tick. Buffered before
            # resolve_moriio_transfer_ack so each ACK is counted exactly once.
            finished_acks = self._pending_unmapped_acks + list(
                self.moriio_wrapper.pop_finished_req_ids()
            )
            self._pending_unmapped_acks = []
            resolved_transfer_ids: set[TransferId] = set()
            for ack in finished_acks:
                transfer_id = ack if isinstance(ack, str) else ack.transfer_id
                if transfer_id not in self.transfer_id_to_request_id:
                    # Mapping not populated yet -- buffer and retry next tick,
                    # do NOT drop (dropping leaks producer KV at high conc and
                    # wedges the prefill).
                    self._pending_unmapped_acks.append(ack)
                    continue
                resolved_transfer_id = resolve_moriio_transfer_ack(
                    ack,
                    producer_tp_size=self.world_size,
                    live_transfer_ids=self.transfer_id_to_request_id.keys(),
                    notification_counts=self._consumer_notification_counts,
                    completed_transfer_ids=(self._completed_consumer_notifications),
                )
                if resolved_transfer_id is not None:
                    resolved_transfer_ids.add(resolved_transfer_id)
            done_sending = {
                self.transfer_id_to_request_id[xfer_id]
                for xfer_id in resolved_transfer_ids
            }
        else:
            if self.mode == MoRIIOMode.WRITE:
                fresh = self.moriio_wrapper.pop_finished_write_req_ids()
                # Accumulate with any completions that arrived before their
                # transfer_id was registered in transfer_id_to_request_id.
                self._unmatched_write_completions |= fresh
                done_recving = self._unmatched_write_completions
            else:
                # READ mode: the scheduler treats KV loads as synchronous
                # (load_kv_async=False), so requests go directly to RUNNING
                # instead of WAITING_FOR_REMOTE_KVS. We still call
                # _pop_done_transfers() to send the notify to the prefill
                # side and clean up internal state, but we must NOT report
                # these as done_recving because the scheduler doesn't
                # expect a finished_recving signal for RUNNING requests.
                self._pop_done_transfers()

        done_recving = {
            self.transfer_id_to_request_id[id]
            for id in filter(
                lambda id: id in self.transfer_id_to_request_id, done_recving
            )
        }
        if self.mode == MoRIIOMode.WRITE and not self.is_producer:
            # Remove the ones we successfully matched; leave unmatched for retry.
            matched_xfer_ids = {
                id
                for id in self._unmatched_write_completions
                if id in self.transfer_id_to_request_id
            }
            self._unmatched_write_completions -= matched_xfer_ids

        return done_sending, done_recving

    def wait_for_layer_load(self, layer_name: str) -> None:
        """Block until all in-flight READs of this layer have landed.

        A host-side blocking wait must not run during full-graph capture.
        """
        if self.is_producer or self.mode != MoRIIOMode.READ:
            return

        if get_forward_context().cudagraph_runtime_mode == CUDAGraphMode.FULL:
            return

        deadline = time.monotonic() + self.moriio_config.transfer_timeout
        while True:
            with self.moriio_wrapper.lock:
                pending = [
                    status_by_layer[layer_name]
                    for status_by_layer in self._recving_transfers.values()
                    if layer_name in status_by_layer
                ]

            if not pending:
                return

            still_running = False
            for status in pending:
                # A failed read is dropped in _pop_done_transfers.
                if status.Succeeded() or status.Failed():
                    continue
                still_running = True

            if not still_running:
                return

            if time.monotonic() > deadline:
                logger.warning(
                    "MoRIIO READ barrier timed out for layer %s; proceeding "
                    "(request dropped via get_finished).",
                    layer_name,
                )
                return

            time.sleep(0.001)

    def _pop_done_transfers(self) -> set[str]:
        done_req_ids: set[str] = set()
        _xfer_timeout = int(os.environ.get("VLLM_MORIIO_TRANSFER_TIMEOUT_S", "120"))
        with self.moriio_wrapper.lock:
            to_remove = []
            for req_id, status_by_layer in self._recving_transfers.items():
                statuses = list(status_by_layer.values())
                failed_status = next(
                    (status for status in statuses if status.Failed()), None
                )
                if statuses and all(status.Succeeded() for status in statuses):
                    host, port, xfer_id = self._recving_transfers_callback_addr[req_id]
                    done_req_ids.add(xfer_id)
                    self.moriio_wrapper.send_notify(
                        xfer_id,
                        host,
                        port,
                        message_type="release",
                        message_fields={"consumer_tp_size": self.world_size},
                    )
                    to_remove.append(req_id)
                elif failed_status is not None:
                    logger.error(
                        "RDMA transfer failed for request %s: %s (code=%s). "
                        "Notifying prefill to free blocks; request will be "
                        "aborted by timeout.",
                        req_id,
                        failed_status.Message(),
                        failed_status.Code(),
                    )
                    host, port, xfer_id = self._recving_transfers_callback_addr[req_id]
                    try:
                        self.moriio_wrapper.send_notify(
                            xfer_id,
                            host,
                            port,
                            message_type="release",
                            message_fields={"consumer_tp_size": self.world_size},
                        )
                    except Exception:
                        logger.exception(
                            "Failed to send error notification for request %s",
                            req_id,
                        )
                    to_remove.append(req_id)
                    # Do NOT add to done_req_ids: decode KV cache is incomplete.
                    # The request will expire via the normal request timeout.
                elif req_id in self._recving_transfers_start:
                    # Abort still-in-flight transfers that exceed the
                    # configured deadline. Otherwise a lost RDMA
                    # completion would leave the decode worker hung
                    # indefinitely on this request.
                    _age = time.monotonic() - self._recving_transfers_start[req_id]
                    if _age > _xfer_timeout:
                        logger.error(
                            "RDMA read TIMED OUT for req %s after %.1fs "
                            "(VLLM_MORIIO_TRANSFER_TIMEOUT_S=%d)",
                            req_id,
                            _age,
                            _xfer_timeout,
                        )
                        to_remove.append(req_id)
            for req_id in to_remove:
                del self._recving_transfers[req_id]
                del self._recving_transfers_callback_addr[req_id]
                self._recving_transfers_start.pop(req_id, None)

            return done_req_ids

    def save_kv_layer(
        self,
        metadata: MoRIIOConnectorMetadata,
        layer_name: str,
        kv_layer: torch.Tensor,
        attn_metadata: "AttentionMetadata | None",
        **kwargs,
    ):
        if not self.is_producer:
            return
        if self.mode == MoRIIOMode.READ:
            return
        remote_engine_id = None

        for req_id, meta in metadata.reqs_to_save.items():
            # we only need to check if dp0 in rank
            remote_engine_id = (
                str(meta.remote_host) + ":" + str(meta.remote_handshake_port)
            )

            meta.remote_engine_id = remote_engine_id

            dp0_remote_engine_id = self.get_engine_name_with_dp(remote_engine_id, 0)
            if dp0_remote_engine_id not in self._remote_agents:
                # Initiate handshake with remote engine to exchange metadata.
                with self._handshake_lock:
                    if remote_engine_id not in self._remote_agents:
                        self._background_moriio_handshake(
                            req_id, remote_engine_id, meta
                        )

                        continue
            self._write_blocks_for_req(req_id, meta, layer_name, kv_layer)

        if remote_engine_id is None:
            return
        _deadline = time.monotonic() + self.moriio_config.transfer_timeout
        while True:
            if (
                self._ready_requests.empty()
                and remote_engine_id not in self.write_ready_flags
            ):
                if time.monotonic() > _deadline:
                    logger.warning(
                        "Timed out waiting for write_ready_flags[%s]; "
                        "adjust with kv_connector_extra_config.transfer_timeout",
                        remote_engine_id,
                    )
                    break
                time.sleep(0.001)
                continue
            elif not self._ready_requests.empty() and (
                remote_engine_id in self.write_ready_flags
            ):
                self._write_blocks_for_req(
                    *self._ready_requests.get_nowait(), layer_name, kv_layer
                )
                break
            else:
                break

    def get_engine_name_with_dp(self, engine_name, dp_rank):
        return f"{engine_name}_dp{dp_rank}"

    def get_engine_name_with_dp_tp(self, engine_name, dp_rank, tp_rank):
        # Per-(dp, tp) session key. The flexible mirror read keys sessions per
        # (dp, tp) so one decode worker can hold a session to EACH prefill TP
        # rank and spread reads across them; other configs keep the DP-only key.
        return f"{engine_name}_dp{dp_rank}_tp{tp_rank}"

    def _eager_handshake_all_dp_ranks(self, metadata: MoRIIOConnectorMetadata) -> None:
        """Handshake EVERY remote prefill DP rank BEFORE the decode forward pass,
        identically across all local TP workers.

        Why this exists (the deadlock it prevents): with heterogeneous DP prefill
        a decode TP worker reads KV from whichever prefill DP rank owns the
        request, so across requests every worker must reach several prefill DP
        ranks. The decode forward issues per-layer TP collectives (e.g. an
        all-gather) that all local TP workers must enter together. If the
        handshakes are left to fire lazily on the read path, the workers diverge:
        a worker whose target rank is already cached races ahead into the forward
        collective while a peer is still blocked in a handshake recv(). The first
        worker then waits inside the collective for the stuck peer -> 600s NCCL
        timeout / hang. This was observed directly with mixed TP<->DP configs.

        Fix: complete ALL prefill-DP-rank handshakes for every referenced remote
        engine HERE, before any read enters the forward, so no worker is still
        handshaking once its peers reach a collective. Fires ONCE per remote
        engine (first contact), gated by _eager_handshaked_engines. The engine
        set comes from scheduler-built metadata (identical on every TP worker),
        so all workers run the same handshakes in the same order and reach the
        all-reduce barrier below together.

        Failure handling: handshake exceptions are caught, never raised before
        the collective (raising early would hang the peers still waiting for it).
        Every worker reaches the all-reduce(MIN) vote; if ANY worker failed, ALL
        raise the same error AFTER the collective, so the step fails fast and
        uniformly in ~seconds instead of one rank hanging the forward for 600s.
        """
        import torch.distributed as dist

        # Distinct remote engines referenced this step, in metadata (==
        # scheduler) order so every TP worker iterates engines identically.
        engines: dict[str, ReqMeta] = {}
        for _req_id, meta in metadata.reqs_to_recv.items():
            remote_engine_id = (
                str(meta.remote_host) + ":" + str(meta.remote_handshake_port)
            )
            engines.setdefault(remote_engine_id, meta)

        for remote_engine_id, meta in engines.items():
            if remote_engine_id in self._eager_handshaked_engines:
                continue

            remote_dp_size = int(meta.remote_dp_size)
            port = int(meta.remote_handshake_port)
            tp_size = int(meta.tp_size)

            # Flexible mirror (TP prefill + MLA, world_size==1 decode): the read
            # round-robins over prefill TP ranks, so pre-warm a session to EVERY
            # (dp, tp) rank. Other configs pre-warm per DP rank (tp resolved by
            # the fixed local-rank mapping) -- byte-identical to before. The
            # mirror's decode is DP+EP, whose forward all-to-all is the collective
            # that the eager barrier keeps everyone in step for.
            flexible = (
                self.world_size == 1
                and self.use_mla
                and remote_dp_size == 1
                and tp_size > 1
            )
            # (engine_id, dp_rank, tp_rank_or_None); tp_rank is None on the legacy
            # path so _moriio_handshake falls back to its _remote_tp_rank mapping.
            targets: list[tuple[Any, int, int | None]]
            if flexible:
                targets = [
                    (self.get_engine_name_with_dp_tp(remote_engine_id, dp, tp), dp, tp)
                    for dp in range(remote_dp_size)
                    for tp in range(max(1, tp_size))
                ]
            else:
                targets = [
                    (self.get_engine_name_with_dp(remote_engine_id, dp), dp, None)
                    for dp in range(remote_dp_size)
                ]

            # Submit handshakes for every not-yet-known target UNDER the lock; do
            # NOT hold it across the join or the collective (a stalled recv must
            # not block another thread's lock acquisition). Gate on BOTH
            # _remote_agents AND layer metadata: a rank with an agent entry but no
            # layer metadata is half-handshaked and would KeyError at read time.
            futures: list[tuple[str, Future[set[str]]]] = []
            with self._handshake_lock:
                for eid, cur_dp_rank, cur_tp_rank in targets:
                    if (
                        eid in self._remote_agents
                        and eid in self.layer_name_to_remote_kv_cache_metadata
                    ):
                        continue
                    fut = self._handshake_initiation_executor.submit(
                        self._moriio_handshake,
                        meta.remote_host,
                        port,
                        tp_size,
                        eid,
                        cur_dp_rank,
                        cur_tp_rank,
                    )
                    futures.append((eid, fut))

            # Join outside the lock. Bounded handshake errors are recorded here
            # and reported after the all-reduce.
            all_ok = True
            results: dict[str, set[str]] = {}
            for eid, fut in futures:
                try:
                    results[eid] = fut.result()
                except Exception:
                    logger.exception("Eager MoRIIO handshake failed for %s", eid)
                    all_ok = False

            with self._handshake_lock:
                for eid, agents in results.items():
                    self._remote_agents[eid] = agents

            logger.info(
                "Eager MoRIIO handshake: engine=%s dp_size=%d new_ranks=%d "
                "ok=%s tp_rank=%d",
                remote_engine_id,
                remote_dp_size,
                len(futures),
                all_ok,
                self.tp_rank,
            )
            # CPU all-reduce = TP-uniform success vote AND lockstep barrier: it
            # blocks until every TP worker arrives, gives them the same verdict,
            # and stays off the model compute stream.
            vote = torch.tensor([1 if all_ok else 0], device="cpu", dtype=torch.int32)
            dist.all_reduce(vote, group=self.tp_group.cpu_group, op=dist.ReduceOp.MIN)
            if int(vote.item()) == 0:
                raise HandshakeError(
                    f"Eager MoRIIO handshake failed for {remote_engine_id} on "
                    "at least one TP rank; failing this step fast to avoid a "
                    "TP collective hang"
                )

            self._eager_handshaked_engines.add(remote_engine_id)

    def start_load_kv(self, metadata: MoRIIOConnectorMetadata):
        """
        Start loading by triggering non-blocking moriio_xfer.
        We check for these trnxs to complete in each step().
        """
        self.transfer_id_to_request_id = metadata.transfer_id_to_request_id
        if self.is_producer:
            live_transfer_ids = set(self.transfer_id_to_request_id)
            self._consumer_notification_counts = {
                transfer_id: count
                for transfer_id, count in self._consumer_notification_counts.items()
                if transfer_id in live_transfer_ids
            }
            self._completed_consumer_notifications.intersection_update(
                live_transfer_ids
            )
            self.moriio_wrapper.async_wait_reqid()
            return
        if self.mode == MoRIIOMode.WRITE:
            return

        # Handshake every referenced remote prefill rank up front, before any
        # read enters the forward pass. A lazy per-rank handshake on the read
        # path lets TP workers diverge into a forward collective while a peer is
        # still blocked handshaking -> NCCL hang (see below).
        self._eager_handshake_all_dp_ranks(metadata)

        wait_handshake_readd_req = False
        remote_engine_id = None

        for req_id, meta in metadata.reqs_to_recv.items():
            remote_engine_id = (
                str(meta.remote_host) + ":" + str(meta.remote_handshake_port)
            )
            meta.remote_engine_id = remote_engine_id
            # The eager handshake above already covered every referenced engine
            # (and keys the mirror per (dp, tp), which the DP-only dp0 probe below
            # would miss). Only fall back to the lazy background handshake for an
            # engine it did not cover.
            dp0_remote_engine_id = self.get_engine_name_with_dp(remote_engine_id, 0)
            if (
                remote_engine_id not in self._eager_handshaked_engines
                and dp0_remote_engine_id not in self._remote_agents
            ):
                # Initiate handshake with remote engine to exchange metadata.
                with self._handshake_lock:
                    if remote_engine_id not in self._remote_agents:
                        self._background_moriio_handshake(
                            req_id, remote_engine_id, meta
                        )
                        wait_handshake_readd_req = True

                        continue

            # Handshake already completed, start async read xfer.
            self._read_blocks_for_req(req_id, meta)
        # Start transfers for requests whose handshakes have now finished.

        if remote_engine_id is None and not wait_handshake_readd_req:
            return
        _deadline = time.monotonic() + self.moriio_config.transfer_timeout
        while True:
            if (
                self._ready_requests.empty()
                and remote_engine_id not in self.load_ready_flag
                and wait_handshake_readd_req
            ):
                if time.monotonic() > _deadline:
                    logger.warning(
                        "Timed out waiting for load_ready_flag[%s]; "
                        "adjust with kv_connector_extra_config.transfer_timeout",
                        remote_engine_id,
                    )
                    break
                time.sleep(0.001)
                continue
            elif (
                not self._ready_requests.empty()
                and remote_engine_id in self.load_ready_flag
            ):
                self._read_blocks_for_req(*self._ready_requests.get_nowait())
                break
            else:
                break

        self._reqs_to_send.update(metadata.reqs_to_send)

    def wait_for_save(self, metadata: MoRIIOConnectorMetadata):
        if self.mode == MoRIIOMode.WRITE and self.is_producer:
            for layer_name, kv_layer in self.kv_caches.items():
                self.save_kv_layer(metadata, layer_name, kv_layer, None)
            self._writer.seal_pending_transfers()

    def _next_flex_tp_rank(self, remote_tp_size: int) -> int:
        """Deterministic round-robin over prefill tp0..N-1 for the flexible read.

        Round-robin (not random): exactly uniform and testable, with the same
        prefill-NIC balancing. Seeded from this decode rank's dp_rank so
        concurrent decode DP ranks are phase-staggered -- at a given read index
        distinct decode ranks target distinct prefill TP ranks.
        """
        rr = getattr(self, "_flex_tp_rr", None)
        if rr is None:
            rr = int(getattr(self, "dp_rank", 0) or 0)
        self._flex_tp_rr = rr + 1
        return rr % remote_tp_size

    def _resolve_read_source(self, meta: ReqMeta) -> tuple[int, bool]:
        """Resolve (chosen_tp, flexible) for reading this request's KV.

        Flexible mirror (decode world_size==1 + MLA + pure-TP prefill): MLA
        replicates the latent KV across the prefill TP ranks, so any is a valid
        source; round-robin across them to spread RDMA/NIC load. Otherwise the
        source TP rank is fixed by the local-rank mapping (_remote_tp_rank) --
        forward DP8EP->TP8 -> tp0; symmetric TP -> tp_rank -- byte-identical to
        prior behaviour. chosen_tp is the single value threaded into the (dp, tp)
        session key, the handshake dial and the notify port, so all three address
        the SAME prefill rank (drift -> read one rank but notify another -> the
        read rank's prefill buffer is never freed).
        """
        remote_tp_size = int(meta.tp_size)
        flexible = (
            self.world_size == 1
            and self.use_mla
            and int(meta.remote_dp_size) == 1
            and remote_tp_size > 1
        )
        if flexible:
            chosen_tp = self._next_flex_tp_rank(remote_tp_size)
        else:
            chosen_tp = self._remote_tp_rank(remote_tp_size)
        return chosen_tp, flexible

    def _read_blocks_for_req(self, req_id: str, meta: ReqMeta):
        logger.debug(
            "Remote agent %s available, calling _read_blocks for req %s",
            meta.remote_engine_id,
            req_id,
        )
        chosen_tp, flexible = self._resolve_read_source(meta)
        self._read_blocks(
            request_id=req_id,
            transfer_id=meta.transfer_id,
            dst_engine_id=meta.remote_engine_id,
            local_block_ids=meta.local_block_ids,
            remote_block_ids=meta.remote_block_ids,
            remote_host=meta.remote_host,
            remote_notify_port=meta.remote_notify_port,
            remote_tp_size=meta.tp_size,
            remote_dp_rank=meta.remote_dp_rank,
            chosen_tp=chosen_tp,
            flexible=flexible,
        )

    def _write_blocks_for_req(self, req_id: ReqId, meta: ReqMeta, layer_name, kv_layer):
        # Stash multi_pod_hosts + local DP size on the worker so
        # MoRIIOEngine._finalize_if_complete (which sees only the WriteTask,
        # not ReqMeta) can pick the per-rank pod IP for the completion notify.
        # Last-writer-wins is safe: all requests share the same topology.
        if meta.multi_pod_hosts:
            self.multi_pod_hosts = list(meta.multi_pod_hosts)
        else:
            self.multi_pod_hosts = [meta.remote_host]
        if meta.remote_dp_size_local:
            self.remote_dp_size_local = int(meta.remote_dp_size_local)
        else:
            self.remote_dp_size_local = int(meta.remote_dp_size)
        self.schedule_write_blocks(
            request_id=req_id,
            transfer_id=meta.transfer_id,
            dst_engine_id=meta.remote_engine_id,
            local_block_ids=meta.local_block_ids,
            remote_block_ids=meta.remote_block_ids,
            layer_name=layer_name,
            kv_layer=kv_layer,
            remote_notify_port=meta.remote_notify_port,
            remote_ip=meta.remote_host,
        )

    def merge_contiguous_blocks(
        self,
        offsets_local: list[int],
        offsets_remote: list[int],
        sizes: list[int],
        assume_sorted: bool = False,
    ) -> tuple[list[int], list[int], list[int]]:
        n = len(offsets_local)
        if n == 0:
            return [], [], []
        if not (n == len(offsets_remote) == len(sizes)):
            raise ValueError("Input list lengths mismatch")
        local_arr = np.fromiter(offsets_local, dtype=np.int64, count=n)
        remote_arr = np.fromiter(offsets_remote, dtype=np.int64, count=n)
        sizes_arr = np.fromiter(sizes, dtype=np.int64, count=n)

        if assume_sorted:
            local_sorted = local_arr
            remote_sorted = remote_arr
            sizes_sorted = sizes_arr
        else:
            if np.all(local_arr[:-1] <= local_arr[1:]):
                local_sorted = local_arr
                remote_sorted = remote_arr
                sizes_sorted = sizes_arr
            else:
                sort_idx = np.argsort(local_arr, kind="stable")
                local_sorted = local_arr[sort_idx]
                remote_sorted = remote_arr[sort_idx]
                sizes_sorted = sizes_arr[sort_idx]

        if n == 1:
            return (
                [int(local_sorted[0])],
                [int(remote_sorted[0])],
                [int(sizes_sorted[0])],
            )

        diff_local = local_sorted[1:] - local_sorted[:-1]
        diff_remote = remote_sorted[1:] - remote_sorted[:-1]
        prev_size = sizes_sorted[:-1]

        contiguous = (diff_local == prev_size) & (diff_remote == prev_size)

        if not contiguous.any():
            return local_sorted.tolist(), remote_sorted.tolist(), sizes_sorted.tolist()

        if contiguous.all():
            total_size = int(sizes_sorted.sum())
            return [int(local_sorted[0])], [int(remote_sorted[0])], [total_size]

        break_positions = np.flatnonzero(~contiguous) + 1
        segment_starts = np.concatenate(([0], break_positions))
        segment_ends = np.concatenate((break_positions, [n]))

        seg_count = len(segment_starts)
        merged_local = [0] * seg_count
        merged_remote = [0] * seg_count
        merged_sizes = [0] * seg_count

        for si in range(seg_count):
            s = segment_starts[si]
            e = segment_ends[si]
            merged_local[si] = int(local_sorted[s])
            merged_remote[si] = int(remote_sorted[s])

            merged_sizes[si] = int(
                local_sorted[e - 1] + sizes_sorted[e - 1] - local_sorted[s]
            )

        return merged_local, merged_remote, merged_sizes

    def _compute_block_transfer_offsets(
        self,
        layer_name: str,
        local_block_ids: list[int],
        remote_block_ids: list[int],
        remote_moriio_meta: MoRIIOAgentMetadata,
        remote_tp_size: int | None = None,
    ) -> tuple[list[int], list[int], list[int]]:
        """Compute transfer offsets for block data.

        Args:
            layer_name: Name of the layer to transfer
            local_block_ids: IDs of local blocks
            remote_block_ids: IDs of remote blocks
            remote_moriio_meta: Metadata of the remote MoRIIO agent
        Returns:
            Tuple of (local_offsets, remote_offsets, transfer_sizes)
        """
        validate_moriio_heterogeneous_tp_kv_heads(
            local_tp_size=self.world_size,
            remote_tp_size=(
                remote_tp_size
                if remote_tp_size and remote_tp_size > 0
                else self.world_size
            ),
            total_num_kv_heads=self.model_config.get_total_num_kv_heads(),
            is_mla=self._is_mla_cache_layer(layer_name),
        )
        return compute_block_transfer_offsets(
            layer_name=layer_name,
            kv_cache=self.kv_caches[layer_name],
            layer_to_spec=self.layer_to_spec,
            local_block_ids=local_block_ids,
            remote_block_ids=remote_block_ids,
            remote_num_blocks=remote_moriio_meta.num_blocks,
            merge_fn=lambda local, remote, sizes: self.merge_contiguous_blocks(
                local, remote, sizes, assume_sorted=False
            ),
        )

    @staticmethod
    def _is_sq_full_status(status) -> bool:
        """True if a MoRIIO transfer status is a transient RDMA send-queue-full
        rejection (retryable backpressure), not a terminal failure.

        read_remote_data posts the RDMA READ synchronously (the mori executor
        joins its worker before returning and marks the status on the calling
        thread), so a send-queue-full rejection is a Failed() status the moment
        the call returns. mori surfaces it as a generic ERR_RDMA_OP carrying
        "SQ full" in the message (no distinct code), so we match the message.
        Only meaningful once status.Failed() is True.
        """
        try:
            return bool(status.Failed()) and "SQ full" in (status.Message() or "")
        except Exception:
            return False

    def _read_blocks(
        self,
        local_block_ids: list[int],
        remote_block_ids: list[int],
        dst_engine_id: str,
        request_id: str,
        transfer_id: str,
        remote_host: str,
        remote_notify_port: int,
        remote_tp_size: int,
        remote_dp_rank: int = 0,
        chosen_tp: int | None = None,
        flexible: bool = False,
    ) -> None:
        if self.mode == MoRIIOMode.WRITE:
            return

        # Read from the prefill rank that actually computed this request's KV
        # (forwarded by the proxy). Hardcoding DP0 reads from a different rank's
        # memory registration; per-rank num_blocks differ, so high block ids can
        # overrun the wrong rank's region.
        #
        # eff_tp = the remote TP rank this read targets. The flexible mirror
        # reads from a round-robin-chosen prefill TP rank and keys the session
        # per (dp, tp); other configs use the fixed local-rank mapping (eff_tp ==
        # _remote_tp_rank), byte-identical to before. This key MUST match the one
        # the eager handshake stored the session under.
        eff_tp = (
            int(chosen_tp)
            if chosen_tp is not None
            else self._remote_tp_rank(remote_tp_size)
        )
        if flexible:
            remote_dp_engine_id = self.get_engine_name_with_dp_tp(
                dst_engine_id, int(remote_dp_rank), eff_tp
            )
        else:
            remote_dp_engine_id = self.get_engine_name_with_dp(
                dst_engine_id, int(remote_dp_rank)
            )
        sessions, remote_moriio_meta = self._get_built_session(remote_dp_engine_id)

        # SQ-full backpressure deadline, shared across this request's layers.
        _sq_deadline = time.monotonic() + self.moriio_config.transfer_timeout
        for layer_name in self.layer_name_to_local_kv_cache_metadata:
            sess_idx = list(self.layer_name_to_local_kv_cache_metadata.keys()).index(
                layer_name
            )
            offs = self._compute_block_transfer_offsets(
                layer_name,
                local_block_ids,
                remote_block_ids,
                remote_moriio_meta,
                remote_tp_size=remote_tp_size,
            )
            # TODO : apply multi-session batch-read when moriio support it
            #
            # SQ-full backpressure: read_remote_data posts the RDMA READ
            # SYNCHRONOUSLY, so a send-queue-full rejection (per-QP HW cap) comes
            # back as a Failed() status right here. A SEPARATE CQ-poll thread
            # drains completions and frees SQ depth, so back off and RE-POST
            # rather than let a transient rejection abort the request. No
            # self-deadlock (the drain is off-thread); the reserve is
            # all-or-nothing (nothing posted on a rejected attempt). Bounded by
            # transfer_timeout; on sustained overload store the failed status and
            # let get_finished handle it non-fatally (notify prefill + drop).
            _backoff = 0.001
            while True:
                transfer_status = self.moriio_wrapper.read_remote_data(
                    offs[2], offs[0], offs[1], sessions[sess_idx]
                )
                if not self._is_sq_full_status(transfer_status):
                    break
                if time.monotonic() > _sq_deadline:
                    logger.warning(
                        "MoRIIO READ send queue stayed full past "
                        "transfer_timeout for req %s layer %s; storing failed "
                        "status (get_finished notifies prefill and drops the "
                        "request). Raise qp_per_transfer if frequent.",
                        request_id,
                        layer_name,
                    )
                    break
                time.sleep(_backoff)
                _backoff = min(_backoff * 2, 0.05)
            with self.moriio_wrapper.lock:
                self._recving_transfers[request_id][layer_name] = transfer_status
                self._recving_transfers_start.setdefault(request_id, time.monotonic())
                self._recving_transfers_callback_addr[request_id] = (
                    remote_host,
                    str(
                        remote_notify_port
                        + get_port_offset(
                            int(remote_dp_rank),
                            eff_tp,
                            remote_tp_size,
                        )
                    ),
                    transfer_id,
                )

_compute_block_transfer_offsets(layer_name, local_block_ids, remote_block_ids, remote_moriio_meta, remote_tp_size=None)

Compute transfer offsets for block data.

Parameters:

  • layer_name

    (str) –

    Name of the layer to transfer

  • local_block_ids

    (list[int]) –

    IDs of local blocks

  • remote_block_ids

    (list[int]) –

    IDs of remote blocks

  • remote_moriio_meta

    (MoRIIOAgentMetadata) –

    Metadata of the remote MoRIIO agent

Returns: Tuple of (local_offsets, remote_offsets, transfer_sizes)

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def _compute_block_transfer_offsets(
    self,
    layer_name: str,
    local_block_ids: list[int],
    remote_block_ids: list[int],
    remote_moriio_meta: MoRIIOAgentMetadata,
    remote_tp_size: int | None = None,
) -> tuple[list[int], list[int], list[int]]:
    """Compute transfer offsets for block data.

    Args:
        layer_name: Name of the layer to transfer
        local_block_ids: IDs of local blocks
        remote_block_ids: IDs of remote blocks
        remote_moriio_meta: Metadata of the remote MoRIIO agent
    Returns:
        Tuple of (local_offsets, remote_offsets, transfer_sizes)
    """
    validate_moriio_heterogeneous_tp_kv_heads(
        local_tp_size=self.world_size,
        remote_tp_size=(
            remote_tp_size
            if remote_tp_size and remote_tp_size > 0
            else self.world_size
        ),
        total_num_kv_heads=self.model_config.get_total_num_kv_heads(),
        is_mla=self._is_mla_cache_layer(layer_name),
    )
    return compute_block_transfer_offsets(
        layer_name=layer_name,
        kv_cache=self.kv_caches[layer_name],
        layer_to_spec=self.layer_to_spec,
        local_block_ids=local_block_ids,
        remote_block_ids=remote_block_ids,
        remote_num_blocks=remote_moriio_meta.num_blocks,
        merge_fn=lambda local, remote, sizes: self.merge_contiguous_blocks(
            local, remote, sizes, assume_sorted=False
        ),
    )

_eager_handshake_all_dp_ranks(metadata)

Handshake EVERY remote prefill DP rank BEFORE the decode forward pass, identically across all local TP workers.

Why this exists (the deadlock it prevents): with heterogeneous DP prefill a decode TP worker reads KV from whichever prefill DP rank owns the request, so across requests every worker must reach several prefill DP ranks. The decode forward issues per-layer TP collectives (e.g. an all-gather) that all local TP workers must enter together. If the handshakes are left to fire lazily on the read path, the workers diverge: a worker whose target rank is already cached races ahead into the forward collective while a peer is still blocked in a handshake recv(). The first worker then waits inside the collective for the stuck peer -> 600s NCCL timeout / hang. This was observed directly with mixed TP<->DP configs.

Fix: complete ALL prefill-DP-rank handshakes for every referenced remote engine HERE, before any read enters the forward, so no worker is still handshaking once its peers reach a collective. Fires ONCE per remote engine (first contact), gated by _eager_handshaked_engines. The engine set comes from scheduler-built metadata (identical on every TP worker), so all workers run the same handshakes in the same order and reach the all-reduce barrier below together.

Failure handling: handshake exceptions are caught, never raised before the collective (raising early would hang the peers still waiting for it). Every worker reaches the all-reduce(MIN) vote; if ANY worker failed, ALL raise the same error AFTER the collective, so the step fails fast and uniformly in ~seconds instead of one rank hanging the forward for 600s.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def _eager_handshake_all_dp_ranks(self, metadata: MoRIIOConnectorMetadata) -> None:
    """Handshake EVERY remote prefill DP rank BEFORE the decode forward pass,
    identically across all local TP workers.

    Why this exists (the deadlock it prevents): with heterogeneous DP prefill
    a decode TP worker reads KV from whichever prefill DP rank owns the
    request, so across requests every worker must reach several prefill DP
    ranks. The decode forward issues per-layer TP collectives (e.g. an
    all-gather) that all local TP workers must enter together. If the
    handshakes are left to fire lazily on the read path, the workers diverge:
    a worker whose target rank is already cached races ahead into the forward
    collective while a peer is still blocked in a handshake recv(). The first
    worker then waits inside the collective for the stuck peer -> 600s NCCL
    timeout / hang. This was observed directly with mixed TP<->DP configs.

    Fix: complete ALL prefill-DP-rank handshakes for every referenced remote
    engine HERE, before any read enters the forward, so no worker is still
    handshaking once its peers reach a collective. Fires ONCE per remote
    engine (first contact), gated by _eager_handshaked_engines. The engine
    set comes from scheduler-built metadata (identical on every TP worker),
    so all workers run the same handshakes in the same order and reach the
    all-reduce barrier below together.

    Failure handling: handshake exceptions are caught, never raised before
    the collective (raising early would hang the peers still waiting for it).
    Every worker reaches the all-reduce(MIN) vote; if ANY worker failed, ALL
    raise the same error AFTER the collective, so the step fails fast and
    uniformly in ~seconds instead of one rank hanging the forward for 600s.
    """
    import torch.distributed as dist

    # Distinct remote engines referenced this step, in metadata (==
    # scheduler) order so every TP worker iterates engines identically.
    engines: dict[str, ReqMeta] = {}
    for _req_id, meta in metadata.reqs_to_recv.items():
        remote_engine_id = (
            str(meta.remote_host) + ":" + str(meta.remote_handshake_port)
        )
        engines.setdefault(remote_engine_id, meta)

    for remote_engine_id, meta in engines.items():
        if remote_engine_id in self._eager_handshaked_engines:
            continue

        remote_dp_size = int(meta.remote_dp_size)
        port = int(meta.remote_handshake_port)
        tp_size = int(meta.tp_size)

        # Flexible mirror (TP prefill + MLA, world_size==1 decode): the read
        # round-robins over prefill TP ranks, so pre-warm a session to EVERY
        # (dp, tp) rank. Other configs pre-warm per DP rank (tp resolved by
        # the fixed local-rank mapping) -- byte-identical to before. The
        # mirror's decode is DP+EP, whose forward all-to-all is the collective
        # that the eager barrier keeps everyone in step for.
        flexible = (
            self.world_size == 1
            and self.use_mla
            and remote_dp_size == 1
            and tp_size > 1
        )
        # (engine_id, dp_rank, tp_rank_or_None); tp_rank is None on the legacy
        # path so _moriio_handshake falls back to its _remote_tp_rank mapping.
        targets: list[tuple[Any, int, int | None]]
        if flexible:
            targets = [
                (self.get_engine_name_with_dp_tp(remote_engine_id, dp, tp), dp, tp)
                for dp in range(remote_dp_size)
                for tp in range(max(1, tp_size))
            ]
        else:
            targets = [
                (self.get_engine_name_with_dp(remote_engine_id, dp), dp, None)
                for dp in range(remote_dp_size)
            ]

        # Submit handshakes for every not-yet-known target UNDER the lock; do
        # NOT hold it across the join or the collective (a stalled recv must
        # not block another thread's lock acquisition). Gate on BOTH
        # _remote_agents AND layer metadata: a rank with an agent entry but no
        # layer metadata is half-handshaked and would KeyError at read time.
        futures: list[tuple[str, Future[set[str]]]] = []
        with self._handshake_lock:
            for eid, cur_dp_rank, cur_tp_rank in targets:
                if (
                    eid in self._remote_agents
                    and eid in self.layer_name_to_remote_kv_cache_metadata
                ):
                    continue
                fut = self._handshake_initiation_executor.submit(
                    self._moriio_handshake,
                    meta.remote_host,
                    port,
                    tp_size,
                    eid,
                    cur_dp_rank,
                    cur_tp_rank,
                )
                futures.append((eid, fut))

        # Join outside the lock. Bounded handshake errors are recorded here
        # and reported after the all-reduce.
        all_ok = True
        results: dict[str, set[str]] = {}
        for eid, fut in futures:
            try:
                results[eid] = fut.result()
            except Exception:
                logger.exception("Eager MoRIIO handshake failed for %s", eid)
                all_ok = False

        with self._handshake_lock:
            for eid, agents in results.items():
                self._remote_agents[eid] = agents

        logger.info(
            "Eager MoRIIO handshake: engine=%s dp_size=%d new_ranks=%d "
            "ok=%s tp_rank=%d",
            remote_engine_id,
            remote_dp_size,
            len(futures),
            all_ok,
            self.tp_rank,
        )
        # CPU all-reduce = TP-uniform success vote AND lockstep barrier: it
        # blocks until every TP worker arrives, gives them the same verdict,
        # and stays off the model compute stream.
        vote = torch.tensor([1 if all_ok else 0], device="cpu", dtype=torch.int32)
        dist.all_reduce(vote, group=self.tp_group.cpu_group, op=dist.ReduceOp.MIN)
        if int(vote.item()) == 0:
            raise HandshakeError(
                f"Eager MoRIIO handshake failed for {remote_engine_id} on "
                "at least one TP rank; failing this step fast to avoid a "
                "TP collective hang"
            )

        self._eager_handshaked_engines.add(remote_engine_id)

_is_sq_full_status(status) staticmethod

True if a MoRIIO transfer status is a transient RDMA send-queue-full rejection (retryable backpressure), not a terminal failure.

read_remote_data posts the RDMA READ synchronously (the mori executor joins its worker before returning and marks the status on the calling thread), so a send-queue-full rejection is a Failed() status the moment the call returns. mori surfaces it as a generic ERR_RDMA_OP carrying "SQ full" in the message (no distinct code), so we match the message. Only meaningful once status.Failed() is True.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
@staticmethod
def _is_sq_full_status(status) -> bool:
    """True if a MoRIIO transfer status is a transient RDMA send-queue-full
    rejection (retryable backpressure), not a terminal failure.

    read_remote_data posts the RDMA READ synchronously (the mori executor
    joins its worker before returning and marks the status on the calling
    thread), so a send-queue-full rejection is a Failed() status the moment
    the call returns. mori surfaces it as a generic ERR_RDMA_OP carrying
    "SQ full" in the message (no distinct code), so we match the message.
    Only meaningful once status.Failed() is True.
    """
    try:
        return bool(status.Failed()) and "SQ full" in (status.Message() or "")
    except Exception:
        return False

_moriio_handshake(host, port, remote_tp_size, expected_engine_id, remote_dp_rank=0, remote_tp_rank=None)

Do a MoRIIO handshake with a remote instance.

remote_tp_rank: explicit remote TP index to dial. Flexible-read callers pass the chosen prefill TP rank so the handshake, the (dp, tp) session key and the notify port all address the SAME rank. None falls back to the local-rank mapping _remote_tp_rank -- byte-identical for callers not yet TP-aware.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def _moriio_handshake(
    self,
    host: str,
    port: int,
    remote_tp_size: int,
    expected_engine_id: str,
    remote_dp_rank: int = 0,
    remote_tp_rank: int | None = None,
) -> set[str]:
    """Do a MoRIIO handshake with a remote instance.

    remote_tp_rank: explicit remote TP index to dial. Flexible-read callers
    pass the chosen prefill TP rank so the handshake, the (dp, tp) session
    key and the notify port all address the SAME rank. None falls back to the
    local-rank mapping _remote_tp_rank -- byte-identical for callers not yet
    TP-aware.
    """

    start_time = time.perf_counter()

    # NOTE(rob): we need each rank to have a unique port. This is
    # a hack to keep us moving. We will switch when moving to etcd
    # or where we have a single ZMQ socket in the scheduler.

    dial_tp_rank = (
        self._remote_tp_rank(remote_tp_size)
        if remote_tp_rank is None
        else int(remote_tp_rank)
    )
    port_offset = get_port_offset(remote_dp_rank, dial_tp_rank, remote_tp_size)
    path = make_zmq_path("tcp", host, port + port_offset)
    logger.debug("handshake Querying metadata on path: %s", path)

    # Send query for the request.
    with zmq_ctx(zmq.DEALER, path) as sock:
        logger.debug("prepare send msg INSTAZNCE: %s", path)
        sock.send(MoRIIOConstants.GET_META_MSG)
        received_frame = sock.recv_multipart()
        if len(received_frame) != 2 or received_frame[0] != b"":
            raise HandshakeError(f"Unexpected frame! {received_frame = }")

        metadata_bytes = received_frame[1]
        decoder = msgspec.msgpack.Decoder(MoRIIOAgentMetadata)
        metadata = decoder.decode(metadata_bytes)
        got_metadata_time = time.perf_counter()
        logger.info(
            "MoRIIO handshake: get metadata took: %s",
            got_metadata_time - start_time,
        )

        self.moriio_wrapper.remote_engine_ip = host
        remote_agent_name = self.moriio_wrapper.register_remote_engine(
            metadata.agent_metadata
        )

        logger.debug(
            "MoRIIO handshake: registered"
            "remote agent %s for engine ID %s, path = %s",
            remote_agent_name,
            expected_engine_id,
            path,
        )

        if len(self.local_kv_cache_metadata) > 0:
            logger.warning(
                "len(self.local_kv_cache_metadata) = %s,"
                "maybe you didnt clear this buffer correctly",
                len(self.local_kv_cache_metadata),
            )
            self.local_kv_cache_metadata = []
        if len(self.remote_kv_cache_metadata) > 0:
            logger.warning(
                "len(self.remote_kv_cache_metadata) = %s,"
                "maybe you didnt clear this buffer correctly",
                len(self.remote_kv_cache_metadata),
            )
            self.remote_kv_cache_metadata = []

        received_frame = sock.recv_multipart()
        if len(received_frame) != 2 or received_frame[0] != b"":
            raise HandshakeError(f"unexpected frame! {received_frame = }")
        buf = received_frame[1]
        self.layer_name_to_remote_kv_cache_metadata[expected_engine_id] = (
            msgpack.loads(buf)
        )
        self.remote_moriio_metadata[expected_engine_id] = metadata
        setup_agent_time = time.perf_counter()
        logger.debug(
            "MoRIIO handshake: add agent took: %s",
            setup_agent_time - got_metadata_time,
        )

    return {remote_agent_name}

_moriio_handshake_listener(metadata, ready_event, base_port, tp_rank, dp_rank, layer_name_to_local_kv_cache_metadata) staticmethod

Background thread for getting new MoRIIO handshakes.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
@staticmethod
def _moriio_handshake_listener(
    metadata: MoRIIOAgentMetadata,
    ready_event: threading.Event,
    base_port: int,
    tp_rank: int,
    dp_rank: int,
    layer_name_to_local_kv_cache_metadata: dict,
):
    """Background thread for getting new MoRIIO handshakes."""

    encoder = msgspec.msgpack.Encoder()
    encoded_data = encoder.encode(metadata)
    size_in_bytes = len(encoded_data)
    logger.debug(
        "Size of encoded MoRIIOAgentMetadata: %s bytes", str(size_in_bytes)
    )

    # Listen for new requests for metadata.
    host = "*"

    path = make_zmq_path("tcp", host, base_port)
    logger.debug("mori handshake starting listening on path: %s", path)

    with zmq_ctx(zmq.ROUTER, path) as sock:
        ready_event.set()
        while True:
            identity, msg = sock.recv_multipart()
            if (
                msg != MoRIIOConstants.GET_META_MSG
                and msg != MoRIIOConstants.POP_DONE_RECV
            ):
                logger.error("Connection listener got unexpected message")
                raise HandshakeError("handshake failed, unexpected msg type")
            elif msg == MoRIIOConstants.GET_META_MSG:
                sock.send_multipart(
                    (identity, b"", encoded_data)
                )  # send local mori io engine meta data
                logger.debug("MoRIIO handshake listener sent metadata")
                # now we send tensor meta data for each block
                buf = msgpack.dumps(layer_name_to_local_kv_cache_metadata)
                sock.send_multipart((identity, b"", buf))
            elif msg == MoRIIOConstants.POP_DONE_RECV:
                _, req_id = sock.recv_multipart()
                logger.debug(
                    "MoRIIO handshake listener received done recv for req",
                    req_id.decode(),
                )

_next_flex_tp_rank(remote_tp_size)

Deterministic round-robin over prefill tp0..N-1 for the flexible read.

Round-robin (not random): exactly uniform and testable, with the same prefill-NIC balancing. Seeded from this decode rank's dp_rank so concurrent decode DP ranks are phase-staggered -- at a given read index distinct decode ranks target distinct prefill TP ranks.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def _next_flex_tp_rank(self, remote_tp_size: int) -> int:
    """Deterministic round-robin over prefill tp0..N-1 for the flexible read.

    Round-robin (not random): exactly uniform and testable, with the same
    prefill-NIC balancing. Seeded from this decode rank's dp_rank so
    concurrent decode DP ranks are phase-staggered -- at a given read index
    distinct decode ranks target distinct prefill TP ranks.
    """
    rr = getattr(self, "_flex_tp_rr", None)
    if rr is None:
        rr = int(getattr(self, "dp_rank", 0) or 0)
    self._flex_tp_rr = rr + 1
    return rr % remote_tp_size

_resolve_read_source(meta)

Resolve (chosen_tp, flexible) for reading this request's KV.

Flexible mirror (decode world_size==1 + MLA + pure-TP prefill): MLA replicates the latent KV across the prefill TP ranks, so any is a valid source; round-robin across them to spread RDMA/NIC load. Otherwise the source TP rank is fixed by the local-rank mapping (_remote_tp_rank) -- forward DP8EP->TP8 -> tp0; symmetric TP -> tp_rank -- byte-identical to prior behaviour. chosen_tp is the single value threaded into the (dp, tp) session key, the handshake dial and the notify port, so all three address the SAME prefill rank (drift -> read one rank but notify another -> the read rank's prefill buffer is never freed).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def _resolve_read_source(self, meta: ReqMeta) -> tuple[int, bool]:
    """Resolve (chosen_tp, flexible) for reading this request's KV.

    Flexible mirror (decode world_size==1 + MLA + pure-TP prefill): MLA
    replicates the latent KV across the prefill TP ranks, so any is a valid
    source; round-robin across them to spread RDMA/NIC load. Otherwise the
    source TP rank is fixed by the local-rank mapping (_remote_tp_rank) --
    forward DP8EP->TP8 -> tp0; symmetric TP -> tp_rank -- byte-identical to
    prior behaviour. chosen_tp is the single value threaded into the (dp, tp)
    session key, the handshake dial and the notify port, so all three address
    the SAME prefill rank (drift -> read one rank but notify another -> the
    read rank's prefill buffer is never freed).
    """
    remote_tp_size = int(meta.tp_size)
    flexible = (
        self.world_size == 1
        and self.use_mla
        and int(meta.remote_dp_size) == 1
        and remote_tp_size > 1
    )
    if flexible:
        chosen_tp = self._next_flex_tp_rank(remote_tp_size)
    else:
        chosen_tp = self._remote_tp_rank(remote_tp_size)
    return chosen_tp, flexible

get_finished()

Get requests that are done sending or recving on this specific worker. The scheduler process (via the MultiprocExecutor) will use this output to track which workers are done.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def get_finished(self) -> tuple[set[str], set[str]]:
    """
    Get requests that are done sending or recving on this specific worker.
    The scheduler process (via the MultiprocExecutor) will use this output
    to track which workers are done.
    """

    done_sending, done_recving = set(), set()

    if self.is_producer:
        # pop_finished_req_ids returns release ACKs sent by decode. Keep
        # duplicate ACKs because heterogeneous TP can fan multiple decode
        # ranks into one prefill rank for the same transfer_id.
        # Combine freshly-arrived ACKs with any buffered from prior ticks
        # whose transfer_id wasn't mapped yet (notify raced ahead of
        # start_load_kv); retry the lookup every tick. Buffered before
        # resolve_moriio_transfer_ack so each ACK is counted exactly once.
        finished_acks = self._pending_unmapped_acks + list(
            self.moriio_wrapper.pop_finished_req_ids()
        )
        self._pending_unmapped_acks = []
        resolved_transfer_ids: set[TransferId] = set()
        for ack in finished_acks:
            transfer_id = ack if isinstance(ack, str) else ack.transfer_id
            if transfer_id not in self.transfer_id_to_request_id:
                # Mapping not populated yet -- buffer and retry next tick,
                # do NOT drop (dropping leaks producer KV at high conc and
                # wedges the prefill).
                self._pending_unmapped_acks.append(ack)
                continue
            resolved_transfer_id = resolve_moriio_transfer_ack(
                ack,
                producer_tp_size=self.world_size,
                live_transfer_ids=self.transfer_id_to_request_id.keys(),
                notification_counts=self._consumer_notification_counts,
                completed_transfer_ids=(self._completed_consumer_notifications),
            )
            if resolved_transfer_id is not None:
                resolved_transfer_ids.add(resolved_transfer_id)
        done_sending = {
            self.transfer_id_to_request_id[xfer_id]
            for xfer_id in resolved_transfer_ids
        }
    else:
        if self.mode == MoRIIOMode.WRITE:
            fresh = self.moriio_wrapper.pop_finished_write_req_ids()
            # Accumulate with any completions that arrived before their
            # transfer_id was registered in transfer_id_to_request_id.
            self._unmatched_write_completions |= fresh
            done_recving = self._unmatched_write_completions
        else:
            # READ mode: the scheduler treats KV loads as synchronous
            # (load_kv_async=False), so requests go directly to RUNNING
            # instead of WAITING_FOR_REMOTE_KVS. We still call
            # _pop_done_transfers() to send the notify to the prefill
            # side and clean up internal state, but we must NOT report
            # these as done_recving because the scheduler doesn't
            # expect a finished_recving signal for RUNNING requests.
            self._pop_done_transfers()

    done_recving = {
        self.transfer_id_to_request_id[id]
        for id in filter(
            lambda id: id in self.transfer_id_to_request_id, done_recving
        )
    }
    if self.mode == MoRIIOMode.WRITE and not self.is_producer:
        # Remove the ones we successfully matched; leave unmatched for retry.
        matched_xfer_ids = {
            id
            for id in self._unmatched_write_completions
            if id in self.transfer_id_to_request_id
        }
        self._unmatched_write_completions -= matched_xfer_ids

    return done_sending, done_recving

register_kv_caches(kv_caches)

Register the KV Cache data in moriio.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def register_kv_caches(self, kv_caches: dict[str, torch.Tensor]):
    """Register the KV Cache data in moriio."""

    self.kv_caches = kv_caches  # layer name to kv cache
    self.kv_cache_shapes = {
        layer_name: kv_cache.shape for layer_name, kv_cache in kv_caches.items()
    }

    first_layer_name, first_kv_cache = next(
        (
            (layer_name, kv_cache)
            for layer_name, kv_cache in kv_caches.items()
            if (
                not self._is_mla_cache_layer(layer_name)
                and len(kv_cache.shape) == 5
                and (kv_cache.shape[0] == 2 or kv_cache.shape[1] == 2)
            )
        ),
        next(iter(kv_caches.items())),
    )
    kv_elem_size = first_kv_cache.element_size()

    use_mla = self._is_mla_cache_layer(first_layer_name)
    first_geometry = self._get_layer_transfer_geometry(first_layer_name)

    if use_mla:
        # MLA case.
        block_rank = 2  # [block_size, latent_dim]
        block_shape = first_kv_cache.shape[-block_rank:]
    else:
        # [2, num_blocks, ...] or [num_blocks, 2, ...]
        block_rank = 3  # [block_size, kv_heads, head_dim]
        block_shape = first_kv_cache.shape[-block_rank:]
    self.num_blocks = first_geometry.num_blocks
    self.slot_size_bytes = first_geometry.slot_size_bytes
    if first_geometry.block_size != self.block_size:
        # DeepSeek-V3 / MLA backends (e.g. FlashMLA) override the
        # configured block_size at attention-layer creation time, so
        # the KV cache tensor is laid out with a different (usually
        # larger) block_size than vllm_config.cache_config.block_size.
        # Trust the actual tensor shape and reconcile.
        logger.info(
            "KV cache block_size=%d differs from config block_size=%d; "
            "using actual tensor shape (attention backend override).",
            first_geometry.block_size,
            self.block_size,
        )
        self.block_size = first_geometry.block_size
    # TODO(tms): self.block_len needs to be per-layer for sliding window,
    # hybrid attn, etc
    # block size in bytes
    self.block_len = first_geometry.block_len
    self.kv_cache_shape = first_kv_cache.shape
    self.block_shape = block_shape
    self.kv_element_size = kv_elem_size

    self.dst_num_blocks[self.engine_id] = self.num_blocks
    kv_caches_base_addr = []
    caches_data = []

    for layer_name in kv_caches:
        geometry = self._get_layer_transfer_geometry(layer_name)
        if geometry.block_size != self.block_size:
            raise ValueError(
                "MoRIIO KV cache block size mismatch for layer "
                f"{layer_name}: {geometry.block_size} != {self.block_size}"
            )
        self.block_lens[layer_name] = geometry.block_len
        for cache, region_len in self._iter_layer_registration_regions(layer_name):
            base_addr = cache.data_ptr()
            caches_data.append((base_addr, region_len, cache.device.index, ""))
            kv_caches_base_addr.append(base_addr)

    for layer_name, kv_cache in kv_caches.items():
        if layer_name not in self.layer_name_to_local_kv_cache_metadata:
            self.layer_name_to_local_kv_cache_metadata[layer_name] = []

        moriio_mem_metadata = self.moriio_wrapper.register_local_tensor(kv_cache)
        self.layer_name_to_local_kv_cache_metadata[layer_name].append(
            moriio_mem_metadata
        )

        self.local_kv_cache_size.append(
            kv_cache.nelement() * kv_cache.element_size()
        )

    self.kv_caches_base_addr[self.engine_id] = kv_caches_base_addr
    self.num_regions = len(caches_data)
    self.num_layers = len(self.kv_caches.keys())

    # Optimization for models with local attention (Llama 4)
    if self.vllm_config.model_config.hf_config.model_type == "llama4":
        from transformers import Llama4TextConfig

        assert isinstance(
            self.vllm_config.model_config.hf_text_config, Llama4TextConfig
        )
        llama4_config = self.vllm_config.model_config.hf_text_config
        no_rope_layers = llama4_config.no_rope_layers
        chunk_size = llama4_config.attention_chunk_size
        chunk_block_size = math.ceil(chunk_size / self.block_size)
        for layer_idx in range(self.num_layers):
            # no_rope_layers[layer_idx] == 0 means NoPE (global)
            # Any other value means RoPE (local chunked)
            is_local_attention = no_rope_layers[layer_idx] != 0
            block_window = chunk_block_size if is_local_attention else None
            self.block_window_per_layer.append(block_window)
        logger.debug(
            "Llama 4 block window per layer mapping: %s",
            self.block_window_per_layer,
        )
        assert len(self.block_window_per_layer) == self.num_layers

    metadata = MoRIIOAgentMetadata(
        engine_id=self.engine_id,
        agent_metadata=self.moriio_wrapper.get_agent_metadata(),
        kv_caches_base_addr=self.kv_caches_base_addr[self.engine_id],
        num_blocks=self.num_blocks,
        block_len=self.block_len,
        attn_backend_name=self.backend_name,
    )
    ready_event = threading.Event()
    self._moriio_handshake_listener_t = threading.Thread(
        target=self._moriio_handshake_listener,
        args=(
            metadata,
            ready_event,
            self.side_channel_port,
            self.tp_rank,
            self.dp_rank,
            self.layer_name_to_local_kv_cache_metadata,
        ),
        daemon=True,
        name="moriio_handshake_listener",
    )
    self._moriio_handshake_listener_t.start()
    ready_event.wait()  # Wait for listener ZMQ socket to be ready.
    self.moriio_wrapper.async_wait_reqid()

schedule_write_blocks(request_id, transfer_id, dst_engine_id, local_block_ids, remote_block_ids, layer_name, kv_layer, remote_notify_port, remote_ip)

Schedule a block write operation.

Parameters:

  • request_id

    (ReqId) –

    Unique identifier for the request

  • transfer_id

    (TransferId) –

    Unique identifier for the transfer

  • dst_engine_id

    (str) –

    Destination engine ID

  • local_block_ids

    (list[int]) –

    Local block IDs to transfer

  • remote_block_ids

    (list[int] | None) –

    Hint for remote block IDs

  • layer_name

    (str) –

    Name of the layer

  • kv_layer

    (Tensor) –

    KV cache tensor

  • remote_notify_port

    (int) –

    Port for completion notification

  • remote_ip

    (str) –

    IP address of remote node

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def schedule_write_blocks(
    self,
    request_id: ReqId,
    transfer_id: TransferId,
    dst_engine_id: str,
    local_block_ids: list[int],
    remote_block_ids: list[int] | None,
    layer_name: str,
    kv_layer: torch.Tensor,
    remote_notify_port: int,
    remote_ip: str,
) -> None:
    """Schedule a block write operation.

    Args:
        request_id: Unique identifier for the request
        transfer_id: Unique identifier for the transfer
        dst_engine_id: Destination engine ID
        local_block_ids: Local block IDs to transfer
        remote_block_ids: Hint for remote block IDs
        layer_name: Name of the layer
        kv_layer: KV cache tensor
        remote_notify_port: Port for completion notification
        remote_ip: IP address of remote node
    """

    # synchronization to prevent dirty reads between
    # transfer and attention operations
    # we can consider removing this synchronization after ibgda is enabled.
    # when mori-io supports ibgda functionality

    stream = torch.cuda.current_stream()
    event = torch.cuda.Event()
    event.record(stream)

    task = WriteTask(
        request_id=request_id,
        transfer_id=transfer_id,
        dst_engine_id=dst_engine_id,
        local_block_ids=local_block_ids,
        remote_block_ids_hint=remote_block_ids,
        layer_name=layer_name,
        event=event,
        remote_notify_port=remote_notify_port,
        remote_ip=remote_ip,
    )
    self._writer.schedule_write(task)

start_load_kv(metadata)

Start loading by triggering non-blocking moriio_xfer. We check for these trnxs to complete in each step().

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def start_load_kv(self, metadata: MoRIIOConnectorMetadata):
    """
    Start loading by triggering non-blocking moriio_xfer.
    We check for these trnxs to complete in each step().
    """
    self.transfer_id_to_request_id = metadata.transfer_id_to_request_id
    if self.is_producer:
        live_transfer_ids = set(self.transfer_id_to_request_id)
        self._consumer_notification_counts = {
            transfer_id: count
            for transfer_id, count in self._consumer_notification_counts.items()
            if transfer_id in live_transfer_ids
        }
        self._completed_consumer_notifications.intersection_update(
            live_transfer_ids
        )
        self.moriio_wrapper.async_wait_reqid()
        return
    if self.mode == MoRIIOMode.WRITE:
        return

    # Handshake every referenced remote prefill rank up front, before any
    # read enters the forward pass. A lazy per-rank handshake on the read
    # path lets TP workers diverge into a forward collective while a peer is
    # still blocked handshaking -> NCCL hang (see below).
    self._eager_handshake_all_dp_ranks(metadata)

    wait_handshake_readd_req = False
    remote_engine_id = None

    for req_id, meta in metadata.reqs_to_recv.items():
        remote_engine_id = (
            str(meta.remote_host) + ":" + str(meta.remote_handshake_port)
        )
        meta.remote_engine_id = remote_engine_id
        # The eager handshake above already covered every referenced engine
        # (and keys the mirror per (dp, tp), which the DP-only dp0 probe below
        # would miss). Only fall back to the lazy background handshake for an
        # engine it did not cover.
        dp0_remote_engine_id = self.get_engine_name_with_dp(remote_engine_id, 0)
        if (
            remote_engine_id not in self._eager_handshaked_engines
            and dp0_remote_engine_id not in self._remote_agents
        ):
            # Initiate handshake with remote engine to exchange metadata.
            with self._handshake_lock:
                if remote_engine_id not in self._remote_agents:
                    self._background_moriio_handshake(
                        req_id, remote_engine_id, meta
                    )
                    wait_handshake_readd_req = True

                    continue

        # Handshake already completed, start async read xfer.
        self._read_blocks_for_req(req_id, meta)
    # Start transfers for requests whose handshakes have now finished.

    if remote_engine_id is None and not wait_handshake_readd_req:
        return
    _deadline = time.monotonic() + self.moriio_config.transfer_timeout
    while True:
        if (
            self._ready_requests.empty()
            and remote_engine_id not in self.load_ready_flag
            and wait_handshake_readd_req
        ):
            if time.monotonic() > _deadline:
                logger.warning(
                    "Timed out waiting for load_ready_flag[%s]; "
                    "adjust with kv_connector_extra_config.transfer_timeout",
                    remote_engine_id,
                )
                break
            time.sleep(0.001)
            continue
        elif (
            not self._ready_requests.empty()
            and remote_engine_id in self.load_ready_flag
        ):
            self._read_blocks_for_req(*self._ready_requests.get_nowait())
            break
        else:
            break

    self._reqs_to_send.update(metadata.reqs_to_send)

wait_for_layer_load(layer_name)

Block until all in-flight READs of this layer have landed.

A host-side blocking wait must not run during full-graph capture.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/moriio/moriio_connector.py
def wait_for_layer_load(self, layer_name: str) -> None:
    """Block until all in-flight READs of this layer have landed.

    A host-side blocking wait must not run during full-graph capture.
    """
    if self.is_producer or self.mode != MoRIIOMode.READ:
        return

    if get_forward_context().cudagraph_runtime_mode == CUDAGraphMode.FULL:
        return

    deadline = time.monotonic() + self.moriio_config.transfer_timeout
    while True:
        with self.moriio_wrapper.lock:
            pending = [
                status_by_layer[layer_name]
                for status_by_layer in self._recving_transfers.values()
                if layer_name in status_by_layer
            ]

        if not pending:
            return

        still_running = False
        for status in pending:
            # A failed read is dropped in _pop_done_transfers.
            if status.Succeeded() or status.Failed():
                continue
            still_running = True

        if not still_running:
            return

        if time.monotonic() > deadline:
            logger.warning(
                "MoRIIO READ barrier timed out for layer %s; proceeding "
                "(request dropped via get_finished).",
                layer_name,
            )
            return

        time.sleep(0.001)