oa/ml/nn/dropout.gen.rs
1// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
2// Source: tool/gen/nn/schema/ml/ml_nn_dropout.json
3// generator_version=8; schema_sha256=9f8a4aaeca2bdb7dfb407fac29c89d87c556d6577081e5bb9b3451cb2c024186
4
5use crate::{Error, Matrix, Result, matrix};
6
7use super::super::{Module, ModuleRegistry, NamedRngState};
8
9// OA donor: oacpp/source/cpp/lib/oa/ml/nn/dropout/dropout.cpp
10// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
11/// Inverted Dropout with explicit train/eval behavior.
12pub struct Dropout {
13 probability: f32,
14 seed: u64,
15 draw: NamedRngState,
16 registry: ModuleRegistry,
17}
18
19impl Dropout {
20 /// Construct Dropout with the thread-local random seed source.
21 ///
22 /// # Errors
23 ///
24 /// Returns an error unless `probability` is finite and in `[0, 1)`.
25 pub fn new(probability: f32) -> Result<Self> {
26 Self::new_with_seed(probability, 0)
27 }
28
29 /// Construct Dropout with an explicit Philox seed.
30 ///
31 /// A nonzero seed makes independently recorded eager calls reproducible.
32 /// Captured programs advance their module-owned device random counter on
33 /// every replay and persist its draw position through `.runstate`. Zero
34 /// consumes the thread-local seed source when training forward is recorded.
35 ///
36 /// # Errors
37 ///
38 /// Returns an error unless `probability` is finite and in `[0, 1)`.
39 pub fn new_with_seed(probability: f32, seed: u64) -> Result<Self> {
40 if !probability.is_finite() || !(0.0..1.0).contains(&probability) {
41 return Err(Error::invalid_argument(
42 "Dropout probability must be finite and in [0, 1)",
43 ));
44 }
45 let mut registry = ModuleRegistry::new();
46 let draw = registry.register_rng_state("draw", 0)?;
47 Ok(Self {
48 probability,
49 seed,
50 draw,
51 registry,
52 })
53 }
54
55 /// Return the probability of dropping each element during training.
56 pub const fn probability(&self) -> f32 {
57 self.probability
58 }
59
60 /// Apply Dropout in training mode or return an identity handle in eval mode.
61 ///
62 /// # Errors
63 ///
64 /// Returns an error from the underlying Matrix operation.
65 pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
66 if !self.is_training() || self.probability == 0.0 {
67 return Ok(input.clone());
68 }
69 // Stream mask positions per training forward through the module-owned
70 // RNG state so eager steps, in-process recaptures, and checkpoint
71 // resumes continue the exact Philox sequence without repeating masks.
72 matrix::dropout_streamed(input, self.probability, self.seed, &self.draw)
73 }
74}
75
76impl Module for Dropout {
77 fn forward(&self, input: &Matrix) -> Result<Matrix> {
78 Dropout::forward(self, input)
79 }
80
81 fn registry(&self) -> &ModuleRegistry {
82 &self.registry
83 }
84}