ringkernel-cpu 0.4.2

CPU backend for RingKernel - testing and fallback implementation
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! GPU Mock Testing Utilities
//!
//! This module provides utilities for mocking GPU behavior in CPU tests.
//! It simulates GPU intrinsics, thread organization, and memory patterns.
//!
//! # Example
//!
//! ```rust
//! use ringkernel_cpu::mock::{MockGpu, MockThread, MockKernelConfig};
//!
//! // Configure a mock kernel launch
//! let config = MockKernelConfig::new()
//!     .with_grid_size(4, 4, 1)
//!     .with_block_size(32, 8, 1);
//!
//! // Create mock GPU context
//! let gpu = MockGpu::new(config);
//!
//! // Execute kernel with mock threads
//! gpu.dispatch(|thread| {
//!     let gid = thread.global_id();
//!     // Kernel code here
//! });
//! ```

use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Barrier, RwLock};

// ============================================================================
// MOCK KERNEL CONFIGURATION
// ============================================================================

/// Configuration for mock kernel execution.
#[derive(Debug, Clone)]
pub struct MockKernelConfig {
    /// Grid dimensions (number of blocks).
    pub grid_dim: (u32, u32, u32),
    /// Block dimensions (threads per block).
    pub block_dim: (u32, u32, u32),
    /// Shared memory size in bytes.
    pub shared_memory_size: usize,
    /// Whether to simulate warp execution.
    pub simulate_warps: bool,
    /// Warp size (typically 32 for NVIDIA, 64 for AMD).
    pub warp_size: u32,
}

impl Default for MockKernelConfig {
    fn default() -> Self {
        Self {
            grid_dim: (1, 1, 1),
            block_dim: (256, 1, 1),
            shared_memory_size: 49152, // 48KB default
            simulate_warps: false,
            warp_size: 32,
        }
    }
}

impl MockKernelConfig {
    /// Create a new mock kernel configuration.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set grid dimensions.
    pub fn with_grid_size(mut self, x: u32, y: u32, z: u32) -> Self {
        self.grid_dim = (x, y, z);
        self
    }

    /// Set block dimensions.
    pub fn with_block_size(mut self, x: u32, y: u32, z: u32) -> Self {
        self.block_dim = (x, y, z);
        self
    }

    /// Set shared memory size.
    pub fn with_shared_memory(mut self, bytes: usize) -> Self {
        self.shared_memory_size = bytes;
        self
    }

    /// Enable warp simulation.
    pub fn with_warp_simulation(mut self, warp_size: u32) -> Self {
        self.simulate_warps = true;
        self.warp_size = warp_size;
        self
    }

    /// Calculate total number of threads.
    pub fn total_threads(&self) -> u64 {
        let blocks = self.grid_dim.0 as u64 * self.grid_dim.1 as u64 * self.grid_dim.2 as u64;
        let threads_per_block =
            self.block_dim.0 as u64 * self.block_dim.1 as u64 * self.block_dim.2 as u64;
        blocks * threads_per_block
    }

    /// Calculate threads per block.
    pub fn threads_per_block(&self) -> u32 {
        self.block_dim.0 * self.block_dim.1 * self.block_dim.2
    }

    /// Calculate total blocks.
    pub fn total_blocks(&self) -> u32 {
        self.grid_dim.0 * self.grid_dim.1 * self.grid_dim.2
    }
}

// ============================================================================
// MOCK THREAD CONTEXT
// ============================================================================

/// Mock thread context providing GPU intrinsics.
#[derive(Debug, Clone)]
pub struct MockThread {
    /// Thread index within block (x, y, z).
    pub thread_idx: (u32, u32, u32),
    /// Block index within grid (x, y, z).
    pub block_idx: (u32, u32, u32),
    /// Block dimensions.
    pub block_dim: (u32, u32, u32),
    /// Grid dimensions.
    pub grid_dim: (u32, u32, u32),
    /// Warp ID (within block).
    pub warp_id: u32,
    /// Lane ID (within warp).
    pub lane_id: u32,
    /// Warp size.
    pub warp_size: u32,
}

impl MockThread {
    /// Create a new mock thread.
    pub fn new(
        thread_idx: (u32, u32, u32),
        block_idx: (u32, u32, u32),
        config: &MockKernelConfig,
    ) -> Self {
        let linear_tid = thread_idx.0
            + thread_idx.1 * config.block_dim.0
            + thread_idx.2 * config.block_dim.0 * config.block_dim.1;

        Self {
            thread_idx,
            block_idx,
            block_dim: config.block_dim,
            grid_dim: config.grid_dim,
            warp_id: linear_tid / config.warp_size,
            lane_id: linear_tid % config.warp_size,
            warp_size: config.warp_size,
        }
    }

    // ========================================================================
    // GPU Intrinsics
    // ========================================================================

    /// Get thread index X.
    #[inline]
    pub fn thread_idx_x(&self) -> u32 {
        self.thread_idx.0
    }

    /// Get thread index Y.
    #[inline]
    pub fn thread_idx_y(&self) -> u32 {
        self.thread_idx.1
    }

    /// Get thread index Z.
    #[inline]
    pub fn thread_idx_z(&self) -> u32 {
        self.thread_idx.2
    }

    /// Get block index X.
    #[inline]
    pub fn block_idx_x(&self) -> u32 {
        self.block_idx.0
    }

    /// Get block index Y.
    #[inline]
    pub fn block_idx_y(&self) -> u32 {
        self.block_idx.1
    }

    /// Get block index Z.
    #[inline]
    pub fn block_idx_z(&self) -> u32 {
        self.block_idx.2
    }

    /// Get block dimension X.
    #[inline]
    pub fn block_dim_x(&self) -> u32 {
        self.block_dim.0
    }

    /// Get block dimension Y.
    #[inline]
    pub fn block_dim_y(&self) -> u32 {
        self.block_dim.1
    }

    /// Get block dimension Z.
    #[inline]
    pub fn block_dim_z(&self) -> u32 {
        self.block_dim.2
    }

    /// Get grid dimension X.
    #[inline]
    pub fn grid_dim_x(&self) -> u32 {
        self.grid_dim.0
    }

    /// Get grid dimension Y.
    #[inline]
    pub fn grid_dim_y(&self) -> u32 {
        self.grid_dim.1
    }

    /// Get grid dimension Z.
    #[inline]
    pub fn grid_dim_z(&self) -> u32 {
        self.grid_dim.2
    }

    /// Get global thread ID (1D linearized).
    #[inline]
    pub fn global_id(&self) -> u64 {
        let block_linear = self.block_idx.0 as u64
            + self.block_idx.1 as u64 * self.grid_dim.0 as u64
            + self.block_idx.2 as u64 * self.grid_dim.0 as u64 * self.grid_dim.1 as u64;

        let threads_per_block =
            self.block_dim.0 as u64 * self.block_dim.1 as u64 * self.block_dim.2 as u64;
        let thread_linear = self.thread_idx.0 as u64
            + self.thread_idx.1 as u64 * self.block_dim.0 as u64
            + self.thread_idx.2 as u64 * self.block_dim.0 as u64 * self.block_dim.1 as u64;

        block_linear * threads_per_block + thread_linear
    }

    /// Get global X coordinate.
    #[inline]
    pub fn global_x(&self) -> u32 {
        self.block_idx.0 * self.block_dim.0 + self.thread_idx.0
    }

    /// Get global Y coordinate.
    #[inline]
    pub fn global_y(&self) -> u32 {
        self.block_idx.1 * self.block_dim.1 + self.thread_idx.1
    }

    /// Get global Z coordinate.
    #[inline]
    pub fn global_z(&self) -> u32 {
        self.block_idx.2 * self.block_dim.2 + self.thread_idx.2
    }

    /// Check if this is the first thread in the block.
    #[inline]
    pub fn is_block_leader(&self) -> bool {
        self.thread_idx == (0, 0, 0)
    }

    /// Check if this is the first thread in the warp.
    #[inline]
    pub fn is_warp_leader(&self) -> bool {
        self.lane_id == 0
    }
}

// ============================================================================
// MOCK SHARED MEMORY
// ============================================================================

/// Mock shared memory for a block.
pub struct MockSharedMemory {
    data: RefCell<Vec<u8>>,
    size: usize,
}

impl MockSharedMemory {
    /// Create new shared memory.
    pub fn new(size: usize) -> Self {
        Self {
            data: RefCell::new(vec![0u8; size]),
            size,
        }
    }

    /// Get size in bytes.
    pub fn size(&self) -> usize {
        self.size
    }

    /// Read a value at offset.
    pub fn read<T: Copy>(&self, offset: usize) -> T {
        let data = self.data.borrow();
        assert!(offset + std::mem::size_of::<T>() <= self.size);
        unsafe { std::ptr::read(data.as_ptr().add(offset) as *const T) }
    }

    /// Write a value at offset.
    pub fn write<T: Copy>(&self, offset: usize, value: T) {
        let mut data = self.data.borrow_mut();
        assert!(offset + std::mem::size_of::<T>() <= self.size);
        unsafe { std::ptr::write(data.as_mut_ptr().add(offset) as *mut T, value) };
    }

    /// Get a slice view.
    pub fn as_slice<T: Copy>(&self, offset: usize, count: usize) -> Vec<T> {
        let data = self.data.borrow();
        let byte_size = count * std::mem::size_of::<T>();
        assert!(offset + byte_size <= self.size);

        let mut result = Vec::with_capacity(count);
        unsafe {
            let ptr = data.as_ptr().add(offset) as *const T;
            for i in 0..count {
                result.push(*ptr.add(i));
            }
        }
        result
    }

    /// Write a slice.
    pub fn write_slice<T: Copy>(&self, offset: usize, values: &[T]) {
        let mut data = self.data.borrow_mut();
        let byte_size = std::mem::size_of_val(values);
        assert!(offset + byte_size <= self.size);

        unsafe {
            let ptr = data.as_mut_ptr().add(offset) as *mut T;
            for (i, v) in values.iter().enumerate() {
                *ptr.add(i) = *v;
            }
        }
    }
}

// ============================================================================
// MOCK ATOMICS
// ============================================================================

/// Mock atomic operations.
pub struct MockAtomics {
    u32_values: RwLock<HashMap<usize, AtomicU32>>,
    u64_values: RwLock<HashMap<usize, AtomicU64>>,
}

impl Default for MockAtomics {
    fn default() -> Self {
        Self::new()
    }
}

impl MockAtomics {
    /// Create new atomics storage.
    pub fn new() -> Self {
        Self {
            u32_values: RwLock::new(HashMap::new()),
            u64_values: RwLock::new(HashMap::new()),
        }
    }

    /// Atomic add (u32).
    pub fn atomic_add_u32(&self, addr: usize, val: u32) -> u32 {
        let mut map = self.u32_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU32::new(0));
        atomic.fetch_add(val, Ordering::SeqCst)
    }

    /// Atomic add (u64).
    pub fn atomic_add_u64(&self, addr: usize, val: u64) -> u64 {
        let mut map = self.u64_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU64::new(0));
        atomic.fetch_add(val, Ordering::SeqCst)
    }

    /// Atomic CAS (u32).
    pub fn atomic_cas_u32(&self, addr: usize, expected: u32, new: u32) -> u32 {
        let mut map = self.u32_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU32::new(0));
        match atomic.compare_exchange(expected, new, Ordering::SeqCst, Ordering::SeqCst) {
            Ok(v) | Err(v) => v,
        }
    }

    /// Atomic max (u32).
    pub fn atomic_max_u32(&self, addr: usize, val: u32) -> u32 {
        let mut map = self.u32_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU32::new(0));
        atomic.fetch_max(val, Ordering::SeqCst)
    }

    /// Atomic min (u32).
    pub fn atomic_min_u32(&self, addr: usize, val: u32) -> u32 {
        let mut map = self.u32_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU32::new(0));
        atomic.fetch_min(val, Ordering::SeqCst)
    }

    /// Load value (u32).
    pub fn load_u32(&self, addr: usize) -> u32 {
        let map = self.u32_values.read().unwrap();
        map.get(&addr)
            .map(|a| a.load(Ordering::SeqCst))
            .unwrap_or(0)
    }

    /// Store value (u32).
    pub fn store_u32(&self, addr: usize, val: u32) {
        let mut map = self.u32_values.write().unwrap();
        let atomic = map.entry(addr).or_insert_with(|| AtomicU32::new(0));
        atomic.store(val, Ordering::SeqCst);
    }
}

// ============================================================================
// MOCK GPU
// ============================================================================

/// Mock GPU for testing kernel execution.
pub struct MockGpu {
    config: MockKernelConfig,
    atomics: Arc<MockAtomics>,
}

impl MockGpu {
    /// Create a new mock GPU.
    pub fn new(config: MockKernelConfig) -> Self {
        Self {
            config,
            atomics: Arc::new(MockAtomics::new()),
        }
    }

    /// Get configuration.
    pub fn config(&self) -> &MockKernelConfig {
        &self.config
    }

    /// Get atomics.
    pub fn atomics(&self) -> &MockAtomics {
        &self.atomics
    }

    /// Dispatch kernel execution sequentially.
    ///
    /// Executes the kernel function for each thread in order.
    /// Useful for deterministic testing.
    pub fn dispatch<F>(&self, kernel: F)
    where
        F: Fn(&MockThread),
    {
        for bz in 0..self.config.grid_dim.2 {
            for by in 0..self.config.grid_dim.1 {
                for bx in 0..self.config.grid_dim.0 {
                    for tz in 0..self.config.block_dim.2 {
                        for ty in 0..self.config.block_dim.1 {
                            for tx in 0..self.config.block_dim.0 {
                                let thread =
                                    MockThread::new((tx, ty, tz), (bx, by, bz), &self.config);
                                kernel(&thread);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Dispatch with block synchronization.
    ///
    /// Provides a barrier for `sync_threads()` simulation within blocks.
    pub fn dispatch_with_sync<F>(&self, kernel: F)
    where
        F: Fn(&MockThread, &Barrier) + Send + Sync,
    {
        let threads_per_block = self.config.threads_per_block() as usize;

        for bz in 0..self.config.grid_dim.2 {
            for by in 0..self.config.grid_dim.1 {
                for bx in 0..self.config.grid_dim.0 {
                    // Each block runs in parallel threads
                    let barrier = Arc::new(Barrier::new(threads_per_block));
                    std::thread::scope(|s| {
                        for tz in 0..self.config.block_dim.2 {
                            for ty in 0..self.config.block_dim.1 {
                                for tx in 0..self.config.block_dim.0 {
                                    let barrier = Arc::clone(&barrier);
                                    let config = &self.config;
                                    let kernel_ref = &kernel;
                                    s.spawn(move || {
                                        let thread =
                                            MockThread::new((tx, ty, tz), (bx, by, bz), config);
                                        kernel_ref(&thread, &barrier);
                                    });
                                }
                            }
                        }
                    });
                }
            }
        }
    }
}

// ============================================================================
// MOCK WARP OPERATIONS
// ============================================================================

/// Mock warp operations for testing warp-level primitives.
pub struct MockWarp {
    /// Lane values (up to 64 lanes for AMD).
    lane_values: Vec<u32>,
    /// Warp size.
    warp_size: u32,
}

impl MockWarp {
    /// Create a new mock warp.
    pub fn new(warp_size: u32) -> Self {
        Self {
            lane_values: vec![0; warp_size as usize],
            warp_size,
        }
    }

    /// Set lane value.
    pub fn set_lane(&mut self, lane: u32, value: u32) {
        if (lane as usize) < self.lane_values.len() {
            self.lane_values[lane as usize] = value;
        }
    }

    /// Simulate warp shuffle.
    pub fn shuffle(&self, src_lane: u32) -> u32 {
        self.lane_values
            .get(src_lane as usize)
            .copied()
            .unwrap_or(0)
    }

    /// Simulate warp shuffle XOR.
    pub fn shuffle_xor(&self, lane_id: u32, mask: u32) -> u32 {
        let src = lane_id ^ mask;
        self.shuffle(src)
    }

    /// Simulate warp shuffle up.
    pub fn shuffle_up(&self, lane_id: u32, delta: u32) -> u32 {
        if lane_id >= delta {
            self.shuffle(lane_id - delta)
        } else {
            self.lane_values[lane_id as usize]
        }
    }

    /// Simulate warp shuffle down.
    pub fn shuffle_down(&self, lane_id: u32, delta: u32) -> u32 {
        if lane_id + delta < self.warp_size {
            self.shuffle(lane_id + delta)
        } else {
            self.lane_values[lane_id as usize]
        }
    }

    /// Simulate warp ballot.
    pub fn ballot(&self, predicate: impl Fn(u32) -> bool) -> u64 {
        let mut result = 0u64;
        for lane in 0..self.warp_size {
            if predicate(lane) {
                result |= 1 << lane;
            }
        }
        result
    }

    /// Simulate warp any.
    pub fn any(&self, predicate: impl Fn(u32) -> bool) -> bool {
        (0..self.warp_size).any(predicate)
    }

    /// Simulate warp all.
    pub fn all(&self, predicate: impl Fn(u32) -> bool) -> bool {
        (0..self.warp_size).all(predicate)
    }

    /// Simulate warp reduction (sum).
    pub fn reduce_sum(&self) -> u32 {
        self.lane_values.iter().sum()
    }

    /// Simulate warp prefix sum (exclusive).
    pub fn prefix_sum_exclusive(&self) -> Vec<u32> {
        let mut result = Vec::with_capacity(self.warp_size as usize);
        let mut sum = 0;
        for &v in &self.lane_values {
            result.push(sum);
            sum += v;
        }
        result
    }
}

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

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

    #[test]
    fn test_mock_config() {
        let config = MockKernelConfig::new()
            .with_grid_size(4, 4, 1)
            .with_block_size(32, 8, 1);

        assert_eq!(config.total_blocks(), 16);
        assert_eq!(config.threads_per_block(), 256);
        assert_eq!(config.total_threads(), 4096);
    }

    #[test]
    fn test_mock_thread_intrinsics() {
        let config = MockKernelConfig::new()
            .with_grid_size(2, 2, 1)
            .with_block_size(16, 16, 1);

        let thread = MockThread::new((5, 3, 0), (1, 0, 0), &config);

        assert_eq!(thread.thread_idx_x(), 5);
        assert_eq!(thread.thread_idx_y(), 3);
        assert_eq!(thread.block_idx_x(), 1);
        assert_eq!(thread.block_dim_x(), 16);
        assert_eq!(thread.global_x(), 21); // 1*16 + 5
        assert_eq!(thread.global_y(), 3); // 0*16 + 3
    }

    #[test]
    fn test_mock_shared_memory() {
        let shmem = MockSharedMemory::new(1024);

        shmem.write::<f32>(0, 3.125);
        shmem.write::<f32>(4, 2.75);

        assert!((shmem.read::<f32>(0) - 3.125).abs() < 0.001);
        assert!((shmem.read::<f32>(4) - 2.75).abs() < 0.001);

        shmem.write_slice::<u32>(100, &[1, 2, 3, 4]);
        let slice = shmem.as_slice::<u32>(100, 4);
        assert_eq!(slice, vec![1, 2, 3, 4]);
    }

    #[test]
    fn test_mock_atomics() {
        let atomics = MockAtomics::new();

        let old = atomics.atomic_add_u32(0, 5);
        assert_eq!(old, 0);

        let old = atomics.atomic_add_u32(0, 3);
        assert_eq!(old, 5);

        assert_eq!(atomics.load_u32(0), 8);
    }

    #[test]
    fn test_mock_gpu_dispatch() {
        let config = MockKernelConfig::new()
            .with_grid_size(2, 1, 1)
            .with_block_size(4, 1, 1);

        let gpu = MockGpu::new(config);
        let counter = Arc::new(AtomicU32::new(0));

        let c = Arc::clone(&counter);
        gpu.dispatch(move |_thread| {
            c.fetch_add(1, Ordering::SeqCst);
        });

        assert_eq!(counter.load(Ordering::SeqCst), 8); // 2 blocks * 4 threads
    }

    #[test]
    fn test_mock_warp_shuffle() {
        let mut warp = MockWarp::new(32);

        // Set lane values
        for i in 0..32 {
            warp.set_lane(i, i * 2);
        }

        // Test shuffle
        assert_eq!(warp.shuffle(5), 10);
        assert_eq!(warp.shuffle(15), 30);

        // Test shuffle XOR
        assert_eq!(warp.shuffle_xor(0, 1), 2); // lane 0 XOR 1 = lane 1 value
        assert_eq!(warp.shuffle_xor(2, 1), 6); // lane 2 XOR 1 = lane 3 value
    }

    #[test]
    fn test_mock_warp_ballot() {
        let warp = MockWarp::new(32);

        // Ballot: all even lanes
        let ballot = warp.ballot(|lane| lane % 2 == 0);
        assert_eq!(ballot, 0x55555555); // Even bits set
    }

    #[test]
    fn test_mock_warp_reduce() {
        let mut warp = MockWarp::new(4);

        warp.set_lane(0, 1);
        warp.set_lane(1, 2);
        warp.set_lane(2, 3);
        warp.set_lane(3, 4);

        assert_eq!(warp.reduce_sum(), 10);

        let prefix = warp.prefix_sum_exclusive();
        assert_eq!(prefix, vec![0, 1, 3, 6]);
    }

    #[test]
    fn test_thread_global_id() {
        let config = MockKernelConfig::new()
            .with_grid_size(2, 2, 1)
            .with_block_size(4, 4, 1);

        // Thread (0,0) in block (0,0) -> global ID 0
        let t1 = MockThread::new((0, 0, 0), (0, 0, 0), &config);
        assert_eq!(t1.global_id(), 0);

        // Thread (0,0) in block (1,0) -> global ID 16 (one block worth)
        let t2 = MockThread::new((0, 0, 0), (1, 0, 0), &config);
        assert_eq!(t2.global_id(), 16);

        // Thread (3,3) in block (0,0) -> linear ID 15
        let t3 = MockThread::new((3, 3, 0), (0, 0, 0), &config);
        assert_eq!(t3.global_id(), 15);
    }
}