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/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..52f337eda 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,14 @@ 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. 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 @@ -415,9 +416,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. | +| [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 and relayed writes, progresses mailboxes and acknowledgments, and releases two-shot send buffers. | +| [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/doctor/spark.rs b/flare-cli/src/doctor/spark.rs index 16a9cb2a1..61cbe98ff 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,22 +174,24 @@ fn inspect( ready.push(Interface { device: &endpoint.name, interface, + gid_index, address, prefix, 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 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 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) { @@ -235,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 index {}", - fabric.gid_index - ), + 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, @@ -250,9 +261,25 @@ fn inspect( )) } +fn format_gid_indices(first: u32, rest: &[u32]) -> String { + if rest.iter().all(|&g| g == first) { + format!("index {first}") + } else { + format!( + "indices [{}]", + std::iter::once(first) + .chain(rest.iter().copied()) + .map(|g| g.to_string()) + .collect::>() + .join(", ") + ) + } +} + struct Interface<'a> { device: &'a str, interface: String, + gid_index: u32, address: Ipv4Addr, prefix: u8, mtu: Option, @@ -491,6 +518,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 +526,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 +550,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..b8f8dd148 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, @@ -178,6 +178,13 @@ 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() + ))); + } let names = topology .hcas .iter() @@ -196,13 +203,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, @@ -388,7 +396,7 @@ 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)]], @@ -433,6 +441,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 +451,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 +468,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..11 { let mut spec = spec.clone(); let mut topology = topology.clone(); match case { @@ -472,6 +484,9 @@ 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(); + } _ => unreachable!(), } // SAFETY: Every case fails preflight before accessing or registering the region. @@ -521,4 +536,69 @@ 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}" + ); + } + } } diff --git a/helios/src/execution/roce_fabric.rs b/helios/src/execution/roce_fabric.rs index 63cb04e7d..997bd71cb 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>, @@ -377,10 +378,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 +403,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 +466,7 @@ pub fn discover_in( }) .collect(); Ok(Fabric { - gid_index, + gid_indices, traffic_class: 0, endpoints, }) @@ -999,6 +1001,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,11 +1026,18 @@ 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)?; 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), @@ -1121,7 +1143,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 +1177,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 +1597,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 +1711,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 +1862,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")], }; diff --git a/ignition/preparation/collectives.py b/ignition/preparation/collectives.py index 76c165770..321c121d0 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -77,10 +77,31 @@ 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 + + roce_devices = getattr(flare_heliopause, "roce_devices", None) + gid_kwargs: dict[str, object] + if roce_devices is None: + gid_kwargs = {"gid_index": flare_heliopause.roce_gid_index()} + else: + 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_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: diff --git a/pyproject.toml b/pyproject.toml index e03a2529c..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 = "5a8ceed80ccc58e11a4d49ccc910f52967699c09" } +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 new file mode 100644 index 000000000..04a0a28ce --- /dev/null +++ b/tests/preparation/test_roce_proxy_parity.py @@ -0,0 +1,143 @@ +# 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 + + # 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