physics_in_parallel 4.0.0-alpha.2

High-performance infrastructure for numerical simulations in physics
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
// src/math/tensor/rank_n/dense_rand.rs
/*!
Random filling for dense rank-N tensors.

`TensorRandFiller` owns a pool of RNG instances and splits tensor storage into
contiguous chunks during refresh. Seeded fillers are deterministic across
identical construction, RNG kind, and refresh sequences.

[`ResolvedRng`] carries the explicit seed and method used by every PiP
stochastic component. Fill partitioning is an implementation detail.

Supported element/distribution pairs:
    - `f64`: `Uniform`, `Normal`, `Bernoulli`;
    - `i64`: `UniformInt`, `Bernoulli`;
    - `usize`: `UniformInt`;
    - `isize`: `UniformInt`.

Indexed fillers additionally expose exact uniform `usize` index sampling over
`0..upper` for algorithms that select sites or storage positions directly.

`new` is the single fallible constructor for both stateful and indexed methods.
[`NUM_RNGS`] fixes deterministic random lanes for stateful methods. Parallelism
follows PiP's process-wide thread cap.
*/

use std::{error::Error, fmt};

use rand::SeedableRng;
use rand::rngs::SmallRng;
use rand_chacha::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng};
use rand_distr::{Bernoulli, Distribution, Normal, Uniform};
use rand_pcg::{Pcg64, Pcg64Mcg};
use rayon::prelude::*;

use crate::math::Tensor as UniversalTensor;
use crate::math::scalar::Scalar;
use crate::math::tensor::rank_n::dense::Tensor as DenseTensor;
use crate::rng::{IndexedRng, ResolvedRng, RngError, RngMethod};
use crate::threading::{parallel_chunk_len, random_lanes_per_job};

//===================================================================
// ---------------------------- Config ------------------------------
//===================================================================

/// Fixed deterministic RNG lane count used by stateful tensor fillers.
///
/// Execution parallelism is controlled independently, so changing a filler's
/// worker limit does not change the stateful random mapping.
pub const NUM_RNGS: usize = 32;

//===================================================================
// -------------------------- Basic Types ---------------------------
//===================================================================

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RandType {
    Uniform { low: f64, high: f64 },    // floats: [low, high)
    UniformInt { low: i64, high: i64 }, // ints:   [low, high]
    Normal { mean: f64, std: f64 },
    Bernoulli { p: f64 },
}

impl RandType {
    #[inline]
    fn name(self) -> &'static str {
        match self {
            Self::Uniform { .. } => "Uniform",
            Self::UniformInt { .. } => "UniformInt",
            Self::Normal { .. } => "Normal",
            Self::Bernoulli { .. } => "Bernoulli",
        }
    }
}

/// Invalid tensor random-filler configuration or distribution.
#[derive(Debug, Clone, PartialEq)]
pub enum TensorRandError {
    Rng(RngError),
    UnsupportedDistribution {
        scalar: &'static str,
        distribution: &'static str,
    },
    InvalidUniformBounds {
        low: f64,
        high: f64,
    },
    InvalidNormalStd {
        std: f64,
    },
    InvalidBernoulliProbability {
        p: f64,
    },
    InvalidUniformIntBounds {
        low: i64,
        high: i64,
    },
    InvalidIndexUpperBound,
    IntegerBoundsOutOfRange {
        scalar: &'static str,
        low: i64,
        high: i64,
    },
    IndexedStepRequired,
    StatefulMethodDoesNotSupportIndexedFill,
}

impl fmt::Display for TensorRandError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rng(error) => error.fmt(formatter),
            Self::UnsupportedDistribution {
                scalar,
                distribution,
            } => write!(
                formatter,
                "distribution {distribution} is not supported for scalar {scalar}"
            ),
            Self::InvalidUniformBounds { low, high } => write!(
                formatter,
                "uniform bounds must be finite with low < high; got low={low}, high={high}"
            ),
            Self::InvalidNormalStd { std } => {
                write!(
                    formatter,
                    "normal standard deviation must be finite and nonnegative; got {std}"
                )
            }
            Self::InvalidBernoulliProbability { p } => write!(
                formatter,
                "Bernoulli probability must be finite and in [0, 1]; got {p}"
            ),
            Self::InvalidUniformIntBounds { low, high } => write!(
                formatter,
                "integer uniform bounds require low <= high; got low={low}, high={high}"
            ),
            Self::InvalidIndexUpperBound => {
                write!(formatter, "uniform index upper bound must be positive")
            }
            Self::IntegerBoundsOutOfRange { scalar, low, high } => write!(
                formatter,
                "integer uniform bounds [{low}, {high}] are outside scalar {scalar}"
            ),
            Self::IndexedStepRequired => write!(
                formatter,
                "indexed tensor random fillers require an explicit step and domain"
            ),
            Self::StatefulMethodDoesNotSupportIndexedFill => write!(
                formatter,
                "stateful tensor random fillers do not support explicit indexed fills"
            ),
        }
    }
}

impl Error for TensorRandError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Rng(error) => Some(error),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct TensorRandFiller {
    kind: RandType,
    rng: ResolvedRng,
    num_rngs: usize,
    rngs: Vec<TensorRng>,
    indexed: Option<IndexedRng>,
}

impl TensorRandFiller {
    /// Constructs a filler from explicit, fully resolved randomness.
    pub fn new(kind: RandType, rng: ResolvedRng) -> Result<Self, TensorRandError> {
        if rng.method() == RngMethod::IndexedSplitMix64 {
            return Ok(Self {
                kind,
                rng,
                num_rngs: NUM_RNGS,
                rngs: Vec::new(),
                indexed: Some(IndexedRng::new(rng).map_err(TensorRandError::Rng)?),
            });
        }
        let rng = rng
            .ensure_supported(
                "TensorRandFiller",
                &[
                    RngMethod::Pcg64,
                    RngMethod::Pcg64Mcg,
                    RngMethod::SmallRng,
                    RngMethod::ChaCha8,
                    RngMethod::ChaCha12,
                    RngMethod::ChaCha20,
                ],
            )
            .map_err(TensorRandError::Rng)?;
        let req = NUM_RNGS;
        let rng_method = rng.method();
        let seed = rng.seed();
        let mut master = SmallRng::seed_from_u64(seed);
        Ok(Self::from_master_rng(
            kind,
            rng,
            rng_method,
            req,
            &mut master,
        ))
    }

    fn from_master_rng(
        kind: RandType,
        rng: ResolvedRng,
        rng_method: RngMethod,
        num_rngs: usize,
        master: &mut SmallRng,
    ) -> Self {
        let mut rngs: Vec<TensorRng> = (0..num_rngs)
            .map(|_| TensorRng::from_master(rng_method, master))
            .collect();
        rngs.shrink_to_fit();
        Self {
            kind,
            rng,
            num_rngs,
            rngs,
            indexed: None,
        }
    }

    #[inline]
    fn active_slices(&self, n: usize) -> usize {
        if n == 0 { 0 } else { self.num_rngs.min(n) }
    }

    #[inline]
    fn chunk_len(&self, n: usize, slices: usize) -> usize {
        if n == 0 || slices == 0 {
            0
        } else {
            n.div_ceil(slices)
        }
    }

    #[inline]
    fn chunk_plan(&self, n: usize) -> Option<(usize, usize)> {
        let slices = self.active_slices(n);
        if slices == 0 {
            None
        } else {
            Some((slices, self.chunk_len(n, slices)))
        }
    }

    #[inline]
    fn indexed_chunk_len(&self, n: usize) -> Option<usize> {
        parallel_chunk_len(n)
    }

    /// Refreshes tensor values in place.
    #[inline]
    pub fn fill<T: TensorRandElement>(
        &mut self,
        tensor: &mut UniversalTensor<T>,
    ) -> Result<(), TensorRandError> {
        if self.indexed.is_some() {
            return Err(TensorRandError::IndexedStepRequired);
        }
        let mut values = tensor.values().collect::<Vec<_>>();
        T::try_fill_slice(self, &mut values)?;
        tensor.replace_with_values(values);
        Ok(())
    }

    /// Fills a tensor reproducibly for an explicit indexed step and domain.
    ///
    /// This operation is available when the filler was constructed with
    /// [`RngMethod::IndexedSplitMix64`]. It retains the tensor's selected
    /// backend.
    pub fn fill_at<T: TensorRandElement>(
        &self,
        tensor: &mut UniversalTensor<T>,
        step: u64,
        domain: u64,
    ) -> Result<(), TensorRandError> {
        let mut values = tensor.values().collect::<Vec<_>>();
        self.try_fill_slice_at(&mut values, step, domain)?;
        tensor.replace_with_values(values);
        Ok(())
    }

    /// Fallibly fills a caller-owned contiguous slice in place.
    ///
    /// This uses the same distribution, RNG state, and parallel chunking as
    /// [`Self::fill`] without requiring a tensor wrapper.
    #[inline]
    pub(crate) fn try_fill_slice<T: TensorRandElement>(
        &mut self,
        values: &mut [T],
    ) -> Result<(), TensorRandError> {
        if self.indexed.is_some() {
            return Err(TensorRandError::IndexedStepRequired);
        }
        T::try_fill_slice(self, values)
    }

    /// Fills a slice reproducibly for an explicit step and random domain.
    ///
    /// Results do not depend on Rayon scheduling or this filler's worker limit.
    pub(crate) fn try_fill_slice_at<T: TensorRandElement>(
        &self,
        values: &mut [T],
        step: u64,
        domain: u64,
    ) -> Result<(), TensorRandError> {
        let Some(key) = self.indexed else {
            return Err(TensorRandError::StatefulMethodDoesNotSupportIndexedFill);
        };
        T::try_fill_slice_indexed(self, key, values, step, domain, 1)
    }

    /// Fills row-major values using `(row, component)` random coordinates.
    pub(crate) fn try_fill_slice_at_layout<T: TensorRandElement>(
        &self,
        values: &mut [T],
        components: usize,
        step: u64,
        domain: u64,
    ) -> Result<(), TensorRandError> {
        assert!(components > 0, "indexed fill components must be positive");
        let Some(key) = self.indexed else {
            return Err(TensorRandError::StatefulMethodDoesNotSupportIndexedFill);
        };
        T::try_fill_slice_indexed(self, key, values, step, domain, components)
    }

    /// Fills one short-lived operation with either its stateful stream or the
    /// supplied indexed domain at step zero.
    pub(crate) fn try_fill_slice_once<T: TensorRandElement>(
        &mut self,
        values: &mut [T],
        components: usize,
        domain: u64,
    ) -> Result<(), TensorRandError> {
        if self.indexed.is_some() {
            self.try_fill_slice_at_layout(values, components, 0, domain)
        } else {
            self.try_fill_slice(values)
        }
    }

    /// Fills exact uniform indices from `0..upper` for an explicit step.
    ///
    /// Sampling uses indexed Lemire rejection and is independent of Rayon
    /// scheduling. This operation is available only on indexed fillers and
    /// does not depend on the filler's scalar distribution.
    pub(crate) fn try_fill_indices_at(
        &self,
        values: &mut [usize],
        upper: usize,
        step: u64,
        domain: u64,
    ) -> Result<(), TensorRandError> {
        if upper == 0 {
            return Err(TensorRandError::InvalidIndexUpperBound);
        }
        let Some(key) = self.indexed else {
            return Err(TensorRandError::StatefulMethodDoesNotSupportIndexedFill);
        };
        let Some(chunk_len) = self.indexed_chunk_len(values.len()) else {
            return Ok(());
        };
        values
            .par_chunks_mut(chunk_len)
            .enumerate()
            .for_each(|(chunk_index, chunk)| {
                let start = chunk_index * chunk_len;
                for (offset, value) in chunk.iter_mut().enumerate() {
                    *value = key
                        .uniform_index(step, domain, (start + offset) as u64, 0, upper)
                        .expect("validated positive uniform-index upper bound");
                }
            });
        Ok(())
    }

    /// Samples two independent uniform indices per row and maps them directly
    /// into three caller-owned row-major buffers.
    ///
    /// This crate-internal bridge keeps indexed sampling inside the random
    /// backend while allowing consumers to assemble final records without
    /// allocating temporary index arrays.
    pub(crate) fn try_fill_index_pairs_with<T, F>(
        &self,
        buffers: (&mut [T], &mut [T], &mut [T]),
        components: usize,
        upper: usize,
        step: u64,
        domains: (u64, u64),
        map: F,
    ) -> Result<(), TensorRandError>
    where
        T: Send,
        F: Fn(usize, usize, &mut [T], &mut [T], &mut [T]) + Send + Sync,
    {
        let (first, second, third) = buffers;
        let (first_domain, second_domain) = domains;
        assert!(components > 0, "indexed pair components must be positive");
        assert_eq!(first.len(), second.len(), "indexed pair buffer mismatch");
        assert_eq!(first.len(), third.len(), "indexed pair buffer mismatch");
        assert_eq!(
            first.len() % components,
            0,
            "indexed pair buffers must contain complete rows"
        );
        if upper == 0 {
            return Err(TensorRandError::InvalidIndexUpperBound);
        }
        let Some(key) = self.indexed else {
            return Err(TensorRandError::StatefulMethodDoesNotSupportIndexedFill);
        };
        let rows = first.len() / components;
        let min_rows_per_job = self.indexed_chunk_len(rows).unwrap_or(1);
        first
            .par_chunks_mut(components)
            .zip(second.par_chunks_mut(components))
            .zip(third.par_chunks_mut(components))
            .with_min_len(min_rows_per_job)
            .enumerate()
            .for_each(|(row, ((first, second), third))| {
                let first_index = key
                    .uniform_index(step, first_domain, row as u64, 0, upper)
                    .expect("validated positive uniform-index upper bound");
                let second_index = key
                    .uniform_index(step, second_domain, row as u64, 0, upper)
                    .expect("validated positive uniform-index upper bound");
                map(first_index, second_index, first, second, third);
            });
        Ok(())
    }

    #[inline]
    pub fn kind(&self) -> &RandType {
        &self.kind
    }

    #[inline]
    pub fn set_kind(&mut self, kind: RandType) {
        self.kind = kind;
    }

    #[inline]
    pub fn resolved_rng(&self) -> ResolvedRng {
        self.rng
    }
}

fn unsupported<T: 'static>(kind: RandType) -> TensorRandError {
    TensorRandError::UnsupportedDistribution {
        scalar: core::any::type_name::<T>(),
        distribution: kind.name(),
    }
}

#[derive(Debug, Clone)]
enum TensorRng {
    SmallRng(SmallRng),
    Pcg64Mcg(Pcg64Mcg),
    Pcg64(Pcg64),
    ChaCha8(ChaCha8Rng),
    ChaCha12(ChaCha12Rng),
    ChaCha20(ChaCha20Rng),
}

impl TensorRng {
    fn from_master(kind: RngMethod, master: &mut SmallRng) -> Self {
        match kind {
            RngMethod::SmallRng => Self::SmallRng(SmallRng::from_rng(master)),
            RngMethod::Pcg64Mcg => Self::Pcg64Mcg(Pcg64Mcg::from_rng(master)),
            RngMethod::Pcg64 => Self::Pcg64(Pcg64::from_rng(master)),
            RngMethod::ChaCha8 => Self::ChaCha8(ChaCha8Rng::from_rng(master)),
            RngMethod::ChaCha12 => Self::ChaCha12(ChaCha12Rng::from_rng(master)),
            RngMethod::ChaCha20 => Self::ChaCha20(ChaCha20Rng::from_rng(master)),
            RngMethod::IndexedSplitMix64 => unreachable!("indexed RNG rejected during resolve"),
        }
    }

    fn fill_sample<T, D>(&mut self, chunk: &mut [T], dist: &D)
    where
        D: Distribution<T>,
    {
        match self {
            Self::SmallRng(rng) => fill_sample_with_rng(chunk, dist, rng),
            Self::Pcg64Mcg(rng) => fill_sample_with_rng(chunk, dist, rng),
            Self::Pcg64(rng) => fill_sample_with_rng(chunk, dist, rng),
            Self::ChaCha8(rng) => fill_sample_with_rng(chunk, dist, rng),
            Self::ChaCha12(rng) => fill_sample_with_rng(chunk, dist, rng),
            Self::ChaCha20(rng) => fill_sample_with_rng(chunk, dist, rng),
        }
    }

    fn fill_mapped_sample<T, S, D, F>(&mut self, chunk: &mut [T], dist: &D, map: F)
    where
        D: Distribution<S>,
        F: Fn(S) -> T + Copy,
    {
        match self {
            Self::SmallRng(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
            Self::Pcg64Mcg(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
            Self::Pcg64(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
            Self::ChaCha8(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
            Self::ChaCha12(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
            Self::ChaCha20(rng) => fill_mapped_sample_with_rng(chunk, dist, map, rng),
        }
    }
}

fn fill_sample_with_rng<T, D, R>(chunk: &mut [T], dist: &D, rng: &mut R)
where
    D: Distribution<T>,
    R: rand::Rng + ?Sized,
{
    for x in chunk {
        *x = dist.sample(rng);
    }
}

fn fill_mapped_sample_with_rng<T, S, D, F, R>(chunk: &mut [T], dist: &D, map: F, rng: &mut R)
where
    D: Distribution<S>,
    F: Fn(S) -> T + Copy,
    R: rand::Rng + ?Sized,
{
    for x in chunk {
        *x = map(dist.sample(rng));
    }
}

//===================================================================
// ------------- Sealed trait for per-type specialization -----------
//===================================================================

mod sealed {
    pub trait Sealed {}
    impl Sealed for f64 {}
    impl Sealed for i64 {}
    impl Sealed for usize {}
    impl Sealed for isize {}
}

pub trait TensorRandElement: sealed::Sealed + Sized + Scalar {
    fn try_fill_slice(
        filler: &mut TensorRandFiller,
        values: &mut [Self],
    ) -> Result<(), TensorRandError>;

    fn try_fill_slice_indexed(
        filler: &TensorRandFiller,
        key: IndexedRng,
        values: &mut [Self],
        step: u64,
        domain: u64,
        components: usize,
    ) -> Result<(), TensorRandError>;

    fn try_fill(
        filler: &mut TensorRandFiller,
        tensor: &mut DenseTensor<Self>,
    ) -> Result<(), TensorRandError> {
        Self::try_fill_slice(filler, tensor.data_mut())
    }

    #[inline]
    fn fill(filler: &mut TensorRandFiller, tensor: &mut DenseTensor<Self>) {
        Self::try_fill(filler, tensor).expect("invalid tensor random refresh configuration");
    }
}

// ---------------------------- f64 ---------------------------------
impl TensorRandElement for f64 {
    fn try_fill_slice_indexed(
        filler: &TensorRandFiller,
        key: IndexedRng,
        values: &mut [f64],
        step: u64,
        domain: u64,
        components: usize,
    ) -> Result<(), TensorRandError> {
        let Some(chunk_len) = filler.indexed_chunk_len(values.len()) else {
            return Ok(());
        };
        match filler.kind {
            RandType::Uniform { low, high } => {
                if !(low.is_finite() && high.is_finite() && low < high) {
                    return Err(TensorRandError::InvalidUniformBounds { low, high });
                }
                values
                    .par_chunks_mut(chunk_len)
                    .enumerate()
                    .for_each(|(chunk_index, chunk)| {
                        let start = chunk_index * chunk_len;
                        for (offset, value) in chunk.iter_mut().enumerate() {
                            let index = start + offset;
                            let unit = key.unit_f64(
                                step,
                                domain,
                                (index / components) as u64,
                                (index % components) as u64,
                                0,
                            );
                            *value = low + (high - low) * unit;
                        }
                    });
            }
            RandType::Normal { mean, std } => {
                if !(std.is_finite() && std >= 0.0) {
                    return Err(TensorRandError::InvalidNormalStd { std });
                }
                if std == 0.0 {
                    values
                        .par_chunks_mut(chunk_len)
                        .for_each(|chunk| chunk.fill(mean));
                    return Ok(());
                }
                values
                    .par_chunks_mut(chunk_len)
                    .enumerate()
                    .for_each(|(chunk_index, chunk)| {
                        let start = chunk_index * chunk_len;
                        for (offset, value) in chunk.iter_mut().enumerate() {
                            let index = start + offset;
                            *value = mean
                                + std
                                    * key.standard_normal(
                                        step,
                                        domain,
                                        (index / components) as u64,
                                        (index % components) as u64,
                                    );
                        }
                    });
            }
            RandType::Bernoulli { p } => {
                if !(p.is_finite() && (0.0..=1.0).contains(&p)) {
                    return Err(TensorRandError::InvalidBernoulliProbability { p });
                }
                values
                    .par_chunks_mut(chunk_len)
                    .enumerate()
                    .for_each(|(chunk_index, chunk)| {
                        let start = chunk_index * chunk_len;
                        for (offset, value) in chunk.iter_mut().enumerate() {
                            let index = start + offset;
                            *value = if key.unit_f64(
                                step,
                                domain,
                                (index / components) as u64,
                                (index % components) as u64,
                                0,
                            ) < p
                            {
                                1.0
                            } else {
                                0.0
                            };
                        }
                    });
            }
            kind => return Err(unsupported::<f64>(kind)),
        }
        Ok(())
    }

    fn try_fill_slice(
        filler: &mut TensorRandFiller,
        values: &mut [f64],
    ) -> Result<(), TensorRandError> {
        let Some((slices, chunk_len)) = filler.chunk_plan(values.len()) else {
            return Ok(());
        };
        let rngs = &mut filler.rngs[..slices];
        let lanes_per_job = random_lanes_per_job(slices);

        match filler.kind {
            RandType::Uniform { low, high } => {
                let dist = Uniform::new(low, high)
                    .map_err(|_| TensorRandError::InvalidUniformBounds { low, high })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| rng.fill_sample(chunk, &dist));
            }
            RandType::Normal { mean, std } => {
                if !(std.is_finite() && std >= 0.0) {
                    return Err(TensorRandError::InvalidNormalStd { std });
                }
                if std == 0.0 {
                    values
                        .par_chunks_mut(chunk_len)
                        .with_min_len(lanes_per_job)
                        .for_each(|chunk| chunk.fill(mean));
                    return Ok(());
                }
                let dist = Normal::new(mean, std)
                    .map_err(|_| TensorRandError::InvalidNormalStd { std })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| rng.fill_sample(chunk, &dist));
            }
            RandType::Bernoulli { p } => {
                let dist = Bernoulli::new(p)
                    .map_err(|_| TensorRandError::InvalidBernoulliProbability { p })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| {
                        rng.fill_mapped_sample(chunk, &dist, |x| if x { 1.0 } else { 0.0 })
                    });
            }
            kind => return Err(unsupported::<f64>(kind)),
        }

        Ok(())
    }
}

// ---------------------------- i64 ---------------------------------
impl TensorRandElement for i64 {
    fn try_fill_slice_indexed(
        _filler: &TensorRandFiller,
        _key: IndexedRng,
        _values: &mut [i64],
        _step: u64,
        _domain: u64,
        _components: usize,
    ) -> Result<(), TensorRandError> {
        Err(TensorRandError::UnsupportedDistribution {
            scalar: "i64",
            distribution: "indexed",
        })
    }

    fn try_fill_slice(
        filler: &mut TensorRandFiller,
        values: &mut [i64],
    ) -> Result<(), TensorRandError> {
        let Some((slices, chunk_len)) = filler.chunk_plan(values.len()) else {
            return Ok(());
        };
        let rngs = &mut filler.rngs[..slices];
        let lanes_per_job = random_lanes_per_job(slices);

        match filler.kind {
            RandType::UniformInt { low, high } => {
                let dist = Uniform::new_inclusive(low, high)
                    .map_err(|_| TensorRandError::InvalidUniformIntBounds { low, high })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| rng.fill_sample(chunk, &dist));
            }
            RandType::Bernoulli { p } => {
                let dist = Bernoulli::new(p)
                    .map_err(|_| TensorRandError::InvalidBernoulliProbability { p })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| {
                        rng.fill_mapped_sample(chunk, &dist, |x| if x { 1 } else { 0 })
                    });
            }
            kind => return Err(unsupported::<i64>(kind)),
        }

        Ok(())
    }
}

// ---------------------------- usize -------------------------------
impl TensorRandElement for usize {
    fn try_fill_slice_indexed(
        _filler: &TensorRandFiller,
        _key: IndexedRng,
        _values: &mut [usize],
        _step: u64,
        _domain: u64,
        _components: usize,
    ) -> Result<(), TensorRandError> {
        Err(TensorRandError::UnsupportedDistribution {
            scalar: "usize",
            distribution: "indexed",
        })
    }

    fn try_fill_slice(
        filler: &mut TensorRandFiller,
        values: &mut [usize],
    ) -> Result<(), TensorRandError> {
        let Some((slices, chunk_len)) = filler.chunk_plan(values.len()) else {
            return Ok(());
        };
        let rngs = &mut filler.rngs[..slices];
        let lanes_per_job = random_lanes_per_job(slices);

        match filler.kind {
            RandType::UniformInt { low, high } => {
                let (low_u, high_u) = match (usize::try_from(low), usize::try_from(high)) {
                    (Ok(lo), Ok(hi)) if lo <= hi => (lo, hi),
                    _ => {
                        return Err(TensorRandError::IntegerBoundsOutOfRange {
                            scalar: "usize",
                            low,
                            high,
                        });
                    }
                };
                let dist = Uniform::new_inclusive(low_u, high_u)
                    .map_err(|_| TensorRandError::InvalidUniformIntBounds { low, high })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| rng.fill_sample(chunk, &dist));
            }
            kind => return Err(unsupported::<usize>(kind)),
        }

        Ok(())
    }
}

// ---------------------------- isize -------------------------------
impl TensorRandElement for isize {
    fn try_fill_slice_indexed(
        _filler: &TensorRandFiller,
        _key: IndexedRng,
        _values: &mut [isize],
        _step: u64,
        _domain: u64,
        _components: usize,
    ) -> Result<(), TensorRandError> {
        Err(TensorRandError::UnsupportedDistribution {
            scalar: "isize",
            distribution: "indexed",
        })
    }

    fn try_fill_slice(
        filler: &mut TensorRandFiller,
        values: &mut [isize],
    ) -> Result<(), TensorRandError> {
        let Some((slices, chunk_len)) = filler.chunk_plan(values.len()) else {
            return Ok(());
        };
        let rngs = &mut filler.rngs[..slices];
        let lanes_per_job = random_lanes_per_job(slices);

        match filler.kind {
            RandType::UniformInt { low, high } => {
                if isize::try_from(low).is_err() || isize::try_from(high).is_err() {
                    return Err(TensorRandError::IntegerBoundsOutOfRange {
                        scalar: "isize",
                        low,
                        high,
                    });
                }
                let dist = Uniform::<i64>::new_inclusive(low, high)
                    .map_err(|_| TensorRandError::InvalidUniformIntBounds { low, high })?;
                values
                    .par_chunks_mut(chunk_len)
                    .zip(rngs.par_iter_mut())
                    .with_min_len(lanes_per_job)
                    .for_each(|(chunk, rng)| rng.fill_mapped_sample(chunk, &dist, |x| x as isize));
            }
            kind => return Err(unsupported::<isize>(kind)),
        }

        Ok(())
    }
}