簡體   English   中英

Pytorch 全局修剪不會減小 model 的大小

[英]Pytorch Global Pruning is not reducing the size of the model

我正在嘗試通過全局修剪修剪我的深度學習 model。 原始的未修剪 model 約為 77.5 MB。 但是修剪后,當我保存 model 時,model 的大小與原始大小相同。 誰能幫我解決這個問題?

以下是修剪代碼:-

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)

如果像這樣應用,修剪不會改變 model 大小

如果你有張量,可以這樣說:

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

你修剪了50%的數據,例如:

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

您仍然會有8個浮點值,並且它們的大小相同。

修剪時減小 model 大小?

  • 當我們以稀疏格式保存權重,但它應該具有高稀疏性(因此 10% 非零元素)
  • 當我們實際刪除某些東西時(例如來自 Conv2d 的Conv2d ,如果它的權重為零或可忽略不計,則可以將其刪除)

否則它將無法正常工作。 查看一些相關項目,這些項目可以讓您無需自己編寫代碼就可以完成,例如Torch-Pruning

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM