Choose an activation

An activation is available in three forms: a function on a tensor (x.relu6()), an entry of the network DSL (relu6()), and a module (ReLU6()). All three compute the same values.

The activations

Activation Definition Typical use

relu

max(x, 0)

The default for hidden layers

leakyRelu

x for x >= 0, negativeSlope * x below

Where units must not go silent

prelu

as leakyRelu, with a learned slope

Convolutional networks; one slope, or one per channel

elu

x for x >= 0, alpha * (exp(x) - 1) below

Activations with a mean closer to zero

selu

scale * elu(x, alpha) with fixed constants

Self-normalizing dense networks

relu6

min(max(x, 0), 6)

Networks for mobile devices and for quantization

hardSigmoid

relu6(x + 3) / 6

A sigmoid without an exponential

hardSwish

x * relu6(x + 3) / 6

MobileNetV3-style networks

sigmoid

1 / (1 + exp(-x))

Gates and binary outputs

tanh

tanh(x)

Recurrent networks, outputs in [-1, 1]

silu

x * sigmoid(x)

Modern convolutional networks

gelu

x * Phi(x)

Transformers

softplus

log(1 + exp(beta * x)) / beta

A smooth ReLU; outputs that must be positive

mish

x * tanh(softplus(x))

A smooth alternative to ReLU and SiLU

softmax

exp(x) / sum(exp(x)) along a dimension

Class probabilities

In a network

val model = definition<FP32, Float> {
    network(ctx) {
        input(64)
        dense(128)
        hardSwish()
        dense(10)
        softmax()
    }
}

An activation that has no DSL entry of its own can be given as a function: activation { it.softplus(beta = 2f) }.

PReLU

PReLU has a parameter, so it is a module. numParameters is 1 for one slope for the whole input, or the number of channels of an input [N, C, …​]. Every slope starts at init.

val prelu = PReLU<FP32, Float>(numParameters = 16, init = 0.25f)
val y = prelu.forward(x, ctx)

The slope is a trainable parameter: an optimizer that holds the module’s parameters updates it.

How they are built and checked

relu6, hardSigmoid, hardSwish, softplus, mish, selu and prelu are composed from operations that exist already (clamp, exp, log, tanh, elu, relu). They need no kernel of their own: every backend, the gradient tape and the graph export handle them as the operations they are made of.

Their values and gradients are held to PyTorch (torch.nn.functional) by suite TS-018 of skainet-ground-truth: at the points where a formula changes, on random values, and for the gradient of the PReLU slope.

softplus returns x where beta * x is above 20. That is the same value in a 32-bit float, and the exponential is not evaluated there, so a large input cannot overflow.