Skip to content

feat(ep): Add KIWI EP dispatch/combine as an optional MORI op - #860

Merged
jhchouuu merged 36 commits into
mainfrom
charlifu/kiwi_intergration_ind
Nov 8, 2026
Merged

jhchouuu merged 36 commits into
mainfrom
charlifu/kiwi_intergration_ind

Conversation

@charlifu

@charlifu charlifu commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This adds KIWI's expert-parallel (EP) dispatch/combine kernels to MORI as mori.ops.dispatch_combine_kiwi. It's an opt-in, ROCm-only build behind BUILD_OPS_KIWI (off by default). In KIWI's design, GPU kernels don't post network operations themselves. Instead they push small descriptors into device-to-host queues in host memory, and CPU proxy threads pop the descriptors and issue the RDMA writes.

The port is self-contained:

  • It doesn't use MORI's shmem, ops or application layers.
  • It doesn't depend on LCI or MPI; the LCI transport is replaced by a small ibverbs layer.
  • Setup collectives run over a callback into torch.distributed.

The dispatch and combine kernels, the KIWI queue/invoke headers, and the workspace layout are unchanged from KIWI 8b6b9f4.

What's included

KIWI core, vendored under the mori::kiwi namespace:

  • include/mori/kiwi/queue/ and src/kiwi/queue/: the SPSC/MPSC device-to-host queues and SPSC/MPMC host-to-device queues.
  • include/mori/kiwi/invoke/: the callback-dispatch layer on top of the queues.
  • src/kiwi/topology/: maps each GPU to its nearest active NIC, and sets proxy-thread CPU affinity.
  • LICENSES/kiwi-hcqueue.txt: KIWI's MIT license.

ibverbs transport, replacing LCI (include/mori/kiwi/rdma/, src/kiwi/rdma/ibverbs.cpp):

  • net_context_t opens the NIC and protection domain, selects the GID, and registers memory with ibv_reg_dmabuf_mr (falling back to ibv_reg_mr).
  • device_t is one completion queue plus one RC QP per peer, created per proxy thread. QPs are connected through the bootstrap allgather.
  • Writes are posted with post_put and, for the 1-byte readiness flag, with post_puts (an inline RDMA write). Completions are read with poll_cq.
  • bootstrap_t / callback_bootstrap_t provide allgather and barrier. They replace LCI's global runtime and its collectives.

EP op (src/ops/dispatch_combine_kiwi/):

  • Dispatch and combine kernels and the count all-to-all, copied from KIWI.
  • Every LCI call in the communication layer (comm/context, comm/transport_callbacks, all2all, ep_context) is replaced:
    • rank queries and setup collectives now use the bootstrap;
    • device creation, memory registration, writes and completion polling now call ibverbs directly.
  • The heap is registered once and shared by all proxy devices (one protection domain). LCI registered it once per device.
  • ep_op.* and pybind_kiwi_ep.cpp are a new C++ op and a pybind module (libmori_kiwi_ep_pybinds.so) that MORI's Python layer loads.
  • Two backends:
    • rdma-only sends everything over RDMA.
    • hybrid uses HIP IPC for peers on the same host and RDMA across hosts.
    • auto, the default, picks one of them.

Python (python/mori/ops/dispatch_combine_kiwi.py):

  • EpDispatchCombineKiwiConfig / EpDispatchCombineKiwiOp, following the EpDispatchCombineOp interface: dispatch, combine, get_dispatch_src_token_pos, max_num_tokens_to_*.
  • Output buffers are zero-copy tensors over memory the op owns.
  • The combine dtype follows MORI's max_token_type_size rule and can be overridden with combine_dtype=.
  • is_available() reports whether the build includes KIWI. The module is imported lazily from mori.ops, so a normal build is unaffected.

Build and packaging:

  • CMakeLists.txt: the new BUILD_OPS_KIWI option, which requires USE_ROCM=ON and links libibverbs.
  • setup.py: reads the BUILD_OPS_KIWI environment variable, then copies libmori_ops_kiwi.so and libmori_kiwi_ep_pybinds.so into the package (or removes stale copies when the flag is off).

Tests and benchmark:

  • tests/python/ops/test_kiwi_dispatch_combine.py: correctness test following test_dispatch_combine_internode.py. It runs 8 ranks, covering tokens per rank {1, 32, 128} × backend {rdma-only, hybrid} × all data types, and checks results against the shared reference.
  • tests/python/ops/bench_kiwi_dispatch_combine.py: torchrun benchmark reporting median, min and max of per-rank medians, plus p90 and bandwidth, in graph or eager mode.

Build and test

BUILD_OPS_KIWI=ON pip install -e . --no-build-isolation
python3 -m pytest -sv tests/python/ops/test_kiwi_dispatch_combine.py
torchrun --nproc_per_node=8 tests/python/ops/bench_kiwi_dispatch_combine.py \
  --num-tokens 1,32,128 --rcomp-backend hybrid

Testing

All runs were on one 8×MI300X (gfx942) node with mlx5 InfiniBand NICs.

Correctness: 12 passed, 12 skipped. The skipped cases are float8_e4m3fn and FP4, which gfx942 doesn't support.

Performance parity with the original KIWI: I ran KIWI's bench_kiwi_ep.py under mpirun and this port's benchmark under torchrun. Both used bf16 dispatch and combine, 4 proxy threads, a queue capacity of 2048, and the same block counts, with runs alternated between the two. The numbers are the slowest rank's median, in µs:

Backend Tokens/rank Blocks Dispatch (KIWI / port) Combine (KIWI / port)
rdma-only 1 12 69.5 / 70.4 72.5 / 77.3
rdma-only 32 32 214.8 / 247.5 617.8 / 534.7
rdma-only 128 64 846.8 / 879.1 2265.8 / 2089.9
hybrid 32 32 241 / 240 255.5 / 257.2
hybrid 128 64 676 / 687 811 / 823

Overall the port is equal or slightly faster. The exception is rdma-only dispatch at 32 tokens, which is about 15% slower, but combine at that size is faster by more, so the total is lower (782 vs 833 µs). I haven't tracked down why. p90 isn't comparable between the two benchmarks: KIWI averages 10 replays per sample, while this benchmark times single replays.

Known limitations and follow-ups

  • Missing parts of the original KIWI interface:
    • combine(out=...);
    • combine scales (combine_scale_dim is fixed at 0);
    • the capture-state check in reset().
  • Behavior difference: decode_send_flat_idx decodes with max_num_tokens_to_send(), which is consistent with how indices are encoded. The original decoded with max_tokens_per_rank, which doesn't match its own encoding.

@jhchouuu
jhchouuu self-requested a review October 28, 2026 03:54
@jhchouuu jhchouuu self-assigned this Oct 28, 2026
@jhchouuu
jhchouuu requested a review from JiakunYan October 28, 2026 03:54
@charlifu charlifu changed the title [Feat] Add KIWI EP dispatch/combine as an optional MORI op (BUILD_OPS_KIWI) feat(ep) Add KIWI EP dispatch/combine as an optional MORI op (BUILD_OPS_KIWI) Oct 28, 2026
Bring the vendored KIWI sources up to KIWI 6efc720 (from 8b6b9f4):

- LL8 device-to-host chunk format (#102): each 16-byte chunk is now two
  halves of 4 B data + 4 B signal, so the consumer relies only on 8-byte
  single-copy atomicity. Updates chunk.hip.hpp and chunk_consumer.hpp.
- Pin proxy threads using the GPU's PCI local_cpulist instead of KFD's
  cpu_core_id_base, which is an APIC id on two-socket SMT hosts (#113).
- Comment updates from the open-source release prep (#111).
@charlifu

charlifu commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

This updates mori's vendored KIWI sources from KIWI 8b6b9f4 to 6efc720. Six files change, with 127 lines added and 71 removed.

Functional changes

  • New chunk format for device-to-host messages (KIWI 102). This changes the format on both sides of the queue.
    • Each 16-byte chunk now holds two halves of 4 bytes of data plus 4 bytes of signal, instead of 8 bytes of data plus 8 bytes of signal.
    • Every signal guards the 4 data bytes next to it. The host consumer therefore only needs aligned 8-byte reads to be atomic, rather than 16-byte reads.
    • The 32-bit metadata is split across the two signals, and the host checks all eight epochs of a line at once.
    • Files: include/mori/kiwi/queue/detail/chunk.hip.hpp (GPU producer) and src/kiwi/queue/chunk_consumer.hpp (host consumer).
  • Proxy thread CPU pinning (KIWI 113).
    • src/kiwi/topology/topology.cpp now reads the GPU's local CPUs from the PCI device's sysfs local_cpulist.
    • Previously it used KFD's cpu_core_id_base. That value is a hardware (APIC) ID, not a Linux CPU ID, so on two-socket hosts with hyperthreading it pinned proxies to CPUs on the wrong socket.
    • If local_cpulist is unavailable, pinning falls back to the process's allowed CPUs as before.

Comment-only changes (KIWI 111): queue.hpp, device_to_host_queue.hip.hpp and ep_config.hpp.

@JiakunYan

@JiakunYan

Copy link
Copy Markdown
Collaborator

@charlifu Thanks for the port! Most of this is kiwi 6efc720 unchanged, so I focused on the new parts. Several of them duplicate code mori already has. Reusing it would cut about 1.3–1.5k lines and leave much less new RDMA code to review.

1. Reuse mori's RDMA layer instead of rdma/ibverbs.{hpp,cpp}. Most of this file is already in mori: NIC/port selection (MatchGpuAndNic, ActiveGbps), GID selection (AutoSelectGidIndex), memory registration (RegisterRdmaMemoryRegionAuto) and QP setup (CreateRdmaEndpoint + ConnectEndpoint). The shmem host proxy (#558) already creates endpoints this way and calls ibv_post_send/ibv_poll_cq on them directly. Only the post/poll/credit hot path needs to stay (~100–150 lines). One gap: CreateRdmaEndpoint always creates a CQ per endpoint, but here each proxy thread shares one CQ. We may need to change it here or open a small separate PR adding an optional shared CQ to RdmaEndpointConfig (@jhchouuu we may need your judgement here).

2. Reuse mori's topology and bootstrap.

  • NIC selection in topology.cpp can use TopoSystem::MatchGpuAndNic. Only the CPU-pinning code needs to stay. Please check that MatchGpuAndNic also spreads GPUs evenly across equally close NICs.
  • bootstrap_t duplicates BootstrapNetwork. A small subclass wrapping the torch callback would replace it.

3. Drop the debug code: the KIWI_EP_DIAG_* switches and the debug_time_buf/DEBUG_*_WORDS timing code.

Minor

  • The description still says 8b6b9f4. Also, the KIWI #102/#111/#113 references in the sync comment link to unrelated mori PRs.

Address review feedback on the KIWI EP port:

- Replace rdma/ibverbs.{hpp,cpp} with comm/rdma.{hpp,cpp} on mori's RDMA
  layer. NIC/port selection, GID selection, memory registration
  (RegisterRdmaMemoryRegionAuto) and QP setup (CreateRdmaEndpoint +
  ConnectEndpoint) now come from mori_application; only the post, poll and
  per-QP send-credit path remains. Each rank's endpoint keeps mori's own CQ,
  and poll_cq sweeps the CQs of ranks with outstanding writes.
- Select the NIC with TopoSystem::MatchGpuAndNic (MORI_KIWI_DEVICE_NAME and
  the explicit device_name still override it) and drop KIWI's NIC
  selection from topology.cpp; only proxy-thread CPU pinning remains.
- Replace bootstrap_t with a BootstrapNetwork subclass that wraps the
  torch allgather callback.
- Remove the KIWI_EP_DIAG_* switches and the debug_time_buf /
  DEBUG_*_WORDS timing code from the kernels, op, pybind and Python API.

mori_ops_kiwi now links mori_application and embeds mori_ibv_shim instead
of linking libibverbs, so BUILD_OPS_KIWI requires BUILD_APPLICATION.
GID, service level, traffic class and DMA-BUF registration follow mori's
MORI_IB_GID_INDEX / MORI_ENABLE_DMABUF_REG settings.
@JiakunYan

Copy link
Copy Markdown
Collaborator

Thanks, this looks good. Just two more minor things:

  1. Dead code: ep_context_t::copy_dest_token_counts_to_host, copy_dispatch_recv_counts_to_host and copy_token_route_metadata_to_host have no callers in this PR (kiwi's C++ tests used them, but those weren't ported). Please remove them.
  2. Please remove LICENSES/kiwi-hcqueue.txt. It's KIWI's pre-release license file ("hcqueue contributors"), which KIWI dropped in its open-source prep. KIWI is now MIT under the AMD copyright, the same as mori, so the files' standard mori headers and mori's LICENSE cover it.

charlifu and others added 2 commits October 30, 2026 22:53
Remove ep_context_t::copy_dest_token_counts_to_host,
copy_dispatch_recv_counts_to_host and copy_token_route_metadata_to_host;
only KIWI's unported C++ tests called them.

Remove LICENSES/kiwi-hcqueue.txt, KIWI's pre-release license. KIWI is MIT
under the AMD copyright, so the standard mori headers and LICENSE cover it.
Co-authored-by: Cursor <cursoragent@cursor.com>

@jhchouuu jhchouuu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed as step 1 of the plan we agreed on: land KIWI EP as an isolated, default-OFF op now; the transport moves into cco in step 2, and the kernels become an EPv2 kernel family in step 3, when this module goes away. Comments starting with "Blocking:" are the ones I'd like resolved before merge.

Tested at 5dd1098 on 2x MI300X + CX7 InfiniBand: the single-node test passes, and EP16 passes for hybrid/rdma-only/auto x bf16/fp8 at 1-128 tokens.

The step 2/3 items we already discussed will be handled as follow-ups.

Comment on lines +96 to +100
const int num_blocks = num_tokens == 1 ? 12
: num_tokens == 2 ? 20
: num_tokens <= 32 ? 32
: num_tokens <= 64 ? 64
: 256;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: Both kernels use a grid barrier, so every block must be co-resident, but this picks 256 blocks for >64 tokens without checking the device, and an explicit num_blocks is only checked to be positive (ep_context.hip.cpp:128-132). On MI300X (304 CUs) 305 blocks hang silently; on MI308X (80 CUs) 81 do. Could an unsupported block count fail with an error instead?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4303883 (clang-format follow-up in 2c73519).

ep_context_t now rejects an unsupported block count at construction instead of hanging. After the existing positive check, it reads the current device's compute-unit count (hipDeviceAttributeMultiprocessorCount) and throws std::invalid_argument if provisioned_num_blocks exceeds it. The message gives both numbers and the device index.

This covers both paths you mentioned:

  • Automatic mode provisions from recommended_num_blocks(max_num_inp_token_per_rank, ...), so 256 blocks on an 80-CU MI308X now fails at setup.
  • An explicit num_blocks is checked the same way, so 305 on an MI300X is rejected.

}
}
}
if (num_valid > 0) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: A token whose top-k ids are all -1 has num_valid == 0, so its row is skipped here, but _combine_out is a reused torch.empty (dispatch_combine_kiwi.py:269), so the token gets the previous call's row (or uninitialized memory) instead of zeros. The tests never generate such a token. Is that intended, given that padding tokens are often all -1?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36c8b1.

Agreed, this wasn't intended. A token whose top-k IDs are all -1 now combines to a zero row, the same result MORI EP gives. MORI never zeroes its combine buffer either; its WarpAccum helpers skip null sources and always store the accumulator.

Kernel: I removed the if (num_valid > 0) guards from all four reducers (float, bf16, FP8 and FP4), in both the vectorized and scalar loops. Each reducer already starts from a zero accumulator, so with no valid sources it stores zeros instead of skipping the row. Output weights needed no change, because that loop already wrote its sum unconditionally. I also dropped the "pre-zeroed" note on d_output, since the kernel now writes every row itself.

Tokens with at least one valid expert already took the store, so normal traffic has no extra writes.

Test: I added test_dispatch_combine_unrouted_token for both rdma-only and hybrid. The first dispatch/combine is fully routed, which fills the reused _combine_out buffer. The second sets token 0's top-k to all -1 and checks that its output row and weights are zero rather than left over from the first call. The full test_kiwi_dispatch_combine.py passes on 8 GPUs.

# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""KIWI EP dispatch/combine with the same Python interface as EpDispatchCombineOp.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: This is not the same interface as EpDispatchCombineOp: the dtype is fixed at construction, block_num/warp_per_block/use_external_inp_buf are ignored, and combine's indices never reach the kernel. Since the module goes away in step 3, could this claim be dropped and the module marked experimental?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in af78277.

I dropped the "same Python interface as EpDispatchCombineOp" claim. The module docstring now says the module is experimental and will be removed once KIWI is a kernel type of EpDispatchCombineOp. It also says the module follows the EpDispatchCombineOp calling convention but isn't a drop-in replacement, and lists the three differences you raised:

  • the dispatch and combine dtypes are fixed at construction, and combine() rejects any other dtype;
  • block_num, rdma_block_num, warp_per_block and use_external_inp_buf are accepted for compatibility and ignored, because KIWI chooses its launch shape from the token count or num_blocks;
  • combine() routes with what the preceding dispatch() recorded, so its indices argument is only shape-checked.

EpDispatchCombineKiwiOp is also marked experimental, and the combine() docstring says indices must match what was passed to dispatch().

This is a documentation-only change; the behavior is the same. The bf16-only combine restriction from your other comment is in 2fce36d, which also adds it to this list.

Comment on lines +215 to +217
self._combine_dtype = (
combine_dtype if combine_dtype is not None else _combine_dtype(config)
)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: Only bf16 combine is tested, and several other dtypes don't match the reducer: every float8 type is decoded as e4m3 FNUZ (combine.hip.cpp:140-156), fp16 is summed as bf16 (combine.hip.cpp:713-716), and a 1-byte "none" dtype writes nothing (combine.hip.cpp:718-728). Could construction reject non-bf16 combine dtypes for now?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2fce36d.

Agreed. The reducer picks its decode path from the element size alone, so every combine dtype other than bf16 is either untested or wrong. Construction now rejects them.

EpDispatchCombineKiwiOp.__init__ resolves the combine dtype first, from combine_dtype or the max_token_type_size default, and raises ValueError unless it's torch.bfloat16. The message names the dtype it got and suggests combine_dtype=torch.bfloat16 or max_token_type_size=2. The check runs before the extension loads or any GPU setup, so a bad config fails right away.

It also covers the cases where the default rule silently picks something else: float32 when max_token_type_size=4, and fp8 combine when max_token_type_size matches an fp8 dispatch dtype. Dispatch dtypes are unchanged, so fp8 dispatch with bf16 combine still works.

The combine_dtype argument docs and the module docstring's list of differences now say combine supports only bfloat16. The existing tests and the benchmark already resolve to bf16 through max_token_type_size=2, so they're unaffected.

Other combine dtypes can be enabled once each has a matching reducer path and a test. That means OCP fp8 and e5m2 decoding, a real fp16 path, and float32 coverage.

Comment thread src/kiwi/CMakeLists.txt Outdated
set_source_files_properties(${MORI_KIWI_SOURCES} PROPERTIES LANGUAGE HIP)

add_library(mori_kiwi STATIC ${MORI_KIWI_SOURCES})
target_include_directories(mori_kiwi PUBLIC ${CMAKE_SOURCE_DIR}/include

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: include/mori/kiwi (20 headers) is installed and packed into every wheel even with BUILD_OPS_KIWI=OFF (top-level CMakeLists.txt:414, setup.py:348). Since steps 2-3 replace these, could they stay private to the build, like UMBP's src/umbp/include?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5681860.

The 20 headers moved from include/mori/kiwi/ to src/kiwi/include/mori/kiwi/, the same layout as UMBP's src/umbp/include. Git records them as renames with no content changes. The mori/kiwi/ prefix is kept, so every #include <mori/kiwi/...> works unchanged.

mori_kiwi now exposes them through target_include_directories(mori_kiwi PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) instead of the top-level include/. mori_ops_kiwi gets the path from its existing public link to mori_kiwi. Nothing outside src/kiwi and src/ops/dispatch_combine_kiwi includes these headers, and the KIWI sources include only mori/kiwi/..., so no other build changes were needed.

Both paths you pointed out read only from the top-level include/, so neither picks the headers up anymore:

  • the install(DIRECTORY include/mori ...) rule at CMakeLists.txt:414;
  • _copy_jit_sources in setup.py, which builds the wheel's _jit-sources tree.

This holds whether BUILD_OPS_KIWI is on or off.

I checked it with a BUILD_OPS_KIWI=ON rebuild. The KIWI tests pass, and the installed package has no mori/kiwi headers.

Comment on lines +62 to +63
std::array<char, EP_HOSTNAME_BYTES> local_hostname{};
KIWI_EP_ASSERT(gethostname(local_hostname.data(), local_hostname.size()) == 0,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same-node grouping here and at ep_context.hip.cpp:152-169 compares raw gethostname(), while mori uses ResolveNodeId (include/mori/utils/host_utils.hpp:48). Since all2all_t is built for every backend, two hosts sharing a hostname would try to open each other's IPC handles even with rdma-only. Should both use ResolveNodeId?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, both now use ResolveNodeId, in c28ed66. ep_context_t allgathers one {node id, hostname} record per rank for every backend. all2all_t receives those node ids and groups ranks by them, and hybrid's same-node IPC peers also compare node ids. So MORI_NODE_ID, then the boot id, then the hostname decide what counts as a node, as elsewhere in mori. Hostnames are now used only in the setup error messages, which show "hostname [node id]". I tested on one host with 8 GPUs by setting MORI_NODE_ID per rank to split it into two nodes of 4. rdma-only, hybrid and auto all pass and report nodes=2 local_size=4, and a non-contiguous assignment aborts with "ranks for one node are not contiguous". The normal single-node runs and the KIWI tests still pass.

Comment on lines +188 to +189
rcomp_backend: "auto", "rdma-only", or "hybrid" (HIP IPC for peers on
the same host).

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rdma-only still uses HIP IPC for the count all-to-all and barrier (all2all.hip.cpp:123-141), and construction aborts unless ranks form contiguous, equal-size hostname groups (all2all.hip.cpp:79-99). Could the docstring say so?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in 2a334bd. The _rcomp_backend entry now says the argument only decides how token payloads reach peers on the same host. rdma-only sends them over RDMA, hybrid writes them through HIP IPC, and auto picks one per call. Every backend still uses HIP IPC between same-host ranks for the count all-to-all and the barrier. The module docstring's list of differences from EpDispatchCombineOp now also says that each host's ranks must be contiguous and every host must have the same number of ranks, and that construction aborts the process otherwise, for every backend.

}

ep_op_t::~ep_op_t() {
if (ctx_) ctx_->join_proxy_threads();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Teardown joins the proxies and frees memory without waiting for kernels already enqueued, so anything they post after the final drain is never sent; the EPv1 handle calls hipDeviceSynchronize() first (src/ops/dispatch_combine/dispatch_combine.cpp:225). Should the caller synchronize, or should teardown wait?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Teardown should wait; the caller can't be relied on here, since the Python op is usually freed by garbage collection. Fixed in 3042b63: ~ep_op_t now calls hipDeviceSynchronize() before join_proxy_threads(), as the EPv1 handle does. It's a device-wide sync because dispatch and combine run on whatever stream the caller passes, and the op doesn't track them. Once the kernels finish, the proxies' existing final drain flushes everything they posted before any memory is freed. I tested it with a stress run that, 30 times, creates the op on 8 GPUs, enqueues four dispatch and combine pairs, and destroys the op without synchronizing. Without the fix, rdma-only hangs every time; with it, rdma-only, hybrid and auto all complete. The KIWI tests and the 8-GPU entry still pass. One limitation is the same as in EPv1: if a kernel is waiting on a peer that has already torn down, it still hangs, so ranks need to stop issuing work before teardown. I didn't add a barrier to the destructor because a collective in a destructor deadlocks when ranks free the op at different times.

BUILD_RPATH "$ORIGIN;${ROCM_PATH}/lib"
INSTALL_RPATH "$ORIGIN;${ROCM_PATH}/lib"
BUILD_WITH_INSTALL_RPATH TRUE)
install(TARGETS mori_ops_kiwi LIBRARY DESTINATION lib)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: libmori_ops_kiwi.so is installed but has no installed header and one consumer (L49), and it exports the mori::kiwi symbols (no --exclude-libs as in src/cco/CMakeLists.txt:29). Does it need to be a separate shared library?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can leave this to step 2.

Comment on lines +149 to +150
if (rank_me == 0) {
std::fprintf(stderr,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Rank 0 prints this to stderr on every construction, also for rdma-only. Could it go through mori's logger?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 4545d61. The message now goes through MORI_OPS_DEBUG, so it's silent by default and shows up with MORI_OPS_LOG_LEVEL=debug, still on rank 0 only. I also dropped the "hybrid" label, since this all-to-all runs for every backend, and the fixed layout details, so it now reads "kiwi-ep count all-to-all: nodes=N local_size=M". The other fprintf calls in the KIWI op are error messages right before an abort and stay as they are. A default 8-GPU run prints nothing, a run at debug level prints the line once, and the KIWI tests pass.

charlifu and others added 8 commits November 3, 2026 17:33
Dispatch and combine wait on a grid barrier, so a launch that cannot stay resident hangs. Fail context setup instead.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
A token whose top-k ids are all -1 skipped its output store, leaving the reused combine buffer's previous row. Always store the accumulator and test this case.

Co-authored-by: Cursor <cursoragent@cursor.com>
…nces

The module follows the EpDispatchCombineOp calling convention but is not a drop-in replacement: dtypes are fixed at construction, launch-shape arguments are ignored, and combine reuses dispatch's routing.

Co-authored-by: Cursor <cursoragent@cursor.com>
The combine reducer picks its decode path from the element size, so fp16, non-FNUZ fp8 and 1-byte integer combine are reduced wrong or not written. Only bfloat16 is tested.

Co-authored-by: Cursor <cursoragent@cursor.com>
The headers lived under include/mori/kiwi, so they were installed and packed into every wheel even with BUILD_OPS_KIWI=OFF. Move them to src/kiwi/include, like UMBP's src/umbp/include, and expose them only through the mori_kiwi target.

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
KIWI device code assumes wave64 and uses the gfx94x/gfx950 sc0/sc1
cache-policy bits, which gfx90a and gfx12 reject. src/kiwi now filters
CMAKE_HIP_ARCHITECTURES to gfx942/gfx950 for both KIWI directories, warns
about skipped targets, and fails at configure time if none remain.

The wave64 guard in chunk.hip.hpp checks __gfx942__/__gfx950__ instead of
__GFX9__, which the top-level build defines for every target when the first
GPU_TARGETS entry is gfx9.
charlifu and others added 14 commits November 4, 2026 22:06
No CI job built with BUILD_OPS_KIWI=ON, so test_kiwi_dispatch_combine.py
always skipped, and it is single-node, so the cross-node paths never ran.

On MI300X_MLX (matrix build_ops_kiwi), the intranode job now builds KIWI
and runs test_kiwi_dispatch_combine.py, and the internode job builds it on
both nodes and runs EP16 for rdma-only/hybrid/auto x bf16/fp8_e4m3_fnuz
through the new torchrun entry test_kiwi_dispatch_combine_internode.py.

The pytest file also covers the auto backend, which switches between
rdma-only and hybrid per launch. EpDispatchCombineTestCase derives its
device from rank % gpu_per_node so it works with ranks on several nodes.
rank % gpu_per_node put the test tensors of ranks 4-7 on GPUs 0-3 in the
single-host tests that emulate two nodes with gpu_per_node=4, so
test_dispatch_combine_minus_one_sentinel faulted in
EpDispatchCopyToStaging. Every caller sets its device before building the
helper (TorchDistContext, or LOCAL_RANK in the multi-node KIWI entry), so use
torch.cuda.current_device().
…ly too

Several waves write each token's RDMA staging slot, and the route-owner wave
then posts it to the proxy. The s_waitcnt(0) before the block barrier was
compiled only for hybrid, and on gfx942 __syncthreads() lowers to a bare
s_barrier that does not wait for outstanding global stores, so with
rdma-only the slot could be posted while other waves' stores were still in
flight. The owner's own s_waitcnt(0) covers only its wave.

Make the drain unconditional. EP8 rdma-only latency at 1-128 tokens is
unchanged within noise.
Drop the write-only token_to_dispatch_recv_slot map, the synchronizing
dispatch()/combine() wrappers, grid_barrier_advance_ticket,
grid_barrier_arrive_and_wait, the rcomp_peer_is_*() accessors, and the
write-only gctx fields model_hidden_dim, max_slots, combine_scale_dim,
combine_scale_type_size and dispatch_quant_format.
num_proxy_threads, queue_capacity, rcomp_backend and device_name tune
KIWI's own transport and may change once KIWI moves to MORI's transport.
Prefix them with an underscore and document them as unstable, and accept
only the documented rcomp_backend names (auto, rdma-only, hybrid).
is_available() caught every ImportError from loading the extension, so a
KIWI build whose library failed to load made the KIWI tests skip as if
BUILD_OPS_KIWI were off. Check only that the library exists; a load
failure now raises when the op is constructed.
Rank 0 printed the all-to-all layout to stderr on every construction,
labelled hybrid even for rdma-only. Log it with MORI_OPS_DEBUG so it is
silent unless MORI_OPS_LOG_LEVEL=debug.
- Remove the MPSC device-to-host, SPSC host-to-device and MPMC host-to-device queues, slot.hip.hpp and config.hpp
- Drop their sources from mori_kiwi, their aliases and includes, and HIP_CHECK_NOEXCEPT
- Describe only the SPSC device-to-host queue in the queue docs

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The op destructor joined the proxy threads and freed memory without
waiting for dispatch/combine kernels still on the caller's streams, so
anything they posted after the proxies' final drain was never sent and
peers could hang. Synchronize the device first, as the EPv1 handle does.
_rcomp_backend only selects how token payloads reach same-host peers;
every backend uses HIP IPC between same-host ranks for the count
all-to-all and barrier. Construction also aborts unless each host's
ranks are contiguous and every host has the same number of ranks.
The KIWI bindings module never links libpython, and the manylinux
interpreters used for the published wheels do not ship one. Match the
other mori pybind modules (#852).
The count all-to-all and hybrid's IPC peer selection compared raw
gethostname() strings, so machines sharing a hostname were treated as one
node and tried to open each other's IPC handles, even with rdma-only.
Gather mori::ResolveNodeId (MORI_NODE_ID, then boot id, then hostname)
once per rank and use it for both; hostnames remain only in setup error
messages.
The automatic block table returns 256 blocks for more than 64 tokens,
which exceeds the CU count of smaller devices such as an 80-CU MI308X and
made construction throw. make_config now records the CU count in
config_t::max_auto_num_blocks, and automatic provisioning and per-launch
block counts are capped at it. Explicit num_blocks is used as given.

@jhchouuu jhchouuu left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM
thanks to @charlifu @JiakunYan again!

@jhchouuu jhchouuu changed the title feat(ep) Add KIWI EP dispatch/combine as an optional MORI op (BUILD_OPS_KIWI) feat(ep): Add KIWI EP dispatch/combine as an optional MORI op Nov 8, 2026
@jhchouuu
jhchouuu merged commit f85fd99 into main Nov 8, 2026
15 checks passed
@jhchouuu jhchouuu mentioned this pull request Nov 8, 2026
1 of 3 tasks
@charlifu

charlifu commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Two-node test

tokens/rank v1 (eager sum) v1 (one CUDA graph) KIWI auto graph KIWI auto eager KIWI hybrid graph KIWI hybrid eager KIWI rdma-only graph KIWI rdma-only eager Best KIWI vs v1
1 211 212 95 91 75 80 81 98 KIWI 2.8× faster
32 252 251 149 131 136 131 195 189 KIWI 1.9× faster
64 284 282 301 303 308 305 343 340 v1 1.06× faster
128 356 348 565 572 565 571 630 627 v1 1.6× faster
256 520 501 1091 1065 1075 1076 1128 1115 v1 2.0× faster
512 729 724 2199 2204 2263 2148 2746 2878 v1 2.9× faster
1024 1230 1231 5472 5444 5409 5432 5605 5525 v1 4.4× faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants