Concepts / Memory Math for Model Training

Memory Math for Model Training

In full finetuning, the number of trainable parameters equals the total number of parameters in the model. Keep this in mind as the rest of the article reduces that count.

  • Programming

The Out-of-Memory Error Everyone Meets

There is a running joke among people who work with neural networks: you are not really doing AI until you have seen the error message 'RuntimeError: CUDA out of memory'. The joke points at a real experience. Running out of memory is a common way that people discover their plans did not account for the resources a model needs. Training and running a neural network both consume memory, and a model that does not fit in the memory available to it cannot be trained or served at all.

This article is about doing that accounting before the error appears. It follows one question through several techniques: if a model is too large to adjust completely on the hardware you own, what can you change instead? Each technique turns out to be a way of reducing the number of trainable parameters, or the memory cost that comes with them.

What do you think happens?

A model has 7 billion parameters and each weight is stored in a 16-bit format, which takes 2 bytes. How many GB do the weights alone need?

Reveal answer
Answer:

About 14 GB, from $7 \times 10^{9} \times 2 \text{ bytes} = 14 \times 10^{9} \text{ bytes}$.

The weights are the first piece of the memory bill. Parameters times bytes per parameter gives the storage for the weights. Training adds more pieces on top of this, as the next section shows.

Finetuning as Further Training

Definition

Finetuning is further training of a pre-trained model on a specific task or dataset. It starts from a model that has already been trained and adjusts it for a new task. It is not always strictly necessary, but when it is used, the adjustment is a training activity with training-side costs.

The obvious way to adjust a pre-trained model is to let every weight move during the adjustment. Early on, models were small enough that this was practical, and this approach came to be called full finetuning. As models grew, the obvious approach began to fail for ordinary people, because the hardware needed to hold and update every weight became out of reach.

Key point

In full finetuning, the number of trainable parameters equals the total number of parameters in the model. Keep this in mind as the rest of the article reduces that count.

Where the 56 GB Comes From

Full finetuning trains every parameter, and for a 7B model in a 16-bit format the total adds up to about 56 GB before activations are counted. That is more than most consumer GPUs provide. Memory cost is easiest to understand when you add up the pieces, and the first piece is the weights themselves.

Worked example

Storing the Weights of a 7B Model

A model has 7B parameters, stored in FP16, where each value takes 2 bytes. How much memory do the weights need?

  1. 1
    Count the parameters

    The model has $7 \times 10^{9}$ parameters, written 7B.

  2. 2
    Find the bytes per parameter

    In FP16 each value takes 2 bytes.

  3. 3
    Multiply

    $7 \times 10^{9} \times 2 = 14 \times 10^{9}$ bytes, which is 14 GB.

  4. 4
    Place the weights within the full bill

    The weights are only the first piece. Full finetuning also keeps other per-parameter data in memory, and the total reaches about 56 GB before activations.

Result

The weights alone take about 14 GB. The full finetuning total is about 56 GB before activations.

Weights7B x 2 bytes = 14 GBGradients andoptimizer statesremaining 42 GBTotal beforeactivationsabout 56 GBadds toadds to
What stacks up in GPU memory during full finetuning, and how do the pieces add to the roughly 56 GB figure before activations?

The diagram separates the weights, which are 14 GB by direct calculation, from the rest of the total. The remaining 42 GB is the portion that covers gradients and optimizer states; the source does not itemize that portion, and it points to dedicated training-memory resources for the arithmetic. The point for planning is that a full finetuning run carries far more than the weights, so a GPU that could hold the 14 GB of weights can still fail the run.

Partial Finetuning and Its Limits

The first workaround is partial finetuning. Instead of updating every parameter, you update only some of them and freeze the rest. A frozen parameter keeps its value throughout training. Picture a model with ten layers. If you freeze the first nine and train only the last one, the number of trainable parameters falls to about 10% of what full finetuning would need.

Layer 1frozenLayer 2frozenLayer 3frozenLayer 4frozenLayer 5frozenLayer 6frozenLayer 7frozenLayer 8frozenLayer 9frozenLayer 10trainable
Which layers are fixed and which one is free to change when only the last layer is trained?

Freezing layers lowers memory use, but it does not solve the core problem. Partial finetuning is parameter-inefficient: it still needs many trainable parameters before it approaches the quality of full finetuning. One reported study on BERT large found that roughly 25% of the parameters had to be updated to match full finetuning on the GLUE benchmark. Performance rose only as more parameters were opened up.

What Makes a Technique Parameter-Efficient

The natural question follows: how can you reach performance close to full finetuning while training far fewer parameters? Techniques that answer this question are called parameter-efficient, and they are grouped under PEFT.

Definition

A technique is parameter-efficient when it gets close to full finetuning's performance while using several orders of magnitude fewer trainable parameters. There is no official cutoff a method must cross to earn the label; this description is the general standard.

Adapter Modules

PEFT was introduced by Houlsby and colleagues in 2019. Their key move was to insert extra parameters into the model in carefully chosen places, and then train only those extra parameters. These extra pieces are called adapter modules. Their authors placed two adapter modules inside each transformer block of a BERT model.

Transformer blockOriginal weightsfrozenAdapter module AtrainableAdapter module Btrainablecontainscontainscontains
Where do the small trainable adapter modules sit relative to the frozen base weights, and which parts of the block receive updates?

The original weights of the block are left alone, and the adapters are the only pieces that receive updates. During finetuning, the original parameters stay unchanged, so the number of trainable parameters is simply the number of parameters inside the adapters. On the GLUE benchmark, this arrangement came within 0.4% of full finetuning while using only 3% of the trainable parameters.

Following One Input Through an Adapter

Placement explains where the adapters sit. Now trace what happens to a single input as it moves through the network. The input passes through the frozen base computation, then through the adapter, and then continues onward. Only the adapter's values change during training, while the base values remain the same for every example.

InputFrozen basecomputationunchanged in trainingAdapterupdated in trainingOnward computationforwardforwardforward
As one input moves forward, which computations are frozen and which one changes during training?

Notice what this path implies. The adapter is an extra computation on every forward pass, so the model does more work than it did before adapters were added. The source identifies this as the main drawback: the additional layers add computational steps, which increases inference latency for the finetuned model. Adapters therefore trade lower training memory for slower inference, unless the trade is handled another way.

In the real world

Consider a team that finetunes an adapter-based model on modest hardware. Training fits in memory because only the adapter parameters are updated. When the team later serves the model to users, each request still passes through the adapter steps, so response time is higher than it would be for the same base model without adapters. The memory win during training does not remove the cost paid at inference time.

Why Frozen Parameters Skip Gradients

Trainability connects directly to the cost of an update. A parameter that is not trainable does not need to be updated, so its gradient does not need to be computed. Gradients are only needed for the parameters that will change, so marking parameters as not trainable removes work for them.

Numerical Formats: BFloat16 and Integers

Memory use depends on how numbers are stored, and the source names two numerical formats. The first is BFloat16, a floating-point format that Google introduced as the secret to high performance on Cloud TPUs. The second is the integer format, which the source says is also called a fixed point format.

The source names these formats but does not describe how many bits either one uses, and it points to outside resources for the detailed arithmetic. This article therefore does not compare their storage sizes. What you can carry forward is the general rule used in the worked example: the bytes needed per parameter set the weight memory, and the format determines those bytes.

Training Memory Versus Inference Memory

Memory calculation is crucial for both model training and model inference, and the two are treated as separate calculations. Inference memory concerns running a model. Training memory concerns training it. Before estimating anything, a practitioner needs to know which activity they are planning for, because the two are different problems.

The source does not walk through either arithmetic. For inference it cites Carol Chen's Transformer Inference Arithmetic (kipply's blog, March 2022). For training it cites EleutherAI's Transformer Math 101 (Anthony et al., April 2023). This article does not present a memory formula, because the source only points to those resources. What the source does establish is the structure of the problem: training and inference are separate calculations, each with its own reference material.

Finetuning is training work, so it belongs on the training side of this split. The source notes that engineers sometimes finetune even when they know it is not needed, because they want to learn how to do it. It also observes that a leader may find it hard to tell whether finetuning is needed or only wanted. That distinction matters for memory planning, because finetuning carries training-side memory costs whether or not it was needed.

Mistakes in Memory Planning

  • Common mistake

    Counting only the weights when estimating a full finetuning run

    What it looks like

    Seeing that 7B parameters at 2 bytes each take 14 GB and concluding that a 16 GB GPU is enough.

    Why it fails

    Full finetuning carries more than the weights. The source puts the total for this 7B, 16-bit case at about 56 GB before activations.

    Do this instead

    Use the full-finetuning total as the planning figure, and treat the weight-only number as the first step of the estimate.

  • Common mistake

    Assuming freezing layers solves the memory problem

    What it looks like

    Freezing nine of ten layers and expecting the run to need only a tenth of the memory of full finetuning in every respect.

    Why it fails

    Freezing lowers memory use, but partial finetuning is parameter-inefficient and still needs many trainable parameters to approach full-finetuning quality.

    Do this instead

    Judge partial finetuning by its quality and its trainable-parameter count together, not by memory alone.

  • Common mistake

    Treating adapters as free at inference time

    What it looks like

    Choosing adapters to save training memory and then deploying the model without considering response time.

    Why it fails

    The adapter adds computational steps to every forward pass, which increases inference latency.

    Do this instead

    Account for the extra inference cost separately from the training savings.

  • Common mistake

    Mixing up training memory and inference memory

    What it looks like

    Using the same estimate to size a training run and a serving deployment.

    Why it fails

    The source treats them as separate calculations with different reference material.

    Do this instead

    Decide which activity you are planning for first, then use the matching method.

Comparing the Three Approaches

The three approaches differ mainly in how many parameters they train and what that choice costs. The table gathers the points made so far. It summarizes the source's claims and is not a complete survey of every method.

ApproachWhich parameters trainTrainable parameter countMain cost noted in the source
Full finetuningEvery parameter in the modelEqual to the total parameter countLarge memory need, about 56 GB for a 7B model in 16-bit before activations
Partial finetuningSome layers; the rest are frozenStill many, to approach full-finetuning qualityParameter-inefficient, though memory is lower
Adapter-based finetuningOnly the inserted adapter modulesSmall; about 3% in the GLUE result reportedExtra computation adds inference latency

Trainable parameters and trade-offs for three finetuning approaches, based on the source's claims.

PEFT also brings benefits beyond memory. The source says PEFT enables finetuning on more affordable hardware, and that PEFT methods are generally sample-efficient. Full finetuning may need tens of thousands to millions of examples before quality improves noticeably, while some PEFT methods can deliver strong results with only a few thousand examples.

Practice: Estimating a Larger Model

MEDIUM

A model has 13B parameters and its weights are stored in a 16-bit format at 2 bytes per value. Estimate the memory needed for the weights alone. Then explain in one sentence why a full finetuning run would need more than this figure.

Hints
  • Multiply the number of parameters by the bytes per parameter, then convert bytes to GB.
  • Compare your answer to the 7B example, where weights alone took about 14 GB and the full total was about 56 GB before activations.
  • The remaining memory in full finetuning covers things beyond the weights, such as gradients and optimizer states.

Summary of Memory Planning

  1. 1
    Full finetuning trains every parameter; for a 7B model in 16-bit it reaches about 56 GB before activations, and the weights alone are about 14 GB.
  2. 2
    Partial finetuning freezes layers to lower memory, but it is parameter-inefficient and still needs many trainable parameters.
  3. 3
    Adapter modules are small trainable pieces inserted into frozen blocks; they reach near full-finetuning performance with about 3% of the trainable parameters on GLUE, but they add computation at inference time.
  4. 4
    Frozen parameters need no gradient, which is why marking parameters as not trainable reduces the training work.
  5. 5
    Training memory and inference memory are separate calculations, and finetuning is further training that carries training-side costs.

At a glance

  • Full finetuning trains every parameter, and a 7B model in 16-bit reaches about 56 GB before activations, with the weights alone taking about 14 GB.
  • Partial finetuning lowers memory by freezing layers but remains parameter-inefficient, needing many trainable parameters to approach full-finetuning quality.
  • Adapter modules are small trainable pieces inserted into frozen transformer blocks, achieving near full-finetuning performance with about 3% of the trainable parameters on GLUE, at the cost of extra inference latency.
  • Training and inference memory are separate calculations, and a frozen parameter needs no gradient computed.

Related concepts

More concepts starting with M