name | about | labels |
---|---|---|
Bug Report | Use this template for reporting a bug | kind/bug |
tensor hook,用外部变量获取梯度失败
Hardware Environment(Ascend
/GPU
/CPU
) / 硬件环境:
/device ascend/GPU/CPU
Software Environment / 软件环境 (Mandatory / 必填):
-- MindSpore version (e.g., 1.7.0.Bxxx) :
-- Python version (e.g., Python 3.7.5) :
-- OS platform and distribution (e.g., Linux Ubuntu 16.04):
-- GCC/Compiler version (if compiled from source):
Excute Mode / 执行模式 (Mandatory / 必填)(PyNative
/Graph
):
/mode pynative
from mindspore.nn import Cell
from mindspore import ops
from mindspore.common import Tensor
import numpy as np
class Net1(Cell):
def __init__(self):
super().__init__()
self.n = 2
def construct(self, x):
return x * self.n
def test_hook_tensor_print():
my_grad = None
def print_fn(grad):
my_grad = grad
return grad
net = Net1()
x = np.random.rand(3,).astype(np.float32)
x = Tensor(x)
x.register_hook(print_fn)
grad_net = ops.grad(net)
grad = grad_net(x)
print(my_grad)
[2. 2. 2.]
None
Please assign maintainer to check this issue.
请为此issue分配处理人。
@chentanjie
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
感谢您的提问,您可以评论//mindspore-assistant更快获取帮助:
该问题本质原因是,python作用域的问题,在print_fn中已经访问不到函数临时变量my_grad 。
通过torch实现于上述逻辑相同的代码,也是返回None。
ok torch也暂不支持
登录 后才可以发表评论