1use crate::{Error, Matrix, Result, matrix};
5
6use super::super::{Module, ModuleRegistry, NamedRngState};
7
8fn 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 pub struct $name {
52 probability: f32,
53 seed: u64,
54 draw: NamedRngState,
55 registry: ModuleRegistry,
56 }
57
58 impl $name {
59 pub fn new(probability: f32) -> Result<Self> {
65 Self::new_with_seed(probability, 0)
66 }
67
68 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 pub const fn probability(&self) -> f32 {
91 self.probability
92 }
93
94 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
139const ALPHA_PRIME: f32 = -1.758_099_3_f32;
141
142fn 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
160fn 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
179pub struct AlphaDropout {
184 probability: f32,
185 seed: u64,
186 draw: NamedRngState,
187 registry: ModuleRegistry,
188}
189
190impl AlphaDropout {
191 pub fn new(probability: f32) -> Result<Self> {
197 Self::new_with_seed(probability, 0)
198 }
199
200 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 pub const fn probability(&self) -> f32 {
223 self.probability
224 }
225
226 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
257pub struct FeatureAlphaDropout {
262 probability: f32,
263 seed: u64,
264 draw: NamedRngState,
265 registry: ModuleRegistry,
266}
267
268impl FeatureAlphaDropout {
269 pub fn new(probability: f32) -> Result<Self> {
275 Self::new_with_seed(probability, 0)
276 }
277
278 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 pub const fn probability(&self) -> f32 {
301 self.probability
302 }
303
304 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}