Skip to main content

oa/ml/nn/
dropout_ext.rs

1//! Dropout variants: channel-masked `Dropout1d/2d/3d`, `AlphaDropout`, and
2//! channel-masked `FeatureAlphaDropout`, composed over `matrix::dropout`.
3
4use crate::{Error, Matrix, Result, matrix};
5
6use super::super::{Module, ModuleRegistry, NamedRngState};
7
8/// Generate a broadcastable keep mask at channel granularity.
9///
10/// `matrix::dropout_streamed` applies the keep mask scaled by `1/(1-p)`;
11/// multiplying the input by that scaled mask is the inverted-dropout contract.
12/// The mask is generated on a ones matrix at `[N, C]` granularity, then
13/// reshaped to broadcast over the trailing spatial axes.
14fn channel_mask(
15	input: &Matrix,
16	spatial_rank: usize,
17	probability: f32,
18	seed: u64,
19	rng: &NamedRngState,
20) -> Result<Matrix> {
21	let shape = input.shape();
22	let mask_shape = shape[..2].to_vec();
23	let ones = Matrix::new_from_slice_handle(
24		input.runtime(),
25		mask_shape.clone(),
26		&vec![1.0_f32; mask_shape.iter().product()],
27	)?;
28	let mask = matrix::dropout_streamed(&ones, probability, seed, rng)?;
29	mask.reshape(
30		[shape[0], shape[1]]
31			.into_iter()
32			.chain(vec![1; spatial_rank])
33			.collect::<Vec<_>>(),
34	)
35}
36
37fn validate_spatial(name: &str, input: &Matrix, spatial_rank: usize) -> Result<()> {
38	if input.shape().len() != spatial_rank + 2 {
39		return Err(Error::invalid_argument(format!(
40			"{name} requires a rank-{} [N, C, ...] input; found {:?}",
41			spatial_rank + 2,
42			input.shape()
43		)));
44	}
45	Ok(())
46}
47
48macro_rules! channel_dropout {
49	($name:ident, $spatial:literal, $doc:literal) => {
50		/// $doc
51		pub struct $name {
52			probability: f32,
53			seed: u64,
54			draw: NamedRngState,
55			registry: ModuleRegistry,
56		}
57
58		impl $name {
59			/// Construct with the thread-local random seed source.
60			///
61			/// # Errors
62			///
63			/// Returns an error unless `probability` is finite and in `[0, 1)`.
64			pub fn new(probability: f32) -> Result<Self> {
65				Self::new_with_seed(probability, 0)
66			}
67
68			/// Construct with an explicit Philox seed.
69			///
70			/// # Errors
71			///
72			/// Returns an error unless `probability` is finite and in `[0, 1)`.
73			pub fn new_with_seed(probability: f32, seed: u64) -> Result<Self> {
74				if !probability.is_finite() || !(0.0..1.0).contains(&probability) {
75					return Err(Error::invalid_argument(
76						"dropout probability must be finite and in [0, 1)",
77					));
78				}
79				let mut registry = ModuleRegistry::new();
80				let draw = registry.register_rng_state("draw", 0)?;
81				Ok(Self {
82					probability,
83					seed,
84					draw,
85					registry,
86				})
87			}
88
89			/// Return the probability of dropping each channel during training.
90			pub const fn probability(&self) -> f32 {
91				self.probability
92			}
93
94			/// Apply channel dropout in training mode or return an identity
95			/// handle in eval mode.
96			///
97			/// # Errors
98			///
99			/// Returns an error for a wrongly ranked input or a mask dispatch
100			/// failure.
101			pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
102				if !self.is_training() || self.probability == 0.0 {
103					return Ok(input.clone());
104				}
105				validate_spatial(stringify!($name), input, $spatial)?;
106				let mask = channel_mask(input, $spatial, self.probability, self.seed, &self.draw)?;
107				matrix::mul(input, &mask)
108			}
109		}
110
111		impl Module for $name {
112			fn forward(&self, input: &Matrix) -> Result<Matrix> {
113				$name::forward(self, input)
114			}
115
116			fn registry(&self) -> &ModuleRegistry {
117				&self.registry
118			}
119		}
120	};
121}
122
123channel_dropout!(
124	Dropout1d,
125	1,
126	"Randomly zero entire channels of a `[N, C, L]` input in training mode."
127);
128channel_dropout!(
129	Dropout2d,
130	2,
131	"Randomly zero entire channels of a `[N, C, H, W]` input in training mode."
132);
133channel_dropout!(
134	Dropout3d,
135	3,
136	"Randomly zero entire channels of a `[N, C, D, H, W]` input in training mode."
137);
138
139/// Donor `alpha_prime` for SELU-preserving dropout (`-alpha * lambda`).
140const ALPHA_PRIME: f32 = -1.758_099_3_f32;
141
142/// Apply the alpha-dropout affine map `a * (x * d + alpha' * (1 - d)) + b`
143/// given an elementwise or channel-broadcast keep mask scaled by `1 - p`.
144fn alpha_dropout_apply(input: &Matrix, raw_mask: &Matrix, probability: f32) -> Result<Matrix> {
145	let scale_a = (1.0_f32 + ALPHA_PRIME * ALPHA_PRIME * probability * (1.0 - probability))
146		.sqrt()
147		.recip();
148	let scale_b = -scale_a * ALPHA_PRIME * probability;
149	let retained = matrix::mul(input, raw_mask)?;
150	let dropped = matrix::scale(
151		&matrix::add_scalar(&matrix::neg(raw_mask)?, 1.0)?,
152		ALPHA_PRIME,
153	)?;
154	matrix::add_scalar(
155		&matrix::scale(&matrix::add(&retained, &dropped)?, scale_a)?,
156		scale_b,
157	)
158}
159
160/// Recover the raw `{0, 1}` keep mask from `matrix::dropout_streamed`'s scaled mask.
161fn raw_mask(
162	keep_shape: &[usize],
163	input: &Matrix,
164	probability: f32,
165	seed: u64,
166	rng: &NamedRngState,
167) -> Result<Matrix> {
168	let ones = Matrix::new_from_slice_handle(
169		input.runtime(),
170		keep_shape.to_vec(),
171		&vec![1.0_f32; keep_shape.iter().product()],
172	)?;
173	matrix::scale(
174		&matrix::dropout_streamed(&ones, probability, seed, rng)?,
175		1.0 - probability,
176	)
177}
178
179/// Elementwise SELU-preserving dropout (`nn.AlphaDropout`).
180///
181/// Applies `a * (x * d + alpha' * (1 - d)) + b` elementwise, keeping the
182/// input mean and variance compatible with SELU activations.
183pub struct AlphaDropout {
184	probability: f32,
185	seed: u64,
186	draw: NamedRngState,
187	registry: ModuleRegistry,
188}
189
190impl AlphaDropout {
191	/// Construct with the thread-local random seed source.
192	///
193	/// # Errors
194	///
195	/// Returns an error unless `probability` is finite and in `[0, 1)`.
196	pub fn new(probability: f32) -> Result<Self> {
197		Self::new_with_seed(probability, 0)
198	}
199
200	/// Construct with an explicit Philox seed.
201	///
202	/// # Errors
203	///
204	/// Returns an error unless `probability` is finite and in `[0, 1)`.
205	pub fn new_with_seed(probability: f32, seed: u64) -> Result<Self> {
206		if !probability.is_finite() || !(0.0..1.0).contains(&probability) {
207			return Err(Error::invalid_argument(
208				"alpha dropout probability must be finite and in [0, 1)",
209			));
210		}
211		let mut registry = ModuleRegistry::new();
212		let draw = registry.register_rng_state("draw", 0)?;
213		Ok(Self {
214			probability,
215			seed,
216			draw,
217			registry,
218		})
219	}
220
221	/// Return the probability of dropping each element during training.
222	pub const fn probability(&self) -> f32 {
223		self.probability
224	}
225
226	/// Apply alpha dropout in training mode or return an identity handle in
227	/// eval mode.
228	///
229	/// # Errors
230	///
231	/// Returns an error from the underlying Matrix operations.
232	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
233		if !self.is_training() || self.probability == 0.0 {
234			return Ok(input.clone());
235		}
236		let mask = raw_mask(
237			input.shape(),
238			input,
239			self.probability,
240			self.seed,
241			&self.draw,
242		)?;
243		alpha_dropout_apply(input, &mask, self.probability)
244	}
245}
246
247impl Module for AlphaDropout {
248	fn forward(&self, input: &Matrix) -> Result<Matrix> {
249		AlphaDropout::forward(self, input)
250	}
251
252	fn registry(&self) -> &ModuleRegistry {
253		&self.registry
254	}
255}
256
257/// Channel-granular SELU-preserving dropout (`nn.FeatureAlphaDropout`).
258///
259/// Shares one `{0, 1}` keep mask per `[N, C]` channel across the trailing
260/// axes, then applies the alpha-dropout affine map.
261pub struct FeatureAlphaDropout {
262	probability: f32,
263	seed: u64,
264	draw: NamedRngState,
265	registry: ModuleRegistry,
266}
267
268impl FeatureAlphaDropout {
269	/// Construct with the thread-local random seed source.
270	///
271	/// # Errors
272	///
273	/// Returns an error unless `probability` is finite and in `[0, 1)`.
274	pub fn new(probability: f32) -> Result<Self> {
275		Self::new_with_seed(probability, 0)
276	}
277
278	/// Construct with an explicit Philox seed.
279	///
280	/// # Errors
281	///
282	/// Returns an error unless `probability` is finite and in `[0, 1)`.
283	pub fn new_with_seed(probability: f32, seed: u64) -> Result<Self> {
284		if !probability.is_finite() || !(0.0..1.0).contains(&probability) {
285			return Err(Error::invalid_argument(
286				"feature alpha dropout probability must be finite and in [0, 1)",
287			));
288		}
289		let mut registry = ModuleRegistry::new();
290		let draw = registry.register_rng_state("draw", 0)?;
291		Ok(Self {
292			probability,
293			seed,
294			draw,
295			registry,
296		})
297	}
298
299	/// Return the probability of dropping each channel during training.
300	pub const fn probability(&self) -> f32 {
301		self.probability
302	}
303
304	/// Apply channel-granular alpha dropout in training mode or return an
305	/// identity handle in eval mode.
306	///
307	/// # Errors
308	///
309	/// Returns an error for a rank-below-two input or a mask dispatch failure.
310	pub fn forward(&self, input: &Matrix) -> Result<Matrix> {
311		if !self.is_training() || self.probability == 0.0 {
312			return Ok(input.clone());
313		}
314		let shape = input.shape();
315		if shape.len() < 2 {
316			return Err(Error::invalid_argument(
317				"FeatureAlphaDropout requires an input of rank at least two",
318			));
319		}
320		let mask = raw_mask(&shape[..2], input, self.probability, self.seed, &self.draw)?.reshape(
321			[shape[0], shape[1]]
322				.into_iter()
323				.chain(vec![1; shape.len() - 2])
324				.collect::<Vec<_>>(),
325		)?;
326		alpha_dropout_apply(input, &mask, self.probability)
327	}
328}
329
330impl Module for FeatureAlphaDropout {
331	fn forward(&self, input: &Matrix) -> Result<Matrix> {
332		FeatureAlphaDropout::forward(self, input)
333	}
334
335	fn registry(&self) -> &ModuleRegistry {
336		&self.registry
337	}
338}