【问题标题】:How to prune the k% lowest weight by pytorch? [closed]如何通过pytorch修剪k%的最低权重? [关闭]
【发布时间】:2021-08-26 09:43:31
【问题描述】:

这里我从名为 Deep compression [Han et. al.] 使用 resnet18

我还使用以下代码,权重乘以掩码,以便它是被 k% 最低权重修剪为零的 after_weight。但是该代码对我不起作用。 任何有效的解决方案?

prune = float(0.1)
def prune_weights(torchweights):
    weights=np.abs(torchweights.cpu().numpy());
    weightshape=weights.shape
    rankedweights=weights.reshape(weights.size).argsort()#.reshape(weightshape)
    
    num = weights.size
    prune_num = int(np.round(num*prune))
    count=0
    masks = np.zeros_like(rankedweights)
    for n, rankedweight in enumerate(rankedweights):
        if rankedweight > prune_num:
            masks[n]=1
        else: count+=1
    print("total weights:", num)
    print("weights pruned:",count)
    
    masks=masks.reshape(weightshape)
    weights=masks*weights
    
    return torch.from_numpy(weights).cuda(), masks

# prune weights
# The pruned weight location is saved in the addressbook and maskbook.
# These will be used during training to keep the weights zero.
addressbook=[]
maskbook=[]
for k, v in net.state_dict().items():
    if "conv2" in k:
        addressbook.append(k)
        print("pruning layer:",k)
        weights=v
        weights, masks = prune_weights(weights)
        maskbook.append(masks)
        checkpoint['net'][k] = weights
        
checkpoint['address'] = addressbook
checkpoint['mask'] = maskbook
net.load_state_dict(checkpoint['net'])

【问题讨论】:

    标签: python pytorch pruning


    【解决方案1】:

    您可以使用torch.nn.utils.prune

    您似乎想删除每个Conv2D 层的 10%。如果是这种情况,您可以这样做:

    import torch
    import torch.nn.utils.prune as prune
    
    # load your model
    net = ?
    
    # in your example, you want to remove 10%
    prune_perc = 0.1
    
    for name, module in net.named_modules():
        if isinstance(module, torch.nn.Conv2d):
            prune.l1_unstructured(module, name='weight', amount=prune_perc)
    

    【讨论】:

    • 不完全一样。根据底部k%的权重百分比和剪枝,l1_unstructured是不同的。
    • @ChrisCheng 你能详细说明一下吗?有什么不同? docs 写道:“通过删除指定数量的(当前未修剪的)具有最低 L1 范数的单元来修剪 [...]。
    猜你喜欢
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    相关资源
    最近更新 更多