AI Wiki中文/EN

Epochs and steps: audit the training loop

Epoch、步数与训练循环

Execute an exact accumulated-gradient loop and distinguish delivered examples, loader tails, discarded gradients and optimizer updates.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Reading a batch is not always an optimizer step

A log says “two epochs, batch size four.” That is not enough to know how many parameter updates occurred. The dataset may have a short final batch, gradients may be accumulated over several batches, and a partial accumulation window may be flushed or discarded at an epoch boundary.

For a finite dataset, an epoch commonly means one planned traversal under the chosen sampler. A microbatch is one group evaluated together. An optimizer step is one application of the parameter-update rule. These counters can differ even in a tiny, single-process training loop.

The fixed PyTorch 2.8 data-loading documentation distinguishes sampler order, batching and drop_last. Deep Learning, Section 8.3.1, Algorithm 8.1 separates gradient estimation from applying an update. Our complete loop below keeps all three counters and performs actual rational-valued updates.

Declare the tail policy before calculating steps

For N examples and batch size B, a sequential finite loader yields M microbatches per epoch:

M={⌈N/B⌉d=0⌊N/B⌋d=1.M=\begin{cases}\lceil N/B\rceil&d=0\\ \lfloor N/B\rfloor&d=1.\end{cases}

Here d=0 keeps the loader tail and d=1 drops it. This assumes one traversal of N indices, a single process and ordinary fixed-size batching. It is not a universal formula for iterable streams, custom samplers, distributed shards or repeated sampling. The documentation warns that an iterable loader’s length can be only an estimate and that multiple workers can each have an incomplete tail.

If K microbatches are accumulated per update and each epoch ends with an explicit flush-or-discard decision, E epochs give:

S={E⌈M/K⌉f=1E⌊M/K⌋f=0.S=\begin{cases}E\lceil M/K\rceil&f=1\\ E\lfloor M/K\rfloor&f=0.\end{cases}

Here f=1 flushes the partial window and f=0 discards it. This is not generally ceil(E M/K), which would correspond to a different cross-epoch accumulation policy. With N=10, B=4, K=2 and E=2, keeping loader tails and flushing produces six microbatches but four optimizer steps. Their example counts are 8,2,8,2. There is no single effective batch size 8 for every update.

Weight losses by examples when batch sizes differ

Let microbatch j have bⱼ examples and mean gradient gⱼ, computed at the same parameters. To match the mean gradient over their union:

gwindow=∑jbjgj∑jbj.g_{\mathrm{window}}=\frac{\sum_j b_j g_j}{\sum_j b_j}.

An unweighted average of the microbatch means matches this only when all sizes are equal or special cancellations happen. For target values 0 through 9 split into sizes 4,4,2, the batch target means are 3/2,11/2 and 17/2. Their unweighted average is 31/6, whereas the overall target mean is 9/2.

For the per-example half squared loss(θ−i)²/2, the gradient is θ−i. A correct accumulation window therefore sums all example gradients at fixed θ and divides by the actual number used. This makes a partial window’s update meaningful without pretending that missing examples were processed.

Trace delivered examples and completed updates

The complete Python 3.12 program uses synthetic targets equal to their indices and starts a scalar predictor at θ=0. It traverses indices sequentially, uses rate 1/10 and records the IDs contributing to every optimizer step. “Fetched” here means delivered in a microbatch to this model loop, not physical disk reads or prefetched records.

from fractions import Fraction as F


def train_epochs(n, batch_size, accumulation, epochs, drop_last=False, flush=True):
    if type(n) is not int or not 0<=n<=64 or type(epochs) is not int or not 0<=epochs<=5:
        raise ValueError('bounded dataset size and epoch count required')
    if type(batch_size) is not int or not 1<=batch_size<=64 or type(accumulation) is not int or not 1<=accumulation<=16:
        raise ValueError('positive bounded batch and accumulation sizes required')
    if type(drop_last) is not bool or type(flush) is not bool:raise ValueError('Boolean policies required')
    theta=F(0);records=[];fetched=used=discarded=microbatches=0
    for epoch in range(1,epochs+1):
        pending=[];gradient_sum=F(0);count=0
        for start in range(0,n,batch_size):
            ids=list(range(start,min(start+batch_size,n)))
            if drop_last and len(ids)<batch_size:continue
            fetched+=len(ids);microbatches+=1;count+=1
            pending.extend(ids);gradient_sum+=sum((theta-i for i in ids),F(0))
            if count==accumulation:
                theta-=F(1,10)*gradient_sum/len(pending)
                records.append(dict(epoch=epoch,ids=pending.copy(),theta=theta));used+=len(pending)
                pending=[];gradient_sum=F(0);count=0
        if pending:
            if flush:
                theta-=F(1,10)*gradient_sum/len(pending)
                records.append(dict(epoch=epoch,ids=pending.copy(),theta=theta));used+=len(pending)
            else:discarded+=len(pending)
    return dict(theta=theta,microbatches=microbatches,fetched=fetched,used=used,
                discarded_gradients=discarded,steps=len(records),records=records)


if __name__=='__main__':
    for drop_last,flush in [(False,True),(True,True),(False,False)]:
        result=train_epochs(10,4,2,2,drop_last,flush)
        print('drop_last:',drop_last,'flush:',flush,'microbatches/steps/fetched/used/discarded:',
              *[result[k] for k in ('microbatches','steps','fetched','used','discarded_gradients')])
        print('examples per update:',[len(r['ids']) for r in result['records']],
              'final theta:',result['theta'],f'({float(result["theta"]):.6f})')
    batches=[list(range(0,4)),list(range(4,8)),list(range(8,10))]
    naive=sum(F(sum(b),len(b)) for b in batches)/len(batches)
    weighted=F(sum(sum(b) for b in batches),sum(map(len,batches)))
    print('equal average of batch target means:',naive,'example-weighted target mean:',weighted)

Actual output:

drop_last: False flush: True microbatches/steps/fetched/used/discarded: 6 4 20 20 0
examples per update: [8, 2, 8, 2] final theta: 42173/20000 (2.108650)
drop_last: True flush: True microbatches/steps/fetched/used/discarded: 4 2 16 16 0
examples per update: [8, 8] final theta: 133/200 (0.665000)
drop_last: False flush: False microbatches/steps/fetched/used/discarded: 6 2 20 16 4
examples per update: [8, 8] final theta: 133/200 (0.665000)
equal average of batch target means: 31/6 example-weighted target mean: 9/2

Keeping and flushing all tails delivers and uses 20 examples over two epochs. Dropping the loader tail delivers only 16. Keeping the loader tail but discarding the partial gradient window delivers 20 yet uses only 16 in updates. Both omissions lose indices 8 and 9 in this fixed-order example, but they occur at different stages and have different counters.

The first full window uses targets 0 through 7, mean 7/2, so θ moves from 0 to 7/20. The next two-example window has target mean 17/2 and moves θ to 233/200. The second epoch continues from that parameter; it does not reinitialize it. Tests check these literal updates, per-update IDs, several count combinations, empty input and a batch larger than the dataset.

The loop costs O(E N) per-example arithmetic and stores O(E N) IDs in its audit trace. A production loop can use counters and bounded logs instead. This program has no accelerator, asynchronous workers or mixed-precision step skipping, so it does not claim to implement those framework behaviors.

The counters are part of the experiment

An epoch with drop_last need not use every example. Sequential order repeatedly discards the same tail here; shuffling can change which examples are omitted and also changes the sequence of updates. A custom sampler may repeat some examples and never visit others, so “one epoch” is not automatically one visit per unique record.

Gradient accumulation matches a larger batch only if the objective and model allow the equivalence. Batch-dependent normalization, cross-example losses, state changes or different random operations can invalidate it. Even when gradients match, changing the number of optimizer steps changes momentum, adaptive state and schedules that advance per update.

A reproducible schedule must say whether its unit is epochs, microbatches, examples, tokens or optimizer steps. For variable-length sequences, example counts alone can hide large differences in processed tokens. Resuming mid-window also requires knowing which gradients and sample position were pending, beyond a displayed epoch number.

Where did the missing examples go?

  1. For N=10, B=4, K=2 and two epochs, keeping and flushing tails gives how many microbatches and updates?

Answer 1: Six microbatches and four updates, using 8,2,8,2 examples.

  1. What is θ after the first two updates in that case?

Answer 2: First 7/20, then 233/200.

  1. What differs between dropping the loader tail and discarding an incomplete accumulation window here?

Answer 3: The first delivers 16 examples; the second delivers 20 but discards gradients from 4. Both use 16 for updates in this fixed-order example.

  1. Why should batch means of sizes 4,4,2 not normally be averaged with equal weights?

Answer 4: That overweights the short batch. Weighting by example count recovers the union’s mean at fixed parameters.

A progress bar is not an update audit

The library documentation provides concrete loader policies and warns about length estimates; the textbook provides the gradient-estimate/update distinction. The counter formulas, synthetic loop, ID trace and exact updates here are original, with no library source copied or PyTorch runtime required.

Read minibatches for sampling assumptions and gradient clipping for another operation whose position relative to accumulation matters. Record what the loop did, rather than inferring it from a single “step” label.

Make a prediction, then check

How many updates for N10,B4,K2,E2 when tails are kept and flushed each epoch?

Choose one answer

Learning objectives

  • Count microbatches and optimizer updates under explicit tail policies.
  • Weight accumulated means by actual example counts.

Prerequisites & connections

Explore related knowledge →

References

  1. torch.utils.data — PyTorch 2.8
    PyTorch contributors
  2. Deep Learning — Chapter 8: Optimization for Training Deep Models
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Shared recurrent gradients, transient powers, stable clipping, exact minibatch distributions and accumulated-update traces are checked against literal references, analytic identities and finite differences. All four examples use the standard library.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.