|
| 1 | + |
| 2 | +""" |
| 3 | + dropout([rng], A, p; [dims]) |
| 4 | +
|
| 5 | +Returns an array in which each element of `A` is either replaced with zero, |
| 6 | +with probability `p`, or else multiplied by `1/(1-p)`. |
| 7 | +
|
| 8 | +By default every element is treated independently. |
| 9 | +With keyword `dims=1`, a choice is made for every value of the 1st index |
| 10 | +i.e. each row of a matrix is either zero or not. |
| 11 | +
|
| 12 | +Optional first argument is the random number generator used. |
| 13 | +
|
| 14 | +# Examples |
| 15 | +``` |
| 16 | +julia> dropout(ones(2, 10), 0.2) |
| 17 | +2×10 Matrix{Float64}: |
| 18 | + 1.25 1.25 0.0 1.25 1.25 1.25 1.25 1.25 1.25 1.25 |
| 19 | + 1.25 1.25 1.25 0.0 1.25 1.25 0.0 1.25 1.25 1.25 |
| 20 | +
|
| 21 | +julia> mean(dropout(ones(10^4, 5), 0.2), dims=1) |
| 22 | +1×5 Matrix{Float64}: |
| 23 | + 0.998 1.00075 0.99125 0.99575 1.00075 |
| 24 | +
|
| 25 | +julia> dropout(ones(5, 5), 0.7, dims=1) # whole row the same |
| 26 | +5×5 Matrix{Float64}: |
| 27 | + 3.33333 3.33333 3.33333 3.33333 3.33333 |
| 28 | + 0.0 0.0 0.0 0.0 0.0 |
| 29 | + 0.0 0.0 0.0 0.0 0.0 |
| 30 | + 3.33333 3.33333 3.33333 3.33333 3.33333 |
| 31 | + 0.0 0.0 0.0 0.0 0.0 |
| 32 | +
|
| 33 | +julia> mean(dropout(ones(10^4, 5), 0.3, dims=1), dims=1) |
| 34 | +1×5 Matrix{Float64}: |
| 35 | + 1.00571 1.00571 1.00571 1.00571 1.00571 |
| 36 | +``` |
| 37 | +""" |
| 38 | +dropout(A::AbstractArray, p::Real; dims = :) = dropout(_rng_from_array(A), A, p; dims) |
| 39 | + |
| 40 | +function dropout(rng::AbstractRNG, A::AbstractArray, p::Real; dims = :) |
| 41 | + T = float(eltype(A)) |
| 42 | + 0 <= p <= 1 || throw(ArgumentError("dropout expects a probability 0 <= p <= 1")) |
| 43 | + if p > 0 |
| 44 | + dst = similar(A, T, size(A)) |
| 45 | + pT = convert(real(T), p) |
| 46 | + _dropout!(rng, dst, A, pT, dims) |
| 47 | + else |
| 48 | + # Not so sure we want fast paths... this tries but doesn't guarantee type-stability, |
| 49 | + # and the rrule does not have such a fast paths. |
| 50 | + convert(AbstractArray{T}, A) |
| 51 | + end |
| 52 | +end |
| 53 | + |
| 54 | +""" |
| 55 | + dropout!(B, A, p; dims=:) |
| 56 | +
|
| 57 | +This does exactly `B .= dropout(A, p; dims)`, |
| 58 | +or rather, it's the implementation of out-of-place [`dropout`](@ref). |
| 59 | +""" |
| 60 | +dropout!(B::AbstractArray, A::AbstractArray, p::Real; dims = :) = dropout!(_rng_from_array(B), B, A, p; dims) |
| 61 | + |
| 62 | +function dropout!(rng::AbstractRNG, dst::AbstractArray, src::AbstractArray, p::Real; dims=:) |
| 63 | + size(dst) == size(src) || throw(DimensionMismatch("dropout! expects output array the same size as input")) |
| 64 | + 0 <= p <= 1 || throw(ArgumentError("dropout expects a probability 0 <= p <= 1")) |
| 65 | + if p > 0 |
| 66 | + pT = convert(real(eltype(dst)), p) |
| 67 | + _dropout!(rng, dst, src, pT, dims) |
| 68 | + else |
| 69 | + # This fast path isn't free, but no concerns about types changing: |
| 70 | + copyto!(dst, src) |
| 71 | + end |
| 72 | +end |
| 73 | + |
| 74 | +# This is the easy case in that we can safely use the output array for random numbers. |
| 75 | +function _dropout!(rng::AbstractRNG, dst::AbstractArray, src::AbstractArray, p::Real, dims::Colon) |
| 76 | + T = real(eltype(dst)) |
| 77 | + val = convert(T, 1/(1-p)) |
| 78 | + rand!(rng, dst) |
| 79 | + ## This is what we want, but it hits a SIMD bug, solved by _fast_broadcast! |
| 80 | + # dst .= (dst.>p) .* val .* src |
| 81 | + _fast_broadcast!(dst, src) do q, x |
| 82 | + ((real(q)>p) * val) * x |
| 83 | + end |
| 84 | + dst |
| 85 | +end |
| 86 | + |
| 87 | +# For other dims, we we do need to allocate something. |
| 88 | +function _dropout!(rng::AbstractRNG, dst::AbstractArray, src::AbstractArray, p::Real, dims) |
| 89 | + T = real(eltype(dst)) |
| 90 | + tmp = similar(dst, T, ntuple(d -> d in dims ? size(src,d) : 1, ndims(src))) |
| 91 | + rand!(rng, tmp) |
| 92 | + val = convert(T, 1/(1-p)) |
| 93 | + ## One-pass strategy -- faster on GPU |
| 94 | + dst .= ((tmp.>p) .* val) .* src |
| 95 | + ## Two-pass strategy -- slightly faster on some CPUs? |
| 96 | + # _fast_broadcast!(tmp) do q |
| 97 | + # (q>p) * val |
| 98 | + # end |
| 99 | + # dst .= tmp .* src |
| 100 | +end |
| 101 | + |
| 102 | +# The gradient needs to keep the random choices made, thus store at least a BitArray, |
| 103 | +# but the following way turns out to be faster & simpler: |
| 104 | +function ChainRulesCore.rrule(::typeof(dropout), rng::AbstractRNG, A::AbstractArray, p::Real; dims = :) |
| 105 | + T = float(real(eltype(A))) |
| 106 | + val = convert(T, 1/(1-p)) |
| 107 | + keep = if dims isa Colon |
| 108 | + similar(A, T, size(A)) |
| 109 | + else |
| 110 | + similar(A, T, ntuple(d -> d in dims ? size(A,d) : 1, ndims(A))) |
| 111 | + end |
| 112 | + rand!(rng, keep) |
| 113 | + Y = @. ((keep>p) * val) * A |
| 114 | + function dropout_back(Δ) |
| 115 | + dY = unthunk(Δ) |
| 116 | + dA = @. ((keep>p) * val) * dY |
| 117 | + (NoTangent(), NoTangent(), dA, NoTangent()) |
| 118 | + end |
| 119 | + return Y, dropout_back |
| 120 | +end |
| 121 | +# Possibly TODO: another approach to the gradient would be to copy the RNG |
| 122 | +# and then re-generate the same mask, instead of storing it. This saves memory |
| 123 | +# and seems about as fast, but needs a method `copy(::CUDA.RNG)` and careful checking. |
| 124 | +# https://github.com/FluxML/NNlib.jl/pull/454#issuecomment-1369357402 |
| 125 | + |
| 126 | +""" |
| 127 | + _fast_broadcast!(f, x, y, z...) |
| 128 | +
|
| 129 | +This does `x .= f.(x, y, z...)`, but works around |
| 130 | +an issue with broadcasting that prevents SIMD in such cases. |
| 131 | +Can be removed once https://github.com/JuliaLang/julia/issues/43153 is fixed. |
| 132 | +
|
| 133 | +Not intended for general use. Does not check sizes! |
| 134 | +""" |
| 135 | +function _fast_broadcast!(f::F, x::Array, yz...) where {F<:Function} |
| 136 | + bc = Broadcast.instantiate(Broadcast.broadcasted(f, x, yz...)) |
| 137 | + @simd ivdep for I in eachindex(bc) |
| 138 | + @inbounds x[I] = bc[I] |
| 139 | + end |
| 140 | + return x |
| 141 | +end |
| 142 | +function _fast_broadcast!(f::F, x::AbstractArray, yz...) where {F<:Function} |
| 143 | + # CUDA does not suffer from this bug |
| 144 | + broadcast!(f, x, x, yz...) |
| 145 | +end |
| 146 | + |
| 147 | + |
| 148 | +""" |
| 149 | + _rng_from_array(x) |
| 150 | +
|
| 151 | +Return the random number generator most appropriate for `x`: |
| 152 | +`CUDA.default_rng()` for `CuArray`, else `Random.default_rng()` |
| 153 | +""" |
| 154 | +_rng_from_array(::AbstractArray) = Random.default_rng() |
| 155 | + |
| 156 | +@non_differentiable _rng_from_array(::Any) |
| 157 | + |
0 commit comments