Batch Size and Gradient Accumulation
Batch size affects both stability and speed, and it is limited by the hardware you have.
Try it: Loop Tracer
How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.
How it works
- Initialise the accumulator before the loop.
- Each iteration, the loop variable takes the next value from the list.
- An if inside the loop decides whether to update the accumulator.
- After the last item the loop ends and the accumulator holds the answer.
Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.
Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.
Loading the simulation…
Is There One Correct Learning Rate?
What do you think happens?
Is there one learning rate that works well for any finetuning job?
Reveal answer
No. There is no universal optimal learning rate.
The right step length depends on the model, the data, and where training currently stands, so no single value wins everywhere.
It is easy to assume that somewhere there is a correct learning rate, a number that works for any finetuning job. Tutorials often show one specific value, and it feels natural that a best setting should exist, the way a recipe has a best oven temperature. The source explains why this assumption trips learners up: the learning rate that works depends on the model, the data, and the stage of training. Instead of searching for a magic number, you find a workable one by experimenting within a typical range and reading the loss curve.
Finetuning starts from a base model that has already been trained, then adjusts it for a specific use case. Along the way you make many choices that are not learned from the data. These settings are called hyperparameters. The exact list depends on the base model and the finetuning method, and the documentation for your model or framework is always the authoritative reference. This article focuses on four hyperparameters that come up again and again and strongly influence how efficiently finetuning works: the learning rate, the batch size (together with gradient accumulation), the number of epochs, and the prompt model weight.
Learning Rate as Step Length
The learning rate sets how fast the model's parameters change with each learning step. A helpful picture is learning as a walk toward a goal, where the learning rate is the length of each step. Short steps are safe but slow: if the steps are too small, reaching the goal takes too long. Long steps cover ground quickly, but they can carry you past the goal. If the steps are too big, the model can overshoot and, as a result, may never converge.
The learning rate is a step length. Too long and the model overshoots the goal; too short and it takes far too long to get there.
Reading the Loss Curve
Experiments are much easier to interpret when you watch the loss curve, because its shape tells you how the step length is behaving. The source gives two diagnostic patterns. If the loss curve fluctuates a lot, the learning rate is probably too big, because each update overshoots and the loss bounces around. If the loss curve is stable but takes a long time to decrease, the learning rate is probably too small, because each update moves the model only a little. The guidance that follows is to increase the learning rate as high as you can while the loss curve remains stable.
What do you think happens?
If you raise the learning rate and the loss starts bouncing around from one check to the next, what does that suggest?
Reveal answer
The learning rate is probably too big, so each update overshoots.
Fluctuation in the loss curve is the source's signal that steps are too long. Lower the rate until the curve is stable again.
Searching the Typical Range
Because the right step length depends on the situation, the source recommends experimenting across the typical range, which is roughly 1e-7 to 1e-3, and seeing which value works best for your run. The range is wide, so the search needs a starting point. The source offers one: take the learning rate used at the end of the pre-training phase and multiply it by a constant between 0.1 and 1. That gives you a sensible neighborhood to search instead of a blind guess.
The intermediate values in the diagram are illustrative points spaced across the range. The source does not name a specific winner, so each run's loss curve decides which candidate to keep. Try a value, read the curve, then move toward a larger rate if the curve is stable and too slow, or back off if it fluctuates.
Changing the Learning Rate During Training
The learning rate does not have to stay fixed during training. You can use larger learning rates at the beginning and smaller learning rates near the end. An algorithm that determines how the learning rate should change throughout training is called a learning rate schedule. A schedule is therefore a rule that maps training progress to a learning rate, and it lets you act on the diagnostic patterns from the loss curve as training moves forward.
Batch Size, Stability, and Cost
The batch size determines how many examples the model learns from in each step before it updates its weights. Batch size affects both stability and speed, and it is limited by the hardware you have. A batch that is too small, such as fewer than eight examples, can lead to unstable training. A larger batch helps aggregate the signals from different examples, which produces more stable and reliable updates.
Bigger is not free. In general, a larger batch lets the model get through the training examples faster, but it also needs more memory to run. Because memory is finite, batch size is capped by the hardware you use. This is the cost versus efficiency trade-off: more expensive compute allows faster finetuning. The source notes that compute remains a bottleneck for finetuning, since models are often so large and memory so constrained that only small batch sizes fit. Small batches can produce unstable weight updates, and that tension is what gradient accumulation is designed to address.
Gradient Accumulation Step by Step
Gradient accumulation changes when the weights get updated, not how many examples each batch holds. Instead of updating the model weights after every batch, you accumulate gradients across several batches and update the weights once enough reliable gradients have been collected. The weight update is therefore based on information gathered from several batches, which helps when each individual batch is too small to give a stable update on its own.
Read the diagram as a flow with a pause in the middle. Each batch contributes its gradients to a running total, and the weights change only at the end of that stretch. The batches still flow through the model one at a time, so the memory limit that forced small batches still applies, but the update you finally make reflects several batches rather than one.
Accumulating over four small batches
Memory only lets you process 2 examples at a time, and each 2-example batch alone gives a noisy update. You want the weight update to reflect more examples than one batch holds. What does gradient accumulation do with 4 batches?
- 1Process the first batch
The model handles 2 examples and produces gradients. These are added to the running total. The weights do not change yet.
- 2Process the next three batches
Each batch adds its gradients to the same running total. Memory use stays the same because still only 2 examples are in the model at once.
- 3Apply one weight update
After the fourth batch, the accumulated gradients from all 8 examples are used for a single update. The update reflects several batches rather than one.
The weights changed once, using information gathered from 8 examples, even though memory only ever held 2 at a time.
Choosing the Number of Epochs
An epoch is one pass over the training data, so the number of epochs determines how many times each training example is trained on. Small datasets often need more epochs than large ones. For a dataset with millions of examples, one or two epochs might be sufficient. A dataset with thousands of examples might still improve after four to ten epochs.
The gap between training loss and validation loss gives you hints about the right number of epochs. The comparison below summarizes the two patterns the source describes.
| What the losses are doing | What it suggests | What to try |
|---|---|---|
| Both training loss and validation loss keep decreasing steadily | The model can benefit from more epochs and more data | Consider more epochs |
| Training loss still decreases while validation loss increases | The model is overfitting to the training data | Try lowering the number of epochs |
Reading training and validation loss to set the number of epochs
The Prompt Model Weight
In instruction finetuning, each training example consists of a prompt and a response, and both can contribute to the model's loss during training. At inference time, however, users usually supply the prompt, and the model only needs to generate the response. Because of this, response tokens should contribute more to the loss than prompt tokens. The prompt model weight is the setting that controls how much prompts count toward the loss compared with responses.
The two extremes are instructive. At 100 percent, prompts contribute to the loss as much as responses, so the model learns equally from both. At 0 percent, the model learns only from responses. The default is typically 10 percent, which means the model learns a little from prompts but mostly from responses.
The prompt model weight sets how much prompts count toward the loss. Its default of about 10 percent keeps the focus on responses, which is what the model must produce at inference time.
Mistakes Beginners Make
Common mistake Assuming one published learning rate works for any finetuning job
Why it failsThe workable step length depends on the model, the data, and where training stands, so no single value wins everywhere.
Do this insteadExperiment across the typical range, starting near the pre-training learning rate multiplied by a constant between 0.1 and 1, and read the loss curve for each run.
Common mistake Judging the learning rate by a single number instead of the curve
Why it failsFluctuation signals steps that are too long, while a stable but slow decrease signals steps that are too short. Neither shows up in one value.
Do this insteadWatch the shape of the loss curve over time and raise the learning rate as high as you can while it stays stable.
Common mistake Believing gradient accumulation lets each batch hold more examples
Why it failsGradient accumulation changes when the weights get updated, not how many examples each batch holds. Batches still pass through the model one at a time.
Do this insteadThink of accumulation as delaying the weight update across several batches, while each batch stays within the memory limit.
Common mistake Choosing the number of epochs from training loss alone
Why it failsTraining loss can keep falling while validation loss rises, which means the model is overfitting.
Do this insteadCompare training and validation loss, and lower the number of epochs if validation loss increases.
Common mistake Setting the prompt model weight high without a reason
Why it failsUsers usually supply the prompt at inference time, so the model mainly needs to learn to generate responses. Giving prompts equal weight spreads learning across both.
Do this insteadKeep the default of about 10 percent unless you have a specific reason to change it.
Practicing the Diagnosis
Three finetuning runs use learning rates from the typical range. Run A's loss curve is stable but takes a very long time to decrease. Run B's loss curve bounces up and down between checks. Run C's loss curve is stable and steadily improving. For each run, decide whether the learning rate is too small, too large, or workable, and say what you would change next.
Hints
- Fluctuation points to steps that are too long, which is the overshoot case.
- A stable curve that barely moves points to steps that are too short.
- If a run is stable and improving, you can keep the rate, or try raising it while the curve stays stable.
A finetuning run on a dataset of a few thousand examples shows training loss still falling while validation loss has started rising after the fifth epoch. Should you add epochs, keep the same count, or lower it? Explain your reasoning using the gap between the two losses.
Hints
- Rising validation loss while training loss falls is the source's sign of overfitting.
- The source describes this pattern as a reason to try lowering the number of epochs.
Key Takeaways
- There is no universal optimal learning rate; find a workable one by experimenting within the typical range of roughly 1e-7 to 1e-3 and reading the loss curve.
- A fluctuating loss suggests the learning rate is too big, while a stable but slow decrease suggests it is too small.
- Batch size is capped by memory and small batches can be unstable; gradient accumulation delays the weight update across several batches without enlarging each batch.
- Use the gap between training and validation loss to set the number of epochs, and lower epochs when validation loss rises.
- The prompt model weight controls how much prompts count toward the loss; its default of about 10 percent keeps the focus on responses.