Memory-Efficient Training and Inference for Large Language Models: Principles and Practice

    This article explains the principles and practices of running and training large language models under limited GPU memory. It covers where memory is actually consumed (weights, activations, gradients, optimizer states, and KV cache), three foundational optimization categories (low-bit quantization, parameter-efficient fine-tuning, and activation checkpointing with efficient attention), the resource characteristics of group-relative policy optimization for reinforcement learning, training-generation co-design, correct gradient accumulation, and a reproducible implementation and evaluation workflow. The core takeaway: low-memory optimization is constraint management, not a single switch.

    1. Clarify the Goal First: Low-Memory Optimization Is Not a Single Technique

    Before running large models on limited hardware, you need to answer three questions: Are you directly deploying an existing model, or fine-tuning it on business data? Are you optimizing output format and domain expression, or improving performance on tasks with clear success criteria? How much precision change and response latency can you tolerate?

    These questions map to different technical paths:

    • Inference deployment: primarily concerns model weights, attention cache, and runtime workspace.
    • Supervised fine-tuning: in addition to weights, you must account for activations, gradients, and optimizer states.
    • Reinforcement learning training: further introduces candidate answer generation, reward computation, policy updates, and possibly reference policy overhead.

    Therefore, “a GPU can run this model” does not mean it can train a model of the same size, let alone handle arbitrary context lengths and concurrent requests. A rigorous optimization plan must specify the model scale, compute precision, training method, sequence length, batch size, and hardware conditions together.

    2. Where Does Memory Actually Go?

    2.1 Model Weights Are Only the Starting Point

    Let the model parameter count be (P) and the storage bits per parameter be (b). The theoretical weight storage is approximately:

    [
    M_{\text{weight}} = P \times b / 8
    ]

    For example, a model with 8 billion parameters stored at 16 bits per parameter requires about 16 billion bytes for weights alone; at 4-bit storage, the theoretical weight size is about 4 billion bytes.

    This is only an ideal lower bound. Real deployments also include quantization scale factors, unquantized layers, temporary dequantization buffers, runtime management overhead, and memory fragmentation. You cannot treat the theoretical size as the minimum memory requirement.

    2.2 Training Carries Substantial Extra State

    During training, you typically also need to store:

    • intermediate activations for backpropagation;
    • gradients for trainable parameters;
    • historical state maintained by the optimizer;
    • high-precision weight copies used by certain mixed-precision schemes;
    • temporary workspace required by operator computations.

    Whether each of these components exists, and how much it occupies, depends on the specific implementation. Especially in long-sequence training, activations can become the dominant bottleneck even when the number of trainable parameters is small.

    2.3 Inference Cache Grows Dynamically with Requests

    Autoregressive generation usually needs to cache the keys and values from attention computation, so that each new token does not require reprocessing the entire history.

    Cache size is jointly determined by the number of model layers, the number of key-value heads, head dimension, cache precision, context length, and the number of concurrent sequences. A model that starts up with short inputs does not guarantee stable operation with long documents, multi-turn conversations, or batched requests.

    Capacity planning should be based on peak usage under the target workload, not just the static footprint after model loading.

    3. Three Foundational Optimizations: Less Storage, Fewer Trainable Parameters, Less Intermediate State

    3.1 Low-Bit Quantization: Reducing Weight Storage Cost

    Quantization represents weights or parts of the computation data at lower bit widths, significantly compressing storage requirements. But quantization is not simply truncating values—it must handle the numerical distributions of different tensors, channels, or groups.

    In practice, pay attention to:

    • whether layers sensitive to outliers need to retain higher precision;
    • whether the target hardware has efficient low-bit compute paths;
    • whether dequantization introduces significant extra overhead;
    • whether quality degrades on long-context and complex reasoning tasks.

    A quantized model is smaller, but not necessarily faster. If the underlying compute path does not match, the saved memory may come with extra data conversion time.

    3.2 Parameter-Efficient Fine-Tuning: Training Only a Small Set of Delta Parameters

    Parameter-efficient fine-tuning typically freezes the base model and trains only a small set of added parameters. For example, weight increments can be represented with low-rank matrices:

    [
    W’ = W + BA
    ]

    where (W) is the frozen weight, and (A) and (B) are the trainable matrices whose inner dimension is much smaller than the original weight dimension.

    This significantly reduces the number of parameters that require gradients and optimizer states. Combined with low-bit base weights, it is often better suited to single-GPU or memory-constrained environments.

    However, note that freezing the base weights does not eliminate backpropagation through the base network. Training the delta parameters still depends on forward results and gradient propagation, so activation and compute costs remain.

    3.3 Activation Checkpointing and Operator Optimization: Trading Recompute for Space

    Activation checkpointing does not store all intermediate results; instead, it recomputes some of them during backpropagation. It usually lowers peak memory at the cost of additional computation.

    Efficient attention implementations reduce memory overhead through tiling, avoiding materialization of intermediate matrices, and optimizing data access. Operator fusion further reduces temporary tensors and device memory reads/writes.

    These techniques can be combined, but their gains are not directly additive. Once one optimization shifts the bottleneck, the marginal effect of the others changes accordingly.

    4. Why Group-Relative Policy Optimization Is Relevant to Resource Efficiency

    For math problem solving, code generation, and structured tasks, you can generate multiple candidate answers for the same prompt and update the model based on reward signals.

    The basic idea of group-relative policy optimization is to construct relative advantages from reward differences within the same group of candidate answers, rather than relying entirely on a separate value estimation network.

    Suppose a prompt produces (G) candidate answers with rewards (r_1,\ldots,r_G). A common advantage estimate takes the form:

    [
    A_i=\frac{r_i-\operatorname{mean}(r)}
    {\operatorname{std}(r)+\epsilon}
    ]

    where (\epsilon) prevents the denominator from becoming too small. Different implementations may adopt different normalization scopes and stabilization methods.

    Removing a separate value network reduces some model state and compute cost, but this does not mean the entire RL process becomes lightweight. Candidate generation often remains the dominant time cost; increasing the number of candidates per group also brings more generated tokens, cache usage, and scoring cost.

    In addition, the following issues must be handled:

    • Rewards lacking discrimination: if all answers in a group receive the same score, the relative advantages are typically near zero, providing insufficient learning signal.
    • Reward hacking: the model may learn to exploit the scoring rules without genuinely improving task capability.
    • Excessively large updates: overly fast policy changes can degrade generation quality.
    • Length bias: different reward aggregation and normalization methods can influence the answer length the model prefers.

    Therefore, RL optimization should validate reward design, training stability, and performance on an independent test set—not just whether training reward is rising.

    5. Training–Generation Co-Design: Avoid Paying for Resources Twice

    RL pipelines typically alternate between “generating candidate answers” and “performing gradient updates.” If the generation module and the training module each keep full weights and caches, significant duplicate memory usage can occur.

    General optimization directions to consider:

    1. Unify memory lifecycle management
      Promptly release caches and temporary tensors that are no longer needed at each stage, so generation peaks and training peaks do not unnecessarily overlap.

    2. Synchronize updated weights efficiently
      The generation side must use the policy version required by the training pipeline. Slow synchronization drags down throughput, while poor version management can alter the algorithm’s behavior.

    3. Group generation requests by length
      Combining requests of similar length helps reduce padding waste, but you must balance it against waiting time and scheduling overhead.

    4. Tune generation batch size and training micro-batch size separately
      The two stages have different memory compositions and should not mechanically share the same batch settings.

    It must be emphasized: weight sharing is not automatically achieved by putting two modules in the same process. Differences in weight layout, quantization format, and device memory management can all lead to extra copies or conversion costs.

    6. Correctness of Gradient Accumulation Matters More Than “It Runs”

    Gradient accumulation reduces the memory needed for a single forward and backward pass by running multiple micro-batches before performing one parameter update.

    A common mistake is averaging the loss separately for each micro-batch and then taking an unweighted average of those averages. When micro-batches contain different numbers of valid tokens, this is not equivalent to averaging over all valid tokens in the effective batch.

    If the (j)-th micro-batch has a total valid-token loss of (S_j) over (N_j) valid tokens, the token-level overall average loss should be:

    [
    L=\frac{\sum_j S_j}{\sum_j N_j}
    ]

    rather than the arithmetic mean of the individual (S_j/N_j) values.

    In implementation, make the loss normalization consistent with the objective function, and correctly handle padding positions, masked labels, and count aggregation across devices. If the training objective itself uses sample-level weighting, preserve that semantics instead of switching everything to token-level averaging.

    A recommended check: with a small model and fixed data, compare the gradients produced by “one large batch” versus “multiple gradient accumulation steps,” and verify that the difference falls within acceptable numerical error.

    7. A Reproducible Implementation and Evaluation Workflow

    Step 1: Establish a Baseline Without Complex Optimizations

    Record the model parameter count, precision, sequence length, effective batch size, training objective, hardware conditions, and data processing method.

    Also measure peak memory, per-step latency, effective token throughput, and validation set quality. Without a clear baseline, subsequent optimizations are hard to attribute.

    Step 2: Enable Optimizations One at a Time

    You can evaluate low-bit loading, parameter-efficient fine-tuning, activation checkpointing, efficient attention, and batch scheduling in sequence.

    For each added optimization, record both its benefit and its cost. If you change multiple configurations at once, you cannot tell which technique drove the improvement even if performance rises.

    Step 3: Cover Real-World Workloads

    The test set should at least include short inputs, long inputs, short outputs, long outputs, and mixed-length cases. RL tasks should also cover different candidate counts and reward distributions.

    Beyond average performance, pay attention to peak memory, tail latency, and stability under abnormal requests.

    Step 4: Treat Quality as a Hard Constraint

    Compare task accuracy, output format compliance, long-text performance, and training stability. Reward metrics used in reinforcement learning should not be the only acceptance criterion—add evaluations independent of the reward rules.

    Any claim about “how much memory was saved” or “how much throughput improved” should come with complete test conditions. The same optimization can produce drastically different results across model architectures, context lengths, and hardware environments.

    8. Conclusion: The Core of Low-Memory Optimization Is Constraint Management

    Low-memory LLM practice is not about finding a single switch that solves everything; it is about building a verifiable balance among model quality, memory capacity, compute cost, and engineering complexity.

    Quantization mainly compresses storage, parameter-efficient fine-tuning reduces training state, activation checkpointing reshapes the space–compute trade-off, and training–inference co-design reduces duplicate usage and stage-switching overhead. Group-relative policy optimization can change the resource structure of reinforcement learning, but generation cost, reward quality, and update stability still require careful handling.

    A reliable technical path always follows the same order: define the task first, then break down memory usage, optimize item by item, and finally confirm the gains through correctness verification and reproducible experiments.