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
use crate::{
shapes::*,
tensor::{NoneTape, OwnedTape, Tensor},
tensor_ops::*,
};
use super::*;
/// Does nothing as a [Module], and calls [dropout()] as [ModuleMut] with probability `1.0 / N`.
///
/// To prevent programmer error, [Module] and [ModuleMut] are only implemented for specific tapes:
/// 1. [Module] requires that the input tensor has a [NoneTape]. i.e. that gradients are not being
/// tracked.
/// 2. [ModuleMut] requires that the tensor has a [OwnedTape]. i.e. that the gradients are being
/// tracked
///
/// That means the following will fail to compile:
///
/// 1. Using [Module] with [OwnedTape] **fails to compile**
/// ```compile_fail
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let dropout: DropoutOneIn<2> = BuildModule::build(&dev);
/// let grads = dropout.alloc_grads();
/// dropout.forward(dev.zeros::<Rank1<5>>().trace(grads));
/// ```
///
/// 2. Using [ModuleMut] with [NoneTape] **fails to compile**
/// ```compile_fail
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let mut dropout: DropoutOneIn<2> = Default::default();
/// dropout.forward_mut(dev.zeros::<Rank1<5>>());
/// ```
///
/// Generics:
/// - `N`: p is set as `1.0 / N`
///
/// Examples:
/// ```rust
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let mut dropout: DropoutOneIn<2> = Default::default();
/// let grads = dropout.alloc_grads();
/// let x: Tensor<Rank2<2, 5>, f32, _> = dev.ones();
/// let r = dropout.forward_mut(x.trace(grads));
/// assert_eq!(r.array(), [[2.0, 2.0, 2.0, 0.0, 0.0], [2.0, 2.0, 0.0, 0.0, 2.0]]);
/// ```
#[derive(Clone, Debug, Default)]
pub struct DropoutOneIn<const N: usize>;
impl<const N: usize> ZeroSizedModule for DropoutOneIn<N> {}
impl<const N: usize, S: Shape, E: Dtype, D: Device<E>> Module<Tensor<S, E, D, NoneTape>>
for DropoutOneIn<N>
{
type Output = Tensor<S, E, D, NoneTape>;
/// Does nothing
type Error = D::Err;
fn try_forward(&self, input: Tensor<S, E, D, NoneTape>) -> Result<Self::Output, D::Err> {
Ok(input)
}
}
impl<const N: usize, S: Shape, E: Dtype, D: Device<E>> ModuleMut<Tensor<S, E, D, OwnedTape<E, D>>>
for DropoutOneIn<N>
{
type Output = Tensor<S, E, D, OwnedTape<E, D>>;
type Error = D::Err;
/// Calls [dropout()] with `p=1/N` using `self.rng`.
fn try_forward_mut(
&mut self,
input: Tensor<S, E, D, OwnedTape<E, D>>,
) -> Result<Self::Output, D::Err> {
input.try_dropout(E::ONE / E::from_usize(N).unwrap())
}
}
/// Does nothing as a [Module], and calls [dropout()] as [ModuleMut] with probability `1.0 / N`.
///
/// To prevent programmer error, [Module] and [ModuleMut] are only implemented for specific tapes:
/// 1. [Module] requires that the input tensor has a [NoneTape]. i.e. that gradients are not being
/// tracked.
/// 2. [ModuleMut] requires that the tensor has a [OwnedTape]. i.e. that the gradients are being
/// tracked
///
/// That means the following will fail to compile:
///
/// 1. Using [Module] with [OwnedTape] **fails to compile**
/// ```compile_fail
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let dropout: Dropout = Default::default();
/// dropout.forward(dev.zeros::<Rank1<5>>().leaky_trace());
/// ```
///
/// 2. Using [ModuleMut] with [NoneTape] **fails to compile**
/// ```compile_fail
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let mut dropout: Dropout = Default::default();
/// dropout.forward_mut(dev.zeros::<Rank1<5>>());
/// ```
///
/// Generics:
/// - `N`: p is set as `1.0 / N`
///
/// Examples:
/// ```rust
/// # use dfdx::prelude::*;
/// # let dev: Cpu = Default::default();
/// let mut dropout = Dropout { p: 0.5 };
/// let grads = dropout.alloc_grads();
/// let x: Tensor<Rank2<2, 5>, f32, _> = dev.ones();
/// let r = dropout.forward_mut(x.trace(grads));
/// assert_eq!(r.array(), [[2.0, 2.0, 2.0, 0.0, 0.0], [2.0, 2.0, 0.0, 0.0, 2.0]]);
/// ```
#[derive(Clone, Debug)]
pub struct Dropout {
pub p: f32,
}
impl Default for Dropout {
/// Sets `self.p` to `0.5`
fn default() -> Self {
Self { p: 0.5 }
}
}
impl ZeroSizedModule for Dropout {}
impl<S: Shape, E: Dtype, D: Device<E>> Module<Tensor<S, E, D, NoneTape>> for Dropout {
type Output = Tensor<S, E, D, NoneTape>;
type Error = D::Err;
/// Does nothing.
fn try_forward(&self, input: Tensor<S, E, D, NoneTape>) -> Result<Self::Output, D::Err> {
Ok(input)
}
}
impl<S: Shape, E: Dtype, D: Device<E>> ModuleMut<Tensor<S, E, D, OwnedTape<E, D>>> for Dropout {
type Output = Tensor<S, E, D, OwnedTape<E, D>>;
type Error = D::Err;
/// Calls [dropout()]
fn try_forward_mut(
&mut self,
input: Tensor<S, E, D, OwnedTape<E, D>>,
) -> Result<Self::Output, D::Err> {
input.try_dropout(E::from_f32(self.p).unwrap())
}
}
#[cfg(test)]
mod tests {
use crate::{
shapes::Rank1,
tensor::{AsArray, OnesTensor, Trace},
tests::*,
};
use super::*;
#[test]
fn test_dropout_internal_rng_reproduce() {
let dev: TestDevice = Default::default();
let mut d1 = Dropout { p: 0.5 };
let mut d2 = Dropout { p: 0.5 };
let t: Tensor<Rank1<100>, TestDtype, _> = dev.ones();
let r1 = d1.forward_mut(t.leaky_trace());
let r2 = d2.forward_mut(t.leaky_trace());
let r1_2 = d1.forward_mut(t.leaky_trace());
assert_ne!(r1.array(), r2.array());
assert_ne!(r1.array(), r1_2.array());
}
#[test]
fn test_dropout_no_tape() {
let dev: TestDevice = Default::default();
let dropout = Dropout { p: 0.5 };
let t: Tensor<Rank1<100>, TestDtype, _> = dev.ones();
let r = dropout.forward(t.clone());
assert_eq!(t.array(), r.array());
}
#[test]
fn test_dropout_tape() {
let dev: TestDevice = Default::default();
let mut dropout = Dropout { p: 0.5 };
let t: Tensor<Rank1<100>, TestDtype, _> = dev.ones();
let r = dropout.forward_mut(t.leaky_trace());
assert_ne!(t.array(), r.array());
}
}