关于with torch.no_grad:的一些小问题

with torch.no_grad:是截断梯度记录的,新生成的数据的都不记录梯度,但是今天产生了一点小疑惑,如果存在多层函数嵌入,是不是函数内所有的数据都不记录梯度,验证了一下,确实是的。

python 复制代码
import torch
x = torch.randn(10, 5, requires_grad = True)
y = torch.randn(10, 5, requires_grad = True)
z = torch.randn(10, 5, requires_grad = True)
def add(x,y,z):
    w = x + y + z
    print(w.requires_grad)
    print(w.grad_fn)
def add2(x,y,z):
    add(x,y,z)
with torch.no_grad():
    add2(x,y,z)
    
add2(x,y,z)
"""
输出:
False
None
True
<AddBackward0 object at 0x00000250371BED68>
"""
相关推荐
AI街潜水的八角33 分钟前
Python电脑屏幕&摄像头录制软件(提供源代码)
开发语言·python
hadage23334 分钟前
--- git 的一些使用 ---
开发语言·git·python
笨笨聊运维7 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite7 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
噜~噜~噜~7 小时前
最大熵原理(Principle of Maximum Entropy,MaxEnt)的个人理解
深度学习·最大熵原理
小毛驴8507 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
闲人编程7 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760008 小时前
Python 数据结构
数据结构·windows·python