warp-types 0.3.2

Type-safe GPU warp programming via linear typestate: compile-time prevention of shuffle-from-inactive-lane bugs
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
//! Memory Coalescing Types
//!
//! **STATUS: Research** — Exploratory prototype, not promoted to main API.
//!
//! Research question: "Can types verify coalescing properties?"
//!
//! # Background
//!
//! Memory coalescing is critical for GPU performance:
//! - Coalesced: All lanes access consecutive addresses → 1 transaction
//! - Uncoalesced: Random access → up to 32 transactions
//! - 10-100x performance difference!
//!
//! # Key Insight
//!
//! Access patterns can be classified by their REGULARITY:
//! - Uniform: All lanes access same address (broadcast)
//! - Consecutive: Lane i accesses base + i (perfect coalescing)
//! - Strided: Lane i accesses base + i*stride (partial coalescing)
//! - Random: No pattern (worst case)
//!
//! These patterns can be encoded in the type system!
//!
//! # Design
//!
//! ```text
//! Ptr<T, AccessPattern>
//! where AccessPattern in {Uniform, Consecutive, Strided<N>, Random}
//! ```

use std::marker::PhantomData;

use crate::WARP_SIZE;

// ============================================================================
// ACCESS PATTERN TYPES
// ============================================================================

/// Marker trait for access patterns
pub trait AccessPattern: Copy + 'static {
    fn name() -> &'static str;
    fn transactions_per_warp() -> usize; // 1 = perfect, 32 = worst
}

/// All lanes access the same address (broadcast load)
#[derive(Copy, Clone)]
pub struct Uniform;

impl AccessPattern for Uniform {
    fn name() -> &'static str {
        "Uniform"
    }
    fn transactions_per_warp() -> usize {
        1
    }
}

/// Lane i accesses base + i * sizeof(T) (perfect coalescing)
#[derive(Copy, Clone)]
pub struct Consecutive;

impl AccessPattern for Consecutive {
    fn name() -> &'static str {
        "Consecutive"
    }
    fn transactions_per_warp() -> usize {
        1
    } // For aligned, same-line access
}

/// Lane i accesses base + i * STRIDE * sizeof(T)
#[derive(Copy, Clone)]
pub struct Strided<const STRIDE: usize>;

impl<const STRIDE: usize> AccessPattern for Strided<STRIDE> {
    fn name() -> &'static str {
        "Strided"
    }
    fn transactions_per_warp() -> usize {
        // Depends on cache line size and stride
        // Rough estimate: stride 0 = uniform (1 txn), otherwise min(WARP_SIZE, STRIDE)
        std::cmp::max(1, std::cmp::min(WARP_SIZE as usize, STRIDE))
    }
}

/// Random access pattern (worst case)
#[derive(Copy, Clone)]
pub struct Random;

impl AccessPattern for Random {
    fn name() -> &'static str {
        "Random"
    }
    fn transactions_per_warp() -> usize {
        WARP_SIZE as usize
    } // Worst case
}

// ============================================================================
// TYPED POINTERS
// ============================================================================

/// A pointer with known access pattern
#[derive(Clone)]
pub struct WarpPtr<T: Copy, P: AccessPattern> {
    base: *const T,
    _pattern: PhantomData<P>,
}

impl<T: Copy, P: AccessPattern> WarpPtr<T, P> {
    /// Create a new typed pointer.
    ///
    /// # Safety
    ///
    /// Caller must ensure `base` is valid for the declared access pattern
    /// and that the pointer remains valid for the lifetime of the `WarpPtr`.
    pub unsafe fn new(base: *const T) -> Self {
        WarpPtr {
            base,
            _pattern: PhantomData,
        }
    }

    pub fn base(&self) -> *const T {
        self.base
    }

    pub fn pattern_name() -> &'static str {
        P::name()
    }

    pub fn expected_transactions() -> usize {
        P::transactions_per_warp()
    }
}

/// A mutable pointer with known access pattern
pub struct WarpPtrMut<T: Copy, P: AccessPattern> {
    base: *mut T,
    _pattern: PhantomData<P>,
}

impl<T: Copy, P: AccessPattern> WarpPtrMut<T, P> {
    /// Create a new mutable typed pointer.
    ///
    /// # Safety
    ///
    /// Caller must ensure `base` is valid for the declared access pattern
    /// and that the pointer remains valid for the lifetime of the `WarpPtrMut`.
    pub unsafe fn new(base: *mut T) -> Self {
        WarpPtrMut {
            base,
            _pattern: PhantomData,
        }
    }

    pub fn base(&self) -> *mut T {
        self.base
    }
}

// ============================================================================
// PATTERN PROMOTION/DEMOTION
// ============================================================================

/// Patterns form a hierarchy: Uniform < Consecutive < Strided < Random
///
/// Combining patterns uses the "worst" pattern:
/// - Uniform + Consecutive = Consecutive
/// - Consecutive + Strided = Strided
/// - Anything + Random = Random
pub trait WorstOf<Other: AccessPattern>: AccessPattern {
    type Result: AccessPattern;
}

// Uniform is dominated by everything
impl WorstOf<Uniform> for Uniform {
    type Result = Uniform;
}
impl WorstOf<Consecutive> for Uniform {
    type Result = Consecutive;
}
impl<const S: usize> WorstOf<Strided<S>> for Uniform {
    type Result = Strided<S>;
}
impl WorstOf<Random> for Uniform {
    type Result = Random;
}

// Consecutive dominates Uniform
impl WorstOf<Uniform> for Consecutive {
    type Result = Consecutive;
}
impl WorstOf<Consecutive> for Consecutive {
    type Result = Consecutive;
}
impl<const S: usize> WorstOf<Strided<S>> for Consecutive {
    type Result = Strided<S>;
}
impl WorstOf<Random> for Consecutive {
    type Result = Random;
}

// Random dominates everything
impl WorstOf<Uniform> for Random {
    type Result = Random;
}
impl WorstOf<Consecutive> for Random {
    type Result = Random;
}
impl<const S: usize> WorstOf<Strided<S>> for Random {
    type Result = Random;
}
impl WorstOf<Random> for Random {
    type Result = Random;
}

// ============================================================================
// SAFE LOAD/STORE WITH PATTERN
// ============================================================================

/// Load with compile-time pattern check
pub mod load {
    use super::*;

    /// Uniform load: all lanes get same value.
    ///
    /// Safety relies on `WarpPtr::new`'s contract: the pointer must remain
    /// valid for the lifetime of the `WarpPtr`. This is the standard Rust
    /// "unsafe constructor, safe usage" pattern (cf. `Vec::from_raw_parts`).
    pub fn uniform<T: Copy>(ptr: &WarpPtr<T, Uniform>) -> T {
        unsafe { *ptr.base() }
    }

    /// Consecutive load: lane i gets base[i]
    /// Returns per-lane values
    pub fn consecutive<T: Copy + Default>(
        ptr: &WarpPtr<T, Consecutive>,
    ) -> [T; WARP_SIZE as usize] {
        let mut result = [T::default(); WARP_SIZE as usize];
        for lane in 0..WARP_SIZE as usize {
            unsafe {
                result[lane] = *ptr.base().add(lane);
            }
        }
        result
    }

    /// Generic load (for any pattern).
    ///
    /// # Safety
    ///
    /// Each `indices[lane]` must be a valid offset from `ptr.base()` —
    /// i.e., `ptr.base().add(indices[lane])` must be in-bounds of the
    /// original allocation.
    pub unsafe fn generic<T: Copy + Default, P: AccessPattern>(
        ptr: &WarpPtr<T, P>,
        indices: &[usize; WARP_SIZE as usize],
    ) -> [T; WARP_SIZE as usize] {
        let mut result = [T::default(); WARP_SIZE as usize];
        for lane in 0..WARP_SIZE as usize {
            unsafe {
                result[lane] = *ptr.base().add(indices[lane]);
            }
        }
        result
    }
}

/// Store with compile-time pattern check
pub mod store {
    use super::*;

    /// Uniform store: all lanes write same value to same address.
    /// Takes `&mut` to satisfy Rust's aliasing rules — writing through
    /// a `*mut T` requires exclusive access to the pointer wrapper.
    pub fn uniform<T: Copy>(ptr: &mut WarpPtrMut<T, Uniform>, value: T) {
        unsafe {
            *ptr.base() = value;
        }
    }

    /// Consecutive store: lane i writes to base[i].
    /// Takes `&mut` to satisfy Rust's aliasing rules.
    pub fn consecutive<T: Copy>(
        ptr: &mut WarpPtrMut<T, Consecutive>,
        values: &[T; WARP_SIZE as usize],
    ) {
        for lane in 0..WARP_SIZE as usize {
            unsafe {
                *ptr.base().add(lane) = values[lane];
            }
        }
    }
}

// ============================================================================
// PATTERN INFERENCE
// ============================================================================

/// Infer access pattern from index expression
pub mod infer {

    /// Index expression types
    pub enum IndexExpr {
        Constant(usize),    // Same for all lanes → Uniform
        LaneId,             // lane_id → Consecutive
        LaneIdTimes(usize), // lane_id * stride → Strided
        LaneIdPlus(usize),  // lane_id + offset → Consecutive (shifted)
        Computed,           // Arbitrary → Random
    }

    /// Infer pattern from index expression
    pub fn pattern_from_index(expr: &IndexExpr) -> &'static str {
        match expr {
            IndexExpr::Constant(_) => "Uniform",
            IndexExpr::LaneId => "Consecutive",
            IndexExpr::LaneIdTimes(1) => "Consecutive",
            IndexExpr::LaneIdTimes(_) => "Strided",
            IndexExpr::LaneIdPlus(_) => "Consecutive",
            IndexExpr::Computed => "Random",
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn test_pattern_inference() {
            assert_eq!(pattern_from_index(&IndexExpr::Constant(0)), "Uniform");
            assert_eq!(pattern_from_index(&IndexExpr::LaneId), "Consecutive");
            assert_eq!(pattern_from_index(&IndexExpr::LaneIdTimes(4)), "Strided");
            assert_eq!(pattern_from_index(&IndexExpr::Computed), "Random");
        }
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transaction_counts() {
        assert_eq!(Uniform::transactions_per_warp(), 1);
        assert_eq!(Consecutive::transactions_per_warp(), 1);
        assert_eq!(Strided::<4>::transactions_per_warp(), 4);
        assert_eq!(Random::transactions_per_warp(), WARP_SIZE as usize);
    }

    #[test]
    fn test_uniform_load() {
        let data = [42i32; 1];
        let ptr = unsafe { WarpPtr::<i32, Uniform>::new(data.as_ptr()) };

        let value = load::uniform(&ptr);
        assert_eq!(value, 42);
    }

    #[test]
    fn test_consecutive_load() {
        let data: [i32; WARP_SIZE as usize] = core::array::from_fn(|i| i as i32);
        let ptr = unsafe { WarpPtr::<i32, Consecutive>::new(data.as_ptr()) };

        let values = load::consecutive(&ptr);
        for lane in 0..WARP_SIZE as usize {
            assert_eq!(values[lane], lane as i32);
        }
    }

    #[test]
    fn test_pattern_hierarchy() {
        // Uniform + Consecutive = Consecutive
        type R1 = <Uniform as WorstOf<Consecutive>>::Result;
        assert_eq!(R1::name(), "Consecutive");

        // Consecutive + Random = Random
        type R2 = <Consecutive as WorstOf<Random>>::Result;
        assert_eq!(R2::name(), "Random");
    }
}

// ============================================================================
// SUMMARY
// ============================================================================

/// Summary: Can types verify coalescing properties?
///
/// ## Answer: Yes, for common patterns
///
/// ### Approach
///
/// Encode access pattern in pointer type:
/// ```text
/// WarpPtr<T, Uniform>      - all lanes access same address
/// WarpPtr<T, Consecutive>  - lane i accesses base + i
/// WarpPtr<T, Strided<N>>   - lane i accesses base + i*N
/// WarpPtr<T, Random>       - arbitrary access
/// ```
///
/// ### Benefits
///
/// 1. **Compile-time performance prediction**: Know transaction count
/// 2. **Pattern enforcement**: API requires specific pattern
/// 3. **Optimization guidance**: Compiler can choose instructions
/// 4. **Documentation**: Pattern is visible in type
///
/// ### Limitations
///
/// 1. **Pattern must be known statically**: Runtime-computed indices → Random
/// 2. **Conservative for complex patterns**: Strided approximates many cases
/// 3. **Doesn't verify alignment**: Misalignment still causes extra transactions
///
/// ### Integration with Session Types
///
/// Coalescing types compose with active set types:
/// ```text
/// fn load<S: ActiveSet, P: AccessPattern>(
///     warp: &Warp<S>,
///     ptr: &WarpPtr<T, P>,
/// ) -> PerLane<T>
/// ```
///
/// The active set S affects which lanes participate in the load.
/// A load on Warp<Even> with Consecutive pattern has half the transactions.
///
/// ### Verdict
///
/// Types CAN verify coalescing for patterns that are statically known.
/// This covers ~80% of GPU memory access (the performance-critical 80%).
/// Random access (remaining 20%) is typed as such, flagging it for review.
pub const _SUMMARY: () = ();