How Generative AI Works: Under the Hood
Generative AI systems do not store or copy databases of text and images. Instead, they learn continuous geometric representations of high-dimensional manifolds. Here is the step-by-step engineering journey of how inputs transform into generated outputs.
1. The Autoregressive Text Generation Pipeline
Autoregressive Large Language Models (LLMs) operate in a loop: predicting one token at a time, appending it to the context, and repeating until an End-of-Sequence (<EOS>) token is generated.
Tokenization
Raw text string is decomposed into sub-word tokens using Byte-Pair Encoding (BPE).
Embedding & RoPE
Tokens map to d-dimensional vectors and are combined with Rotary Positional Embeddings.
Forward Pass & Attention
N layers of Transformer blocks apply Multi-Head Attention and feed-forward SwiGLU networks.
Sampling & Decoding
Final hidden state projects onto vocabulary logits; temperature and Top-p select the next token.
Understanding Sub-Word Tokenization (BPE)
Byte-Pair Encoding (BPE) iteratively merges the most frequent byte pairs in the training corpus. Modern models like Llama 3 use a 128,000-token vocabulary, whereas GPT-4 uses 100,000 tokens (cl100k_base). Words like "understanding" are compressed into 1 token, while rare foreign words or code symbols split into 2–4 sub-tokens.
Token IDs: [24890, 19283, 374, 18274, 3429, 13] (6 tokens)
2. Mathematical Sampling & Decoding Strategies
At the final layer of an LLM, the model outputs an unnormalized vector of scores called logits z ∈ ℝ^V, where V is the vocabulary size. How we convert these logits into a chosen token dictates the model's creativity and coherence.
P(w_i) = exp(z_i / T) / ∑_(j=1)^V exp(z_j / T)
| Decoding Parameter | Mathematical Behavior | Practical Use Case |
|---|---|---|
| Greedy Decoding (T = 0) | Selects argmax_i (z_i) deterministically. | Math problem solving, code syntax generation, SQL queries. |
| Low Temperature (0.1 – 0.4) | Sharpens probability peaks; heavily penalizes low-probability tokens. | Technical documentation, data extraction, enterprise RAG search. |
| High Temperature (0.7 – 1.0) | Flattens the probability curve; unlocks lexical diversity. | Creative writing, brainstorming, roleplay chatbots. |
| Top-k Truncation | Retains only the top k highest-probability tokens (e.g. k=50), setting rest to 0. | Prevents the model from ever picking bizarre, low-probability 'long-tail' tokens. |
| Top-p (Nucleus) Sampling | Dynamically keeps the smallest set of tokens whose cumulative sum exceeds p (e.g. p=0.9). | Adapts candidate pool dynamically: narrow pool when confident, wider when uncertain. |
3. How Diffusion Models Generate Images
Unlike autoregressive text generation which works sequentially, visual generative models (e.g., Stable Diffusion, Flux, Midjourney) rely on stochastic differential equations and denoising diffusion:
1. Latent Compression (VAE)
High-resolution pixel space (e.g., 1024×1024×3 = 3.1M numbers) is compressed 8× by an autoencoder into a compact latent space (128×128×4 = 65k numbers). This reduces compute requirements by 48×.
2. Forward Diffusion Noise Schedule
In training, controlled Gaussian noise is added over T = 1000 timesteps according to a variance schedule:q(x_t | x_(t-1)) = N(√(1 - β_t) x_(t-1), β_t I)
3. Conditioned Reverse Denoising
A U-Net or Diffusion Transformer (DiT) is trained to predict the added noise ϵ_θ(x_t, t, c), conditioned on text embeddings c via cross-attention layers at each timestep.
4. Custom Implementation: Temperature & Nucleus Sampler
Here is how sampling algorithms are mathematically coded in PyTorch inside modern inference engines (vLLM/Hugging Face):
import torch
import torch.nn.functional as F
def sample_next_token(logits: torch.Tensor, temperature: float = 0.7, top_p: float = 0.9) -> int:
"""
Applies temperature scaling and Nucleus (Top-p) filtering to raw model logits.
"""
# 1. Apply temperature scaling
if temperature > 0:
logits = logits / temperature
else:
# Greedy decoding if temperature is 0
return torch.argmax(logits, dim=-1).item()
# 2. Convert logits to probabilities
probs = F.softmax(logits, dim=-1)
# 3. Sort probabilities in descending order
sorted_probs, sorted_indices = torch.sort(probs, descending=True)
cumulative_probs = torch.cumsum(sorted_probs, dim=-1)
# 4. Remove tokens with cumulative probability above the threshold (Nucleus)
sorted_indices_to_remove = cumulative_probs > top_p
# Shift indices to the right to keep the first token above the threshold
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
# 5. Zero out removed tokens and renormalize
sorted_probs[sorted_indices_to_remove] = 0.0
sorted_probs = sorted_probs / torch.sum(sorted_probs, dim=-1, keepdim=True)
# 6. Sample from filtered multinomial distribution
next_sorted_token_idx = torch.multinomial(sorted_probs, num_samples=1)
next_token_id = sorted_indices.gather(-1, next_sorted_token_idx).item()
return next_token_idKey Architecture Takeaways
- BPE tokenization maps strings to integers; modern vocabularies range from 32k to 128k sub-words.
- Temperature controls distribution entropy: low values enforce factual determinism, high values introduce stylistic variation.
- Top-p sampling provides a dynamic safety net by truncating the low-probability distribution tail.
- Diffusion models generate by running learned reverse denoising on compressed latent representations.
Explore Related Tools
Hand-picked utilities and calculators related to this tool.
