Fine-tuning on a budget: LoRA, gradient accumulation, number formats and shipping the result
What a small adapter really saves, how to accumulate gradients without changing the objective, why BF16 and FP16 fail differently, and how to release a checkpoint like production software.
Consolidates and expands four notes first published in Issue 002 on November 7, 2026. See the archive record.
Most organizations that adapt a language model do not have a training cluster. They have one server, or a few rented accelerators for a week, and a deadline. The techniques that make that possible are well known: low-rank adapters, gradient accumulation, reduced-precision arithmetic. Each one is also easy to misread, and the misreadings tend to surface late, as a model that trained “fine” but behaves differently, or a deployment that is far larger than the tiny adapter file suggested.
This guide follows a fine-tuning project from budget to release. It counts what LoRA actually removes, shows how gradient accumulation can quietly change the training objective, explains why two 16-bit formats fail in different ways, and ends with a release procedure for the finished weights.
LoRA: count the update, then count everything else
Choose the deployment before reading the file size
LoRA represents a weight update as the product of two thin matrices. For a frozen matrix W of shape d × k, the update is BA, where B is d × r and A is r × k [1]. Only A and B train.
Before celebrating a small adapter file, decide how it will be served. A compatible linear LoRA update can be merged into the base weights for inference, as the paper describes [1]. A merged model is a full-size model: the adapter is small, the deployment is not. Alternatively, a service can keep one shared base in memory and attach adapters per task. That saves storage across many tasks, but runtime overhead, batching across adapters and how many adapters stay resident depend on the serving implementation. The paper’s merge argument does not mean every multi-adapter system runs at zero cost.
Quantized bases add one more decision: in which precision are the base and update combined? A merged or requantized artifact is a new model and needs its own quality check.
The parameter arithmetic
A rank-r update has r × (d + k) trainable parameters instead of d × k. For a hypothetical 4,096 × 4,096 matrix at rank 16:
| Quantity | Parameters | Two-byte storage |
|---|---|---|
| Original matrix | 16,777,216 | 32 MiB |
| Adapter pair (A and B) | 131,072 | 0.25 MiB |
The adapter has 1/128 of the matrix’s parameters. That ratio belongs to this shape and rank, not to a whole model.
Scale it up: 32 hypothetical layers, two targeted matrices each, gives 64 adapter pairs with 8,388,608 trainable parameters, about 16 MiB at two bytes. The matrices they adapt occupy 2 GiB, and the rest of the model sits outside this partial count entirely.
The training memory the ratio leaves out
Freezing a weight removes its gradient and its optimizer state. It does not remove the weight from the forward pass, and it does not remove the activations needed to compute the adapter’s gradients. The frozen base still has to be resident.
For illustration, two float32 optimizer-moment arrays for those 8,388,608 adapter parameters add 64 MiB. That excludes gradients, any master copy of weights, activations and workspace. The LoRA paper discusses reduced optimizer memory and reports measured ratios for its own experiments [1]; the 128-to-1 parameter ratio above is not a prediction of 128 times less GPU memory.
Keep the base revision with the adapter
An adapter without the exact base model revision, configuration and tokenizer is not a reproducible model. Store them together. For a multi-task service, record which base copies are shared, which adapters are resident and which merged artifacts also exist. Those choices decide how much of the storage saving survives in production.
Gradient accumulation: the denominator matters
When the batch you want does not fit in memory, gradient accumulation runs several smaller microbatches, sums their gradients and steps the optimizer once. Done correctly, the result matches a larger batch. Done carelessly, it changes what is being optimized.
The equal-size case
Suppose four data-parallel workers each process microbatches of two equally weighted examples and accumulate eight microbatches per optimizer step. The nominal effective batch is 4 × 2 × 8 = 64 examples. If every microbatch loss is a mean over equal-sized microbatches, dividing each by eight before the backward pass yields the local mean gradient. Ordinary data-parallel averaging across the four workers then gives the 64-example mean.
PyTorch’s mixed-precision examples describe this accounting and warn that gradient scaling must stay consistent across the accumulation window [2]. The DDP design note describes averaging gradients across processes [3]. Custom communication hooks or loss reductions change those semantics, so inspect the real configuration.
The unequal-token trap
Language-model losses are usually averaged over non-padding tokens, and microbatches rarely contain the same number of them. Take one microbatch with 100 valid tokens and mean loss 1, and another with 900 valid tokens and mean loss 3.
Averaging the two means gives 2. The true token mean is:
(100 × 1 + 900 × 3) / 1,000 = 2.8
The naive recipe gives the short microbatch half the weight when its tokens deserve a tenth: five times its proper share, and nine times its proper weight relative to the long microbatch. The fix is to scale each microbatch’s summed token loss by the total valid-token count for the whole window. Across W workers with ordinary averaging, scale each local summed loss by W divided by the global valid-token count, so the average comes out as the global mean.
The last window of the epoch
If an epoch ends after three microbatches of an intended eight, dividing their losses by eight shrinks that update. Decide explicitly whether to drop the partial window, divide by its real size, or carry it into the next epoch. Count optimizer steps separately from microbatch steps, because learning-rate schedules, gradient clipping and checkpoint intervals should follow optimizer steps. With mixed-precision gradient scaling, PyTorch warns against unscaling before the window completes [2].
Verify rather than assume
Matching the average gradient formula does not guarantee identical training. Batch-dependent layers, nondeterministic kernels, floating-point reduction order and a different optimizer cadence all leave traces. Accumulation also does not make training faster: repeated small passes add overhead. A cheap check is to compute one full-batch gradient on a small controlled model and compare it with the accumulated version, then repeat with variable lengths and a partial final window.
Number formats: range and resolution are different failures
Where the rounding steps fall
BF16 and FP16 both use 16 bits but divide them differently. BF16 keeps eight exponent bits, giving it a range comparable to FP32, and seven fraction bits [4]. FP16 has fewer exponent bits and ten fraction bits [5].
For values between 1 and 2, a format with p fraction bits has spacing 2^−p:
| Format | Fraction bits | Spacing near 1 | 1.001 rounds to | Absolute error |
|---|---|---|---|---|
| BF16 | 7 | 0.0078125 | 1 | 0.001 |
| FP16 | 10 | 0.0009765625 | 1.0009765625 | 0.0000234 |
BF16 avoids overflow where FP16 would fail, but it cannot represent small changes near 1 that FP16 can. Avoiding overflow does not recover discarded fraction bits, and finer spacing does not prevent overflow.
Small updates can vanish
Add 0.001 to 1 a hundred times, rounding to BF16 after each addition. Every step rounds back to 1, so the stored value never moves. Add the hundred increments first and round once, and 1.1 becomes 1.1015625. The difference is entirely where rounding happens.
Real kernels often accumulate in a wider format, so this construction is not how every BF16 matrix multiply behaves. It is why mixed-precision training keeps master weights and accumulations in higher precision, and why “we trained in BF16” is not a complete description of a run.
Debugging a numerical change
PyTorch’s numerical-accuracy notes explain that floating-point operations are not associative and that mathematically identical computations need not be bitwise identical across platforms or releases [6]. When results change, record input and output dtypes, accumulation precision, reduction shapes and the backend actually selected, then compare intermediate values around the divergence. Use both absolute and relative error; each is misleading on its own at some magnitudes. And check downstream task behavior, because small tensor differences do not map to a fixed bound on answer quality.
Shipping the weights: treat a checkpoint as a release
Training ends with files. Production starts with a release procedure.
Stage, validate, activate
Download the new checkpoint into a versioned staging location beside the working release. Check the manifest and required files there. Run a smoke test that loads the complete set in the intended runtime and produces a bounded response. Only then switch the active pointer, and keep the previous release available for rollback. A rollback that requires re-downloading the old weights is a much slower recovery than switching to a copy already on disk.
Budget the disk and the transfer
Suppose a release contains 40 billion parameters at two bytes each: 80 decimal GB of raw weights. Keeping old and new sets side by side needs 160 GB; keeping one transfer archive as well brings the peak to 240 GB, before temporary files.
At a fully used 1 Gbit/s link, moving 80 GB takes at least 640 seconds, about 10 minutes 40 seconds. At 10 Gbit/s the floor is 64 seconds. Protocol overhead, shared links, source throttling and disk speed add to both, and loading into accelerator memory and initializing the runtime come after. Plan maintenance windows on the realistic number, not the link’s headline rate.
Record what makes the files runnable
Weights alone do not define a model. Record the exact revision, configuration, tokenizer, special-token mapping, shard index and every expected shard, plus the license. A branch name such as “main” can move; a content hash detects whether a file matches an expected value, but it only authenticates anything if that expected value came through a trusted channel.
| Field | What to record |
|---|---|
| Path | Exact relative path for each required file and shard |
| Size | Expected byte count from the release manifest |
| Digest | Expected content hash from a trusted source |
| Revision | Source revision shared by the whole file set |
| Validation | Whether the staged file matched size and digest |
Review the loader, not just the tensors
Python’s pickle documentation warns plainly that unpickling malicious data can execute arbitrary code [7]. A familiar model name or file extension is not a loading policy. Safetensors stores tensors without executable content and supports selective loading [8], which removes one class of risk. It does not authenticate the publisher, validate behavior or make accompanying custom code safe. Review code-loading settings separately.
A worked budget for one accelerator
Pull the pieces together for a hypothetical project: adapting a 7-billion-parameter model with rank-16 adapters on two projections per layer across 32 layers, on a single accelerator.
| Memory term | Illustrative size | Notes |
|---|---|---|
| Frozen base weights at 16-bit | 14 GB | Must be resident for the forward pass |
| Adapter parameters | 16 MiB | From the calculation above |
| Adapter gradients | 16 MiB | Same size as the adapter at two bytes |
| Optimizer moments (two float32 arrays) | 64 MiB | Assumed optimizer layout |
| Activations | Measure | Grows with sequence length × microbatch size |
| Framework workspace | Measure | Kernel and allocator dependent |
The adapter-related terms total under 100 MiB. The base weights dominate, and activations are the term that decides whether a given sequence length and microbatch fit. That is exactly the term gradient accumulation exists to control: if a microbatch of eight sequences does not fit, four microbatches of two may, with the effective batch preserved through correct loss normalization.
Two common ways to shrink the remaining terms each carry their own checks. Activation checkpointing recomputes activations during the backward pass instead of storing them, trading memory for extra computation time. Loading the frozen base in a quantized format reduces the largest term, but the update is then trained against a different base representation, and the merged or served result needs its own quality evaluation.
Choosing rank and targets
There is no universal rank. Higher rank gives the update more capacity and costs proportionally more adapter parameters; targeting more projection matrices does the same. The practical approach is empirical and cheap: start with a small rank on a modest set of targets, evaluate on a held-out set that represents the real task, and increase only if the evaluation shows the adapter is the limiting factor rather than data quality or quantity. Record rank, targets, learning rate and data revision with every run so results can be compared.
Rent or run in-house?
Small fine-tuning projects are often short. A week on one accelerator is 168 hours. Under illustrative assumptions of 1 kW average draw for the node, a facility PUE of 1.3 and electricity at $0.08 per kWh, the energy for that week costs about $17. For a team that already owns suitable hardware in a facility with spare power and cooling, the marginal cost of a run is mostly people’s time. For a team that does not, renting is usually simpler than adding a high-power server to an office or a closet whose circuits and cooling were never sized for one. The decision often turns less on the price of compute than on whether the local electrical and thermal capacity exists at all.
A one-page plan for a small fine-tuning project
- Decide merged versus shared-base serving before training.
- Budget training memory as frozen base + activations + adapter gradients + optimizer state, then measure peak usage.
- Normalize losses by valid tokens across the whole accumulation window, and decide how to handle the final partial window.
- Name the precision of storage, computation and accumulation separately.
- Release through staging, validation, activation and retained rollback, with a manifest and a safe loader.
On the infrastructure side, small projects often succeed or fail on unglamorous items: whether the server has enough local disk for two releases, whether the link can move a checkpoint inside the maintenance window, and whether the rack can run one more accelerator at full power for a week. Those belong in the plan from the first day.
Sources and limitations
- LoRA, version 2, §4.1 (update-matrix shapes; merging with no additional inference latency), §4.2 (optimizer-state memory savings and the batching limitation of merged weights).
- PyTorch AMP examples, version 2.15, “Gradient accumulation”.
- PyTorch DDP design note, “Backward Pass”: mean gradient reduction. The note describes an older internal design; verify current wrappers.
- Google Cloud: BFloat16: sign, exponent and fraction allocation.
- Intel BF16 technical note: FP16 and BF16 bit allocation.
- PyTorch numerical accuracy, version 2.15: non-associativity and cross-platform limits.
- Python pickle documentation: security warning on untrusted data.
- Safetensors documentation: tensor storage and partial loading.
Matrix shapes, loss values, rounding examples, transfer rates and disk copies are original illustrative calculations. No training run, hardware test or security audit was performed. This guide consolidates and expands four shorter notes first published on November 7, 2026, whose addresses now redirect here.
Continue exploring
- Retrieval-augmented generation in production: scores, index memory, token budgets and failure analysis
- How to read an AI benchmark: sample sizes, paired comparisons, latency tails and hidden workload mixes
- Where the memory goes when you serve a large language model