快捷键

LazyModuleMixin

类 torch.nn.modules.lazy.LazyModuleMixin(*args, **kwargs)[source][source] ¶

用于模块懒加载参数的混入类,也称为“懒模块”。

懒加载模块,或称为“懒模块”,从其前向方法的第一个输入中推导出其参数的形状。在第一次前向之前,它们包含不应访问或使用的 torch.nn.UninitializedParameter ,之后则包含常规的 torch.nn.Parameter 。懒模块很方便,因为它们不需要计算某些模块参数,例如典型 torch.nn.Linearin_features 参数。

在构建之后,带有懒加载模块的网络应首先转换为所需的 dtype 并放置在预期的设备上。这是因为懒加载模块仅执行形状推断,因此通常的 dtype 和设备放置行为适用。然后,懒加载模块应执行“干运行”,以初始化模块中的所有组件。这些“干运行”将正确大小、dtype 和设备的输入通过网络发送到每个懒加载模块。之后,网络可以像往常一样使用。

>>> class LazyMLP(torch.nn.Module):
...    def __init__(self) -> None:
...        super().__init__()
...        self.fc1 = torch.nn.LazyLinear(10)
...        self.relu1 = torch.nn.ReLU()
...        self.fc2 = torch.nn.LazyLinear(1)
...        self.relu2 = torch.nn.ReLU()
...
...    def forward(self, input):
...        x = self.relu1(self.fc1(input))
...        y = self.relu2(self.fc2(x))
...        return y
>>> # constructs a network with lazy modules
>>> lazy_mlp = LazyMLP()
>>> # transforms the network's device and dtype
>>> # NOTE: these transforms can and should be applied after construction and before any 'dry runs'
>>> lazy_mlp = lazy_mlp.cuda().double()
>>> lazy_mlp
LazyMLP( (fc1): LazyLinear(in_features=0, out_features=10, bias=True)
  (relu1): ReLU()
  (fc2): LazyLinear(in_features=0, out_features=1, bias=True)
  (relu2): ReLU()
)
>>> # performs a dry run to initialize the network's lazy modules
>>> lazy_mlp(torch.ones(10,10).cuda())
>>> # after initialization, LazyLinear modules become regular Linear modules
>>> lazy_mlp
LazyMLP(
  (fc1): Linear(in_features=10, out_features=10, bias=True)
  (relu1): ReLU()
  (fc2): Linear(in_features=10, out_features=1, bias=True)
  (relu2): ReLU()
)
>>> # attaches an optimizer, since parameters can now be used as usual
>>> optim = torch.optim.SGD(mlp.parameters(), lr=0.01)

使用懒加载模块时,需要注意的一个最终注意事项是,网络参数的初始化顺序可能会改变,因为懒加载模块总是在其他模块之后初始化。例如,如果上面定义的 LazyMLP 类首先定义了 torch.nn.LazyLinear 模块,然后是常规的 torch.nn.Linear 模块,则第二个模块将在构造时初始化,而第一个模块将在第一次干运行时初始化。这可能导致使用懒加载模块的网络参数的初始化与没有懒加载模块的网络参数的初始化不同,因为参数初始化的顺序通常取决于有状态的随机数生成器,这可能会不同。有关更多详细信息,请参阅可重现性部分。

懒加载模块可以像其他模块一样使用状态字典进行序列化。例如:

>>> lazy_mlp = LazyMLP()
>>> # The state dict shows the uninitialized parameters
>>> lazy_mlp.state_dict()
OrderedDict([('fc1.weight', Uninitialized parameter),
             ('fc1.bias',
              tensor([-1.8832e+25,  4.5636e-41, -1.8832e+25,  4.5636e-41, -6.1598e-30,
                       4.5637e-41, -1.8788e+22,  4.5636e-41, -2.0042e-31,  4.5637e-41])),
             ('fc2.weight', Uninitialized parameter),
             ('fc2.bias', tensor([0.0019]))])

懒加载模块可以加载常规模块(即,您可以序列化和反序列化初始化的 LazyModules,并且它们将保持初始化状态)

>>> full_mlp = LazyMLP()
>>> # Dry run to initialize another module
>>> full_mlp.forward(torch.ones(10, 1))
>>> # Load an initialized state into a lazy module
>>> lazy_mlp.load_state_dict(full_mlp.state_dict())
>>> # The state dict now holds valid values
>>> lazy_mlp.state_dict()
OrderedDict([('fc1.weight',
              tensor([[-0.3837],
                      [ 0.0907],
                      [ 0.6708],
                      [-0.5223],
                      [-0.9028],
                      [ 0.2851],
                      [-0.4537],
                      [ 0.6813],
                      [ 0.5766],
                      [-0.8678]])),
             ('fc1.bias',
              tensor([-1.8832e+25,  4.5636e-41, -1.8832e+25,  4.5636e-41, -6.1598e-30,
                       4.5637e-41, -1.8788e+22,  4.5636e-41, -2.0042e-31,  4.5637e-41])),
             ('fc2.weight',
              tensor([[ 0.1320,  0.2938,  0.0679,  0.2793,  0.1088, -0.1795, -0.2301,  0.2807,
                        0.2479,  0.1091]])),
             ('fc2.bias', tensor([0.0019]))])

然而,请注意,如果状态加载时已初始化,则在“干运行”期间不会替换加载的参数。这防止了在不同上下文中使用已初始化的模块。

has_uninitialized_params()[source][source]

检查模块是否有未初始化的参数。

initialize_parameters(*args, **kwargs)[source][source]

根据输入批次的属性初始化参数。

这在参数形状推理时将参数初始化与正向传递分离的接口。


© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源