为什么在 Pytorch 中,当我复制网络权重时,它会在反向传播后自动更新?

2023-12-10

我编写了以下代码作为测试,因为在我的原始网络中,我使用 ModuleDict 并取决于我提供的索引,它只会切片和训练该网络的一部分。

我想确保只有切片层会更新它们的权重,所以我编写了一些测试代码来仔细检查。好吧,我得到了一些奇怪的结果。假设我的模型有 2 层,第 1 层是 FC,第 2 层是 Conv2d,如果我对网络进行切片并且仅使用第 2 层,我会期望第 1 层的权重保持不变,因为它们未使用,第 2 层的权重将在 1 个周期后更新。

所以我的计划是使用for循环从网络中获取所有权重 在训练之前我会在 1 之后执行optimizer.step()。这两次我都会将这些权重完全分开存储在 2 个 Python 列表中,以便稍后比较它们的结果。好吧,出于某种原因,如果我将它们与以下两个列表进行比较,它们是完全相同的torch.equal()我想这是因为也许内存中仍然存在某种隐藏的链接?所以我尝试使用.detach()当我从循环中抓住权重时,结果仍然相同。在这种情况下,第 2 层的权重应该有所不同,因为它应该包含训练前来自网络的权重。

在下面的代码中注意到我实际上使用了layer1并忽略了layer2。

完整代码:

class mymodel(nn.Module):
    def __init__(self):
        super().__init__() 
        self.layer1 = nn.Linear(10, 5)
        self.layer2 = nn.Conv2d(1, 5, 4, 2, 1)
        self.act = nn.Sigmoid()
    def forward(self, x):
        x = self.layer1(x) #only layer1 and act are used layer 2 is ignored so only layer1 and act's weight should be updated
        x = self.act(x)
        return x
model = mymodel()

weights = []

for param in model.parameters(): # loop the weights in the model before updating and store them
    print(param.size())
    weights.append(param)

critertion = nn.BCELoss() #criterion and optimizer setup
optimizer = optim.Adam(model.parameters(), lr = 0.001)

foo = torch.randn(3, 10) #fake input
target = torch.randn(3, 5) #fake target

result = model(foo) #predictions and comparison and backprop
loss = criterion(result, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()


weights_after_backprop = [] # weights after backprop
for param in model.parameters():
    weights_after_backprop.append(param) # only layer1's weight should update, layer2 is not used

for i in zip(weights, weights_after_backprop):
    print(torch.equal(i[0], i[1]))

# **prints all Trues when "layer1" and "act" should be different, I have also tried to call param.detach in the loop but I got the same result.

你必须clone参数,否则您只需复制参考。

weights = []

for param in model.parameters():
    weights.append(param.clone())

criterion = nn.BCELoss() # criterion and optimizer setup
optimizer = optim.Adam(model.parameters(), lr=0.001)

foo = torch.randn(3, 10) # fake input
target = torch.randn(3, 5) # fake target

result = model(foo) # predictions and comparison and backprop
loss = criterion(result, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()


weights_after_backprop = [] # weights after backprop
for param in model.parameters():
    weights_after_backprop.append(param.clone()) # only layer1's weight should update, layer2 is not used

for i in zip(weights, weights_after_backprop):
    print(torch.equal(i[0], i[1]))

这使

False
False
True
True
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在 Pytorch 中,当我复制网络权重时,它会在反向传播后自动更新? 的相关文章

随机推荐