myelin-accelerator 0.2.0

Rust/CUDA acceleration primitives for spiking neural networks and neuromorphic workloads
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
// Copyright 2026 Raul Montoya Cardenas
// SPDX-License-Identifier: MIT OR Apache-2.0

pub use crate::capability::{
    Backend, CapabilityFacts, CapabilityReport, ComputeCapability, ExecutionPolicy, FallbackReason,
    FallbackRecord, KernelAvailability,
};
use crate::capability::{apply_failure_to_facts, evaluate_capabilities};
pub use crate::error::{GpuError, GpuResult};

pub(crate) fn host_facts() -> CapabilityFacts {
    CapabilityFacts::not_built()
}

#[derive(Debug)]
pub struct GpuContext;
impl GpuContext {
    pub fn init() -> GpuResult<Self> {
        Err(GpuError::NoGpu)
    }
    pub fn is_available() -> bool {
        false
    }

    /// Device 0 compute capability; unavailable in a CPU-only build.
    pub fn compute_capability(&self) -> Option<ComputeCapability> {
        None
    }
}

#[derive(Debug)]
pub struct KernelModule;
#[derive(Debug)]
pub struct Function;
impl KernelModule {
    pub fn load() -> GpuResult<Self> {
        Err(GpuError::NoGpu)
    }
    pub fn load_satsolver() -> GpuResult<Self> {
        Err(GpuError::NoGpu)
    }
    pub fn get_function(&self, _: &str) -> GpuResult<Function> {
        Err(GpuError::NoGpu)
    }
}

pub struct GpuBuffer<T> {
    data: Vec<T>,
}
impl<T: Default + Clone> GpuBuffer<T> {
    /// Allocate a buffer of `len` elements, initialised to `T::default()`.
    ///
    /// The buffer is readable immediately: [`Self::to_vec`] after `alloc`
    /// returns `len` copies of `T::default()` without any prior upload.
    /// `alloc(0)` succeeds and yields an empty, readable buffer. This mirrors
    /// the CUDA backend's initialisation contract so callers behave identically
    /// on either path.
    ///
    /// Oversized requests fail with [`GpuError::MemoryError`] instead of
    /// panicking: the byte size is checked with the same
    /// `size_of::<T>() * len` arithmetic and `isize::MAX` ceiling as the CUDA
    /// backend, and the backing `Vec` is reserved fallibly (GH #48).
    pub fn alloc(len: usize) -> GpuResult<Self> {
        crate::error::checked_alloc_bytes::<T>(len)?;
        let mut data: Vec<T> = Vec::new();
        data.try_reserve_exact(len)
            .map_err(|e| GpuError::MemoryError(format!("alloc({len}): reserve failed: {e:?}")))?;
        data.resize(len, T::default());
        Ok(Self { data })
    }
    /// Allocate a buffer holding a copy of `data`. `from_slice(&[])` yields an
    /// empty buffer.
    pub fn from_slice(data: &[T]) -> GpuResult<Self> {
        Ok(Self {
            data: data.to_vec(),
        })
    }
    /// Copy the buffer's current contents into a fresh `Vec<T>`.
    pub fn to_vec(&self) -> GpuResult<Vec<T>> {
        Ok(self.data.clone())
    }
    /// Upload from a host slice, replacing the buffer's contents.
    ///
    /// `data.len()` must equal [`Self::len`]; a mismatch returns
    /// [`GpuError::MemoryError`] before mutating anything, leaving the existing
    /// contents intact. Empty-to-empty uploads succeed as a no-op. The error
    /// payload matches the CUDA backend exactly.
    pub fn upload(&mut self, data: &[T]) -> GpuResult<()> {
        if data.len() != self.data.len() {
            return Err(GpuError::MemoryError(format!(
                "upload: length mismatch, buffer has {} elements but input has {}",
                self.data.len(),
                data.len()
            )));
        }
        self.data.clone_from_slice(data);
        Ok(())
    }
    pub fn len(&self) -> usize {
        self.data.len()
    }
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
    pub fn as_device_ptr(&self) -> *const T {
        self.data.as_ptr()
    }
}

impl GpuBuffer<f32> {
    /// Zero the first `count` elements; leaves any tail untouched (host stub).
    ///
    /// Matches the CUDA `GpuBuffer<f32>::zero_prefix` surface so callers do not
    /// depend on feature-specific method resolution.
    pub fn zero_prefix(&mut self, count: usize) -> GpuResult<()> {
        if count > self.data.len() {
            return Err(GpuError::MemoryError(format!(
                "zero_prefix: count {count} > buffer len {}",
                self.data.len()
            )));
        }
        for slot in &mut self.data[..count] {
            *slot = 0.0;
        }
        Ok(())
    }
}

pub struct GpuAccelerator {
    capabilities: CapabilityReport,
}

impl GpuAccelerator {
    /// Construct with [`ExecutionPolicy::PreferGpu`] (caller-approved CPU fallback).
    pub fn new() -> Self {
        match Self::with_policy(ExecutionPolicy::PreferGpu) {
            Ok(acc) => acc,
            Err(_) => unreachable!("PreferGpu construction is infallible"),
        }
    }

    /// Fail closed: never return a CPU-backend accelerator.
    pub fn require_gpu() -> GpuResult<Self> {
        Self::with_policy(ExecutionPolicy::RequireGpu)
    }

    /// Construct under an explicit execution policy.
    pub fn with_policy(policy: ExecutionPolicy) -> GpuResult<Self> {
        let mut facts = host_facts();
        apply_failure_to_facts(&mut facts, FallbackReason::CudaFeatureNotBuilt);
        let capabilities = evaluate_capabilities(&facts);
        match policy {
            ExecutionPolicy::PreferGpu => Ok(Self { capabilities }),
            ExecutionPolicy::RequireGpu => {
                let fb = capabilities.fallback.clone().unwrap_or_else(|| {
                    FallbackRecord::cpu(
                        FallbackReason::CudaFeatureNotBuilt,
                        "GPU was required but the cuda feature is not enabled",
                    )
                });
                Err(GpuError::unavailable(fb.reason, fb.detail))
            }
        }
    }

    pub fn is_ready(&self) -> bool {
        false
    }

    pub fn capabilities(&self) -> &CapabilityReport {
        &self.capabilities
    }

    pub fn selected_backend(&self) -> Backend {
        self.capabilities.selected_backend
    }

    pub fn fallback(&self) -> Option<&FallbackRecord> {
        self.capabilities.fallback.as_ref()
    }

    fn unavailable_error(&self) -> GpuError {
        match &self.capabilities.fallback {
            Some(fb) => GpuError::unavailable(fb.reason, fb.detail.clone()),
            None => GpuError::NoGpu,
        }
    }

    pub fn kernels(&self) -> GpuResult<&KernelModule> {
        Err(self.unavailable_error())
    }
    #[allow(clippy::too_many_arguments)]
    pub fn stdp_update(
        &self,
        _: &mut GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: f32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }
    #[allow(clippy::too_many_arguments)]
    pub fn stdp_update_async(
        &self,
        _: &mut GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: f32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }
    pub fn satsolver_extract(
        &self,
        _: &GpuBuffer<u8>,
        _: &GpuBuffer<i32>,
        _: &mut GpuBuffer<u8>,
        _: i32,
        _: i32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }
    #[allow(clippy::too_many_arguments)]
    pub fn satsolver_aux_reduce_best(
        &self,
        _: &GpuBuffer<u8>,
        _: &mut GpuBuffer<u8>,
        _: &GpuBuffer<i32>,
        _: &mut GpuBuffer<i32>,
        _: &mut GpuBuffer<i32>,
        _: &GpuBuffer<i32>,
        _: i32,
        _: i32,
        _: i32,
        _: i32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }
    pub fn poisson_encode(
        &self,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<u32>,
        _: u32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    pub fn satsolver_extract_async(
        &self,
        _: &GpuBuffer<u8>,
        _: &GpuBuffer<i32>,
        _: &mut GpuBuffer<u8>,
        _: i32,
        _: i32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn satsolver_aux_reduce_best_async(
        &self,
        _: &GpuBuffer<u8>,
        _: &mut GpuBuffer<u8>,
        _: &GpuBuffer<i32>,
        _: &mut GpuBuffer<i32>,
        _: &mut GpuBuffer<i32>,
        _: &GpuBuffer<i32>,
        _: i32,
        _: i32,
        _: i32,
        _: i32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    pub fn poisson_encode_async(
        &self,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<u32>,
        _: u32,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn ternary_gemv(
        &self,
        _: &GpuBuffer<u32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: i32,
        _: bool,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn ternary_gemv_async(
        &self,
        _: &GpuBuffer<u32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: i32,
        _: bool,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn ternary_gemm(
        &self,
        _: &GpuBuffer<u32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: i32,
        _: i32,
        _: bool,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    #[allow(clippy::too_many_arguments)]
    pub fn ternary_gemm_async(
        &self,
        _: &GpuBuffer<u32>,
        _: &GpuBuffer<f32>,
        _: &GpuBuffer<f32>,
        _: &mut GpuBuffer<f32>,
        _: i32,
        _: i32,
        _: i32,
        _: i32,
        _: bool,
    ) -> GpuResult<()> {
        Err(self.unavailable_error())
    }

    pub fn synchronize(&self) -> GpuResult<()> {
        Err(self.unavailable_error())
    }
}
impl Default for GpuAccelerator {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn context_api_reports_no_compute_capability() {
        let ctx = GpuContext;
        assert_eq!(ctx.compute_capability(), None);
    }

    // ── GpuError Display ────────────────────────────────────────────────────

    #[test]
    fn error_display_nogpu() {
        let err = GpuError::NoGpu;
        assert_eq!(
            err.to_string(),
            "No GPU available (built without `cuda` feature)"
        );
    }

    #[test]
    fn error_display_init_failed() {
        let err = GpuError::InitFailed("device busy".into());
        assert_eq!(err.to_string(), "GPU init failed: device busy");
    }

    #[test]
    fn error_display_module_load_failed() {
        let err = GpuError::ModuleLoadFailed("bad ptx".into());
        assert_eq!(err.to_string(), "PTX module load failed: bad ptx");
    }

    #[test]
    fn error_display_kernel_not_found() {
        let err = GpuError::KernelNotFound("foo_kernel".into());
        assert_eq!(err.to_string(), "Kernel not found: foo_kernel");
    }

    #[test]
    fn error_display_memory_error() {
        let err = GpuError::MemoryError("OOM".into());
        assert_eq!(err.to_string(), "GPU memory error: OOM");
    }

    #[test]
    fn error_display_launch_failed() {
        let err = GpuError::LaunchFailed("grid too large".into());
        assert_eq!(err.to_string(), "Kernel launch failed: grid too large");
    }

    #[test]
    fn error_display_cuda_error() {
        let err = GpuError::CudaError("illegal memory".into());
        assert_eq!(err.to_string(), "CUDA error: illegal memory");
    }

    #[test]
    fn error_display_unavailable() {
        let err = GpuError::unavailable(
            FallbackReason::CudaFeatureNotBuilt,
            "crate built without the cuda feature",
        );
        assert_eq!(
            err.to_string(),
            "GPU unavailable (cuda_feature_not_built): crate built without the cuda feature"
        );
    }

    #[test]
    fn error_display_invalid_input() {
        let err = GpuError::invalid_input("n_vars must be >= 0, got -1");
        assert_eq!(
            err.to_string(),
            "invalid input: n_vars must be >= 0, got -1"
        );
    }

    #[test]
    fn error_is_std_error() {
        let err: &dyn std::error::Error = &GpuError::NoGpu;
        assert!(!err.to_string().is_empty());
    }

    // ── GpuContext ──────────────────────────────────────────────────────────

    #[test]
    fn context_init_returns_no_gpu() {
        let result = GpuContext::init();
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), GpuError::NoGpu));
    }

    #[test]
    fn context_is_available_returns_false() {
        assert!(!GpuContext::is_available());
    }

    // ── KernelModule ────────────────────────────────────────────────────────

    #[test]
    fn kernel_module_load_returns_no_gpu() {
        let result = KernelModule::load();
        assert!(matches!(result.unwrap_err(), GpuError::NoGpu));
    }

    #[test]
    fn kernel_module_load_satsolver_returns_no_gpu() {
        let result = KernelModule::load_satsolver();
        assert!(matches!(result.unwrap_err(), GpuError::NoGpu));
    }

    // ── GpuBuffer ───────────────────────────────────────────────────────────

    #[test]
    fn buffer_alloc_zero_length() {
        let buf = GpuBuffer::<u8>::alloc(0).unwrap();
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn buffer_alloc_u8() {
        let buf = GpuBuffer::<u8>::alloc(100).unwrap();
        assert_eq!(buf.len(), 100);
        let data = buf.to_vec().unwrap();
        assert_eq!(data, vec![0u8; 100]);
    }

    #[test]
    fn buffer_alloc_f32() {
        let buf = GpuBuffer::<f32>::alloc(64).unwrap();
        assert_eq!(buf.len(), 64);
        let data = buf.to_vec().unwrap();
        assert!(data.iter().all(|&v| v == 0.0f32));
    }

    /// Oversized requests return `MemoryError` instead of panicking (GH #48),
    /// mirroring the CUDA backend. All cases fail checked arithmetic before
    /// any physical allocation.
    #[test]
    fn buffer_alloc_overflow_returns_memory_error() {
        // u64: `8 * len` overflows `usize` / exceeds the `isize::MAX` ceiling.
        for len in [usize::MAX, isize::MAX as usize] {
            assert_alloc_overflow::<u64>(len);
        }
        // u8: one byte per element, so `usize::MAX` / past-ceiling byte counts.
        for len in [usize::MAX, isize::MAX as usize + 1] {
            assert_alloc_overflow::<u8>(len);
        }
        // Wide element type: overflow with a smaller element count.
        assert_alloc_overflow::<Wide512>(usize::MAX);
    }

    /// Assert an oversized `alloc` fails with the overflow `MemoryError`.
    fn assert_alloc_overflow<T: Default + Clone>(len: usize) {
        match GpuBuffer::<T>::alloc(len) {
            Err(GpuError::MemoryError(msg)) => {
                assert!(msg.contains("size overflow"), "msg: {msg}")
            }
            Err(other) => panic!("expected MemoryError, got {other}"),
            Ok(_) => panic!("oversized alloc unexpectedly succeeded"),
        }
    }

    /// 4 KiB element used to probe overflow with a wide element size.
    #[derive(Clone)]
    struct Wide512 {
        _payload: [u64; 512],
    }

    impl Default for Wide512 {
        fn default() -> Self {
            Self {
                _payload: [0u64; 512],
            }
        }
    }

    /// Zero-sized types allocate without bytes; zero and ordinary lengths work.
    #[test]
    fn buffer_alloc_zero_sized_type() {
        let empty = GpuBuffer::<()>::alloc(0).unwrap();
        assert_eq!(empty.len(), 0);
        assert!(empty.to_vec().unwrap().is_empty());
        let buf = GpuBuffer::<()>::alloc(8).unwrap();
        assert_eq!(buf.len(), 8);
        assert_eq!(buf.to_vec().unwrap(), vec![(); 8]);
    }

    #[test]
    fn buffer_from_slice_roundtrip() {
        let input = vec![1i32, 2, 3, 4, 5];
        let buf = GpuBuffer::from_slice(&input).unwrap();
        assert_eq!(buf.len(), 5);
        let output = buf.to_vec().unwrap();
        assert_eq!(input, output);
    }

    #[test]
    fn buffer_from_slice_empty() {
        let buf = GpuBuffer::<u8>::from_slice(&[]).unwrap();
        assert_eq!(buf.len(), 0);
    }

    #[test]
    fn buffer_upload_ok() {
        let mut buf = GpuBuffer::<i32>::alloc(4).unwrap();
        buf.upload(&[10, 20, 30, 40]).unwrap();
        assert_eq!(buf.to_vec().unwrap(), vec![10, 20, 30, 40]);
    }

    #[test]
    fn buffer_upload_length_mismatch() {
        let mut buf = GpuBuffer::<i32>::alloc(4).unwrap();
        let result = buf.upload(&[1, 2]);
        assert!(result.is_err());
        match result.unwrap_err() {
            GpuError::MemoryError(msg) => {
                assert!(msg.contains("length mismatch"));
                assert!(msg.contains("4"));
                assert!(msg.contains("2"));
            }
            other => panic!("expected MemoryError, got: {other}"),
        }
    }

    // ── LIM-1302 buffer-contract regression (CPU stub) ──────────────────────

    /// Assert `err` is the length-mismatch `MemoryError` naming both lengths.
    fn assert_length_mismatch(err: GpuError, buffer_len: usize, input_len: usize) {
        match err {
            GpuError::MemoryError(msg) => {
                assert!(msg.contains("length mismatch"), "msg: {msg}");
                assert!(
                    msg.contains(&format!("buffer has {buffer_len} elements")),
                    "msg: {msg}"
                );
                assert!(
                    msg.contains(&format!("input has {input_len}")),
                    "msg: {msg}"
                );
            }
            other => panic!("expected MemoryError, got {other}"),
        }
    }

    /// Allocation lengths 0, 1, and representative boundary sizes all read back
    /// as `T::default()` immediately after `alloc`, with no prior upload.
    #[test]
    fn buffer_alloc_boundary_lengths_read_back_default() {
        for len in [0usize, 1, 2, 15, 16, 17, 256, 257, 4096] {
            let buf = GpuBuffer::<i32>::alloc(len).unwrap();
            assert_eq!(buf.len(), len, "len {len}");
            assert_eq!(buf.is_empty(), len == 0, "is_empty at len {len}");
            assert_eq!(
                buf.to_vec().unwrap(),
                vec![0i32; len],
                "readback at len {len}"
            );
        }
    }

    /// `from_slice` then `to_vec` round-trips exact values across boundary sizes.
    #[test]
    fn buffer_from_slice_to_vec_roundtrip_boundaries() {
        for len in [0usize, 1, 16, 17, 128, 257] {
            let input: Vec<u32> = (0..len as u32)
                .map(|i| i.wrapping_mul(2_654_435_761))
                .collect();
            let buf = GpuBuffer::from_slice(&input).unwrap();
            assert_eq!(buf.to_vec().unwrap(), input, "roundtrip at len {len}");
        }
    }

    /// An equal-length upload replaces every element.
    #[test]
    fn buffer_upload_equal_length_replaces_all() {
        let mut buf = GpuBuffer::from_slice(&[9i32, 9, 9, 9]).unwrap();
        buf.upload(&[1, 2, 3, 4]).unwrap();
        assert_eq!(buf.to_vec().unwrap(), vec![1, 2, 3, 4]);
    }

    /// A too-short upload is rejected and leaves existing contents unchanged;
    /// the error payload names both the buffer and input lengths.
    #[test]
    fn buffer_upload_too_short_rejected_and_non_mutating() {
        let mut buf = GpuBuffer::from_slice(&[1i32, 2, 3, 4]).unwrap();
        assert_length_mismatch(buf.upload(&[7, 8]).unwrap_err(), 4, 2);
        assert_eq!(buf.to_vec().unwrap(), vec![1, 2, 3, 4], "contents mutated");
    }

    /// A too-long upload is rejected and leaves existing contents unchanged.
    #[test]
    fn buffer_upload_too_long_rejected_and_non_mutating() {
        let mut buf = GpuBuffer::from_slice(&[1i32, 2, 3, 4]).unwrap();
        assert_length_mismatch(buf.upload(&[7, 8, 9, 10, 11]).unwrap_err(), 4, 5);
        assert_eq!(buf.to_vec().unwrap(), vec![1, 2, 3, 4], "contents mutated");
    }

    /// Empty-to-empty upload succeeds as a no-op.
    #[test]
    fn buffer_upload_empty_into_empty_ok() {
        let mut buf = GpuBuffer::<i32>::alloc(0).unwrap();
        buf.upload(&[]).unwrap();
        assert!(buf.to_vec().unwrap().is_empty());
    }

    /// Empty/nonempty length mismatches fail in both directions.
    #[test]
    fn buffer_upload_empty_nonempty_mismatches_fail() {
        let mut empty = GpuBuffer::<i32>::alloc(0).unwrap();
        assert_length_mismatch(empty.upload(&[1]).unwrap_err(), 0, 1);

        let mut nonempty = GpuBuffer::<i32>::alloc(3).unwrap();
        assert_length_mismatch(nonempty.upload(&[]).unwrap_err(), 3, 0);
    }

    #[test]
    fn buffer_zero_prefix_preserves_tail() {
        let mut buf = GpuBuffer::<f32>::from_slice(&[1.0, 2.0, 3.0, 4.0]).unwrap();
        buf.zero_prefix(2).unwrap();
        assert_eq!(buf.to_vec().unwrap(), vec![0.0, 0.0, 3.0, 4.0]);
    }

    #[test]
    fn buffer_zero_prefix_rejects_oversize() {
        let mut buf = GpuBuffer::<f32>::from_slice(&[1.0, 2.0]).unwrap();
        let err = buf.zero_prefix(3).unwrap_err();
        match err {
            GpuError::MemoryError(msg) => assert!(msg.contains("zero_prefix")),
            other => panic!("expected MemoryError, got {other}"),
        }
        assert_eq!(buf.to_vec().unwrap(), vec![1.0, 2.0]);
    }

    #[test]
    fn buffer_as_device_ptr_non_null() {
        let buf = GpuBuffer::<u8>::alloc(16).unwrap();
        let ptr = buf.as_device_ptr();
        assert!(!ptr.is_null());
    }

    // ── GpuAccelerator ──────────────────────────────────────────────────────

    #[test]
    fn accelerator_new() {
        let acc = GpuAccelerator::new();
        assert!(!acc.is_ready());
        assert_eq!(acc.selected_backend(), Backend::Cpu);
        let fb = acc.fallback().expect("CPU stub records a fallback");
        assert_eq!(fb.reason, FallbackReason::CudaFeatureNotBuilt);
        assert_eq!(fb.selected_backend, Backend::Cpu);
        assert!(!fb.detail.contains("/home/"));
        assert!(!acc.capabilities().cuda_built);
    }

    #[test]
    fn accelerator_default() {
        let acc = GpuAccelerator::default();
        assert!(!acc.is_ready());
    }

    #[test]
    fn accelerator_require_gpu_fails_closed() {
        let err = match GpuAccelerator::require_gpu() {
            Err(e) => e,
            Ok(_) => panic!("require_gpu must fail on the CPU stub"),
        };
        assert_eq!(
            err.fallback_reason(),
            Some(FallbackReason::CudaFeatureNotBuilt)
        );
        match err {
            GpuError::Unavailable { reason, detail } => {
                assert_eq!(reason, FallbackReason::CudaFeatureNotBuilt);
                assert!(!detail.contains("/home/"));
            }
            other => panic!("expected Unavailable, got {other}"),
        }
    }

    #[test]
    fn accelerator_with_policy_prefer_gpu_is_cpu() {
        let acc = GpuAccelerator::with_policy(ExecutionPolicy::PreferGpu).unwrap();
        assert_eq!(acc.selected_backend(), Backend::Cpu);
        assert!(!acc.is_ready());
    }

    #[test]
    fn accelerator_kernels_returns_unavailable() {
        let acc = GpuAccelerator::new();
        assert_unavailable_not_built(acc.kernels().unwrap_err());
    }

    #[test]
    fn accelerator_synchronize_returns_unavailable() {
        let acc = GpuAccelerator::new();
        assert_unavailable_not_built(acc.synchronize().unwrap_err());
    }

    fn assert_unavailable_not_built(err: GpuError) {
        match err {
            GpuError::Unavailable { reason, detail } => {
                assert_eq!(reason, FallbackReason::CudaFeatureNotBuilt);
                assert!(!detail.contains("/home/"));
                assert!(!detail.contains("/Users/"));
            }
            other => panic!("expected Unavailable(cuda_feature_not_built), got {other}"),
        }
    }

    #[test]
    fn accelerator_satsolver_extract_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let assignment = GpuBuffer::<u8>::alloc(10).unwrap();
        let best_walker = GpuBuffer::<i32>::alloc(1).unwrap();
        let mut output = GpuBuffer::<u8>::alloc(10).unwrap();
        assert_unavailable_not_built(
            acc.satsolver_extract(&assignment, &best_walker, &mut output, 10, 1)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_poisson_encode_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let stimuli = GpuBuffer::<f32>::alloc(10).unwrap();
        let mut spikes = GpuBuffer::<u32>::alloc(10).unwrap();
        assert_unavailable_not_built(acc.poisson_encode(&stimuli, &mut spikes, 42).unwrap_err());
    }

    #[test]
    fn accelerator_satsolver_extract_async_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let assignment = GpuBuffer::<u8>::alloc(10).unwrap();
        let best_walker = GpuBuffer::<i32>::alloc(1).unwrap();
        let mut output = GpuBuffer::<u8>::alloc(10).unwrap();
        assert_unavailable_not_built(
            acc.satsolver_extract_async(&assignment, &best_walker, &mut output, 10, 1)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_poisson_encode_async_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let stimuli = GpuBuffer::<f32>::alloc(10).unwrap();
        let mut spikes = GpuBuffer::<u32>::alloc(10).unwrap();
        assert_unavailable_not_built(
            acc.poisson_encode_async(&stimuli, &mut spikes, 42)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_ternary_gemv_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let w = GpuBuffer::<u32>::alloc(1).unwrap();
        let s = GpuBuffer::<f32>::alloc(1).unwrap();
        let x = GpuBuffer::<f32>::alloc(1).unwrap();
        let mut y = GpuBuffer::<f32>::alloc(1).unwrap();
        assert_unavailable_not_built(
            acc.ternary_gemv(&w, &s, &x, &mut y, 1, 1, 1, false)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_ternary_gemm_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let w = GpuBuffer::<u32>::alloc(1).unwrap();
        let s = GpuBuffer::<f32>::alloc(1).unwrap();
        let b = GpuBuffer::<f32>::alloc(1).unwrap();
        let mut c = GpuBuffer::<f32>::alloc(1).unwrap();
        assert_unavailable_not_built(
            acc.ternary_gemm(&w, &s, &b, &mut c, 1, 1, 1, 1, false)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_ternary_gemv_async_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let w = GpuBuffer::<u32>::alloc(1).unwrap();
        let s = GpuBuffer::<f32>::alloc(1).unwrap();
        let x = GpuBuffer::<f32>::alloc(1).unwrap();
        let mut y = GpuBuffer::<f32>::alloc(1).unwrap();
        assert_unavailable_not_built(
            acc.ternary_gemv_async(&w, &s, &x, &mut y, 1, 1, 1, false)
                .unwrap_err(),
        );
    }

    #[test]
    fn accelerator_ternary_gemm_async_returns_unavailable() {
        let acc = GpuAccelerator::new();
        let w = GpuBuffer::<u32>::alloc(1).unwrap();
        let s = GpuBuffer::<f32>::alloc(1).unwrap();
        let b = GpuBuffer::<f32>::alloc(1).unwrap();
        let mut c = GpuBuffer::<f32>::alloc(1).unwrap();
        assert_unavailable_not_built(
            acc.ternary_gemm_async(&w, &s, &b, &mut c, 1, 1, 1, 1, false)
                .unwrap_err(),
        );
    }

    // ── Property-based tests ────────────────────────────────────────────────

    use proptest::prelude::*;

    proptest! {
        #[test]
        fn buffer_from_slice_roundtrip_prop(data in proptest::collection::vec(any::<i32>(), 0..=256)) {
            let buf = GpuBuffer::from_slice(&data).unwrap();
            prop_assert_eq!(buf.len(), data.len());
            prop_assert_eq!(buf.to_vec().unwrap(), data);
        }

        #[test]
        fn buffer_alloc_has_correct_len(n in 0usize..=1024) {
            let buf = GpuBuffer::<u8>::alloc(n).unwrap();
            prop_assert_eq!(buf.len(), n);
        }

        #[test]
        fn buffer_upload_roundtrip(
            // Use finite floats only — NaN != NaN breaks equality assertions.
            data in proptest::collection::vec(
                any::<f32>().prop_filter("finite", |v| v.is_finite()),
                1..=128
            )
        ) {
            let mut buf = GpuBuffer::<f32>::alloc(data.len()).unwrap();
            buf.upload(&data).unwrap();
            prop_assert_eq!(buf.to_vec().unwrap(), data);
        }
    }
}