2.4K Star 8.2K Fork 4.4K

GVPMindSpore / mindspore

 / 详情

[CT][MS]tensor hook, save grad to outer var fail

DONE
Bug-Report 成员
创建于  
2024-04-22 11:21
name about labels
Bug Report Use this template for reporting a bug kind/bug

Describe the current behavior / 问题描述 (Mandatory / 必填)

tensor hook,用外部变量获取梯度失败

Environment / 环境信息 (Mandatory / 必填)

  • 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

Related testcase / 关联用例 (Mandatory / 必填)

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)

Steps to reproduce the issue / 重现步骤 (Mandatory / 必填)

Describe the expected behavior / 预期结果 (Mandatory / 必填)

[2. 2. 2.]

Related log / screenshot / 日志 / 截图 (Mandatory / 必填)

None

Special notes for this issue/备注 (Optional / 选填)

评论 (4)

chentanjie 创建了Bug-Report
chentanjie 添加了
 
kind/bug
标签
chentanjie 添加了
 
sig/pynative
标签
chentanjie 添加了
 
v2.3.0.rc2
标签
展开全部操作日志

Please assign maintainer to check this issue.
请为此issue分配处理人。
@chentanjie

感谢您的提问,您可以评论//mindspore-assistant更快获取帮助:

  1. 如果您刚刚接触MindSpore,或许您可以在教程找到答案
  2. 如果您是资深Pytorch用户,您或许需要:
  1. 如果您遇到动态图问题,可以设置set_context(pynative_synchronize=True)查看报错栈协助定位
  2. 模型精度调优问题可参考官网调优指南
  3. 如果您反馈的是框架BUG,请确认您在ISSUE中提供了MindSpore版本、使用的后端类型(CPU、GPU、Ascend)、环境、训练的代码官方链接以及可以复现报错的代码的启动方式等必要的定位信息
  4. 如果您已经定位出问题根因,欢迎提交PR参与MindSpore开源社区,我们会尽快review
chentanjie 修改了描述
chentanjie 修改了描述

该问题本质原因是,python作用域的问题,在print_fn中已经访问不到函数临时变量my_grad 。
通过torch实现于上述逻辑相同的代码,也是返回None。

zjun 添加了
 
ctl/componenttest
标签
zjun 添加了
 
rca/others
标签
zjun 添加了
 
rct/newfeature
标签
zjun 添加协作者zjun
zjun 负责人zjun 修改为chentanjie
zjun 任务状态TODO 修改为VALIDATION

ok torch也暂不支持

chentanjie 任务状态VALIDATION 修改为DONE
fangwenyi 移除了
 
v2.3.0.rc2
标签
fangwenyi 添加了
 
master
标签

登录 后才可以发表评论

状态
负责人
项目
里程碑
Pull Requests
关联的 Pull Requests 被合并后可能会关闭此 issue
分支
开始日期   -   截止日期
-
置顶选项
优先级
预计工期 (小时)
参与者(3)
6580807 zjun3021 1615805932 5280992 chen tanjie 1645579326
Python
1
https://gitee.com/mindspore/mindspore.git
git@gitee.com:mindspore/mindspore.git
mindspore
mindspore
mindspore

搜索帮助