如果我们将一个可训练参数与一个不可训练参数组合,那么原始的可训练参数是否仍然可训练?

11

我有两个神经网络,使用pytorch操作以某种花哨的方式组合它们的参数。我将结果存储在第三个神经网络中,该神经网络的参数被设置为不可训练。然后我通过这个新的神经网络传递数据。这个新的神经网络只是一个占位符:

placeholder_net.W = Op( not_trainable_net.W, trainable_net.W )

然后我传递数据:

output = placeholder_net(input)

我担心由于占位符网络的参数被设置为不可训练,它实际上不会训练应该训练的变量。这种情况会发生吗?或者当您将可训练参数与不可训练参数组合在一起时(然后将其设置为参数不可训练),结果是什么?


当前解决方案:

del net3.conv0.weight
net3.conv0.weight = net.conv0.weight + net2.conv0.weight

import torch
from torch import nn
import torch.optim as optim

import torchvision
import torchvision.transforms as transforms

from collections import OrderedDict

import copy

def dont_train(net):
    '''
    set training parameters to false.
    '''
    for param in net.parameters():
        param.requires_grad = False
    return net

def get_cifar10():
    transform = transforms.Compose(
        [transforms.ToTensor(),
         transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
    trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=4,shuffle=True, num_workers=2)
    classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck')
    return trainloader,classes



def combine_nets(net_train, net_no_train, net_place_holder):
        '''
            Combine nets in a way train net is trainable
        '''
        params_train = net_train.named_parameters()
        dict_params_place_holder = dict(net_place_holder.named_parameters())
        dict_params_no_train = dict(net_no_train.named_parameters())
        for name, param_train in params_train:
            if name in dict_params_place_holder:
                layer_name, param_name = name.split('.')
                param_no_train = dict_params_no_train[name]
                ## get place holder layer
                layer_place_holder = getattr(net_place_holder, layer_name)
                delattr(layer_place_holder, param_name)
                ## get new param
                W_new = param_train + param_no_train  # notice addition is just chosen for the sake of an example
                ## store param in placehoder net
                setattr(layer_place_holder, param_name, W_new)
        return net_place_holder

def combining_nets_lead_to_error():
    '''
    Intention is to only train the net with trainable params.
    Placeholder rnet is a dummy net, it doesn't actually do anything except hold the combination of params and its the
    net that does the forward pass on the data.
    '''
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    ''' create three musketeers '''
    net_train = nn.Sequential(OrderedDict([
          ('conv1', nn.Conv2d(1,20,5)),
          ('relu1', nn.ReLU()),
          ('conv2', nn.Conv2d(20,64,5)),
          ('relu2', nn.ReLU())
        ])).to(device)
    net_no_train = copy.deepcopy(net_train).to(device)
    net_place_holder = copy.deepcopy(net_train).to(device)
    ''' prepare train, hyperparams '''
    trainloader,classes = get_cifar10()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net_train.parameters(), lr=0.001, momentum=0.9)
    ''' train '''
    net_train.train()
    net_no_train.eval()
    net_place_holder.eval()
    for epoch in range(2):  # loop over the dataset multiple times
        running_loss = 0.0
        for i, (inputs, labels) in enumerate(trainloader, 0):
            optimizer.zero_grad() # zero the parameter gradients
            inputs, labels = inputs.to(device), labels.to(device)
            # combine nets
            net_place_holder = combine_nets(net_train,net_no_train,net_place_holder)
            #
            outputs = net_place_holder(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()
            # print statistics
            running_loss += loss.item()
            if i % 2000 == 1999:  # print every 2000 mini-batches
                print('[%d, %5d] loss: %.3f' %
                      (epoch + 1, i + 1, running_loss / 2000))
                running_loss = 0.0
    ''' DONE '''
    print('Done \a')

if __name__ == '__main__':
    combining_nets_lead_to_error()

如果我们将一个可训练参数与一个不可训练参数合并,那么原始的可训练参数是否仍然可训练? - Charlie Parker
相关:https://discuss.pytorch.org/t/trainable-variable-in-loss-function-and-matrix-multiplication/495 - Charlie Parker
也许有用,删除属性... https://discuss.pytorch.org/t/how-does-one-delete-layers-in-a-neural-network/17704 - Charlie Parker
3个回答

7
首先,任何网络都不应该使用eval()模式。将requires_grad标志设置为false,使参数对于仅第二个网络而言是不可训练的,并训练占位符网络。
如果这种方法行不通,您可以尝试以下我更喜欢的方法。
不要使用多个网络,而是使用单个网络,并在非线性层之前的每个可训练层后使用一个非可训练层作为并行连接。
例如,看一下这张图片:

enter image description here

将requires_grad标志设置为false,使参数不可训练。不要使用eval()并训练网络。
在非线性之前组合层的输出很重要。初始化平行层的参数,并选择后操作,以使其产生与组合参数相同的结果。

2
为什么在我的情况下使用eval对于任何网络都是不好/不正确的?只是好奇。 - Charlie Parker
像dropout或batchNormalization这样的模块在训练和评估过程中需要有不同的行为。仅仅冻结层/网络并不能得到所需的行为。这就像我们需要在非训练期间使用特定模块的额外模式一样。 - Ganesh
我只尝试了你的第一个选项,因为第二个选项对我来说更难做,因为我正在使用的网络已经被训练过了。所以我有两个网络在“微调彼此”。我无法确定它是否不起作用是因为代码有错误还是因为我使用的方法可能不起作用。也许一个好主意是制作一个大小为1的新数据集,并查看即使使用这种有趣的训练方法,它是否至少可以记忆一个数据点。 - Charlie Parker
好的,我认为第一个建议(至少对于我的代码)肯定不起作用,因为我刚刚在 cifar 10 上使用 W+0 训练了 W(0 是不可训练的参数),只使用了一个示例,但是网络无法学习这个示例。一定有什么问题... - Charlie Parker
请注意,只有当我使用“combine_nets”代码时它才无法正常工作。当我直接在网络上进行训练时,它当然会像预期的那样记忆单个示例。 - Charlie Parker

6

我不确定这是否是您想要了解的。

但是,如果我理解正确 - 您想知道使用不可训练可训练变量进行操作的结果是否仍然是可训练的?

如果是这样的话,确实如此,以下是一个示例:

>>> trainable = torch.ones(1, requires_grad=True)
>>> non_trainable = torch.ones(1, requires_grad=False)
>>> result = trainable + non_trainable
>>> result.requires_grad
True

也许您会发现torch.set_grad_enabled很有用,这里提供了一些示例(PyTorch版本0.4.0的迁移指南):https://pytorch.org/2018/04/22/0_4_0-migration-guide.html

我想知道的是,如果我使用交叉熵后更新结果(通过优化器类),是否只有可训练参数会改变。我猜我可以尝试一下,在optimizer.step()之后检查可训练内容的值是否发生了变化。 - Charlie Parker
你想先通过可训练网络来提供数据,然后再通过一个不可训练的网络,你的问题是第一个网络是否会被正确地训练? - MBT
不。我想用Op(例如您建议的求和)以任何我想要的方式组合两个网络,然后我想通过这个新网络传递数据,但只针对可训练网络进行训练(WLOG)。从语义上讲,新网络只是一个占位符,除了作为通过组合网络传递数据的一种方式(也许作为获取可训练网络梯度的一种方式)之外,它没有实际意义。 - Charlie Parker
其实我不认为这会是个问题,但我还没有尝试过。如果你对此有疑虑,可以先尝试一个类似结构的简单示例 - 祝好运! - MBT

5

以下是原始回答,我在这里解决你上传的额外代码。

在你的combine_nets函数中,你不必要地尝试删除并设置属性,而可以像这样简单地复制所需的值:

def combine_nets(net_train, net_no_train, net_place_holder):
    '''
        Combine nets in a way train net is trainable
    '''
    params_train = net_no_train.named_parameters()
    dict_params_place_holder = dict(net_place_holder.named_parameters())
    dict_params_no_train = dict(net_train.named_parameters())
    for name, param_train in params_train:
        if name in dict_params_place_holder:
            param_no_train = dict_params_no_train[name]
            W_new = param_train + param_no_train 
            dict_params_no_train[name].data.copy_(W_new.data)
    return net_place_holder

由于您提供的代码中存在其他错误,所以我无法在没有进一步更改的情况下运行它,因此我在下面附上了之前给您的代码的更新版本:

import torch
from torch import nn
from torch.autograd import Variable
import torch.optim as optim


# toy feed-forward net
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()

        self.fc1 = nn.Linear(10, 5)
        self.fc2 = nn.Linear(5, 5)
        self.fc3 = nn.Linear(5, 1)

    def forward(self, x):
        x = self.fc1(x)
        x = self.fc2(x)
        x = self.fc3(x)
        return x

def combine_nets(net_train, net_no_train, net_place_holder):
    '''
        Combine nets in a way train net is trainable
    '''
    params_train = net_no_train.named_parameters()
    dict_params_place_holder = dict(net_place_holder.named_parameters())
    dict_params_no_train = dict(net_train.named_parameters())
    for name, param_train in params_train:
        if name in dict_params_place_holder:
            param_no_train = dict_params_no_train[name]
            W_new = param_train + param_no_train
            dict_params_no_train[name].data.copy_(W_new.data)
return net_place_holder


# define random data
random_input1 = Variable(torch.randn(10,))
random_target1 = Variable(torch.randn(1,))
random_input2 = Variable(torch.rand(10,))
random_target2 = Variable(torch.rand(1,))
random_input3 = Variable(torch.randn(10,))
random_target3 = Variable(torch.randn(1,))

# define net
net1 = Net()
net_place_holder = Net()
net2 = Net()

# train the net1
criterion = nn.MSELoss()
optimizer = optim.SGD(net1.parameters(), lr=0.1)
for i in range(100):
    net1.zero_grad()
    output = net1(random_input1)
    loss = criterion(output, random_target1)
    loss.backward()
    optimizer.step()

# train the net2
criterion = nn.MSELoss()
optimizer = optim.SGD(net2.parameters(), lr=0.1)
for i in range(100):
    net2.zero_grad()
    output = net2(random_input2)
    loss = criterion(output, random_target2)
    loss.backward()
    optimizer.step()

# train the net2
criterion = nn.MSELoss()
optimizer = optim.SGD(net_place_holder.parameters(), lr=0.1)
for i in range(100):
    net_place_holder.zero_grad()
    output = net_place_holder(random_input3)
    loss = criterion(output, random_target3)
    loss.backward()
    optimizer.step()

print('#'*50)
print('Weights before combining')
print('')
print('net1 fc2 weight after train:')
print(net1.fc3.weight)
print('net2 fc2 weight after train:')
print(net2.fc3.weight)

combine_nets(net1, net2, net_place_holder)

print('#'*50)
print('')
print('Weights after combining')
print('net1 fc2 weight after train:')
print(net1.fc3.weight)
print('net2 fc2 weight after train:')
print(net2.fc3.weight)


# train the net
criterion = nn.MSELoss()
optimizer1 = optim.SGD(net1.parameters(), lr=0.1)
for i in range(100):
    net1.zero_grad()
    net2.zero_grad()
    output1 = net1(random_input3)
    output2 = net2(random_input3)
    loss1 = criterion(output1, random_target3)
    loss2 = criterion(output2, random_target3)
    loss = loss1 + loss2
    loss.backward()
    optimizer1.step()

print('#'*50)
print('Weights after further training')
print('')
print('net1 fc2 weight after freeze:')
print(net1.fc3.weight)
print('net2 fc2 weight after freeze:')
print(net2.fc3.weight)

那么我们不需要删除像conv0.weight这样的属性吗?这是我在pytorch论坛上得到的建议,但对我来说似乎很奇怪...我想我只需要确保正确的变量被插入计算树中,以便正确执行反向计算,对吗?我想的是有3个网络,2个是我要组合的真实网络,第3个只是一个占位符。将占位符设置为eval(),未经训练的网络也设置为eval。但另一个没有设置为eval。然后,占位符网络将保存组合以进行正确的前向计算。 - Charlie Parker
你的代码问题在于你缺少了一个关键部分,即我的代码中不起作用的网络组合。如果你尝试将一个网络的参数与另一个网络的参数组合起来...由于某些原因它就无法工作。 - Charlie Parker
@CharlieParker,为了明确起见,您想要拥有三个网络N1、N2、N3,并通过执行以下操作将它们合并成一个网络N4:对于每一层i:L1 * L3 + L2 * L3?您希望反向传播仅影响N1的变量吗? - ginge
不完全如此,但这应该足以解决我的问题。更像是我将2个参数组合起来,并希望通过net1进行反向传播。 - Charlie Parker
嗯,为什么你要使用原地操作来合并网络?我认为这会产生可训练网络的错误梯度... - Charlie Parker
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接