Series I · Part 01 Technical Monograph

Autoregressive Transformers & Inference Mechanics

1.1 Subword Tokenization, RoPE & Causal Self-Attention  •  1.2 KV-Cache Memory Arithmetic, Decoding & Calibration

Publication: Series I (Part 01/12) Study Time: 40–45 minutes Authorship: Original AhnLim Foundation OER (CC BY-NC 4.0)

Part 01 Scope & Analytical Objectives

  • Trace how raw UTF-8 text and domain code map into Byte-Pair Encoding (BPE) subword IDs, dense embeddings, and Rotary Positional Embeddings (RoPE), diagnosing why irregular digit chunking impairs raw token arithmetic.
  • Derive the matrix dimensions and asymptotic complexity of causal scaled dot-product attention and Grouped-Query Attention (GQA), contrasting compute-bound prompt prefill against memory-bandwidth-bound token decoding.
  • Compute exact GPU High-Bandwidth Memory (HBM) KV-cache requirements across batch sizes, sequence lengths, and numerical precisions, and diagnose probability miscalibration under temperature and nucleus sampling.

Executive & Technical Overview

Treating a Large Language Model (LLM) as an opaque black-box text generator works for casual experimentation—and fails predictably under rigorous scientific or enterprise engineering requirements. Why does an LLM occasionally misadd two 9-digit ledger balances while effortlessly summarizing a 40-page regulatory docket? Why does doubling prompt context from 32,768 to 65,536 tokens quadruple prefill attention compute while expanding per-request GPU memory linearly? Why can setting temperature = 0.0 still yield slightly different token trajectories under concurrent server batching?

Every one of these empirical behaviors follows directly from three mathematical mechanisms at the core of modern decoder-only transformers: subword tokenization, causal self-attention with relative rotary positions, and KV-cached autoregressive decoding. Mastering these mechanics gives systems engineers quantitative control over latency, hardware cost, and reliability.

1.1 Subword Tokenization, RoPE & Causal Self-Attention

A. Byte-Pair Encoding (BPE) & Token Fertility Asymmetries

Autoregressive transformers do not ingest raw Unicode characters or whitespace-delimited words; instead, they operate over a finite subword vocabulary V (typically 100,000 to 256,000 symbols) constructed via byte-level Byte-Pair Encoding (BPE). Starting from the 256 base UTF-8 byte values, BPE iteratively merges the highest-frequency adjacent symbol pair in a calibration corpus until reaching vocabulary capacity |V|.

Given an input string S, a deterministic greedy scanner maps S into integer token indices x = (x1, x2, …, xT). Three operational consequences immediately affect system design:

  • Token Fertility & Context Economics: Token fertility measures the average number of subword tokens required per word or structured record. Standard English prose averages ~3.8–4.2 characters per token, whereas deeply indented JSON/XML, Base64 blobs, underrepresented human languages, and molecular SMILES strings exhibit high fertility—consuming context budget and quadratic attention compute much faster.
  • Non-Aligned Numerical Segmentation: Unless a model family enforces single-digit tokenization, multi-digit integers split inconsistently depending on length: 148290 may split into two tokens [148, 290], whereas 1482905 splits into [14, 829, 05]. Because place-value alignment shifts arbitrarily across token boundaries, delegating arithmetic to deterministic Python/SQL tools is an architectural necessity rather than a temporary workaround.
  • Boundary Artifacts in String & Diff Operations: Because newline characters and indentation runs often merge into composite tokens, LLMs struggle to count exact line numbers reliably unless explicit line indices (001: ...) are injected into the prompt.

B. Causal Scaled Dot-Product Attention & Grouped-Query Attention (GQA)

Each token index xt retrieves a row vector from embedding matrix WE ∈ R|V| × dmodel. Inside transformer block ℓ ∈ {1, …, L}, pre-normalized hidden states H ∈ RT × dmodel project into Query, Key, and Value matrices of head dimension dk:

Q = H WQ,    K = H WK,    V = H WV    where   WQ, WK, WV ∈ Rdmodel × dk

To preserve causality—ensuring position t depends solely on positions j ≤ t—an upper-triangular mask Mt,j = −∞ (for j > t) and 0 (for j ≤ t) is applied prior to row-wise softmax:

Attention(Q, K, V) = softmax( (Q K⊤) / √dk + M ) V

Dividing by √dk prevents variance explosion: if components of qt and kj have zero mean and unit variance, their inner product has variance dk; unscaled inner products drive softmax into near-one-hot saturation with vanishing gradients.

While classic Multi-Head Attention (MHA, Vaswani et al., 2017) allocates nh separate Key and Value projections alongside nh Query heads, modern frontier and open-weights models use Grouped-Query Attention (GQA, Ainslie et al., 2023). GQA retains nh query heads (e.g., 64) partitioned into nkv groups (e.g., 8) that share a single Key and Value head per group—shrinking KV-cache storage and memory-bus traffic by 8× while matching MHA accuracy.

C. Relative Sequence Geometry via Rotary Positional Embeddings (RoPE)

Without positional information, self-attention is permutation-equivariant up to the causal mask. Rather than adding fixed sinusoidal offsets only at layer 0, contemporary architectures apply Rotary Positional Embeddings (RoPE, Su et al., 2021) directly to qt and kj inside every attention layer. Grouping feature coordinates into 2D pairs (2m−1, 2m), RoPE rotates each pair by angle tθm where θm = β−2(m−1)/dk (with base β typically 10,000 to 1,000,000):

[ q′t,2m−1 ; q′t,2m ] = [ cos(tθm)   −sin(tθm) ; sin(tθm)   cos(tθm) ] [ qt,2m−1 ; qt,2m ]

Because the dot product of two rotated 2D vectors depends solely on the difference of their rotation angles (t − j)θm, RoPE encodes translation-invariant relative token distance natively inside inner-product attention. High-frequency planes capture local syntax, whereas low-frequency planes track long-range discourse dependencies.

1.2 KV-Cache Memory Arithmetic, Decoding & Calibration

A. Two Distinct Hardware Regimes: Compute-Bound Prefill vs. Bandwidth-Bound Decode

Serving an LLM request consists of two physically distinct execution phases with opposite hardware bottlenecks:

Execution Phase Matrix Kernel Dominant Hardware Bottleneck Observable SLA Metric
1. Prefill (Prompt Ingestion) Parallel matrix-matrix multiplication (GEMM) across all Tin prompt tokens simultaneously. Compute-bound (GPU Tensor Core TFLOP/s); quadratic O(Tin2) attention work at long contexts. TTFT (Time to First Token)
2. Decode (Autoregressive Output) Sequential matrix-vector multiplication (GEMV) for 1 new token per step against cached Keys/Values. Memory-bandwidth-bound (HBM TB/s); every single generated token streams model weights + active KV cache from VRAM. ITL / TPOT (Inter-Token Latency)

B. Exact KV-Cache Memory Arithmetic

Caching historical Key and Value projections reduces total generation complexity from cubic O(S3) to quadratic O(S2), at the cost of holding dynamic state in GPU VRAM. For L transformer layers, nkv key-value heads per layer, head dimension dk, b bytes per numerical element (b = 2 for BF16/FP16; b = 1 for FP8), concurrent batch size B, and sequence length S = Tin + Tout:

MemoryKV (bytes) = 2 × L × nkv × dk × b × B × S

The leading factor of 2 accounts for storing both K and V tensors. When serving multi-document RAG or multi-turn agent trajectories (S ≥ 32,768), unpaged KV caches quickly rival the memory footprint of the model weights themselves. Modern inference engines (such as PagedAttention architectures) allocate KV blocks in non-contiguous virtual memory pages to eliminate internal fragmentation and share identical system-prompt prefixes across concurrent users.

C. Decoding Samplers, Floating-Point Non-Associativity & Calibration

At step t, final hidden state ht(L) maps through unembedding matrix WU to logits zt ∈ R|V|, rescaled by temperature T > 0:

PT(xt+1 = v | x1:t) = exp(zt,v / T) / ∑u ∈ V exp(zt,u / T)
  • Greedy Decoding (T → 0) & Batch Non-Determinism: Selecting argmaxv zt,v eliminates random sampling noise and should be the default for structured extraction, SQL/code synthesis, and classification. However, IEEE-754 floating-point addition is non-associative: (a + b) + c ≠ a + (b + c). When a cloud server dynamically batches your request alongside varying concurrent traffic, GPU reduction tile orders shift slightly, occasionally flipping two nearly tied top logits at bit precision and altering downstream tokens.
  • Top-p (Nucleus) Sampling: Retains the smallest sorted set of candidate tokens whose cumulative probability exceeds threshold p (e.g., p = 0.90 at T = 0.6), preventing catastrophic tail-token hallucinations while preserving controlled lexical diversity for open-ended drafting.
  • Epistemic Miscalibration (NIST AI 600-1 Confabulation Risk): Post-training preference tuning rewards fluent, authoritative tone—decoupling verbalized confidence (“I am 98% sure”) from empirical truth. Never gate high-consequence decisions on self-reported prose confidence; measure Expected Calibration Error (ECE) over token probabilities on discrete validation sets or enforce deterministic external verification.

Worked Engineering Lab & Reference Implementation

Suppose your engineering team hosts a 70B-parameter open-weights transformer (L = 80 layers, nh = 64 query heads, nkv = 8 GQA key-value heads, dk = 128) to process B = 8 concurrent 32,768-token technical dockets. In BF16 (b = 2 bytes), model weights occupy ~130.4 GiB and the KV cache adds 80.0 GiB (totaling 210.4 GiB before workspace overhead). Below is an original, self-contained Python diagnostic utility computing exact VRAM budgets, nucleus sampling truncation, and Expected Calibration Error (ECE):

import math
from typing import Sequence, Tuple

def compute_vram_budget_gib(
    param_billions: float,
    weight_bytes: float,
    layers: int,
    kv_heads: int,
    head_dim: int,
    kv_bytes: float,
    batch_size: int,
    unique_seq_len: int,
    shared_prefix_len: int = 0,
) -> dict:
    """Computes exact weight + KV-cache memory in GiB with optional prefix caching."""
    gib = 1024 ** 3
    weight_gib = (param_billions * 1e9 * weight_bytes) / gib
    bytes_per_token = 2 * layers * kv_heads * head_dim * kv_bytes
    shared_kv_gib = (bytes_per_token * shared_prefix_len) / gib
    unique_kv_gib = (bytes_per_token * batch_size * unique_seq_len) / gib
    total_kv_gib = shared_kv_gib + unique_kv_gib
    return {
        "weights_gib": round(weight_gib, 2),
        "kv_cache_gib": round(total_kv_gib, 2),
        "total_gib": round(weight_gib + total_kv_gib, 2),
    }

def expected_calibration_error(
    confidences: Sequence[float], correctness: Sequence[int], n_bins: int = 10
) -> float:
    """Computes Expected Calibration Error (ECE) across uniform probability bins."""
    assert len(confidences) == len(correctness) and len(confidences) > 0
    n = len(confidences)
    ece = 0.0
    for b in range(n_bins):
        lo, hi = b / n_bins, (b + 1) / n_bins
        idx = [
            i for i, c in enumerate(confidences)
            if (lo <= c <= hi if b == n_bins - 1 else lo <= c < hi)
        ]
        if not idx:
            continue
        avg_conf = sum(confidences[i] for i in idx) / len(idx)
        avg_acc = sum(correctness[i] for i in idx) / len(idx)
        ece += (len(idx) / n) * abs(avg_acc - avg_conf)
    return round(ece, 4)

# Example comparison: BF16 uncached vs. FP8 + 24k shared system-manual prefix cache
bf16_naive = compute_vram_budget_gib(70, 2.0, 80, 8, 128, 2.0, batch_size=8, unique_seq_len=32768)
fp8_cached = compute_vram_budget_gib(70, 1.0, 80, 8, 128, 1.0, batch_size=8, unique_seq_len=8192, shared_prefix_len=24576)
# bf16_naive -> {'weights_gib': 130.39, 'kv_cache_gib': 80.0, 'total_gib': 210.39}
# fp8_cached -> {'weights_gib': 65.19,  'kv_cache_gib': 13.75, 'total_gib': 78.94}

Analytical Review & Self-Study Questions

Work through each analytical problem independently before expanding the reference derivation:

Problem 1.1 (KV-Cache Scaling): How much KV-cache VRAM would the 70B BF16 deployment (B = 8, S = 32,768, L = 80, d_k = 128) consume if it used standard Multi-Head Attention (n_kv = 64) instead of 8-group GQA (n_kv = 8)?
Substituting n_kv = 64 multiplies per-token KV storage by 8×: 2 × 80 × 64 × 128 × 2 = 2,621,440 bytes/token (2.5 MiB/token). Across B = 8 and S = 32,768 tokens, the KV cache alone would require 640.0 GiB (nearly 5× the size of the 130.4 GiB model weights), illustrating why GQA is essential for long-context serving.
Problem 1.2 (Prefill vs. Decode Diagnosis): Your production telemetry shows Time-to-First-Token (TTFT) spiked by 4.1× after users began uploading 40-page contracts, while Inter-Token Latency (ITL) rose by only 1.3×. Explain the underlying hardware cause.
Prompt prefill executes full causal self-attention across all T_in input tokens simultaneously, scaling quadratically O(T_in²) in Tensor Core compute once context length dominates linear projections—driving the 4.1× TTFT jump. Subsequent decode steps perform O(T_in) bandwidth reads from the cached KV tensors alongside constant model-weight reads, producing a much gentler linear increase in per-token decode time.
Problem 1.3 (Calibration Audit): On 200 clinical-coding test items, a model assigns 0.90 mean token probability to its chosen code, yet achieves 0.68 empirical accuracy in that bin. Compute this bin's calibration gap and state why raw threshold filtering at p >= 0.85 is unsafe without recalibration.
The bin's absolute calibration error is |0.68 − 0.90| = 0.22 (22 percentage points of overconfidence). Filtering predictions at nominal p >= 0.85 under the assumption of <=15% error rate would silently pass a 32% error rate into downstream workflows; isotonic or temperature-scaling recalibration on a held-out validation set is required first.

Public-Domain Standards & Open-Access References

All theoretical formulations, worked numerical examples, and Python implementations in this publication are originally authored by AhnLim Foundation and grounded exclusively in public-domain government standards and peer-reviewed open-access scientific literature:

  • Vaswani, A. et al. (2017). Attention Is All You Need. Advances in Neural Information Processing Systems (NeurIPS / open-access arXiv:1706.03762).
  • Su, J. et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. Open-access preprint (arXiv:2104.09864).
  • Ainslie, J. et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. EMNLP (open-access arXiv:2305.13245).
  • National Institute of Standards and Technology (2024). Artificial Intelligence Risk Management Framework: Generative Artificial Intelligence Profile (NIST AI 600-1). U.S. Department of Commerce (Public Domain, DOI: 10.6028/NIST.AI.600-1).
Copyright & Provenance Attestation: Zero proprietary textbook passages or restricted datasets are reproduced on ahnlim.org. Educators, researchers, practitioners, and independent readers may freely share, print, and adapt this publication under CC BY-NC 4.0 with attribution to AhnLim Foundation (Series I, Part 01).