LLM Architecture and Parameters: How to Estimate Memory and Choose the Right Model

    This article explains how to estimate the deployment cost of large language models by understanding their architecture and parameters. It breaks down Transformer layer components, distinguishes between dense and Mixture-of-Experts (MoE) models, and provides practical formulas for calculating weight memory, KV cache size, and total VRAM usage. It concludes with a hands-on checklist for model selection and capacity planning, covering everything from context length and quantization to inference framework compatibility and compliance costs.

    Introduction

    Model selection often starts with benchmark scores, but those scores cannot tell you whether your GPU has enough VRAM, how much compute each token will cost, or whether latency will meet your requirements. Developers need to read the architecture and parameter numbers to estimate deployment costs. This article first explains the key components of Transformer layers, then clarifies what total parameters, activated parameters, and quantization sizes mean. We provide estimation formulas for weight memory and KV cache, and finish with a practical selection checklist you can execute directly.

    Transformer Layer Components

    Modern large language models almost all use a decoder-only Transformer architecture. Input text is first tokenized into token sequences, transformed layer by layer through multiple Transformer blocks, and finally passed through an output layer to produce a probability distribution for each token in the vocabulary. The differences between models mainly come from the internal design of the blocks, as well as the configuration of the number of layers (L) and hidden dimension (d).

    A typical Transformer layer contains two core submodules: self-attention and a feed-forward network. The table below lists the role of each component and its impact on deployment.

    Component Primary Role Deployment Impact
    Self-Attention (GQA/MLA) Computes correlations between tokens Determines KV Cache size, affecting VRAM during long contexts and high concurrency
    Feed-Forward Network (FFN, commonly SwiGLU) Non-linear transformation; widely considered the main location for storing factual knowledge Accounts for the majority of parameters, determines weight size
    Normalization (RMSNorm) Stabilizes numerical distributions across layers Very small parameter count; negligible impact on VRAM
    Positional Encoding (RoPE) Allows the model to distinguish token order Determines usable context length; requires training scheme support

    Self-Attention: What GQA and MLA Solve

    Self-attention computes weights between tokens using three linear transformations: Query, Key, and Value. Original Multi-Head Attention (MHA) keeps independent Keys and Values for each head, requiring a large amount of KV cache during inference. The longer the sequence and the higher the concurrency, the faster this memory grows.

    Two mainstream approaches are used today.

    • Grouped Query Attention (GQA): Multiple Query heads share a group of Key/Value heads. The KV cache shrinks proportionally to the sharing ratio. Excessive sharing can reduce model expressiveness, so there is a trade-off between quality and memory.
    • Multi-head Latent Attention (MLA): Key/Value are compressed into a low-dimensional latent vector. Only this vector is cached during inference and is then restored for computation. It provides further cache compression but adds computational and implementation complexity. Before deployment, you need to confirm whether your inference framework supports it.

    FFN, Normalization, and Positional Encoding

    Most mainstream models use a gated SwiGLU structure for the FFN. Gating introduces an additional weight matrix, so the intermediate dimension is typically reduced accordingly to control the total parameter count.

    Normalization layers have largely shifted from LayerNorm to RMSNorm for simpler computation. Pre-Norm placement makes training deeper networks more stable.

    Rotary Positional Embedding (RoPE) is the most common positional encoding approach. The context length a model has seen during pretraining is limited, so extending support to tens of thousands of tokens or more typically requires techniques like frequency interpolation and continued training on long-context data. Context capability depends on the training approach—it cannot be judged from the maximum length field in a config file. Short-context quality may also change after extrapolation, so real evaluation at your target length is essential.

    Understanding Parameter Numbers: Dense Models vs. MoE

    Estimating Parameters for Dense Models

    In a dense model, every input token passes through all parameters. The structure is simple, training is stable, and inference behavior is easy to predict.

    Under standard settings, the following approximate formula estimates the non-embedding parameter count:

    Parameters ≈ 12 × number of layers × hidden dimension²

    The formula assumes: decoder-only structure, multi-head attention, FFN intermediate dimension equal to 4× the hidden dimension, and it excludes token embeddings and the output layer. With GQA, SwiGLU, or different FFN widths, the result will differ. Therefore, use this only to estimate magnitude—it does not replace actual VRAM measurement.

    For example, with 32 layers and a hidden dimension of 4096, the formula gives roughly 6.4 billion parameters. With 80 layers and a hidden dimension of 8192, it gives approximately 64.4 billion. Note that these are non-embedding estimates; vendor figures like “7B” or “70B” use different counting methods that usually include embeddings and the output layer. Always compare numbers under the same counting convention.

    How MoE Achieves Large Capacity

    Mixture-of-Experts (MoE) models replace the single FFN in dense models with multiple expert FFNs. Each layer has a router that computes a score for each expert per token, selects the top-k experts, and weights the outputs by those scores.

    This structure produces two numbers that must be considered separately:

    • Total parameters: the sum of all weights in the model, determining how much storage and VRAM is required for weights.
    • Activated parameters: the weights actually used to process a single token, roughly determining compute per token.

    The gap between total and activated parameters is the source of MoE’s compute savings. Model capacity can be large while per-token computation remains modest.

    MoE also comes with costs, including:

    1. VRAM: all expert weights must reside in accessible memory (unless offloaded), so VRAM scales with total parameters, not activated parameters.
    2. Load balancing: if the router consistently assigns tokens to a small subset of experts, those experts become overloaded while others sit idle. Training typically adds auxiliary losses or bias terms to balance load.
    3. Capacity factor: each expert has a cap on tokens it can process per iteration: capacity = capacity factor × (tokens per batch / number of experts) × top-k. Tokens beyond the cap are dropped or re-routed, affecting output quality.
    4. Communication: when experts are distributed across multiple GPUs or nodes, tokens must be dispatched to the relevant experts and results collected per layer, requiring all-to-all communication. Network bandwidth can become a bottleneck.
    5. Batch effects: at small decoding batches, each token only touches a few experts, so the speed advantage is clear. As batch size grows, different tokens may access nearly all experts, reducing the actual speedup.

    Example calculation: Consider a hypothetical model with 32 layers, hidden dimension 4096, 64 experts per layer, each with a SwiGLU intermediate dimension of 2048, using Top-2 routing. Ignoring embeddings, shared experts, and router parameters:

    • Each expert: 3 × 4096 × 2048 ≈ 25.17M parameters
    • Total expert parameters: 64 × 25.17M × 32 layers ≈ 51.5B
    • Attention parameters: 4 × 4096² × 32 layers ≈ 2.15B
    • Total parameters ≈ 53.7B
    • Activated parameters: 2 × 25.17M × 32 layers + 2.15B ≈ 3.76B

    In this example, total parameters are roughly 14× the activated parameters. VRAM depends on the 53.7B total, while per-token compute is roughly driven by 3.76B activated parameters.

    Quantization Size and VRAM Estimation

    Weight Size

    Weight size ≈ number of parameters × bytes per parameter

    Bytes per parameter: 2 bytes for FP16/BF16, 1 byte for INT8, 0.5 byte for INT4. Using the 53.7B total parameter example:

    • FP16: ~107 GB
    • INT8: ~54 GB
    • INT4: ~27 GB

    These are theoretical values for weights only. Actual quantized files also contain scaling factors, zero points, and non-quantized layers (such as embeddings), so real files will be slightly larger. Always check the actual model file size.

    KV Cache Estimation

    KV Cache ≈ 2 × layers × KV heads × head dimension × sequence length × batch size × bytes per element

    Example: 32 layers, head dimension 128, sequence length 8192, batch size 1, FP16:

    • GQA with 8 KV heads: 2 × 32 × 8 × 128 × 8192 × 1 × 2 ≈ 1 GiB
    • MHA with 32 KV heads: same conditions ≈ 4 GiB

    KV cache grows linearly with batch size and sequence length. At high request concurrency, it can exceed the memory occupied by the weights themselves.

    Total VRAM

    Total VRAM ≈ weights + KV cache + runtime overhead

    Runtime overhead includes the inference framework, CUDA context, temporary tensors, and activations. Reserving a percentage for overhead is a useful starting point, but it is only an assumption—confirm by measuring peak memory on your target framework.

    Example: a dense model with an estimated 6.4B non-embedding parameters requires about 13 GB of FP16 weights (6.4B × 2 bytes). Adding 8K context KV cache with batch size 1 and reserving for runtime overhead, verify whether a single GPU is sufficient by measuring the actual peak VRAM.

    Dense vs. MoE Comparison

    Dimension Dense Model MoE Model
    Parameter Structure Every token passes through all parameters Each token passes through only top-k experts
    VRAM Footprint Roughly equal to total parameters Scaled by total parameters, typically much larger than activated parameters
    Compute per Token Nearly linear in parameter count Correlated with activated parameters
    Batch Scaling Stable behavior, easy to predict Larger batches increase expert coverage, reducing speedup
    Multi-GPU Communication Primarily tensor parallelism communication Additional all-to-all communication between experts
    Engineering Complexity Lower Requires attention to routing, load balancing, and capacity parameters
    Framework Support Generally mature Must verify inference framework support for the specific MoE structure

    Model Selection Checklist

    Go through the following items in order. Each item should have a clear number or conclusion.

    • Workload type: Is it online chat, batch offline processing, or code completion? What are the average input and output lengths?
    • Latency requirements: What are your targets for time-to-first-token and per-token latency? Are there concurrency peak requirements?
    • Context length: What is the maximum context you need? Calculate KV cache at your target length, not at the model’s stated maximum.
    • VRAM budget: Using the formulas in Section 4, calculate weights, KV cache, and runtime overhead. Can your single-GPU or multi-GPU setup fit the model?
    • Compute budget: Estimate compute per token using activated parameters. Combine with hardware throughput to estimate cost per million tokens.
    • Inference framework: Does your target framework support the architecture (e.g., MLA, MoE routing) and the quantization format you plan to use?
    • Quantization plan: Is the quality loss from INT8 or INT4 acceptable? Validate against your own datasets.
    • Compliance and licensing: Does the model license permit commercial use? Do you have data residency or regional requirements?
    • Real-world validation: Run your actual workload on target hardware, record peak VRAM, time-to-first-token, and throughput, and compare with estimates.

    If a candidate model is MoE, also confirm the expert parallelism strategy, inter-node network bandwidth, and whether expert load is balanced under your real workload.