问题:PyTorch:使用 numpy 数组为 GRU / LSTM 手动设置权重参数

我正在尝试用 pytorch 中手动定义的参数填充 GRU/LSTM。

我有参数的 numpy 数组,其形状在其文档中定义(https://pytorch.org/docs/stable/nn.html#torch.nn.GRU)。

它似乎有效,但我不确定返回的值是否正确。

这是用 numpy 参数填充 GRU/LSTM 的正确方法吗?

gru = nn.GRU(input_size, hidden_size, num_layers,
              bias=True, batch_first=False, dropout=dropout, bidirectional=bidirectional)

def set_nn_wih(layer, parameter_name, w, l0=True):
    param = getattr(layer, parameter_name)
    if l0:
        for i in range(3*hidden_size):
            param.data[i] = w[i*input_size:(i+1)*input_size]
    else:
        for i in range(3*hidden_size):
            param.data[i] = w[i*num_directions*hidden_size:(i+1)*num_directions*hidden_size]

def set_nn_whh(layer, parameter_name, w):
    param = getattr(layer, parameter_name)
    for i in range(3*hidden_size):
        param.data[i] = w[i*hidden_size:(i+1)*hidden_size]

l0=True

for i in range(num_directions):
    for j in range(num_layers):
        if j == 0:
            wih = w0[i, :, :3*input_size]
            whh = w0[i, :, 3*input_size:]  # check
            l0=True
        else:
            wih = w[j-1, i, :, :num_directions*3*hidden_size]
            whh = w[j-1, i, :, num_directions*3*hidden_size:]
            l0=False

        if i == 0:
            set_nn_wih(
                gru, "weight_ih_l{}".format(j), torch.from_numpy(wih.flatten()),l0)
            set_nn_whh(
                gru, "weight_hh_l{}".format(j), torch.from_numpy(whh.flatten()))
        else:
            set_nn_wih(
                gru, "weight_ih_l{}_reverse".format(j), torch.from_numpy(wih.flatten()),l0)
            set_nn_whh(
                gru, "weight_hh_l{}_reverse".format(j), torch.from_numpy(whh.flatten()))

y, hn = gru(x_t, h_t)

numpy 数组定义如下:

rng = np.random.RandomState(313)
w0 = rng.randn(num_directions, hidden_size, 3*(input_size +
               hidden_size)).astype(np.float32)
w = rng.randn(max(1, num_layers-1), num_directions, hidden_size,
              3*(num_directions*hidden_size + hidden_size)).astype(np.float32)

解答

这是一个很好的问题,你已经给出了一个不错的答案。然而,它重新发明了轮子——有一个非常优雅的 Pytorch 内部例程,可以让你不费吹灰之力地做同样的事情——并且适用于任何网络。

这里的核心概念是 PyTorch 的state_dict。状态字典有效地包含由nn.Modules及其子模块等关系给出的树结构组织的parameters

简短回答

如果您只希望代码使用state_dict将值加载到张量中,请尝试此行(其中dict包含有效的state_dict):

`model.load_state_dict(dict, strict=False)`

如果您只想加载一些参数值,其中strict=False至关重要。

长答案——包括对 PyTorch 的state_dict的介绍

这是一个状态字典如何查找 GRU 的示例(我选择了input_size = hidden_size = 2以便我可以打印整个状态字典):

rnn = torch.nn.GRU(2, 2, 1)
rnn.state_dict()
# Out[10]: 
#     OrderedDict([('weight_ih_l0', tensor([[-0.0023, -0.0460],
#                         [ 0.3373,  0.0070],
#                         [ 0.0745, -0.5345],
#                         [ 0.5347, -0.2373],
#                         [-0.2217, -0.2824],
#                         [-0.2983,  0.4771]])),
#                 ('weight_hh_l0', tensor([[-0.2837, -0.0571],
#                         [-0.1820,  0.6963],
#                         [ 0.4978, -0.6342],
#                         [ 0.0366,  0.2156],
#                         [ 0.5009,  0.4382],
#                         [-0.7012, -0.5157]])),
#                 ('bias_ih_l0',
#                 tensor([-0.2158, -0.6643, -0.3505, -0.0959, -0.5332, -0.6209])),
#                 ('bias_hh_l0',
#                 tensor([-0.1845,  0.4075, -0.1721, -0.4893, -0.2427,  0.3973]))])

所以state_dict网络的所有参数。如果我们“嵌套”了nn.Modules,我们会得到由参数名称表示的树:

class MLP(torch.nn.Module):      
    def __init__(self):
        torch.nn.Module.__init__(self)
        self.lin_a = torch.nn.Linear(2, 2)
        self.lin_b = torch.nn.Linear(2, 2)


mlp = MLP()
mlp.state_dict()
#    Out[23]: 
#        OrderedDict([('lin_a.weight', tensor([[-0.2914,  0.0791],
#                            [-0.1167,  0.6591]])),
#                    ('lin_a.bias', tensor([-0.2745, -0.1614])),
#                    ('lin_b.weight', tensor([[-0.4634, -0.2649],
#                            [ 0.4552,  0.3812]])),
#                    ('lin_b.bias', tensor([ 0.0273, -0.1283]))])


class NestedMLP(torch.nn.Module):
    def __init__(self):
        torch.nn.Module.__init__(self)
        self.mlp_a = MLP()
        self.mlp_b = MLP()


n_mlp = NestedMLP()
n_mlp.state_dict()
#   Out[26]: 
#        OrderedDict([('mlp_a.lin_a.weight', tensor([[ 0.2543,  0.3412],
#                            [-0.1984, -0.3235]])),
#                    ('mlp_a.lin_a.bias', tensor([ 0.2480, -0.0631])),
#                    ('mlp_a.lin_b.weight', tensor([[-0.4575, -0.6072],
#                            [-0.0100,  0.5887]])),
#                    ('mlp_a.lin_b.bias', tensor([-0.3116,  0.5603])),
#                    ('mlp_b.lin_a.weight', tensor([[ 0.3722,  0.6940],
#                            [-0.5120,  0.5414]])),
#                    ('mlp_b.lin_a.bias', tensor([0.3604, 0.0316])),
#                    ('mlp_b.lin_b.weight', tensor([[-0.5571,  0.0830],
#                            [ 0.5230, -0.1020]])),
#                    ('mlp_b.lin_b.bias', tensor([ 0.2156, -0.2930]))])

那么——如果你不想提取状态字典,而是改变它——从而改变网络的参数怎么办?使用nn.Module.load_state_dict(state_dict, strict=True)(链接到文档) 只要键(即参数名称)正确且值(即参数)是正确形状的torch.tensors。如果strictkwarg 设置为True(默认值),则加载的 dict 必须与原始状态 dict 完全匹配,但参数的值除外。也就是说,每个参数都必须有一个新值。

对于上面的 GRU 示例,我们需要为每个'weight_ih_l0', 'weight_hh_l0', 'bias_ih_l0', 'bias_hh_l0'提供正确大小的张量(以及正确的设备,顺便说一句)。由于我们有时只想加载 some 值(正如我认为您想要做的那样),我们可以将strictkwarg 设置为False- 然后我们可以只加载部分状态字典,例如一个只包含'weight_ih_l0'的参数值。

作为一个实用的建议,我只需创建要加载值的模型,然后打印状态字典(或至少一个键列表和相应的张量大小)

print([k, v.shape for k, v in model.state_dict().items()])

这会告诉您要更改的参数的确切名称。然后,您只需使用相应的参数名称和张量创建一个状态字典,然后加载它:

from dollections import OrderedDict
new_state_dict = OrderedDict({'tensor_name_retrieved_from_original_dict': new_tensor_value})
model.load_state_dict(new_state_dict, strict=False)
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐