Embeddings, Normalization, Dropout & Activations

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Between the linear and convolution layers (Linear, Convolution & Pooling Layers) and the loss functions sit the small layers that decide whether a network trains well: embeddings that turn ids into vectors, normalization that keeps activations well scaled, dropout that regularizes, and activations that add nonlinearity. The theory is in Training Deep Networks, Neural Network Fundamentals and Embeddings & Representation Learning. This page is the PyTorch reference: constructor arguments, defaults, behaviour differences between train() and eval(), and the mistakes that cost the most time.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. Functional equivalents of these modules (F.layer_norm, F.dropout, F.gelu, …​) are covered in torch.nn.functional. For production text embeddings and vector search see Embeddings.

Embeddings

nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False) is a lookup table: a weight matrix of shape (num_embeddings, embedding_dim), initialized from \(\mathcal{N}(0, 1)\), indexed by an integer tensor of any shape. The output has the input shape with embedding_dim appended. The input must be torch.long (or torch.int) ids in [0, num_embeddings); an out-of-range id raises an index error on CPU and a device-side assert on CUDA, which is a classic cause of confusing GPU crashes.

  • padding_idx: the vector at that index receives no gradient and starts as zeros. You can overwrite it, but it is still not updated by training.

  • max_norm and norm_type: rows that are looked up and exceed the norm are renormalized in place in the weight. If you apply a differentiable operation to Embedding.weight before the forward call, clone it first or autograd can fail.

  • scale_grad_by_freq: scales gradients by the inverse frequency of the ids in the mini-batch, which counteracts very frequent ids.

  • sparse=True: the gradient of the weight is a sparse tensor, which saves memory for huge tables. Only some optimizers accept sparse gradients: SGD (CPU and CUDA), SparseAdam (CPU and CUDA) and Adagrad (CPU only). Adam and AdamW do not. See Optimizers.

import torch
from torch import nn

emb = nn.Embedding(num_embeddings=10_000, embedding_dim=64, padding_idx=0)
ids = torch.tensor([[5, 17, 0, 0], [9, 4, 3, 0]])
x = emb(ids)                                  # (2, 4, 64)
print(x.shape, x[0, 2].abs().sum())           # the padding row is all zeros

# Load vectors that were trained elsewhere. freeze=True (the default) sets requires_grad=False.
pretrained = torch.randn(10_000, 64)
frozen = nn.Embedding.from_pretrained(pretrained, freeze=True, padding_idx=0)
tuned = nn.Embedding.from_pretrained(pretrained, freeze=False, padding_idx=0)

# Weight tying: reuse the input embedding as the output projection of a language model.
vocab, d = 10_000, 64
lm_head = nn.Linear(d, vocab, bias=False)
lm_head.weight = emb.weight

nn.EmbeddingBag computes the sum, mean or max of a bag of embeddings without materializing the intermediate (L, d) tensor; it is the efficient layer for bag-of-words style inputs and recommendation features, taking a flat id tensor plus offsets. Positional encodings are not provided by PyTorch; learned positions are another nn.Embedding (as in the encoder example of Attention, SDPA, FlexAttention & Transformers) and sinusoidal or rotary encodings are written by hand.

Normalization layers

The 2.15 torch.nn page lists BatchNorm1d/2d/3d, their Lazy variants, SyncBatchNorm, GroupNorm, InstanceNorm1d/2d/3d, LayerNorm, LocalResponseNorm and RMSNorm. They differ in which axes the statistics are computed over, which determines when each is appropriate.

Layer Statistics over Typical use

BatchNorm1d/2d/3d

Batch and spatial axes, per channel

CNNs with reasonably large batches

LayerNorm

The trailing normalized_shape dimensions of each sample

Transformers, RNNs, small batches

RMSNorm

Root mean square over the trailing dimensions, no mean subtraction

Recent large language models

GroupNorm

Groups of channels within each sample

CNNs with small or varying batches (detection, segmentation)

InstanceNorm

Each channel of each sample

Style transfer and image generation

BatchNorm

nn.BatchNorm1d(num_features, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (and the 2d and 3d versions) normalizes each channel with batch statistics in training and with stored running estimates in evaluation. Details that matter:

  • In training the forward pass uses the biased variance; the stored running_var is updated with the unbiased variance.

  • momentum is the weight of the new observation in the running averages (0.1 by default). It is unrelated to optimizer momentum. momentum=None switches to a simple cumulative average.

  • With track_running_stats=False there are no running buffers and the layer uses batch statistics in both modes.

  • running_mean and running_var are buffers: they are saved in the state_dict and moved with .to(device), but they are not parameters and optimizers never see them.

  • Forgetting model.eval() at validation time is the single most common batch-norm bug: the output then depends on the other samples in the batch and the running statistics keep changing.

  • Batch norm needs more than one value per channel in training; a batch of one sample (or a final batch of size one) fails or is meaningless. Use drop_last=True in the DataLoader or GroupNorm.

  • SyncBatchNorm computes statistics across processes in distributed training; convert with nn.SyncBatchNorm.convert_sync_batchnorm(model) (see DistributedDataParallel).

  • Freezing a pretrained network for fine-tuning requires putting the batch-norm layers in eval() mode as well as setting requires_grad=False on their parameters (see Transfer Learning & Fine-Tuning).

LayerNorm, RMSNorm and GroupNorm

nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True) normalizes over the last dimensions given by normalized_shape, with identical behaviour in training and evaluation and no dependence on batch size. nn.RMSNorm(normalized_shape, eps=None, elementwise_affine=True) divides by the root mean square only, \(y_i = x_i / \sqrt{\varepsilon + \tfrac{1}{n}\sum_j x_j^2}\cdot\gamma_i\), skipping the mean subtraction and the bias. With eps=None it uses the machine epsilon of the computation type (the float32 epsilon for float16, bfloat16 and float32 inputs). nn.GroupNorm(num_groups, num_channels, eps=1e-05, affine=True) requires num_channels divisible by num_groups.

import torch
from torch import nn

x = torch.randn(8, 16, 32, 32)             # (N, C, H, W)

bn = nn.BatchNorm2d(16)
gn = nn.GroupNorm(num_groups=4, num_channels=16)
inorm = nn.InstanceNorm2d(16, affine=True)

tokens = torch.randn(8, 128, 256)          # (N, L, E)
ln = nn.LayerNorm(256)                     # per-token normalization over E
rms = nn.RMSNorm(256)

for m in (bn, gn, inorm):
    print(type(m).__name__, m(x).shape)
print(ln(tokens).shape, rms(tokens).shape)

# Train versus eval statistics
bn.train(); _ = bn(x); print(bn.running_mean[:3], bn.num_batches_tracked)
bn.eval();  y_eval = bn(x)                 # now uses the running estimates

In Transformers the position of the norm matters: post-norm applies it after the residual add, pre-norm (norm_first=True in the nn.Transformer layers) before each sub-layer. Pre-norm trains deeper stacks more stably and usually does not need as careful a warm-up. Under mixed precision, normalization layers are among the operations autocast runs in float32 (see Mixed Precision with torch.amp).

Dropout

nn.Dropout(p=0.5, inplace=False) zeroes each element independently with probability p during training and scales the survivors by \(1/(1-p)\) so the expected value is unchanged; in eval() it is the identity. p is the drop probability, not the keep probability as in some other frameworks' older examples.

  • Dropout1d, Dropout2d and Dropout3d zero entire channels. Use them after convolutions, where neighbouring activations are strongly correlated and element-wise dropout barely regularizes.

  • AlphaDropout and FeatureAlphaDropout preserve the mean and variance for SELU networks.

  • F.dropout(x, p, training=...) defaults to training=True, so a functional call inside a module must pass self.training or it keeps dropping at evaluation time. The module version follows train() and eval() automatically.

  • Dropout in attention: F.scaled_dot_product_attention(dropout_p=...) ignores the module mode, so pass 0.0 at evaluation.

  • Monte Carlo dropout (keeping dropout active at inference to sample predictions) is done by calling .train() on the dropout layers only, not on batch-norm layers.

import torch
from torch import nn

class Head(nn.Module):
    def __init__(self, d_in, n_classes, p=0.3):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(d_in, 256), nn.GELU(), nn.Dropout(p), nn.Linear(256, n_classes)
        )

    def forward(self, x):
        return self.net(x)

head = Head(128, 10)
x = torch.randn(4, 128)
head.train(); a, b = head(x), head(x)
print(torch.allclose(a, b))                # False: different dropout masks
head.eval();  a, b = head(x), head(x)
print(torch.allclose(a, b))                # True: dropout is the identity

# Monte Carlo dropout: only the Dropout modules stay in training mode
head.eval()
for m in head.modules():
    if isinstance(m, nn.Dropout):
        m.train()
samples = torch.stack([head(x) for _ in range(20)])
print(samples.std(0).mean())

Activation modules

Activations exist both as modules (nn.ReLU()) and as functions (F.relu, torch.relu). Use modules inside nn.Sequential and when you want the activation visible in print(model); use functions inside forward. Choosing among them is discussed in Neural Network Fundamentals.

Module Notes Typical place

nn.ReLU, nn.LeakyReLU, nn.PReLU, nn.ReLU6

inplace=True saves memory but can break autograd if the input is needed again; PReLU has a learnable slope.

CNNs, MLPs

nn.GELU with approximate

'none' (the default) is the exact \(x\Phi(x)\); 'tanh' is the faster approximation. Use the same variant that a pretrained model was trained with.

Transformer feed-forward blocks

nn.SiLU, nn.Mish

\(x\sigma(x)\); SiLU is the "swish" used in many CNNs and gated MLPs.

Modern CNNs, LLM MLPs

nn.GLU

Splits the input in two halves along dim and gates one with the sigmoid of the other. Gated variants such as SwiGLU are built from nn.Linear plus SiLU by hand.

Gated feed-forward

nn.ELU, nn.SELU, nn.CELU

SELU is meant for self-normalizing networks with AlphaDropout.

Less common now

nn.Sigmoid, nn.Tanh, nn.Hardsigmoid, nn.Hardswish

Saturating; avoid in deep hidden stacks. Hard variants suit mobile models.

Gates, output ranges

nn.Softmax(dim), nn.LogSoftmax(dim), nn.Softmin

dim is required in practice; omitting it relies on a deprecated implicit choice. Do not apply before CrossEntropyLoss.

Probabilities for inference

import torch
from torch import nn

mlp = nn.Sequential(
    nn.Linear(32, 64), nn.GELU(approximate="tanh"),
    nn.Linear(64, 64), nn.SiLU(),
    nn.Linear(64, 5),
)
logits = mlp(torch.randn(10, 32))
probs = nn.Softmax(dim=-1)(logits)         # inference only: the training loss takes logits
print(probs.sum(-1))                       # all ones


class SwiGLU(nn.Module):
    def __init__(self, d, hidden):
        super().__init__()
        self.gate = nn.Linear(d, hidden, bias=False)
        self.up = nn.Linear(d, hidden, bias=False)
        self.down = nn.Linear(hidden, d, bias=False)

    def forward(self, x):
        return self.down(nn.functional.silu(self.gate(x)) * self.up(x))

Pitfalls checklist

  • Embedding ids are integers in range; floats or negative ids fail.

  • Apply model.eval() before validation: it changes batch norm and dropout.

  • Do not put a softmax before nn.CrossEntropyLoss (see Loss Functions).

  • A frozen batch-norm layer still updates its running statistics unless it is in eval() mode.

  • nn.Embedding(max_norm=...) edits the weight in place and conflicts with autograd tricks.

  • sparse=True embeddings require a sparse-capable optimizer.

  • Changing normalization type after pretraining changes the model; load matching layers or retrain.

  • Weight decay is usually not applied to normalization parameters and biases; use parameter groups (see Optimizers).