PyTorch: Where the gradient goes, what the model keeps

Checks the calculation chart, gradient add-up, parameter registration and training status, starting with leaf lengths and shared parameters.

System Chapter . StepCollate in 2 Graphics6 self-measurement3 First-hand sources
Start Body
Learning objectives and first steps4 objectives 2 first repairs

Try to do it after reading

  • Distinguishing length values, calculating graphs from parameter gradients
  • Hand-counted shared parameters and different results from detach
  • Check Parameter, buffer and training modules
  • Interpretation of breakcharts, in situ modification and restoration of borders

Suggested first

  • Chain law
  • Python object and stretch shape

The training curve remains intact. Check if the gradient reaches the parameters

When the multi-source feature is integrated into a neural network, the forward output of a number does not mean that the new branch is involved in training. A common occurrence is to convert the intermediate load to Python and to recreate it; Or a new training matrix was created without giving it to the optimist. Both procedures may function properly and losses may be slowed down by other branches. When checking, check the numeric stream, the lead stream and the parameter ownership separately, and not just the final curve.

This chapter describes the mechanism in eager, using individual metric parameters, and does not involve GPU, multi-card or compile. The autograd and Quickstart curricula, which are checked by 2026-10-29, show PyTorch 2.15, and the leaf plaque page still displays 2.14; The underlying semantics of both are used here, and there is no claim that these versions are available on this aircraft. All figures are synthetic teaching calculations.

Value, diagram, grad is not the same thing

Thrust first saves values and shape, dtype, device. Settings requires_grad=True After that, eligible calculations can also establish a guidance relationship. (b) The weight of the leaf is usually created directly by the user and requires a gradient; The results from microcalculations are usually non-leaf. Inverse calculations can pass through non-leaf, but it's .grad Default not to save, cannot assert that this path is not part of the guide by reading None. It does need to be observed retain_grad(), while considering additional storage.

Parameter .grad It is a built-up slot written in reverse, not the parameters themselves, and not the full state of the optimizer. (b) The middle map established in the front is usually released backwards; A new image will be created from a new front. Thus, the “graduation” has to be discussed separately from the “repeated reverse of the same release map”.Official autograd curriculum The starting point for this distinction is given.

Two gradient paths for sharing parameters(a) The mark w simultaneously enters the square branch and triple the branch, and the two guides are added to the w; The dotted line indicates that it is optional to cut three times the branch.ww²3w+f = 10Driver 2 w = 4(a) Nominal 3; detach after 0
Original calculation. (a) The line indicates a forward dependence; At w = 2, two reverse contributions were added to 7.

Test with a shared parameter

Set f(w)=w²+3w, both input and output are markers, current w=2I don't know. The forward square is 4, the linear branch is 6, and the horizontal branch is 10. The two guides are 4 and 3, respectively, with a total gradient of 7. If used in second branch w.detach(), the forward result is still 10, but the lead is only 4. detach changes the orientation to not make the current value zero and does not automatically create a separate memory copy.

dfdw=2w+3=7

If you go back and do it again, backward I don't know .grad, the cumulative gradient is 14. If the same f object is re-reversed, the default is likely to report the "map released " ; Add retain_graph=True It's just that we keep the graph, and it's not for us to decide whether or not to accumulate the gradient. Keeping every batch map for a long time will also result in visible growth. Indicator records should normally be kept .detach().item() The range obtained does not keep the loss object with the map in the list.

# 标准 Python:独立检查解析导数,已执行复算。
w, eps = 2.0, 1e-5
f = lambda v: v*v + 3*v
numerical = (f(w+eps)-f(w-eps))/(2*eps)
assert abs(numerical-7.0) < 1e-8
print(f(w), numerical) # 10.0,约 7.0

Below are the corresponding frame check clips, which are not implemented in the target PyTorch environment. At each time, it is possible to re-move the map to avoid misconstruing the cumulative act.

import torch
w = torch.tensor(2.0, requires_grad=True)
(w*w + 3*w).backward()
print(w.grad) # 预期 7
(w*w + 3*w).backward()
print(w.grad) # 预期 14
w.grad = None
(w*w + 3*w.detach()).backward()
print(w.grad) # 预期 4

Parameter registration determines what the optimiser and saving can see

Yes nn.Module Here, here nn.Parameter The attribution attributes are registered as parameters; A set of submodules should be used ModuleList Wait for the registered container. Normal Python list can save objects but does not automatically provide the same registration synonym. List when slated wrong named_parameters()Confirms that the additional branches, shared weights and freezes are in line with expectations; Then check if the optimizer parameter group really contains them.

A gradient is not required for not all volumes to be saved. (a) Normalized running averages, fixed masks, etc. can be registered as buffer; Lasting buffer usually enters state_dict. Instead, any temporary mass attribute should not be assumed to automatically migrate or preserve the device along the model.state_dict Nor does it amount to a complete program: object structure, pre-processing configuration, feature order and dependent version still need to be recorded separately.

Four directions of model statusTable compares parameters, lasting buffers, ordinary properties and temporary activations for participation in gradients, state_dict and equipment migration.ItemTrainable gradientstate_dictWith. to()ParameterUsuallyYesYesLasted bufferNot normallyYesYesNormal Thread PropertiesLook at SettingsYesYesActivate temporarilyPass GuidesYesNot applicable
This is a comparison of common registration patterns and does not include extensions such as custom-defined hooks. Parameter, which is closed by the gradient, remains a registered parameter.

One check each for mode, freezing and numerical stability

model.eval() Changes the behaviour of modules Dropout, BatchNorm, etc., without automatically stopping the guidance.no_grad() Stop recording the gradient in the current context and do not freeze running statistics automatically. When the base is frozen, it is necessary to confirm whether the parameters are updated and to determine the model to be used in the training of the base module. Can't just because of parameters requires_grad=False All states are determined to remain unchanged.

In situ changes are another category of issues. The framework may be misreported through a version check if the old value saved forward is needed in reverse and the old value is covered in situ. Don't use it .data (b) “Repairing” training by bypassing the examination; The update is first made clear whether it takes place in the map or at the optimist stage. The None gradient is also different from the zero gradient: the former may not be involved in the calculation, while the latter may be involved but the local lead numbers may be zero. The debugging is checked by parameter name, shape, the existence of grad, and the gradient parameters, which are easier to locate than printing all the sheets.

Positioning unlearning branches with minimum status table

A check can fix the same input, save a copy of the pre-update parameter before recording loss for each objective parameter grad and update the post-altitude value. Checks the learning rate, the optimisation parameter group and whether step is actually performed if grad exists and the parameters are not changed; If the parameters change and the verification behaviour remains unchanged, check whether the branch is covered by the subsequent door. A comparison of the address of the object is meaningless and requires a comparison of actual values.

A distinction is also made between training parameters and input gradients. Characteristic weights usually do not require requires_grad and model parameters are still training; Enables the input gradient on a problem-specific basis only if you need to explain the input sensitivity. Keeping grad for all input and intermediate activation will increase memory and may cause debugging output to flood the real anomalies. A small number of named objects are observed before the complete model is restored.

Self-measurement and interpretation

The middle mass of grad is None, can you tell if this side is broken?

Can't. The non-leaf gradient is not retained by default; It is to be confirmed whether it has grad_fn and whether its final loss is dependent on it, and to be observed with retain_grad or a gradient hook if necessary.

Why is detach still 10?

detach retains the current value and only cuts the lead path to the second part of this chapter. The forward calculation of the square branch with the triple branch has not been deleted.

Put the same Parameter in two branches. Do you need to update it twice?

No need. The shared parameters receive a gradient and an upgrade of all paths, as agreed; Repeated additions to the optimizer parameter group may also cause errors.

Normal level in list can be calculated forward. Why still check registration?

The Python call did not prove success of the optimizer, the equipment migration and the state_dict was able to travel through it. Use registered containers and check the list of parameters.

Can you still request a gradient for input in eval mode?

Yes, provided that the calculation enables the gradient and the input meets the guidance requirements. The module mode and the context of autograd are two dimensions.

Only the loss list continues to grow, and how do you judge if the map is kept?

Check whether the list elements are still the volume with grad_fn and compare the memory changes after changing to a marker record; A leak cannot be asserted on the basis of a visible cache value alone.

Continue reading " Write one cycle of training " , followed by " Efficient Training and Recoverability Experiment " . The mechanism of this chapter is based on the three official curricula mentioned above, drawings, counts and explanations; Standard Python has been calculated and the PyTorch fragments have only the expected results, no frame or GPU results.

Sources and reconciliations

Definitions, methods and interfaces are available.

  1. Automatic Differentiation with torch.autograd
  2. Understanding requires_grad, retain_grad, Leaf, and Non-leaf Tensors
  3. PyTorch Quickstart

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.

← Back to the knowledge directory
Ask Max Ask about this site
Ask Max ↗

Opening the assistant…

Paper figure

Photo comments

LEAVE A NOTE

About this photograph

Connecting to the discussion board…

    Comments become public after moderation. You can delete your own comments from this browser.
    No email is required. Clearing cookies prevents this browser from claiming earlier comments.

    MAX WANG / INDEX

    Find something

    Enter a keyword, or explore the directory below.