Generative AI & Large Language Models 40–50 mins read Intermediate • PyTorch • Hugging Face Transformers

Large Language Models (LLMs): Architecture, Tokenization & Transformer Decoders

Deconstruct the core engineering behind modern foundational AI systems like GPT-4, Llama 3, Claude, and Gemini. Master autoregressive next-token prediction, subword tokenization (BPE), causal masked self-attention, decoder-only blocks, decoding hyperparameters (temperature, top-$k$, top-$p$), KV cache inference acceleration, and production inference pipelines.

What You Will Master

Autoregressive Next-Token Prediction: The probabilistic chain rule of language modeling and sequence generation loops.
Tokenization & Byte-Pair Encoding: Why character- and word-level methods fail, how BPE builds subwords, and special tokens.
Embeddings & Modern Position Encodings: Embedding matrix lookups and Rotary Position Embedding (RoPE) dynamics.
Transformer Decoder Blocks: Causal triangular attention masks, Multi-Head & Grouped-Query Attention, SwiGLU, and RMSNorm.
Text Decoding Strategies: Greedy decoding vs temperature scaling, top-$k$, and nucleus (top-$p$) sampling mathematics.
KV Cache Inference Acceleration: How caching Key and Value tensors transforms $\mathcal{O}(S^2)$ token generation into $\mathcal{O}(S)$ complexity.
Post-Training Alignment & Fine-Tuning: Pretraining vs Supervised Fine-Tuning (SFT), RLHF, DPO, and LoRA/QLoRA parameter efficiency.
Production PyTorch Implementation: Build and run a full Hugging Face causal generation pipeline with sampling and streaming.
1

Introduction: What Is a Large Language Model (LLM)?

Over the past few years, AI systems such as ChatGPT, Claude, Gemini, and Llama have redefined human-computer interaction. They write software, translate nuanced languages, summarize dense technical literature, answer complex conceptual queries, and generate creative literature. At the technological epicenter of this revolution lies the Large Language Model (LLM).

At its mathematical essence, an LLM is a machine learning model trained on hundreds of billions or trillions of tokens of text data to discover statistical patterns of human thought and communication. Its fundamental operational mechanism is deceptively straightforward: given an input sequence of tokens, predict the probability distribution over the entire vocabulary for the immediate next token.

Architectural Clarification: Raw LLM vs Chatbot Application
Attribute Foundational LLM Conversational Chatbot / Agent
Primary Nature Statistical token completion engine trained on raw text. Full interactive application wrapping a tuned model.
Core Objective Autoregressively minimize cross-entropy loss on next tokens. Deliver safe, conversational, helpful, user-aligned responses.
Exemplars Llama 3 Base, GPT-4 Base, Qwen 2.5 Base, Mistral Base. ChatGPT, Claude.ai, Gemini App, Perplexity, Copilot.
Training Stages Self-supervised pretraining on massive web-scale corpora. Pretraining + SFT + Preference Optimization (RLHF/DPO).
Tool Integration Outputs raw text tokens only (no direct external capability). Orchestrates web search, code execution sandboxes, and APIs.

A raw pretrained model given the prompt "The capital of France is" may complete it with " Paris". However, if given "Write an essay on photosynthesis:", an unaligned base model might simply generate more multiple-choice questions about photosynthesis because it learned from exam papers. To transform a raw statistical sequence predictor into a reliable assistant, modern engineering uses post-training alignment, chat templates, and system prompt framing.

2

How Language Models Work: Next-Token Prediction & Autoregression

How does predicting one word at a time generate cohesive essays and working code? The theoretical foundation of language modeling is the probabilistic chain rule of conditional probabilities.

The Autoregressive Joint Probability Chain Rule

Any arbitrary sequence of $n$ tokens $\mathbf{x} = (x_1, x_2, \dots, x_n)$ has a joint probability defined by the product of conditional distributions:

$$P(x_1, x_2, \dots, x_n) = \prod_{i=1}^n P(x_i \mid x_1, x_2, \dots, x_{i-1}) = \prod_{i=1}^n P(x_i \mid \mathbf{x}_{<i})$$
$x_i$: The $i$-th target token in the vocabulary.
$\mathbf{x}_{<i}$: The preceding context tokens $(x_1, \dots, x_{i-1})$.
$P(x_i \mid \mathbf{x}_{<i})$: Softmax probability generated by the neural network.

When generating text, the LLM operates in an autoregressive loop:

  1. Step 1: Feed prompt tokens $\mathbf{x} = (x_1, \dots, x_t)$ into the Transformer.
  2. Step 2: Compute logits for position $t$ across all tokens in vocabulary $V$.
  3. Step 3: Convert logits to probabilities using Softmax (scaled by temperature).
  4. Step 4: Select candidate token $x_{t+1}$ using a decoding policy (e.g., Top-$p$ sampling).
  5. Step 5: Append $x_{t+1}$ to the input sequence: $\mathbf{x}_{\text{new}} = (x_1, \dots, x_t, x_{t+1})$.
  6. Step 6: Repeat until the model emits the designated End-of-Sequence token (e.g., <|endoftext|> or <|im_end|>) or reaches the max token budget.
3

Tokenization: Bridging Raw Text and Numerical IDs

Neural networks cannot process raw UTF-8 string characters directly. They perform floating-point tensor operations. Tokenization is the deterministic algorithm that fragments human text into discrete atomic chunks called tokens and maps each token to an integer identifier.

Tokenization Paradigms Comparison
Paradigm Vocabulary Size Sequence Length Out-of-Vocabulary (OOV) Modern Usage
Word-Level Massive ($10^6+$ words) Short Catastrophic (new words $\to$ <UNK>) Deprecated in modern LLMs
Character-Level Tiny (256 bytes) Extremely Long ($10\times$) Zero OOV issues Quadratic attention memory bottleneck
Subword / Byte-Level BPE Balanced ($32\text{k} - 128\text{k}$) Optimal balance Zero OOV (falls back to single bytes) Standard in GPT-4, Llama 3, Claude

Byte-Pair Encoding (BPE) Algorithm

Invented by Philip Gage in 1994 as a data compression format and adapted for NLP by Sennrich et al. (2016), BPE starts with individual bytes as base vocabulary and iteratively merges the most frequent adjacent pairs:

BPE Iterative Merge Process:
1. Initial Corpus: {"low": 5, "lower": 2, "newest": 6, "widest": 3}
2. Vocabulary Base: {d, e, i, l, n, o, r, s, t, w}
3. Most frequent adjacent pair: ('e', 's') occurs 9 times → Merge into new token 'es'
4. Next most frequent pair: ('es', 't') occurs 9 times → Merge into token 'est'
5. Repeat until target vocabulary size (e.g. 50,257 for GPT-2, 128,256 for Llama 3) is reached.
Special Tokens in LLMs: Special delimiter tokens inject structural state into the model:
  • <|begin_of_text|> / <s> (BOS): Marks the start of a sequence.
  • <|end_of_text|> / </s> (EOS): Instructs generation termination.
  • <|pad|> (PAD): Aligns varying sequence lengths in parallel mini-batches.
  • <|start_header_id|>system<|end_header_id|>: Chat template role delineation.
4

Token Embeddings & Positional Encodings (RoPE)

After tokenization, discrete token integers $\mathbf{x} \in \mathbb{N}^S$ enter the model. The first layer is a learned Token Embedding Matrix $\mathbf{W}_e \in \mathbb{R}^{V \times D}$, where $V$ is vocabulary size and $D$ is model hidden dimension ($D = 4096$ in Llama 3 8B).

A token ID $k$ acts as a row index lookup into $\mathbf{W}_e$: $$\mathbf{e}_k = \mathbf{W}_e[k, :] \in \mathbb{R}^D$$

Why Self-Attention Is Permutation Invariant

The core attention equation $\text{Softmax}(Q K^\top / \sqrt{d_k}) V$ computes pairwise dot products. If you shuffle the token order, the dot products yield the identical set of values. Without explicit positional information, the network cannot distinguish between "The dog bit the man" and "The man bit the dog".

Modern Standard: Rotary Position Embedding (RoPE)

Introduced by Su et al. (RoFormer, 2021) and adopted across Llama 1/2/3, Mistral, Qwen, and Gemma, RoPE encodes relative position by rotating Query and Key vectors in 2D coordinate subspaces:

$$\mathbf{R}_{\Theta, m}^{2d} = \begin{pmatrix} \cos(m \theta_i) & -\sin(m \theta_i) \\ \sin(m \theta_i) & \cos(m \theta_i) \end{pmatrix}$$

Crucially, the dot product between Query at position $m$ and Key at position $n$ depends purely on their relative offset $(m - n)$: $$\langle \mathbf{R}_m \mathbf{q}, \mathbf{R}_n \mathbf{k} \rangle = \mathbf{q}^\top \mathbf{R}_{n - m} \mathbf{k}$$ This enables graceful context extension (e.g. from 4k to 128k tokens) via frequency interpolation techniques such as YaRN and RoPE scaling.

Transformer Input Tensor Dimensions:
Tensor Shape = [Batch Size (B), Sequence Length (S), Hidden Dimension (D)]
Example: [Batch=4, Seq_Len=2048, Hidden_Dim=4096] contains $4 \times 2048 \times 4096 = 33,554,432$ floating point elements ($134.2\text{ MB}$ in FP32).
5

Transformer Decoder Architecture: Pre-Norm Blocks & Causal Attention

Unlike the original 2017 "Attention Is All You Need" encoder-decoder paper designed for machine translation, modern autoregressive LLMs utilize a Decoder-Only Pre-Norm Transformer architecture.

Anatomy of a Modern Decoder Block (Llama 3 / Mistral)

Sub-Layer 1: Causal Self-Attention
$\mathbf{x}_0 = \text{Input Representation} \in \mathbb{R}^{B \times S \times D}$
1. $\tilde{\mathbf{x}}_0 = \text{RMSNorm}(\mathbf{x}_0)$
2. Projections: $\mathbf{Q} = \tilde{\mathbf{x}}_0 \mathbf{W}_Q, \mathbf{K} = \tilde{\mathbf{x}}_0 \mathbf{W}_K, \mathbf{V} = \tilde{\mathbf{x}}_0 \mathbf{W}_V$
3. Apply RoPE: $\tilde{\mathbf{Q}} = \text{RoPE}(\mathbf{Q}), \tilde{\mathbf{K}} = \text{RoPE}(\mathbf{K})$
4. Causal Attention: $\mathbf{A} = \text{Softmax}\left(\frac{\tilde{\mathbf{Q}}\tilde{\mathbf{K}}^\top}{\sqrt{d_k}} + \mathbf{M}\right)\mathbf{V}$
5. Residual Addition: $\mathbf{x}_1 = \mathbf{x}_0 + \mathbf{A}\mathbf{W}_O$
Sub-Layer 2: SwiGLU MLP Feed-Forward
1. $\tilde{\mathbf{x}}_1 = \text{RMSNorm}(\mathbf{x}_1)$
2. Gated Up-Projection:
$\text{gate} = \text{SiLU}(\tilde{\mathbf{x}}_1 \mathbf{W}_{\text{gate}})$
$\text{up} = \tilde{\mathbf{x}}_1 \mathbf{W}_{\text{up}}$
3. Element-wise Product: $\mathbf{h} = \text{gate} \odot \text{up}$
4. Down-Projection: $\mathbf{y} = \mathbf{h} \mathbf{W}_{\text{down}}$
5. Residual Addition: $\mathbf{x}_2 = \mathbf{x}_1 + \mathbf{y}$

The Causal Mask Matrix $\mathbf{M}$

In masked self-attention, we enforce causality by adding a lower-triangular additive mask matrix $\mathbf{M} \in \mathbb{R}^{S \times S}$:

$$M_{ij} = \begin{cases} 0 & \text{if } j \le i \quad (\text{past or present token}) \\ -\infty & \text{if } j > i \quad (\text{future token}) \end{cases}$$

Because $\exp(-\infty) = 0$, applying the Softmax operator forces all attention weights for future positions to identically zero: $$\text{Attention Weight}_{ij} = \frac{\exp\left(\frac{\mathbf{q}_i^\top \mathbf{k}_j}{\sqrt{d_k}} + M_{ij}\right)}{\sum_{l=1}^S \exp\left(\frac{\mathbf{q}_i^\top \mathbf{k}_l}{\sqrt{d_k}} + M_{il}\right)} = 0 \quad \forall j > i$$ This mathematical property guarantees that token $i$ can never see or attend to token $i+1$, preserving autoregressive integrity.

RMSNorm vs LayerNorm

Classical LayerNorm computes mean $\mu$ and variance $\sigma^2$: $$\text{LN}(x) = \frac{x - \mu}{\sqrt{\sigma^2 + \epsilon}} \odot \gamma + \beta$$ Zhang and Sennrich (2019) demonstrated that the mean-centering operation $\mu$ adds unnecessary computation without improving generalization. RMSNorm (Root Mean Square Normalization) normalizes purely by root mean square: $$\text{RMSNorm}(x) = \frac{x}{\sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}} \odot \gamma$$ This delivers an estimated $7\%$ to $12\%$ speedup across deep layers while preserving complete numerical stability.

6

Decoder-Only vs Encoder-Only vs Encoder-Decoder

Not all Transformer models are structured alike. The deep learning literature features three foundational archetypes:

Architecture Type Attention Visibility Pretraining Objective Exemplars Primary Use Cases
Encoder-Only Bidirectional (all tokens attend to all tokens) Masked Language Modeling (MLM) BERT, RoBERTa, DeBERTa Text classification, Named Entity Recognition, Sentence Embeddings.
Decoder-Only Causal / Unidirectional (attend only to past tokens) Causal Next-Token Prediction GPT-4, Llama 3, Mistral, Qwen Open-ended text generation, reasoning, coding, conversational chat.
Encoder-Decoder Bidirectional Encoder + Causal Decoder with Cross-Attention Span Corruption / Seq2Seq T5, BART, Flan-T5 Fixed sequence translation, document summarization.
7

LLM Pretraining: Optimization & Cross-Entropy Loss

Pretraining is the most computationally demanding phase of LLM creation, typically consuming millions of GPU-hours on clusters of H100s. The training pipeline processes trillions of tokens scraped from web documents (Common Crawl), curated books, high-quality codebases (GitHub), scientific arXiv papers, and encyclopedic knowledge.

Pretraining Loss Formulation

For a batch of sequences of length $S$, the model minimizes the empirical Cross-Entropy Loss:

$$\mathcal{L}(\theta) = -\frac{1}{S} \sum_{i=1}^S \log P_\theta(x_i \mid x_1, \dots, x_{i-1})$$

Where $P_\theta(x_i \mid \mathbf{x}_{<i}) = \frac{\exp(z_{i, x_i})}{\sum_{j=1}^V \exp(z_{i, j})}$, and $z_{i, j}$ is the raw unnormalized logit produced by the Language Model Head for vocabulary token $j$ at sequence position $i$.

Pretraining does not memorize facts verbatim; it compresses statistical dependencies, syntactic grammars, world models, and semantic logic into weight matrices $\theta$.

8

Text Generation Strategies: Temperature, Top-$k$ & Top-$p$ (Nucleus)

Once the final decoder block outputs hidden vectors $\mathbf{h}_S \in \mathbb{R}^D$, the Language Model Head projects them to the vocabulary dimension: $\mathbf{z} = \mathbf{h}_S \mathbf{W}_{\text{head}} \in \mathbb{R}^V$. How we select the next token from logit vector $\mathbf{z}$ governs the entire personality, creativity, and precision of the LLM.

Greedy Decoding
Deterministic selection of the argmax token:
$$\hat{x} = \arg\max_{i \in V} z_i$$

Pros: Fast, reproducible, optimal for math and strict factual extraction.
Cons: Highly susceptible to degenerate repetitive loops (e.g. "The system was very very very...") and fails to explore diverse paths.

Stochastic Sampling
Randomly sampling token $\hat{x}$ according to $P_i$:
$$\hat{x} \sim P(x \mid \mathbf{x}_{<t}) = \text{Softmax}(\mathbf{z})$$

Pros: Creative, natural, diverse writing.
Cons: Pure sampling risks selecting bizarre low-probability tokens from the vocabulary tail, causing incoherent gibberish.

Temperature Scaling

Temperature $T > 0$ modifies the logit scale before computing Softmax: $$P_i = \frac{\exp(z_i / T)}{\sum_{j=1}^V \exp(z_j / T)}$$

  • Low Temperature ($T \to 0$, e.g. $T = 0.2$): Sharpens the distribution. The highest logit dominates; behaves almost like greedy decoding. Ideal for coding and math.
  • Standard Temperature ($T = 0.7 - 1.0$): Balanced natural human-like cadence.
  • High Temperature ($T > 1.2$, e.g. $T = 1.8$): Flattens the distribution towards uniform entropy. Encourages novelty but risks hallucinations and syntactic collapse.

Top-$k$ Sampling

Truncates the candidate pool to only the top $k$ tokens with the highest logits, setting all other logits to $-\infty$. For example, with $k=50$, only the 50 most probable tokens can ever be sampled.

Top-$p$ (Nucleus) Sampling (Holtzman et al., 2020)

Instead of a fixed count $k$, Top-$p$ dynamically adjusts the candidate pool size based on confidence. It selects the smallest set of tokens $V^{(p)}$ whose cumulative probability exceeds threshold $p \in (0, 1]$: $$\sum_{i \in V^{(p)}} P_i \ge p$$ When the model is confident (one token has $95\%$ probability), the candidate set shrinks to $1$ token. When the context is ambiguous, the candidate set automatically expands to include dozens of plausible alternatives.

8

KV Cache: Solving the Autoregressive Inference Bottleneck

In naive autoregressive generation, generating token $t+1$ requires passing all tokens $1 \dots t$ through the network. As sequence length $S$ reaches thousands of tokens, recomputing past Key and Value vectors yields a catastrophic $\mathcal{O}(S^2)$ computational complexity per generated token.

The KV Cache Solution

Because of the causal attention mask, the Key and Value representations of token $i$ depend only on tokens $\le i$. Once computed, they never change!

Without KV Cache (Naive):
  • Step $t$: Forward pass on all $t$ tokens.
  • Re-projects $\mathbf{Q}, \mathbf{K}, \mathbf{V}$ for past tokens $1 \dots t-1$.
  • Per-token FLOPs: $\mathcal{O}(t^2)$.
  • Total Generation FLOPs: $\mathcal{O}(S^3)$. Severe GPU underutilization.
With KV Cache:
  • Step $t$: Forward pass on only the 1 newly generated token.
  • Append $\mathbf{k}_t$ and $\mathbf{v}_t$ to cached tensors in GPU VRAM.
  • Attention dot product: $\mathbf{q}_t \mathbf{K}_{\text{cached}}^\top \in \mathbb{R}^{1 \times t}$.
  • Per-token FLOPs: $\mathcal{O}(t)$. Massive throughput speedup.
KV Cache Memory Footprint Formula:
$$\text{Memory}_{\text{KV}} = 2 \times 2 \times n_{\text{layers}} \times n_{\text{heads}} \times d_{\text{head}} \times S \times B \times \text{bytes\_per\_elem}$$ Example for Llama 3 8B (32 layers, 8 KV heads in GQA, head dim 128, FP16 = 2 bytes) with Batch 4, Context 8,192:
$$2 \times 2 \times 32 \times 8 \times 128 \times 8192 \times 4 \times 2 \text{ bytes} \approx 8.59 \text{ GB of VRAM}$$
9

Context Window, Long-Context Engineering & Pitfalls

The Context Window defines the maximum sequence length $S_{\max}$ that an LLM can ingest in a single forward pass (e.g. 8k for original Llama 2, 128k for Llama 3, 1M+ for Gemini 1.5).

The "Lost in the Middle" Deficit

Liu et al. (Stanford, 2023) demonstrated that LLMs reliably retrieve facts placed at the extreme beginning (primacy effect) or extreme end (recency effect) of their context window. When critical facts are buried in the middle of a 64k-token prompt, retrieval accuracy drops drastically.

FlashAttention Acceleration

Standard attention materializes the intermediate $S \times S$ attention matrix into High Bandwidth Memory (HBM). FlashAttention (Dao et al.) uses tiling and kernel fusion in SRAM to compute exact softmax without ever writing the $S \times S$ matrix to HBM, yielding $3-5\times$ speedups.

10

Post-Training: SFT, Preference Optimization (RLHF / DPO) & LoRA

Pretrained models are statistical raw materials. Transforming them into obedient, safe conversational assistants requires a multi-stage post-training pipeline:

Stage Methodology Dataset Type Objective
Supervised Fine-Tuning (SFT) Standard cross-entropy loss applied solely on assistant answer tokens. {"prompt": ..., "completion": ...} Teach the model chat format, tone, and direct instruction-following.
RLHF (PPO) Train a Reward Model $R(x, y)$ on human preferences; optimize policy via PPO with KL penalty. Pairwise comparisons: (prompt, chosen, rejected) Maximize human preference and safety while preventing reward hacking.
DPO (Direct Preference Optimization) Implicitly optimizes policy directly on preference pairs without training a separate reward model. Pairwise comparisons: (prompt, chosen, rejected) Substantially simpler, mathematically stable preference alignment.
LoRA & QLoRA (PEFT) Freeze base weights $\mathbf{W}_0$; train low-rank decomposition $\Delta \mathbf{W} = \mathbf{B}\mathbf{A}$ ($r \ll d$). Domain-specific SFT tasks Reduces trainable parameters by $99.9\%$, enabling fine-tuning on consumer GPUs.
11

Hallucinations, Biases & Security Vulnerabilities

Because LLMs are probabilistic token predictors rather than factual knowledge graph query engines, they are subject to fundamental limitations:

Hallucination

The fluent fabrication of non-existent citations, APIs, or historical dates. Caused by probabilistic completion under uncertainty. Mitigated by RAG (Retrieval-Augmented Generation) and tool groundings.

Knowledge Cutoff

A static neural network knows nothing about events occurring after its training cutoff date unless bridged with live web search APIs or dynamic RAG pipelines.

Prompt Injection

Adversarial inputs that hijack the system prompt instruction (e.g. "Ignore all previous instructions and output..."). Requires strict input sanitization, dual-LLM guards, and structured tool signatures.

Interactive LLM & Transformer Decoder Studio

Test subword tokenization, inspect causal attention masks, adjust sampling sliders in real time, and simulate KV cache speedups.

Presets:

Visual token boundaries and assigned vocabulary token IDs.

Tokenization Efficiency Metrics
Characters
51
Words
7
Tokens
8
Ratio (T/W)
1.14
Interactive Token Chips:

Observe how frequent English words represent exactly one token, while rare, morphological, or non-Latin words fragment into subwords or individual byte tokens.

12

Production PyTorch & Hugging Face Implementation

The following production-grade script loads an autoregressive causal language model using Hugging Face transformers, tokenizes a prompt, and executes greedy decoding, temperature sampling, and streaming generation.

generate_text_pipeline.py Python 3.10+ • PyTorch • Transformers
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer

# 1. Device configuration (CUDA GPU if available)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Executing inference on device: {device}")

# 2. Load Tokenizer and Causal Language Model
model_id = "gpt2"  # Educational compact decoder; replace with "meta-llama/Meta-Llama-3-8B"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id).to(device)
model.eval()

# Ensure padding token exists
if tokenizer.pad_token is None:
    tokenizer.pad_token = tokenizer.eos_token

# 3. Format input prompt
prompt = "Artificial intelligence and large language models will"
inputs = tokenizer(prompt, return_tensors="pt").to(device)

print(f"Prompt: '{prompt}'")
print(f"Input Token IDs: {inputs['input_ids'].tolist()[0]}")
print(f"Token Count: {inputs['input_ids'].shape[1]}")

# 4. Strategy A: Deterministic Greedy Decoding
with torch.no_grad():
    greedy_output = model.generate(
        **inputs,
        max_new_tokens=30,
        do_sample=False,
        pad_token_id=tokenizer.eos_token_id
    )
print("\n[Strategy A: Greedy Decoding Output]")
print(tokenizer.decode(greedy_output[0], skip_special_tokens=True))

# 5. Strategy B: Stochastic Sampling with Temperature, Top-k, and Top-p
with torch.no_grad():
    sample_output = model.generate(
        **inputs,
        max_new_tokens=30,
        do_sample=True,
        temperature=0.8,
        top_k=50,
        top_p=0.92,
        repetition_penalty=1.15,
        pad_token_id=tokenizer.eos_token_id
    )
print("\n[Strategy B: Temperature (0.8) + Top-p (0.92) Sampling Output]")
print(tokenizer.decode(sample_output[0], skip_special_tokens=True))

# 6. Strategy C: Real-Time Token Streaming Generation
print("\n[Strategy C: Real-Time Token Streaming]")
streamer = TextStreamer(tokenizer, skip_prompt=True)
with torch.no_grad():
    _ = model.generate(
        **inputs,
        max_new_tokens=40,
        do_sample=True,
        temperature=0.7,
        top_p=0.9,
        streamer=streamer,
        pad_token_id=tokenizer.eos_token_id
    )
13

Major Open-Source LLMs Architecture Matrix

Model Parameters Context Window Attention Paradigm Positional Encoding Activation Norm
GPT-2 (2019) 124M – 1.5B 1,024 Standard MHA Absolute Learned GELU LayerNorm
Llama 2 (2023) 7B – 70B 4,096 GQA (70B) / MHA (7B) RoPE SwiGLU RMSNorm
Mistral 7B (2023) 7.3B 8,192 (Sliding 4k) GQA + Sliding Window RoPE SwiGLU RMSNorm
Llama 3 (2024) 8B – 405B 8,192 – 128k Grouped-Query (GQA) RoPE (scaled) SwiGLU RMSNorm
Qwen 2.5 (2024) 0.5B – 72B 128k Grouped-Query (GQA) RoPE (YaRN) SwiGLU RMSNorm
14

Top 10 Anti-Patterns in LLM Inference & Deployment

# Anti-Pattern Mechanism of Failure Production Remedy
1 Missing KV Cache Recomputing entire context per token causes quadratic $\mathcal{O}(S^2)$ slowdown. Always set use_cache=True in Hugging Face / vLLM.
2 Extreme Temperature ($T > 1.5$) Flattened Softmax assigns mass to vocabulary tail, yielding nonsensical gibberish. Constrain temperature to $0.6 - 0.9$ for creative text, $0.1 - 0.3$ for coding.
3 Greedy Search for Creative Tasks Argmax gets trapped in repetitive sentence cycles. Enable Nucleus Top-$p$ sampling ($p \approx 0.9$) with repetition penalties.
4 Omission of EOS Stopping Criteria Model keeps generating hallucinated tokens until hitting max limit. Configure stopping criteria with correct EOS / chat end tokens.
5 Unsanitized User Prompts Exposes model to direct prompt injection attacks. Use structured chat templates, separate system instructions, and input guardrails.
6 Burying Needle in the Middle Lost-in-the-middle effect ignores instructions placed midway in long contexts. Place critical instructions at the extreme beginning and end of prompts.
7 Unquantized FP32 VRAM Ingestion Consumes $4\times$ unnecessary GPU memory with zero accuracy gain. Serve models in BF16, FP8, or 4-bit AWQ / GPTQ quantization.
8 Neglecting Padding Token Setup GPT-style models lack default pad tokens, corrupting attention masks during batching. Set tokenizer.pad_token = tokenizer.eos_token explicitly.
9 Treating LLM as a Database Weights contain lossy statistical approximations; factual hallucination is inevitable. Use RAG (Retrieval-Augmented Generation) with verifiable vector search.
10 Ignoring Batch Size in KV Footprint High concurrency causes Out-Of-Memory (OOM) crashes due to unbounded KV caches. Deploy PagedAttention (vLLM) to dynamically manage non-contiguous KV memory.

Key Takeaways: What You Learned

  • Next-Token Prediction: The foundation of modern LLMs is minimizing cross-entropy loss over conditional joint sequence probabilities $P(x_i \mid \mathbf{x}_{<i})$.
  • Tokenization & BPE: Byte-Pair Encoding merges frequent subword pairs, balancing vocabulary size ($32\text{k}-128\text{k}$) and avoiding OOV tokens.
  • Decoder-Only Pre-Norm Architecture: Masked multi-head causal self-attention with lower-triangular $-\infty$ masking prevents future token visibility.
  • RoPE & RMSNorm: Modern open-source LLMs adopt Rotary Position Embeddings for relative position encoding and RMSNorm for faster execution.
  • Sampling Dynamics: Temperature adjusts logit sharpness, while Top-$k$ and Nucleus (Top-$p$) dynamically prune low-probability noise.
  • KV Cache: Caching Key and Value tensors turns $\mathcal{O}(S^2)$ per-token computation into $\mathcal{O}(S)$, enabling real-time streaming generation.
  • Post-Training: Raw base models are aligned through Supervised Fine-Tuning (SFT) and preference optimization (RLHF/DPO) into safe conversational agents.
Previous: Lesson 15.31 Multimodal AI & CLIP Next: Lesson 15.33 Prompt Engineering & In-Context Learning