riri 0.8.0

A Miri-style undefined-behaviour detector for Rust GPU kernels: run SIMT kernels on the CPU and catch data races, barrier and warp divergence, bad shuffle masks, and uninitialised reads of shared or global memory, understands release and acquire ordering between blocks, and shrinks a failing schedule to the few decisions that cause it.
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! A `cuda_device`-shaped surface, so a kernel written for cuda-oxide can be
//! checked by Riri without being rewritten.
//!
//! cuda-oxide kernels take their identity from hardware registers rather than
//! from a context argument: `thread::index_1d()` and friends are free
//! functions. Riri gives each simulated GPU thread its own OS thread, so the
//! same shape works here by parking the thread's share of the launch in a
//! thread local and rebuilding a [`ThreadCtx`] from it on demand. No raw
//! pointers are involved, and Riri stays free of `unsafe`.
//!
//! The intended use is one kernel source compiled two ways:
//!
//! ```ignore
//! #[cfg_attr(not(riri), cuda_device::kernel)]
//! pub fn vecadd(a: &[f32], b: &[f32], mut c: DisjointSlice<f32>) {
//!     if let Some((c_elem, idx)) = c.get_mut_indexed() {
//!         let i = idx.get();
//!         *c_elem = a[i] + b[i];
//!     }
//! }
//! ```
//!
//! `cfg_attr` carries the `#[kernel]` attribute only on the GPU build, which
//! is why Riri needs no proc macro of its own and keeps its empty dependency
//! list. Under Riri the same function is an ordinary Rust function, called
//! once per simulated thread by [`launch`].
//!
//! # What this checks, and what it cannot
//!
//! In cuda-oxide's Tier 1 the inputs are `&[T]`, which nothing writes during
//! a launch, and the single write path is [`DisjointSlice`], whose checked
//! accessors hand each thread a distinct index. Races are therefore ruled out
//! by construction, and Riri has nothing to add.
//!
//! The value is in Tier 2, where the guarantee is a claim rather than a
//! proof. [`DisjointSlice::get_unchecked_mut`] asserts that the caller's
//! index is unique to it, and nothing verifies that on hardware. Under Riri
//! the access is instrumented like any other, so two threads claiming the
//! same element is an ordinary data race with both source lines named. Warp
//! collectives are checked the same way as the rest of [`crate::warp`].
//!
//! Not covered yet:
//!
//! - Shared memory, deliberately. cuda-oxide's `SharedArray` is a zero-sized
//!   marker: their compiler recognises the type and backs it with storage in
//!   address space 3, and every accessor on it is `unreachable!` off-device.
//!   Riri would have to supply storage of its own, and `Index` hands out
//!   references into storage that starts uninitialised, which needs
//!   `MaybeUninit` behind `unsafe`. Use [`ThreadCtx::shared`] instead, which
//!   is checked exactly as the rest of Riri is.
//! - 2D and tiled index spaces, the `_sync` shuffle forms, managed barriers,
//!   clusters, and TMA.
//!
//! # Fidelity
//!
//! `cuda-device` is not published to crates.io and its workspace pins a
//! specific nightly, so Riri cannot depend on it and this surface is written
//! from the published API reference rather than compiled against the real
//! crate. Signatures can drift. Treat a mismatch as a bug in Riri.

use std::cell::RefCell;
use std::marker::PhantomData;
use std::panic::Location;
use std::sync::Arc;

use crate::ctx::ThreadCtx;
use crate::diag::Report;
use crate::launch::{LaunchConfig, LaunchState};
use crate::mem::{ElemMut, GlobalBuf};
use crate::sched::{Choices, SplitMix64};
use crate::sync::Ordering;

struct Bound {
    state: Arc<LaunchState>,
    block: u32,
    thread: u32,
    gid: usize,
    slot: usize,
}

thread_local! {
    static CURRENT: RefCell<Option<Bound>> = const { RefCell::new(None) };
}

/// Rebuilds this thread's context and hands it to `f`.
fn with_ctx<R>(f: impl FnOnce(&ThreadCtx<'_>) -> R) -> R {
    CURRENT.with(|cell| {
        let bound = cell.borrow();
        let bound = bound
            .as_ref()
            .expect("riri: a cuda-oxide device function was called outside riri::oxide::launch");
        let ctx = ThreadCtx {
            launch: &bound.state,
            block: bound.block,
            thread: bound.thread,
            gid: bound.gid,
            slot: bound.slot,
        };
        f(&ctx)
    })
}

/// Clears the binding however the kernel leaves, including by unwinding.
struct Unbind;

impl Drop for Unbind {
    fn drop(&mut self) {
        CURRENT.with(|cell| *cell.borrow_mut() = None);
    }
}

/// Runs a cuda-oxide shaped kernel once per simulated GPU thread.
///
/// The closure takes no arguments: the kernel finds its own identity through
/// [`thread`], exactly as it does on the GPU. Call the kernel function inside
/// it, handing over whatever it takes by value.
///
/// ```
/// use riri::oxide::{self, DisjointSlice};
/// use riri::{GlobalBuf, LaunchConfig};
///
/// fn vecadd(a: &[f32], b: &[f32], mut c: DisjointSlice<f32>) {
///     if let Some((mut c_elem, idx)) = c.get_mut_indexed() {
///         let i = idx.get();
///         *c_elem = a[i] + b[i];
///     }
/// }
///
/// let a = vec![1.0f32; 64];
/// let b = vec![2.0f32; 64];
/// let out = GlobalBuf::new("c", vec![0.0f32; 64]);
/// let c = DisjointSlice::new(&out);
///
/// let report = oxide::launch(&LaunchConfig::new(2, 32), || {
///     vecadd(&a, &b, c.clone())
/// });
///
/// report.assert_clean();
/// assert!(out.to_vec().iter().all(|&x| x == 3.0));
/// ```
pub fn launch<F>(config: &LaunchConfig, kernel: F) -> Report
where
    F: Fn() + Sync,
{
    crate::launch::run_shared(
        config,
        Choices::Random(SplitMix64(config.seed)),
        |state, ctx| {
            CURRENT.with(|cell| {
                *cell.borrow_mut() = Some(Bound {
                    state: Arc::clone(state),
                    block: ctx.block,
                    thread: ctx.thread,
                    gid: ctx.gid,
                    slot: ctx.slot,
                });
            });
            let _unbind = Unbind;
            kernel();
        },
    )
    .0
}

/// An opaque witness that a thread owns one index.
///
/// As in cuda-oxide it has no public constructor, cannot be copied, cloned,
/// sent, or shared, and so cannot be passed between threads to claim another
/// thread's element.
pub struct ThreadIndex<'k> {
    index: usize,
    _not_send: PhantomData<*const ()>,
    _scope: PhantomData<&'k ()>,
}

impl ThreadIndex<'_> {
    /// The index this witness stands for.
    pub fn get(&self) -> usize {
        self.index
    }
}

/// Thread identification and block-level synchronisation.
#[allow(non_snake_case)]
pub mod thread {
    use super::{with_ctx, ThreadIndex};
    use std::marker::PhantomData;
    use std::panic::Location;

    fn witness<'k>(index: usize) -> ThreadIndex<'k> {
        ThreadIndex {
            index,
            _not_send: PhantomData,
            _scope: PhantomData,
        }
    }

    /// `blockIdx.x * blockDim.x + threadIdx.x`, as an owned witness.
    pub fn index_1d<'k>() -> ThreadIndex<'k> {
        witness(with_ctx(|t| t.global_linear()))
    }

    pub fn threadIdx_x() -> u32 {
        with_ctx(|t| t.thread_idx().x)
    }

    pub fn threadIdx_y() -> u32 {
        with_ctx(|t| t.thread_idx().y)
    }

    pub fn threadIdx_z() -> u32 {
        with_ctx(|t| t.thread_idx().z)
    }

    pub fn blockIdx_x() -> u32 {
        with_ctx(|t| t.block_idx().x)
    }

    pub fn blockIdx_y() -> u32 {
        with_ctx(|t| t.block_idx().y)
    }

    pub fn blockIdx_z() -> u32 {
        with_ctx(|t| t.block_idx().z)
    }

    pub fn blockDim_x() -> u32 {
        with_ctx(|t| t.block_dim().x)
    }

    pub fn blockDim_y() -> u32 {
        with_ctx(|t| t.block_dim().y)
    }

    pub fn blockDim_z() -> u32 {
        with_ctx(|t| t.block_dim().z)
    }

    pub fn gridDim_x() -> u32 {
        with_ctx(|t| t.grid_dim().x)
    }

    /// Lanes per warp, as `warpSize`.
    pub fn warp_size() -> u32 {
        with_ctx(|t| t.warp_size())
    }

    /// `__syncthreads()`.
    #[track_caller]
    pub fn sync_threads() {
        let at = Location::caller();
        with_ctx(|t| t.sync_threads_at(at));
    }
}

/// The write path: a slice whose elements are claimed one per thread.
///
/// Backed by a [`GlobalBuf`], so every access through it is instrumented.
/// Cloning is cheap and shares the buffer, which is how each simulated thread
/// receives its own handle the way a GPU kernel receives its own argument.
pub struct DisjointSlice<T> {
    buf: GlobalBuf<T>,
}

impl<T> Clone for DisjointSlice<T> {
    fn clone(&self) -> Self {
        DisjointSlice {
            buf: self.buf.clone(),
        }
    }
}

impl<T: Copy + Send + 'static> DisjointSlice<T> {
    /// Wraps an instrumented buffer as the kernel's write path.
    pub fn new(buf: &GlobalBuf<T>) -> Self {
        DisjointSlice { buf: buf.clone() }
    }

    pub fn len(&self) -> usize {
        self.buf.len()
    }

    pub fn is_empty(&self) -> bool {
        self.buf.is_empty()
    }

    /// Mints this thread's witness and resolves it in one call.
    ///
    /// `None` for a thread whose index is past the end, which is how a launch
    /// rounded up to whole blocks drops its tail.
    #[track_caller]
    pub fn get_mut_indexed(&mut self) -> Option<(ElemMut<'_, T>, ThreadIndex<'_>)> {
        let at = Location::caller();
        let index = with_ctx(|t| t.global_linear());
        let elem = with_ctx(|t| self.buf.elem_mut(t, index, true, at))?;
        Some((
            elem,
            ThreadIndex {
                index,
                _not_send: PhantomData,
                _scope: PhantomData,
            },
        ))
    }

    /// Resolves an explicit witness, bounds checked.
    #[track_caller]
    pub fn get_mut(&mut self, idx: ThreadIndex<'_>) -> Option<ElemMut<'_, T>> {
        let at = Location::caller();
        let index = idx.get();
        with_ctx(|t| self.buf.elem_mut(t, index, true, at))
    }

    /// Claims an element by raw index, with no check that the claim is unique.
    ///
    /// On hardware nothing verifies that two threads did not pass the same
    /// index. Under Riri the access is instrumented, so they do not get away
    /// with it: the second claim is reported as a data race naming both
    /// lines. Out of range is a trap rather than `None`, matching the
    /// unchecked contract.
    ///
    /// This mirrors an `unsafe fn` in cuda-oxide. It is safe here because
    /// Riri checks rather than trusts, which is the entire point of running
    /// the kernel under it.
    #[track_caller]
    pub fn get_unchecked_mut(&mut self, index: usize) -> ElemMut<'_, T> {
        let at = Location::caller();
        with_ctx(|t| self.buf.elem_mut(t, index, false, at))
            .expect("riri: unchecked access is never None")
    }
}

/// How an atomic orders the accesses around it, spelled as cuda-oxide spells
/// it. The same five cases as [`crate::Ordering`], which this converts to.
pub type AtomicOrdering = Ordering;

/// `__threadfence()`: orders this thread's accesses against the atomics
/// around it, at device scope.
///
/// Riri models device scope, which within one launch is everything there is,
/// so [`threadfence_system`] is the same function. `threadfence_block` is
/// deliberately absent: it orders only within a block, Riri's clocks are not
/// scoped that way, and treating it as a device fence would report a kernel
/// clean that relied on it for cross-block visibility. A missing function is
/// better than a wrong answer.
pub fn threadfence() {
    with_ctx(|t| t.threadfence());
}

/// `__threadfence_system()`. See [`threadfence`]: within a single launch
/// there is no host or peer device to order against, so this is that.
pub fn threadfence_system() {
    with_ctx(|t| t.threadfence());
}

/// One atomically accessed element of device memory.
///
/// cuda-oxide gives a kernel these through its data, as `DeviceAtomicU32` and
/// friends, and calls methods on them with no context argument. The same
/// methods are here with the same signatures, so the lines that use them need
/// no changing. What differs is where one comes from: under Riri it names an
/// element of an instrumented buffer, usually through [`DeviceAtomicSlice`].
pub struct DeviceAtomic<T> {
    buf: GlobalBuf<T>,
    index: usize,
}

impl<T: Copy + Send + 'static> DeviceAtomic<T> {
    /// Names one element of `buf` as atomically accessed.
    pub fn at(buf: &GlobalBuf<T>, index: usize) -> Self {
        DeviceAtomic {
            buf: buf.clone(),
            index,
        }
    }

    #[track_caller]
    pub fn load(&self, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_load_at(t, self.index, order, at))
    }

    #[track_caller]
    pub fn store(&self, val: T, order: AtomicOrdering) {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_store_at(t, self.index, val, order, at));
    }

    #[track_caller]
    pub fn swap(&self, val: T, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_swap_at(t, self.index, val, order, at))
    }
}

impl<T: Copy + Send + PartialEq + 'static> DeviceAtomic<T> {
    #[track_caller]
    pub fn compare_exchange(&self, current: T, new: T, order: AtomicOrdering) -> Result<T, T> {
        let at = Location::caller();
        with_ctx(|t| {
            self.buf
                .atomic_compare_exchange_at(t, self.index, current, new, order, at)
        })
    }
}

impl<T: Copy + Send + Ord + 'static> DeviceAtomic<T> {
    #[track_caller]
    pub fn fetch_min(&self, val: T, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_min_at(t, self.index, val, order, at))
    }

    #[track_caller]
    pub fn fetch_max(&self, val: T, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_max_at(t, self.index, val, order, at))
    }
}

impl<T: Copy + Send + std::ops::Add<Output = T> + 'static> DeviceAtomic<T> {
    #[track_caller]
    pub fn fetch_add(&self, val: T, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_add_at(t, self.index, val, order, at))
    }
}

impl<T: Copy + Send + std::ops::Sub<Output = T> + 'static> DeviceAtomic<T> {
    #[track_caller]
    pub fn fetch_sub(&self, val: T, order: AtomicOrdering) -> T {
        let at = Location::caller();
        with_ctx(|t| self.buf.atomic_sub_at(t, self.index, val, order, at))
    }
}

/// A run of atomics, indexed the way a kernel indexes them.
///
/// `counters[i].fetch_add(1, AtomicOrdering::Relaxed)` reads the same here as
/// it does against cuda-oxide, which is the point. The handles are real
/// objects, so indexing can hand out a reference to one; each proxies to its
/// element of the instrumented buffer.
pub struct DeviceAtomicSlice<T> {
    handles: Vec<DeviceAtomic<T>>,
}

impl<T: Copy + Send + 'static> DeviceAtomicSlice<T> {
    pub fn new(buf: &GlobalBuf<T>) -> Self {
        DeviceAtomicSlice {
            handles: (0..buf.len()).map(|i| DeviceAtomic::at(buf, i)).collect(),
        }
    }

    pub fn len(&self) -> usize {
        self.handles.len()
    }

    pub fn is_empty(&self) -> bool {
        self.handles.is_empty()
    }
}

impl<T> std::ops::Index<usize> for DeviceAtomicSlice<T> {
    type Output = DeviceAtomic<T>;

    fn index(&self, index: usize) -> &DeviceAtomic<T> {
        &self.handles[index]
    }
}

/// Warp-level primitives.
///
/// cuda-oxide's unsuffixed forms take no member mask, so Riri supplies the
/// whole warp, which is what the hardware instruction they lower to assumes.
/// A warp that is not converged at one of these is therefore reported, which
/// is the bug those forms invite.
pub mod warp {
    use super::with_ctx;
    use std::panic::Location;

    /// This thread's lane within its warp.
    pub fn lane_id() -> u32 {
        with_ctx(|t| t.lane_id())
    }

    /// This thread's warp within its block.
    pub fn warp_id() -> u32 {
        with_ctx(|t| t.warp_id())
    }

    #[track_caller]
    pub fn shuffle(val: u32, src_lane: u32) -> u32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_sync_at(t, t.warp_valid_mask(), val, src_lane, at))
    }

    #[track_caller]
    pub fn shuffle_f32(val: f32, src_lane: u32) -> f32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_sync_at(t, t.warp_valid_mask(), val, src_lane, at))
    }

    #[track_caller]
    pub fn shuffle_up(val: u32, delta: u32) -> u32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_up_sync_at(t, t.warp_valid_mask(), val, delta, at))
    }

    #[track_caller]
    pub fn shuffle_up_f32(val: f32, delta: u32) -> f32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_up_sync_at(t, t.warp_valid_mask(), val, delta, at))
    }

    #[track_caller]
    pub fn shuffle_down(val: u32, delta: u32) -> u32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_down_sync_at(t, t.warp_valid_mask(), val, delta, at))
    }

    #[track_caller]
    pub fn shuffle_down_f32(val: f32, delta: u32) -> f32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_down_sync_at(t, t.warp_valid_mask(), val, delta, at))
    }

    #[track_caller]
    pub fn shuffle_xor(val: u32, lane_mask: u32) -> u32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_xor_sync_at(t, t.warp_valid_mask(), val, lane_mask, at))
    }

    #[track_caller]
    pub fn shuffle_xor_f32(val: f32, lane_mask: u32) -> f32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::shfl_xor_sync_at(t, t.warp_valid_mask(), val, lane_mask, at))
    }

    #[track_caller]
    pub fn all(predicate: bool) -> bool {
        let at = Location::caller();
        with_ctx(|t| {
            crate::warp::ballot(t, t.warp_valid_mask(), predicate, "all", at) == t.warp_valid_mask()
        })
    }

    #[track_caller]
    pub fn any(predicate: bool) -> bool {
        let at = Location::caller();
        with_ctx(|t| crate::warp::ballot(t, t.warp_valid_mask(), predicate, "any", at) != 0)
    }

    #[track_caller]
    pub fn ballot(predicate: bool) -> u32 {
        let at = Location::caller();
        with_ctx(|t| crate::warp::ballot(t, t.warp_valid_mask(), predicate, "ballot", at))
    }

    #[track_caller]
    pub fn popc(predicate: bool) -> u32 {
        ballot(predicate).count_ones()
    }
}