Neural Lens

Welcome

Inside the machine
that speaks.

A rigorous, interactive primer on Natural Language Processing and Large Language Models — built for CSE students. Six structured topics, a live lab, curated videos, and a quiz.

01

Tokenization

How raw text becomes integers — the atomic unit every LLM reasons with.

02

Embeddings

Dense vector spaces where geometry encodes semantic meaning.

03

Self-Attention

The mechanism that lets every token see every other token simultaneously.

04

Transformer

The architecture that ended RNN dominance and started the LLM era.

05

RLHF

How raw predictors become aligned, helpful assistants in three phases.

06

Hallucinations

Why fluent, confident, and factually wrong are not mutually exclusive.

Topic 01 of 06

Tokenization

A language model cannot read words. It reads integers. Tokenization bridges human-readable text and machine-readable numbers — converting any string into a sequence of integer IDs from a fixed vocabulary.

Why characters or words aren't enough

A character-level vocabulary is tiny but produces very long sequences, making attention computationally expensive. A word-level vocabulary would require hundreds of thousands of entries and can never handle unseen words. Subword tokenization hits the sweet spot: a vocabulary of ~50,000–100,000 units, with common words as single tokens and rare words expressed as composable subwords.

Example: "unhappiness" might tokenize as ["un", "happi", "ness"]. Each piece is a reusable unit the model has seen many times in other contexts.

Byte-Pair Encoding (BPE)

The dominant algorithm for LLM tokenization. BPE starts with individual characters and iteratively merges the most frequent adjacent pair of symbols into a new unit, repeating until a target vocabulary size is reached. The learned merge rules are then applied to encode any new text.

1
Initialise — vocabulary starts as all individual characters + a special end-of-word marker
2
Count — scan the entire corpus and count every adjacent symbol pair
3
Merge — combine the most frequent pair into a new symbol; update all occurrences
4
Repeat — continue until vocabulary size equals the target (e.g. 50,257 for GPT-2)
5
Encode — apply learned merge rules to any new text to produce token IDs

Recommended video

Andrej Karpathy — "Let's build the GPT Tokenizer" · BPE and tiktoken from scratch

Topic 02 of 06

Embeddings

An integer token ID is just a label — it carries no information about meaning. Embeddings convert those integers into dense floating-point vectors where geometric proximity reflects semantic similarity.

The embedding lookup table

The model maintains a learned matrix of size V × d where V is the vocabulary size and d is the embedding dimension (512–4096 in modern models). Looking up token ID 15496 retrieves row 15496 — a vector of d numbers called its embedding. This lookup is the very first operation in every forward pass.

Key insight: Embeddings are not hand-designed. They emerge entirely from training. The model learns to place tokens that appear in similar contexts near each other in vector space — encoding grammar, syntax, semantics, and world knowledge without any explicit instruction.

Geometric structure of meaning

Word2Vec (2013) demonstrated that embedding arithmetic captures analogy: vec("king") − vec("man") + vec("woman") ≈ vec("queen"). This relationship emerges from statistical co-occurrence patterns — not programming. Transformer models learn vastly richer embedding spaces, but the same geometric intuition applies.

Static vs contextual embeddings

Word2Vec and GloVe assign one fixed vector per word regardless of context. The word "bank" had the same embedding whether used in "river bank" or "bank account". Transformers produce contextual embeddings — the vector for "bank" is different in every sentence, shaped by every other token via self-attention.

Recommended video

3Blue1Brown — "But what is a word embedding?" · Vector arithmetic and semantic geometry

Topic 03 of 06

Self-Attention

Self-attention lets every token directly query every other token — capturing long-range dependencies that recurrent networks could not. It is the core mechanism of the Transformer.

Query, Key, Value

For each token embedding x, three linear projections produce a Query Q ("what am I searching for?"), a Key K ("what do I advertise?"), and a Value V ("what do I carry?"). The attention weight between tokens i and j is the dot product Qi·Kj scaled by √dk, passed through softmax. The output for token i is a weighted sum of all Value vectors.

Formula: Attention(Q, K, V) = softmax( QKᵀ / √dk ) · V

Live heatmap demo

Hover any word below. The highlight intensity on other words shows how strongly an attention head attends to that token in context.

Hover a word to reveal its attention pattern

Multi-head attention

The Transformer runs h attention heads in parallel, each with independent Q/K/V projections. Different heads specialise — one may track syntactic dependencies, another co-reference, another positional proximity. Their outputs are concatenated and projected back to the model dimension.

Causal masking (GPT)

During generation, token i must not see token j > i. A causal mask sets those attention scores to −∞ before softmax, making them zero after normalisation. This enforces strictly left-to-right generation.

Recommended video

3Blue1Brown — "But what is a GPT?" · Transformers and attention explained visually

Topic 04 of 06

The Transformer

"Attention Is All You Need" (Vaswani et al., Google, 2017) replaced recurrent networks as the dominant sequence-modelling architecture. The key insight: attention mechanisms alone — without recurrence or convolution — are sufficient.

Architecture at a glance

1
Token + positional embeddings — each token ID becomes a d-dimensional vector; sine/cosine positional encodings inject sequence order
2
Multi-head self-attention — every token attends to all others (or all previous ones, for causal generation)
3
Add & LayerNorm — residual connection adds input to output; LayerNorm stabilises training
4
Feed-forward network — two linear layers with GELU, projecting to 4× model width and back
5
Repeat N times — GPT-4 stacks ~128 layers; depth is what creates deep understanding
6
Output head — final hidden state → vocabulary-sized logits → softmax → token probability distribution
BERT vs GPT: BERT uses bidirectional attention — reads the full sentence at once, optimal for understanding tasks. GPT uses causal (unidirectional) attention — reads left to right, optimal for generation. Both are Transformers; only the masking strategy differs.

Recommended video

Andrej Karpathy — "Let's build GPT from scratch" · Complete Transformer implementation in Python

Topic 05 of 06

RLHF

Reinforcement Learning from Human Feedback transforms a raw next-token predictor into a helpful, safe assistant. Without it, a pre-trained LLM is brilliant at imitating the internet — including its worst parts.

Phase 1 — Supervised Fine-Tuning (SFT)

Human contractors write ideal (prompt → response) pairs. The base model is fine-tuned on these examples, shifting it toward "helpful assistant" behaviour in style and tone. This alone is insufficient — the behaviour is inconsistent and the model still produces harmful outputs.

Phase 2 — Reward Model Training

The SFT model generates multiple responses to each prompt. Human raters rank them from best to worst. A separate neural network — the Reward Model (RM) — is trained on these rankings. It learns to score any (prompt, response) pair without further human involvement.

Phase 3 — RL via PPO

The SFT model is treated as a policy. The Reward Model evaluates its outputs; Proximal Policy Optimization (PPO) updates the policy's weights to maximise reward. A KL-divergence penalty prevents the policy from drifting so far from the SFT baseline that it "reward-hacks" — generating responses that score well on the RM but humans dislike.

Critical distinction: RLHF teaches behaviour, not facts. All world knowledge comes from pre-training. RLHF only shapes how that knowledge is expressed — tone, safety, honesty, helpfulness.

Recommended video

Yannic Kilcher — "InstructGPT: Training language models to follow instructions" · Paper walkthrough

Topic 06 of 06

Hallucinations

A hallucination is any model output that is fluent, confident, and factually false. The model has no concept of truth — only of generating statistically likely continuations. "Sounding correct" and "being correct" are distinct.

Why they happen

LLMs are trained to maximise the likelihood of the next token. When asked about something rare or outside their training distribution, they do not know to say "I don't know." They generate whatever sequence would have been most likely in similar contexts — which can be entirely fabricated, stated with equal confidence to true facts.

Taxonomy: Intrinsic (contradicts information already in the context), Extrinsic (fabricates new information), Temporal (outdated facts stated as current), Citation (non-existent papers with plausible DOIs and author names).

Active mitigations

1
RAG — Retrieval-Augmented Generation grounds responses in retrieved documents, limiting what the model can freely fabricate
2
Chain-of-Thought — externalise reasoning steps before the final answer, making errors visible and correctable
3
Uncertainty calibration — train models to express calibrated doubt rather than projecting false confidence
4
Human-in-the-loop — for high-stakes applications, require verification of all factual claims against primary sources
Rule: Treat every factual claim from an LLM as a hypothesis. Verify before acting. LLMs are reasoning engines, not knowledge stores.

Recommended video

Andrej Karpathy — "Neural networks: Zero to Hero" · Building intuition for why generation is probabilistic

Interactive Lab

Hands-on demos

Two live experiments. Interact directly with the mechanics you've read about.

01

Tokenizer Playground

Type any text and watch it fragment into tokens in real time. Each chip is one token — the atomic unit an LLM reasons with. Spaces are shown as · to make whitespace tokens visible.

0 tokens
Tokens will appear here…

Simplified whitespace/punctuation tokenizer. Production LLMs use Byte-Pair Encoding with a 50k–100k vocabulary table.

02

Probability Waterfall

Click Generate to simulate one step of autoregressive decoding. Three candidate tokens fall in with their probabilities; the highest-probability token is selected and appended to the sentence.

Context window
Large language models are trained to predict

Video Library

Watch to understand

Curated lectures from the sharpest educators in ML. Click any card to watch in an overlay.

3Blue1Brown GPT
3Blue1Brown

But what is a GPT?

Visual first-principles breakdown of Transformer architecture and text generation.

Architecture
Build GPT from scratch
Andrej Karpathy

Let's build GPT from scratch

Code a Transformer in Python from zero — the definitive technical walkthrough.

Deep Dive
RLHF paper walkthrough
Yannic Kilcher

RLHF — InstructGPT Paper

The alignment technique behind ChatGPT, explained via the original paper.

Alignment
Neural networks zero to hero
Andrej Karpathy

Neural Networks: Zero to Hero

From backpropagation to a character-level language model. The complete series.

Foundations
GPT Tokenizer
Andrej Karpathy

Let's build the GPT Tokenizer

BPE from scratch — tiktoken internals and Unicode edge cases explained.

Tokenization
Word embeddings
3Blue1Brown

Word Embeddings & Word2Vec

The geometric intuition behind semantic vector spaces, beautifully visualised.

Embeddings

Assessment

Knowledge Check

Eight questions covering all six topics. Select an answer to reveal instant feedback and a technical explanation.

1. What does BPE (Byte-Pair Encoding) do during tokenizer training?

2. What geometric property do word embeddings exhibit?

3. What is the scaled dot-product attention formula?

4. How does GPT enforce left-to-right generation?

5. What does the Reward Model learn in the RLHF pipeline?

6. An LLM "hallucination" is best defined as:

7. What does RAG primarily address?

8. In RLHF, the KL-divergence penalty: