BrainBank

July 29 2026 Note

7/29/2026, 11:07:23 PM · updated 7/29/2026, 11:28:03 PM · Source

#knowledge#transformers#self-attention#q-k-v-vectors#encoder-decoder#quantization#llm-inference

A detailed walkthrough of how Generative Pre-trained Transformers function, breaking down the Q/K/V self-attention retrieval system, the semantic weights assigned by encoders versus the predictive outputs of decoders, and how quantization optimizes inference efficiency.

This note provides a technical overview of Generative Pre-trained Transformers (GPTs), detailing their foundational architecture, the core mechanics of self-attention via Query, Key, and Value vectors, and key processing stages including encoding, decoding, inference layers, and quantization techniques.

Core Architecture & The Q/K/V Mechanism

First Layer: Position 128
Second Layer: 32 Token Internal meaning (4 batch, 8 token each)
Third Layer: 3 Tables

image.png

In AI transformer models, Q (Query), K (Key), and V (Value) are three distinct vector representations created for every token to power the self-attention mechanism. They function like a retrieval system where a token asks a question, searches an index, and retrieves content. [1, 2, 3, 4, 5]

image.png

Roles of Q, K, and V

  • Query (Q): What a specific token is looking for right now (like typing a search term).
  • Key (K): What kind of information a token offers (like an index label or tag on a database entry).
  • Value (V): The actual core data or meaning the token shares when its key matches a query.

How They Work Together

  • Matching: The model multiplies Q and K vectors together to score how relevant each word is to the current word.
  • Blending: It applies those scores as weights to the V vectors to build a new, context-aware meaning for the text.

Self-Attention, Encoders, and Decoders

Self-attention mechanisms are the signature feature of transformers, empowering them to process an entire input sequence at once. Transformers can self-direct their “attention” to the most important tokens in the input sequence, no matter where they are.

By contrast, older recurrent neural networks (RNNs) and convolutional neural networks (CNNs) assess input data sequentially or hierarchically. Self-attention allows GPTs to process context and reply at length with language that feels natural, rather than merely guessing the next word in a sentence.

Encoders

Encoding is the process of mapping tokens onto a virtual three-dimensional vector space. Tokens encoded nearby in the 3D space are assumed to be more similar in meaning. This mathematical vectorization of an input sequence is known as an embedding.

The encoder blocks in the transformer network assign each embedding a weight, which determines its relative importance. Meanwhile, position encoders capture semantics, enabling GPT models to differentiate between groupings of the same words but in different orders—for example, “The egg came before the chicken” as compared to “The chicken came before the egg.”

Decoders

Decoders predict the most statistically probable response to the embeddings prepared by the encoders. Self-attention mechanisms permit the decoder to identify the most important portions of the input sequence, while advanced algorithms determine the output most likely to be correct.

Video Reference: It's about time we learn Transformers.., by Caleb Writes Code.
https://www.youtube.com/watch?v=7gkaDEpHg

Inference Layers

image.png image.png image.png image.png

Quantization

Quantization is the process of reducing data precision, most commonly by converting 32-bit floating-point numbers into lower-precision formats like 8-bit integers to shrink file sizes and speed up computing. May loss Precision.

image.png

Key takeaways

  • Transformers rely on Q (Query), K (Key), and V (Value) vectors to power a retrieval-like self-attention system that scores relevance and blends contextual meaning.
  • Unlike the sequential processing of RNNs and CNNs, transformers process entire sequences in parallel, enabling natural, context-aware language generation through dedicated encoder and decoder blocks.
  • Inference layers handle the final computational steps required to transform encoded representations into actionable outputs.
  • Quantization optimizes model performance by reducing precision (e.g., from 32-bit float to 8-bit int), significantly shrinking file sizes and accelerating computation at the potential cost of some accuracy.

Learning map

Phase 1: Input Representation & Context

  1. Map raw text into discrete tokens and embed them into a unified vector space.
  2. Apply positional encoding vectors to give the model temporal awareness so it can distinguish identical words used in different orders.

Phase 2: The Self-Attention Retrieval System

  1. Isolate Q (Query), K (Key), and V (Value) matrices derived from each token's embedding.
  2. Execute matrix multiplication of Q and K to generate an attention score representing contextual relevance.
  3. Normalize those scores as weights and apply them across the V vectors to create context-aware output representations.

Phase 3: Structural Processing (Encoder → Decoder)

  1. Pass weighted vectors through Encoder blocks to capture semantic relationships across the entire sequence simultaneously.
  2. Route the final embeddings into the Decoder block, utilizing masked self-attention to predict statistically probable next-token outputs step-by-step.

Phase 4: Inference & Quantization Optimization

  1. Analyze raw 32-bit floating point (FP32) data precision during initial model runs.
  2. Implement quantization routines (e.g., FP16 → INT8) to shrink matrix sizes, reduce memory footprint, and accelerate inference without sacrificing core functional logic.

Get hands-on — step by step

  1. Download a locally hosted LLM via a library like transformers() or use the llama.cpp environment to observe raw Q/K/V matrix dimensions as data passes through layers.
  2. Take a short two-sentence sample and manually calculate a simplified single-head attention score: dot product the Query vector against all Key vectors, apply Softmax, then scale the Value vectors.
  3. Compare the memory footprint of an unquantized GPT architecture (FP16/BF16) versus a quantized version (INT8 or NF4) using bitsandbytes and measure the resulting speedup during text generation.
  4. Visualizes how shifting the decoder layers' weights affects the statistical probability distribution across the final vocabulary logits before the output token is finalized.

Top 3 sources

  1. 1
    The Annotated Transformer

    A foundational, step-by-step annotated tutorial that breaks down the exact math, dimensions, and flow of QKV vectors and attention matrices.

    https://nlp.seas.harvard.edu/2018/04/03/attention.html

  2. 2
    Hugging Face Transformers Course

    A highly regarded practical guide explaining how tokenizers ingest text and utilize underlying PyTorch modules for attention and decoding.

    https://huggingface.co/course/chapter1/3

  3. 3
    Karpathy: LLMs from Scratch (YouTube)

    A widely celebrated video series by Andrej Karpathy that walks through building attention mechanisms, transformer blocks, and quantization purely from Python code.

    https://www.youtube.com/watch?v=kCc8FmEb1qY

Links are AI-suggested — worth a quick sanity check before diving in.