oarust 0.20.1

GPU-first semantic computing runtime written in Rust
Documentation
// @generated by tool/gen/nn/generate.py; DO NOT EDIT.
// Source: tool/gen/nn/schema/ml/ml_nn_dropout.json
// generator_version=8; schema_sha256=9f8a4aaeca2bdb7dfb407fac29c89d87c556d6577081e5bb9b3451cb2c024186

use crate::{Error, Matrix, Result, matrix};

use super::super::{Module, ModuleRegistry, NamedRngState};

// OA donor: oacpp/source/cpp/lib/oa/ml/nn/dropout/dropout.cpp
// Adaptation: Rust ownership, ModuleRegistry and checked error contracts; preserved operation behavior
/// Inverted Dropout with explicit train/eval behavior.
pub struct Dropout {
	probability: f32,
	seed: u64,
	draw: NamedRngState,
	registry: ModuleRegistry,
}

impl Dropout {
	/// Construct Dropout with the thread-local random seed source.
	///
	/// # Errors
	///
	/// Returns an error unless `probability` is finite and in `[0, 1)`.
	pub fn new(probability: f32) -> Result<Self> {
		Self::new_with_seed(probability, 0)
	}

	/// Construct Dropout with an explicit Philox seed.
	///
	/// A nonzero seed makes independently recorded eager calls reproducible.
	/// Captured programs advance their module-owned device random counter on
	/// every replay and persist its draw position through `.runstate`. Zero
	/// consumes the thread-local seed source when training forward is recorded.
	///
	/// # Errors
	///
	/// Returns an error unless `probability` is finite and in `[0, 1)`.
	pub fn new_with_seed(probability: f32, seed: u64) -> Result<Self> {
		if !probability.is_finite() || !(0.0..1.0).contains(&probability) {
			return Err(Error::invalid_argument(
				"Dropout probability must be finite and in [0, 1)",
			));
		}
		let mut registry = ModuleRegistry::new();
		let draw = registry.register_rng_state("draw", 0)?;
		Ok(Self {
			probability,
			seed,
			draw,
			registry,
		})
	}

	/// Return the probability of dropping each element during training.
	pub const fn probability(&self) -> f32 {
		self.probability
	}

	/// Apply Dropout in training mode or return an identity handle in eval mode.
	///
	/// # Errors
	///
	/// Returns an error from the underlying Matrix operation.
	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
		if !self.is_training() || self.probability == 0.0 {
			return Ok(input.clone());
		}
		// Stream mask positions per training forward through the module-owned
		// RNG state so eager steps, in-process recaptures, and checkpoint
		// resumes continue the exact Philox sequence without repeating masks.
		matrix::dropout_streamed(input, self.probability, self.seed, &self.draw)
	}
}

impl Module for Dropout {
	fn forward(&self, input: &Matrix) -> Result<Matrix> {
		Dropout::forward(self, input)
	}

	fn registry(&self) -> &ModuleRegistry {
		&self.registry
	}
}