From f73a751e54a667e830de7f514bd23cd029c400ed Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 08:37:29 -0800 Subject: [PATCH 1/4] helios,flare-cli,ignition: sync ABI-14 RoCE proxy (#672/#649/#577) and wire roce_set_relay Why: Manual vendoring of `helios/native/roce_proxy.c` blocked three companion RoCE transport updates while native serving omitted the two-shot all-gather relay (`roce_set_relay`) already compiled into the proxy. Multi-HCA hosts with distinct per-device IPv4 RoCEv2 GID slots dropped active rails during discovery; switchless closed rings routed large prefill reduce-scatter and shard-gather traffic over 2-hop CPU mailboxes; `RING_WINDOW = 8` sat below the 2-hop relay BDP knee without a connect-time window/size guard; and hybrid switch-plus-cable mesh clusters sent all-gather shards over the switch instead of forwarding over direct partner cables. What changed: - Before: `helios/native/roce_proxy.c` tracked FlashInfer `5a8ceed80c` (single context GID index, opcodes `0..6`, `RING_WINDOW = 8`, 1168-byte `roce_blob_t`, `reserve()` at `/6`, `ring_service_slot()` at `/4`, no eager ring drain in `run_pipe_op`). `roce_fabric::discover_in` required one host-wide GID index, `Fabric::topology` computed `direct` without a relay plan, and `RoceTransport::connect` never called `roce_set_relay`. - After: - Re-vendored `helios/native/roce_proxy.c` byte-for-byte after its 9-line header from the unified FlashInfer branch (`#209 + #195 + rebased #157`): per-HCA `roce_create_with_gids`, 1-hop closed-ring opcodes `KIND_RING_RS/AG/RSAG = 7..9` with extended `credit_phases()`, `RING_WINDOW = 16` with connect-time `(ring_window, ring_bytes)` validation (`1176`-byte `roce_blob_t`, preserving `ROCE_ABI_VERSION = 14`), named SQE limits `ROCE_RESERVE_OPS = 48 < ROCE_RELAY_OPS = 64` with `drain_cqs` polled before `ring_service` in `drain_all`, and eager `drain_all(c)` in `run_pipe_op` when `c->ring != NULL`. - Updated `helios/src/execution/roce_fabric.rs`, `helios/src/execution/roce.rs`, `heliopause/src/python.rs`, `ignition/preparation/collectives.py`, `flare-cli/src/doctor/spark.rs`, and `docs/cli-design.md` to select and pass per-HCA GID indices (`roce_create_with_gids`, `roce_devices()`) and fail loudly if mixed per-HCA GIDs meet an older FlashInfer lacking `gid_indices`. - Ported `partners()` and `relay_plan()` into `roce_fabric.rs`, added `Topology::relay_plan` for `Shape::Mesh` + `Links::All` paired-cable fabrics, validated relay plans in `RoceTransport::open` preflight, invoked `roce_set_relay` in `RoceTransport::connect` between `roce_connect` and `roce_start`, surfaced `, all-gather relay` in `flare-cli/src/cluster.rs`, and updated `docs/roce-ring.md`. - Compatibility: `ROCE_ABI_VERSION` remains `14`; existing ABI `9/10/11/14` cores load without re-export, and `peer_blobs` rejects legacy `1168`-byte connection records alongside foreign ABIs. Claimed benefit: Unblocks dual-CX7 mixed-GID serving, enables 1-hop closed-ring prefill opcodes `7..9` and `RING_WINDOW = 16` relay throughput with preserved lane-0 relay priority up to `world = 16`, and activates `roce_set_relay` on paired-cable mesh fabrics without re-exporting cores (expected 25% switch traffic reduction on 4-rank paired-cable meshes per `_roce_proxy.c` design). Supporting evidence and limitations: Verified on Linux x86_64 with live active RDMA HCA `rocep82s0f0`: - `cargo test --locked --release --manifest-path helios/Cargo.toml --features roce --lib execution::roce`: 38 passed, 0 failed (covering `roce_create_with_gids`, `roce_set_relay` FFI rejection on unconnected context, `roce_blob_bytes() == 1176`, legacy `1168`-byte rejection, 14 preflight checks, per-HCA GID discovery, and 4/8-rank + LLDP link-local `relay_plan` invariants). - `cargo test --locked --release --manifest-path helios/Cargo.toml --features roce,runtime-core,server --lib -- --skip frontend::templates --skip template`: 1,831 passed, 0 unrelated failures (1 template-fixture test requires `FLARE_TEST_TEMPLATE_DIR`). - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml --features roce`: 247 passed, 0 failed; `flare`: 247 passed, 0 failed; `heliopause --lib`: 229 passed, 0 failed. - `RUSTFLAGS="-D warnings" cargo check --locked --release` on `helios (--features runtime-core,server,roce)` and `flare-cli (--tests --features roce)`: pass (0 warnings). - Limitations: Multi-host 4x DGX Spark GB10 `flare run` serving, live paired-cable mesh `roce_set_relay` traffic, and `--features rdma` (whose `ibverbs-sys` bindgen fails on Arch rdma-core headers) were not executed on this single-host x86_64 machine; `pyproject.toml` pin bump awaits upstream FlashInfer merge. Design-Signed-Off-By: Antigravity (Gemini 4); design-review=2e5b --- docs/cli-design.md | 2 +- docs/roce-ring.md | 31 ++- flare-cli/src/cluster.rs | 7 +- flare-cli/src/doctor/spark.rs | 106 ++++++- heliopause/src/python.rs | 29 +- helios/native/roce_proxy.c | 398 +++++++++++++++++++++++---- helios/src/execution/roce.rs | 238 +++++++++++++++- helios/src/execution/roce_fabric.rs | 409 +++++++++++++++++++++++++--- ignition/preparation/collectives.py | 21 +- 9 files changed, 1113 insertions(+), 128 deletions(-) diff --git a/docs/cli-design.md b/docs/cli-design.md index 22ec7ac3a..ce94b56ea 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1706,7 +1706,7 @@ on these hosts and are unverified when no GPU is selected or detected. - PCI identifies the ConnectX-7 physical function (`15b3:1021`) even if its RDMA driver has not bound. The fabric check is not applicable when the adapter is absent. -- The report uses serving's RoCEv2 GID index and lists the selected +- The report uses serving's per-device RoCEv2 GID indices and lists the selected ConnectX-7 devices, interface names, IPv4 prefixes, and observed MTUs. One active device with an assigned IPv4 address and RoCEv2 GID is sufficient. The report identifies active devices skipped by discovery. diff --git a/docs/roce-ring.md b/docs/roce-ring.md index 810bd03e8..373c75d2c 100644 --- a/docs/roce-ring.md +++ b/docs/roce-ring.md @@ -106,9 +106,9 @@ that receiving kernels wait for. The proxy performs transport work, not the model's reductions. Ring mode also allocates registered host memory on each rank at startup, sized -for the group: about 1.004 MiB per rank in the group, so 4.02 MiB on each rank -of a four-rank group and 16.06 MiB at sixteen ranks. This region contains -eight relay mailboxes, acknowledgment words, and outgoing descriptors for every +for the group: about 2.008 MiB per rank in the group, so 8.03 MiB on each rank +of a four-rank group and 32.13 MiB at sixteen ranks. This region contains +sixteen relay mailboxes, acknowledgment words, and outgoing descriptors for every origin rank and each of two rails. It is separate from captured graph storage and the core's collective region. Relay payloads occupy at most 64 KiB per packet. @@ -126,7 +126,7 @@ A transfer from rank 0 to rank 2 through rank 1 proceeds as follows: The last relay waits for its send completion, then acknowledges the packet to the preceding hop. Longer paths pass acknowledgments back through each relay to the origin. -4. Rank 0 keeps at most eight packets in flight on a rail: it reuses a mailbox +4. Rank 0 keeps at most sixteen packets in flight on a rail: it reuses a mailbox slot only after the acknowledgment of the packet that last used that slot returns. Relay buffers and outgoing descriptors remain live until downstream acknowledgment permits reuse. @@ -158,13 +158,16 @@ uv sync --locked --extra prepare --extra test cargo build --release --manifest-path flare-cli/Cargo.toml ``` -Preparation and serving use proxy ABI 14. Its proxy holds eight packets in flight per sender and -rail in ring mailboxes that the runtime allocates at startup, serves the pipelined reduce-scatter -and shard-gather operations, connects four queue-pair lanes per rail, and exchanges start-of-op -credits between proxies. Cores recording proxy ABI 9, 10 or 11 have the same captured region -layout, so the runtime loads cores that record ABI 9, 10, 11 or 14. Serving does not enable -FlashInfer's all-gather relay. The chain topology is a mode of this layout, and startup rejects -any other proxy ABI before replay. +Preparation and serving use proxy ABI 14. Its proxy holds sixteen packets in flight per sender and +rail in ring mailboxes that the runtime allocates at startup (validated across ranks during +connect), serves the pipelined reduce-scatter, shard-gather, and closed-ring 1-hop bidirectional +reduce-scatter and shard-gather operations, connects four queue-pair lanes per rail, and exchanges +start-of-op credits between proxies. Cores recording proxy ABI 9, 10 or 11 have the same captured +region layout, so the runtime loads cores that record ABI 9, 10, 11 or 14. On mesh topologies whose +ranks form mutual direct-cable pairs (unless `--roce-switch-only` excludes direct cables), serving +enables FlashInfer's two-shot all-gather relay (`roce_set_relay`) across cable partners; ring and +chain topologies do not use that mesh relay. The chain topology is a mode of this layout, and +startup rejects any other proxy ABI before replay. ### Prepare across four hosts @@ -415,9 +418,9 @@ failed collective as a completed model step. | Component | Responsibility | | --- | --- | -| [Fabric discovery and route planning](../helios/src/execution/roce_fabric.rs) | Finds host devices and builds symmetric neighbor routes. | -| [Native transport owner](../helios/src/execution/roce.rs) | Validates the core ABI and layout, registers its region, enables the ring, and retains transport resources. | -| [RDMA proxy](../helios/native/roce_proxy.c) | Posts direct and relayed writes, progresses mailboxes and acknowledgments, and releases two-shot send buffers. | +| [Fabric discovery and route planning](../helios/src/execution/roce_fabric.rs) | Finds host devices with per-HCA GIDs, builds symmetric routes, and derives mesh partner-cable relay plans. | +| [Native transport owner](../helios/src/execution/roce.rs) | Validates the core ABI and layout, registers its region, enables the ring or mesh all-gather relay, and retains transport resources. | +| [RDMA proxy](../helios/native/roce_proxy.c) | Posts direct, 1-hop closed-ring, and relayed writes, progresses mailboxes and acknowledgments, and releases two-shot send buffers. | | [Serving distribution](../flare-cli/src/distribution.rs) | Receives and verifies rank cores before handing rendezvous sockets to serving. | | [Cluster startup](../flare-cli/src/cluster.rs) | Exchanges endpoints and connection records before native replay. | | [Collective preparation](../ignition/preparation/collectives.py) | Passes the routing choice to b12x and retains the transport through export. | diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 3531faecc..0f5b73827 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -94,7 +94,7 @@ fn open( fn connected(transport: &RoceTransport) -> String { let topology = transport.topology(); format!( - "{} rails per {}{}: {}", + "{} rails per {}{}{}: {}", topology.rails, match topology.shape { Shape::Mesh => "peer", @@ -105,6 +105,11 @@ fn connected(transport: &RoceTransport) -> String { Links::All => "", Links::Shared => ", switch only", }, + if topology.relay_plan.is_some() { + ", all-gather relay" + } else { + "" + }, topology.peer_routes().join("; ") ) } diff --git a/flare-cli/src/doctor/spark.rs b/flare-cli/src/doctor/spark.rs index 16a9cb2a1..e3e14fbf1 100644 --- a/flare-cli/src/doctor/spark.rs +++ b/flare-cli/src/doctor/spark.rs @@ -144,12 +144,12 @@ fn inspect( )); } - // Use the same GID index and assigned-address verification as serving. + // Use the same per-device GID indices and assigned-address verification as serving. let fabric = discover(); let mut ready = Vec::new(); if let Ok(fabric) = &fabric { let mut unresolved = Vec::new(); - for endpoint in &fabric.endpoints { + for (idx, endpoint) in fabric.endpoints.iter().enumerate() { // Serving discovers every RDMA adapter. This check covers ConnectX-7 devices. if !active.contains(&endpoint.name) { continue; @@ -158,9 +158,13 @@ fn inspect( unresolved.push(endpoint.name.as_str()); continue; }; + let Some(gid_index) = fabric.gid_index_for(idx) else { + unresolved.push(endpoint.name.as_str()); + continue; + }; let netdev = root .join(&endpoint.name) - .join(format!("ports/1/gid_attrs/ndevs/{}", fabric.gid_index)); + .join(format!("ports/1/gid_attrs/ndevs/{gid_index}")); let Some(interface) = read(&netdev) else { unresolved.push(endpoint.name.as_str()); continue; @@ -170,6 +174,7 @@ fn inspect( ready.push(Interface { device: &endpoint.name, interface, + gid_index, address, prefix, mtu, @@ -181,11 +186,12 @@ fn inspect( .map(Interface::describe) .collect::>() .join(", "); + let ready_gids: Vec = ready.iter().map(|port| port.gid_index).collect(); + let gid_label = format_gid_indices(&ready_gids); let mut detail = format!( - "{} of {} active CX7 devices supply IPv4 endpoints for serving at RoCEv2 GID index {}: {listed}.", + "{} of {} active CX7 devices supply IPv4 endpoints for serving at RoCEv2 GID {gid_label}: {listed}.", ready.len(), active.len(), - fabric.gid_index ); let mut warnings = configuration_warnings(&ready); if ready.iter().any(Interface::is_link_local) { @@ -236,8 +242,8 @@ fn inspect( let reason = match fabric { Err(error) => error.to_string(), Ok(fabric) => format!( - "discovery could not verify a local IPv4 address and prefix on a ConnectX-7 device at RoCEv2 GID index {}", - fabric.gid_index + "discovery could not verify a local IPv4 address and prefix on a ConnectX-7 device at RoCEv2 GID {}", + format_gid_indices(&fabric.gid_indices) ), }; Ok(result( @@ -250,9 +256,25 @@ fn inspect( )) } +fn format_gid_indices(indices: &[u32]) -> String { + match indices { + [] => "index (none)".into(), + [first, rest @ ..] if rest.iter().all(|&g| g == *first) => format!("index {first}"), + _ => format!( + "indices [{}]", + indices + .iter() + .map(u32::to_string) + .collect::>() + .join(", ") + ), + } +} + struct Interface<'a> { device: &'a str, interface: String, + gid_index: u32, address: Ipv4Addr, prefix: u8, mtu: Option, @@ -491,6 +513,7 @@ mod tests { Interface { device: "roce0", interface: "enp1s0f0np0".into(), + gid_index: 3, address: Ipv4Addr::new(192, 168, 0, 0), prefix: 31, mtu: Some(9000), @@ -498,6 +521,7 @@ mod tests { Interface { device: "roce1", interface: "enp1s0f1np1".into(), + gid_index: 3, address: Ipv4Addr::new(192, 168, 1, 15), prefix: 24, mtu: Some(9000), @@ -521,4 +545,72 @@ mod tests { interfaces.iter_mut().for_each(|port| port.prefix = 16); assert!(configuration_warnings(&interfaces).is_empty()); } + + #[test] + fn cx7_readiness_handles_distinct_per_hca_gid_indices() { + let dir = tempfile::tempdir().unwrap(); + let sysfs = dir.path(); + add_spark(sysfs); + let root = sysfs.join("class/infiniband"); + for (dev, net, gid_idx, gid_hex) in [ + ("roce0", "enP2p1s0f0np0", 3, "c0a8:650a"), + ("roce1", "enp1s0f0np0", 5, "c0a8:640a"), + ] { + write(&root, &format!("{dev}/device/vendor"), "0x15b3\n"); + write(&root, &format!("{dev}/device/device"), "0x1021\n"); + let port = root.join(dev).join("ports/1"); + write(&port, "state", "4: ACTIVE\n"); + write( + &port, + &format!("gid_attrs/ndevs/{gid_idx}"), + &format!("{net}\n"), + ); + write(&port, &format!("gid_attrs/types/{gid_idx}"), "RoCE v2\n"); + write( + &port, + &format!("gids/{gid_idx}"), + &format!("0000:0000:0000:0000:0000:ffff:{gid_hex}\n"), + ); + write(sysfs, &format!("class/net/{net}/mtu"), "9000\n"); + } + // Decoy IPv6 RoCEv2 entry at index 3 on roce1 so reading a uniform ndevs/3 would fail. + let roce1_port = root.join("roce1/ports/1"); + write(&roce1_port, "gid_attrs/ndevs/3", "decoy0\n"); + write(&roce1_port, "gid_attrs/types/3", "RoCE v2\n"); + write( + &roce1_port, + "gids/3", + "fe80:0000:0000:0000:0200:00ff:fe00:0001\n", + ); + + let rep = report(sysfs, |netdev, _| { + matches!(netdev, "enP2p1s0f0np0" | "enp1s0f0np0").then_some(24) + }); + let check = cx7(&rep); + assert!(rep.ok); + assert_eq!(check.status, CheckStatus::Pass, "{}", check.detail); + assert!( + check.detail.contains("2 of 2 active CX7 devices"), + "{}", + check.detail + ); + assert!(check.detail.contains("indices [3, 5]"), "{}", check.detail); + assert!(check.detail.contains("enp1s0f0np0"), "{}", check.detail); + assert!(!check.detail.contains("decoy0"), "{}", check.detail); + + // When no local IPv4 prefix resolves, the Warn fallback also reports all selected indices. + let warn_rep = report(sysfs, |_, _| None); + let warn_check = cx7(&warn_rep); + assert_eq!( + warn_check.status, + CheckStatus::Warn, + "{}", + warn_check.detail + ); + assert!( + warn_check.detail.contains("indices [3, 5]"), + "{}", + warn_check.detail + ); + } } diff --git a/heliopause/src/python.rs b/heliopause/src/python.rs index 4c50a33de..5f91b13c7 100644 --- a/heliopause/src/python.rs +++ b/heliopause/src/python.rs @@ -665,6 +665,7 @@ fn flare_heliopause(module: &Bound<'_, PyModule>) -> PyResult<()> { module.add_class::()?; module.add_function(wrap_pyfunction!(current_context, module)?)?; module.add_function(wrap_pyfunction!(memory_inventory, module)?)?; + module.add_function(wrap_pyfunction!(roce_devices, module)?)?; module.add_function(wrap_pyfunction!(roce_gid_index, module)?)?; module.add_function(wrap_pyfunction!(serve_tensor_parallel_rank, module)?)?; #[cfg(target_os = "linux")] @@ -689,14 +690,36 @@ fn memory_inventory(py: Python<'_>) -> PyResult> Ok(result) } -/// This host's RoCE GID index by the rule native serving uses: 3 when every active device has a -/// RoCEv2 IPv4 GID there, otherwise the lowest index at which one does. +/// The first selected RoCE device's GID index by the rule native serving uses: each active device +/// prefers index 3 when it has a RoCEv2 IPv4 GID there, otherwise its own lowest RoCEv2 IPv4 GID +/// index. Prefer `roce_devices` when HCAs on the host may have distinct GID indices. #[pyfunction] fn roce_gid_index() -> PyResult { #[cfg(target_os = "linux")] { crate::execution::roce_fabric::discover() - .map(|fabric| fabric.gid_index) + .map(|fabric| fabric.gid_index()) + .map_err(|error| PyRuntimeError::new_err(error.to_string())) + } + #[cfg(not(target_os = "linux"))] + Err(PyRuntimeError::new_err("RoCE preparation requires Linux")) +} + +/// This host's discovered RoCE devices and their per-device RoCEv2 IPv4 GID indices, in the same +/// name-sorted order as native serving discovery. +#[pyfunction] +fn roce_devices() -> PyResult> { + #[cfg(target_os = "linux")] + { + crate::execution::roce_fabric::discover() + .map(|fabric| { + fabric + .endpoints + .into_iter() + .zip(fabric.gid_indices) + .map(|(endpoint, gid_index)| (endpoint.name, gid_index)) + .collect() + }) .map_err(|error| PyRuntimeError::new_err(error.to_string())) } #[cfg(not(target_os = "linux"))] diff --git a/helios/native/roce_proxy.c b/helios/native/roce_proxy.c index be4a21e8d..db5104ad1 100644 --- a/helios/native/roce_proxy.c +++ b/helios/native/roce_proxy.c @@ -82,6 +82,16 @@ // On the ring transports a credit to a rank that is not a neighbor travels as an empty mailbox // write, whose flag lands on every rail; only rail 0's credit word is read. // +// On closed rings of three or more ranks, pipelined reduce-scatter (ctrl kind[slot] = 7), +// shard gather (ctrl kind[slot] = 8), and fused reduce-scatter plus all-gather (ctrl kind[slot] +// = 9) also run as bidirectional 1-hop ring collectives over pipe_send, pipe_recv, and +// pipe_flag. Each direction (clockwise and counter-clockwise) owns half of the payload across +// W shards; every RDMA write targets a direct neighbor striped across all rails and rotated +// across n_lane QPs with no CPU mailbox relay. pipe_recv holds 4 * (W - 1) half-shard slots +// of shard_cap / 2 (2 * (W - 1) for RS, 2 * (W - 1) for AG), and pipe_flag uses rows 0..1 +// (RS) and W..W + 1 (AG). Cross-family transitions between two-shot/pipe and ring_bidir ops +// exchange start-of-op credits because their pipe_recv layouts overlap. +// // A cabled fabric can relay the all-gather chunks (phase 1 of a two-shot op or a shard gather) // when its ranks form pairs joined by direct cables (roce_set_relay). A rank then sends its // reduced shard to its partner and to one rank in every other pair, which forwards each chunk to @@ -138,6 +148,15 @@ #define ROCE_FLAG_STRIDE 128 #define ROCE_PORT 1 #define ROCE_SEND_DEPTH 512 +// Signaled-op ceilings per (HCA, peer, lane) QP. Direct stripes chain two WRs +// and ring relay packets chain three. Keeping local origin writes strictly +// below the relay forwarding cap preserves lane-0 priority for inbound relays +// while leaving room for up to ROCE_MAX_PEERS * RING_WINDOW unreserved +// per-origin ACKs plus provider SQE overhead. +#define ROCE_RELAY_OPS (ROCE_SEND_DEPTH / 8u) +#define ROCE_RESERVE_OPS 48u +_Static_assert(ROCE_RESERVE_OPS < ROCE_RELAY_OPS, + "local origin reserve limit must stay strictly below relay cap"); #define ROCE_ABI_VERSION 14 #define ROCE_MAX_CHUNKS 64 #define ROCE_VARLEN_MAX_CHUNKS 512 @@ -172,19 +191,18 @@ _Static_assert(CTRL_CREDIT >= CTRL_READY_VL + ROCE_VARLEN_MAX_CHUNKS && #define KIND_GATHER_SHARDS 4 #define KIND_RING2_STEP1 5u #define KIND_RING2_STEP2 6u +#define KIND_RING_RS 7 +#define KIND_RING_AG 8 +#define KIND_RING_RSAG 9 // Two-step ring direct writes signal 1 in RING2_SIGNAL_STRIDE ops per (HCA, peer) // QP. Capping signaled outstanding ops at RING2_MAX_OUTSTANDING keeps at most // RING2_MAX_OUTSTANDING * RING2_SIGNAL_STRIDE * 2 + (RING2_SIGNAL_STRIDE - 1) * 2 -// = 222 WRs in flight on a 512-deep send queue, leaving room for up to 85 -// subsequent three-WR relay ops (255 WRs) plus world=4 ring ACKs. +// = 222 WRs in flight on a 512-deep send queue, leaving room for up to +// ROCE_RELAY_OPS three-WR relay ops (192 WRs) plus world=4 ring ACKs (64 WRs). #define RING2_SIGNAL_STRIDE 16u #define RING2_MAX_OUTSTANDING 6u _Static_assert((RING2_SIGNAL_STRIDE & (RING2_SIGNAL_STRIDE - 1u)) == 0, "RING2_SIGNAL_STRIDE must be a power of two"); -_Static_assert(RING2_MAX_OUTSTANDING* RING2_SIGNAL_STRIDE * 2 + (RING2_SIGNAL_STRIDE - 1u) * 2 + - (ROCE_SEND_DEPTH / 6) * 3 <= - ROCE_SEND_DEPTH, - "batched ring2 WRs must fit inside ROCE_SEND_DEPTH with queue slack"); // run_pipe_op phase mask: reduce-scatter chunks, all-gather chunks. #define PIPE_PHASE_RS 1u #define PIPE_PHASE_AG 2u @@ -202,8 +220,14 @@ _Static_assert(RING2_MAX_OUTSTANDING* RING2_SIGNAL_STRIDE * 2 + (RING2_SIGNAL_ST // The startup region, sized for the world, holds per (origin, rail, slot): // mailboxes, then 8-byte acknowledgment words, then outgoing descriptors. #define RING_CHUNK_BYTES 65536 -#define RING_WINDOW 8 +#define RING_WINDOW 16 #define RING_COMPLETION (UINT64_C(1) << 63) +_Static_assert(ROCE_RELAY_OPS * 3u + ROCE_MAX_PEERS * RING_WINDOW <= ROCE_SEND_DEPTH, + "send queue depth must hold reserved/relay chains plus all per-origin ring ACKs"); +_Static_assert(RING2_MAX_OUTSTANDING* RING2_SIGNAL_STRIDE * 2u + (RING2_SIGNAL_STRIDE - 1u) * 2u + + ROCE_RELAY_OPS * 3u + 4u * RING_WINDOW <= + ROCE_SEND_DEPTH, + "batched ring2 WRs plus relay chains and world=4 ACKs must fit ROCE_SEND_DEPTH"); typedef struct { uint64_t serial, target, offset, flag_offset, flag_value, nbytes, previous; uint8_t padding[72]; @@ -240,6 +264,8 @@ typedef struct { uint32_t mtu[ROCE_MAX_HCAS]; uint32_t qp_num[ROCE_MAX_HCAS][ROCE_MAX_PEERS][ROCE_MAX_LANES]; uint32_t lanes; + uint32_t ring_window; + uint64_t ring_bytes; } roce_blob_t; typedef struct { @@ -256,6 +282,7 @@ typedef struct { uint16_t lid; enum ibv_mtu mtu; uint32_t max_inline; + int gid_index; } roce_hca_t; typedef struct { @@ -264,7 +291,6 @@ typedef struct { int n_hca; int n_rail; int n_lane; - int gid_index; int traffic_class; roce_hca_t hca[ROCE_MAX_HCAS]; uint8_t* region; @@ -420,7 +446,7 @@ int roce_layout(int world, uint64_t slot_bytes, uint64_t pipe_bytes, uint64_t va uint64_t roce_blob_bytes(void) { return sizeof(roce_blob_t); } -static int open_hca(roce_ctx_t* c, int h, const char* name) { +static int open_hca(roce_ctx_t* c, int h, const char* name, int gid_index) { int num = 0; struct ibv_device** list = ibv_get_device_list(&num); if (list == NULL) { @@ -457,7 +483,8 @@ static int open_hca(roce_ctx_t* c, int h, const char* name) { } hca->lid = port.lid; hca->mtu = port.active_mtu; - if (ibv_query_gid(hca->ctx, ROCE_PORT, c->gid_index, &hca->gid) != 0) { + hca->gid_index = gid_index; + if (ibv_query_gid(hca->ctx, ROCE_PORT, hca->gid_index, &hca->gid) != 0) { set_err(c, "ibv_query_gid", errno); return -1; } @@ -527,17 +554,25 @@ static int open_hca(roce_ctx_t* c, int h, const char* name) { return 0; } -roce_ctx_t* roce_create(int world, int rank, const char* const* hca_names, int n_hca, int gid_index, - int traffic_class, int n_lane, void* region, uint64_t region_bytes, - uint64_t slot_bytes, uint64_t pipe_bytes, uint64_t varlen_bytes, char* err, - uint64_t err_len) { +roce_ctx_t* roce_create_with_gids(int world, int rank, const char* const* hca_names, int n_hca, + const int* gid_indices, int traffic_class, int n_lane, + void* region, uint64_t region_bytes, uint64_t slot_bytes, + uint64_t pipe_bytes, uint64_t varlen_bytes, char* err, + uint64_t err_len) { uint64_t layout[17]; if (roce_layout(world, slot_bytes, pipe_bytes, varlen_bytes, layout) != 0 || layout[4] > region_bytes || rank < 0 || rank >= world || n_hca < 1 || n_hca > ROCE_MAX_HCAS || - traffic_class < 0 || traffic_class > 255 || n_lane < 1 || n_lane > ROCE_MAX_LANES) { + gid_indices == NULL || traffic_class < 0 || traffic_class > 255 || n_lane < 1 || + n_lane > ROCE_MAX_LANES) { snprintf(err, err_len, "invalid roce runtime geometry"); return NULL; } + for (int h = 0; h < n_hca; h++) { + if (gid_indices[h] < 0 || gid_indices[h] > 255) { + snprintf(err, err_len, "invalid roce gid index %d for HCA %d", gid_indices[h], h); + return NULL; + } + } roce_ctx_t* c = calloc(1, sizeof(*c)); if (c == NULL) { snprintf(err, err_len, "out of memory"); @@ -546,7 +581,6 @@ roce_ctx_t* roce_create(int world, int rank, const char* const* hca_names, int n c->world = world; c->rank = rank; c->n_hca = n_hca; - c->gid_index = gid_index; c->traffic_class = traffic_class; c->n_lane = n_lane; c->region = region; @@ -565,7 +599,7 @@ roce_ctx_t* roce_create(int world, int rank, const char* const* hca_names, int n c->varlen_flag_off = layout[14]; c->varlen_bytes = layout[15]; for (int h = 0; h < n_hca; h++) { - if (open_hca(c, h, hca_names[h]) != 0) { + if (open_hca(c, h, hca_names[h], gid_indices[h]) != 0) { snprintf(err, err_len, "%s", c->err); roce_destroy(c); return NULL; @@ -574,6 +608,18 @@ roce_ctx_t* roce_create(int world, int rank, const char* const* hca_names, int n return c; } +roce_ctx_t* roce_create(int world, int rank, const char* const* hca_names, int n_hca, int gid_index, + int traffic_class, int n_lane, void* region, uint64_t region_bytes, + uint64_t slot_bytes, uint64_t pipe_bytes, uint64_t varlen_bytes, char* err, + uint64_t err_len) { + int gids[ROCE_MAX_HCAS]; + for (int h = 0; h < ROCE_MAX_HCAS; h++) { + gids[h] = gid_index; + } + return roce_create_with_gids(world, rank, hca_names, n_hca, gids, traffic_class, n_lane, region, + region_bytes, slot_bytes, pipe_bytes, varlen_bytes, err, err_len); +} + // Enable before exchanging blobs; startup allocation, never during replay. int roce_enable_ring_open(roce_ctx_t* c); int roce_enable_ring(roce_ctx_t* c) { @@ -616,6 +662,8 @@ int roce_local_blob(roce_ctx_t* c, void* out, uint64_t out_len) { blob.region_addr = (uint64_t)(uintptr_t)c->region; blob.ring_addr = (uint64_t)(uintptr_t)c->ring; blob.lanes = (uint32_t)c->n_lane; + blob.ring_window = c->ring == NULL ? 0 : (uint32_t)RING_WINDOW; + blob.ring_bytes = c->ring == NULL ? 0 : (uint64_t)ring_bytes(c->world); for (int h = 0; h < c->n_hca; h++) { blob.rkey[h] = c->hca[h].mr->rkey; blob.ring_rkey[h] = c->ring == NULL ? 0 : c->ring_mr[h]->rkey; @@ -651,7 +699,7 @@ static int connect_qp(roce_ctx_t* c, int h, int r, int p, int lane, const roce_b rtr.ah_attr.src_path_bits = 0; rtr.ah_attr.port_num = ROCE_PORT; memcpy(rtr.ah_attr.grh.dgid.raw, peer->gid[r], 16); - rtr.ah_attr.grh.sgid_index = (uint8_t)c->gid_index; + rtr.ah_attr.grh.sgid_index = (uint8_t)hca->gid_index; rtr.ah_attr.grh.hop_limit = 64; rtr.ah_attr.grh.traffic_class = (uint8_t)c->traffic_class; rtr.ah_attr.grh.flow_label = 0; @@ -693,6 +741,8 @@ int roce_connect(roce_ctx_t* c, const void* blobs, uint64_t blobs_len, const int snprintf(c->err, sizeof(c->err), "invalid rail count %d", n_rail); return -1; } + const uint32_t expected_ring_window = c->ring == NULL ? 0 : (uint32_t)RING_WINDOW; + const uint64_t expected_ring_bytes = c->ring == NULL ? 0 : (uint64_t)ring_bytes(c->world); const roce_blob_t* all = (const roce_blob_t*)blobs; for (int p = 0; p < c->world; p++) { if ((all[p].ring_addr != 0) != (c->ring != NULL)) { @@ -704,6 +754,13 @@ int roce_connect(roce_ctx_t* c, const void* blobs, uint64_t blobs_len, const int p, all[p].lanes, c->n_lane); return -1; } + if (all[p].ring_window != expected_ring_window || all[p].ring_bytes != expected_ring_bytes) { + snprintf(c->err, sizeof(c->err), + "rank %d uses ring window %u (%llu bytes) where this rank uses %u (%llu bytes)", p, + all[p].ring_window, (unsigned long long)all[p].ring_bytes, expected_ring_window, + (unsigned long long)expected_ring_bytes); + return -1; + } c->peer_addr[p] = all[p].region_addr; c->ring_addr[p] = all[p].ring_addr; } @@ -845,11 +902,12 @@ static int reserve_limit(roce_ctx_t* c, int h, int p, int lane, uint32_t limit) } // Wait until lane `lane` of HCA h can take one more stripe to peer p. Direct stripes need two -// requests and relay packets chain three. One sixth of the send queue (85 signaled ops, at most -// 255 chained WRs) leaves room for up to 128 unreserved per-origin ACKs at world=16 plus provider -// SQE overhead. +// requests and relay packets chain three. Capping local origin writes at ROCE_RESERVE_OPS (48), +// strictly below ring_service_slot()'s ROCE_RELAY_OPS (64, at most 192 chained WRs), preserves +// lane-0 headroom for inbound relay forwarding plus up to 256 unreserved per-origin ACKs at +// world=16 with RING_WINDOW=16 and provider SQE overhead. static int reserve(roce_ctx_t* c, int h, int p, int lane) { - return reserve_limit(c, h, p, lane, ROCE_SEND_DEPTH / 6); + return reserve_limit(c, h, p, lane, ROCE_RESERVE_OPS); } // Each original sender has RING_WINDOW private mailbox slots per rail at every @@ -978,7 +1036,7 @@ static int ring_service_slot(roce_ctx_t* c, int origin, int rail, int slot) { c->ring_inflight[origin][rail][slot] = serial; int next = ring_next(c, target); int h = c->rail_hca[next][rail]; - if (c->hca[h].outstanding[next][0] >= ROCE_SEND_DEPTH / 4) return 1; + if (c->hca[h].outstanding[next][0] >= ROCE_RELAY_OPS) return 1; if (next != target) { if (ring_submit(c, origin, rail, slot, next, box->data, c->ring_mr[h]->lkey, d) != 0) return -1; *pending = 2; @@ -1211,10 +1269,10 @@ static int drain_cqs(roce_ctx_t* c) { } static int drain_all(roce_ctx_t* c) { - if (ring_service(c) != 0) { + if (drain_cqs(c) != 0) { return -1; } - return drain_cqs(c); + return ring_service(c); } // Post one-shot op seq to every peer: the whole payload, one stripe plus its flag @@ -1447,14 +1505,42 @@ static int forward_pipe_chunk(roce_ctx_t* c, uint32_t seq, int s, uint32_t chunk return 0; } +static uint32_t kind_phases(uint32_t kind) { + switch (kind) { + case KIND_TWOSHOT: + case KIND_RING_RSAG: + return PIPE_PHASE_RS | PIPE_PHASE_AG; + case KIND_REDUCE_SCATTER: + case KIND_RING_RS: + return PIPE_PHASE_RS; + case KIND_GATHER_SHARDS: + case KIND_RING_AG: + return PIPE_PHASE_AG; + default: + return 0; + } +} + +static int kind_1hop(uint32_t kind) { return kind >= KIND_RING_RS && kind <= KIND_RING_RSAG; } + // The phases of an op of `kind` following an op of `prev` that must wait for peers' credits (see -// the header): phase 0 after a reduce-scatter, phase 1 of a shard gather after an op that gathers. +// the header): phase 0 after a reduce-scatter, phase 1 of a shard gather after an op that gathers, +// and the first phase of any cross-family transition between pipe and ring_bidir (which partition +// pipe_recv with different phase layouts). static uint32_t credit_phases(uint32_t prev, uint32_t kind) { + uint32_t prev_p = kind_phases(prev); + uint32_t cur_p = kind_phases(kind); + if (prev_p == 0 || cur_p == 0) { + return 0; + } + if (kind_1hop(prev) != kind_1hop(kind)) { + return (cur_p & PIPE_PHASE_RS) != 0 ? CREDIT_RS : CREDIT_AG; + } uint32_t need = 0; - if (prev == KIND_REDUCE_SCATTER && (kind == KIND_REDUCE_SCATTER || kind == KIND_TWOSHOT)) { + if (prev_p == PIPE_PHASE_RS && (cur_p & PIPE_PHASE_RS) != 0) { need |= CREDIT_RS; } - if (kind == KIND_GATHER_SHARDS && (prev == KIND_TWOSHOT || prev == KIND_GATHER_SHARDS)) { + if ((prev_p & PIPE_PHASE_AG) != 0 && cur_p == PIPE_PHASE_AG) { need |= CREDIT_AG; } return need; @@ -1511,6 +1597,41 @@ static int credits_arrived(const roce_ctx_t* c, uint32_t seq) { return 1; } +// Release pipe_send: wait until every posted write completed, so the NIC no longer reads the +// buffer the next op will overwrite, then publish CTRL_PIPE_DONE. +static int pipe_op_release(roce_ctx_t* c, uint32_t seq, const char* what) { + volatile uint32_t* ctrl = (volatile uint32_t*)(c->region + c->ctrl_off); + c->ops_posted += 1; + for (;;) { + if (drain_all(c) != 0) { + return -1; + } + uint32_t pending = 0; + for (int h = 0; h < c->n_hca; h++) { + for (int p = 0; p < c->world; p++) { + for (int l = 0; l < c->n_lane; l++) { + pending += c->hca[h].outstanding[p][l]; + } + } + } + if (pending == 0) { + break; + } + uint32_t err_seq = __atomic_load_n(&ctrl[CTRL_ERROR], __ATOMIC_ACQUIRE); + if (err_seq != 0) { + snprintf(c->err, sizeof(c->err), "%s op %u abandoned: kernel timed out at seq %u", what, seq, + err_seq); + return -1; + } + if (!atomic_load_explicit(&c->running, memory_order_relaxed)) { + snprintf(c->err, sizeof(c->err), "RoCE proxy stopped releasing %s op %u", what, seq); + return -1; + } + } + __atomic_store_n(&ctrl[CTRL_PIPE_DONE], seq, __ATOMIC_RELEASE); + return 0; +} + // Run pipelined op seq over the phases in `phases`: post each reduce-scatter // chunk once the kernel staged it and each all-gather chunk once the kernel // reduced (or, for a shard gather, staged) it. With the relay, also forward each relayed source's @@ -1572,6 +1693,9 @@ static int run_pipe_op(roce_ctx_t* c, uint32_t seq, uint32_t nbytes, uint32_t ch } } if (posted) { + if (c->ring != NULL && drain_all(c) != 0) { + return -1; + } idle = 0; continue; } @@ -1591,36 +1715,192 @@ static int run_pipe_op(roce_ctx_t* c, uint32_t seq, uint32_t nbytes, uint32_t ch } } } - c->ops_posted += 1; - // Release pipe_send: wait until every posted write, our all-gather included, - // completed, so the NIC no longer reads the shard the next op will overwrite. + return pipe_op_release(c, seq, "two-shot"); +} + +static inline void ring_dir_shard_bounds(const roce_ctx_t* c, int dir, int shard, uint32_t total, + uint32_t* first_out, uint32_t* end_out) { + uint32_t half_p = total / 2u; + uint32_t base = dir == 0 ? 0u : half_p; + uint32_t len = dir == 0 ? half_p : (total - half_p); + *first_out = base + (uint32_t)(((uint64_t)shard * len) / (uint64_t)c->world); + *end_out = base + (uint32_t)(((uint64_t)(shard + 1) * len) / (uint64_t)c->world); +} + +// Post one 1-hop chunk along `dir` (0 = CW, 1 = CCW) for `shard`. When `src_slot < 0`, +// read from pipe_send at the shard's global offset; otherwise forward zero-copy from +// pipe_recv[src_slot]. Clamping lo/hi to end preserves empty-chunk flag writes so +// receivers wait uniformly for every chunk. +static int post_ring_bidir_chunk(roce_ctx_t* c, uint32_t seq, int dir, int shard, uint32_t total, + uint32_t c_idx, uint32_t chunk_packs, int src_slot, int dst_slot, + int flag_row, uint32_t flag_idx) { + uint32_t first, end; + ring_dir_shard_bounds(c, dir, shard, total, &first, &end); + uint64_t lo = (uint64_t)first + (uint64_t)c_idx * chunk_packs; + uint64_t hi = lo + chunk_packs; + if (lo > end) { + lo = end; + } + if (hi > end) { + hi = end; + } + uint64_t half_cap = c->shard_cap / 2u; + uint64_t off_bytes = (lo - first) * 16u; + const uint8_t* src = + src_slot < 0 ? (c->region + c->pipe_send_off + lo * 16u) + : (c->region + c->pipe_recv_off + (uint64_t)src_slot * half_cap + off_bytes); + uint64_t remote_off = c->pipe_recv_off + (uint64_t)dst_slot * half_cap + off_bytes; + uint64_t flag_off = + c->pipe_flag_off + + (((uint64_t)flag_row * ROCE_MAX_CHUNKS + (uint64_t)flag_idx) * (uint64_t)c->n_rail) * + ROCE_FLAG_STRIDE; + int peer = dir == 0 ? (c->rank + 1) % c->world : (c->rank + c->world - 1) % c->world; + return post_striped(c, peer, src, remote_off, (uint32_t)(hi - lo), flag_off, seq, + (int)(flag_idx % (uint32_t)c->n_lane)); +} + +// Concurrent multi-rail, bidirectional 1-hop closed-ring collective supporting: +// PIPE_PHASE_RS (KIND_RING_RS = 7): standalone 1-hop Reduce-Scatter +// PIPE_PHASE_AG (KIND_RING_AG = 8): standalone 1-hop All-Gather +// PIPE_PHASE_RS | PIPE_PHASE_AG (KIND_RING_RSAG = 9): fused Reduce-Scatter + All-Gather +// Every RDMA write crosses strictly 1 hop to CW/CCW direct neighbors, striped across all +// n_rail links and rotated across n_lane QPs per rail (zero 2-hop CPU mailbox relay). +static int run_ring_bidir_op(roce_ctx_t* c, uint32_t seq, uint32_t nbytes, uint32_t chunk_packs, + uint32_t chunks, uint32_t phases, uint32_t credit) { + volatile uint32_t* ctrl = (volatile uint32_t*)(c->region + c->ctrl_off); + int W = c->world; + int R = c->rank; + int do_rs = (phases & PIPE_PHASE_RS) != 0; + int do_ag = (phases & PIPE_PHASE_AG) != 0; + if (c->ring == NULL || c->ring_open || W < 3 || nbytes == 0 || nbytes % 16 != 0 || + nbytes > c->pipe_bytes || (uint64_t)(W - 1) * chunks > ROCE_MAX_CHUNKS) { + snprintf(c->err, sizeof(c->err), + "invalid ring_bidir op %u: world=%d nbytes=%u chunks=%u chunk_packs=%u phases=%u", seq, + W, nbytes, chunks, chunk_packs, phases); + return -1; + } + uint32_t total = nbytes / 16u; + uint32_t half_max = (total + 1u) / 2u; + uint32_t widest = (half_max + (uint32_t)W - 1u) / (uint32_t)W; + uint64_t half_cap = c->shard_cap / 2u; + if ((uint64_t)chunks * chunk_packs < widest) { + snprintf(c->err, sizeof(c->err), "ring_bidir op %u chunk coverage %u*%u < widest %u", seq, + chunks, chunk_packs, widest); + return -1; + } + if ((uint64_t)widest * 16u > half_cap) { + snprintf(c->err, sizeof(c->err), "ring_bidir op %u half-shard %llu exceeds half_cap %llu", seq, + (unsigned long long)((uint64_t)widest * 16u), (unsigned long long)half_cap); + return -1; + } + + uint32_t rs_sent[ROCE_MAX_PEERS]; + uint32_t ag_fwd[2][ROCE_MAX_PEERS]; + for (int s = 0; s < W - 1; s++) { + rs_sent[s] = do_rs ? 0u : chunks; + ag_fwd[0][s] = (do_ag && s >= 1) ? 0u : chunks; + ag_fwd[1][s] = (do_ag && s >= 1) ? 0u : chunks; + } + uint32_t ag0_sent = do_ag ? 0u : chunks; + uint64_t idle = 0; + uint32_t post_batch = 0; + for (;;) { - if (drain_all(c) != 0) { - return -1; + int done = (ag0_sent == chunks); + for (int s = 0; s < W - 1; s++) { + if (rs_sent[s] < chunks) done = 0; + if (s >= 1 && (ag_fwd[0][s] < chunks || ag_fwd[1][s] < chunks)) done = 0; } - uint32_t pending = 0; - for (int h = 0; h < c->n_hca; h++) { - for (int p = 0; p < c->world; p++) { - for (int l = 0; l < c->n_lane; l++) { - pending += c->hca[h].outstanding[p][l]; + if (done) break; + + if (credit != 0 && credits_arrived(c, seq)) { + credit = 0; + } + + int posted = 0; + + // 1. Prioritize zero-copy 1-hop AG forwarding so incoming shards keep the ring pipeline full. + if (do_ag && !(credit & CREDIT_AG)) { + for (int s = 1; s < W - 1; s++) { + for (int dir = 0; dir < 2; dir++) { + uint32_t c_idx = ag_fwd[dir][s]; + if (c_idx < chunks) { + uint32_t prev_flag_idx = (uint32_t)(s - 1) * chunks + c_idx; + if (pipe_chunk_arrived(c, seq, dir, prev_flag_idx)) { + int sh = dir == 0 ? ((R - s + 2 * W) % W) : ((R + s) % W); + int src_slot = 2 * (W - 1) + dir * (W - 1) + (s - 1); + uint32_t dst_flag_idx = (uint32_t)s * chunks + c_idx; + if (post_ring_bidir_chunk(c, seq, dir, sh, total, c_idx, chunk_packs, src_slot, + src_slot + 1, W + dir, dst_flag_idx) != 0) { + return -1; + } + ag_fwd[dir][s]++; + posted = 1; + } + } } } } - if (pending == 0) { - break; + + // 2. RS step s: once the kernel marks RS step s chunk c_idx ready, send CW and CCW 1-hop. + if (do_rs && !(credit & CREDIT_RS)) { + for (int s = 0; s < W - 1; s++) { + uint32_t c_idx = rs_sent[s]; + if (c_idx < chunks) { + uint32_t r_word = (uint32_t)s * chunks + c_idx; + if (__atomic_load_n(&ctrl[CTRL_READY_RS + r_word], __ATOMIC_ACQUIRE) == seq) { + int sh_dir[2] = {(R - 1 - s + 2 * W) % W, (R + 1 + s) % W}; + for (int dir = 0; dir < 2; dir++) { + if (post_ring_bidir_chunk(c, seq, dir, sh_dir[dir], total, c_idx, chunk_packs, -1, + dir * (W - 1) + s, dir, r_word) != 0) { + return -1; + } + } + rs_sent[s]++; + posted = 1; + } + } + } } - if (ctrl[CTRL_ERROR] != 0) { - snprintf(c->err, sizeof(c->err), "two-shot op %u abandoned: kernel timed out at seq %u", seq, - ctrl[CTRL_ERROR]); - return -1; + + // 3. AG step 0: send own shard R directly 1-hop CW and CCW across all rails. + if (do_ag && !(credit & CREDIT_AG) && ag0_sent < chunks && + __atomic_load_n(&ctrl[CTRL_READY_AG + ag0_sent], __ATOMIC_ACQUIRE) == seq) { + uint32_t c_idx = ag0_sent; + for (int dir = 0; dir < 2; dir++) { + if (post_ring_bidir_chunk(c, seq, dir, R, total, c_idx, chunk_packs, -1, + 2 * (W - 1) + dir * (W - 1), W + dir, c_idx) != 0) { + return -1; + } + } + ag0_sent++; + posted = 1; } - if (!atomic_load_explicit(&c->running, memory_order_relaxed)) { - snprintf(c->err, sizeof(c->err), "RoCE proxy stopped releasing two-shot op %u", seq); - return -1; + + if (posted) { + if ((++post_batch & 3u) == 0u) { + if (drain_cqs(c) != 0) { + return -1; + } + } + idle = 0; + continue; + } + if (++idle % 64 == 0) { + if (drain_all(c) != 0) return -1; + uint32_t err_seq = __atomic_load_n(&ctrl[CTRL_ERROR], __ATOMIC_ACQUIRE); + if (err_seq != 0) { + snprintf(c->err, sizeof(c->err), "ring_bidir op %u abandoned: kernel timed out at seq %u", + seq, err_seq); + return -1; + } + if (!atomic_load_explicit(&c->running, memory_order_relaxed)) { + snprintf(c->err, sizeof(c->err), "RoCE proxy stopped inside ring_bidir op %u", seq); + return -1; + } } } - __atomic_store_n(&ctrl[CTRL_PIPE_DONE], seq, __ATOMIC_RELEASE); - return 0; + return pipe_op_release(c, seq, "ring_bidir"); } // Run variable-length all-gather op seq: post each chunk of our contribution, from our row of @@ -1838,21 +2118,21 @@ static void* proxy_main(void* arg) { rc = post_ring2_step(c, s, nbytes, 0); } else if (kind == KIND_RING2_STEP2) { rc = post_ring2_step(c, s, nbytes, 1); - } else if (kind == KIND_TWOSHOT || kind == KIND_REDUCE_SCATTER || - kind == KIND_GATHER_SHARDS) { - uint32_t phases = kind == KIND_TWOSHOT ? (PIPE_PHASE_RS | PIPE_PHASE_AG) - : kind == KIND_REDUCE_SCATTER ? PIPE_PHASE_RS - : PIPE_PHASE_AG; + } else if (kind == KIND_VARLEN) { + rc = run_varlen_op(c, s, nbytes, ctrl[CTRL_SLOT_CHUNK_PACKS + slot], + ctrl[CTRL_SLOT_CHUNKS + slot]); + } else if (kind_phases(kind) != 0) { + uint32_t phases = kind_phases(kind); // Every rank runs the same op sequence, so all of them post and await the same credits. uint32_t credit = credit_phases(c->last_kind, kind); rc = credit != 0 ? post_credits(c, s) : 0; if (rc == 0) { - rc = run_pipe_op(c, s, nbytes, ctrl[CTRL_SLOT_CHUNK_PACKS + slot], - ctrl[CTRL_SLOT_CHUNKS + slot], phases, credit); + uint32_t chunk_packs = ctrl[CTRL_SLOT_CHUNK_PACKS + slot]; + uint32_t chunks = ctrl[CTRL_SLOT_CHUNKS + slot]; + rc = kind_1hop(kind) + ? run_ring_bidir_op(c, s, nbytes, chunk_packs, chunks, phases, credit) + : run_pipe_op(c, s, nbytes, chunk_packs, chunks, phases, credit); } - } else if (kind == KIND_VARLEN) { - rc = run_varlen_op(c, s, nbytes, ctrl[CTRL_SLOT_CHUNK_PACKS + slot], - ctrl[CTRL_SLOT_CHUNKS + slot]); } else { snprintf(c->err, sizeof(c->err), "unknown op kind %u at seq %u", kind, s); rc = -1; diff --git a/helios/src/execution/roce.rs b/helios/src/execution/roce.rs index 9b29e9c44..68d7232c9 100644 --- a/helios/src/execution/roce.rs +++ b/helios/src/execution/roce.rs @@ -14,8 +14,8 @@ use std::ffi::{CStr, CString, c_char, c_int, c_void}; use std::sync::atomic::{AtomicU32, Ordering}; -use super::roce_fabric::Topology; use super::roce_fabric::Shape; +use super::roce_fabric::Topology; use crate::runtime_core::RoceSpec; use crate::{ExecutionError, Failure, Result}; @@ -43,12 +43,12 @@ unsafe extern "C" { out: *mut u64, ) -> c_int; fn roce_blob_bytes() -> u64; - fn roce_create( + fn roce_create_with_gids( world: c_int, rank: c_int, hca_names: *const *const c_char, n_hca: c_int, - gid_index: c_int, + gid_indices: *const c_int, traffic_class: c_int, n_lane: c_int, region: *mut c_void, @@ -69,6 +69,7 @@ unsafe extern "C" { routes: *const i32, n_rail: c_int, ) -> c_int; + fn roce_set_relay(c: *mut Context, plan: *const i32, n: c_int) -> c_int; fn roce_start(c: *mut Context) -> c_int; fn roce_failed(c: *mut Context) -> c_int; fn roce_error(c: *mut Context) -> *const c_char; @@ -98,6 +99,38 @@ fn peer_blobs(records: &[Vec], world: usize) -> Result> { .collect()) } +fn validate_relay_plan(shape: Shape, world: usize, rank: usize, plan: &[i32]) -> Result<()> { + if shape != Shape::Mesh { + return Err(failure("RoCE all-gather relay requires a mesh topology")); + } + if plan.len() != 2 * world { + return Err(failure(format!( + "RoCE all-gather relay plan has {} entries for {} ranks", + plan.len(), + world + ))); + } + for p in 0..world { + let via = plan[p]; + let to = plan[world + p]; + let bad_self = p == rank && (via != -1 || to != -1); + let bad_via = via != -1 + && (via < 0 + || via as usize >= world + || via as usize == rank + || via as usize == p + || plan[via as usize] != -1); + let bad_to = + to != -1 && (to < 0 || to as usize >= world || to as usize == rank || to as usize == p); + if bad_self || bad_via || bad_to { + return Err(failure(format!( + "invalid RoCE all-gather relay plan entry for rank {p}: via={via}, to={to}" + ))); + } + } + Ok(()) +} + /// One rank's connected transport. Dropping it stops the proxy and releases the HCAs; the region /// itself belongs to the core. pub struct RoceTransport { @@ -178,6 +211,16 @@ impl RoceTransport { ))); } } + if topology.gid_indices.len() != topology.hcas.len() { + return Err(failure(format!( + "RoCE topology has {} GID indices for {} HCAs", + topology.gid_indices.len(), + topology.hcas.len() + ))); + } + if let Some(plan) = &topology.relay_plan { + validate_relay_plan(topology.shape, spec.world, spec.rank, plan)?; + } let names = topology .hcas .iter() @@ -196,13 +239,14 @@ impl RoceTransport { let region = spec.region_address as *mut c_void; // Flags and the control record must start at zero: every rank begins again at sequence 1. unsafe { std::ptr::write_bytes(region.cast::(), 0, spec.region_bytes as usize) }; + let gid_indices: Vec = topology.gid_indices.iter().map(|&g| g as c_int).collect(); let context = unsafe { - roce_create( + roce_create_with_gids( spec.world as c_int, spec.rank as c_int, pointers.as_ptr(), pointers.len() as c_int, - topology.gid_index as c_int, + gid_indices.as_ptr(), topology.traffic_class as c_int, PROXY_LANES, region, @@ -297,6 +341,16 @@ impl RoceTransport { self.proxy_error() ))); } + if let Some(plan) = &self.topology.relay_plan { + let status = + unsafe { roce_set_relay(self.context, plan.as_ptr(), plan.len() as c_int) }; + if status != 0 { + return Err(failure(format!( + "RoCE all-gather relay setup failed: {}", + self.proxy_error() + ))); + } + } if unsafe { roce_start(self.context) } != 0 { return Err(failure(format!( "RoCE proxy thread failed to start: {}", @@ -388,11 +442,12 @@ mod tests { }; let topology = Topology { hcas: vec!["rail0".into(), "rail1".into()], - gid_index: 3, + gid_indices: vec![3, 3], traffic_class: 0, rails: 2, routes: vec![vec![], vec![(0, 0), (1, 1)], vec![], vec![(0, 0), (1, 1)]], direct: vec![false; 4], + relay_plan: None, shape: Shape::Ring, links: super::super::roce_fabric::Links::All, }; @@ -433,6 +488,7 @@ mod tests { fn peer_records_require_one_native_ring_protocol() { // SAFETY: This query has no arguments, device access, or allocation. let size = unsafe { roce_blob_bytes() } as usize; + assert_eq!(size, 1176); let record = |abi: u32, value: u8| { let mut bytes = abi.to_le_bytes().to_vec(); bytes.extend(vec![value; size]); @@ -442,6 +498,9 @@ mod tests { let expected = [vec![0x12; size], vec![0x34; size]].concat(); assert_eq!(peer_blobs(&records, 2).unwrap(), expected); assert!(peer_blobs(&records, 3).is_err()); + let mut legacy = records.clone(); + legacy[1].truncate(4 + 1168); + assert!(peer_blobs(&legacy, 2).is_err()); let mut foreign = records.clone(); foreign[1] = record(9, 0x34); assert!(peer_blobs(&foreign, 2).is_err()); @@ -456,7 +515,7 @@ mod tests { #[test] fn rejects_incompatible_core_and_routes_before_modifying_region() { let (region, spec, topology) = specification(); - for case in 0..10 { + for case in 0..14 { let mut spec = spec.clone(); let mut topology = topology.clone(); match case { @@ -472,6 +531,34 @@ mod tests { 7 => topology.routes[1].clear(), 8 => topology.routes[2] = vec![(0, 0), (1, 1)], 9 => topology.routes[3][1].0 = 2, + 10 => { + topology.gid_indices.pop(); + } + 11 => { + // Relay plans are valid only on mesh topologies. + topology.relay_plan = Some(vec![-1, -1, 1, -1, -1, 3, -1, -1]); + } + 12 => { + topology.shape = Shape::Mesh; + topology.routes = vec![ + vec![], + vec![(0, 0), (1, 1)], + vec![(0, 0), (1, 1)], + vec![(0, 0), (1, 1)], + ]; + topology.relay_plan = Some(vec![-1; 6]); + } + 13 => { + topology.shape = Shape::Mesh; + topology.routes = vec![ + vec![], + vec![(0, 0), (1, 1)], + vec![(0, 0), (1, 1)], + vec![(0, 0), (1, 1)], + ]; + // Rank 0 cannot relay through itself (via == rank). + topology.relay_plan = Some(vec![-1, 0, -1, -1, -1, -1, -1, -1]); + } _ => unreachable!(), } // SAFETY: Every case fails preflight before accessing or registering the region. @@ -521,4 +608,141 @@ mod tests { ); } } + + #[test] + fn roce_create_with_gids_rejects_null_and_out_of_range_gid_indices() { + let (mut region, spec, _) = specification(); + let names = [ + CString::new("rail0").unwrap(), + CString::new("rail1").unwrap(), + ]; + let pointers: Vec<*const c_char> = names.iter().map(|name| name.as_ptr()).collect(); + let mut message = [0 as c_char; 512]; + + // SAFETY: NULL `gid_indices` is rejected in geometry validation before touching `region` + // or calling into libibverbs. + let ctx = unsafe { + roce_create_with_gids( + spec.world as c_int, + spec.rank as c_int, + pointers.as_ptr(), + pointers.len() as c_int, + std::ptr::null(), + 0, + PROXY_LANES, + region.as_mut_ptr().cast(), + spec.region_bytes, + spec.slot_bytes, + spec.pipe_bytes, + spec.varlen_bytes, + message.as_mut_ptr(), + message.len() as u64, + ) + }; + assert!(ctx.is_null()); + let text = unsafe { CStr::from_ptr(message.as_ptr()) }.to_string_lossy(); + assert!(text.contains("invalid roce runtime geometry"), "{text}"); + + for bad in [-1 as c_int, 256 as c_int] { + let gids = [3 as c_int, bad]; + message.fill(0); + // SAFETY: Out-of-range GID indices fail before allocation or RDMA device access. + let ctx = unsafe { + roce_create_with_gids( + spec.world as c_int, + spec.rank as c_int, + pointers.as_ptr(), + pointers.len() as c_int, + gids.as_ptr(), + 0, + PROXY_LANES, + region.as_mut_ptr().cast(), + spec.region_bytes, + spec.slot_bytes, + spec.pipe_bytes, + spec.varlen_bytes, + message.as_mut_ptr(), + message.len() as u64, + ) + }; + assert!(ctx.is_null()); + let text = unsafe { CStr::from_ptr(message.as_ptr()) }.to_string_lossy(); + assert!( + text.contains(&format!("invalid roce gid index {bad} for HCA 1")), + "{text}" + ); + } + } + + #[test] + fn relay_plan_validation_matches_c_proxy_invariants() { + // Valid 4-rank partner-cable plan for rank 0 (partners (0,3) and (1,2)). + let valid = vec![-1, -1, 1, -1, -1, 3, -1, -1]; + validate_relay_plan(Shape::Mesh, 4, 0, &valid).unwrap(); + assert!(validate_relay_plan(Shape::Ring, 4, 0, &valid).is_err()); + assert!(validate_relay_plan(Shape::Chain, 4, 0, &valid).is_err()); + assert!(validate_relay_plan(Shape::Mesh, 4, 0, &valid[..7]).is_err()); + // Chained relay (via points to a peer that itself relays) is rejected. + let chained = vec![-1, 2, 3, -1, -1, -1, -1, -1]; + assert!(validate_relay_plan(Shape::Mesh, 4, 0, &chained).is_err()); + // Self entry must be (-1, -1). + let self_via = vec![1, -1, -1, -1, -1, -1, -1, -1]; + assert!(validate_relay_plan(Shape::Mesh, 4, 0, &self_via).is_err()); + // Forward-to-self is rejected. + let to_self = vec![-1, -1, -1, -1, -1, 0, -1, -1]; + assert!(validate_relay_plan(Shape::Mesh, 4, 0, &to_self).is_err()); + + // When a live active RDMA device is present, also verify the linked C `roce_set_relay` + // rejects an unconnected context cleanly through FFI. + let Ok(entries) = std::fs::read_dir("/sys/class/infiniband") else { + return; + }; + let mut active: Vec = entries + .flatten() + .filter_map(|entry| { + let name = entry.file_name().into_string().ok()?; + let state = std::fs::read_to_string(entry.path().join("ports/1/state")).ok()?; + state.contains("ACTIVE").then_some(name) + }) + .collect(); + active.sort(); + let Some(hca) = active.first() else { + return; + }; + let (mut region, spec, _) = specification(); + let hca_name = CString::new(hca.as_str()).unwrap(); + let pointers = [hca_name.as_ptr()]; + let gids = [0 as c_int]; + let mut message = [0 as c_char; 512]; + if unsafe { roce_ensure_libibverbs(message.as_mut_ptr(), message.len() as u64) } != 0 { + return; + } + // SAFETY: `region` is live for the duration of `ctx` and `roce_destroy` runs before return. + let ctx = unsafe { + roce_create_with_gids( + spec.world as c_int, + spec.rank as c_int, + pointers.as_ptr(), + 1, + gids.as_ptr(), + 0, + 1, + region.as_mut_ptr().cast(), + spec.region_bytes, + spec.slot_bytes, + spec.pipe_bytes, + spec.varlen_bytes, + message.as_mut_ptr(), + message.len() as u64, + ) + }; + if ctx.is_null() { + return; + } + let status = unsafe { roce_set_relay(ctx, valid.as_ptr(), valid.len() as c_int) }; + assert_ne!(status, 0); + let err = unsafe { CStr::from_ptr(roce_error(ctx)) }.to_string_lossy(); + assert!(err.contains("connected mesh transport"), "{err}"); + unsafe { roce_destroy(ctx) }; + } } diff --git a/helios/src/execution/roce_fabric.rs b/helios/src/execution/roce_fabric.rs index 63cb04e7d..99b37866e 100644 --- a/helios/src/execution/roce_fabric.rs +++ b/helios/src/execution/roce_fabric.rs @@ -218,10 +218,11 @@ pub fn ipv4_subnet_mask(prefix: u8) -> u32 { u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0) } -/// This host's RoCE devices in name order, and the GID index and traffic class they use. +/// This host's RoCE devices in name order, and the per-device RoCEv2 GID indices and traffic class +/// they use. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Fabric { - pub gid_index: u32, + pub gid_indices: Vec, pub traffic_class: u32, pub endpoints: Vec, } @@ -306,7 +307,7 @@ impl Links { #[derive(Clone, Debug, PartialEq, Eq)] pub struct Topology { pub hcas: Vec, - pub gid_index: u32, + pub gid_indices: Vec, pub traffic_class: u32, pub rails: usize, pub routes: Vec>, @@ -314,6 +315,9 @@ pub struct Topology { /// devices that are LLDP neighbors, or, with three or more ranks, a subnet held by fewer ranks /// than the world. It does not verify that the cable carries traffic. pub direct: Vec, + /// All-gather relay plan (`2 * world` entries: `via` then `forward`) for `roce_set_relay`, + /// present on mesh topologies whose ranks form mutual direct-cable pairs. + pub relay_plan: Option>, pub shape: Shape, pub links: Links, } @@ -377,10 +381,10 @@ fn has_rocev2_ipv4_gid(device: &Path, index: u32) -> bool { } /// Discover the RoCE devices under `root` (normally /sys/class/infiniband): every device whose -/// port 1 is active and holds a RoCEv2 GID at the chosen index. The index is 3 when every active -/// device has a RoCEv2 IPv4 GID there, otherwise the lowest index at which one does. `prefix` -/// gives a network device's prefix length for an address it holds, and `lldp` the LLDP neighbor -/// MAC addresses of each listed network device (see `parse_lldp`). +/// port 1 is active and holds a RoCEv2 IPv4 GID. Each active device selects index 3 when it has a +/// RoCEv2 IPv4 GID there, otherwise its own lowest index with a RoCEv2 IPv4 GID. `prefix` gives a +/// network device's prefix length for an address it holds, and `lldp` the LLDP neighbor MAC +/// addresses of each listed network device (see `parse_lldp`). pub fn discover_in( root: &Path, prefix: impl Fn(&str, Ipv4Addr) -> Option, @@ -402,36 +406,37 @@ pub fn discover_in( .collect(); names.sort(); let roce_v2_ipv4 = |name: &str, index: u32| has_rocev2_ipv4_gid(&root.join(name), index); - let gid_index = if !names.is_empty() - && names - .iter() - .all(|name| roce_v2_ipv4(name, PREFERRED_GID_INDEX)) - { - PREFERRED_GID_INDEX - } else { - (0..GID_TABLE) - .find(|&index| names.iter().any(|name| roce_v2_ipv4(name, index))) - .ok_or_else(|| failure("no active RDMA device has a RoCEv2 IPv4 GID"))? + let pick_gid_index = |name: &str| { + if roce_v2_ipv4(name, PREFERRED_GID_INDEX) { + Some(PREFERRED_GID_INDEX) + } else { + (0..GID_TABLE).find(|&index| roce_v2_ipv4(name, index)) + } }; - let devices: Vec<(&String, Option)> = names + let devices: Vec<(&String, u32, Option)> = names .iter() - .filter(|name| roce_v2_ipv4(name, gid_index)) - .take(MAX_DEVICES) - .map(|name| { + .filter_map(|name| { + let gid = pick_gid_index(name)?; let port = root.join(name).join("ports/1"); - ( + Some(( name, - read(&port.join(format!("gid_attrs/ndevs/{gid_index}"))), - ) + gid, + read(&port.join(format!("gid_attrs/ndevs/{gid}"))), + )) }) + .take(MAX_DEVICES) .collect(); - let netdevs: Vec = devices.iter().filter_map(|(_, n)| n.clone()).collect(); + if devices.is_empty() { + return Err(failure("no active RDMA device has a RoCEv2 IPv4 GID")); + } + let gid_indices: Vec = devices.iter().map(|(_, gid, _)| *gid).collect(); + let netdevs: Vec = devices.iter().filter_map(|(_, _, n)| n.clone()).collect(); let mut neighbors = lldp(&netdevs); let endpoints: Vec = devices .into_iter() - .map(|(name, netdev)| { + .map(|(name, gid, netdev)| { let port = root.join(name).join("ports/1"); - let address = read(&port.join(format!("gids/{gid_index}"))) + let address = read(&port.join(format!("gids/{gid}"))) .as_deref() .and_then(mapped_ipv4); let ipv4 = address @@ -464,7 +469,7 @@ pub fn discover_in( }) .collect(); Ok(Fabric { - gid_index, + gid_indices, traffic_class: 0, endpoints, }) @@ -968,6 +973,93 @@ fn direct_peers(endpoints: &[Vec], rank: usize, routes: &[Vec<(u32, u3 .collect() } +/// Per rank, its only peer whose every mesh rail rides a point-to-point direct cable (devices +/// that are LLDP neighbors, or a subnet held by those two ranks alone), else `None`. With fewer +/// than three ranks every subnet joins both, so no rank has a cable partner for relay. +pub fn partners( + endpoints: &[Vec], + rails: usize, + links: Links, +) -> Result>> { + let world = endpoints.len(); + if world < 3 || links == Links::Shared { + return Ok(vec![None; world]); + } + let planner = Planner::new(endpoints, rails, links)?; + let mut out = Vec::with_capacity(world); + for rank in 0..world { + let mut direct = Vec::new(); + for peer in 0..world { + if peer == rank { + continue; + } + let chosen = planner.peer(rank, peer)?; + let cable = !chosen.is_empty() + && chosen.iter().all(|&(local, remote)| { + let x = &endpoints[rank][local as usize]; + let y = &endpoints[peer][remote as usize]; + lldp_adjacent(x, y) + || x.network() + .is_some_and(|network| planner.breadths[&network] == 2) + }); + if cable { + direct.push(peer); + } + } + out.push((direct.len() == 1).then(|| direct[0])); + } + Ok(out) +} + +/// The all-gather relay plan of `rank` for `roce_set_relay`, or `None` unless `world >= 4` is even +/// and the ranks form mutual direct-cable pairs with no rank left out. +/// +/// The returned `2 * world` entries hold `via` (the rank forwarding `rank`'s all-gather chunks to +/// peer `p`, or `-1` when sent directly) followed by `forward` (the rank to which `rank` forwards +/// source `s`'s chunks, or `-1` when none). Every rank derives the same pairing from the shared +/// endpoint list. +pub fn relay_plan( + endpoints: &[Vec], + rank: usize, + rails: usize, + links: Links, +) -> Result>> { + let world = endpoints.len(); + if rank >= world { + return Err(failure("invalid RoCE relay plan request")); + } + if world < 4 || world % 2 != 0 || links == Links::Shared { + return Ok(None); + } + let mates = partners(endpoints, rails, links)?; + let mut paired = Vec::with_capacity(world); + for (r, mate) in mates.iter().enumerate() { + let Some(m) = *mate else { + return Ok(None); + }; + if mates.get(m).copied().flatten() != Some(r) { + return Ok(None); + } + paired.push(m); + } + let side: Vec = (0..world).map(|r| u8::from(r > paired[r])).collect(); + let mate = paired[rank]; + let mut plan = vec![-1i32; 2 * world]; + for peer in 0..world { + if peer == rank || peer == mate { + continue; + } + if side[peer] != side[rank] { + // Peer's partner is on our side and receives our chunks directly. + plan[peer] = paired[peer] as i32; + } else { + // Peer is on our side: we receive its chunks and pass them to our partner. + plan[world + peer] = mate as i32; + } + } + Ok(Some(plan)) +} + /// The routes of `shape` for `rank`: a mesh routes to every rank; a ring or chain routes only to /// the ranks `shape` links, and the native proxy forwards writes to the others. The same plan works /// over a switch while keeping unlinked QPs unconnected. Routes are planned over every rank's @@ -999,6 +1091,19 @@ pub fn plan_shape_routes( } impl Fabric { + /// The first selected device's RoCEv2 GID index, or `PREFERRED_GID_INDEX` when empty. + pub fn gid_index(&self) -> u32 { + self.gid_indices + .first() + .copied() + .unwrap_or(PREFERRED_GID_INDEX) + } + + /// The RoCEv2 GID index selected for endpoint `index`. + pub fn gid_index_for(&self, index: usize) -> Option { + self.gid_indices.get(index).copied() + } + /// The topology this rank opens for `shape` over `links`, from every rank's endpoints in rank /// order. pub fn topology( @@ -1011,14 +1116,27 @@ impl Fabric { if endpoints.get(rank) != Some(&self.endpoints) || endpoints.iter().any(Vec::is_empty) { return Err(failure("every rank needs at least one RoCE device")); } + if self.gid_indices.len() != self.endpoints.len() { + return Err(failure(format!( + "RoCE fabric has {} GID indices for {} devices", + self.gid_indices.len(), + self.endpoints.len() + ))); + } let rails = endpoints.iter().map(Vec::len).min().unwrap().min(MAX_RAILS); let routes = plan_shape_routes(endpoints, rank, rails, shape, links)?; + let relay_plan = if shape == Shape::Mesh { + relay_plan(endpoints, rank, rails, links)? + } else { + None + }; Ok(Topology { hcas: self.endpoints.iter().map(|e| e.name.clone()).collect(), - gid_index: self.gid_index, + gid_indices: self.gid_indices.clone(), traffic_class: self.traffic_class, rails, direct: direct_peers(endpoints, rank, &routes), + relay_plan, routes, shape, links, @@ -1121,7 +1239,8 @@ mod tests { ) .unwrap(); assert_eq!(*asked.borrow(), ["net-roceP2p1s0f0", "net-rocep1s0f0"]); - assert_eq!(fabric.gid_index, 3); + assert_eq!(fabric.gid_index(), 3); + assert_eq!(fabric.gid_indices, vec![3, 3]); assert_eq!( fabric.endpoints, vec![ @@ -1154,13 +1273,81 @@ mod tests { &[(1, "RoCE v2", a), (3, "IB/RoCE v1", a)], ); let fabric = discover_in(&root, |_, _| Some(16), |_| Default::default()).unwrap(); - assert_eq!((fabric.gid_index, fabric.endpoints.len()), (1, 1)); + assert_eq!((fabric.gid_index(), fabric.endpoints.len()), (1, 1)); + assert_eq!(fabric.gid_indices, vec![1]); std::fs::remove_dir_all(&root).unwrap(); std::fs::create_dir_all(&root).unwrap(); assert!(discover_in(&root, |_, _| Some(16), |_| Default::default()).is_err()); let _ = std::fs::remove_dir_all(&root); } + #[test] + fn mixed_per_hca_gid_indices_discover_both_ipv4_rails() { + let root = scratch("mixed-gid"); + let a = Ipv4Addr::new(10, 200, 1, 10); + let b = Ipv4Addr::new(10, 200, 2, 10); + device(&root, "roceP2p1s0f0", "4: ACTIVE", &[(3, "RoCE v2", b)]); + device(&root, "rocep1s0f0", "4: ACTIVE", &[(5, "RoCE v2", a)]); + // Link-local IPv6 occupies index 3 on rocep1s0f0, while its IPv4 RoCEv2 GID sits at 5. + let port = root.join("rocep1s0f0/ports/1"); + std::fs::write( + port.join("gids/3"), + "fe80:0000:0000:0000:0200:00ff:fe00:0001\n", + ) + .unwrap(); + std::fs::write(port.join("gid_attrs/types/3"), "RoCE v2\n").unwrap(); + std::fs::write(port.join("gid_attrs/ndevs/3"), "net-rocep1s0f0\n").unwrap(); + + let fabric = discover_in(&root, |_, _| Some(24), |_| Default::default()).unwrap(); + assert_eq!(fabric.endpoints.len(), 2); + assert_eq!(fabric.gid_index(), 3); + assert_eq!(fabric.gid_indices, vec![3, 5]); + assert_eq!(fabric.gid_index_for(0), Some(3)); + assert_eq!(fabric.gid_index_for(1), Some(5)); + assert_eq!(fabric.gid_index_for(2), None); + assert_eq!(fabric.endpoints[0].name, "roceP2p1s0f0"); + assert_eq!(fabric.endpoints[0].ipv4, Some((b, 24))); + assert_eq!(fabric.endpoints[1].name, "rocep1s0f0"); + assert_eq!(fabric.endpoints[1].ipv4, Some((a, 24))); + + let peer = vec![ + endpoint("roceP2p1s0f0", "10.200.2.11/24"), + endpoint("rocep1s0f0", "10.200.1.11/24"), + ]; + let topology = fabric + .topology( + &[fabric.endpoints.clone(), peer], + 0, + Shape::Mesh, + Links::All, + ) + .unwrap(); + assert_eq!(topology.rails, 2); + assert_eq!(topology.gid_indices, vec![3, 5]); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn preferred_gid_index_wins_per_hca_over_lower_roce_v2_index() { + let root = scratch("prefer-three-per-hca"); + let a = Ipv4Addr::new(10, 200, 1, 10); + let b = Ipv4Addr::new(10, 200, 2, 10); + // First HCA has valid RoCE v2 IPv4 GIDs at both 1 and 3: preferred index 3 must win. + device( + &root, + "roceP2p1s0f0", + "4: ACTIVE", + &[(1, "RoCE v2", a), (3, "RoCE v2", b)], + ); + // Sibling HCA only has its RoCE v2 IPv4 GID at index 5. + device(&root, "rocep1s0f0", "4: ACTIVE", &[(5, "RoCE v2", a)]); + let fabric = discover_in(&root, |_, _| Some(24), |_| Default::default()).unwrap(); + assert_eq!(fabric.gid_indices, vec![3, 5]); + assert_eq!(fabric.endpoints[0].ipv4, Some((b, 24))); + assert_eq!(fabric.endpoints[1].ipv4, Some((a, 24))); + let _ = std::fs::remove_dir_all(&root); + } + #[test] fn endpoints_survive_the_rendezvous_encoding() { let endpoints = vec![ @@ -1506,7 +1693,7 @@ mod tests { assert_eq!(route_devices(&pair, rank, switched), sorted(SWITCH_DEVICES)); } let fabric = Fabric { - gid_index: 3, + gid_indices: vec![3; pair[0].len()], traffic_class: 0, endpoints: pair[0].clone(), }; @@ -1620,7 +1807,7 @@ mod tests { fn a_topology_marks_and_lists_each_peer_route() { let endpoints = switch_with_partner_cables(); let fabric = Fabric { - gid_index: 3, + gid_indices: vec![3; endpoints[1].len()], traffic_class: 0, endpoints: endpoints[1].clone(), }; @@ -1771,7 +1958,7 @@ mod tests { #[test] fn a_topology_opens_every_device_and_caps_rails_at_the_smallest_rank() { let fabric = Fabric { - gid_index: 3, + gid_indices: vec![3, 3], traffic_class: 0, endpoints: vec![endpoint("a", "10.0.0.1/24"), endpoint("b", "10.0.1.1/24")], }; @@ -2122,4 +2309,158 @@ mod tests { } } } + + #[test] + fn relay_plan_delivers_every_shard_once_and_forwards_only_over_cables() { + let cases: Vec<(&str, Vec>, Vec)> = vec![ + ("four-ranks", switch_with_partner_cables(), PARTNER.to_vec()), + ( + "four-ranks-lldp", + with_lldp(&switch_with_partner_cables(), &PARTNER), + PARTNER.to_vec(), + ), + ( + "eight-ranks", + paired_switch(4), + (0..8).map(|r| r ^ 1).collect(), + ), + ]; + for (label, endpoints, mates) in cases { + let world = endpoints.len(); + assert_eq!( + partners(&endpoints, 2, Links::All).unwrap(), + mates.iter().copied().map(Some).collect::>(), + "{label}" + ); + let plans: Vec> = (0..world) + .map(|rank| { + relay_plan(&endpoints, rank, 2, Links::All) + .unwrap() + .unwrap_or_else(|| panic!("{label}: rank {rank} missing relay plan")) + }) + .collect(); + let mut writers: std::collections::BTreeMap<(usize, usize), Vec> = + std::collections::BTreeMap::new(); + for source in 0..world { + for peer in 0..world { + if peer != source && plans[source][peer] == -1 { + writers.entry((source, peer)).or_default().push(source); + } + } + } + for forwarder in 0..world { + for source in 0..world { + let target = plans[forwarder][world + source]; + if target != -1 { + assert_eq!( + writers.get(&(source, forwarder)), + Some(&vec![source]), + "{label}: forwarder {forwarder} must receive source {source} directly" + ); + writers + .entry((source, target as usize)) + .or_default() + .push(forwarder); + assert_eq!( + target as usize, mates[forwarder], + "{label}: rank {forwarder} must forward only to partner" + ); + } + } + } + for source in 0..world { + for peer in 0..world { + if peer == source { + continue; + } + let assigned = &writers[&(source, peer)]; + assert_eq!( + assigned.len(), + 1, + "{label}: ({source}, {peer}) -> {assigned:?}" + ); + let writer = assigned[0]; + if writer != source { + assert_eq!(writer as i32, plans[source][peer], "{label}"); + assert_eq!(writer, mates[peer], "{label}"); + } + } + } + } + // With two pairs, each rank sends two of its three all-gather shards over its cable. + let four = switch_with_partner_cables(); + for rank in 0..4 { + let plan = relay_plan(&four, rank, 2, Links::All).unwrap().unwrap(); + let direct: Vec = (0..4).filter(|&p| p != rank && plan[p] == -1).collect(); + let forwarded: Vec = plan[4..] + .iter() + .filter(|&&t| t != -1) + .map(|&t| t as usize) + .collect(); + let sends: Vec = direct.into_iter().chain(forwarded).collect(); + assert_eq!(sends.len(), 3); + assert_eq!(sends.iter().filter(|&&p| p == PARTNER[rank]).count(), 2); + } + } + + #[test] + fn relay_plan_supports_lldp_link_local_cables_and_disables_for_switch_only_or_ring() { + let mut endpoints = with_lldp(&switch_with_partner_cables(), &PARTNER); + // Replace partner-cable subnets with shared link-local space so only LLDP marks cables. + for (rank, devices) in endpoints.iter_mut().enumerate() { + for e in devices.iter_mut() { + if DIRECT_DEVICES.contains(&e.name.as_str()) { + e.ipv4 = Some((Ipv4Addr::new(169, 254, 1, 11 + rank as u8), 16)); + } + } + } + let fabric = Fabric { + gid_indices: vec![3; endpoints[1].len()], + traffic_class: 0, + endpoints: endpoints[1].clone(), + }; + let mesh = fabric + .topology(&endpoints, 1, Shape::Mesh, Links::All) + .unwrap(); + assert_eq!(mesh.relay_plan, Some(vec![-1, -1, -1, 0, 2, -1, -1, -1])); + let switch_only = fabric + .topology(&endpoints, 1, Shape::Mesh, Links::Shared) + .unwrap(); + assert_eq!(switch_only.relay_plan, None); + let ring = fabric + .topology(&endpoints, 1, Shape::Ring, Links::All) + .unwrap(); + assert_eq!(ring.relay_plan, None); + let chain = fabric + .topology(&endpoints, 1, Shape::Chain, Links::All) + .unwrap(); + assert_eq!(chain.relay_plan, None); + + // A missing partner cable, purely switched fabric, or 2-rank group produces no relay plan. + let mut down = switch_with_partner_cables(); + down[2].retain(|e| SWITCH_DEVICES.contains(&e.name.as_str())); + assert_eq!( + partners(&down, 2, Links::All).unwrap(), + vec![Some(3), None, None, Some(0)] + ); + for rank in 0..4 { + assert_eq!(relay_plan(&down, rank, 2, Links::All).unwrap(), None); + } + let switched: Vec> = (0..4) + .map(|r| { + vec![ + spark("roceP2p1s0f0", &format!("10.200.0.{}/24", 11 + r)), + spark("rocep1s0f0", &format!("10.200.1.{}/24", 11 + r)), + ] + }) + .collect(); + assert_eq!(partners(&switched, 2, Links::All).unwrap(), vec![None; 4]); + assert_eq!(relay_plan(&switched, 0, 2, Links::All).unwrap(), None); + let pair = vec![ + switch_with_partner_cables()[0].clone(), + switch_with_partner_cables()[3].clone(), + ]; + assert_eq!(partners(&pair, 2, Links::All).unwrap(), vec![None, None]); + assert_eq!(relay_plan(&pair, 0, 2, Links::All).unwrap(), None); + } } diff --git a/ignition/preparation/collectives.py b/ignition/preparation/collectives.py index 76c165770..9a5a286a5 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -77,10 +77,27 @@ def create_roce_runtime(group, device, *, max_tokens, pipe_tokens, hidden_size, lambda size: core_storage.host_allocate("roce", (size,), torch.uint8).host_view) if type(varlen_bytes) is not int or varlen_bytes < 0 or varlen_bytes % 16: raise ValueError("variable-length gather capacity must be a nonnegative multiple of 16 bytes") - # Each host uses the GID index native serving discovers for it. + # Each host uses the HCAs and per-device GID indices native serving discovers for it. + import inspect + + devices = flare_heliopause.roce_devices() + gid_kwargs: dict[str, object] + if "gid_indices" in inspect.signature(roce.AllReduce.__init__).parameters: + gid_kwargs = { + "hca_names": [name for name, _ in devices], + "gid_indices": [gid for _, gid in devices], + } + else: + distinct = sorted({gid for _, gid in devices}) + if len(distinct) > 1: + raise RuntimeError( + f"host RoCE devices use distinct GID indices {distinct} ({devices}); " + "update the pinned FlashInfer dependency to a revision supporting per-HCA gid_indices" + ) + gid_kwargs = {"gid_index": distinct[0] if distinct else flare_heliopause.roce_gid_index()} runtime = roce.AllReduce(exchange_group=group, device=device, max_size=nbytes, max_gather_bytes=gather_bytes, pipe_bytes=pipe_bytes, region_allocator=region, - gid_index=flare_heliopause.roce_gid_index(), + **gid_kwargs, ring=ring, **({"ring_open": True} if ring_open else {}), **({"max_varlen_bytes": varlen_bytes} if varlen_bytes else {})) if core_storage is not None: From 7a09d49ed89093a55f50788f984fd3e9c7bb6ea8 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 08:37:29 -0800 Subject: [PATCH 2/4] ci,tests: enforce vendored RoCE proxy byte parity and run roce unit tests Why: Previously, no automated check verified that vendored `helios/native/roce_proxy.c` remained byte-for-byte identical to FlashInfer's `_roce_proxy.c` after its 9-line provenance header, and `.github/workflows/native-serving.yml` only ran `cargo check` for `--features roce` without executing `execution::roce` unit tests. That allowed protocol drift and left C/FFI preflight and handshake tests unexecuted in CI. What changed: - Before: `tests/preparation/` had no RoCE proxy parity check or unit test for `create_roce_runtime`'s per-HCA GID dispatch; `.github/workflows/native-serving.yml`'s `rdma` job stopped after `cargo check --tests --features roce,rdma`. - After: Added `tests/preparation/test_roce_proxy_parity.py` (executed by `.github/workflows/python-cpu.yml`) asserting LF line endings, the 9-line SPDX/provenance header, and 0-byte diff between `helios/native/roce_proxy.c` lines 10..EOF and the installed FlashInfer package's `_roce_proxy.c`, plus contract tests for `create_roce_runtime` per-HCA GID forwarding and loud rejection of mixed-GID hosts on older FlashInfer builds. Added a `cargo test --locked --release --manifest-path helios/Cargo.toml --features roce --lib execution::roce` step to `.github/workflows/native-serving.yml`. Claimed benefit: Prevents future preparation-vs-serving RoCE proxy drift and executes native RoCE C/FFI and fabric planner unit tests automatically in CI. Supporting evidence and limitations: Verified locally with `PYTHONPATH=: pytest tests/preparation/test_roce_proxy_parity.py tests/preparation/test_core_boundary.py tests/preparation/test_capture_roce_wait.py` (7 passed, 0 failed), `pytest tests/cli` (148 passed, 0 failed), and `cargo test --locked --release --manifest-path helios/Cargo.toml --features roce --lib execution::roce` (38 passed, 0 failed). In GitHub Actions `python-cpu.yml`, parity will pass once `pyproject.toml` pins the merged FlashInfer revision carrying `#209 + #195 + #157`. Design-Signed-Off-By: Antigravity (Gemini 4); design-review=2e5b --- .github/workflows/native-serving.yml | 2 + tests/preparation/test_roce_proxy_parity.py | 131 ++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 tests/preparation/test_roce_proxy_parity.py diff --git a/.github/workflows/native-serving.yml b/.github/workflows/native-serving.yml index 68b94b47b..8327f438b 100644 --- a/.github/workflows/native-serving.yml +++ b/.github/workflows/native-serving.yml @@ -111,3 +111,5 @@ jobs: cargo check --locked --manifest-path selene/Cargo.toml --tests --features rdma cargo check --locked --manifest-path selene-manager/Cargo.toml --tests --features rdma cargo check --locked --manifest-path flare-cli/Cargo.toml --tests --features roce,rdma + - name: Test native RoCE transport + run: cargo test --locked --release --manifest-path helios/Cargo.toml --features roce --lib execution::roce diff --git a/tests/preparation/test_roce_proxy_parity.py b/tests/preparation/test_roce_proxy_parity.py new file mode 100644 index 000000000..be93a5bb8 --- /dev/null +++ b/tests/preparation/test_roce_proxy_parity.py @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""Enforce byte-for-byte parity between vendored `helios/native/roce_proxy.c` and FlashInfer.""" + +from __future__ import annotations + +import difflib +import importlib.util +from pathlib import Path +from types import SimpleNamespace + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +VENDORED_PROXY = ROOT / "helios" / "native" / "roce_proxy.c" +PROVENANCE_LINES = 9 + + +def _upstream_roce_proxy() -> Path: + spec = importlib.util.find_spec("flashinfer") + if spec is None or not spec.submodule_search_locations: + pytest.fail("flashinfer package is not installed in the preparation environment") + for location in spec.submodule_search_locations: + candidate = ( + Path(location) / "experimental" / "b12x" / "comm" / "roce" / "_roce_proxy.c" + ) + if candidate.is_file(): + return candidate + pytest.fail( + "could not locate flashinfer/experimental/b12x/comm/roce/_roce_proxy.c in installed flashinfer" + ) + + +def test_vendored_roce_proxy_is_byte_identical_to_pinned_flashinfer(): + vendored_raw = VENDORED_PROXY.read_bytes() + assert b"\r" not in vendored_raw, "helios/native/roce_proxy.c must use LF line endings" + + lines = vendored_raw.splitlines(keepends=True) + assert len(lines) > PROVENANCE_LINES + header = b"".join(lines[:PROVENANCE_LINES]).decode("utf-8") + assert "SPDX-License-Identifier: Apache-2.0" in header + assert "flashinfer/experimental/b12x/comm/roce/_roce_proxy.c" in header + assert lines[PROVENANCE_LINES - 1] == b"\n", ( + "line 9 of helios/native/roce_proxy.c must be the blank separator after the provenance header" + ) + + vendored_body = b"".join(lines[PROVENANCE_LINES:]) + upstream_path = _upstream_roce_proxy() + upstream_raw = upstream_path.read_bytes() + if vendored_body != upstream_raw: + diff = "".join( + difflib.unified_diff( + upstream_raw.decode("utf-8", errors="replace").splitlines(keepends=True), + vendored_body.decode("utf-8", errors="replace").splitlines(keepends=True), + fromfile=str(upstream_path), + tofile=f"{VENDORED_PROXY} (lines {PROVENANCE_LINES + 1}..EOF)", + n=3, + ) + ) + preview = diff if len(diff) <= 4000 else diff[:4000] + "\n... (truncated)\n" + pytest.fail( + "helios/native/roce_proxy.c diverged from pinned FlashInfer _roce_proxy.c:\n" + + preview + ) + + +def test_create_roce_runtime_forwards_per_hca_gids_and_rejects_silent_mixed_fallback( + monkeypatch, +): + import sys + + from ignition.preparation import collectives + + recorded = {} + + class _AllReduceWithGids: + def __init__(self, *, hca_names=None, gid_indices=None, gid_index=None, **kwargs): + recorded["hca_names"] = hca_names + recorded["gid_indices"] = gid_indices + recorded["gid_index"] = gid_index + + class _AllReduceLegacy: + def __init__(self, *, gid_index=None, **kwargs): + recorded["legacy_gid_index"] = gid_index + + fake_heliopause = SimpleNamespace( + roce_devices=lambda: [("roceP2p1s0f0", 3), ("rocep1s0f0", 5)], + roce_gid_index=lambda: 3, + ) + fake_roce_pkg = SimpleNamespace(AllReduce=_AllReduceWithGids) + monkeypatch.setitem(sys.modules, "flare_heliopause", fake_heliopause) + monkeypatch.setitem(sys.modules, "b12x.comm", SimpleNamespace(roce=fake_roce_pkg)) + monkeypatch.setitem(sys.modules, "b12x.comm.roce", fake_roce_pkg) + + collectives.create_roce_runtime( + group=None, + device="cpu", + max_tokens=16, + pipe_tokens=16, + hidden_size=128, + gather_bytes=128, + ) + assert recorded["hca_names"] == ["roceP2p1s0f0", "rocep1s0f0"] + assert recorded["gid_indices"] == [3, 5] + assert recorded["gid_index"] is None + + # Older FlashInfer without `gid_indices` must fail loudly on mixed-GID hosts instead of + # silently preparing 1 rail while serving connects 2 rails. + fake_roce_pkg.AllReduce = _AllReduceLegacy + with pytest.raises(RuntimeError, match="distinct GID indices"): + collectives.create_roce_runtime( + group=None, + device="cpu", + max_tokens=16, + pipe_tokens=16, + hidden_size=128, + gather_bytes=128, + ) + + # Uniform-GID hosts still work on legacy builds. + fake_heliopause.roce_devices = lambda: [("roce0", 3), ("roce1", 3)] + collectives.create_roce_runtime( + group=None, + device="cpu", + max_tokens=16, + pipe_tokens=16, + hidden_size=128, + gather_bytes=128, + ) + assert recorded["legacy_gid_index"] == 3 From 81ef561e75551943624724384725f2bec96467c1 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 08:51:33 -0800 Subject: [PATCH 3/4] pyproject: pin flashinfer-python to unified RoCE ABI-14 proxy commit Why: `tests/preparation/test_roce_proxy_parity.py` enforces byte-for-byte parity between vendored `helios/native/roce_proxy.c` and the installed `flashinfer-python` source `_roce_proxy.c`. Keeping `pyproject.toml` on the prior FlashInfer commit (`5a8ceed80c`) would fail `python-cpu.yml` until the companion FlashInfer PR merges. What changed: Updated `[tool.uv.sources].flashinfer-python.rev` in `pyproject.toml` from `5a8ceed80ccc58e11a4d49ccc910f52967699c09` to `524799c47fca54229c15b6db12261171854a7b7d` (HEAD of `local-inference-lab/flashinfer#213`). Update this revision again to the merged `main` commit if `flashinfer#213` is squash-merged. Verification: Verified `pyproject.toml` parses via `tomllib` and confirmed that commit `524799c47fca54229c15b6db12261171854a7b7d` exists on `local-inference-lab/flashinfer` and matches `helios/native/roce_proxy.c` below line 9 (SHA-256 `1f6b3ea80dd0ebe55aa33f9c3af175c61d5a72af948991c568b485ad1b1c25bc`). Design-Signed-Off-By: Antigravity (Gemini 4); design-review=2e5b --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e03a2529c..f1f2992a3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,7 @@ explicit = true torch = { index = "pytorch-cu132" } torchvision = { index = "pytorch-cu132" } flare-heliopause = { path = "heliopause" } -flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", rev = "5a8ceed80ccc58e11a4d49ccc910f52967699c09" } +flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", rev = "524799c47fca54229c15b6db12261171854a7b7d" } [tool.setuptools.packages.find] include = ["ignition*"] From 41ad1a437a98766eab0228df8dc6344a3a18ddd4 Mon Sep 17 00:00:00 2001 From: Luke Alonso Date: Thu, 3 Dec 2026 12:29:12 -0800 Subject: [PATCH 4/4] helios,ignition,flare-cli: defer mesh roce_set_relay, repin merged FlashInfer, and keep roce_gid_index fallback Why: PR #707 review identified three issues: (1) enabling `roce_set_relay` by default reversed #279's documented serving behavior without a 4-node paired-cable + switch mesh A/B measurement, (2) `pyproject.toml` pointed at an unmerged FlashInfer branch commit before `local-inference-lab/flashinfer#213` merged to `main`, and (3) `flare-cli/src/doctor/spark.rs` retained an unreachable empty arm in `format_gid_indices`. In addition, calling `flare_heliopause.roce_devices()` unconditionally in `ignition/preparation/collectives.py` broke downstream test stubs in `hyperflare-recipes/tests/preparation/test_collectives.py` that provide only `roce_gid_index`. What changed: - Removed `partners()`, `relay_plan()`, `Topology::relay_plan`, `validate_relay_plan`, the `roce_set_relay` FFI call, and the `cluster.rs` relay summary from this branch (preserved separately on `wire-roce-set-relay`), and restored `docs/roce-ring.md` to state that serving does not enable FlashInfer's mesh all-gather relay. - Updated `[tool.uv.sources].flashinfer-python.rev` in `pyproject.toml` to merged `local-inference-lab/flashinfer` `main` commit `1441ce862ffbc9d8550fdda7ad90e97ca04f4b8e` (identical `_roce_proxy.c` body SHA-256 `1f6b3ea80dd0ebe55aa33f9c3af175c61d5a72af948991c568b485ad1b1c25bc`). - Updated `ignition/preparation/collectives.py` to check `getattr(flare_heliopause, "roce_devices", None)` before calling it, falling back to `roce_gid_index()` only when `roce_devices` is absent, and added coverage in `tests/preparation/test_roce_proxy_parity.py`. - Changed `format_gid_indices` in `flare-cli/src/doctor/spark.rs` to take `(first: u32, rest: &[u32])`, eliminating the unreachable empty arm. Claimed benefit and result: Keeps #707 focused on the merged ABI-14 RoCE proxy sync, per-HCA GID selection, and CI parity/test coverage without reversing #279 or breaking downstream `hyperflare-recipes` unit tests. Supporting evidence and limitations: - `RUSTFLAGS="-D warnings" cargo check --locked --release` on `helios` (`--features runtime-core,server,roce`) and `flare-cli` (`--tests --features roce`): PASS (0 warnings). - `cargo test --locked --release --manifest-path helios/Cargo.toml --features roce --lib execution::roce`: 35 passed, 0 failed. - `cargo test --locked --release --manifest-path flare-cli/Cargo.toml --features roce`: 247 passed, 0 failed. - `tests/preparation/{test_roce_proxy_parity,test_core_boundary,test_capture_roce_wait}.py`: 7 passed, 0 failed; `hyperflare-recipes/tests/preparation/test_collectives.py -k test_roce_setup`: 2 passed, 0 failed. - Multi-node 4x GB10 serving validation is executed next on the updated binary. Design-Signed-Off-By: Antigravity (Gemini 4); design-review=2e5b --- docs/roce-ring.md | 12 +- flare-cli/src/cluster.rs | 7 +- flare-cli/src/doctor/spark.rs | 37 +-- helios/src/execution/roce.rs | 146 +----------- helios/src/execution/roce_fabric.rs | 250 -------------------- ignition/preparation/collectives.py | 30 ++- pyproject.toml | 2 +- tests/preparation/test_roce_proxy_parity.py | 12 + 8 files changed, 58 insertions(+), 438 deletions(-) diff --git a/docs/roce-ring.md b/docs/roce-ring.md index 373c75d2c..52f337eda 100644 --- a/docs/roce-ring.md +++ b/docs/roce-ring.md @@ -163,11 +163,9 @@ rail in ring mailboxes that the runtime allocates at startup (validated across r connect), serves the pipelined reduce-scatter, shard-gather, and closed-ring 1-hop bidirectional reduce-scatter and shard-gather operations, connects four queue-pair lanes per rail, and exchanges start-of-op credits between proxies. Cores recording proxy ABI 9, 10 or 11 have the same captured -region layout, so the runtime loads cores that record ABI 9, 10, 11 or 14. On mesh topologies whose -ranks form mutual direct-cable pairs (unless `--roce-switch-only` excludes direct cables), serving -enables FlashInfer's two-shot all-gather relay (`roce_set_relay`) across cable partners; ring and -chain topologies do not use that mesh relay. The chain topology is a mode of this layout, and -startup rejects any other proxy ABI before replay. +region layout, so the runtime loads cores that record ABI 9, 10, 11 or 14. Serving does not enable +FlashInfer's all-gather relay. The chain topology is a mode of this layout, and startup rejects any +other proxy ABI before replay. ### Prepare across four hosts @@ -418,8 +416,8 @@ failed collective as a completed model step. | Component | Responsibility | | --- | --- | -| [Fabric discovery and route planning](../helios/src/execution/roce_fabric.rs) | Finds host devices with per-HCA GIDs, builds symmetric routes, and derives mesh partner-cable relay plans. | -| [Native transport owner](../helios/src/execution/roce.rs) | Validates the core ABI and layout, registers its region, enables the ring or mesh all-gather relay, and retains transport resources. | +| [Fabric discovery and route planning](../helios/src/execution/roce_fabric.rs) | Finds host devices with per-HCA GIDs and builds symmetric neighbor routes. | +| [Native transport owner](../helios/src/execution/roce.rs) | Validates the core ABI and layout, registers its region, enables the ring, and retains transport resources. | | [RDMA proxy](../helios/native/roce_proxy.c) | Posts direct, 1-hop closed-ring, and relayed writes, progresses mailboxes and acknowledgments, and releases two-shot send buffers. | | [Serving distribution](../flare-cli/src/distribution.rs) | Receives and verifies rank cores before handing rendezvous sockets to serving. | | [Cluster startup](../flare-cli/src/cluster.rs) | Exchanges endpoints and connection records before native replay. | diff --git a/flare-cli/src/cluster.rs b/flare-cli/src/cluster.rs index 0f5b73827..3531faecc 100644 --- a/flare-cli/src/cluster.rs +++ b/flare-cli/src/cluster.rs @@ -94,7 +94,7 @@ fn open( fn connected(transport: &RoceTransport) -> String { let topology = transport.topology(); format!( - "{} rails per {}{}{}: {}", + "{} rails per {}{}: {}", topology.rails, match topology.shape { Shape::Mesh => "peer", @@ -105,11 +105,6 @@ fn connected(transport: &RoceTransport) -> String { Links::All => "", Links::Shared => ", switch only", }, - if topology.relay_plan.is_some() { - ", all-gather relay" - } else { - "" - }, topology.peer_routes().join("; ") ) } diff --git a/flare-cli/src/doctor/spark.rs b/flare-cli/src/doctor/spark.rs index e3e14fbf1..61cbe98ff 100644 --- a/flare-cli/src/doctor/spark.rs +++ b/flare-cli/src/doctor/spark.rs @@ -180,14 +180,14 @@ fn inspect( mtu, }); } - if !ready.is_empty() { + if let Some((first_ready, rest_ready)) = ready.split_first() { let listed = ready .iter() .map(Interface::describe) .collect::>() .join(", "); - let ready_gids: Vec = ready.iter().map(|port| port.gid_index).collect(); - let gid_label = format_gid_indices(&ready_gids); + let rest_gids: Vec = rest_ready.iter().map(|port| port.gid_index).collect(); + let gid_label = format_gid_indices(first_ready.gid_index, &rest_gids); let mut detail = format!( "{} of {} active CX7 devices supply IPv4 endpoints for serving at RoCEv2 GID {gid_label}: {listed}.", ready.len(), @@ -241,10 +241,15 @@ fn inspect( let reason = match fabric { Err(error) => error.to_string(), - Ok(fabric) => format!( - "discovery could not verify a local IPv4 address and prefix on a ConnectX-7 device at RoCEv2 GID {}", - format_gid_indices(&fabric.gid_indices) - ), + Ok(fabric) => { + let gid_label = match fabric.gid_indices.split_first() { + Some((&first, rest)) => format_gid_indices(first, rest), + None => format!("index {}", fabric.gid_index()), + }; + format!( + "discovery could not verify a local IPv4 address and prefix on a ConnectX-7 device at RoCEv2 GID {gid_label}" + ) + } }; Ok(result( CheckStatus::Warn, @@ -256,18 +261,18 @@ fn inspect( )) } -fn format_gid_indices(indices: &[u32]) -> String { - match indices { - [] => "index (none)".into(), - [first, rest @ ..] if rest.iter().all(|&g| g == *first) => format!("index {first}"), - _ => format!( +fn format_gid_indices(first: u32, rest: &[u32]) -> String { + if rest.iter().all(|&g| g == first) { + format!("index {first}") + } else { + format!( "indices [{}]", - indices - .iter() - .map(u32::to_string) + std::iter::once(first) + .chain(rest.iter().copied()) + .map(|g| g.to_string()) .collect::>() .join(", ") - ), + ) } } diff --git a/helios/src/execution/roce.rs b/helios/src/execution/roce.rs index 68d7232c9..b8f8dd148 100644 --- a/helios/src/execution/roce.rs +++ b/helios/src/execution/roce.rs @@ -69,7 +69,6 @@ unsafe extern "C" { routes: *const i32, n_rail: c_int, ) -> c_int; - fn roce_set_relay(c: *mut Context, plan: *const i32, n: c_int) -> c_int; fn roce_start(c: *mut Context) -> c_int; fn roce_failed(c: *mut Context) -> c_int; fn roce_error(c: *mut Context) -> *const c_char; @@ -99,38 +98,6 @@ fn peer_blobs(records: &[Vec], world: usize) -> Result> { .collect()) } -fn validate_relay_plan(shape: Shape, world: usize, rank: usize, plan: &[i32]) -> Result<()> { - if shape != Shape::Mesh { - return Err(failure("RoCE all-gather relay requires a mesh topology")); - } - if plan.len() != 2 * world { - return Err(failure(format!( - "RoCE all-gather relay plan has {} entries for {} ranks", - plan.len(), - world - ))); - } - for p in 0..world { - let via = plan[p]; - let to = plan[world + p]; - let bad_self = p == rank && (via != -1 || to != -1); - let bad_via = via != -1 - && (via < 0 - || via as usize >= world - || via as usize == rank - || via as usize == p - || plan[via as usize] != -1); - let bad_to = - to != -1 && (to < 0 || to as usize >= world || to as usize == rank || to as usize == p); - if bad_self || bad_via || bad_to { - return Err(failure(format!( - "invalid RoCE all-gather relay plan entry for rank {p}: via={via}, to={to}" - ))); - } - } - Ok(()) -} - /// One rank's connected transport. Dropping it stops the proxy and releases the HCAs; the region /// itself belongs to the core. pub struct RoceTransport { @@ -218,9 +185,6 @@ impl RoceTransport { topology.hcas.len() ))); } - if let Some(plan) = &topology.relay_plan { - validate_relay_plan(topology.shape, spec.world, spec.rank, plan)?; - } let names = topology .hcas .iter() @@ -341,16 +305,6 @@ impl RoceTransport { self.proxy_error() ))); } - if let Some(plan) = &self.topology.relay_plan { - let status = - unsafe { roce_set_relay(self.context, plan.as_ptr(), plan.len() as c_int) }; - if status != 0 { - return Err(failure(format!( - "RoCE all-gather relay setup failed: {}", - self.proxy_error() - ))); - } - } if unsafe { roce_start(self.context) } != 0 { return Err(failure(format!( "RoCE proxy thread failed to start: {}", @@ -447,7 +401,6 @@ mod tests { rails: 2, routes: vec![vec![], vec![(0, 0), (1, 1)], vec![], vec![(0, 0), (1, 1)]], direct: vec![false; 4], - relay_plan: None, shape: Shape::Ring, links: super::super::roce_fabric::Links::All, }; @@ -515,7 +468,7 @@ mod tests { #[test] fn rejects_incompatible_core_and_routes_before_modifying_region() { let (region, spec, topology) = specification(); - for case in 0..14 { + for case in 0..11 { let mut spec = spec.clone(); let mut topology = topology.clone(); match case { @@ -534,31 +487,6 @@ mod tests { 10 => { topology.gid_indices.pop(); } - 11 => { - // Relay plans are valid only on mesh topologies. - topology.relay_plan = Some(vec![-1, -1, 1, -1, -1, 3, -1, -1]); - } - 12 => { - topology.shape = Shape::Mesh; - topology.routes = vec![ - vec![], - vec![(0, 0), (1, 1)], - vec![(0, 0), (1, 1)], - vec![(0, 0), (1, 1)], - ]; - topology.relay_plan = Some(vec![-1; 6]); - } - 13 => { - topology.shape = Shape::Mesh; - topology.routes = vec![ - vec![], - vec![(0, 0), (1, 1)], - vec![(0, 0), (1, 1)], - vec![(0, 0), (1, 1)], - ]; - // Rank 0 cannot relay through itself (via == rank). - topology.relay_plan = Some(vec![-1, 0, -1, -1, -1, -1, -1, -1]); - } _ => unreachable!(), } // SAFETY: Every case fails preflight before accessing or registering the region. @@ -673,76 +601,4 @@ mod tests { ); } } - - #[test] - fn relay_plan_validation_matches_c_proxy_invariants() { - // Valid 4-rank partner-cable plan for rank 0 (partners (0,3) and (1,2)). - let valid = vec![-1, -1, 1, -1, -1, 3, -1, -1]; - validate_relay_plan(Shape::Mesh, 4, 0, &valid).unwrap(); - assert!(validate_relay_plan(Shape::Ring, 4, 0, &valid).is_err()); - assert!(validate_relay_plan(Shape::Chain, 4, 0, &valid).is_err()); - assert!(validate_relay_plan(Shape::Mesh, 4, 0, &valid[..7]).is_err()); - // Chained relay (via points to a peer that itself relays) is rejected. - let chained = vec![-1, 2, 3, -1, -1, -1, -1, -1]; - assert!(validate_relay_plan(Shape::Mesh, 4, 0, &chained).is_err()); - // Self entry must be (-1, -1). - let self_via = vec![1, -1, -1, -1, -1, -1, -1, -1]; - assert!(validate_relay_plan(Shape::Mesh, 4, 0, &self_via).is_err()); - // Forward-to-self is rejected. - let to_self = vec![-1, -1, -1, -1, -1, 0, -1, -1]; - assert!(validate_relay_plan(Shape::Mesh, 4, 0, &to_self).is_err()); - - // When a live active RDMA device is present, also verify the linked C `roce_set_relay` - // rejects an unconnected context cleanly through FFI. - let Ok(entries) = std::fs::read_dir("/sys/class/infiniband") else { - return; - }; - let mut active: Vec = entries - .flatten() - .filter_map(|entry| { - let name = entry.file_name().into_string().ok()?; - let state = std::fs::read_to_string(entry.path().join("ports/1/state")).ok()?; - state.contains("ACTIVE").then_some(name) - }) - .collect(); - active.sort(); - let Some(hca) = active.first() else { - return; - }; - let (mut region, spec, _) = specification(); - let hca_name = CString::new(hca.as_str()).unwrap(); - let pointers = [hca_name.as_ptr()]; - let gids = [0 as c_int]; - let mut message = [0 as c_char; 512]; - if unsafe { roce_ensure_libibverbs(message.as_mut_ptr(), message.len() as u64) } != 0 { - return; - } - // SAFETY: `region` is live for the duration of `ctx` and `roce_destroy` runs before return. - let ctx = unsafe { - roce_create_with_gids( - spec.world as c_int, - spec.rank as c_int, - pointers.as_ptr(), - 1, - gids.as_ptr(), - 0, - 1, - region.as_mut_ptr().cast(), - spec.region_bytes, - spec.slot_bytes, - spec.pipe_bytes, - spec.varlen_bytes, - message.as_mut_ptr(), - message.len() as u64, - ) - }; - if ctx.is_null() { - return; - } - let status = unsafe { roce_set_relay(ctx, valid.as_ptr(), valid.len() as c_int) }; - assert_ne!(status, 0); - let err = unsafe { CStr::from_ptr(roce_error(ctx)) }.to_string_lossy(); - assert!(err.contains("connected mesh transport"), "{err}"); - unsafe { roce_destroy(ctx) }; - } } diff --git a/helios/src/execution/roce_fabric.rs b/helios/src/execution/roce_fabric.rs index 99b37866e..997bd71cb 100644 --- a/helios/src/execution/roce_fabric.rs +++ b/helios/src/execution/roce_fabric.rs @@ -315,9 +315,6 @@ pub struct Topology { /// devices that are LLDP neighbors, or, with three or more ranks, a subnet held by fewer ranks /// than the world. It does not verify that the cable carries traffic. pub direct: Vec, - /// All-gather relay plan (`2 * world` entries: `via` then `forward`) for `roce_set_relay`, - /// present on mesh topologies whose ranks form mutual direct-cable pairs. - pub relay_plan: Option>, pub shape: Shape, pub links: Links, } @@ -973,93 +970,6 @@ fn direct_peers(endpoints: &[Vec], rank: usize, routes: &[Vec<(u32, u3 .collect() } -/// Per rank, its only peer whose every mesh rail rides a point-to-point direct cable (devices -/// that are LLDP neighbors, or a subnet held by those two ranks alone), else `None`. With fewer -/// than three ranks every subnet joins both, so no rank has a cable partner for relay. -pub fn partners( - endpoints: &[Vec], - rails: usize, - links: Links, -) -> Result>> { - let world = endpoints.len(); - if world < 3 || links == Links::Shared { - return Ok(vec![None; world]); - } - let planner = Planner::new(endpoints, rails, links)?; - let mut out = Vec::with_capacity(world); - for rank in 0..world { - let mut direct = Vec::new(); - for peer in 0..world { - if peer == rank { - continue; - } - let chosen = planner.peer(rank, peer)?; - let cable = !chosen.is_empty() - && chosen.iter().all(|&(local, remote)| { - let x = &endpoints[rank][local as usize]; - let y = &endpoints[peer][remote as usize]; - lldp_adjacent(x, y) - || x.network() - .is_some_and(|network| planner.breadths[&network] == 2) - }); - if cable { - direct.push(peer); - } - } - out.push((direct.len() == 1).then(|| direct[0])); - } - Ok(out) -} - -/// The all-gather relay plan of `rank` for `roce_set_relay`, or `None` unless `world >= 4` is even -/// and the ranks form mutual direct-cable pairs with no rank left out. -/// -/// The returned `2 * world` entries hold `via` (the rank forwarding `rank`'s all-gather chunks to -/// peer `p`, or `-1` when sent directly) followed by `forward` (the rank to which `rank` forwards -/// source `s`'s chunks, or `-1` when none). Every rank derives the same pairing from the shared -/// endpoint list. -pub fn relay_plan( - endpoints: &[Vec], - rank: usize, - rails: usize, - links: Links, -) -> Result>> { - let world = endpoints.len(); - if rank >= world { - return Err(failure("invalid RoCE relay plan request")); - } - if world < 4 || world % 2 != 0 || links == Links::Shared { - return Ok(None); - } - let mates = partners(endpoints, rails, links)?; - let mut paired = Vec::with_capacity(world); - for (r, mate) in mates.iter().enumerate() { - let Some(m) = *mate else { - return Ok(None); - }; - if mates.get(m).copied().flatten() != Some(r) { - return Ok(None); - } - paired.push(m); - } - let side: Vec = (0..world).map(|r| u8::from(r > paired[r])).collect(); - let mate = paired[rank]; - let mut plan = vec![-1i32; 2 * world]; - for peer in 0..world { - if peer == rank || peer == mate { - continue; - } - if side[peer] != side[rank] { - // Peer's partner is on our side and receives our chunks directly. - plan[peer] = paired[peer] as i32; - } else { - // Peer is on our side: we receive its chunks and pass them to our partner. - plan[world + peer] = mate as i32; - } - } - Ok(Some(plan)) -} - /// The routes of `shape` for `rank`: a mesh routes to every rank; a ring or chain routes only to /// the ranks `shape` links, and the native proxy forwards writes to the others. The same plan works /// over a switch while keeping unlinked QPs unconnected. Routes are planned over every rank's @@ -1125,18 +1035,12 @@ impl Fabric { } let rails = endpoints.iter().map(Vec::len).min().unwrap().min(MAX_RAILS); let routes = plan_shape_routes(endpoints, rank, rails, shape, links)?; - let relay_plan = if shape == Shape::Mesh { - relay_plan(endpoints, rank, rails, links)? - } else { - None - }; Ok(Topology { hcas: self.endpoints.iter().map(|e| e.name.clone()).collect(), gid_indices: self.gid_indices.clone(), traffic_class: self.traffic_class, rails, direct: direct_peers(endpoints, rank, &routes), - relay_plan, routes, shape, links, @@ -2309,158 +2213,4 @@ mod tests { } } } - - #[test] - fn relay_plan_delivers_every_shard_once_and_forwards_only_over_cables() { - let cases: Vec<(&str, Vec>, Vec)> = vec![ - ("four-ranks", switch_with_partner_cables(), PARTNER.to_vec()), - ( - "four-ranks-lldp", - with_lldp(&switch_with_partner_cables(), &PARTNER), - PARTNER.to_vec(), - ), - ( - "eight-ranks", - paired_switch(4), - (0..8).map(|r| r ^ 1).collect(), - ), - ]; - for (label, endpoints, mates) in cases { - let world = endpoints.len(); - assert_eq!( - partners(&endpoints, 2, Links::All).unwrap(), - mates.iter().copied().map(Some).collect::>(), - "{label}" - ); - let plans: Vec> = (0..world) - .map(|rank| { - relay_plan(&endpoints, rank, 2, Links::All) - .unwrap() - .unwrap_or_else(|| panic!("{label}: rank {rank} missing relay plan")) - }) - .collect(); - let mut writers: std::collections::BTreeMap<(usize, usize), Vec> = - std::collections::BTreeMap::new(); - for source in 0..world { - for peer in 0..world { - if peer != source && plans[source][peer] == -1 { - writers.entry((source, peer)).or_default().push(source); - } - } - } - for forwarder in 0..world { - for source in 0..world { - let target = plans[forwarder][world + source]; - if target != -1 { - assert_eq!( - writers.get(&(source, forwarder)), - Some(&vec![source]), - "{label}: forwarder {forwarder} must receive source {source} directly" - ); - writers - .entry((source, target as usize)) - .or_default() - .push(forwarder); - assert_eq!( - target as usize, mates[forwarder], - "{label}: rank {forwarder} must forward only to partner" - ); - } - } - } - for source in 0..world { - for peer in 0..world { - if peer == source { - continue; - } - let assigned = &writers[&(source, peer)]; - assert_eq!( - assigned.len(), - 1, - "{label}: ({source}, {peer}) -> {assigned:?}" - ); - let writer = assigned[0]; - if writer != source { - assert_eq!(writer as i32, plans[source][peer], "{label}"); - assert_eq!(writer, mates[peer], "{label}"); - } - } - } - } - // With two pairs, each rank sends two of its three all-gather shards over its cable. - let four = switch_with_partner_cables(); - for rank in 0..4 { - let plan = relay_plan(&four, rank, 2, Links::All).unwrap().unwrap(); - let direct: Vec = (0..4).filter(|&p| p != rank && plan[p] == -1).collect(); - let forwarded: Vec = plan[4..] - .iter() - .filter(|&&t| t != -1) - .map(|&t| t as usize) - .collect(); - let sends: Vec = direct.into_iter().chain(forwarded).collect(); - assert_eq!(sends.len(), 3); - assert_eq!(sends.iter().filter(|&&p| p == PARTNER[rank]).count(), 2); - } - } - - #[test] - fn relay_plan_supports_lldp_link_local_cables_and_disables_for_switch_only_or_ring() { - let mut endpoints = with_lldp(&switch_with_partner_cables(), &PARTNER); - // Replace partner-cable subnets with shared link-local space so only LLDP marks cables. - for (rank, devices) in endpoints.iter_mut().enumerate() { - for e in devices.iter_mut() { - if DIRECT_DEVICES.contains(&e.name.as_str()) { - e.ipv4 = Some((Ipv4Addr::new(169, 254, 1, 11 + rank as u8), 16)); - } - } - } - let fabric = Fabric { - gid_indices: vec![3; endpoints[1].len()], - traffic_class: 0, - endpoints: endpoints[1].clone(), - }; - let mesh = fabric - .topology(&endpoints, 1, Shape::Mesh, Links::All) - .unwrap(); - assert_eq!(mesh.relay_plan, Some(vec![-1, -1, -1, 0, 2, -1, -1, -1])); - let switch_only = fabric - .topology(&endpoints, 1, Shape::Mesh, Links::Shared) - .unwrap(); - assert_eq!(switch_only.relay_plan, None); - let ring = fabric - .topology(&endpoints, 1, Shape::Ring, Links::All) - .unwrap(); - assert_eq!(ring.relay_plan, None); - let chain = fabric - .topology(&endpoints, 1, Shape::Chain, Links::All) - .unwrap(); - assert_eq!(chain.relay_plan, None); - - // A missing partner cable, purely switched fabric, or 2-rank group produces no relay plan. - let mut down = switch_with_partner_cables(); - down[2].retain(|e| SWITCH_DEVICES.contains(&e.name.as_str())); - assert_eq!( - partners(&down, 2, Links::All).unwrap(), - vec![Some(3), None, None, Some(0)] - ); - for rank in 0..4 { - assert_eq!(relay_plan(&down, rank, 2, Links::All).unwrap(), None); - } - let switched: Vec> = (0..4) - .map(|r| { - vec![ - spark("roceP2p1s0f0", &format!("10.200.0.{}/24", 11 + r)), - spark("rocep1s0f0", &format!("10.200.1.{}/24", 11 + r)), - ] - }) - .collect(); - assert_eq!(partners(&switched, 2, Links::All).unwrap(), vec![None; 4]); - assert_eq!(relay_plan(&switched, 0, 2, Links::All).unwrap(), None); - let pair = vec![ - switch_with_partner_cables()[0].clone(), - switch_with_partner_cables()[3].clone(), - ]; - assert_eq!(partners(&pair, 2, Links::All).unwrap(), vec![None, None]); - assert_eq!(relay_plan(&pair, 0, 2, Links::All).unwrap(), None); - } } diff --git a/ignition/preparation/collectives.py b/ignition/preparation/collectives.py index 9a5a286a5..321c121d0 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -80,21 +80,25 @@ def create_roce_runtime(group, device, *, max_tokens, pipe_tokens, hidden_size, # Each host uses the HCAs and per-device GID indices native serving discovers for it. import inspect - devices = flare_heliopause.roce_devices() + roce_devices = getattr(flare_heliopause, "roce_devices", None) gid_kwargs: dict[str, object] - if "gid_indices" in inspect.signature(roce.AllReduce.__init__).parameters: - gid_kwargs = { - "hca_names": [name for name, _ in devices], - "gid_indices": [gid for _, gid in devices], - } + if roce_devices is None: + gid_kwargs = {"gid_index": flare_heliopause.roce_gid_index()} else: - distinct = sorted({gid for _, gid in devices}) - if len(distinct) > 1: - raise RuntimeError( - f"host RoCE devices use distinct GID indices {distinct} ({devices}); " - "update the pinned FlashInfer dependency to a revision supporting per-HCA gid_indices" - ) - gid_kwargs = {"gid_index": distinct[0] if distinct else flare_heliopause.roce_gid_index()} + devices = roce_devices() + if "gid_indices" in inspect.signature(roce.AllReduce.__init__).parameters: + gid_kwargs = { + "hca_names": [name for name, _ in devices], + "gid_indices": [gid for _, gid in devices], + } + else: + distinct = sorted({gid for _, gid in devices}) + if len(distinct) > 1: + raise RuntimeError( + f"host RoCE devices use distinct GID indices {distinct} ({devices}); " + "update the pinned FlashInfer dependency to a revision supporting per-HCA gid_indices" + ) + gid_kwargs = {"gid_index": distinct[0] if distinct else flare_heliopause.roce_gid_index()} runtime = roce.AllReduce(exchange_group=group, device=device, max_size=nbytes, max_gather_bytes=gather_bytes, pipe_bytes=pipe_bytes, region_allocator=region, **gid_kwargs, diff --git a/pyproject.toml b/pyproject.toml index f1f2992a3..351625b34 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -44,7 +44,7 @@ explicit = true torch = { index = "pytorch-cu132" } torchvision = { index = "pytorch-cu132" } flare-heliopause = { path = "heliopause" } -flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", rev = "524799c47fca54229c15b6db12261171854a7b7d" } +flashinfer-python = { git = "https://github.com/local-inference-lab/flashinfer.git", rev = "1441ce862ffbc9d8550fdda7ad90e97ca04f4b8e" } [tool.setuptools.packages.find] include = ["ignition*"] diff --git a/tests/preparation/test_roce_proxy_parity.py b/tests/preparation/test_roce_proxy_parity.py index be93a5bb8..04a0a28ce 100644 --- a/tests/preparation/test_roce_proxy_parity.py +++ b/tests/preparation/test_roce_proxy_parity.py @@ -129,3 +129,15 @@ def __init__(self, *, gid_index=None, **kwargs): gather_bytes=128, ) assert recorded["legacy_gid_index"] == 3 + + # External test stubs exposing only `roce_gid_index` remain compatible. + monkeypatch.setitem(sys.modules, "flare_heliopause", SimpleNamespace(roce_gid_index=lambda: 5)) + collectives.create_roce_runtime( + group=None, + device="cpu", + max_tokens=16, + pipe_tokens=16, + hidden_size=128, + gather_bytes=128, + ) + assert recorded["legacy_gid_index"] == 5