Dropout, CNNs, Normalization, Skip Connections, Loss, Embeddings
This post follows from the deep neural networks post and introduces other modules of modern neural networks.
Dropout
Dropout is a method that drops neurons (in different layers) with a given probability \(p\) at training time. For each training sample, a new thinned network is sampled, made of the neurons that are kept. The outputs of the kept neurons are scaled by \(1/(1-p)\) at training time, so that the expected output of each neuron is the same at training and inference time. At inference time, no neuron is dropped: the full network approximates the average of the predictions of all the thinned networks, which is much cheaper than averaging several trained networks. The following picture, adapted from the paper, illustrates a standard network (left) and one of its thinned networks (right):
class Dropout:
def __init__(self, p=0.5):
self.p, self.training = p, True # training is False at inference time
def forward(self, x):
if not self.training:
return x
self.mask = (np.random.rand(*x.shape) >= self.p) / (1 - self.p) # scaled kept units
return x * self.mask
def backward(self, dx):
return dx * self.mask
def parameters(self):
return []
Dropout reduces overfitting: the network cannot rely on any single activation, so it learns redundant ways of solving the task with several neurons. It also leads to sparse activations. The paper found that dropping 20% of the input units and 50% of the hidden units is often close to optimal. However, a dropout network takes 2 to 3 times longer to train than a standard network, as its parameter updates are very noisy.
Convolutional Neural Networks
Large fully connected networks have a very high number of parameters, so they may require lots of data to be trained. In some scenarios, local connectivity should suffice. For example, an image \(x^{(0)}[n,m]\) is naturally processed by a linear shift-invariant filter, whose output \(x^{(1)}[n,m]\) is given by the convolution of the input with the filter \(h[n,m]\):
\[x^{(1)}[n,m] = \sum_{u,v} h[u,v]x^{(0)} [n-u,m-v]\]An appropriate filter brings out features of the image, such as its edges. With a small filter, the output \(x^{(1)}\) at position \([n, m]\) only depends on the input near \([n, m]\). Thus, a fully connected network is not needed, only one that connects nearby positions, with far fewer parameters. In practice, a convolution works as a sliding window of a filter (kernel), where the output at each position is the sum of the inputs under the window, weighted by the kernel. Each output channel (or feature map) has its own kernel, which spans all the channels of the input. A deep network of such layers is a convolutional neural network (CNN), illustrated below:
A CNN that classifies \(16 \times 16\) RGB patches of a satellite image as road or non-road: each stage of convolution/pooling/fully-connected layers. Each label gives the shape of the data after a layer for \(N\) input images, with the number of channels or units in brackets. At the end, the output probabilities of the two classes.
Notice the three types of operations involved:
- convolutional layer: slides its kernels over the input, and passes the result to the next layer. Deep learning libraries compute a cross-correlation, \(x^{(1)}[n,m] = \sum_{u,v} h[u,v] \, x^{(0)}[n+u,m+v]\), i.e. a convolution with a flipped kernel; as the kernel is learned, the two are equivalent;
- pooling: combines the outputs of a cluster of neurons into a single neuron in the next layer. Max pooling keeps the maximum of each window (\(2 \times 2\) in the picture), which makes the output robust to small shifts of the input, while average pooling smooths it and is mostly used once at the end of a network, over each whole feature map;
- fully connected: the layers of a multi-layer perceptron (MLP), a universal approximator, which map the features to the output.
For larger shifts, rotations and scalings, a spatial transformer learns to warp the feature maps of each input.
Normalization
The distribution of the inputs of each layer changes during training, as the parameters of the layers before it change. The paper Batch Normalization calls this change internal covariate shift: it slows down training, as it requires lower learning rates and a careful initialization. Normalization layers fix the mean (typically to 0) and the variance (to 1) of the inputs of a layer. This also improves numerical precision, as it keeps the values near zero, where floating-point numbers are densest. The methods differ in the dimensions that they normalize over:
- batch normalization (BN) normalizes each feature, or each channel of a feature map, over the samples of the mini-batch (and over all positions in a CNN). It is the normalization of CNNs trained with large mini-batches;
- layer normalization (LN) normalizes each sample over its features. It does not depend on the other samples, and it is the normalization of recurrent neural networks (RNNs) and Transformers;
- instance normalization (IN) normalizes each channel of each sample over its positions. It removes the contrast of each image, and is used in style transfer and image generation;
- group normalization (GN) normalizes each sample over groups of channels, with all their positions. LN is GN with one group, and IN is GN with one channel per group. It replaces BN in CNNs trained with small mini-batches, e.g. for object detection and segmentation;
- RMSNorm is LN without the mean: it divides each sample by the root mean square of its features. It is cheaper than LN, and it is used in most recent large language models (LLMs);
-
adaptive layer normalization (AdaLN) adapts LN to a condition, extra information about each sample, e.g. the timestep of a diffusion model or a class label. LN normalizes each sample \(x\) with the mean \(\mu\) and the variance \(\sigma^2\) of its features, and then applies a learned scale \(\gamma\) and shift \(\beta\), the same for all samples, whatever their condition. AdaLN instead computes \(\gamma\) and \(\beta\) from an embedding \(c\) of the condition. LN and AdaLN are given by:
\[\begin{align*} \text{LN}(x) & = \gamma \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta \\ \text{AdaLN}(x, c) & = \gamma(c) \odot \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} + \beta(c) \end{align*}\]where \(\epsilon\) is a small constant against a division by zero, and \(\odot\) is the element-wise product. A linear layer computes \(\gamma(c) = c W_\gamma + b_\gamma\) and \(\beta(c) = c W_\beta + b_\beta\), with the learned weights \(W_\gamma\) and \(W_\beta\) and biases \(b_\gamma\) and \(b_\beta\). This lets the condition steer the features inside the network at a lower cost than cross-attention layers.
The following picture illustrates the values that BN, LN, IN and GN normalize together:
The values that batch, layer, instance and group normalization normalize together (blue), in a tensor of feature maps with the batch axis \(N\) (\(B\) in the text), the channel axis \(C\), and the spatial axes \(H\) and \(W\) drawn as one. Adapted from: Group Normalization
BN normalizes each feature \(x\), a column of the \(B \times K\) input \(X\) of the layer, with its mean \(\mu\) and its variance \(\sigma^2\) over the mini-batch, and then scales and shifts it, as (Algorithm 1 in the paper):
\[\mu = \frac{1}{B} \mathbf{1}^T x, \quad \sigma^2 = \frac{1}{B} \lVert x - \mu \mathbf{1} \rVert^2, \quad \hat{x} = \frac{x - \mu \mathbf{1}}{\sqrt{\sigma^2 + \epsilon}}, \quad y = \gamma \hat{x} + \beta \mathbf{1}\]where \(\mathbf{1}\) is a column of \(B\) ones, \(\epsilon\) is a small constant against a division by zero, and \(\gamma\) and \(\beta\) are two learned parameters of the feature, which can give it any other mean and variance. At inference time, the batch may hold a single sample, so BN normalizes with running averages of the mean and the variance, computed during training. The other normalization methods compute the same at training and inference time. In training, BN also updates the running averages, with the weight momentum of the new statistics:
class BatchNorm: # statistics over all axes but the last: the samples and the positions
def __init__(self, n, eps=1e-5, momentum=0.1):
self.gamma, self.beta = Parameter(np.ones(n)), Parameter(np.zeros(n))
self.eps, self.momentum, self.training = eps, momentum, True
self.mean, self.var = np.zeros(n), np.ones(n) # running averages, for inference
def forward(self, x):
self.axes = tuple(range(x.ndim - 1))
if self.training:
mu, var = x.mean(axis=self.axes), x.var(axis=self.axes)
k = x.size // len(mu) # values per feature
self.mean += self.momentum * (mu - self.mean)
self.var += self.momentum * (var * k / (k - 1) - self.var) # unbiased variance
else:
mu, var = self.mean, self.var
self.s = np.sqrt(var + self.eps)
self.x_hat = (x - mu) / self.s # saved for the backward pass
return self.gamma.data * self.x_hat + self.beta.data
The backward pass also goes through \(\mu\) and \(\sigma^2\), as they depend on every sample. With \(g = \gamma \, \partial \mathcal{L} / \partial y\), the derivative of the loss with respect to \(\hat{x}\), the chain rule gives:
\[\frac{\partial \mathcal{L}}{\partial x} = \frac{1}{\sqrt{\sigma^2 + \epsilon}} \left( g - \frac{1}{B} (\mathbf{1}^T g) \, \mathbf{1} - \frac{1}{B} (\hat{x}^T g) \, \hat{x} \right), \quad \frac{\partial \mathcal{L}}{\partial \gamma} = \hat{x}^T \frac{\partial \mathcal{L}}{\partial y}, \quad \frac{\partial \mathcal{L}}{\partial \beta} = \mathbf{1}^T \frac{\partial \mathcal{L}}{\partial y}\]where the second and the third terms in the brackets come from the mean and the variance. In code, BN averages over all axes but the last, so that it follows a fully connected layer (\(B \times K\)) as well as a convolutional layer (\(B \times H \times W \times C\)):
def backward(self, dy):
self.gamma.grad += np.sum(dy * self.x_hat, axis=self.axes)
self.beta.grad += np.sum(dy, axis=self.axes)
g = dy * self.gamma.data # the derivative with respect to x_hat
return (g - g.mean(axis=self.axes) - self.x_hat * np.mean(g * self.x_hat, axis=self.axes)) / self.s
def parameters(self):
return [self.gamma, self.beta]
Skip Connections
In very deep networks, the accuracy drops as the depth increases. This is known as the degradation problem, and it is not caused by overfitting, since the training error increases as well. Skip connections feed the output of a layer to a later layer, skipping the layers in between. In ResNet, a block of layers adds its input \(x\) to the output of its layers, \(F(x)\), so that the layers only need to learn a correction (a residual) to their input:
\[\begin{align*} y & = x + F(x) \\ \frac{\partial \mathcal{L}}{\partial x} & = \frac{\partial \mathcal{L}}{\partial y} + \left( \frac{\partial F}{\partial x} \right)^T \frac{\partial \mathcal{L}}{\partial y} \end{align*}\]In the backward pass, the first term passes the gradient of the layers above to the layers below unchanged, so the gradient does not vanish, even when the derivatives of the skipped layers are small. In code, a residual block is an MLP of the skipped layers, whose output is added to its input:
class Residual(MLP): # y = x + F(x), with the layers of F
def __init__(self, *layers):
self.layers = list(layers)
def forward(self, x):
return x + super().forward(x)
def backward(self, dy):
return dy + super().backward(dy)
For a more advanced implementation, manifold-constrained hyper-connections (mHC), used in DeepSeek-V4, widen \(x\) into several streams, mixed by learned doubly stochastic matrices that keep the signal stable. Deeply-supervised nets fight vanishing gradients in another way: they add a classifier and its loss to each hidden layer.
Loss Functions
The choice of the loss function depends on the task. Each loss below is averaged over a mini-batch of \(B\) samples.
Mean squared error (MSE). Regression tasks predict a real value \(\hat{y}_i\) for each target \(y_i\), and mostly use the MSE of the post on deep neural networks, \(\mathcal{L} = \frac{1}{B} \sum_{i=1}^{B} (y_i - \hat{y}_i)^2\). Its square penalizes the large errors the most, which suits targets with Gaussian noise, but makes it sensitive to outliers.
Mean absolute error (MAE). The MAE, \(\mathcal{L} = \frac{1}{B} \sum_{i=1}^{B} \vert y_i - \hat{y}_i \vert\), grows linearly with the error, not quadratically, so it is more robust to outliers. However, its gradient keeps its size near the minimum, so it needs a smaller learning rate there.
Huber loss. The Huber loss combines the MSE and the MAE. It is given by:
\[\mathcal{L} = \frac{1}{B} \sum_{i=1}^{B} \rho(y_i - \hat{y}_i), \quad \rho(\epsilon) = \begin{cases} \frac{1}{2} \epsilon^2 & \text{for } \vert \epsilon \vert < k \\ k \vert \epsilon \vert - \frac{1}{2} k^2 & \text{for } \vert \epsilon \vert \geq k \end{cases}\]where \(\rho\) is the loss of a sample with the error \(\epsilon\), and \(k\) is the threshold at which its two parts meet with the same value and slope. Thus, its gradient shrinks near the minimum, as with the MSE, and stays bounded for outliers, as with the MAE. However, \(k\) is one more hyper-parameter, which depends on the scale of the targets.
Cross-entropy (CE). Classification tasks use the cross-entropy. The network outputs one logit \(z_c\) per class, and the softmax turns them into probabilities, \(p_c = \exp(z_c) / \sum_{c'} \exp(z_{c'})\). The softmax is preferred over a division by the sum, as it accepts negative logits, and its logarithm suits the cross-entropy. With two classes, or several labels per sample, the binary cross-entropy (BCE) uses one sigmoid output \(p_i\) per label instead, the probability that the label \(y_i\) is 1. The two losses are given by:
\[\mathcal{L}_\text{CE} = -\frac{1}{B} \sum_{i=1}^{B} \log p_{i, y_i}, \quad \mathcal{L}_\text{BCE} = -\frac{1}{B} \sum_{i=1}^{B} \left( y_i \log p_i + (1 - y_i) \log (1 - p_i) \right)\]where \(p_{i, y_i}\) is the probability of the true class \(y_i\) of the sample \(i\). Both are preferred over the MSE for classification, as their gradient with respect to the logits, \((p - y) / B\), does not vanish when the model is confidently wrong.
Contrastive loss. The contrastive loss learns embeddings, vectors that are close for similar inputs and far apart for dissimilar ones, e.g. for signature or face verification. It trains siamese networks, two copies of one network with shared weights, on pairs of inputs labeled as similar (\(y = 1\)) or dissimilar (\(y = 0\)). With the Euclidean distance \(\delta\) between the two embeddings of a pair, it is given by:
\[\mathcal{L} = \frac{1}{2} y \, \delta^2 + \frac{1}{2} (1-y) \max(0, m - \delta)^2\]where the margin \(m\) is a hyper-parameter. The loss pulls similar pairs together, and pushes dissimilar pairs apart until their distance reaches \(m\).
Triplet loss. The triplet loss learns embeddings from triplets: an anchor \(x\), a positive \(x^+\) of the same class, e.g. another picture of the same person, and a negative \(x^-\) of another class. It was introduced for tasks with a very large number of classes, such as face recognition, and is given by:
\[\mathcal{L} = \max \left( \lVert f(x) - f(x^+) \rVert^2 - \lVert f(x) - f(x^-) \rVert^2 + m, 0 \right)\]where \(f(x)\) is the embedding of \(x\), and \(m\) is a margin. Unlike the contrastive loss, which constrains absolute distances, the triplet loss constrains relative ones: the negative must be farther from the anchor than the positive, by the margin.
InfoNCE loss. The InfoNCE loss compares an anchor, the query \(q\), with one positive key \(k^+\) and many negative keys \(k^-\) at once: the query must pick its positive key among all the keys. For unit-length embeddings, it is given by (Eq. 1 in MoCo):
\[\mathcal{L}_q = - \log \frac{\exp(q^T k^+ / \tau)}{\exp(q^T k^+ / \tau) + \sum_{k^-} \exp(q^T k^- / \tau)}\]where \(q^T k\) is the cosine similarity of the query and a key, and the temperature \(\tau\) scales the similarities. The negatives of a query are usually the positive keys of the other queries of the mini-batch. With the \(B\) queries and their positive keys in the rows of \(Q\) and \(K^+\), InfoNCE is then the cross-entropy of the logits \(Z = Q (K^+)^T / \tau\), where the true class of the query \(i\) is the key \(i\). It gives each query \(B-1\) negatives from one matrix multiplication, so it has replaced the triplet loss for search. The contrastive loss still suits verification, as its margin gives a fixed threshold on the distance.
Connectionist Temporal Classification (CTC) loss. The CTC loss trains sequence models, such as RNNs, when the alignment of the target to the input is unknown, as in speech and handwriting recognition. At each time step, the network outputs the probability of each label and of an extra blank label (−). An alignment has one label per time step, and gives the target once its repeated labels and its blanks are removed, e.g. “c−aat” gives “cat”. The loss is the negative logarithm of the probability of the target \(l\), the sum over all its alignments \(\pi\):
\[\mathcal{L} = -\log \sum_{\pi \in \mathcal{B}^{-1}(l)} \prod_{t=1}^{T} p^t_{\pi_t}\]where \(\mathcal{B}^{-1}(l)\) is the set of the alignments of \(l\), \(T\) is the number of time steps, and \(p^t_k\) is the probability of the label \(k\) at time \(t\). The number of alignments grows exponentially with \(T\), so the sum is computed by dynamic programming, with a forward and a backward pass over the target.
Focal loss. The focal loss extends the cross-entropy to imbalanced classes, e.g. in dense object detection, where the background is much more common than the objects. It down-weights the loss of the easy examples, so that the many easy examples of the background do not dominate the loss (Eq. 5 in the paper):
\[\mathcal{L} = -\alpha_t (1 - p_t)^\gamma \log(p_t)\]where \(p_t\) is the predicted probability of the true class, \(\alpha_t\) is a weight of the true class, and \(\gamma\) is the focusing parameter, usually 2. With \(\gamma = 0\), it is the cross-entropy weighted by \(\alpha_t\). The following picture shows the focal loss for several values of \(\gamma\):
The focal loss as a function of \(p_t\), with \(\alpha_t = 1\), for values of \(\gamma\) from 0, the cross-entropy, to 5. A larger \(\gamma\) lowers the loss of the well-classified examples (\(p_t > 0.5\)) the most, which puts more focus on the misclassified ones. Inspired by: Focal Loss for Dense Object Detection
Dice loss. The Dice loss is used in image segmentation, mostly in medical imaging, where the objects (e.g. tumors) cover a small part of the image. It maximizes the overlap of the predicted and the true masks, measured by the Dice coefficient, from 0 (no overlap) to 1 (perfect overlap), so that a small object counts as much as the background. With the softmax outputs \(p_{i,c}\) and the one-hot ground truth \(g_{i,c}\) of the pixel \(i\) (of \(M\)) for the class \(c\) (of \(C\)), it is given by:
\[\mathcal{L} = 1 - \frac{1}{C} \sum_{c=1}^{C} \frac{2 I_c}{S_c}, \quad I_c = \sum_{i=1}^{M} p_{i,c} \, g_{i,c}, \quad S_c = \sum_{i=1}^{M} \left( p_{i,c} + g_{i,c} \right)\]where \(I_c\) is the overlap of the two masks of the class \(c\), and \(S_c\) the sum of their sizes.
Embeddings
Embeddings are dense, low-dimensional vectors that represent data (e.g. words, images or the rows of a table). The layer that converts data to that latent embedding is called encoder, and the converse operation is given by decoder.
Tokens. A tokenizer splits the text into tokens, words or frequent pieces of words, and maps each token to its index in a vocabulary of \(V\) tokens. An embedding layer then gives each token its embedding, a row of a \(V \times E\) matrix \(W\). It is a lookup table (nn.Embedding in PyTorch), that extracts the row at the index of the token, mathematically equivalent to the product of the one-hot vector \(x\) of a token with a dictionary table. During training, only the selected index rows are backpropagated:
So \(W\) is a lookup table (nn.Embedding in PyTorch): in practice, the layer reads the row at the index of the token, with no product.
Words. Word2vec learns one embedding per word of a vocabulary of \(V\) words. Its encoder is the lookup table \(W\), and its decoder is a matrix \(W'\) followed by a softmax over the vocabulary. The continuous bag of words (CBOW) model predicts a word from the words around it, while the skip-gram model predicts the words around each word, as illustrated below. CBOW is faster to train and better at syntactic relationships (‘cat’ is close to ‘cats’), and skip-gram at semantic ones (‘cat’ is close to ‘dog’).
Text. Word2vec gives ‘bank’ the same embedding in ‘river bank’ and in ‘bank account’. A Transformer encoder, such as BERT, gives each token an embedding that depends on its context. Its first layer is a lookup table, and the attention layers after it add the context. BERT is pre-trained to predict masked tokens, as illustrated below:
BERT: the encoder gives each token an embedding, a row of the matrix, and the decoder predicts the masked token from its row. Inspired by: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Positional. Self-attention compares each token with all other tokens in \(\text{softmax}(Q K^T)\), but ignores their order. An absolute positional embedding encodes the position of a token in the sequence. The Transformer computes them from sine and cosine waves, with one frequency per pair of dimensions, and adds them to the model input \(x\). The embedding of position \(m\) is given by:
\[PE_{m,2i} = \sin(m \theta_i), \quad PE_{m,2i+1} = \cos(m \theta_i)\]where \(\theta_i = 10000^{-2i/E}\) is the frequency of the pair \(i = 0, \ldots, E/2-1\). Together, the pairs give each position a unique pattern. The following picture shows the first three pairs for \(E = 16\):
The rotary position embedding (RoPE) encodes relative positions. In every attention layer, it rotates each pair \(i\) of dimensions of the query \(q\) and the key \(k\) of the token at position \(m\) by the angle \(m \theta_i\):
\[\begin{bmatrix} q'_{m,2i} \\ q'_{m,2i+1} \end{bmatrix} = \begin{bmatrix} \cos m\theta_i & -\sin m\theta_i \\ \sin m\theta_i & \cos m\theta_i \end{bmatrix} \begin{bmatrix} q_{m,2i} \\ q_{m,2i+1} \end{bmatrix}\]where \(\theta_i = 10000^{-2i/d}\) and \(d\) is the number of rotated dimensions, i.e. the head size. The queries \(Q = X W^Q\) and the keys \(K = X W^K\) are projections of the input \(X\). RoPE rotates each row \(q_m\) of \(Q\) to \(q_m R_m^T\), and each row \(k_n\) of \(K\) to \(k_n R_n^T\), where \(R_m\) applies the rotation above to all pairs \((2i, 2i+1)\). The score is then computed as:
\[q_m R_m^T (k_n R_n^T)^T = q_m R_m^T R_n k_n^T = q_m R_{n-m} k_n^T\]where the transpose of a rotation rotates by the opposite angles, i.e. \(R_m^T R_n = R_{-m} R_n = R_{n-m}\). Thus, the score depends on the positions only through their distance \(n - m\). The model learns \(W^Q\) and \(W^K\) to work with the rotation angles, e.g. it may put the features of short-range context in the pairs that rotate fast, and those of long-range context in the pairs that rotate slowly.
However, RoPE has three issues in long contexts:
- extrapolation: the fast pairs (low \(i\)) turn many times over the training length and only tell nearby tokens apart. Past the training length, the slow pairs (high \(i\)) take angles never seen in training, the attention scores go out of distribution, and the perplexity explodes;
- precision: the rotated query and key are stored in BF16, which cannot resolve the small turn of the slowest pairs from one token to the next;
- rounding: BF16 rounding makes the score of one distance depend on the absolute positions, and more so as the context grows.
As a solution, Position Interpolation scales all positions down into the trained range, and YaRN only the slow pairs; both need only a short fine-tuning.
3D RoPE (Lumina-Next) splits the pairs of each head into three groups, rotated by the frame \(t\), the row \(h\) and the column \(w\) of the patch. It replaces \(R_m\) with \(R_{t,h,w}\), defined as (Eq. 2 in the paper):
\[R_{t,h,w} = \begin{bmatrix} R_t & 0 & 0 \\ 0 & R_h & 0 \\ 0 & 0 & R_w \end{bmatrix}\]where \(R_t\), \(R_h\) and \(R_w\) are RoPE rotations over \(d/3\) dimensions, with \(\theta_i = 10000^{-6i/d}\). Thus, the score of two patches depends on their distances in time, height and width.
Images. The encoder is a CNN or a Vision Transformer (ViT), which reads patches of the image as tokens. A masked autoencoder needs no labels: it masks 75% of the patches, encodes the visible ones, and trains a small decoder to rebuild the image:
A masked autoencoder: the decoder rebuilds the image from the embeddings of the visible patches and a mask token for each masked patch. Adapted from: Masked Autoencoders Are Scalable Vision Learners
Multi-modal Contextual embeddings. CLIP trains an image encoder and a text encoder together, with InfoNCE on 400 million images and their captions. An image and its caption (ie with a similar context) then have close embeddings. Embeddings of the images are its queries \(Q\), and those of their captions its positive keys \(K^+\), as illustrated below:
CLIP: \(Z = Q (K^+)^T / \tau\) holds the similarities of \(B\) images with their captions. InfoNCE, along the rows and the columns, raises the similarities of the right pairs (green) and lowers the others (red). Inspired by: Learning Transferable Visual Models From Natural Language Supervision
Audio. Audio can be natively represented by its raw waveform or a log-Mel spectrogram, a 2D time-frequency image of the waveform (computed by a short-time Fourier transform). To generate audio, a neural audio codec, such as SoundStream, turns the waveform into tokens and back:
Videos. A mini-batch of videos is a 5D input (batch size, channels, time, height, width). 3D CNNs convolve over time as well as space, and video Transformers split the video into tubelets, patches that span a few frames:
Graphs. A graph neural network (GNN) computes the embedding of each node from its neighbors, by message passing. A step is given by:
\[x_i^{(k)} = \gamma^{(k)} \left( x_i^{(k-1)}, \Box_{j \in \mathcal{N}(i)} \, \psi^{(k)} \left( x_i^{(k-1)}, x_j^{(k-1)}, e_{j,i} \right) \right)\]where \(x_i^{(k)}\) is the embedding of node \(i\) at step \(k\), \(\mathcal{N}(i)\) the set of its neighbors, and \(e_{j,i}\) the embedding of the edge from node \(j\) to node \(i\). The aggregation \(\Box\) is a differentiable, permutation-invariant function (e.g. sum, mean or max), and \(\gamma\) and \(\psi\) are differentiable functions, such as MLPs or RNNs. The embedding of a graph is the latent of any node(s) of the graph, after few message passing iterations. This can also be further encoded with a Variational Graph Auto-Encoders:
A graph convolutional network is a simple case of message passing: it sums the embeddings of the node and of its neighbors, normalized by their degrees, followed by a linear layer and an activation.
Tabular data. Principal component analysis (PCA) is a linear autoencoder, with the smallest squared error of any linear encoder and decoder of its size. An MLP autoencoder extends it to non-linear structure. A categorical column, e.g. a city, is embedded by a lookup table, as the words of Word2vec, and a numerical column by a learned vector scaled by its value.
Tables are hard for neural networks: their columns mix types and units, many of them carry no information about the target, and the target often changes abruptly, while neural networks favor smooth functions. Thus, gradient-boosted trees, such as XGBoost. Tabular foundation models are a recent answer: TabPFN, a Transformer model that reads labeled rows of a new table in its context, and predicts the other rows in one forward pass, with no training.
Missing values are frequent in tables, and a work around is to do imputation and replace by the mean or most commonly add an additional input colums to mention if corresponding cell is populated or not. Trees need no imputation: XGBoost learns, at each split, the branch that the rows with a missing value take.