Skip to main content

rlx_driver/
symmetric.rs

1// RLX — versatile ML compiler + runtime.
2// Copyright (C) 2026 Eugene Hauptmann, Nataliya Kosmyna.
3//
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, version 3.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License
14// along with this program. If not, see <https://www.gnu.org/licenses/>.
15
16//! Symmetric-memory primitives for collective ops (plan #49).
17//!
18//! Borrowed from MAX's `kernels/src/shmem/{_nvshmem, _rocshmem,
19//! _mpi, shmem_buffer, ep_comm}.mojo`. Symmetric heaps are the
20//! standard abstraction for multi-device collective comm: every
21//! rank allocates the same logical region; addresses are
22//! identical across ranks (the physical backing differs). One
23//! rank can `put` directly into another's slot at the same
24//! offset.
25//!
26//! The Rust spelling here ships:
27//!
28//!   - [`SymmetricHeap`] — owns the per-rank physical storage.
29//!     Single-machine emulation today (one `Vec<u8>` per rank);
30//!     the trait surface ([`SymmetricTransport`]) is what a
31//!     future MPI / NVSHMEM-equivalent / process-shared-memory
32//!     impl plugs into.
33//!   - [`SymmetricBuffer`] — a `(rank, offset, len)` view.
34//!   - [`SymmetricTransport`] — the trait every transport
35//!     impl satisfies. `LocalTransport` is the in-process,
36//!     single-machine impl used by tests + collective-algo
37//!     correctness checks (plan #12).
38//!
39//! This is the foundation; #12 builds AllReduce / AllGather /
40//! ReduceScatter on top.
41
42use std::sync::{Arc, RwLock};
43
44/// Identifier for a participant in a collective. Ranks are
45/// `0..num_ranks` and stay stable for the lifetime of a
46/// transport.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
48pub struct Rank(pub u32);
49
50/// `(rank, offset, len)` view into a symmetric heap. The same
51/// `(offset, len)` pair is valid on every rank — that's what
52/// "symmetric" means.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct SymmetricBuffer {
55    pub rank: Rank,
56    pub offset: usize,
57    pub len: usize,
58}
59
60/// One-sided operation surface. `put(buf, src)` writes `src`
61/// into `buf.rank`'s memory at `buf.offset`; `get(buf, dst)`
62/// reads from `buf.rank`'s memory into `dst`. Both calls block
63/// until completion (a future async impl can return a future).
64pub trait SymmetricTransport {
65    /// How many ranks participate.
66    fn num_ranks(&self) -> u32;
67    /// This process's rank.
68    fn this_rank(&self) -> Rank;
69
70    /// Write `src` into `buf`. Errors on length mismatch.
71    fn put(&self, buf: SymmetricBuffer, src: &[u8]) -> Result<(), CollectiveError>;
72    /// Read from `buf` into `dst`. Errors on length mismatch.
73    fn get(&self, buf: SymmetricBuffer, dst: &mut [u8]) -> Result<(), CollectiveError>;
74
75    /// Block until every rank has reached this barrier. Local
76    /// emulation is a memory fence + a counter; real transports
77    /// implement their own.
78    fn barrier(&self) -> Result<(), CollectiveError>;
79}
80
81#[derive(Debug, Clone)]
82pub enum CollectiveError {
83    /// `(rank, offset, len)` walks past the heap.
84    OutOfBounds {
85        rank: Rank,
86        offset: usize,
87        len: usize,
88        heap_size: usize,
89    },
90    /// `src.len() != buf.len`.
91    LengthMismatch { expected: usize, got: usize },
92    /// Unknown rank id.
93    UnknownRank { rank: Rank, num_ranks: u32 },
94    /// Underlying transport failed (network, mmap, etc.).
95    TransportError { reason: String },
96}
97
98impl std::fmt::Display for CollectiveError {
99    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
100        match self {
101            Self::OutOfBounds {
102                rank,
103                offset,
104                len,
105                heap_size,
106            } => write!(
107                f,
108                "OOB on rank {}: offset {offset} + len {len} > heap_size {heap_size}",
109                rank.0
110            ),
111            Self::LengthMismatch { expected, got } => {
112                write!(f, "length mismatch: expected {expected}, got {got}")
113            }
114            Self::UnknownRank { rank, num_ranks } => {
115                write!(f, "unknown rank {} (have {num_ranks})", rank.0)
116            }
117            Self::TransportError { reason } => write!(f, "transport: {reason}"),
118        }
119    }
120}
121
122impl std::error::Error for CollectiveError {}
123
124/// Per-rank symmetric memory: a `Vec<u8>` per rank, all the same
125/// size. Owned by the [`LocalTransport`].
126#[derive(Debug)]
127pub struct SymmetricHeap {
128    storage: Vec<Arc<RwLock<Vec<u8>>>>,
129    pub heap_size: usize,
130}
131
132impl SymmetricHeap {
133    pub fn new(num_ranks: u32, heap_size: usize) -> Self {
134        let storage = (0..num_ranks)
135            .map(|_| Arc::new(RwLock::new(vec![0u8; heap_size])))
136            .collect();
137        Self { storage, heap_size }
138    }
139
140    pub fn num_ranks(&self) -> u32 {
141        self.storage.len() as u32
142    }
143
144    pub fn rank_view(&self, rank: Rank) -> Option<Arc<RwLock<Vec<u8>>>> {
145        self.storage.get(rank.0 as usize).cloned()
146    }
147}
148
149/// Single-machine in-process transport. All `num_ranks`
150/// "ranks" share one [`SymmetricHeap`] instance, so put / get
151/// are just locks + memcpy. Useful for unit tests and for
152/// algorithm-correctness checking of collective ops without a
153/// real cluster.
154#[derive(Debug, Clone)]
155pub struct LocalTransport {
156    heap: Arc<SymmetricHeap>,
157    me: Rank,
158    /// Shared, reusable rendezvous barrier across all ranks from the same
159    /// [`fan_out`](Self::fan_out). A real `std::sync::Barrier` (auto-reset
160    /// after every rank passes), so multi-step collectives — ring all-reduce
161    /// in particular — synchronize correctly across threads.
162    barrier: Arc<std::sync::Barrier>,
163}
164
165impl LocalTransport {
166    pub fn new(num_ranks: u32, heap_size: usize, this_rank: Rank) -> Self {
167        let heap = Arc::new(SymmetricHeap::new(num_ranks, heap_size));
168        let barrier = Arc::new(std::sync::Barrier::new(num_ranks as usize));
169        Self::with_heap(heap, this_rank, barrier)
170    }
171
172    /// Construct multiple `LocalTransport`s sharing one heap **and one
173    /// barrier** — `Vec` of length `num_ranks`, each with its own `me`.
174    /// Drive each on its own thread for multi-rank collective tests.
175    pub fn fan_out(num_ranks: u32, heap_size: usize) -> Vec<Self> {
176        let heap = Arc::new(SymmetricHeap::new(num_ranks, heap_size));
177        let barrier = Arc::new(std::sync::Barrier::new(num_ranks as usize));
178        (0..num_ranks)
179            .map(|i| Self::with_heap(heap.clone(), Rank(i), barrier.clone()))
180            .collect()
181    }
182
183    fn with_heap(heap: Arc<SymmetricHeap>, me: Rank, barrier: Arc<std::sync::Barrier>) -> Self {
184        Self { heap, me, barrier }
185    }
186
187    fn check_buf(&self, buf: SymmetricBuffer) -> Result<(), CollectiveError> {
188        if buf.rank.0 >= self.heap.num_ranks() {
189            return Err(CollectiveError::UnknownRank {
190                rank: buf.rank,
191                num_ranks: self.heap.num_ranks(),
192            });
193        }
194        if buf.offset + buf.len > self.heap.heap_size {
195            return Err(CollectiveError::OutOfBounds {
196                rank: buf.rank,
197                offset: buf.offset,
198                len: buf.len,
199                heap_size: self.heap.heap_size,
200            });
201        }
202        Ok(())
203    }
204}
205
206impl SymmetricTransport for LocalTransport {
207    fn num_ranks(&self) -> u32 {
208        self.heap.num_ranks()
209    }
210    fn this_rank(&self) -> Rank {
211        self.me
212    }
213
214    fn put(&self, buf: SymmetricBuffer, src: &[u8]) -> Result<(), CollectiveError> {
215        self.check_buf(buf)?;
216        if src.len() != buf.len {
217            return Err(CollectiveError::LengthMismatch {
218                expected: buf.len,
219                got: src.len(),
220            });
221        }
222        let view = self.heap.rank_view(buf.rank).expect("checked above");
223        let mut guard = view.write().unwrap();
224        guard[buf.offset..buf.offset + buf.len].copy_from_slice(src);
225        Ok(())
226    }
227
228    fn get(&self, buf: SymmetricBuffer, dst: &mut [u8]) -> Result<(), CollectiveError> {
229        self.check_buf(buf)?;
230        if dst.len() != buf.len {
231            return Err(CollectiveError::LengthMismatch {
232                expected: buf.len,
233                got: dst.len(),
234            });
235        }
236        let view = self.heap.rank_view(buf.rank).expect("checked above");
237        let guard = view.read().unwrap();
238        dst.copy_from_slice(&guard[buf.offset..buf.offset + buf.len]);
239        Ok(())
240    }
241
242    fn barrier(&self) -> Result<(), CollectiveError> {
243        // Real rendezvous: blocks until every rank from the same `fan_out`
244        // reaches here, then all proceed. Reusable across collective steps.
245        self.barrier.wait();
246        Ok(())
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    #[test]
255    fn put_then_get_round_trips() {
256        let t = LocalTransport::new(4, 1024, Rank(0));
257        let buf = SymmetricBuffer {
258            rank: Rank(2),
259            offset: 16,
260            len: 8,
261        };
262        t.put(buf, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap();
263        let mut dst = [0u8; 8];
264        t.get(buf, &mut dst).unwrap();
265        assert_eq!(&dst, &[1, 2, 3, 4, 5, 6, 7, 8]);
266    }
267
268    #[test]
269    fn fan_out_yields_one_transport_per_rank() {
270        let ts = LocalTransport::fan_out(3, 64);
271        assert_eq!(ts.len(), 3);
272        for (i, t) in ts.iter().enumerate() {
273            assert_eq!(t.this_rank(), Rank(i as u32));
274            assert_eq!(t.num_ranks(), 3);
275        }
276    }
277
278    #[test]
279    fn put_visible_to_other_rank_via_shared_heap() {
280        // Rank 0 writes into rank 2's slot; rank 2 reads its
281        // own slot and sees the write.
282        let ts = LocalTransport::fan_out(3, 32);
283        let payload = [9u8, 9, 9, 9];
284        ts[0]
285            .put(
286                SymmetricBuffer {
287                    rank: Rank(2),
288                    offset: 0,
289                    len: 4,
290                },
291                &payload,
292            )
293            .unwrap();
294        let mut dst = [0u8; 4];
295        ts[2]
296            .get(
297                SymmetricBuffer {
298                    rank: Rank(2),
299                    offset: 0,
300                    len: 4,
301                },
302                &mut dst,
303            )
304            .unwrap();
305        assert_eq!(dst, payload);
306    }
307
308    #[test]
309    fn oob_offset_errors() {
310        let t = LocalTransport::new(2, 8, Rank(0));
311        let err = t
312            .put(
313                SymmetricBuffer {
314                    rank: Rank(1),
315                    offset: 4,
316                    len: 8,
317                },
318                &[0u8; 8],
319            )
320            .unwrap_err();
321        assert!(matches!(err, CollectiveError::OutOfBounds { .. }));
322    }
323
324    #[test]
325    fn unknown_rank_errors() {
326        let t = LocalTransport::new(2, 8, Rank(0));
327        let err = t
328            .get(
329                SymmetricBuffer {
330                    rank: Rank(99),
331                    offset: 0,
332                    len: 4,
333                },
334                &mut [0u8; 4],
335            )
336            .unwrap_err();
337        assert!(matches!(err, CollectiveError::UnknownRank { .. }));
338    }
339
340    #[test]
341    fn length_mismatch_errors() {
342        let t = LocalTransport::new(2, 32, Rank(0));
343        let err = t
344            .put(
345                SymmetricBuffer {
346                    rank: Rank(1),
347                    offset: 0,
348                    len: 4,
349                },
350                &[0u8; 8],
351            )
352            .unwrap_err();
353        assert!(matches!(err, CollectiveError::LengthMismatch { .. }));
354    }
355}