diff --git a/docs/cli-design.md b/docs/cli-design.md index a1de8c84d..99c966b60 100644 --- a/docs/cli-design.md +++ b/docs/cli-design.md @@ -1693,7 +1693,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/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..d8ec5abd4 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"))] @@ -721,6 +744,7 @@ mod binding_tests { } assert!(module.hasattr("GraphExecutor").unwrap()); assert!(module.hasattr("current_context").unwrap()); + assert!(module.hasattr("roce_devices").unwrap()); assert_eq!( module.hasattr("Server").unwrap(), cfg!(all(feature = "server", feature = "qualification")) diff --git a/helios/native/roce_proxy.c b/helios/native/roce_proxy.c index be4a21e8d..90e278d5f 100644 --- a/helios/native/roce_proxy.c +++ b/helios/native/roce_proxy.c @@ -256,6 +256,7 @@ typedef struct { uint16_t lid; enum ibv_mtu mtu; uint32_t max_inline; + int gid_index; } roce_hca_t; typedef struct { @@ -264,7 +265,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 +420,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 +457,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 +528,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 +555,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 +573,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 +582,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) { @@ -651,7 +671,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; diff --git a/helios/src/execution/roce.rs b/helios/src/execution/roce.rs index 9b29e9c44..7c10eab8f 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)]], @@ -456,7 +464,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 +480,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 +532,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..51ce73560 100644 --- a/ignition/preparation/collectives.py +++ b/ignition/preparation/collectives.py @@ -77,10 +77,36 @@ 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. Pass + # aligned `hca_names` and `gid_indices` when the installed b12x RoCE runtime supports them + # (local-inference-lab/flashinfer#209). On older b12x builds, allow a scalar `gid_index` only + # when all discovered HCAs share one GID index; fail loudly on mixed-index hosts rather than + # silently preparing with only the first HCA's GID index. + 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: + unique_gids = {gid for _, gid in devices} + if len(unique_gids) > 1: + discovered = ", ".join(f"{name}=GID {gid}" for name, gid in devices) + raise RuntimeError( + f"Host RoCE devices have distinct RoCEv2 IPv4 GID indices ({discovered}), " + "but the installed b12x RoCE runtime does not accept per-HCA `gid_indices`. " + "Update flashinfer-python to a build with per-HCA GID support " + "(local-inference-lab/flashinfer#209)." + ) + gid_kwargs = { + "gid_index": devices[0][1] if devices 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/tests/preparation/test_roce_collectives.py b/tests/preparation/test_roce_collectives.py new file mode 100644 index 000000000..e32edd29a --- /dev/null +++ b/tests/preparation/test_roce_collectives.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-FileCopyrightText: Copyright (c) 2026 Flare community contributors +# SPDX-License-Identifier: Apache-2.0 + +"""RoCE preparation passes per-HCA GID indices and fails loudly when legacy b12x cannot.""" + +import sys +from types import ModuleType, SimpleNamespace + +import pytest + +from ignition.preparation.collectives import create_roce_runtime + + +def _install_stubs(monkeypatch, *, devices, all_reduce_cls): + heliopause = ModuleType("flare_heliopause") + heliopause.roce_devices = lambda: list(devices) + heliopause.roce_gid_index = lambda: devices[0][1] + roce_mod = ModuleType("b12x.comm.roce") + roce_mod.AllReduce = all_reduce_cls + comm_mod = ModuleType("b12x.comm") + comm_mod.roce = roce_mod + b12x_mod = ModuleType("b12x") + b12x_mod.comm = comm_mod + monkeypatch.setitem(sys.modules, "flare_heliopause", heliopause) + monkeypatch.setitem(sys.modules, "b12x", b12x_mod) + monkeypatch.setitem(sys.modules, "b12x.comm", comm_mod) + monkeypatch.setitem(sys.modules, "b12x.comm.roce", roce_mod) + + +def test_roce_runtime_passes_per_hca_gids_when_supported(monkeypatch): + seen = {} + + class ModernAllReduce: + def __init__(self, *, exchange_group, device, max_size, max_gather_bytes, pipe_bytes, + region_allocator, hca_names=None, gid_indices=None, ring=False, **extra): + seen["hca_names"] = hca_names + seen["gid_indices"] = gid_indices + + _install_stubs( + monkeypatch, + devices=[("roceP2p1s0f0", 3), ("rocep1s0f0", 5)], + all_reduce_cls=ModernAllReduce, + ) + runtime = create_roce_runtime( + group=SimpleNamespace(), device="cuda:0", + max_tokens=16, pipe_tokens=16, hidden_size=128, gather_bytes=128, + ) + assert isinstance(runtime, ModernAllReduce) + assert seen == {"hca_names": ["roceP2p1s0f0", "rocep1s0f0"], "gid_indices": [3, 5]} + + +def test_roce_runtime_legacy_b12x_allows_uniform_gids(monkeypatch): + seen = {} + + class LegacyAllReduce: + def __init__(self, *, exchange_group, device, max_size, max_gather_bytes, pipe_bytes, + region_allocator, gid_index=3, ring=False, **extra): + seen["gid_index"] = gid_index + + _install_stubs( + monkeypatch, + devices=[("roceP2p1s0f0", 5), ("rocep1s0f0", 5)], + all_reduce_cls=LegacyAllReduce, + ) + runtime = create_roce_runtime( + group=SimpleNamespace(), device="cuda:0", + max_tokens=16, pipe_tokens=16, hidden_size=128, gather_bytes=128, + ) + assert isinstance(runtime, LegacyAllReduce) + assert seen == {"gid_index": 5} + + +def test_roce_runtime_legacy_b12x_rejects_mixed_per_hca_gids(monkeypatch): + class LegacyAllReduce: + def __init__(self, *, exchange_group, device, max_size, max_gather_bytes, pipe_bytes, + region_allocator, gid_index=3, ring=False, **extra): + raise AssertionError("AllReduce should not be constructed for mixed GIDs on legacy b12x") + + _install_stubs( + monkeypatch, + devices=[("roceP2p1s0f0", 3), ("rocep1s0f0", 5)], + all_reduce_cls=LegacyAllReduce, + ) + with pytest.raises(RuntimeError, match="distinct RoCEv2 IPv4 GID indices"): + create_roce_runtime( + group=SimpleNamespace(), device="cuda:0", + max_tokens=16, pipe_tokens=16, hidden_size=128, gather_bytes=128, + )