将权重和偏差转换为稀疏张量 pytorch

Convert weight and bias to sparse tensor pytorch

我正在尝试将 torch.nn.Parameters 转换为稀疏张量。 Pytorch 文档说 Parameters 是一个 Tensor's 子类。张量支持 to_sparse 方法,但如果我将 Parameters 转换为稀疏,它会给我:
TypeError: cannot assign 'torch.cuda.sparse.FloatTensor' as parameter 'weight' (torch.nn.Parameter or None expected)
有没有办法绕过这个并使用稀疏张量作为参数?
这是产生问题的示例代码:

for name, module in net.named_modules():
    if isinstance(module, torch.nn.Conv2d):
        module.weight = module.weight.data.to_sparse()
        module.bias = module.bias.data.to_sparse()

torch.Tensor.to_sparse() returns 不能分配给 module.weight 的张量的稀疏副本,因为这是 torch.nn.Parameter 的一个实例。所以,你应该这样做:

module.weight = torch.nn.Parameter(module.weight.data.to_sparse())
module.bias = torch.nn.Parameter(module.bias.data.to_sparse())

请注意,Parameters是一种特定类型的张量,被标记为来自nn.Module的参数,因此它们与普通张量不同。