# Basic Layers

These core layers form the foundation of almost all neural networks.

Flux.ChainType
Chain(layers...)

Chain multiple layers / functions together, so that they are called in sequence on a given input.

Chain also supports indexing and slicing, e.g. m[2] or m[1:end-1]. m[1:3](x) will calculate the output of the first three layers.

Examples

julia> m = Chain(x -> x^2, x -> x+1);

julia> m(5) == 26
true

julia> m = Chain(Dense(10, 5), Dense(5, 2));

julia> x = rand(10);

julia> m(x) == m[2](m[1](x))
true
source
Flux.DenseType
Dense(in, out, σ=identity; bias=true, init=glorot_uniform)
Dense(W::AbstractMatrix, [bias, σ])

Create a traditional Dense layer, whose forward pass is given by:

y = σ.(W * x .+ bias)

The input x should be a vector of length in, or batch of vectors represented as an in × N matrix, or any array with size(x,1) == in. The out y will be a vector of length out, or a batch with size(y) == (out, size(x)[2:end]...)

Keyword bias=false will switch off trainable bias for the layer. The initialisation of the weight matrix is W = init(out, in), calling the function given to keyword init, with default glorot_uniform. The weight matrix and/or the bias vector (of length out) may also be provided explicitly.

Examples

julia> d = Dense(5, 2)
Dense(5, 2)         # 12 parameters

julia> d(rand(Float32, 5, 64)) |> size
(2, 64)

julia> d(rand(Float32, 5, 1, 1, 64)) |> size  # treated as three batch dimensions
(2, 1, 1, 64)

julia> d1 = Dense(ones(2, 5), false, tanh)  # using provided weight matrix
Dense(5, 2, tanh; bias=false)  # 10 parameters

julia> d1(ones(5))
2-element Vector{Float64}:
0.9999092042625951
0.9999092042625951

julia> Flux.params(d1)  # no trainable bias
Params([[1.0 1.0 … 1.0 1.0; 1.0 1.0 … 1.0 1.0]])
source

## Convolution and Pooling Layers

These layers are used to build convolutional neural networks (CNNs).

Flux.ConvType
Conv(filter, in => out, σ = identity;
stride = 1, pad = 0, dilation = 1, groups = 1, [bias, weight, init])

Standard convolutional layer. filter is a tuple of integers specifying the size of the convolutional kernel; in and out specify the number of input and output channels.

Image data should be stored in WHCN order (width, height, channels, batch). In other words, a 100×100 RGB image would be a 100×100×3×1 array, and a batch of 50 would be a 100×100×3×50 array. This has N = 2 spatial dimensions, and needs a kernel size like (5,5), a 2-tuple of integers.

To take convolutions along N feature dimensions, this layer expects as input an array with ndims(x) == N+2, where size(x, N+1) == in is the number of input channels, and size(x, ndims(x)) is (as always) the number of observations in a batch. Then:

• filter should be a tuple of N integers.
• Keywords stride and dilation should each be either single integer, or a tuple with N integers.
• Keyword pad can be:
• a single integer for equal padding all around,
• a tuple of N integers, to apply the same padding at begin/end of each spatial dimension,
• a tuple of 2*N integers, for asymmetric padding, or
• the singleton SamePad(), to calculate padding such that size(output,d) == size(x,d) / stride (possibly rounded) for each spatial dimension.
• Keyword groups is expected to be an Int. It specifies the number of groups to divide a convolution into.

Keywords to control initialization of the layer:

• init - Function used to generate initial weights. Defaults to glorot_uniform.
• weight - Initial weights of the layer. Typically an array, and can be used to override other configurations. By default, these are generated using convfilter.
• bias - Initial bias is zero by default, this can be disabled entirely by setting it to Flux.Zeros() or equivalently false, or another vector provided as bias = randn(Float32, out).

Examples

julia> xs = rand(Float32, 100, 100, 3, 50); # a batch of images

julia> layer = Conv((5,5), 3 => 7, relu; bias = false)
Conv((5, 5), 3 => 7, relu, bias=false)  # 525 parameters

julia> layer(xs) |> size
(96, 96, 7, 50)

julia> Conv((5,5), 3 => 7; stride = 2)(xs) |> size
(48, 48, 7, 50)

julia> Conv((5,5), 3 => 7; stride = 2, pad = SamePad())(xs) |> size
(50, 50, 7, 50)

julia> Conv((1,1), 3 => 7; pad = (20,10,0,0))(xs) |> size
(130, 100, 7, 50)

julia> Conv((5,5), 3 => 7; stride = 2, dilation = 4)(xs) |> size
(42, 42, 7, 50)
source
Flux.AdaptiveMaxPoolType
AdaptiveMaxPool(out::NTuple)

Adaptive max pooling layer. Calculates the necessary window size such that its output has size(y)[1:N] == out.

Expects as input an array with ndims(x) == N+2, i.e. channel and batch dimensions, after the N feature dimensions, where N = length(out).

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # batch of 50 RGB images

(25, 25, 3, 50)

true
source
Flux.MaxPoolType
MaxPool(window::NTuple; pad=0, stride=window)

Max pooling layer, which replaces all pixels in a block of size window with one.

Expects as input an array with ndims(x) == N+2, i.e. channel and batch dimensions, after the N feature dimensions, where N = length(window).

By default the window size is also the stride in each dimension. The keyword pad accepts the same options as for the Conv layer, including SamePad().

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # batch of 50 RGB images

Chain(
Conv((5, 5), 3 => 7, pad=2),          # 532 parameters
)

julia> m[1](xs) |> size
(100, 100, 7, 50)

julia> m(xs) |> size
(20, 20, 7, 50)

julia> lay = MaxPool((5,), pad=2, stride=(3,))  # one-dimensional window

julia> lay(rand(Float32, 100, 7, 50)) |> size
(34, 7, 50)
source
Flux.GlobalMaxPoolType
GlobalMaxPool()

Global max pooling layer.

Transforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing max pooling on the complete (w,h)-shaped feature maps.

julia> xs = rand(Float32, 100, 100, 3, 50);

julia> m = Chain(Conv((3,3), 3 => 7), GlobalMaxPool());

julia> m(xs) |> size
(1, 1, 7, 50)

julia> GlobalMaxPool()(rand(3,5,7)) |> size  # preserves 2 dimensions
(1, 5, 7)
source
Flux.AdaptiveMeanPoolType
AdaptiveMeanPool(out::NTuple)

Adaptive mean pooling layer. Calculates the necessary window size such that its output has size(y)[1:N] == out.

Expects as input an array with ndims(x) == N+2, i.e. channel and batch dimensions, after the N feature dimensions, where N = length(out).

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # batch of 50 RGB images

(25, 25, 3, 50)

true
source
Flux.MeanPoolType
MeanPool(window::NTuple; pad=0, stride=window)

Mean pooling layer, averaging all pixels in a block of size window.

Expects as input an array with ndims(x) == N+2, i.e. channel and batch dimensions, after the N feature dimensions, where N = length(window).

By default the window size is also the stride in each dimension. The keyword pad accepts the same options as for the Conv layer, including SamePad().

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);

Chain(
Conv((5, 5), 3 => 7),                 # 532 parameters
)

julia> m[1](xs) |> size
(96, 96, 7, 50)

julia> m(xs) |> size
(20, 20, 7, 50)
source
Flux.GlobalMeanPoolType
GlobalMeanPool()

Global mean pooling layer.

Transforms (w,h,c,b)-shaped input into (1,1,c,b)-shaped output, by performing mean pooling on the complete (w,h)-shaped feature maps.

julia> xs = rand(Float32, 100, 100, 3, 50);

julia> m = Chain(Conv((3,3), 3 => 7), GlobalMeanPool());

julia> m(xs) |> size
(1, 1, 7, 50)
source
Flux.DepthwiseConvType
DepthwiseConv(filter, in => out, σ=identity; stride=1, pad=0, dilation=1, [bias, init])

Depthwise convolutional layer. filter is a tuple of integers specifying the size of the convolutional kernel, while in and out specify the number of input and output channels.

Note that out must be an integer multiple of in.

Parameters are controlled by additional keywords, with defaults init=glorot_uniform and bias=true.

See also Conv for more detailed description of keywords.

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # a batch of 50 RGB images

julia> lay = DepthwiseConv((5,5), 3 => 6, relu; bias=false)
DepthwiseConv((5, 5), 3 => 6, relu, bias=false)  # 150 parameters

julia> lay(xs) |> size
(96, 96, 6, 50)

julia> DepthwiseConv((5,5), 3 => 9, stride=2, pad=2)(xs) |> size
(50, 50, 9, 50)
source
Flux.ConvTransposeType
ConvTranspose(filter, in => out, σ=identity; stride=1, pad=0, dilation=1, [bias, init])

Standard convolutional transpose layer. filter is a tuple of integers specifying the size of the convolutional kernel, while in and out specify the number of input and output channels.

Note that pad=SamePad() here tries to ensure size(output,d) == size(x,d) * stride.

Parameters are controlled by additional keywords, with defaults init=glorot_uniform and bias=true.

See also Conv for more detailed description of keywords.

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # a batch of 50 RGB images

julia> lay = ConvTranspose((5,5), 3 => 7, relu)
ConvTranspose((5, 5), 3 => 7, relu)  # 532 parameters

julia> lay(xs) |> size
(104, 104, 7, 50)

julia> ConvTranspose((5,5), 3 => 7, stride=2)(xs) |> size
(203, 203, 7, 50)

(300, 300, 7, 50)
source
Flux.CrossCorType
CrossCor(filter, in => out, σ=identity; stride=1, pad=0, dilation=1, [bias, init])

Standard cross convolutional layer. filter is a tuple of integers specifying the size of the convolutional kernel; in and out specify the number of input and output channels.

Parameters are controlled by additional keywords, with defaults init=glorot_uniform and bias=true.

See also Conv for more detailed description of keywords.

Examples

julia> xs = rand(Float32, 100, 100, 3, 50);  # a batch of 50 RGB images

julia> lay = CrossCor((5,5), 3 => 6, relu; bias=false)
CrossCor((5, 5), 3 => 6, relu, bias=false)  # 450 parameters

julia> lay(xs) |> size
(96, 96, 6, 50)

julia> CrossCor((5,5), 3 => 7, stride=3, pad=(2,0))(xs) |> size
(34, 32, 7, 50)
source
Flux.SamePadType
SamePad()

Passed as an option to convolutional layers (and friends), this causes the padding to be chosen such that the input and output sizes agree (on the first N dimensions, the kernel or window) when stride==1.

See also Conv, MaxPool.

source
Flux.flattenFunction
flatten(x::AbstractArray)

Reshape arbitrarly-shaped input into a matrix-shaped output, preserving the size of the last dimension.

See also unsqueeze.

Examples

julia> rand(3,4,5) |> Flux.flatten |> size
(12, 5)

julia> xs = rand(Float32, 10,10,3,7);

julia> m = Chain(Conv((3,3), 3=>4, pad=1), Flux.flatten, Dense(400,33));

julia> xs |> m[1] |> size
(10, 10, 4, 7)

julia> xs |> m |> size
(33, 7)
source
Flux.convfilterFunction
convfilter(filter::Tuple, in => out[; init = glorot_uniform])

Constructs a standard convolutional weight matrix with given filter and channels from in to out.

Accepts the keyword init (default: glorot_uniform) to control the sampling distribution.

See also: depthwiseconvfilter

source
Flux.depthwiseconvfilterFunction
depthwiseconvfilter(filter::Tuple, in => out)

Constructs a depthwise convolutional weight array defined by filter and channels from in to out.

Accepts the keyword init (default: glorot_uniform) to control the sampling distribution.

See also: convfilter

source

## Upsampling Layers

Flux.UpsampleType

Upsample(mode = :nearest; [scale, size]) Upsample(scale, mode = :nearest)

An upsampling layer. One of two keywords must be given:

If scale is a number, this applies to all but the last two dimensions (channel and batch) of the input. It may also be a tuple, to control dimensions individually. Alternatively, keyword size accepts a tuple, to directly specify the leading dimensions of the output.

Currently supported upsampling modes and corresponding NNlib's methods are:

Examples

julia> m = Upsample(scale = (2, 3))
Upsample(:nearest, scale = (2, 3))

julia> m(ones(2, 2, 1, 1)) |> size
(4, 6, 1, 1)

julia> m = Upsample(:bilinear, size = (4, 5))
Upsample(:bilinear, size = (4, 5))

julia> m(ones(2, 2, 1, 1)) |> size
(4, 5, 1, 1)
source

## Recurrent Layers

Much like the core layers above, but can be used to process sequence data (as well as other kinds of structured data).

Flux.RNNFunction
RNN(in::Integer, out::Integer, σ = tanh)

The most basic recurrent layer; essentially acts as a Dense layer, but with the output fed back into the input each time step.

source
Flux.RecurType
Recur(cell)

Recur takes a recurrent cell and makes it stateful, managing the hidden state in the background. cell should be a model of the form:

h, y = cell(h, x...)

For example, here's a recurrent network that keeps a running total of its inputs:

accum(h, x) = (h + x, x)
rnn = Flux.Recur(accum, 0)
rnn(2)      # 2
rnn(3)      # 3
rnn.state   # 5
rnn.(1:10)  # apply to a sequence
rnn.state   # 60
source
Flux.reset!Function
reset!(rnn)

Reset the hidden state of a recurrent layer back to its original value.

Assuming you have a Recur layer rnn, this is roughly equivalent to:

rnn.state = hidden(rnn.cell)
source

## Other General Purpose Layers

These are marginally more obscure than the Basic Layers. But in contrast to the layers described in the other sections are not readily grouped around a particular purpose (e.g. CNNs or RNNs).

Flux.MaxoutType
Maxout(over)

The Maxout layer has a number of internal layers which all receive the same input. It returns the elementwise maximum of the internal layers' outputs.

Maxout over linear dense layers satisfies the univeral approximation theorem.

source
Flux.SkipConnectionType
SkipConnection(layer, connection)

Create a skip connection which consists of a layer or Chain of consecutive layers and a shortcut connection linking the block's input to the output through a user-supplied 2-argument callable. The first argument to the callable will be propagated through the given layer while the second is the unchanged, "skipped" input.

The simplest "ResNet"-type connection is just SkipConnection(layer, +). Here is a more complicated example:

julia> m = Conv((3,3), 4 => 7, pad=(1,1));

julia> x = ones(Float32, 5, 5, 4, 10);

julia> size(m(x)) == (5, 5, 7, 10)
true

julia> sm = SkipConnection(m, (mx, x) -> cat(mx, x, dims=3));

julia> size(sm(x)) == (5, 5, 11, 10)
true
source
Flux.ParallelType
Parallel(connection, layers...)

Create a 'Parallel' layer that passes an input array to each path in layers, reducing the output with connection.

Called with one input x, this is equivalent to reduce(connection, [l(x) for l in layers]). If called with multiple inputs, they are zipped with the layers, thus Parallel(+, f, g)(x, y) = f(x) + g(y).

Examples

julia> model = Chain(Dense(3, 5),
Parallel(vcat, Dense(5, 4), Chain(Dense(5, 7), Dense(7, 4))),
Dense(8, 17));

julia> size(model(rand(3)))
(17,)

julia> model = Parallel(+, Dense(10, 2), Dense(5, 2))
Parallel(
+,
Dense(10, 2),                         # 22 parameters
Dense(5, 2),                          # 12 parameters
)                   # Total: 4 arrays, 34 parameters, 392 bytes.

julia> size(model(rand(10), rand(5)))
(2,)
source
Flux.BilinearType
Bilinear(in1, in2, out, σ=identity; bias=true, init=glorot_uniform)
Bilinear(W::AbstractArray, [bias, σ])

Creates a Bilinear layer, which operates on two inputs at the same time. Its output, given vectors x & y, is another vector z with, for all i ∈ 1:out:

z[i] = σ(x' * W[i,:,:] * y + bias[i])

If x and y are matrices, then each column of the output z = B(x, y) is of this form, with B a Bilinear layer.

If y is not given, it is taken to be equal to x, i.e. B(x) == B(x, x)

The two inputs may also be provided as a tuple, B((x, y)) == B(x, y), which is accepted as the input to a Chain.

The initialisation works as for Dense layer, with W = init(out, in1, in2). By default the bias vector is zeros(Float32, out), option bias=false will switch off trainable bias. Either of these may be provided explicitly.

Examples

julia> x, y = randn(Float32, 5, 32), randn(Float32, 5, 32);

julia> B = Flux.Bilinear(5, 5, 7);

julia> B(x) |> size  # interactions based on one input
(7, 32)

julia> B(x,y) == B((x,y))  # two inputs, may be given as a tuple
true

julia> sc = SkipConnection(
Chain(Dense(5, 20, tanh), Dense(20, 9, tanh)),
Flux.Bilinear(9, 5, 3, bias=false),
);  # used as the recombinator, with skip as the second input

julia> sc(x) |> size
(3, 32)

julia> Flux.Bilinear(rand(4,8,16), false, tanh)  # first dim of weight is the output
Bilinear(8, 16, 4, tanh, bias=false)
source
Flux.DiagonalType
Diagonal(α, β)
Diagonal(size::Integer...)

Create an element-wise linear layer, which performs

y = α .* x .+ β

The learnable arrays are initialised α = ones(Float32, size) and β = zeros(Float32, size).

Used by LayerNorm.

source
Flux.EmbeddingType
Embedding(in, out; init=randn)

A lookup table that stores embeddings of dimension out for a vocabulary of size in.

This layers is often used to store word embeddings and retrieve them using indices. The input to the layer can be either a vector of indexes or the corresponding onehot encoding.

Examples

julia> using Flux: Embedding

julia> vocab_size, embed_size = 1000, 4;

julia> model = Embedding(vocab_size, embed_size)
Embedding(1000, 4)

julia> vocab_idxs = [1, 722, 53, 220, 3]

julia> x = OneHotMatrix(vocab_idxs, vocab_size);

julia> model(x)
4×5 Matrix{Float32}:
0.91139    0.670462    0.463217   0.670462    0.110932
0.247225  -0.0823874   0.698694  -0.0823874   0.945958
-0.393626  -0.590136   -0.545422  -0.590136    0.77743
-0.497621   0.87595    -0.870251   0.87595    -0.772696

julia> model(vocab_idxs) == model(x) true

source

## Normalisation & Regularisation

These layers don't affect the structure of the network but may improve training times or reduce overfitting.

Flux.normaliseFunction
normalise(x; dims=ndims(x), ϵ=1e-5)

Normalise x to mean 0 and standard deviation 1 across the dimension(s) given by dims. Per default, dims is the last dimension. ϵ is a small additive factor added to the denominator for numerical stability.

source
Flux.BatchNormType
BatchNorm(channels::Integer, λ=identity;
initβ=zeros32, initγ=ones32,
ϵ=1f-5, momentum= 0.1f0)

Batch Normalization layer. channels should be the size of the channel dimension in your data (see below).

Given an array with N dimensions, call the N-1th the channel dimension. For a batch of feature vectors this is just the data dimension, for WHCN images it's the usual channel dimension.

BatchNorm computes the mean and variance for each D_1×...×D_{N-2}×1×D_N input slice and normalises the input accordingly.

If affine=true, it also applies a shift and a rescale to the input through to learnable per-channel bias β and scale γ parameters.

After normalisation, elementwise activation λ is applied.

If track_stats=true, accumulates mean and var statistics in training phase that will be used to renormalize the input in test phase.

Use testmode! during inference.

Examples

m = Chain(
Dense(28^2, 64),
BatchNorm(64, relu),
Dense(64, 10),
BatchNorm(10),
softmax)
source
Flux.dropoutFunction
dropout(x, p; dims=:, active=true)

The dropout function. If active is true, for each input, either sets that input to 0 (with probability p) or scales it by 1 / (1 - p). dims specifies the unbroadcasted dimensions, e.g. dims=1 applies dropout along columns and dims=2 along rows. This is used as a regularisation, i.e. it reduces overfitting during training.

If active is false, it just returns the input x.

Warning: when using this function, you have to manually manage the activation state. Usually in fact, dropout is used while training but is deactivated in the inference phase. This can be automatically managed using the Dropout layer instead of the dropout function.

The Dropout layer is what you should use in most scenarios.

source
Flux.DropoutType
Dropout(p; dims=:)

Dropout layer. In the forward pass, apply the Flux.dropout function on the input.

To apply dropout along certain dimension(s), specify the dims keyword. e.g. Dropout(p; dims = 3) will randomly zero out entire channels on WHCN input (also called 2D dropout).

Does nothing to the input once Flux.testmode! is true.

source
Flux.LayerNormType
LayerNorm(sz, λ=identity; affine=true, ϵ=1fe-5)

A normalisation layer designed to be used with recurrent hidden states. The argument sz should be an integer or a tuple of integers. In the forward pass, the layer normalises the mean and standard deviation of the input, the applied the elementwise activation λ. The input is normalised along the first length(sz) dimensions for tuple sz, along the first dimension for integer sz. The input is expected to have first dimensions' size equal to sz.

If affine=true also applies a learnable shift and rescaling as in the Diagonal layer.

source
Flux.InstanceNormType
InstanceNorm(channels::Integer, λ=identity;
initβ=zeros32, initγ=ones32,
affine=false, track_stats=false,
ϵ=1f-5, momentum=0.1f0)

Instance Normalization layer. channels should be the size of the channel dimension in your data (see below).

Given an array with N > 2 dimensions, call the N-1th the channel dimension. For WHCN images it's the usual channel dimension.

InstanceNorm computes the mean and variance for each D_1×...×D_{N-2}×1×1 input slice and normalises the input accordingly.

If affine=true, it also applies a shift and a rescale to the input through to learnable per-channel bias β and scale γ parameters.

If track_stats=true, accumulates mean and var statistics in training phase that will be used to renormalize the input in test phase.

Warning: the defaults for affine and track_stats used to be true in previous Flux versions (< v0.12).

source
Flux.GroupNormType
GroupNorm(channels::Integer, G::Integer, λ=identity;
initβ=zeros32, initγ=ones32,
affine=true, track_stats=false,
ϵ=1f-5, momentum=0.1f0)

Group Normalization layer.

chs is the number of channels, the channel dimension of your input. For an array of N dimensions, the N-1th index is the channel dimension.

G is the number of groups along which the statistics are computed. The number of channels must be an integer multiple of the number of groups.

channels should be the size of the channel dimension in your data (see below).

Given an array with N > 2 dimensions, call the N-1th the channel dimension. For WHCN images it's the usual channel dimension.

If affine=true, it also applies a shift and a rescale to the input through to learnable per-channel bias β and scale γ parameters.

If track_stats=true, accumulates mean and var statistics in training phase that will be used to renormalize the input in test phase.

source

### Testmode

Many normalisation layers behave differently under training and inference (testing). By default, Flux will automatically determine when a layer evaluation is part of training or inference. Still, depending on your use case, it may be helpful to manually specify when these layers should be treated as being trained or not. For this, Flux provides Flux.testmode!. When called on a model (e.g. a layer or chain of layers), this function will place the model into the mode specified.

Flux.testmode!Function
testmode!(m, mode = true)

Set a layer or model's test mode (see below). Using :auto mode will treat any gradient computation as training.

Note: if you manually set a model into test mode, you need to manually place it back into train mode during training phase.

Possible values include:

• false for training
• true for testing
• :auto or nothing for Flux to detect the mode automatically
source
Flux.trainmode!Function
trainmode!(m, mode = true)

Set a layer of model's train mode (see below). Symmetric to testmode! (i.e. trainmode!(m, mode) == testmode!(m, !mode)).

Note: if you manually set a model into train mode, you need to manually place it into test mode during testing phase.

Possible values include:

• true for training
• false for testing
• :auto or nothing for Flux to detect the mode automatically
source