incin-core 0.1.0

Core tensor operations and static shape checking for incin
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
//! Floating-point precision policies and loss scaling for mixed-precision training.

use crate::err::{Error, Result};
use crate::exec::{LayoutClass, MathMode};
use crate::shapes::Dyn;
use crate::shapes::error::OperationKind;
use crate::tensor::dtype::{BuiltinDType, ConstDType, DType, DTypeDescriptor, FloatDType};
use crate::tensor::dtype::{bf16, f16};

/// Role of precision choice being queried (compute or accumulator).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PrecisionRole {
    /// Element-wise computation precision.
    Compute,
    /// Reduction/matmul accumulation precision.
    Accumulator,
}

/// Loss scale state tracking current multiplier and overflow history.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LossScaleState {
    policy: LossScaling,
    scale: f32,
    steps_since_last_overflow: usize,
}

impl LossScaleState {
    /// Creates a new loss scale state initialized from policy.
    #[must_use]
    pub fn new(policy: LossScaling) -> Self {
        let scale = policy.initial_scale();
        Self {
            policy,
            scale,
            steps_since_last_overflow: 0,
        }
    }

    /// Returns the underlying loss scaling configuration policy.
    #[must_use]
    pub const fn policy(&self) -> LossScaling {
        self.policy
    }

    /// Returns the current scale factor.
    #[must_use]
    pub const fn scale(&self) -> f32 {
        self.scale
    }

    /// Returns the number of consecutive finite steps recorded since last overflow.
    #[must_use]
    pub const fn steps_since_last_overflow(&self) -> usize {
        self.steps_since_last_overflow
    }

    /// Updates dynamic loss scaling based on whether non-finite (NaN/Inf) values were found.
    pub fn update(&mut self, found_nan_or_inf: bool) {
        if let LossScaling::Dynamic {
            growth_factor,
            backoff_factor,
            growth_interval,
            ..
        } = self.policy
        {
            if found_nan_or_inf {
                self.scale = (self.scale * backoff_factor).max(1.0);
                self.steps_since_last_overflow = 0;
            } else {
                self.steps_since_last_overflow += 1;
                if self.steps_since_last_overflow >= growth_interval {
                    self.scale *= growth_factor;
                    self.steps_since_last_overflow = 0;
                }
            }
        }
    }

    /// Checks parameter gradients for non-finite values (NaN/Inf), unscales them in-place if all finite,
    /// and updates the loss scaling state machine.
    ///
    /// Returns `Ok(true)` if all gradients were finite and successfully unscaled (or scale is 1.0).
    /// Returns `Ok(false)` if non-finite gradients were found (overflow); gradients are NOT unscaled
    /// and the loss scale is backed off.
    pub fn unscale_and_update_vars<'a, B, K, I>(
        &mut self,
        vars: I,
        grads: &mut crate::autograd::Gradients<B>,
    ) -> Result<bool>
    where
        B: crate::tensor::backend::VariableBackend
            + crate::tensor::backend::AutogradBackend
            + crate::optim::OptimizerBackend<K>
            + crate::tensor::backend::HostReadback,
        K: ConstDType,
        I: IntoIterator<Item = &'a B::Var<K>>,
    {
        let mut found_nan_or_inf = false;
        let mut present = alloc::vec::Vec::new();

        for var in vars {
            let tensor = B::var_as_tensor::<K>(var)?;
            if let Some(grad) = B::get_grad::<K>(&tensor, grads.as_backend())? {
                let float_vals = B::float_to_vec1::<K>(&grad)?;
                if float_vals.iter().any(|v| !v.is_finite()) {
                    found_nan_or_inf = true;
                    break;
                }
                present.push((tensor, grad));
            }
        }

        // Captured before `update()` runs: the gradients just collected were
        // produced by a backward pass through a loss scaled by *this* value.
        // `update()` may grow `self.scale` for the *next* step right here
        // (once `steps_since_last_overflow` reaches the growth interval), and
        // unscaling by that new, larger value instead of the one actually
        // used would silently halve (or worse) this step's update on exactly
        // the step where growth triggers.
        let current_scale = self.scale();

        self.update(found_nan_or_inf);

        if found_nan_or_inf {
            return Ok(false);
        }

        if (current_scale - 1.0).abs() > f32::EPSILON {
            let inv_scale = 1.0 / (current_scale as f64);
            for (tensor, grad) in present {
                let unscaled = B::optimizer_mul_scalar(&grad, inv_scale)?;
                B::set_grad::<K>(&tensor, grads.as_backend_mut(), unscaled)?;
            }
        }

        Ok(true)
    }
}

/// Loss scaling configuration for mixed-precision numerical stability.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub enum LossScaling {
    /// No loss scaling applied.
    #[default]
    None,
    /// Static loss scaling with a fixed multiplier.
    Static(f32),
    /// Dynamic loss scaling that adjusts based on non-finite gradient detection.
    Dynamic {
        /// Initial scale factor.
        initial_scale: f32,
        /// Factor by which to multiply scale when no non-finite gradients occur.
        growth_factor: f32,
        /// Factor by which to multiply scale when a non-finite gradient occurs.
        backoff_factor: f32,
        /// Number of consecutive finite steps required before growing scale.
        growth_interval: usize,
    },
}

impl LossScaling {
    /// Creates a static loss scaling policy.
    #[must_use]
    pub const fn static_scale(scale: f32) -> Self {
        Self::Static(scale)
    }

    /// Creates a dynamic loss scaling policy with recommended defaults.
    #[must_use]
    pub const fn dynamic_default() -> Self {
        Self::Dynamic {
            initial_scale: 65536.0,
            growth_factor: 2.0,
            backoff_factor: 0.5,
            growth_interval: 2000,
        }
    }

    /// Creates a custom dynamic loss scaling policy.
    #[must_use]
    pub const fn dynamic(
        initial_scale: f32,
        growth_factor: f32,
        backoff_factor: f32,
        growth_interval: usize,
    ) -> Self {
        Self::Dynamic {
            initial_scale,
            growth_factor,
            backoff_factor,
            growth_interval,
        }
    }

    /// Returns the initial scale factor.
    #[must_use]
    pub fn initial_scale(&self) -> f32 {
        match *self {
            Self::None => 1.0,
            Self::Static(scale) => scale,
            Self::Dynamic { initial_scale, .. } => initial_scale,
        }
    }
}

impl core::hash::Hash for LossScaling {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        core::mem::discriminant(self).hash(state);
        match *self {
            Self::None => {}
            Self::Static(s) => s.to_bits().hash(state),
            Self::Dynamic {
                initial_scale,
                growth_factor,
                backoff_factor,
                growth_interval,
            } => {
                initial_scale.to_bits().hash(state);
                growth_factor.to_bits().hash(state);
                backoff_factor.to_bits().hash(state);
                growth_interval.hash(state);
            }
        }
    }
}

impl Eq for LossScaling {}

/// Explicit precision choice for compute and accumulator attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum PrecisionChoice {
    /// Use the backend's truthful native arithmetic.
    #[default]
    Native,
    /// Require exact DTypeDescriptor for this role.
    Exact(DTypeDescriptor),
}

/// Immutable runtime precision policy governing datatype defaults and choices.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RuntimePrecisionPolicy {
    pub(crate) generated: DTypeDescriptor,
    pub(crate) parameter: DTypeDescriptor,
    pub(crate) active_dtype: Option<DTypeDescriptor>,
    pub(crate) compute: PrecisionChoice,
    pub(crate) accumulator: PrecisionChoice,
    pub(crate) loss_scaling: LossScaling,
}

impl core::default::Default for RuntimePrecisionPolicy {
    fn default() -> Self {
        Self::fp32()
    }
}

impl RuntimePrecisionPolicy {
    /// Standard full-precision float32 policy.
    #[must_use]
    pub const fn fp32() -> Self {
        Self {
            generated: <f32 as ConstDType>::DESCRIPTOR,
            parameter: <f32 as ConstDType>::DESCRIPTOR,
            active_dtype: None,
            compute: PrecisionChoice::Native,
            accumulator: PrecisionChoice::Native,
            loss_scaling: LossScaling::None,
        }
    }

    /// Standard double-precision float64 policy.
    #[must_use]
    pub const fn fp64() -> Self {
        Self::exact_dtype(<f64 as ConstDType>::DESCRIPTOR)
    }

    /// Policy requiring exact dtype descriptor for all operations.
    #[must_use]
    pub const fn exact_dtype(dtype: DTypeDescriptor) -> Self {
        Self {
            generated: dtype,
            parameter: dtype,
            active_dtype: Some(dtype),
            compute: PrecisionChoice::Exact(dtype),
            accumulator: PrecisionChoice::Exact(dtype),
            loss_scaling: LossScaling::None,
        }
    }

    /// Policy requiring exact float dtype `K`.
    pub fn exact<K: ConstDType + FloatDType>() -> Self {
        Self::exact_dtype(K::DESCRIPTOR)
    }

    /// Mixed-precision float16 policy.
    #[must_use]
    pub const fn mixed_f16() -> Self {
        Self {
            generated: <f16 as ConstDType>::DESCRIPTOR,
            parameter: <f16 as ConstDType>::DESCRIPTOR,
            active_dtype: Some(<f16 as ConstDType>::DESCRIPTOR),
            compute: PrecisionChoice::Native,
            accumulator: PrecisionChoice::Exact(<f32 as ConstDType>::DESCRIPTOR),
            loss_scaling: LossScaling::dynamic_default(),
        }
    }

    /// Mixed-precision bfloat16 policy.
    #[must_use]
    pub const fn mixed_bf16() -> Self {
        Self {
            generated: <bf16 as ConstDType>::DESCRIPTOR,
            parameter: <bf16 as ConstDType>::DESCRIPTOR,
            active_dtype: Some(<bf16 as ConstDType>::DESCRIPTOR),
            compute: PrecisionChoice::Native,
            accumulator: PrecisionChoice::Exact(<f32 as ConstDType>::DESCRIPTOR),
            loss_scaling: LossScaling::None,
        }
    }

    /// Returns generated tensor default dtype descriptor.
    #[must_use]
    pub const fn generated(&self) -> DTypeDescriptor {
        self.generated
    }

    /// Returns parameter default dtype descriptor.
    #[must_use]
    pub const fn parameter(&self) -> DTypeDescriptor {
        self.parameter
    }

    /// Returns the target active dtype descriptor if constrained to a specific storage dtype.
    pub const fn active_dtype(&self) -> Option<DTypeDescriptor> {
        self.active_dtype
    }

    /// Returns compute precision choice.
    #[must_use]
    pub const fn compute(&self) -> PrecisionChoice {
        self.compute
    }

    /// Returns accumulator precision choice.
    #[must_use]
    pub const fn accumulator(&self) -> PrecisionChoice {
        self.accumulator
    }

    /// Returns loss scaling configuration.
    #[must_use]
    pub const fn loss_scaling(&self) -> LossScaling {
        self.loss_scaling
    }

    /// Sets compute precision choice.
    #[must_use]
    pub const fn with_compute(mut self, compute: PrecisionChoice) -> Self {
        self.compute = compute;
        self
    }

    /// Sets accumulator precision choice.
    #[must_use]
    pub const fn with_accumulator(mut self, accumulator: PrecisionChoice) -> Self {
        self.accumulator = accumulator;
        self
    }
}

/// Precision request passed during operation resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PrecisionRequest {
    /// Operation the decision was made for.
    pub operation: OperationKind,
    /// Storage dtype of the inputs.
    pub storage: DTypeDescriptor,
    /// Dtype produced.
    pub output: DTypeDescriptor,
    /// Layout class observed.
    pub layout: LayoutClass,
    /// Rank observed.
    pub rank: usize,
    /// Training flag observed.
    pub training: bool,
    /// Math mode observed.
    pub math_mode: MathMode,
}

impl PrecisionRequest {
    /// Creates a precision request for an operation.
    #[must_use]
    pub const fn new(
        operation: OperationKind,
        storage: DTypeDescriptor,
        output: DTypeDescriptor,
        layout: LayoutClass,
        rank: usize,
        training: bool,
        math_mode: MathMode,
    ) -> Self {
        Self {
            operation,
            storage,
            output,
            layout,
            rank,
            training,
            math_mode,
        }
    }
}

impl core::default::Default for PrecisionRequest {
    fn default() -> Self {
        Self {
            operation: OperationKind::Pointwise,
            storage: <f32 as ConstDType>::DESCRIPTOR,
            output: <f32 as ConstDType>::DESCRIPTOR,
            layout: LayoutClass::Contiguous,
            rank: 1,
            training: false,
            math_mode: MathMode::Fast,
        }
    }
}

/// Concrete resolved data types for storage, compute, accumulation, and output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ResolvedPrecision {
    /// Storage dtype of the inputs.
    pub storage: DTypeDescriptor,
    /// Dtype kernels compute in.
    pub compute: DTypeDescriptor,
    /// Dtype reductions accumulate in.
    pub accumulator: DTypeDescriptor,
    /// Dtype produced.
    pub output: DTypeDescriptor,
    /// Loss-scaling configuration applied around losses.
    pub loss_scaling: LossScaling,
}

impl ResolvedPrecision {
    /// Creates a resolved precision contract.
    #[must_use]
    pub const fn new(
        storage: DTypeDescriptor,
        compute: DTypeDescriptor,
        accumulator: DTypeDescriptor,
        output: DTypeDescriptor,
        loss_scaling: LossScaling,
    ) -> Self {
        Self {
            storage,
            compute,
            accumulator,
            output,
            loss_scaling,
        }
    }

    /// Storage dtype descriptor.
    #[must_use]
    pub const fn storage(&self) -> DTypeDescriptor {
        self.storage
    }

    /// Compute dtype descriptor.
    #[must_use]
    pub const fn compute(&self) -> DTypeDescriptor {
        self.compute
    }

    /// Accumulator dtype descriptor.
    #[must_use]
    pub const fn accumulator(&self) -> DTypeDescriptor {
        self.accumulator
    }

    /// Output dtype descriptor.
    #[must_use]
    pub const fn output(&self) -> DTypeDescriptor {
        self.output
    }

    /// Loss scaling configuration.
    #[must_use]
    pub const fn loss_scaling(&self) -> LossScaling {
        self.loss_scaling
    }
}

/// Trait implemented by concrete backends to describe native arithmetic capabilities.
pub trait PrecisionCapabilities {
    /// Queries the backend's truthful native precision for `request`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::UnsupportedDType`] if the storage dtype is not supported.
    fn native_precision(&self, request: &PrecisionRequest) -> Result<ResolvedPrecision>;
}

/// Authoritative resolver applying a precision policy against backend capabilities.
///
/// # Errors
///
/// Returns [`Error::UnsupportedPrecision`] if an `Exact` choice cannot be honored,
/// or [`Error::UnsupportedDType`] if the storage dtype is unsupported.
pub fn resolve_precision<B>(
    backend: &B,
    policy: RuntimePrecisionPolicy,
    request: &PrecisionRequest,
) -> Result<ResolvedPrecision>
where
    B: PrecisionCapabilities + ?Sized,
{
    let native = backend.native_precision(request)?;

    if let Some(active) = policy.active_dtype
        && request.storage != active
    {
        return Ok(ResolvedPrecision {
            storage: request.storage,
            compute: native.compute,
            accumulator: native.accumulator,
            output: request.output,
            loss_scaling: LossScaling::None,
        });
    }

    let compute = match policy.compute {
        PrecisionChoice::Native => native.compute,
        PrecisionChoice::Exact(k) => {
            if native.compute == k {
                k
            } else {
                return Err(Error::UnsupportedPrecision {
                    operation: request.operation,
                    storage: request.storage,
                    requested: k,
                    role: PrecisionRole::Compute,
                    backend: core::any::type_name::<B>(),
                });
            }
        }
    };

    let accumulator = match policy.accumulator {
        PrecisionChoice::Native => native.accumulator,
        PrecisionChoice::Exact(k) => {
            if native.accumulator == k {
                k
            } else {
                return Err(Error::UnsupportedPrecision {
                    operation: request.operation,
                    storage: request.storage,
                    requested: k,
                    role: PrecisionRole::Accumulator,
                    backend: core::any::type_name::<B>(),
                });
            }
        }
    };

    let loss_scaling = match policy.active_dtype {
        Some(active) if request.storage == active => policy.loss_scaling,
        None => policy.loss_scaling,
        Some(_) => LossScaling::None,
    };

    Ok(ResolvedPrecision {
        storage: request.storage,
        compute,
        accumulator,
        output: request.output,
        loss_scaling,
    })
}

/// Type-level precision specification trait for targets.
pub trait PrecisionSpec:
    'static + Send + Sync + Copy + core::fmt::Debug + Eq + PartialEq + core::hash::Hash
{
    /// Field type stored in `Target`.
    type Field: Clone + Send + Sync + 'static + core::fmt::Debug;

    /// Generated tensor default dtype.
    type GeneratedDType: DType;
    /// Layer parameter default dtype.
    type ParameterDType: DType;

    /// Initializes field for target.
    fn init_field(&self) -> Self::Field;

    /// Extracts generated dtype field representation.
    fn generated_dtype_field(field: &Self::Field) -> <Self::GeneratedDType as DType>::Field;

    /// Extracts parameter dtype field representation.
    fn parameter_dtype_field(field: &Self::Field) -> <Self::ParameterDType as DType>::Field;

    /// Extracts runtime policy representation.
    fn runtime_policy(field: &Self::Field) -> RuntimePrecisionPolicy;
}

/// Static policy markers.
#[allow(clippy::module_inception)]
pub mod precision {
    use super::*;

    /// Default policy marker (f32 generated, f32 parameters).
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
    pub struct Default;

    impl PrecisionSpec for Default {
        type Field = ();
        type GeneratedDType = f32;
        type ParameterDType = f32;

        fn init_field(&self) -> Self::Field {}

        fn generated_dtype_field(_field: &Self::Field) -> <Self::GeneratedDType as DType>::Field {
            <Self::GeneratedDType as DType>::init(())
        }

        fn parameter_dtype_field(_field: &Self::Field) -> <Self::ParameterDType as DType>::Field {
            <Self::ParameterDType as DType>::init(())
        }

        fn runtime_policy(_field: &Self::Field) -> RuntimePrecisionPolicy {
            RuntimePrecisionPolicy::fp32()
        }
    }

    /// bfloat16 mixed precision policy marker.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
    pub struct Bf16Mixed;

    /// Legacy compatibility alias.
    pub type MixedBf16 = Bf16Mixed;

    impl PrecisionSpec for Bf16Mixed {
        type Field = ();
        type GeneratedDType = bf16;
        type ParameterDType = bf16;

        fn init_field(&self) -> Self::Field {}

        fn generated_dtype_field(_field: &Self::Field) -> <Self::GeneratedDType as DType>::Field {
            <Self::GeneratedDType as DType>::init(())
        }

        fn parameter_dtype_field(_field: &Self::Field) -> <Self::ParameterDType as DType>::Field {
            <Self::ParameterDType as DType>::init(())
        }

        fn runtime_policy(_field: &Self::Field) -> RuntimePrecisionPolicy {
            RuntimePrecisionPolicy::mixed_bf16()
        }
    }

    /// float16 mixed precision policy marker.
    #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
    pub struct F16Mixed;

    /// Legacy compatibility alias.
    pub type MixedF16 = F16Mixed;

    impl PrecisionSpec for F16Mixed {
        type Field = ();
        type GeneratedDType = f16;
        type ParameterDType = f16;

        fn init_field(&self) -> Self::Field {}

        fn generated_dtype_field(_field: &Self::Field) -> <Self::GeneratedDType as DType>::Field {
            <Self::GeneratedDType as DType>::init(())
        }

        fn parameter_dtype_field(_field: &Self::Field) -> <Self::ParameterDType as DType>::Field {
            <Self::ParameterDType as DType>::init(())
        }

        fn runtime_policy(_field: &Self::Field) -> RuntimePrecisionPolicy {
            RuntimePrecisionPolicy::mixed_f16()
        }
    }

    /// Exact precision policy marker for floating dtype `K`.
    pub struct Exact<K: BuiltinDType + FloatDType>(core::marker::PhantomData<K>);

    impl<K: BuiltinDType + FloatDType> Clone for Exact<K> {
        fn clone(&self) -> Self {
            *self
        }
    }

    impl<K: BuiltinDType + FloatDType> Copy for Exact<K> {}

    impl<K: BuiltinDType + FloatDType> core::fmt::Debug for Exact<K> {
        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
            f.debug_struct("Exact").finish()
        }
    }

    impl<K: BuiltinDType + FloatDType> core::default::Default for Exact<K> {
        fn default() -> Self {
            Self::new()
        }
    }

    impl<K: BuiltinDType + FloatDType> PartialEq for Exact<K> {
        fn eq(&self, _other: &Self) -> bool {
            true
        }
    }

    impl<K: BuiltinDType + FloatDType> Eq for Exact<K> {}

    impl<K: BuiltinDType + FloatDType> core::hash::Hash for Exact<K> {
        fn hash<H: core::hash::Hasher>(&self, _state: &mut H) {}
    }

    impl<K: BuiltinDType + FloatDType> Exact<K> {
        /// Creates a new `Exact<K>` policy marker.
        #[must_use]
        pub const fn new() -> Self {
            Self(core::marker::PhantomData)
        }
    }

    impl<K: BuiltinDType + FloatDType> PrecisionSpec for Exact<K> {
        type Field = ();
        type GeneratedDType = K;
        type ParameterDType = K;

        fn init_field(&self) -> Self::Field {}

        fn generated_dtype_field(_field: &Self::Field) -> <K as DType>::Field {
            K::init(())
        }

        fn parameter_dtype_field(_field: &Self::Field) -> <K as DType>::Field {
            K::init(())
        }

        fn runtime_policy(_field: &Self::Field) -> RuntimePrecisionPolicy {
            RuntimePrecisionPolicy::exact::<K>()
        }
    }
}

pub use precision::{Bf16Mixed, Default, Exact, F16Mixed, MixedBf16, MixedF16};

impl PrecisionSpec for Dyn {
    type Field = RuntimePrecisionPolicy;
    type GeneratedDType = Dyn;
    type ParameterDType = Dyn;

    fn init_field(&self) -> Self::Field {
        RuntimePrecisionPolicy::default()
    }

    fn generated_dtype_field(field: &Self::Field) -> DTypeDescriptor {
        field.generated
    }

    fn parameter_dtype_field(field: &Self::Field) -> DTypeDescriptor {
        field.parameter
    }

    fn runtime_policy(field: &Self::Field) -> RuntimePrecisionPolicy {
        *field
    }
}