pytorch如何知道某个Parameter是在哪一个Module中的创建的

pytorch如何知道某个Parameter是在哪一个Module中的创建的

在定位pytorch精度问题时,发现optimizer中某些Parameter值异常,想知道它属于哪个模块的.本文提供二种方法
1.全局搜索
2.在创建Parameter的地方加一个属性,写明所在的模块名,需要的时候直接获取

代码

python 复制代码
import torch
import sys
sys.setrecursionlimit(1000)
        
def search_recursive(var,stack,_id,depth):
    if var.__class__.__name__ in [
                                    "module","type","NoneType",
                                    "str","int","function","method-wrapper",
                                    "builtin_function_or_method",
                                    "method","_TensorMeta",
                                    "Tensor","method_descriptor",
                                    "bool","device","dtype",
                                    "getset_descriptor","layout",
                                    "wrapper_descriptor","property",
                                    "_ParameterMeta","mappingproxy",
                                    "Parameter","_abc_data","SourceFileLoader",
                                    "code","bytes","ABCMeta",
                                    "ForwardRef","ellipsis","TypeVar"
                                 ]:
        return False
    
    if isinstance(var,dict):
        for k,v in var.items():
            ret=search_recursive(v,stack,_id,depth+1)
            if ret:
                return ret
    elif isinstance(var,list) or isinstance(var,tuple):
        for i in var:
            ret=search_recursive(i,stack,_id,depth+1)
            if ret:
                return ret
    else:     
        if not var.__class__.__name__.startswith("_"):
            stack[depth]=var.__class__.__name__         
        for name in dir(var):
            try:
                obj=eval(f"var.{name}")
                if isinstance(obj,torch.nn.modules.linear.Linear) and id(obj.weight)==_id:
                    return stack[depth]
                ret=search_recursive(obj,stack,_id,depth+1)
                if ret:
                    return ret                 
            except:
                pass              
    return None

class MyModel(torch.nn.Module):
    def __init__(self):
        super(MyModel, self).__init__()
        self.mlp=torch.nn.Linear(5120,3850)
        self.mlp.weight.__setattr__("model_name","MyModel") #方法一:通过添加属性
    def forward(self, x):
        out=self.mlp(x)
        return out
class MyContainer(object):
    def __init__(self):
        self.obj=MyModel()    
    def get_param(self):
        return self.obj.mlp.weight
obj = MyContainer()
param_group={}
param_group["w0"]=obj.get_param()
param_array=[param_group,obj]

print("GetModelName By getattr:",getattr(param_group["w0"],"model_name"))
# 方法二:递归搜索全局变量
model_name=search_recursive(globals(),{},id(param_group["w0"]),0)
print("GetModelName By search_recursive:",model_name)
相关推荐
m0_609000429 分钟前
向日葵好用吗?4款稳定的远程控制软件推荐。
运维·服务器·网络·人工智能·远程工作
开MINI的工科男1 小时前
深蓝学院-- 量产自动驾驶中的规划控制算法 小鹏
人工智能·机器学习·自动驾驶
waterHBO1 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AI大模型知识分享2 小时前
Prompt最佳实践|如何用参考文本让ChatGPT答案更精准?
人工智能·深度学习·机器学习·chatgpt·prompt·gpt-3
张人玉4 小时前
人工智能——猴子摘香蕉问题
人工智能
草莓屁屁我不吃4 小时前
Siri因ChatGPT-4o升级:我们的个人信息还安全吗?
人工智能·安全·chatgpt·chatgpt-4o
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
AI科研视界5 小时前
ChatGPT+2:修订初始AI安全性和超级智能假设
人工智能·chatgpt