/usr/local/lib64/python3.6/site-packages/torch/nn/utils/__pycache__
NameSizeModeActions
clip_grad.cpython-36.pyc39470644editdlrm
convert_parameters.cpython-36.pyc23450644editdlrm
fusion.cpython-36.pyc15280644editdlrm
init.cpython-36.pyc22840644editdlrm
memory_format.cpython-36.pyc37630644editdlrm
parametrizations.cpython-36.pyc149990644editdlrm
parametrize.cpython-36.pyc198700644editdlrm
prune.cpython-36.pyc455570644editdlrm
rnn.cpython-36.pyc159340644editdlrm
spectral_norm.cpython-36.pyc96420644editdlrm
weight_norm.cpython-36.pyc46070644editdlrm
__init__.cpython-36.pyc7320644editdlrm
Edit: /usr/local/lib64/python3.6/site-packages/torch/nn/utils/__pycache__/prune.cpython-36.pyc (45557B)
3 Eg|@s>dZddlZddlmZmZddlmZddlmZddl Z GdddeZ Gdd d e Z Gd d d e Z Gd d d e Z Gddde ZGddde ZGddde ZGddde ZddZddZd4ddZddZd5ddZd6d d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3Z dS)7z Pruning methods N)ABCabstractmethod)Iterable)Tuplec@s^eZdZUdZeddZddZeddZ dd Z e d d d d Z dddZ ddZd S)BasePruningMethodzAbstract base class for creation of new pruning techniques. Provides a skeleton for customization requiring the overriding of methods such as :meth:`compute_mask` and :meth:`apply`. cCsdS)N)selfrr@/usr/local/lib64/python3.6/site-packages/torch/nn/utils/prune.py__init__szBasePruningMethod.__init__cCst||j|j|dS)aWMultiplies the mask (stored in ``module[name + '_mask']``) into the original tensor (stored in ``module[name + '_orig']``) and stores the result into ``module[name]`` by using :meth:`apply_mask`. Args: module (nn.Module): module containing the tensor to prune inputs: not used. N)setattr _tensor_name apply_mask)rmoduleinputsrrr __call__s zBasePruningMethod.__call__cCsdS)aComputes and returns a mask for the input tensor ``t``. Starting from a base ``default_mask`` (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the ``default_mask`` according to the specific pruning method recipe. Args: t (torch.Tensor): tensor representing the importance scores of the parameter to prune. default_mask (torch.Tensor): Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as ``t``. Returns: mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` Nr)rt default_maskrrr compute_mask#szBasePruningMethod.compute_maskcCsN|jdk stdj|t||jd}t||jd}|j|jd|}|S)aSimply handles the multiplication between the parameter being pruned and the generated mask. Fetches the mask and the original tensor from the module and returns the pruned version of the tensor. Args: module (nn.Module): module containing the tensor to prune Returns: pruned_tensor (torch.Tensor): pruned version of the input tensor NzModule {} has to be pruned_mask_orig)dtype)r AssertionErrorformatgetattrtor)rrmaskorigZ pruned_tensorrrr r 7s zBasePruningMethod.apply_maskN)importance_scoresc Os8dd}||||f||}t||}|dk rL|j|jksPtdj||n|}t|ts~|j|d||j|=tj |} nt||dj j tj d} y>|j || d} |j|d| t|||j||j|WnZtk r2} z._get_composite_methodNzRimportance_scores should have the same shape as parameter {} of {}rr) memory_format)r)rshaperrr!r#Zregister_parameter _parameterstorch ones_likedetachclonecontiguous_formatrZregister_bufferr r Zregister_forward_pre_hook Exception) r%rr&rr'r(r.r,rrrerrr applyMs41        zBasePruningMethod.applycCsJ|dk r|j|jks"tdn|}|dk r.|ntj|}||j||dS)aComputes and returns a pruned version of input tensor ``t`` according to the pruning rule specified in :meth:`compute_mask`. Args: t (torch.Tensor): tensor to prune (of same dimensions as ``default_mask``). importance_scores (torch.Tensor): tensor of importance scores (of same shape as ``t``) used to compute mask for pruning ``t``. The values in this tensor indicate the importance of the corresponding elements in the ``t`` that is being pruned. If unspecified or None, the tensor ``t`` will be used in its place. default_mask (torch.Tensor, optional): mask from previous pruning iteration, if any. To be considered when determining what portion of the tensor that pruning should act on. If None, default to a mask of ones. Returns: pruned version of tensor ``t``. Nz8importance_scores should have the same shape as tensor t)r)r0rr2r3r)rrrrrrr prunes zBasePruningMethod.prunecCs|jdk stdj||j|}t||jr:t||j|j|jd}|j|_|j|jd=|j|jd=t ||j|dS)arRemoves the pruning reparameterization from a module. The pruned parameter named ``name`` remains permanently pruned, and the parameter named ``name+'_orig'`` is removed from the parameter list. Similarly, the buffer named ``name+'_mask'`` is removed from the buffers. Note: Pruning itself is NOT undone or reversed! NzCModule {} has to be pruned before pruning can be removedrr) r rrr hasattrdelattrr1dataZ_buffersr )rrZweightrrrr removes    zBasePruningMethod.remove)NN)__name__ __module__ __qualname____doc__strr r rrrr classmethodr9r:r>rrrr r s   rc@s@eZdZdZddZddZddZdd Zd d Zd d Z dS)r#aContainer holding a sequence of pruning methods for iterative pruning. Keeps track of the order in which pruning methods are applied and handles combining successive pruning calls. Accepts as argument an instance of a BasePruningMethod or an iterable of them. cGsjt|_t|ts&|j|_|j|n@t|dkrN|dj|_|j|dnx|D]}|j|qTWdS)Nrr)tuple_pruning_methodsr!rr r$len)rr'r,rrr r s     zPruningContainer.__init__cCsnt|t r(|dk r(tdjt|n2|dk rZ|j|jkrZtdj|j|dj|j|j|f7_dS)zAdds a child pruning ``method`` to the container. Args: method (subclass of BasePruningMethod): child pruning method to be added to the container. Nz&{} is not a BasePruningMethod subclasszWCan only add pruning methods acting on the parameter named '{}' to PruningContainer {}.z Found '{}')r!r TypeErrorrtyper ValueErrorrF)rr,rrr r$!sz#PruningContainer.add_pruning_methodcCs t|jS)N)rGrF)rrrr __len__8szPruningContainer.__len__cCs t|jS)N)iterrF)rrrr __iter__;szPruningContainer.__iter__cCs |j|S)N)rF)ridxrrr __getitem__>szPruningContainer.__getitem__cCs"dd}|jd}||||}|S)aApplies the latest ``method`` by computing the new partial masks and returning its combination with the ``default_mask``. The new partial mask should be computed on the entries or channels that were not zeroed out by the ``default_mask``. Which portions of the tensor ``t`` the new mask will be calculated from depends on the ``PRUNING_TYPE`` (handled by the type handler): * for 'unstructured', the mask will be computed from the raveled list of nonmasked entries; * for 'structured', the mask will be computed from the nonmasked channels in the tensor; * for 'global', the mask will be computed across all entries. Args: t (torch.Tensor): tensor representing the parameter to prune (of same dimensions as ``default_mask``). default_mask (torch.Tensor): mask from previous pruning iteration. Returns: mask (torch.Tensor): new mask that combines the effects of the ``default_mask`` and the new mask from the current pruning ``method`` (of same dimensions as ``default_mask`` and ``t``). cs|}|j|jd}|jdkr&|dk}n|jdkrt|dsBtd|j}|jdkr`|dkrvtdj||jfd d t |Dd dk}t d g|}||<n4|jd krt |j }t d g|}nt dj|j|j||||d}|j|jd||<|S)aJ Args: method (a BasePruningMethod subclass): pruning method currently being applied. t (torch.Tensor): tensor representing the parameter to prune (of same dimensions as mask). mask (torch.Tensor): mask from previous pruning iteration Returns: new_mask (torch.Tensor): new mask that combines the effects of the old mask and the new mask from the current pruning method (of same dimensions as mask and t). )r unstructuredr structureddimzVPruning methods of PRUNING_TYPE "structured" need to have the attribute `dim` defined.rz4Index is out of bounds for tensor with dimensions {}csg|]}|kr|qSrr).0d)rRrr szIPruningContainer.compute_mask.._combine_masks..)rRNglobalzUnrecognized PRUNING_TYPE {})r)rr PRUNING_TYPEr;AttributeErrorrR IndexErrorrsumrangeslicerGr0rJr)r,rrZnew_maskslcZn_dimsZ keep_channelZ partial_maskr)rRr _combine_masks]s6    "   z5PruningContainer.compute_mask.._combine_masksr)rF)rrrr^r,rrrr rAsB  zPruningContainer.compute_maskN) r?r@rArBr r$rKrMrOrrrrr r# s r#cs0eZdZdZdZddZefddZZS)Identityz|Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones. rPcCs|}|S)Nr)rrrrrrr rszIdentity.compute_maskcstt|j||S)agAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. )superr`r9)r%rr&) __class__rr r9s zIdentity.apply) r?r@rArBrWrrDr9 __classcell__rr)rbr r`sr`cs8eZdZdZdZddZddZefddZZ S) RandomUnstructuredaPrune (currently unpruned) units in a tensor at random. Args: name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. rPcCst|||_dS)N)_validate_pruning_amount_initamount)rrfrrr r szRandomUnstructured.__init__cCsf|j}t|j|}t|||jtjd}|dkrbtj|}tj|j d|d}d|j d|j <|S)N)r/rr)r*r_r_) nelement_compute_nparams_toprunerf_validate_pruning_amountr5r2r6Z rand_liketopkviewindices)rrr tensor_sizenparams_toprunerprobrjrrr rs   zRandomUnstructured.compute_maskcstt|j|||dS)aAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. )rf)rardr9)r%rr&rf)rbrr r9szRandomUnstructured.apply) r?r@rArBrWr rrDr9rcrr)rbr rds  rdcs:eZdZdZdZddZddZed fdd ZZ S) L1UnstructuredazPrune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. rPcCst|||_dS)N)rerf)rrfrrr r szL1Unstructured.__init__cCsd|j}t|j|}t|||jtjd}|dkr`tjtj|j d|dd}d|j d|j <|S)N)r/rrF)r*largestr_r_) rgrhrfrir5r2r6rjabsrkrl)rrrrmrnrrjrrr rs  zL1Unstructured.compute_maskNcstt|j||||dS)aAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. importance_scores (torch.Tensor): tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. )rfr)rarpr9)r%rr&rfr)rbrr r9s zL1Unstructured.apply)N) r?r@rArBrWr rrDr9rcrr)rbr rps  rpcs<eZdZdZdZd ddZddZed fdd ZZ S)RandomStructuredaPrune entire (currently unpruned) channels in a tensor at random. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. dim (int, optional): index of the dim along which we define channels to prune. Default: -1. rQrcCst|||_||_dS)N)rerfrR)rrfrRrrr r EszRandomStructured.__init__cCsrt|t||j|j|j}t|j|}t||dd}|dkrL|}n"|||j||}||j|jd9}|S)aComputes and returns a mask for the input tensor ``t``. Starting from a base ``default_mask`` (which should be a mask of ones if the tensor has not been pruned yet), generate a random mask to apply on top of the ``default_mask`` by randomly zeroing out channels along the specified dim of the tensor. Args: t (torch.Tensor): tensor representing the parameter to prune default_mask (torch.Tensor): Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as ``t``. Returns: mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` Raises: IndexError: if ``self.dim >= len(t.shape)`` c SsTtj|}tj||dj}||k}tj|}tdgt|j}|||<d||<|S)N)r*r)r2ZrandZkthvaluevalues zeros_liker\rGr0) rrRZ nchannelsZnchannels_toprunero thresholdZ channel_maskrr]rrr make_maskrs  z0RandomStructured.compute_mask..make_maskr)r) _validate_structured_pruning_validate_pruning_dimrRr0rhrfrirr)rrrrmrnrwrrrr rKs    zRandomStructured.compute_maskcstt|j||||dS)aAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. dim (int, optional): index of the dim along which we define channels to prune. Default: -1. )rfrR)rarsr9)r%rr&rfrR)rbrr r9szRandomStructured.applyr_)r_r_)r_) r?r@rArBrWr rrDr9rcrr)rbr rs7s   >rscs<eZdZdZdZd ddZddZed fd d ZZ S) LnStructuredaiPrune entire (currently unpruned) channels in a tensor based on their L\ ``n``-norm. Args: amount (int or float): quantity of channels to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid entries for argument ``p`` in :func:`torch.norm`. dim (int, optional): index of the dim along which we define channels to prune. Default: -1. rQrcCst|||_||_||_dS)N)rerfnrR)rrfr{rRrrr r szLnStructured.__init__c Cst|t||j|j|j}t|j|}||}t||t||j|j}t j ||dd}dd}|dkrt|} n"|||j|j } | |j | j d9} | S)aComputes and returns a mask for the input tensor ``t``. Starting from a base ``default_mask`` (which should be a mask of ones if the tensor has not been pruned yet), generate a mask to apply on top of the ``default_mask`` by zeroing out the channels along the specified dim with the lowest L\ ``n``-norm. Args: t (torch.Tensor): tensor representing the parameter to prune default_mask (torch.Tensor): Base mask from previous pruning iterations, that need to be respected after the new mask is applied. Same dims as ``t``. Returns: mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t`` Raises: IndexError: if ``self.dim >= len(t.shape)`` T)r*rqcSs2tj|}tdgt|j}|||<d||<|S)Nr)r2rur\rGr0)rrRrlrr]rrr rws  z,LnStructured.compute_mask..make_maskr)r)rxryrRr0rhrfri _compute_normr{r2rjrlrr) rrrrmrnZnparams_tokeepnormrjrwrrrr rs     zLnStructured.compute_maskNcstt|j||||||dS)aAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid entries for argument ``p`` in :func:`torch.norm`. dim (int): index of the dim along which we define channels to prune. importance_scores (torch.Tensor): tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. )rfr{rRr)rarzr9)r%rr&rfr{rRr)rbrr r9s zLnStructured.applyr_)r_)N) r?r@rArBrWr rrDr9rcrr)rbr rzs   Erzcs4eZdZdZddZddZefddZZS)CustomFromMaskrVcCs ||_dS)N)r)rrrrr r szCustomFromMask.__init__cCs*|j|jjkst||jj|jd}|S)N)r)r0rrrr)rrrrrrr r#szCustomFromMask.compute_maskcstt|j|||dS)agAdds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. )r)rar~r9)r%rr&r)rbrr r9(s zCustomFromMask.apply) r?r@rArWr rrDr9rcrr)rbr r~sr~cCstj|||S)aApplies pruning reparametrization to the tensor corresponding to the parameter called ``name`` in ``module`` without actually pruning any units. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Note: The mask is a tensor of ones. Args: module (nn.Module): module containing the tensor to prune. name (str): parameter name within ``module`` on which pruning will act. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.identity(nn.Linear(2, 3), 'bias') >>> print(m.bias_mask) tensor([1., 1., 1.]) )r`r9)rr&rrr identity6s rcCstj||||S)aPrunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) units selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1) >>> torch.sum(m.weight_mask == 0) tensor(1) )rdr9)rr&rfrrr random_unstructuredVsrcCstj||||d|S)axPrunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified `amount` of (currently unpruned) units with the lowest L1-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. importance_scores (torch.Tensor): tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2) >>> m.state_dict().keys() odict_keys(['bias', 'weight_orig', 'weight_mask']) )rfr)rpr9)rr&rfrrrr l1_unstructuredxs#rcCstj|||||S)aPrunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. dim (int): index of the dim along which we define channels to prune. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.random_structured( nn.Linear(5, 3), 'weight', amount=3, dim=1 ) >>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0)) >>> print(columns_pruned) 3 )rsr9)rr&rfrRrrr random_structureds"rcCstj||||||d|S)aOPrunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` with the lowest L\ ``n``-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid entries for argument ``p`` in :func:`torch.norm`. dim (int): index of the dim along which we define channels to prune. importance_scores (torch.Tensor): tensor of importance scores (of same shape as module parameter) used to compute mask for pruning. The values in this tensor indicate the importance of the corresponding elements in the parameter being pruned. If unspecified or None, the module parameter will be used in its place. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.ln_structured( nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf') ) )r)rzr9)rr&rfr{rRrrrr ln_structureds&rc st|tstddk rnitts4tdtjjjfdd|D}tjjjdd|D}t}d|_ |f|}d|_ |j dkrtd j ||j |j ||j ||}d } xN|D]F\} } t| | } | j} || | | j| }t| | |d | | 7} qWdS) aD Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: parameters (Iterable of (module, name) tuples): parameters of the model to prune in a global fashion, i.e. by aggregating all weights prior to deciding which ones to prune. module must be of type :class:`nn.Module`, and name must be a string. pruning_method (function): a valid pruning function from this module, or a custom one implemented by the user that satisfies the implementation guidelines and has ``PRUNING_TYPE='unstructured'``. importance_scores (dict): a dictionary mapping (module, name) tuples to the corresponding parameter's importance scores tensor. The tensor should be the same shape as the parameter, and is used for computing mask for pruning. If unspecified or None, the parameter will be used in place of its importance scores. kwargs: other keyword arguments such as: amount (int or float): quantity of parameters to prune across the specified parameters. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute number of parameters to prune. Raises: TypeError: if ``PRUNING_TYPE != 'unstructured'`` Note: Since global structured pruning doesn't make much sense unless the norm is normalized by the size of the parameter, we now limit the scope of global pruning to unstructured methods. Examples: >>> net = nn.Sequential(OrderedDict([ ('first', nn.Linear(10, 4)), ('second', nn.Linear(4, 1)), ])) >>> parameters_to_prune = ( (net.first, 'weight'), (net.second, 'weight'), ) >>> prune.global_unstructured( parameters_to_prune, pruning_method=prune.L1Unstructured, amount=10, ) >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0)) tensor(10, dtype=torch.uint8) z4global_unstructured(): parameters is not an IterableNz=global_unstructured(): importance_scores must be of type dictcs&g|]\}}j||ft||qSr)getr)rSrr&)rrr rU9sz'global_unstructured..c Ss,g|]$\}}t||dtjt||qS)r)rr2r3)rSrr&rrr rUAstemprPz_Only "unstructured" PRUNING_TYPE supported for the `pruning_method`. Found method {} of type {}r)r)r!rrHdictr2nnutilsZparameters_to_vectorr#r rWrr$rrZnumelZview_ascustom_from_mask) parametersZpruning_methodrr(Zrelevant_importance_scoresrr-r,Z final_maskpointerrr&paramZ num_paramZ param_maskr)rr global_unstructureds8<           rcCstj||||S)a Prunes tensor corresponding to parameter called ``name`` in ``module`` by applying the pre-computed mask in ``mask``. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. 2) replacing the parameter ``name`` by its pruned version, while the original (unpruned) parameter is stored in a new parameter named ``name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. mask (Tensor): binary mask to be applied to the parameter. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.custom_from_mask( nn.Linear(5, 3), name='bias', mask=torch.tensor([0, 1, 0]) ) >>> print(m.bias_mask) tensor([0., 1., 0.]) )r~r9)rr&rrrr rksrcCsVx@|jjD]2\}}t|tr |j|kr |j||j|=|Sq Wtdj||dS)aRemoves the pruning reparameterization from a module and the pruning method from the forward hook. The pruned parameter named ``name`` remains permanently pruned, and the parameter named ``name+'_orig'`` is removed from the parameter list. Similarly, the buffer named ``name+'_mask'`` is removed from the buffers. Note: Pruning itself is NOT undone or reversed! Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. Examples: >>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2) >>> m = remove(m, name='weight') zJParameter '{}' of module {} has to be pruned before pruning can be removedN)rr r!rr r>rJr)rr&r*r+rrr r>s r>cCs@x:|jD].\}}x$|jjD]\}}t|trdSqWq WdS)aCheck whether ``module`` is pruned by looking for ``forward_pre_hooks`` in its modules that inherit from the :class:`BasePruningMethod`. Args: module (nn.Module): object that is either pruned or unpruned Returns: binary answer to whether ``module`` is pruned. Examples: >>> m = nn.Linear(5, 7) >>> print(prune.is_pruned(m)) False >>> prune.random_unstructured(m, name='weight', amount=0.2) >>> print(prune.is_pruned(m)) True TF)Z named_modulesrr r!r)r_ submoduler+rrr is_pruneds   rcCsft|tjstdj|t|tjr.|dksTt|tj rbt|dksTt|dkrbtdj|dS)aValidation helper to check the range of amount at init. Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. Raises: ValueError: if amount is a float not in [0, 1], or if it's a negative integer. TypeError: if amount is neither a float nor an integer. Note: This does not take into account the number of parameters in the tensor to be pruned, which is known only at prune. z2Invalid type for amount: {}. Must be int or float.rg?gzPamount={} should either be a float in the range [0, 1] or a non-negative integerN)r!numbersRealrHrIntegralfloatrJ)rfrrr res  recCs(t|tjr$||kr$tdj||dS)aValidation helper to check that the amount of parameters to prune is meaningful wrt to the size of the data (`tensor_size`). Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. tensor_size (int): absolute number of parameters in the tensor to prune. zEamount={} should be smaller than the number of parameters to prune={}N)r!rrrJr)rfrmrrr risricCs*|j}t|dkr&tdj|t|dS)a#Validation helper to check that the tensor to be pruned is multi- dimensional, such that the concept of "channels" is well-defined. Args: t (torch.Tensor): tensor representing the parameter to prune Raises: ValueError: if the tensor `t` is not at least 2D. rziStructured pruning can only be applied to multidimensional tensors. Found tensor of shape {} with {} dimsN)r0rGrJr)rr0rrr rxs  rxcCs$t|tjr|Stt||SdS)aSince amount can be expressed either in absolute value or as a percentage of the number of units/channels in a tensor, this utility function converts the percentage to absolute value to standardize the handling of pruning. Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameters to prune. tensor_size (int): absolute number of parameters in the tensor to prune. Returns: int: the number of units to prune in the tensor N)r!rrintround)rfrmrrr rhs rhcCs"||jkrtdj||jdS)z Args: t (torch.Tensor): tensor representing the parameter to prune dim (int): index of the dim along which we define channels to prune z&Invalid index {} for tensor of size {}N)rRrYrr0)rrRrrr ry)s rycCs>tt|j}|dkr ||}|j|tj|||d}|S)aCompute the L_n-norm across all entries in tensor `t` along all dimension except for the one identified by dim. Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim), then norm will have Size [4], and each entry will represent the `L_n`-norm computed using the 3x2=6 entries for each of the 4 channels. Args: t (torch.Tensor): tensor representing the parameter to prune n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid entries for argument p in torch.norm dim (int): dim identifying the channels to prune Returns: norm (torch.Tensor): L_n norm computed across all dimensions except for `dim`. By construction, `norm.shape = t.shape[-1]`. r)prR)listr[rRr>r2r})rr{rRZdimsr}rrr r|3s  r|)N)N)N)!rBrabcrrcollections.abcrtypingrr2rr#r`rdrprsrzr~rrrrrrrr>rrerirxrhryr|rrrr s>  9Af " )& , x!"