Autoregressive models (GPT 2018) simplifies the generative modelling problem by treating it as a sequential process
Autoregression is a statistical technique used in time-series analysis that assumes that the current value of a time series is a function of its past values.
Why not call Autoregressive models Seq-seq? seq-seq is an umbrella term where model maps an input sequence to an output sequence, the output generation can be in non-auto regressive manner too (output sequence predicted all at once) e.g. NAT transformers, BERT
For a many-many model, Autoregressive models can be used
Differences between textual and image data
- Textual data is composed of discrete chunks, pixels in image are in continuous color spectrum. Image data allows easy gradient-based updates since pixel values are continuous, but text is discrete, making direct backpropagation challenging. To train text models, we need alternative techniques to handle this discreteness.
- Text data has time dimension, but no spatial dimension (arrangement of data in some defined space e.g. height and width), order of words is important and unlike images won't make sense in reverse flip. There are often long-term sequential dependencies between words that need to be captured by the model
- Text data is highly sensitive to small changes, as altering a few words can drastically affect meaning, whereas images remain recognizable despite minor pixel changes. This makes training text models challenging, as every word is crucial for coherence.
Tokenization
Is the process of splitting the text into individual units, could be words, chars, etc.
If we use word tokenization, large vocabulary size, using UNK (unknown tokens) instead of low frequency words can help, model cannot predict words outside training vocabulary. If we use character tokenization, allows generation of new words outside training set. Smaller vocabulary size training is faster, may generate non-sensical words
RNNs ~ (1986)
Processes data sequentially by maintaining a hidden state/context. Captures temporal dependencies. The goal was to simulate how humans process sequential data like speech and handwriting.
✅ Actually does sequence modelling
✅ Used with convolutional layers to enhance receptive field (region of the input image that a neuron can be influenced by when making predictions)
❌ Vanishing gradients
❌ Slow training process
❌ Poor performance for sequences > 45 timesteps
Feed forward vs Recurrent Network
- Feedforward does not have input at each timestep
- Feedforward has different parameters for each layer

No matter how long the input/output sequence is, we only need one function f. If f’s are different, then it becomes a h3 feedforward NN. This may be treated as another compression from fully connected network.
Problems solved using RNNs
- Generating text
- Machine translation
- Speech recognition
- Generating Image descriptions
- Chatbots
Solutions to RNN gradient problems
- Gradient clipping - technique to limit the magnitude of gradients during backprop preventing exploding gradient problem
- Gradient scaling - technique to multiply gradients by scaling factor to prevent extremely small values or large values during backprop to ensure stable training
- Better initialize the matrix W
- Use regularization
- Use ReLU instead of Tanh/sigmoid/softmax
- Use LSTM/GRU
LSTM ~ (1997 Sepp)
Designed to handle long-term dependencies and overcome vanishing gradient problem in standard RNNs.

GRU ~ (2014 Kyunghyun)
LSTMs are computationally expensive, three gates (input, forget, output), GRUs exhibit same performance while being computationally efficient, combines input and forget gates into single update gate.
Simple RNNs suffer from vanishing gradients due to repeated multiplication of weights over many time steps, LSTMs and GRUs use gating mechanism, i.e. don’t have weight matrices multiplying the rest.

Deep RNN ~ (2010s Geoffrey hinton)
Standard RNNs struggle with learning high-level abstract features because they process data in a shallow manner.
Deep RNNs capture more complex temporal structures by stacking multiple RNN layers, enabling the model to extract deeper representations from sequential data.
Inspired by the success of deep feedforward networks (MLPs and CNNs), researchers applied the same idea to RNNs, improving their expressive power.

Bidirectional RNN ~ (1997 Mike Schuster)
Standard RNNs process information only in one direction (past → future), making them ineffective for tasks where future context is important.
BiRNNs solve this by using two RNNs, one processing the sequence forward and the other backward, allowing them to utilize both past and future information.
Speech and text often depend on future context, so the idea of reading sequences in both directions was inspired by how humans process language.

Pixel CNN ~ (2016 Oord et al.)
Is a generative model that generates images pixel-by-pixel in an autoregressive manner. Instead of treating an image as a whole, PixelCNN predicts each pixel's value conditioned on previously generated pixels.
Traditional models (GANs, VAEs) struggled with mode collapse and poor likelihood estimation
PixelRNN was introduced in the same paper as Pixel CNN. Pixel RNN is an autoregressive generative model that generates images pixel-by-pixel in a sequential manner using 2D LSTMs, due to sequential pixel processing, its computationally expensive, Pixel CNN was proposed as a faster alternative to PixelRNN. used in DeepMind's WaveNet for speech synthesis and image compression. Got best paper award at ICML2016
PixelCNN in paper is trained to reconstruct its input, can be tuned for downstream tasks later.

| VAE | GAN | Autoregressive models |
| ✔ Stable training ✔ Efficient inference | ✔ high quality images ✔ Fast sampling (no Markov chain etc. estimations) | ✔ Simple and stable training process ✔ Currently gives best log likelihood |
| ❌ Blurry images due to Gaussian assumption | ❌ Difficult training ❌ Careful hyperparameter tuning | ❌ Slow inference |
Autoregressive image modelling
Given all (pixels + channels) to top ⬆ and to left ⬅, current pixel value is predicted.
Causal comes from causality meaning cause and effect - something happens because of something that came before it
Pixel RNN has an unbounded dependency range, meaning that prediction for a pixel can depend on all previous pixels in the image, there is no fixed limit on how far back the model can look, LSTMs incorporate information from every pixel that came before it regardless of distance, adds a huge compute cost though but good performance. Pixel CNN has a bounded receptive field means that when predicting a pixel, model only looks at a fixed size neighborhood of pixels around it, even if we increase the kernel counts, effective receptive field is still bounded unless kernel dim = image dim. Pixel CNN has better parallelizability while training and testing but during inference, has the same parallelizability as Pixel RNN
Pixel CNN uses masked convolutions to
condition current pixel value.

Residual connections
PixelCNN has a skip connections mechanism that allows network to preserve information while still stacking layers deeper. Without skip connections, network would need to learn identity mappings through the intermediate layers, which is more complex

← Causal conv
Step-by-Step Generation
- Initialize an empty canvas of size H x W x C
- For each pixel form a context by taking all previous generated pixels (including their channels too) and apply masked convolutions
- Pass the convolutions to a FNN
- At the final layer network outputs a set of logits for each value of pixel 256 sized final layer
- Apply softmax to convert logits into probability distribution
- To select pixel value, select most likely value or stochastically sample from distribution
- Continue until all pixels in the image are generated
- PixelCNN stacks 15 Resnet blocks are added at appropriate timesteps, Output of each block is computed as , where A is previous blocks output and function F applies residual transformations
To compute pixel m value we are using 3x3 mask (A)
Pixel m depends on l, g, h, I
Blindspot problem
Those pixels depends on a, b, c, d, e, f, k

But despite coming before pixel m, j is never taken into account as 'context'
Our J biru is inside blind spot
Pixel RNN
Instead of generating an image all at once (like a GAN) or learning a latent representation (like a VAE), PixelRNN generates each pixel one at a time, conditioned on previously generated pixels.
Using fully 2D LSTMs is too computationally expensive
Has two variants/compromises:
- Row LSTM PixelRNN
Uses vertical LSTMs to generate an image row by row. Each row is processed independently using an LSTM and information is passed down row-wise.
Each pixel is represented as one-hot vector (if grayscale)
Image is treated as grid of pixels, each row is a sequence of W pixels
X =
Now to generate pixel we would apply masked convolutions to ensure that each pixel is only dependant on previous pixels in a causal manner.
But why the fuck should I apply masked convolutions when the future pixels are not even generated?
During inference: internally, RowLSTM processes entire row in one forward pass and not pixel-by-pixel, if we don’t mask the convolutions before the LSTM, it could accidently see future parallelized pixels within that image
During training: we already have the full image, so instead of feeding the pixels sequentially, we process all rows simultaneously in a single forward pass. Makes training process faster and masked convolutions prevent LSTM from cheating by seeing future pixels.
Each row's first hidden state value is initialized using final hidden state from previous row. Afterwards, each row's pixel is generated using prior pixel values in the same row.
Dependencies are captured row by row, this limits model to capture global dependencies
- Diagonal BiLSTM PixelRNN
To allow for parallelization along the diagonals, input map is skewed. When spatial layer is computed, output map is shifted back into original size.

For each diagonal computation all previous diagonal values are required as posterior e.g. to compute diagonal 4's value, we would need diagonal 3, 2, 1 values. Each pixel value is a fusion of Forward and backward LSTMs hidden state at previous diagonal's instance e.g. for pixel at location A the leftmost column's LSTM fwd bwd fusion value is input to at location A.
By lining up diagonals into columns, the computation can be batched more effectively, reducing the overhead of memory reads/writes. Zeroes are appended at skewed coordinates to ensure only the original pixel's contribute in the output calculations. For each diagonal, you can process all its pixels in one forward (top-to-bottom) and one backward (bottom-to-top) pass of the LSTM. Once that’s done, you move on to the next diagonal. (parallelized hwa hwa na skew ki wjah se bachu)
PixelCNN calculation #01
masked convolutions are used to ensure that a pixel doesn’t "see" future pixels during training.
Mask Type A: Used in the first layer - ensures a pixel cannot see itself.
Mask Type B: Used in subsequent layers - allows a pixel to see itself and previous pixels, but not future pixels.


In standard practice we do:
Type A masking on Red
Type B masking on Green
Type B masking on Blue
Example did not considered Blue by stating an absolute nonsense reason
PixelCNN calculation #02

