Interesting bug caused by getattr
题意:由 getattr
引起的有趣的 bug
问题背景:
I try to train 8 CNN models with the same structures simultaneously. After training a model on a batch, I need to synchronize the weights of the feature extraction layers in other 7 models.
我尝试同时训练8个具有相同结构的卷积神经网络(CNN)模型。在对一个批次的数据训练一个模型后,我需要同步其他7个模型中特征提取层的权重。
This is the model: 这是模型
class GNet(nn.Module):def __init__(self, dim_output, dropout=0.5):super(GNet, self).__init__()self.out_dim = dim_output# Load the pretrained AlexNet modelalexnet = models.alexnet(pretrained=True)self.pre_filtering = nn.Sequential(alexnet.features[:4])# Set requires_grad to False for all parameters in the pre_filtering networkfor param in self.pre_filtering.parameters():param.requires_grad = False# construct the feature extractor# every intermediate feature will be fed to the feature extractor# res: 25 x 25self.feat_ex1 = nn.Conv2d(192, 128, kernel_size=3, stride=1)# res: 25 x 25self.feat_ex2 = nn.Sequential(nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))# res: 25 x 25self.feat_ex3 = nn.Sequential(nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))# res: 13 x 13self.feat_ex4 = nn.Sequential(nn.MaxPool2d(kernel_size=3, stride=2, padding=1),nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))# res: 13 x 13self.feat_ex5 = nn.Sequential(nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))# res: 13 x 13self.feat_ex6 = nn.Sequential(nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1))# res: 13 x 13self.feat_ex7 = nn.Sequential(nn.BatchNorm2d(128),nn.Dropout(p=dropout),nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1))# define the flexible pooling field of each layer# use a full convolution layer here to perform flexible poolingself.fpf13 = nn.Conv2d(in_channels=448, out_channels=448, kernel_size=13, groups=448)self.fpf25 = nn.Conv2d(in_channels=384, out_channels=384, kernel_size=25, groups=384)self.linears = {}for i in range(self.out_dim):self.linears[f'linear_{i+1}'] = nn.Linear(832, 1)self.LogTanh = LogTanh()self.flatten = nn.Flatten()
And this is the function to synchronize the weights:
这是同步权重的函数:
def sync_weights(models, current_sub, sync_seqs):for sub in range(1, 9):if sub != current_sub:# Synchronize the specified layerswith torch.no_grad():for seq_name in sync_seqs:reference_layer = getattr(models[current_sub], seq_name)[2]layer = getattr(models[sub], seq_name)[2]layer.weight.data = reference_layer.weight.data.clone()if layer.bias is not None:layer.bias.data = reference_layer.bias.data.clone()
then an error is raised: 然后出现了一个错误:
'Conv2d' object is not iterable
which means the getattr() returns a Conv2D object. But if I remove [2]:
意思是 getattr()
函数返回了一个 Conv2D
对象。但是,如果我移除了 [2]
def sync_weights(models, current_sub, sync_seqs):for sub in range(1, 9):if sub != current_sub:# Synchronize the specified layerswith torch.no_grad():for seq_name in sync_seqs:reference_layer = getattr(models[current_sub], seq_name)layer = getattr(models[sub], seq_name)layer.weight.data = reference_layer.weight.data.clone()if layer.bias is not None:layer.bias.data = reference_layer.bias.data.clone()
I get another error: 我得到了另一个错误
'Sequential' object has no attribute 'weight'
which means the getattr() returns a Sequential. But previously it returns a Conv2D object. Does anyone know anything about this? For your information, the sync_seqs parameter passed in sync_weights is:
意思是 getattr()
现在返回的是一个 Sequential
模型,但之前它返回的是一个 Conv2D
对象。有人知道这是怎么回事吗?为了提供更多信息,sync_weights
函数中传入的 sync_seqs
参数是:
sync_seqs = ['feat_ex1','feat_ex2','feat_ex3','feat_ex4','feat_ex5','feat_ex6','feat_ex7'
]
问题解决:
In both instances, getattr
is returning a Sequential
, which in turn contains a bunch of objects. In the second case, you're directly assigning that Sequential
to a variable, so reference_layer
ends up containing a Sequential
.
在这两种情况下,getattr
都返回了一个 Sequential
对象,而这个 Sequential
对象又包含了一系列的其他对象。在第二种情况下,你直接将这个 Sequential
对象赋值给了一个变量,因此 reference_layer
最终包含了一个 Sequential
对象。
In the first case, however, you're not doing that direct assignemnt. You're taking the Sequential
object and then indexing it with [2]
. That means reference_layer
contains the third item in the Sequential
, which is a Conv2d
object.
在第一种情况下,你没有进行直接的赋值。你是先获取了 Sequential
对象,然后使用 [2]
对其进行索引。这意味着 reference_layer
包含的是 Sequential
中的第三个项目,这个项目是一个 Conv2D
对象。
Take a more simple example. Suppose I had a ListContainer
class that did nothing except hold a list. I could then recreate your example as follows, with test1
corresponding to your first test case and vice versa:
以一个更简单的例子来说明。假设我有一个 ListContainer
类,它唯一的作用就是持有一个列表。然后我可以按照以下方式重现你的例子,其中 test1
对应你的第一个测试用例,反之亦然:
class ListContainer:def __init__(self, list_items):self.list_items = list_itemsletters = ["a", "b", "c"]
container = ListContainer(letters)test1 = getattr(container, "list_items")[0]
test2 = getattr(container, "list_items")print(type(test1)) # <class 'str'>
print(type(test2)) # <class 'list'>
In both tests, getattr
itself is returning a list - but in the second, we're doing something with that list after we get it, so test2 ends up being a string instead.
在两次测试中,getattr
本身都返回了一个列表——但在第二次测试中,我们在获取到这个列表之后对它进行了某种操作,所以 test2
最终变成了一个字符串而不是列表。
相关文章:

Interesting bug caused by getattr
题意:由 getattr 引起的有趣的 bug 问题背景: I try to train 8 CNN models with the same structures simultaneously. After training a model on a batch, I need to synchronize the weights of the feature extraction layers in other 7 models. …...

获取后端返回的图形验证码
如果后端返回的直接就是一个图形,有以下几种方式展示 一、直接在img标签里面的src里面调用接口 <img :src"dialogSrc" class"photo" alt"验证码图片" click"changeDialog">let orgUrl "/api/captcha" …...

奇怪的Excel单元格字体颜色格式
使用VBA代码修改单元格全部字符字体颜色是个很简单的任务,例如设置A1单元格字体颜色为红色。 Range("A1").Font.Color RGB(255, 0, 0)有时需要修改部分字符的颜色,如下图所示,将红色字符字体颜色修改为蓝色。代码将会稍许复杂&am…...

浅谈芯片验证中的仿真运行之 timescale (五)提防陷阱
一 仿真单位 timeunit 我们知道,当我们的代码中写清楚延时语句时,若不指定时间单位,则使用此单位; 例如: `timescale 1ns/1ps 则 #15 语句表示delay15ns; 例:如下代码,module a 的timescale是1ns/1ps, module b 是1ps/1ps; module b中的clk,频率是由输入参…...
uniapp 重置表单数据
场景 例如有数据如下 data(){return {queryForm:{value1:undefined,}} } 点击重置时候想重置form的数据, 操作 Object.assign(this.$data.queryForm, this.$options.data().queryForm); 就可以重置数据...
自学YOLO前置知识
YOLO前置知识 学习YOLO(You Only Look Once)之前,掌握一些前置知识会帮助你更好地理解和应用该技术。以下是一些推荐的前置知识领域: 计算机视觉基础: 图像处理:了解图像的基本处理技术,如滤波…...
Ubuntu18.04 编译报错: Could NOT find JNI
一、问题描述 Ubuntu18.04 编译报错 OpenCV 时,出现以下错误: Could NOT find JNI (missing: JAVA_INCLUDE_PATH JAVA_INCLUDE_PATH2 JAVA_AWT_INCLUDE_PATH)二、解决方法 先执行以下指令, export JAVA_HOME/usr/lib/jvm/java-8-openjdk-am…...

SQL labs-SQL注入(五,使用sqlmap进行cookie注入)
本文仅作为学习参考使用,本文作者对任何使用本文进行渗透攻击破坏不负任何责任。 引言: Cookie 是一些数据, 存储于你电脑上的文本文件中。当 web 服务器向浏览器发送 web 页面时,在连接关闭后,服务端不会记录用户的信息。Cookie…...
C语言——内存管理
目录 前言 一、内存分类 1. 栈区(Stack) 2. 堆区(Heap) 3. 数据段(Data Segment) 4. 代码段(Code Segment) 二、内存分配方式 1、静态内存分配 2、栈内分配 3、动态内存分配 &#x…...

Unity UGUI 之 Image和Rawimage
本文仅作学习笔记与交流,不作任何商业用途 本文包括但不限于unity官方手册,唐老狮,麦扣教程知识,引用会标记,如有不足还请斧正 1.Image是什么 Unity - 手册:图像 精灵格式是什么? 1.2重要参数 …...

Lua 语法学习笔记
Lua 语法学习笔记 安装(windows) 官网:https://www.lua.org/ 下载SDK 解压&修改名称(去除版本号) 将lua后面的版本号去掉,如lua54.exe->lua.ext 配置环境变量 数据类型 数据类型描述nil这个最简单,只有值n…...

Prometheus配置alertmanager告警
1、拉取镜像并运行 1、配置docker镜像源 [rootlocalhost ~]# vim /etc/docker/daemon.json {"registry-mirrors": ["https://dfaad.mirror.aliyuncs.com"] } [rootlocalhost ~]# systemctl daemon-reload [rootlocalhost ~]# systemctl restart docker2、…...
.net core 外观者设计模式 实现,多种支付选择
1,接口 /// <summary>/// Web页面支付/// </summary>public interface IWebPagePay{public WebPagePayResult CreatePay(string productName, string orderSn, string totalPrice);}2,实现接口 实现阿里支付 public class AliPagePay : IWe…...

Matlab 命令行窗口默认输出(异常)
目录 前言Matlab 先验知识1 异常输出的代码2 正常输出的代码 前言 在单独调试 Matlab 写的函数时出现不想出现的异常打印值,逐个注释排查才找到是 if elseif else 代码块的问题,会默认打印输出 else 部分第一个返回值的值(下方代码中的 P值&…...

LeetCode/NowCoder-二叉树OJ练习
励志冰檗:形容在清苦的生活环境中激励自己的意志。💓💓💓 目录 说在前面 题目一:单值二叉树 题目二:相同的树 题目三:对称二叉树 题目四:二叉树的前序遍历 题目五:另…...

PSINS工具箱函数介绍——insplot
insplot是一个绘图命令,用于将avp数据绘制出来 本文所述的代码需要基于PSINS工具箱,工具箱的讲解: PSINS初学指导基于PSINS的相关程序设计(付费专题)使用方法 此函数使用起来也很简单,直接后面加avp即可,如: insplot(avp);其中,avp为: 每行表示一个时间1~3列为姿态…...

Docker简单快速入门
1. 安装Docker 基于 Ubuntu 24.04 LTS 安装Docker 。 # 更新包索引并安装依赖包 sudo apt-get update sudo apt-get install -y apt-transport-https ca-certificates curl software-properties-common# 添加Docker的官方GPG密钥并存储在正确的位置 curl -fsSL https://mirror…...

【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 图像物体的边界(200分) - 三语言AC题解(Python/Java/Cpp)
🍭 大家好这里是清隆学长 ,一枚热爱算法的程序员 ✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解 💻 ACM银牌🥈| 多次AK大厂笔试 | 编程一对一辅导 👏 感谢大家的订阅➕ 和 喜欢💗 🍿 最新华为OD机试D卷目录,全、新、准,题目覆盖率达 95% 以上,支持题目在线…...

【无人机】低空经济中5G RedCap芯片的技术分析报告
1. 引言 图一. 新基建:低空经济 低空经济作为一种新兴的经济形态,涵盖了无人机、电动垂直起降飞行器(eVTOL)、低空物流、空中交通管理等多个领域。随着5G网络的普及和演进,5G RedCap(Reduced Capability&a…...

MongoDB教程(二十一):MongoDB大文件存储GridFS
💝💝💝首先,欢迎各位来到我的博客,很高兴能够在这里和您见面!希望您在这里不仅可以有所收获,同时也能感受到一份轻松欢乐的氛围,祝你生活愉快! 文章目录 引言一、GridFS…...

UE5 学习系列(二)用户操作界面及介绍
这篇博客是 UE5 学习系列博客的第二篇,在第一篇的基础上展开这篇内容。博客参考的 B 站视频资料和第一篇的链接如下: 【Note】:如果你已经完成安装等操作,可以只执行第一篇博客中 2. 新建一个空白游戏项目 章节操作,重…...

Flask RESTful 示例
目录 1. 环境准备2. 安装依赖3. 修改main.py4. 运行应用5. API使用示例获取所有任务获取单个任务创建新任务更新任务删除任务 中文乱码问题: 下面创建一个简单的Flask RESTful API示例。首先,我们需要创建环境,安装必要的依赖,然后…...
【Java学习笔记】Arrays类
Arrays 类 1. 导入包:import java.util.Arrays 2. 常用方法一览表 方法描述Arrays.toString()返回数组的字符串形式Arrays.sort()排序(自然排序和定制排序)Arrays.binarySearch()通过二分搜索法进行查找(前提:数组是…...
Cesium1.95中高性能加载1500个点
一、基本方式: 图标使用.png比.svg性能要好 <template><div id"cesiumContainer"></div><div class"toolbar"><button id"resetButton">重新生成点</button><span id"countDisplay&qu…...

关于iview组件中使用 table , 绑定序号分页后序号从1开始的解决方案
问题描述:iview使用table 中type: "index",分页之后 ,索引还是从1开始,试过绑定后台返回数据的id, 这种方法可行,就是后台返回数据的每个页面id都不完全是按照从1开始的升序,因此百度了下,找到了…...
Golang dig框架与GraphQL的完美结合
将 Go 的 Dig 依赖注入框架与 GraphQL 结合使用,可以显著提升应用程序的可维护性、可测试性以及灵活性。 Dig 是一个强大的依赖注入容器,能够帮助开发者更好地管理复杂的依赖关系,而 GraphQL 则是一种用于 API 的查询语言,能够提…...

C++ Visual Studio 2017厂商给的源码没有.sln文件 易兆微芯片下载工具加开机动画下载。
1.先用Visual Studio 2017打开Yichip YC31xx loader.vcxproj,再用Visual Studio 2022打开。再保侟就有.sln文件了。 易兆微芯片下载工具加开机动画下载 ExtraDownloadFile1Info.\logo.bin|0|0|10D2000|0 MFC应用兼容CMD 在BOOL CYichipYC31xxloaderDlg::OnIni…...
基于matlab策略迭代和值迭代法的动态规划
经典的基于策略迭代和值迭代法的动态规划matlab代码,实现机器人的最优运输 Dynamic-Programming-master/Environment.pdf , 104724 Dynamic-Programming-master/README.md , 506 Dynamic-Programming-master/generalizedPolicyIteration.m , 1970 Dynamic-Programm…...

算法笔记2
1.字符串拼接最好用StringBuilder,不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...

初探Service服务发现机制
1.Service简介 Service是将运行在一组Pod上的应用程序发布为网络服务的抽象方法。 主要功能:服务发现和负载均衡。 Service类型的包括ClusterIP类型、NodePort类型、LoadBalancer类型、ExternalName类型 2.Endpoints简介 Endpoints是一种Kubernetes资源…...