oneflow.nn.LayerNorm

class oneflow.nn.LayerNorm(normalized_shape: Union[int, Tuple[int], oneflow.Size], eps: float = 1e-05, elementwise_affine: bool = True)

Applies Layer Normalization over a mini-batch of inputs as described in the paper Layer Normalization

\[y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta\]

The mean and standard-deviation are calculated separately over the last certain number dimensions which have to be of the shape specified by normalized_shape. \(\gamma\) and \(\beta\) are learnable affine transform parameters of normalized_shape if elementwise_affine is True. The standard-deviation is calculated via the biased estimator.

Note

Unlike Batch Normalization and Instance Normalization, which applies scalar scale and bias for each entire channel/plane with the affine option, Layer Normalization applies per-element scale and bias with elementwise_affine.

This layer uses statistics computed from input data in both training and evaluation modes.

Parameters
  • normalized_shape (int or list or oneflow.Size) –

    input shape from an expected input of size

    \[[* \times \text{normalized_shape}[0] \times \text{normalized_shape}[1] \times \ldots \times \text{normalized_shape}[-1]]\]

    If a single integer is used, it is treated as a singleton list, and this module will

    normalize over the last dimension which is expected to be of that specific size.

  • eps – a value added to the denominator for numerical stability. Default: 1e-5

  • elementwise_affine – a boolean value that when set to True, this module has learnable per-element affine parameters initialized to ones (for weights) and zeros (for biases). Default: True.

Shape:
  • Input: \((N, *)\)

  • Output: \((N, *)\) (same shape as input)

For example:

>>> import numpy as np
>>> import oneflow as flow

>>> input_arr = np.array(
...     [
...         [
...             [[-0.16046895, -1.03667831], [-0.34974465, 0.26505867]],
...             [[-1.24111986, -0.53806001], [1.72426331, 0.43572459]],
...         ],
...         [
...             [[-0.77390957, -0.42610624], [0.16398858, -1.35760343]],
...             [[1.07541728, 0.11008703], [0.26361224, -0.48663723]],
...         ],
...     ],
...     dtype=np.float32,
... )

>>> x = flow.Tensor(input_arr)
>>> m = flow.nn.LayerNorm(2)
>>> y = m(x).numpy()
>>> y
array([[[[ 0.99997395, -0.99997395],
         [-0.999947  ,  0.999947  ]],

        [[-0.99995965,  0.9999595 ],
         [ 0.99998784, -0.99998784]]],


       [[[-0.9998348 ,  0.99983466],
         [ 0.9999914 , -0.9999914 ]],

        [[ 0.9999785 , -0.9999785 ],
         [ 0.9999646 , -0.9999646 ]]]], dtype=float32)