Efficient training and revitalising experiments
From the effective sample denominator, gradient accumulation and mixing accuracy, to the point of inspection where the same experiment can continue.
Learning objectives and first steps4 objectives • 3 first fixes
Try to do it after reading
- Merge correctly with long batch gradients
- Distinguishing AMP from the gradient to crop duties
- Estimated training bottlenecks and visible composition
- Define Checkpoint and Restore Receiving and Inspection
Suggested first
- Full training cycle
- Gradient and Parameter
- Basic concept of floating points
The training is fast. We have to make sure it's still the same target
Different lengths of multi-source sequences can result in significant waste and vary the number of valid tokens per batch. For the purpose of modeling, engineering is commonly used for mixed accuracy, accumulation gradient, distribution and check point weighting; However, these modifications may change the denominator or the frequency of updates of the target quietly. Increased throughput and changed learning behaviour do not directly warrant acceleration of completion of the equivalent.
All examples of gradients, durations and memory in this chapter are composite figures. 2026-10-29 Check the PyTorch curriculum display 2.15; The CUDA snippet is not implemented and does not provide speed or GPU gains. Standard Python is used to verify the statistical equivalent before the hardware performance is measured separately.
No longer. microbatch to be merged by valid unit
A gradient of 1, 3, 5 for three samples to a metric parameter. The full batch average gradient is 3. In order to save memory, we'll take care of two, one, two. microbatch mean 2 and 5, respectively; A simple average of the two would yield 3.5, which would have deviated from the original sample average target.
The correct approach would be to accumulate the gradients of the individual batches and divide them by total sample numbers; Alternatively, the average loss per instalment was multiplied by the sample number in that instalment as a proportion of the total. For sequences, choose whether to average the effective token or to average each sequence by series first. Both can be meaningful, but not the same goal. The last batch of insufficient size should also be included in the same rule.
# 标准 Python,已执行。import mathmicro = [[1.,3.],[5.]]global_mean = sum(sum(v) for v in micro)/sum(len(v) for v in micro)wrong = sum(sum(v)/len(v) for v in micro)/len(micro)assert global_mean == 3.0 and wrong == 3.5grad = [3.,4.]norm = math.sqrt(sum(v*v for v in grad))clipped = [v*min(1.,2./norm) for v in grad]assert all(abs(a-b)<1e-12 for a,b in zip(clipped,[1.2,1.6]))Combining accuracy is not the same as turning all values into half accuracy
Autocast Select Precision by Calculator; The gradient scale is used to mitigate the spillovers of some low-precision gradients, which have different responsibilities. float16 and bfloat16 have different index ranges, and the latter should not be assumed to be directly applicable because it is stable on a particular model. The state of the optimizer, the main parameters and the partial attribution may also still use higher precision.
If the loss is multiplied by 1024, the gradient obtained is also increased by 1024 times; The scale must be restored before updating. The gradient crop should be for unscalable gradients, otherwise the same threshold corresponds to another constraint. (b) The vector [3,4] is reduced to 2 by [1.2,1.6]; Crop to change updates, not simply display scaling.
# PyTorch 2.15官方接口形式;CUDA条件示意,未执行。scaler = torch.amp.GradScaler("cuda")optimizer.zero_grad(set_to_none=True)with torch.autocast(device_type="cuda", dtype=torch.float16): loss = criterion(model(features), target)scaler.scale(loss).backward()scaler.unscale_(optimizer)torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=2.0)scaler.step(optimizer)scaler.update()This paragraph omits models and data constructions and describes only the order. If there are more than one cumulative microbatch, the border should be fully updated to be reunified unscale, tailoring and step, without advance updates of the scalding status in each small batch. When NaN appears, the first level of input, loss and first level is not limited, then the accuracy is judged, and all anomalies cannot be presented to scaler for cover.
The distribution is first the synchronization protocol
DDP usually replicates the model in each process and synchronizes the gradient; It doesn't define us as the data cut and the global loss caliber. If the number of valid samples is the same for each rank, the average gradient of rank can be averaged in the global sample; If there are two rank samples and one sample each, the direct average mean will get another 3.5. The correct weighting needs to be constructed by valid global count and the actual attribution of the distributed interface is checked.
Do not extrapolate global achievement from the voucher card log in Docca. The epoch of repeated sampling, final batch, drums by sequence length, gradient accumulated synchronous boundary, random feed and Sampler will influence the outcome. Simulation of averages on-board alone cannot be counted as having completed multiple processes or multiple-card validation.
Checkpoints should indicate “where to proceed”
Saves a model weight that restores part of the forecast function, but does not necessarily continue the optimization process. The dynamics of Adam, the Learning Rate Scheduler, AMP scaler, global update steps, random status and data sequence are experimental. Characteristic dictionaries, standardization statistics, code versions and data versions also determine what exactly these weights apply to input.
The information can be verified by saving it to a temporary file and replacing the official document with the atomic after success; Remote storage of atomic properties requires a different view of the platform. Do not counter-sequentize unselected trainees. (b) Restoring testing takes a number of steps under the same environment, fixed follow-on batch, and predefined tolerance; Different versions of equipment, algorithms or libraries do not guarantee consistency.
We'll test the bottlenecks first, then we'll pick up the acceleration
The visualization is composed of parameters, gradients, optimiser status, activations and temporary workspaces, and the full training costs cannot be estimated by two bytes of parameters alone. If primarily long sequence activation, length drums or recalculations may be considered; (b) Optimize the flow of data if the main input waits; It may be more appropriate to compile or quantify each step if it is taken by small calculus and schedule costs.
Recording of preheat, compilation, time-consuming, peak-level memory and effective token vomiting at each step of the steady state, while maintaining a baseline for the same sample and target. The GPU timer is required to process an asynchronous execution and cannot simply use CPU time when sending a call to calculate the time spent. This chapter does not give the percentage of acceleration that is not actually measured.
Self-measurement and interpretation
Two samples, two and one. Average gradients two and five. What is the global gradient?
(2x2+1x5)/3=3; The direct average of two means will get the wrong 3.5.
Is each sequence equivalent to each token equivalent price?
Prices are usually different for lengths, with long sequences assuming a higher weight on average at token. Objectives must be stated in advance.
What's wrong with cutting to two as soon as the gradient is scaled?
The threshold is applied to a magnified gradient and the post-restoration constraint is changed. Usually unscale first and then crop as agreed.
You save the weight and the number of steps, and Adam will be able to carry on completely?
The state of the optimiser and other related states are also required. The same number of steps does not mean that the momentum and the learning rate are the same as the data order.
Two GPUs, so you promise to swallow twice as much?
No guarantee. Communications, data entry, uneven load and batch changes limit returns and must be measured and maintained statistically.
When the reboot is close to loss, does it prove the recovery is completely correct?
Parameters, optimists, random state and subsequent steps will also be examined; Closeness to individual metrics may mask differences in status.
The next step is to select a mechanism to perform controlled experiments, first to prove that the target and the recovery are correct and then to report on performance. The above AMP, the check points and the DDP official curriculum support the respective interfaces; Standard Python arithmetic has been implemented, and CUDA, multi-process and recovery training has not been measured.
Sources and reconciliations
Definitions, methods and interfaces are available.
- PyTorch — Automatic Mixed Precision recipe
- PyTorch — Saving And Loading A General Checkpoint
- PyTorch — Getting Started with Distributed Data Parallel
Figures and calculations are reorganized according to this chapter. Mathematical measurements, framework operations and real business effects are described separately in the body of the text.