nexar 0.1.2

Distributed runtime with QUIC transport, stream-multiplexed messaging, and built-in collectives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use nexar::client::NexarClient;
use nexar::cluster::sparse::{
    TopologyStrategy, build_neighbors, build_routing_table, build_spanning_tree,
};
use nexar::config::NexarConfig;
use nexar::device::CpuAdapter;
use nexar::types::{DataType, ReduceOp};
use std::sync::Arc;

fn kregular_config(degree: usize) -> NexarConfig {
    NexarConfig {
        topology: TopologyStrategy::KRegular { degree },
        enable_tcp_bulk_sidecar: false,
        ..NexarConfig::default()
    }
}

fn hypercube_config() -> NexarConfig {
    NexarConfig {
        topology: TopologyStrategy::Hypercube,
        enable_tcp_bulk_sidecar: false,
        ..NexarConfig::default()
    }
}

// --- Unit tests for topology ---

#[test]
fn test_kregular_neighbors() {
    // KRegular{6} with 16 nodes: each rank has exactly 6 neighbors (±1, ±2, ±3).
    for rank in 0..16u32 {
        let neighbors = build_neighbors(&TopologyStrategy::KRegular { degree: 6 }, rank, 16);
        assert_eq!(
            neighbors.len(),
            6,
            "rank {rank} has {} neighbors, expected 6",
            neighbors.len()
        );
        // Verify ±1, ±2, ±3
        for d in 1..=3u32 {
            assert!(neighbors.contains(&((rank + d) % 16)));
            assert!(neighbors.contains(&((rank + 16 - d) % 16)));
        }
    }
}

#[test]
fn test_hypercube_neighbors() {
    // Hypercube with 16 nodes: each rank has 4 neighbors (log2(16) = 4).
    for rank in 0..16u32 {
        let neighbors = build_neighbors(&TopologyStrategy::Hypercube, rank, 16);
        assert_eq!(
            neighbors.len(),
            4,
            "rank {rank} has {} neighbors, expected 4",
            neighbors.len()
        );
        // Each neighbor differs in exactly one bit.
        for &n in &neighbors {
            let diff = rank ^ n;
            assert_eq!(
                diff.count_ones(),
                1,
                "rank {rank} neighbor {n} differs in {} bits",
                diff.count_ones()
            );
        }
    }
}

#[test]
fn test_routing_table_complete() {
    // Every rank should have a route to every other rank.
    let strategy = TopologyStrategy::KRegular { degree: 6 };
    for rank in 0..16u32 {
        let rt = build_routing_table(&strategy, rank, 16);
        for dest in 0..16u32 {
            if dest == rank {
                continue;
            }
            assert!(
                rt.route(dest).is_some(),
                "rank {rank} has no route to {dest}"
            );
        }
    }
}

#[test]
fn test_spanning_tree_covers_all() {
    let tree = build_spanning_tree(&TopologyStrategy::KRegular { degree: 6 }, 0, 16);
    assert_eq!(tree.children.len(), 16, "tree should contain all 16 ranks");
    // Root has no parent.
    assert!(!tree.parent.contains_key(&0));
    // All other ranks have a parent.
    for r in 1..16u32 {
        assert!(tree.parent.contains_key(&r), "rank {r} has no parent");
    }
    // Every parent->child edge should be between direct neighbors.
    let strategy = TopologyStrategy::KRegular { degree: 6 };
    for (&parent, children) in &tree.children {
        let parent_neighbors = build_neighbors(&strategy, parent, 16);
        for &child in children {
            assert!(
                parent_neighbors.contains(&child),
                "tree edge {parent}->{child} is not a direct connection"
            );
        }
    }
}

// --- Integration tests ---

#[tokio::test]
async fn test_connection_count() {
    // Verify each node has exactly K connections (not N-1).
    let adapter = Arc::new(CpuAdapter::new());
    let config = kregular_config(6);
    let clients = NexarClient::bootstrap_local_with_config(16, adapter, config)
        .await
        .unwrap();

    for client in &clients {
        let mut direct_count = 0;
        for r in 0..16u32 {
            if r != client.rank() && client.has_direct_peer(r) {
                direct_count += 1;
            }
        }
        assert_eq!(
            direct_count,
            6,
            "rank {} has {} direct peers, expected 6",
            client.rank(),
            direct_count
        );
    }
}

#[tokio::test]
async fn test_kregular_relay_send_recv() {
    // 16 nodes, KRegular{6}: point-to-point between non-adjacent ranks.
    let adapter = Arc::new(CpuAdapter::new());
    let config = kregular_config(6);
    let clients = NexarClient::bootstrap_local_with_config(16, adapter, config)
        .await
        .unwrap();

    // Rank 0 and rank 8 are NOT direct neighbors in KRegular{6} (only ±1..±3).
    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();
    let c0 = Arc::clone(&clients[0]);
    let c8 = Arc::clone(&clients[8]);

    let send_data: Vec<f32> = vec![3.125, 2.71, 1.41, 1.73];
    let mut recv_buf: Vec<f32> = vec![0.0; 4];
    let size = send_data.len() * std::mem::size_of::<f32>();

    let send_ptr = send_data.as_ptr() as u64;
    let recv_ptr = recv_buf.as_mut_ptr() as u64;

    let send_task = tokio::spawn(async move { unsafe { c0.send(send_ptr, size, 8, 99).await } });
    let recv_task = tokio::spawn(async move { unsafe { c8.recv(recv_ptr, size, 0, 99).await } });

    send_task.await.unwrap().unwrap();
    recv_task.await.unwrap().unwrap();
    assert_eq!(recv_buf, vec![3.125, 2.71, 1.41, 1.73]);
}

#[tokio::test]
async fn test_kregular_allreduce() {
    // 16 nodes, KRegular{6}: ring allreduce completes correctly.
    run_allreduce_test(16, Some(kregular_config(6))).await;
}

#[tokio::test]
async fn test_kregular_broadcast() {
    // 16 nodes, KRegular{6}: broadcast from root reaches all ranks.
    let adapter = Arc::new(CpuAdapter::new());
    let clients = NexarClient::bootstrap_local_with_config(16, adapter, kregular_config(6))
        .await
        .unwrap();

    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();

    let mut handles = Vec::new();
    for client in &clients {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            let count = 8usize;
            let mut data: Vec<f32> = if client.rank() == 0 {
                vec![42.0; count]
            } else {
                vec![0.0; count]
            };
            let ptr = data.as_mut_ptr() as u64;
            unsafe {
                client
                    .broadcast(ptr, count, DataType::F32, 0)
                    .await
                    .unwrap();
            }
            data
        }));
    }

    for handle in handles {
        let result = handle.await.unwrap();
        for &v in &result {
            assert!((v - 42.0).abs() < 1e-6, "expected 42.0, got {v}");
        }
    }
}

#[tokio::test]
async fn test_kregular_barrier() {
    // 16 nodes, KRegular{6}: barrier completes.
    let adapter = Arc::new(CpuAdapter::new());
    let config = kregular_config(6);
    let clients = NexarClient::bootstrap_local_with_config(16, adapter, config)
        .await
        .unwrap();

    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();

    let mut handles = Vec::new();
    for client in &clients {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            client.barrier().await.unwrap();
        }));
    }

    for handle in handles {
        handle.await.unwrap();
    }
}

#[tokio::test]
async fn test_hypercube_allreduce() {
    // 16 nodes, Hypercube: allreduce completes correctly.
    let config = hypercube_config();
    run_allreduce_test(16, Some(config)).await;
}

// --- Allreduce regression tests (various sizes and algorithms) ---

/// Helper: run allreduce with `world_size` nodes and verify all elements equal the expected sum.
async fn run_allreduce_test(world_size: u32, config: Option<NexarConfig>) {
    let adapter = Arc::new(CpuAdapter::new());
    let clients = if let Some(cfg) = config {
        NexarClient::bootstrap_local_with_config(world_size, adapter, cfg)
            .await
            .unwrap()
    } else {
        NexarClient::bootstrap_local(world_size, adapter)
            .await
            .unwrap()
    };

    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();
    let count = world_size.max(8) as usize;
    let expected_sum: f32 = (0..world_size).map(|r| r as f32 + 1.0).sum();

    let mut handles = Vec::new();
    for (i, client) in clients.iter().enumerate() {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            let val = (i as f32) + 1.0;
            let mut data = vec![val; count];
            let ptr = data.as_mut_ptr() as u64;
            unsafe {
                client
                    .all_reduce(ptr, count, DataType::F32, ReduceOp::Sum)
                    .await
                    .unwrap();
            }
            data
        }));
    }

    for (rank, handle) in handles.into_iter().enumerate() {
        let result = handle.await.unwrap();
        for (i, &v) in result.iter().enumerate() {
            assert!(
                (v - expected_sum).abs() < 1e-3,
                "world={world_size} rank {rank} elem {i}: expected {expected_sum}, got {v}"
            );
        }
    }
}

fn no_tcp_config(ring_max_world: usize) -> NexarConfig {
    NexarConfig {
        enable_tcp_bulk_sidecar: false,
        ring_max_world,
        ..NexarConfig::default()
    }
}

#[tokio::test]
async fn test_halving_doubling_5nodes() {
    // Non-power-of-2: exercises excess rank handling.
    run_allreduce_test(5, Some(no_tcp_config(0))).await;
}

#[tokio::test]
async fn test_halving_doubling_8nodes() {
    // Power-of-2: straightforward halving-doubling.
    run_allreduce_test(8, Some(no_tcp_config(0))).await;
}

#[tokio::test]
async fn test_ring_7nodes_no_tcp() {
    // Odd count, QUIC-only (no TCP sidecar): regression for connection swapping bug.
    run_allreduce_test(7, Some(no_tcp_config(8))).await;
}

// --- Sparse topology + reduce-scatter tests ---

#[tokio::test]
async fn test_kregular_reduce_scatter() {
    // 16 nodes, KRegular{6}: reduce-scatter via relay routing.
    let adapter = Arc::new(CpuAdapter::new());
    let clients = NexarClient::bootstrap_local_with_config(16, adapter, kregular_config(6))
        .await
        .unwrap();

    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();
    let world = 16usize;
    let count_per_rank = 4usize;
    let total = count_per_rank * world;

    let mut handles = Vec::new();
    for client in &clients {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            let rank = client.rank() as usize;
            // Each rank fills send buffer with (rank+1) at every position.
            let val = (rank as f32) + 1.0;
            let mut send_buf = vec![val; total];
            let mut recv_buf = vec![0.0f32; count_per_rank];
            let send_ptr = send_buf.as_mut_ptr() as u64;
            let recv_ptr = recv_buf.as_mut_ptr() as u64;
            unsafe {
                client
                    .reduce_scatter(
                        send_ptr,
                        recv_ptr,
                        count_per_rank,
                        DataType::F32,
                        ReduceOp::Sum,
                    )
                    .await
                    .unwrap();
            }
            recv_buf
        }));
    }

    let expected_sum: f32 = (0..world).map(|r| r as f32 + 1.0).sum();
    for handle in handles {
        let result = handle.await.unwrap();
        for &v in &result {
            assert!(
                (v - expected_sum).abs() < 1e-3,
                "expected {expected_sum}, got {v}"
            );
        }
    }
}

#[tokio::test]
async fn test_hypercube_broadcast() {
    // 8 nodes, Hypercube: broadcast from root=3 reaches all ranks.
    let adapter = Arc::new(CpuAdapter::new());
    let clients = NexarClient::bootstrap_local_with_config(8, adapter, hypercube_config())
        .await
        .unwrap();

    let clients: Vec<Arc<NexarClient>> = clients.into_iter().map(Arc::new).collect();
    let root = 3u32;

    let mut handles = Vec::new();
    for client in &clients {
        let client = Arc::clone(client);
        handles.push(tokio::spawn(async move {
            let count = 8usize;
            let mut data: Vec<f32> = if client.rank() == root {
                vec![99.5; count]
            } else {
                vec![0.0; count]
            };
            let ptr = data.as_mut_ptr() as u64;
            unsafe {
                client
                    .broadcast(ptr, count, DataType::F32, root)
                    .await
                    .unwrap();
            }
            data
        }));
    }

    for handle in handles {
        let result = handle.await.unwrap();
        for &v in &result {
            assert!((v - 99.5).abs() < 1e-6, "expected 99.5, got {v}");
        }
    }
}