Skip to main content

Inside LLM Compute: Matrices, GPU & VRAM

Follow a token from its embedding through memory transfers, tensor-core math, attention, KV cache, and output generation. Includes interactive matrix and memory simulations. · interactive original ↗

01 · Foundations: what is a matrix?​

A scalar is one number; a vector is a one-dimensional array; a matrix is a two-dimensional array; and a tensor generalizes these to arbitrary dimensions. LLMs represent token embeddings and activations as tensors.

Scalar → Vector → Matrix → Tensor​

5
[3, 7, 2]
[[1, 2, 3], [4, 5, 6]]
Tensor shape: [batch, tokens, hidden]

A token embedding is a vector. Multiple token vectors form a matrix; batches of sequences form higher-rank tensors.

Matrix multiplication dimensions​

A: (m × n)
B: (n × p)
C = A × B: (m × p)

The inner dimensions must match. Each output element is a dot product between a row of A and a column of B.

note

Core idea: text becomes token IDs, token IDs become numerical vectors, and learned weight matrices transform those vectors repeatedly.

02 · Interactive matrix multiplication​

Choose an output cell in C. The highlighted row in A and column in B are multiplied element-by-element and summed. Then explore how a GPU moves and computes this data.

A (2×4)
×
B (4×3)
=
C (2×3)

Pick a row of A (r1, r2) and a column of B (c1–c3), or a cell of C, to see that dot product. Type over a number in A or B to change it — C recomputes.

1 × 1 + 2 × 4 + 3 × 7 + 4 × 10 = 70
Compute

Multiply-and-accumulate operations form the output. Tensor Cores can process many fused matrix operations in parallel.

1 × 1 + 2 × 4 + 3 × 7 + 4 × 10 = 70

Why tiling and reuse matter​

A naive implementation reloads the same values repeatedly. Tiled GEMM loads blocks of A and B into fast on-chip storage so many multiply-accumulate operations reuse them. Pipelines can overlap loading, computing, and writing.

caution

Important correction: GPU computation and VRAM access are not strictly separate, alternating steps. Modern GPU kernels overlap data movement and arithmetic.

03 · GPU hardware and memory hierarchy​

VRAM stores the bulk data; GPU compute units execute arithmetic. Between them are caches, shared memory, and registers. NVIDIA GPUs organize compute units into streaming multiprocessors (SMs).

GPU DeviceVRAM / HBMModel weights · Activations · KV cache · WorkspaceL2 CacheShared on-chip cacheSM 1RegistersShared Memory / L1Tensor CoresCUDA CoresSM 2 … NRegistersShared Memory / L1Tensor CoresCUDA Cores
ComponentRoleLLM example
VRAM / HBMBulk storageWeights, KV cache, activations
L2 CacheShared on-chip cachingReuse hot data; reduce HBM traffic
Shared Memory / L1Fast on-chip working setTiled GEMM operand reuse
RegistersVery fast per-thread storageAccumulators and intermediate values
Tensor CoresHigh-throughput matrix arithmeticGEMM, Attention projections, FFN
CUDA CoresGeneral arithmetic / controlElementwise math, portions of reductions
Simplified NVIDIA-oriented diagram: actual chips have many SMs, schedulers, load/store units, and architecture-specific caches. Some operations are fused, so intermediate results never reach VRAM.

04 · A Transformer does much more than MatMul​

A decoder-only Transformer repeatedly applies normalization, Q/K/V projections, positional operations, causal attention, residual additions, and feed-forward networks. Final logits are converted to the next token.

Text → Token IDs → EmbeddingRMSNorm / LayerNormQ = XWq · K = XWk · V = XWvRoPE + AttentionQKᵀ → Mask → Softmax → × VKV Cache (VRAM)Read old K/V · append new K/VOutput Projection + Residual + NormFFN / MLPMatMul → Activation / Gating → MatMulResidual → Repeat Transformer Blocks × NFinal Norm → Vocabulary Projection → LogitsSampling → Next Token

Attention: Q, K and V​

Q = X Wq ; K = X Wk ; V = X Wv
Attention(Q,K,V) = softmax(QKᵀ / √dₖ + mask) V

Q is the query representation; K provides matching features; V carries the information being mixed. The QKᵀ product creates attention scores, a causal mask blocks future positions, softmax normalizes scores, and multiplying by V aggregates information. Optimized kernels such as FlashAttention avoid materializing the full attention matrix in HBM.

Feed-forward network (FFN)​

An FFN applies learned matrix projections and a nonlinear activation. Many modern LLMs use gated variants such as SwiGLU. The displayed formula is a simplified example with a column-vector convention.

FFN(X) ≈ W₂ · activation(W₁X + b₁) + b₂
Example: 4096 → 11008 → 4096

Other GPU operations in an LLM​

OperationRoleTypical pressure
GEMM / MatMulMatrix productsCompute or memory
RMSNorm / LayerNormNormalize activationsMemory / reduction
RoPEInject position informationElementwise / memory
SoftmaxNormalize attention scoresReduction / memory
SiLU / GELUNonlinear activationsCompute / memory
AttentionMix contextual informationCompute / KV I/O
Residual AddCombine pathwaysMemory bandwidth
SamplingChoose next tokenReduction / sampling
Quantize / DequantizeCompact / restore numeric formatsMemory / compute

05 · What occupies VRAM?​

Inference memory is more than model weights. The working set includes weights, cached keys/values, intermediate activations, runtime buffers, and allocation overhead.

Illustrative memory composition​

WeightsKV CacheActivationsWorkspace
The proportions above are conceptual only, not measurements from any particular model.

Weight storage and precision​

For a hypothetical 7-billion-parameter model, raw weight size is approximately parameter count × bytes per parameter.

PrecisionBytes / parameter7B model weights
FP32428 GB
FP16 / BF16214 GB
INT817 GB
INT40.53.5 GB
Quantized models also require scales, metadata, and sometimes higher-precision layers. GB is decimal here; usable GPU capacity is often displayed in GiB.

KV Cache: why context and concurrency consume memory​

At each decoder layer, previously computed keys and values are cached. During decode, attention reads historical K/V and appends new K/V. This simple formula assumes dense, uniform caching across sequences.

KV bytes = 2 × layers × cached_tokens × KV_heads × head_dim × bytes_per_element × sequences
1.00 GiB
Estimated raw KV cache size (GiB)
Excludes allocator fragmentation, page tables, runtime buffers, prefix sharing, sliding-window attention, cache offload, and architecture-specific variants.

06 · Prefill versus Decode​

LLM generation has two performance regimes. Prefill processes many prompt tokens together. Decode then produces one token per sequence at a time, while using the growing KV cache.

1 PrefillMany prompt tokensBuild KV cache2 DecodeNew tokenRead + append KV

① Prefill​

Many prompt tokens are processed in parallel, often producing large matrix multiplications with good compute utilization. The KV cache is built. Time to first token (TTFT) includes prefill and additional serving overhead.

② Decode​

For each active sequence, the model processes its latest token, reads past KV, and appends new KV. At low batch sizes this often behaves like matrix-vector work and can be limited by memory bandwidth.

DimensionPrefillDecode
Input shapeMany prompt tokensOne new token per sequence
Typical GEMMLarge matricesSmaller matrices / matrix-vector at low batch
KV CacheBuildRead and append
Common limitCompute + attentionBandwidth / KV I/O at low batch
MetricTTFTTPOT / tokens per second
caution

Decode is not always memory-bound. Larger batches, long-context attention, and different model architectures can shift the bottleneck toward compute.

07 · Compute-bound vs memory-bound​

Performance is constrained both by arithmetic throughput (FLOP/s) and the rate at which operands move (bytes/s). Arithmetic intensity measures FLOPs per byte transferred. Explore the simplified Roofline model below.

Attainable FLOP/s ≤ min(Peak FLOP/s, Bandwidth × Arithmetic Intensity)
Theoretical attainable throughput
10.0 TFLOP/s
Memory Bound
TFLOP/s
Arithmetic Intensity (FLOP/byte)
Educational roofline: assumes decimal TB/TFLOP units, ideal utilization, and a single memory-bandwidth ceiling. Real kernels also face latency, occupancy, launch overhead, cache behavior, and other limits.

A bandwidth-only lower-bound example​

14 GB ÷ 1,000 GB/s = 0.014 s = 14 ms

If 14 GB of weights must be read from HBM at an ideal 1 TB/s, the transfer alone takes at least 14 ms. This is not a real token latency prediction: cache reuse, KV traffic, arithmetic, and scheduling also matter.

08 · Training vs Inference​

Inference primarily runs the forward pass using fixed weights. Training additionally computes gradients through a backward pass and updates weights with an optimizer.

Forward passActivations + LossBackward passGradientsOptimizer stepUpdate weights
DimensionInferenceTraining
Forward passYesYes
Backward / gradientsNoYes
Update weightsNoYes
Optimizer statesNormally noUsually yes
Activation storageForward working setSaved or recomputed for backward

Training also stores gradients, optimizer states (for example Adam moments), and backward-required activations. Precision, sharding, checkpointing, and optimizer choice change the memory footprint substantially.

09 · Key takeaways​

QuestionAnswer
Where are large weight matrices?Primarily in VRAM/HBM.
Who performs matrix multiplication?Usually GPU Tensor Cores accelerate the heavy GEMM kernels.
Does every intermediate go to VRAM?No. Registers, caches and kernel fusion can avoid writes.
Why does long context use more memory?KV cache generally grows with cached tokens and active sequences.
Why can a high-FLOPS GPU still be slow?Memory bandwidth, utilization, kernel overhead, and KV traffic.
Why is training more memory-intensive?Gradients, optimizer states, and backward activations.
note

Think in two coupled systems: (1) the mathematical graph of Transformer operations, and (2) the physical path that moves tensors through GPU memory to execution units. Both determine latency and throughput.

What to learn next​

Follow this sequence: VRAM/HBM → L2 → Shared Memory → Registers → Tensor Core MMA → Accumulator → Output; then study FlashAttention, PagedAttention, continuous batching, quantization, and GPU profiling.