advanced25 min studyLesson 588 in Engineering

Optimizer, RNG, and data-cursor recovery

Restore the hidden histories that determine the next update and distinguish a saved generator state from a repeated initial seed.

On this page

What you’ll understand

  • Calculate a momentum update with and without restored history.
  • Distinguish RNG seed, current generator state, and deterministic execution.
  • Define data progress by committed logical consumption instead of read-ahead.

A restart can load identical weights and still take a different next step. Momentum contains earlier gradients, the scheduler interprets counters, a scaler may suppress an overflowing update, and the next batch depends on consumed input and random choices. These are not optional details when the contract is faithful continuation. Restore their relationships at the chosen cut, then test what the resumed program actually does next.

Optimizer history is part of the numerical state

Momentum and adaptive optimizers carry quantities that cannot generally be inferred from current parameters. A zeroed moment buffer changes the next update even if the gradient and learning rate are identical. Step counters affect bias corrections and schedules; parameter-group identities affect which settings apply to which tensors. Restore optimizer state with the framework’s supported mapping rather than matching transient object addresses or assuming two same-shaped tensors are interchangeable. Also distinguish the checkpoint’s stored precision from the compute precision and any master-weight representation used for updates.

A scaler’s current scale, growth tracker, and overflow handling can affect the sequence of successful updates. Decide how scheduler advancement relates to skipped steps in the application loop. A checkpoint taken after an attempted update must record whether the optimizer actually changed parameters. The next learning-rate value alone is not always a full scheduler state: warmup, restarts, token counts, or phase transitions may require additional history. Version the training-loop convention so restored counters are interpreted in the same order.

vk+1=βvk+gk+1,θk+1=θk−ηvk+1v_{k+1}=\beta v_k+g_{k+1},\qquad \theta_{k+1}=\theta_k-\eta v_{k+1}
This stipulated unnormalized momentum-SGD variant uses dimensionless scalar theta and gradient for the example, 0≤beta<1, and positive learning rate eta. It is not Adam and excludes weight decay, dampening, Nesterov variants, scaling, and distributed normalization.↔ Scroll wide equations horizontally.

Restore random streams and committed input progress

An initial seed selects the start of a random stream; it does not identify the position reached after training has consumed many draws. Save each relevant generator’s current state or an explicitly reproducible logical counter mapping. Libraries and augmentation workers may use separate generators. Restoration order matters because model construction, warmup, or loader setup can consume random values before the first intended resumed operation. Restore at the point required by the application contract and keep test-only random draws from perturbing the production stream.

The data cursor should identify the next logical uncommitted contribution, not merely the furthest record fetched by a worker. Prefetch and decoding can run ahead, while retries or dropped batches can separate read position from successful updates. Preserve dataset identity, shuffle and sampler state, packing remainders, and any required pending accumulation. An explicit policy may replay prefetched but unconsumed records. External readers may need committed offsets or idempotency keys rather than a tensor snapshot alone. Verify sample or token identities after restart, not only a monotonically increasing batch counter.

inext=istart+ncommittedi_{\rm next}=i_{\rm start}+n_{\rm committed}
This simple ordered-stream cursor uses integer record counts, with no shuffle, filtering, packing, or duplication. It excludes merely prefetched records. Real samplers need richer state and explicit logical identity; the expression is not a universal rank-local offset formula.↔ Scroll wide equations horizontally.

Separate stream restoration from bitwise determinism

PyTorch 2.14 warns that reproducibility is not guaranteed across releases and platforms, even with equal seeds. Kernel algorithms, collective reduction order, floating-point rounding, and topology changes can introduce differences beyond random stream state. Define whether your oracle expects exact sample identities, numerically close next updates, or bitwise equality under a tightly fixed environment. Restoring RNG is necessary for some contracts but is not sufficient for all of them. Record the chosen deterministic settings and their compatibility instead of promising universal identical trajectories.

The modular instrument is a transparent state-position analogy, not a random generator. Reset, set both m=8 and a=3, predict residue one after three additions, then Step three times. Separately Reset, set both m=8 and a=1, predict residue three after three additions, then Step three times. Both the rule and position affect the next value. This short periodic sequence neither models a real RNG nor demonstrates its statistical quality. It helps distinguish restoring a current execution position from merely knowing that a process once started at zero.

Recover the next momentum update

Use the stated momentum rule with θ=1, stored v=0.2, β=0.9, η=0.1, and next gradient g=0.5. Compare faithful history restoration with incorrectly resetting v to zero.

  1. With the stored history, the next velocity is 0.9×0.2+0.5=0.68. The next parameter is 1−0.1×0.68=0.932.

  2. With a zeroed velocity, the next velocity is 0.5 and the parameter becomes 1−0.1×0.5=0.95. The same initial parameter and new gradient therefore do not establish the same update.

  3. The parameter difference is 0.95−0.932=0.018. A restore oracle that inspects only the pre-update parameter value misses this error; it needs the history and a next-update check under the specified rule.

The result

Optimizer histories change future computation. A deliberate reset may be a valid new experiment, but it is not faithful continuation of this state.

Explore the model

Interactive lab

Interactive lab · modular

Execution position is different from a starting seed

Reset, set both m=8 and a=3, predict residue one, then Step three times. Separately Reset, set both m=8 and a=1, predict residue three, then Step three times. This exact additive sequence is not a PRNG or RNG-quality test; it illustrates dependence on rule and position only.

Execution position is different from a starting seedAddition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Current readings: Residue r0: 0; Orbit period · m/gcd(m,a): 12; Distinct residues visited: 1 of 12. All parameters are adjustable with the labeled controls below.Repeated addition modulo 12: the current residue is 0, and the orbit period is 12.01234567891011+ 5mod 12An additive orbitn = 0rₙ = 0Period = 12Cycle starts at 0:0 → 5 → 10 → 3 →8 → 1 → 6 → 11 →4 → 9 → 2 → 7 → 0Exact residues · two additions per second
Additive orbitCurrent residue / next edge
Residue r0
0
Orbit period · m/gcd(m,a)
12
Distinct residues visited
1 of 12
t = 0 s

Addition modulo m starts at zero: rₙ = na mod m. Playback advances two additions per second. The orbit has period m/gcd(m,a), including period one for a = 0. This is not a cryptographic security test or a primality algorithm. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forPreserve current stream position and interpretation, then test actual next inputs and updates.

Check your understanding

A restart knows the original RNG seed but not how many or which generator draws were consumed. What can it conclude?

Try it yourself

An ordered input source has committed records 0 through 999 to completed updates, while workers have prefetched through record 1099. Under a replay-prefetch policy, what is the next logical record after recovery, and how many prefetched records are replayable?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Use committed consumption as the recovery boundary.

Compare with the solution

The next record is 1000. Records 1000 through 1099 are one hundred prefetched but uncommitted records that may be read again under this policy. Starting at 1100 would skip their contributions. Shuffling, packing, filtering, and external acknowledgments would require richer saved state and their own replay contract.

Take it with you

  • Restore optimizer, scheduler, scaler, and counter relationships together.
  • A seed is not the current generator state or a complete input cursor.
  • Test next sample identities and updates under an explicit reproducibility level.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.