【问题标题】:Pytorch Global Pruning is not reducing the size of the modelPytorch Global Pruning 不会减少模型的大小
【发布时间】:2021-04-25 20:24:26
【问题描述】:

我正在尝试通过全局修剪来修剪我的深度学习模型。原始的 UnPruned 模型约为 77.5 MB。但是修剪后,当我保存模型时,模型的大小与原始大小相同。谁能帮我解决这个问题?

以下是修剪代码:-

import torch.nn.utils.prune as prune

parameters_to_prune = (
(model.encoder[0], ‘weight’),
(model.up_conv1[0], ‘weight’),
(model.up_conv2[0], ‘weight’),
(model.up_conv3[0], ‘weight’),
)
print(parameters_to_prune)

prune.global_unstructured(
parameters_to_prune,
pruning_method=prune.L1Unstructured,
amount=0.2,
)

print(
“Sparsity in Encoder.weight: {:.2f}%”.format(
100. * float(torch.sum(model.encoder[0].weight == 0))
/ float(model.encoder[0].weight.nelement())
)
)
print(
“Sparsity in up_conv1.weight: {:.2f}%”.format(
100. * float(torch.sum(model.up_conv1[0].weight == 0))
/ float(model.up_conv1[0].weight.nelement())
)
)
print(
“Sparsity in up_conv2.weight: {:.2f}%”.format(
100. * float(torch.sum(model.up_conv2[0].weight == 0))
/ float(model.up_conv2[0].weight.nelement())
)
)
print(
“Sparsity in up_conv3.weight: {:.2f}%”.format(
100. * float(torch.sum(model.up_conv3[0].weight == 0))
/ float(model.up_conv3[0].weight.nelement())
)
)

print(
“Global sparsity: {:.2f}%”.format(
100. * float(
torch.sum(model.encoder[0].weight == 0)
+ torch.sum(model.up_conv1[0].weight == 0)
+ torch.sum(model.up_conv2[0].weight == 0)
+ torch.sum(model.up_conv3[0].weight == 0)
)
/ float(
model.encoder[0].weight.nelement()
+ model.up_conv1[0].weight.nelement()
+ model.up_conv2[0].weight.nelement()
+ model.up_conv3[0].weight.nelement()
)
)
)

**Setting Pruning to Permanent**
prune.remove(model.encoder[0], “weight”)
prune.remove(model.up_conv1[0], “weight”)
prune.remove(model.up_conv2[0], “weight”)
prune.remove(model.up_conv3[0], “weight”)

**Saving the model**
PATH = “C:\PrunedNet.pt”
torch.save(model.state_dict(), PATH)

【问题讨论】:

    标签: deep-learning computer-vision pytorch vision pruning


    【解决方案1】:

    如果像这样应用,修剪不会改变模型大小

    如果你有张量,可以这样说:

    [1., 2., 3., 4., 5., 6., 7., 8.]
    

    然后你修剪 50% 的数据,例如:

    [1., 2., 0., 4., 0., 6., 0., 0.]
    

    您仍将拥有 8 浮点值,并且它们的大小将相同。

    何时修剪会减小模型大小?

    • 当我们以稀疏格式保存权重,但它应该具有高稀疏性(因此 10% 的非零元素)
    • 当我们实际移除某些东西时(例如来自 Conv2d 的内核,如果它的权重为零或可忽略不计,则可以将其移除)

    否则它将无法正常工作。查看一些相关项目,这些项目可以让您无需自己编写代码即可完成,例如 Torch-Pruning

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 2015-10-07
      • 2021-07-25
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2018-01-14
      • 1970-01-01
      相关资源
      最近更新 更多