Complete a training loop
Align data, patterns, losses, gradients, parameter updates and statistical calibres to check training codes using a small, measurable PyTorch example.
Learning objectives and first steps4 objectives • 3 first fixes
Try to do it after reading
- Describe the status of each step of the training cycle
- Distinguishing train / eval from whether to record gradients
- Accurate losses of different sizes batch
- Achieved by a fixed-value baseline check, with an indication of what needs to be preserved to resume training
Suggested first
- Reverse transmission and gradient drop
- Logits and cross entropy
- Number shapes and parameters registered
loss is dropping. Is the code right
The training program is more than that backward() and step()I don't know. It also sets out how the sample will form batch, which state changes during training, what will be closed during validation and what the denominator of the entire loss is. Data leaks or statistical errors can also produce beautiful curves, so small models can be used to check closed rings and then add GPU, mixed accuracy and distribution.
This chapter reads: PyTorch eager The mode is dominated and the interface is checked on 2.15 official documents. Examples are only CPU, two composite samples and a linear classifier; No regular rules, category weights, padding or label neglect. It examines the updated values and does not provide proof of generalization effect.
What exactly does every step have to change
| Stage | Main work | The state that needs attention |
|---|---|---|
| Take batch | Access input and target, check shape / dtype / device | Data sequencing, pre-processing, samplingrs |
| Clear gradient | Do not allow the previous Parameter Gradient to mix with the current update | grad for parameters |
| Forward | Calculate logits using current parameters | Activate; Operating statistics on certain layers |
| loss | Comparison of projections and targets as agreed | Valid samples, weighting and unimonization denominators |
| Reverse | Pass the loss gradient to parameters | grad added |
| Update | Change parameters by gradient | Parameters, Optimizer Status |
The gradient position in this order may be expressed in equivalent terms, but it must be ensured that this update accumulates exactly the desired gradient. When the gradient is deliberately accumulated, it cannot be removed after each microbatch.
A step-by-step update
Take X=[[1,0],[0,1]]Label y=[0,1]I don't know. Linear layer weight shape as [输出维度,输入维度], the full weight and bias are initially zero. Two initials. logits, both [0,0]On average, cross entropy is log 2≈0.69314718。
Indexed in categories, not entitled to weight mean CE Lower weight gradient is [[-0.25,0.25],[0.25,-0.25]], the bias gradient is [0,0]I don't know. Updated with SGD, learning ratio 0.1:
W=[[0.025,−0.025],[−0.025,0.025]]
The correct category score for each sample is higher than for the other. 0.05, and the new average loss should read log(1+exp(−0.05))≈0.6684596480I don't know. Linear separators can start here from scratch; The network of multiple hidden units cannot also be initialized on this basis.
import torchfrom torch import nnfrom torch.utils.data import DataLoader, TensorDataset
X = torch.tensor([[1.0, 0.0], [0.0, 1.0]], dtype=torch.float64)y = torch.tensor([0, 1], dtype=torch.long)loader = DataLoader(TensorDataset(X, y), batch_size=2, shuffle=False)model = nn.Linear(2, 2, dtype=torch.float64)nn.init.zeros_(model.weight)nn.init.zeros_(model.bias)optimizer = torch.optim.SGD(model.parameters(), lr=0.1)criterion = nn.CrossEntropyLoss(reduction="mean")
model.train()loss_sum, sample_count = 0.0, 0for features, target in loader: optimizer.zero_grad(set_to_none=True) logits = model(features) loss = criterion(logits, target) loss.backward() optimizer.step() loss_sum += loss.detach().item() * len(target) sample_count += len(target)
model.eval()with torch.no_grad(): updated_loss = criterion(model(X), y).item()print(loss_sum / sample_count) # 更新前:约 0.69314718print(updated_loss) # 更新后:约 0.66845965The second calculation here still uses the same two samples, so it is called “updated numeric recovery”, and cannot be independently validated for the set results. The actual project is divided into time, user or appropriate independent units before generalization is checked on the validation set.PyTorch Quickstart Official access to the training and testing cycle is provided.
To really connect training to independent verification
The top two samples are just arithmetic tests. The real cycle requires fixed training, validation and final testing prior to entering training and ensures that pre-processing only coincides with permitted data. Each epoch is updated to the training model and then the mode is changed to run through the independent validation set without updating the parameters. Thresholds and models are selected in accordance with the agreed certification agreement and the final test set is retained until the selection is completed.
Training loss is usually calculated separately from the parameters before batch is updated and the parameters continue to change in the round; Validation of loss is usually calculated using a set of parameters fixed at the end of the same round. Thus, the difference between training loss and validation of loss cannot be fully explained as a generalized gap, and the Dropout, data enhancement and standardization models can also affect both. When comparisons are needed, the same fixed model, the same forward model and a clear range of data are used to reconstruct the curve to avoid adding more meaning to it.
shape running, not monitoring
Category example logits as[B,C], the target category is indexed as[B]And it's plastic. The return should identify each output in relation to the element by element. Some broadcasts do not make mistakes, but produce completely different goals. Set regression prediction shape as[2,1], values 1 and 3; The target is shape [2]and the values are also 1 and 3. It is expected that a sample-by-samp error of 0 would result in a two-by-two error matrix of 2 x 2, with an average square error of 2.
# 标准Python:显式展开错误广播的结果,已执行。prediction, target = [1.,3.], [1.,3.]paired_mse = sum((p-t)**2 for p,t in zip(prediction,target))/2broadcast_mse = sum((p-t)**2 for p in prediction for t in target)/4assert paired_mse == 0.0 and broadcast_mse == 2.0Therefore, checking the number of shape, dtype and valid labels at each mission entrance is considered correct, rather than relying on the final loss as a mark. The sample ID should also be sampled together to confirm that pre-treatment, disruption and configuring do not place the characteristics in a misallocation of the label; Similarly, the two levels of shape may still come from different objects.
The entire training and validation process will be checked before the mini-species are prepared as expected. If a very small sample cannot be drawn, then the label, input scale, gradient, whether the update is implemented and the loss and output interface are matched in turn. Don't start by increasing the depth of the network to hide the basic protocol problem. Subsequent mixing accuracy, distribution and interruption recovery are treated in separate chapters, avoiding the simultaneous introduction of too many variables.
train / eval and autograd are two things
model.train()、model.eval() It changes behaviour in modules Dropout, BatchNorm, etctorch.no_grad() controls whether a gradient is recorded. Write only eval, but it is still possible to create a calculation chart; Write only no_grad, but keep train, and some running statistics may change. Validation usually requires the alignment of both states.
To continue training after validation, please return train. Freezing parameters, closing gradients and changing training models are not the same operations and cannot be replaced with a switch to replace all semantics.
Don't even the average
Two batch sizes of 3 and 1, by sample loss as [1,2,3] and [4]I don't know. Two batch mean with 2 and 4, respectively, with a direct average of 3; The correct average for the whole round is (3×2+1×4)/4=2.5。
Multiply the code above batch size It is only applicable to cases of declared non-restrictive and non-negative labels. (a) The effective token for the sequence is an average for each sequence and the weighted average for the category is a different target;CrossEntropyLoss Document The corresponding reduction rule is clarified.
TensorFlow, which step is it
In Keras3 using the TensorFlow backend,tf.GradientTape Corresponds to gradient recording and calculation, optimizers apply_gradients Updates the corresponding parameters. The following is a correspondence that omits models, data and optimizer constructions:
with tf.GradientTape() as tape: logits = model(features, training=True) loss = loss_fn(target, logits) # 如 from_logits=True 的稀疏交叉熵gradients = tape.gradient(loss, model.trainable_variables)optimizer.apply_gradients(zip(gradients, model.trainable_variables))Don't catch it. TF1 It's... Session / placeholder Explain the main line. You don't want to. Keras Old Saved Interface as 2 Keras 3 Agreement. Detailed realization reference Keras Official Custom Training Cycle。
Inspection understanding and continuation of practice
Two consecutive forwards and separate backward, with no known gradient in the middle. What happens?
The parameter grad defaults to add two contributions. When deliberately doing microbatch cumulative, it needs to be properly regularized and updated at the specified time. It's always going back and forth. Once again, the same map that was retransmitted and released. backward , which is usually reported directly wrong and cannot be confused with the gradient.
Can you just save the weight of the model and run from the break?
Usually not enough. We also need to consider optimizers, learning rate schedules, AMP scaler , steps, configuration, data version and random state, including, where necessary, the progress of the sampler. The successful loading of documents does not constitute a resumption of the same training process.
Does the same seed ensure that different devices and versions are given the same results in place?
There's no guarantee. Arithmetic realization, floating point sequence and operating environment will influence the outcome and should be documented as random and defined as reasonable numerical tolerance.
Why is it possible to return losses to non-zero, as projected [2,1] and targeted [2] values?
Radio may form a 2x2 comparison rather than a sample-by-sample comparison. The average error in this case is 2 and the correct pair is 0.
Is the training round loss calculated by the same set of parameters at the end of the cycle?
Usually not, it mixes the results of each batch with the different parameters before updating. When a fixed parameter comparison is required, it should be extra.
Can train always be maintained without calling step on validation?
The status cannot be considered fixed on this basis. There are still training behaviours such as Dropout and BatchNorm to validate the need for visible selection of the right model.
The next step is to complete the integration and independent validation of very small data sets and then to separate training in blending accuracy, data flow linear performance analysis and distribution. Each time a mechanism is added, the original baseline is retained. Source core for 2026-10-29; The above values have been independently recovered, but the code is not implemented in the target PyTorch/ TensorFlow environment, much less in the case of GPU performance. I'll see you at the border PyTorch Reproducibility。
Sources and reconciliations
Definitions, methods and interfaces are available.
- PyTorch Learn the Basics — Quickstart
- PyTorch CrossEntropyLoss
- Keras — Writing a training loop from scratch in TensorFlow
- PyTorch Reproducibility
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.