PyTorch - Automatic differentiation package - torch.autograd

本文详细介绍了PyTorch中自动梯度的功能与使用方法,包括Variable与Function类的作用及其实现细节,同时提供了backward函数的具体用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

torch.autograd provides classes and functions implementing automatic differentiation of arbitrary scalar valued functions. It requires minimal changes to the existing code - you only need to wrap all tensors in Variable objects.

torch.autograd. backward ( variablesgrad_variablesretain_variables=False ) [source]

Computes the sum of gradients of given variables w.r.t. graph leaves.

The graph is differentiated using the chain rule. If any of variables are non-scalar (i.e. their data has more than one element) and require gradient, the function additionaly requires specifyinggrad_variables. It should be a sequence of matching length, that containins gradient of the differentiated function w.r.t. corresponding variables (None is an acceptable value for all variables that don’t need gradient tensors).

This function accumulates gradients in the leaves - you might need to zero them before calling it.

Parameters:
  • variables (sequence of Variable) – Variables of which the derivative will be computed.
  • grad_variables (sequence of Tensor) – Gradients w.r.t. each element of corresponding variables. Required only for non-scalar variables that require gradient.
  • retain_variables (bool) – If True, buffers necessary for computing gradients won’t be freed after use. It is only necessary to specify True if you want to differentiate some subgraph multiple times.

Variable

API compatibility

Variable API is nearly the same as regular Tensor API (with the exception of a couple in-place methods, that would overwrite inputs required for gradient computation). In most cases Tensors can be safely replaced with Variables and the code will remain to work just fine. Because of this, we’re not documenting all the operations on variables, and you should refere to torch.Tensor docs for this purpose.

In-place operations on Variables

Supporting in-place operations in autograd is a hard matter, and we discourage their use in most cases. Autograd’s aggressive buffer freeing and reuse makes it very efficient and there are very few occasions when in-place operations actually lower memory usage by any significant amount. Unless you’re operating under heavy memory pressure, you might never need to use them.

In-place correctness checks

All Variable s keep track of in-place operations applied to them, and if the implementation detects that a variable was saved for backward in one of the functions, but it was modified in-place afterwards, an error will be raised once backward pass is started. This ensures that if you’re using in-place functions and not seing any errors, you can be sure that the computed gradients are correct.

class torch.autograd. Variable [source]

Wraps a tensor and records the operations applied to it.

Variable is a thin wrapper around a Tensor object, that also holds the gradient w.r.t. to it, and a reference to a function that created it. This reference allows retracing the whole chain of operations that created the data. If the Variable has been created by the user, its creator will beNone and we call such objects leaf Variables.

Since autograd only supports scalar valued function differentiation, grad size always matches the data size. Also, grad is normally only allocated for leaf variables, and will be always zero otherwise.

Variables:
  • data – Wrapped tensor of any type.
  • grad – Variable holding the gradient of type and location matching the .data. This attribute is lazily allocated and can’t be reassigned.
  • requires_grad – Boolean indicating whether the Variable has been created by a subgraph containing any Variable, that requires it. See Excluding subgraphs from backward for more details. Can be changed only on leaf Variables.
  • volatile – Boolean indicating that the Variable should be used in inference mode, i.e. don’t save the history. See Excluding subgraphs from backward for more details. Can be changed only on leaf Variables.
  • creator – Function of which the variable was an output. For leaf (user created) variables it’s None. Read-only attribute.
Parameters:
  • data (any tensor class) – Tensor to wrap.
  • requires_grad (bool) – Value of the requires_grad flag. Keyword only.
  • volatile (bool) – Value of the volatile flag. Keyword only.
backward ( gradient=Noneretain_variables=False ) [source]

Computes the gradient of current variable w.r.t. graph leaves.

The graph is differentiated using the chain rule. If the variable is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionaly requires specifyinggradient. It should be a tensor of matching type and location, that containins the gradient of the differentiated function w.r.t. self.

This function accumulates gradients in the leaves - you might need to zero them before calling it.

Parameters:
  • gradient (Tensor) – Gradient of the differentiated function w.r.t. the data. Required only if the data has more than one element. Type and location should match these ofself.data.
  • retain_variables (bool) – If True, buffers necessary for computing gradients won’t be freed after use. It is only necessary to specify True if you want to differentiate some subgraph multiple times (in some cases it will be much more efficient to useautograd.backward).
detach ( ) [source]

Returns a new Variable, detached from the current graph.

Result will never require gradient. If the input is volatile, the output will be volatile too.

Note

Returned Variable uses the same data tensor, as the original one, and in-place modifications on either of them will be seen, and may trigger errors in correctness checks.

detach_ ( ) [source]

Detaches the Variable from the graph that created it, making it a leaf.

register_hook ( hook ) [source]

Registers a backward hook.

The hook will be called every time a gradient with respect to the variable is computed. The hook should have the following signature:

hook(grad) -> Variable or None

The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of grad.

This function returns a handle with a method handle.remove() that removes the hook from the module.

Example

>>> v = Variable(torch.Tensor([0, 0, 0]), requires_grad=True)
>>> h = v.register_hook(lambda grad: grad * 2)  # double the gradient
>>> v.backward(torch.Tensor([1, 1, 1]))
>>> v.grad.data
 2
 2
 2
[torch.FloatTensor of size 3]
>>> h.remove()  # removes the hook
reinforce ( reward ) [source]

Registers a reward obtained as a result of a stochastic process.

Differentiating stochastic nodes requires providing them with reward value. If your graph contains any stochastic operations, you should call this function on their outputs. Otherwise an error will be raised.

Parameters: reward (Tensor) – Tensor with per-element rewards. It has to match the device location and shape of Variable’s data.

class torch.autograd. Function [source]

Records operation history and defines formulas for differentiating ops.

Every operation performed on Variable s creates a new function object, that performs the computation, and records that it happened. The history is retained in the form of a DAG of functions, with edges denoting data dependencies (input <- output). Then, when backward is called, the graph is processed in the topological ordering, by calling backward() methods of eachFunction object, and passing returned gradients on to next Function s.

Normally, the only way users interact with functions is by creating subclasses and defining new operations. This is a recommended way of extending torch.autograd.

Since Function logic is a hotspot in most scripts, almost all of it was moved to our C backend, to ensure that the framework overhead is minimal.

Each function is meant to be used only once (in the forward pass).

Variables:
  • saved_tensors – Tuple of Tensors that were saved in the call to forward().
  • needs_input_grad – Tuple of booleans of length num_inputs, indicating whether a given input requires gradient. This can be used to optimize buffers saved for backward, and ignoring gradient computation in backward().
  • num_inputs – Number of inputs given to forward().
  • num_outputs – Number of tensors returned by forward().
  • requires_grad – Boolean indicating whether the backward() will ever need to be called.
  • previous_functions – Tuple of (int, Function) pairs of length num_inputs. Each entry contains a reference to a Function that created corresponding input, and an index of the previous function output that’s been used.
backward ( *grad_output ) [source]

Defines a formula for differentiating the operation.

This function is to be overriden by all subclasses.

All arguments are tensors. It has to accept exactly as many arguments, as many outputs didforward() return, and it should return as many tensors, as there were inputs to forward(). Each argument is the gradient w.r.t the given output, and each returned value should be the gradient w.r.t. the corresponding input.

forward ( *input ) [source]

Performs the operation.

This function is to be overriden by all subclasses.

It can take and return an arbitrary number of tensors.

mark_dirty ( *args ) [source]

Marks given tensors as modified in an in-place operation.

This should be called at most once, only from inside the forward() method, and all arguments should be inputs.

Every tensor that’s been modified in-place in a call to forward() should be given to this function, to ensure correcness of our checks. It doesn’t matter wheter the function is called before or after modification.

mark_non_differentiable ( *args ) [source]

Marks outputs as non-differentiable.

This should be called at most once, only from inside the forward() method, and all arguments should be outputs.

This will mark outputs as not requiring gradients, increasing the efficiency of backward computation. You still need to accept a gradient for each output in backward(), but it’s always going to be None.

This is used e.g. for indices returned from a max Function.

mark_shared_storage ( *pairs ) [source]

Marks that given pairs of distinct tensors are sharing storage.

This should be called at most once, only from inside the forward() method, and all arguments should be pairs of (input, output).

If some of the outputs are going to be tensors sharing storage with some of the inputs, all pairs of (input_arg, output_arg) should be given to this function, to ensure correctness checking of in-place modification. The only exception is when an output is exactly the same tensor as input (e.g. in-place ops). In such case it’s easy to conclude that they’re sharing data, so we don’t require specifying such dependencies.

This function is not needed in most functions. It’s primarily used in indexing and transpose ops.

save_for_backward ( *tensors ) [source]

Saves given tensors for a future call to backward().

This should be called at most once, and only from inside the forward() method.

Later, saved tensors can be accessed through the saved_tensors attribute. Before returning them to the user, a check is made, to ensure they weren’t used in any in-place operation that modified their content.

Arguments can also be None.

<think>我们遇到了安装PyTorch时关于cuda-nvtx包的依赖问题。错误信息显示缺少cuda-nvtx>=12.1,<12.2的包。 原因分析:可能是清华镜像站中pytorch频道没有为Windows平台提供cuda-nvtx 12.1版本,或者包名称有差异。 解决方案: 1. 尝试使用官方PyTorch频道安装(可能需要接受许可协议,并可能较慢): conda install pytorch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 pytorch-cuda=12.1 -c pytorch -c nvidia 2. 使用pip安装(推荐,因为PyTorch官方pip源通常更全): pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu121 3. 如果坚持使用conda,可以尝试单独安装cuda-nvtx包(但可能仍然需要nvidia频道): conda install -c nvidia cuda-nvtx=12.1 但注意:由于我们之前遇到conda-forge和清华镜像没有Windows上的CUDA 12.1,这里同样可能存在镜像源不完整的问题。 因此,最可靠的方案是使用pip安装。 步骤: 1. 创建一个新的conda环境(可选,但推荐): conda create -n torch_env python=3.10 conda activate torch_env 2. 使用pip安装: pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cu121 3. 验证安装: python -c "import torch; print(torch.__version__); print(torch.cuda.is_available())" 如果显示True,则安装成功。 如果网络问题导致下载慢,可以考虑使用国内镜像(如阿里云、清华源)进行pip安装,但注意PyTorch的CUDA版本通常需要从官方源下载,所以如果国内镜像没有预编译版本,仍然需要从官方下载。可以尝试添加临时镜像: pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://mirrors.aliyun.com/pypi/simple/ --extra-index-url https://download.pytorch.org/whl/cu121 注意:这里使用阿里云镜像作为主索引,当阿里云没有时,会从PyTorch官方下载。 最后,如果上述方法都失败,可以考虑下载预编译的wheel文件手动安装: - 访问 https://download.pytorch.org/whl/cu121/torch_stable.html - 根据你的Python版本和系统下载对应的torchtorchvision、torchaudio的whl文件 - 然后使用pip安装下载的文件,例如: pip install torch-2.3.1+cu121-cp310-cp310-win_amd64.whl pip install torchvision-0.18.1+cu121-cp310-cp310-win_amd64.whl pip install torchaudio-2.3.1+cu121-cp310-cp310-win_amd64.whl 注意:Python版本和系统(win_amd64)要匹配。 根据以上分析,我们推荐使用pip直接安装。</think>### PyTorch安装失败分析与解决方案 您遇到的 **LibMambaUnsatisfiableError** 错误表明安装**没有成功**。核心问题是清华镜像站缺少Windows平台所需的`cuda-nvtx=12.1`依赖包。以下是详细分析和解决方案: #### 错误原因解析: 1. **镜像站缺失依赖**:清华镜像站`pytorch`频道缺少Windows平台的`cuda-nvtx=12.1`包 2. **CUDA组件依赖链**:`pytorch-cuda=12.1`依赖`cuda-nvtx>=12.1,<12.2` 3. **平台限制**:NVIDIA官方未在conda渠道提供Windows版CUDA组件完整包 4. **频道优先级冲突**:`--override-channels`覆盖了默认频道,导致无法从官方源查找 #### 完整解决方案: ##### 方案1:使用pip安装PyTorch(推荐) ```cmd pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 ^ --index-url https://download.pytorch.org/whl/cu121 ``` 验证安装: ```python import torch print(torch.__version__) # 应输出2.3.1 print(torch.cuda.is_available()) # 应输出True ``` ##### 方案2:从NVIDIA频道安装缺失依赖 ```cmd conda install -c nvidia cuda-nvtx=12.1 conda install pytorch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 ^ -c pytorch -c nvidia ``` ##### 方案3:手动下载安装(离线方案) 1. 访问[PyTorch官方下载页](https://download.pytorch.org/whl/torch_stable.html) 2. 下载对应文件: - torch-2.3.1+cu121-cp310-cp310-win_amd64.whl - torchvision-0.18.1+cu121-cp310-cp310-win_amd64.whl - torchaudio-2.3.1+cu121-cp310-cp310-win_amd64.whl 3. 本地安装: ```cmd pip install torch-2.3.1+cu121-cp310-cp310-win_amd64.whl pip install torchvision-0.18.1+cu121-cp310-cp310-win_amd64.whl pip install torchaudio-2.3.1+cu121-cp310-cp310-win_amd64.whl ``` #### 安装后验证步骤: ```cmd python -c "import torch; print(f'PyTorch版本: {torch.__version__}\\nCUDA可用: {torch.cuda.is_available()}\\nCUDA版本: {torch.version.cuda}')" ``` 预期输出: ``` PyTorch版本: 2.3.1+cu121 CUDA可用: True CUDA版本: 12.1 ``` > **替代方案**:如果只需CPU版本: > ```cmd > conda install pytorch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 cpuonly -c pytorch > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值