prune.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  1. r"""
  2. Pruning methods
  3. """
  4. import numbers
  5. from abc import ABC, abstractmethod
  6. from collections.abc import Iterable
  7. from typing import Tuple
  8. import torch
  9. class BasePruningMethod(ABC):
  10. r"""Abstract base class for creation of new pruning techniques.
  11. Provides a skeleton for customization requiring the overriding of methods
  12. such as :meth:`compute_mask` and :meth:`apply`.
  13. """
  14. _tensor_name: str
  15. def __init__(self):
  16. pass
  17. def __call__(self, module, inputs):
  18. r"""Multiplies the mask (stored in ``module[name + '_mask']``)
  19. into the original tensor (stored in ``module[name + '_orig']``)
  20. and stores the result into ``module[name]`` by using
  21. :meth:`apply_mask`.
  22. Args:
  23. module (nn.Module): module containing the tensor to prune
  24. inputs: not used.
  25. """
  26. setattr(module, self._tensor_name, self.apply_mask(module))
  27. @abstractmethod
  28. def compute_mask(self, t, default_mask):
  29. r"""Computes and returns a mask for the input tensor ``t``.
  30. Starting from a base ``default_mask`` (which should be a mask of ones
  31. if the tensor has not been pruned yet), generate a random mask to
  32. apply on top of the ``default_mask`` according to the specific pruning
  33. method recipe.
  34. Args:
  35. t (torch.Tensor): tensor representing the importance scores of the
  36. parameter to prune.
  37. default_mask (torch.Tensor): Base mask from previous pruning
  38. iterations, that need to be respected after the new mask is
  39. applied. Same dims as ``t``.
  40. Returns:
  41. mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
  42. """
  43. pass
  44. def apply_mask(self, module):
  45. r"""Simply handles the multiplication between the parameter being
  46. pruned and the generated mask.
  47. Fetches the mask and the original tensor from the module
  48. and returns the pruned version of the tensor.
  49. Args:
  50. module (nn.Module): module containing the tensor to prune
  51. Returns:
  52. pruned_tensor (torch.Tensor): pruned version of the input tensor
  53. """
  54. # to carry out the multiplication, the mask needs to have been computed,
  55. # so the pruning method must know what tensor it's operating on
  56. assert self._tensor_name is not None, "Module {} has to be pruned".format(
  57. module
  58. ) # this gets set in apply()
  59. mask = getattr(module, self._tensor_name + "_mask")
  60. orig = getattr(module, self._tensor_name + "_orig")
  61. pruned_tensor = mask.to(dtype=orig.dtype) * orig
  62. return pruned_tensor
  63. @classmethod
  64. def apply(cls, module, name, *args, importance_scores=None, **kwargs):
  65. r"""Adds the forward pre-hook that enables pruning on the fly and
  66. the reparametrization of a tensor in terms of the original tensor
  67. and the pruning mask.
  68. Args:
  69. module (nn.Module): module containing the tensor to prune
  70. name (str): parameter name within ``module`` on which pruning
  71. will act.
  72. args: arguments passed on to a subclass of
  73. :class:`BasePruningMethod`
  74. importance_scores (torch.Tensor): tensor of importance scores (of
  75. same shape as module parameter) used to compute mask for pruning.
  76. The values in this tensor indicate the importance of the
  77. corresponding elements in the parameter being pruned.
  78. If unspecified or None, the parameter will be used in its place.
  79. kwargs: keyword arguments passed on to a subclass of a
  80. :class:`BasePruningMethod`
  81. """
  82. def _get_composite_method(cls, module, name, *args, **kwargs):
  83. # Check if a pruning method has already been applied to
  84. # `module[name]`. If so, store that in `old_method`.
  85. old_method = None
  86. found = 0
  87. # there should technically be only 1 hook with hook.name == name
  88. # assert this using `found`
  89. hooks_to_remove = []
  90. for k, hook in module._forward_pre_hooks.items():
  91. # if it exists, take existing thing, remove hook, then
  92. # go through normal thing
  93. if isinstance(hook, BasePruningMethod) and hook._tensor_name == name:
  94. old_method = hook
  95. hooks_to_remove.append(k)
  96. found += 1
  97. assert (
  98. found <= 1
  99. ), "Avoid adding multiple pruning hooks to the\
  100. same tensor {} of module {}. Use a PruningContainer.".format(
  101. name, module
  102. )
  103. for k in hooks_to_remove:
  104. del module._forward_pre_hooks[k]
  105. # Apply the new pruning method, either from scratch or on top of
  106. # the previous one.
  107. method = cls(*args, **kwargs) # new pruning
  108. # Have the pruning method remember what tensor it's been applied to
  109. method._tensor_name = name
  110. # combine `methods` with `old_method`, if `old_method` exists
  111. if old_method is not None: # meaning that there was a hook
  112. # if the hook is already a pruning container, just add the
  113. # new pruning method to the container
  114. if isinstance(old_method, PruningContainer):
  115. old_method.add_pruning_method(method)
  116. method = old_method # rename old_method --> method
  117. # if the hook is simply a single pruning method, create a
  118. # container, add the old pruning method and the new one
  119. elif isinstance(old_method, BasePruningMethod):
  120. container = PruningContainer(old_method)
  121. # Have the pruning method remember the name of its tensor
  122. # setattr(container, '_tensor_name', name)
  123. container.add_pruning_method(method)
  124. method = container # rename container --> method
  125. return method
  126. method = _get_composite_method(cls, module, name, *args, **kwargs)
  127. # at this point we have no forward_pre_hooks but we could have an
  128. # active reparametrization of the tensor if another pruning method
  129. # had been applied (in which case `method` would be a PruningContainer
  130. # and not a simple pruning method).
  131. # Pruning is to be applied to the module's tensor named `name`,
  132. # starting from the state it is found in prior to this iteration of
  133. # pruning. The pruning mask is calculated based on importances scores.
  134. orig = getattr(module, name)
  135. if importance_scores is not None:
  136. assert (
  137. importance_scores.shape == orig.shape
  138. ), "importance_scores should have the same shape as parameter \
  139. {} of {}".format(
  140. name, module
  141. )
  142. else:
  143. importance_scores = orig
  144. # If this is the first time pruning is applied, take care of moving
  145. # the original tensor to a new parameter called name + '_orig' and
  146. # and deleting the original parameter
  147. if not isinstance(method, PruningContainer):
  148. # copy `module[name]` to `module[name + '_orig']`
  149. module.register_parameter(name + "_orig", orig)
  150. # temporarily delete `module[name]`
  151. del module._parameters[name]
  152. default_mask = torch.ones_like(orig) # temp
  153. # If this is not the first time pruning is applied, all of the above
  154. # has been done before in a previous pruning iteration, so we're good
  155. # to go
  156. else:
  157. default_mask = (
  158. getattr(module, name + "_mask")
  159. .detach()
  160. .clone(memory_format=torch.contiguous_format)
  161. )
  162. # Use try/except because if anything goes wrong with the mask
  163. # computation etc., you'd want to roll back.
  164. try:
  165. # get the final mask, computed according to the specific method
  166. mask = method.compute_mask(importance_scores, default_mask=default_mask)
  167. # reparametrize by saving mask to `module[name + '_mask']`...
  168. module.register_buffer(name + "_mask", mask)
  169. # ... and the new pruned tensor to `module[name]`
  170. setattr(module, name, method.apply_mask(module))
  171. # associate the pruning method to the module via a hook to
  172. # compute the function before every forward() (compile by run)
  173. module.register_forward_pre_hook(method)
  174. except Exception as e:
  175. if not isinstance(method, PruningContainer):
  176. orig = getattr(module, name + "_orig")
  177. module.register_parameter(name, orig)
  178. del module._parameters[name + "_orig"]
  179. raise e
  180. return method
  181. def prune(self, t, default_mask=None, importance_scores=None):
  182. r"""Computes and returns a pruned version of input tensor ``t``
  183. according to the pruning rule specified in :meth:`compute_mask`.
  184. Args:
  185. t (torch.Tensor): tensor to prune (of same dimensions as
  186. ``default_mask``).
  187. importance_scores (torch.Tensor): tensor of importance scores (of
  188. same shape as ``t``) used to compute mask for pruning ``t``.
  189. The values in this tensor indicate the importance of the
  190. corresponding elements in the ``t`` that is being pruned.
  191. If unspecified or None, the tensor ``t`` will be used in its place.
  192. default_mask (torch.Tensor, optional): mask from previous pruning
  193. iteration, if any. To be considered when determining what
  194. portion of the tensor that pruning should act on. If None,
  195. default to a mask of ones.
  196. Returns:
  197. pruned version of tensor ``t``.
  198. """
  199. if importance_scores is not None:
  200. assert (
  201. importance_scores.shape == t.shape
  202. ), "importance_scores should have the same shape as tensor t"
  203. else:
  204. importance_scores = t
  205. default_mask = default_mask if default_mask is not None else torch.ones_like(t)
  206. return t * self.compute_mask(importance_scores, default_mask=default_mask)
  207. def remove(self, module):
  208. r"""Removes the pruning reparameterization from a module. The pruned
  209. parameter named ``name`` remains permanently pruned, and the parameter
  210. named ``name+'_orig'`` is removed from the parameter list. Similarly,
  211. the buffer named ``name+'_mask'`` is removed from the buffers.
  212. Note:
  213. Pruning itself is NOT undone or reversed!
  214. """
  215. # before removing pruning from a tensor, it has to have been applied
  216. assert (
  217. self._tensor_name is not None
  218. ), "Module {} has to be pruned\
  219. before pruning can be removed".format(
  220. module
  221. ) # this gets set in apply()
  222. # to update module[name] to latest trained weights
  223. weight = self.apply_mask(module) # masked weights
  224. # delete and reset
  225. if hasattr(module, self._tensor_name):
  226. delattr(module, self._tensor_name)
  227. orig = module._parameters[self._tensor_name + "_orig"]
  228. orig.data = weight.data
  229. del module._parameters[self._tensor_name + "_orig"]
  230. del module._buffers[self._tensor_name + "_mask"]
  231. setattr(module, self._tensor_name, orig)
  232. class PruningContainer(BasePruningMethod):
  233. """Container holding a sequence of pruning methods for iterative pruning.
  234. Keeps track of the order in which pruning methods are applied and handles
  235. combining successive pruning calls.
  236. Accepts as argument an instance of a BasePruningMethod or an iterable of
  237. them.
  238. """
  239. def __init__(self, *args):
  240. self._pruning_methods: Tuple["BasePruningMethod", ...] = tuple()
  241. if not isinstance(args, Iterable): # only 1 item
  242. self._tensor_name = args._tensor_name
  243. self.add_pruning_method(args)
  244. elif len(args) == 1: # only 1 item in a tuple
  245. self._tensor_name = args[0]._tensor_name
  246. self.add_pruning_method(args[0])
  247. else: # manual construction from list or other iterable (or no args)
  248. for method in args:
  249. self.add_pruning_method(method)
  250. def add_pruning_method(self, method):
  251. r"""Adds a child pruning ``method`` to the container.
  252. Args:
  253. method (subclass of BasePruningMethod): child pruning method
  254. to be added to the container.
  255. """
  256. # check that we're adding a pruning method to the container
  257. if not isinstance(method, BasePruningMethod) and method is not None:
  258. raise TypeError(
  259. "{} is not a BasePruningMethod subclass".format(type(method))
  260. )
  261. elif method is not None and self._tensor_name != method._tensor_name:
  262. raise ValueError(
  263. "Can only add pruning methods acting on "
  264. "the parameter named '{}' to PruningContainer {}.".format(
  265. self._tensor_name, self
  266. )
  267. + " Found '{}'".format(method._tensor_name)
  268. )
  269. # if all checks passed, add to _pruning_methods tuple
  270. self._pruning_methods += (method,) # type: ignore[operator]
  271. def __len__(self):
  272. return len(self._pruning_methods)
  273. def __iter__(self):
  274. return iter(self._pruning_methods)
  275. def __getitem__(self, idx):
  276. return self._pruning_methods[idx]
  277. def compute_mask(self, t, default_mask):
  278. r"""Applies the latest ``method`` by computing the new partial masks
  279. and returning its combination with the ``default_mask``.
  280. The new partial mask should be computed on the entries or channels
  281. that were not zeroed out by the ``default_mask``.
  282. Which portions of the tensor ``t`` the new mask will be calculated from
  283. depends on the ``PRUNING_TYPE`` (handled by the type handler):
  284. * for 'unstructured', the mask will be computed from the raveled
  285. list of nonmasked entries;
  286. * for 'structured', the mask will be computed from the nonmasked
  287. channels in the tensor;
  288. * for 'global', the mask will be computed across all entries.
  289. Args:
  290. t (torch.Tensor): tensor representing the parameter to prune
  291. (of same dimensions as ``default_mask``).
  292. default_mask (torch.Tensor): mask from previous pruning iteration.
  293. Returns:
  294. mask (torch.Tensor): new mask that combines the effects
  295. of the ``default_mask`` and the new mask from the current
  296. pruning ``method`` (of same dimensions as ``default_mask`` and
  297. ``t``).
  298. """
  299. def _combine_masks(method, t, mask):
  300. r"""
  301. Args:
  302. method (a BasePruningMethod subclass): pruning method
  303. currently being applied.
  304. t (torch.Tensor): tensor representing the parameter to prune
  305. (of same dimensions as mask).
  306. mask (torch.Tensor): mask from previous pruning iteration
  307. Returns:
  308. new_mask (torch.Tensor): new mask that combines the effects
  309. of the old mask and the new mask from the current
  310. pruning method (of same dimensions as mask and t).
  311. """
  312. new_mask = mask # start off from existing mask
  313. new_mask = new_mask.to(dtype=t.dtype)
  314. # compute a slice of t onto which the new pruning method will operate
  315. if method.PRUNING_TYPE == "unstructured":
  316. # prune entries of t where the mask is 1
  317. slc = mask == 1
  318. # for struct pruning, exclude channels that have already been
  319. # entirely pruned
  320. elif method.PRUNING_TYPE == "structured":
  321. if not hasattr(method, "dim"):
  322. raise AttributeError(
  323. "Pruning methods of PRUNING_TYPE "
  324. '"structured" need to have the attribute `dim` defined.'
  325. )
  326. # find the channels to keep by removing the ones that have been
  327. # zeroed out already (i.e. where sum(entries) == 0)
  328. n_dims = t.dim() # "is this a 2D tensor? 3D? ..."
  329. dim = method.dim
  330. # convert negative indexing
  331. if dim < 0:
  332. dim = n_dims + dim
  333. # if dim is still negative after subtracting it from n_dims
  334. if dim < 0:
  335. raise IndexError(
  336. "Index is out of bounds for tensor with dimensions {}".format(
  337. n_dims
  338. )
  339. )
  340. # find channels along dim = dim that aren't already tots 0ed out
  341. keep_channel = mask.sum(dim=[d for d in range(n_dims) if d != dim]) != 0
  342. # create slice to identify what to prune
  343. slc = [slice(None)] * n_dims
  344. slc[dim] = keep_channel
  345. elif method.PRUNING_TYPE == "global":
  346. n_dims = len(t.shape) # "is this a 2D tensor? 3D? ..."
  347. slc = [slice(None)] * n_dims
  348. else:
  349. raise ValueError(
  350. "Unrecognized PRUNING_TYPE {}".format(method.PRUNING_TYPE)
  351. )
  352. # compute the new mask on the unpruned slice of the tensor t
  353. partial_mask = method.compute_mask(t[slc], default_mask=mask[slc])
  354. new_mask[slc] = partial_mask.to(dtype=new_mask.dtype)
  355. return new_mask
  356. method = self._pruning_methods[-1]
  357. mask = _combine_masks(method, t, default_mask)
  358. return mask
  359. class Identity(BasePruningMethod):
  360. r"""Utility pruning method that does not prune any units but generates the
  361. pruning parametrization with a mask of ones.
  362. """
  363. PRUNING_TYPE = "unstructured"
  364. def compute_mask(self, t, default_mask):
  365. mask = default_mask
  366. return mask
  367. @classmethod
  368. def apply(cls, module, name):
  369. r"""Adds the forward pre-hook that enables pruning on the fly and
  370. the reparametrization of a tensor in terms of the original tensor
  371. and the pruning mask.
  372. Args:
  373. module (nn.Module): module containing the tensor to prune
  374. name (str): parameter name within ``module`` on which pruning
  375. will act.
  376. """
  377. return super(Identity, cls).apply(module, name)
  378. class RandomUnstructured(BasePruningMethod):
  379. r"""Prune (currently unpruned) units in a tensor at random.
  380. Args:
  381. name (str): parameter name within ``module`` on which pruning
  382. will act.
  383. amount (int or float): quantity of parameters to prune.
  384. If ``float``, should be between 0.0 and 1.0 and represent the
  385. fraction of parameters to prune. If ``int``, it represents the
  386. absolute number of parameters to prune.
  387. """
  388. PRUNING_TYPE = "unstructured"
  389. def __init__(self, amount):
  390. # Check range of validity of pruning amount
  391. _validate_pruning_amount_init(amount)
  392. self.amount = amount
  393. def compute_mask(self, t, default_mask):
  394. # Check that the amount of units to prune is not > than the number of
  395. # parameters in t
  396. tensor_size = t.nelement()
  397. # Compute number of units to prune: amount if int,
  398. # else amount * tensor_size
  399. nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
  400. # This should raise an error if the number of units to prune is larger
  401. # than the number of units in the tensor
  402. _validate_pruning_amount(nparams_toprune, tensor_size)
  403. mask = default_mask.clone(memory_format=torch.contiguous_format)
  404. if nparams_toprune != 0: # k=0 not supported by torch.kthvalue
  405. prob = torch.rand_like(t)
  406. topk = torch.topk(prob.view(-1), k=nparams_toprune)
  407. mask.view(-1)[topk.indices] = 0
  408. return mask
  409. @classmethod
  410. def apply(cls, module, name, amount):
  411. r"""Adds the forward pre-hook that enables pruning on the fly and
  412. the reparametrization of a tensor in terms of the original tensor
  413. and the pruning mask.
  414. Args:
  415. module (nn.Module): module containing the tensor to prune
  416. name (str): parameter name within ``module`` on which pruning
  417. will act.
  418. amount (int or float): quantity of parameters to prune.
  419. If ``float``, should be between 0.0 and 1.0 and represent the
  420. fraction of parameters to prune. If ``int``, it represents the
  421. absolute number of parameters to prune.
  422. """
  423. return super(RandomUnstructured, cls).apply(module, name, amount=amount)
  424. class L1Unstructured(BasePruningMethod):
  425. r"""Prune (currently unpruned) units in a tensor by zeroing out the ones
  426. with the lowest L1-norm.
  427. Args:
  428. amount (int or float): quantity of parameters to prune.
  429. If ``float``, should be between 0.0 and 1.0 and represent the
  430. fraction of parameters to prune. If ``int``, it represents the
  431. absolute number of parameters to prune.
  432. """
  433. PRUNING_TYPE = "unstructured"
  434. def __init__(self, amount):
  435. # Check range of validity of pruning amount
  436. _validate_pruning_amount_init(amount)
  437. self.amount = amount
  438. def compute_mask(self, t, default_mask):
  439. # Check that the amount of units to prune is not > than the number of
  440. # parameters in t
  441. tensor_size = t.nelement()
  442. # Compute number of units to prune: amount if int,
  443. # else amount * tensor_size
  444. nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
  445. # This should raise an error if the number of units to prune is larger
  446. # than the number of units in the tensor
  447. _validate_pruning_amount(nparams_toprune, tensor_size)
  448. mask = default_mask.clone(memory_format=torch.contiguous_format)
  449. if nparams_toprune != 0: # k=0 not supported by torch.kthvalue
  450. # largest=True --> top k; largest=False --> bottom k
  451. # Prune the smallest k
  452. topk = torch.topk(torch.abs(t).view(-1), k=nparams_toprune, largest=False)
  453. # topk will have .indices and .values
  454. mask.view(-1)[topk.indices] = 0
  455. return mask
  456. @classmethod
  457. def apply(cls, module, name, amount, importance_scores=None):
  458. r"""Adds the forward pre-hook that enables pruning on the fly and
  459. the reparametrization of a tensor in terms of the original tensor
  460. and the pruning mask.
  461. Args:
  462. module (nn.Module): module containing the tensor to prune
  463. name (str): parameter name within ``module`` on which pruning
  464. will act.
  465. amount (int or float): quantity of parameters to prune.
  466. If ``float``, should be between 0.0 and 1.0 and represent the
  467. fraction of parameters to prune. If ``int``, it represents the
  468. absolute number of parameters to prune.
  469. importance_scores (torch.Tensor): tensor of importance scores (of same
  470. shape as module parameter) used to compute mask for pruning.
  471. The values in this tensor indicate the importance of the corresponding
  472. elements in the parameter being pruned.
  473. If unspecified or None, the module parameter will be used in its place.
  474. """
  475. return super(L1Unstructured, cls).apply(
  476. module, name, amount=amount, importance_scores=importance_scores
  477. )
  478. class RandomStructured(BasePruningMethod):
  479. r"""Prune entire (currently unpruned) channels in a tensor at random.
  480. Args:
  481. amount (int or float): quantity of parameters to prune.
  482. If ``float``, should be between 0.0 and 1.0 and represent the
  483. fraction of parameters to prune. If ``int``, it represents the
  484. absolute number of parameters to prune.
  485. dim (int, optional): index of the dim along which we define
  486. channels to prune. Default: -1.
  487. """
  488. PRUNING_TYPE = "structured"
  489. def __init__(self, amount, dim=-1):
  490. # Check range of validity of amount
  491. _validate_pruning_amount_init(amount)
  492. self.amount = amount
  493. self.dim = dim
  494. def compute_mask(self, t, default_mask):
  495. r"""Computes and returns a mask for the input tensor ``t``.
  496. Starting from a base ``default_mask`` (which should be a mask of ones
  497. if the tensor has not been pruned yet), generate a random mask to
  498. apply on top of the ``default_mask`` by randomly zeroing out channels
  499. along the specified dim of the tensor.
  500. Args:
  501. t (torch.Tensor): tensor representing the parameter to prune
  502. default_mask (torch.Tensor): Base mask from previous pruning
  503. iterations, that need to be respected after the new mask is
  504. applied. Same dims as ``t``.
  505. Returns:
  506. mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
  507. Raises:
  508. IndexError: if ``self.dim >= len(t.shape)``
  509. """
  510. # Check that tensor has structure (i.e. more than 1 dimension) such
  511. # that the concept of "channels" makes sense
  512. _validate_structured_pruning(t)
  513. # Check that self.dim is a valid dim to index t, else raise IndexError
  514. _validate_pruning_dim(t, self.dim)
  515. # Check that the amount of channels to prune is not > than the number of
  516. # channels in t along the dim to prune
  517. tensor_size = t.shape[self.dim]
  518. # Compute number of units to prune: amount if int,
  519. # else amount * tensor_size
  520. nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
  521. # This should raise an error if the number of units to prune is larger
  522. # than the number of units in the tensor
  523. _validate_pruning_amount(nparams_toprune, tensor_size)
  524. # Compute binary mask by initializing it to all 0s and then filling in
  525. # 1s wherever topk.indices indicates, along self.dim.
  526. # mask has the same shape as tensor t
  527. def make_mask(t, dim, nchannels, nchannels_toprune):
  528. # generate a random number in [0, 1] to associate to each channel
  529. prob = torch.rand(nchannels)
  530. # generate mask for each channel by 0ing out the channels that
  531. # got assigned the k = nchannels_toprune lowest values in prob
  532. threshold = torch.kthvalue(prob, k=nchannels_toprune).values
  533. channel_mask = prob > threshold
  534. mask = torch.zeros_like(t)
  535. slc = [slice(None)] * len(t.shape)
  536. slc[dim] = channel_mask
  537. mask[slc] = 1
  538. return mask
  539. if nparams_toprune == 0: # k=0 not supported by torch.kthvalue
  540. mask = default_mask
  541. else:
  542. # apply the new structured mask on top of prior (potentially
  543. # unstructured) mask
  544. mask = make_mask(t, self.dim, tensor_size, nparams_toprune)
  545. mask *= default_mask.to(dtype=mask.dtype)
  546. return mask
  547. @classmethod
  548. def apply(cls, module, name, amount, dim=-1):
  549. r"""Adds the forward pre-hook that enables pruning on the fly and
  550. the reparametrization of a tensor in terms of the original tensor
  551. and the pruning mask.
  552. Args:
  553. module (nn.Module): module containing the tensor to prune
  554. name (str): parameter name within ``module`` on which pruning
  555. will act.
  556. amount (int or float): quantity of parameters to prune.
  557. If ``float``, should be between 0.0 and 1.0 and represent the
  558. fraction of parameters to prune. If ``int``, it represents the
  559. absolute number of parameters to prune.
  560. dim (int, optional): index of the dim along which we define
  561. channels to prune. Default: -1.
  562. """
  563. return super(RandomStructured, cls).apply(module, name, amount=amount, dim=dim)
  564. class LnStructured(BasePruningMethod):
  565. r"""Prune entire (currently unpruned) channels in a tensor based on their
  566. L\ ``n``-norm.
  567. Args:
  568. amount (int or float): quantity of channels to prune.
  569. If ``float``, should be between 0.0 and 1.0 and represent the
  570. fraction of parameters to prune. If ``int``, it represents the
  571. absolute number of parameters to prune.
  572. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  573. entries for argument ``p`` in :func:`torch.norm`.
  574. dim (int, optional): index of the dim along which we define
  575. channels to prune. Default: -1.
  576. """
  577. PRUNING_TYPE = "structured"
  578. def __init__(self, amount, n, dim=-1):
  579. # Check range of validity of amount
  580. _validate_pruning_amount_init(amount)
  581. self.amount = amount
  582. self.n = n
  583. self.dim = dim
  584. def compute_mask(self, t, default_mask):
  585. r"""Computes and returns a mask for the input tensor ``t``.
  586. Starting from a base ``default_mask`` (which should be a mask of ones
  587. if the tensor has not been pruned yet), generate a mask to apply on
  588. top of the ``default_mask`` by zeroing out the channels along the
  589. specified dim with the lowest L\ ``n``-norm.
  590. Args:
  591. t (torch.Tensor): tensor representing the parameter to prune
  592. default_mask (torch.Tensor): Base mask from previous pruning
  593. iterations, that need to be respected after the new mask is
  594. applied. Same dims as ``t``.
  595. Returns:
  596. mask (torch.Tensor): mask to apply to ``t``, of same dims as ``t``
  597. Raises:
  598. IndexError: if ``self.dim >= len(t.shape)``
  599. """
  600. # Check that tensor has structure (i.e. more than 1 dimension) such
  601. # that the concept of "channels" makes sense
  602. _validate_structured_pruning(t)
  603. # Check that self.dim is a valid dim to index t, else raise IndexError
  604. _validate_pruning_dim(t, self.dim)
  605. # Check that the amount of channels to prune is not > than the number of
  606. # channels in t along the dim to prune
  607. tensor_size = t.shape[self.dim]
  608. # Compute number of units to prune: amount if int,
  609. # else amount * tensor_size
  610. nparams_toprune = _compute_nparams_toprune(self.amount, tensor_size)
  611. nparams_tokeep = tensor_size - nparams_toprune
  612. # This should raise an error if the number of units to prune is larger
  613. # than the number of units in the tensor
  614. _validate_pruning_amount(nparams_toprune, tensor_size)
  615. # Structured pruning prunes entire channels so we need to know the
  616. # L_n norm along each channel to then find the topk based on this
  617. # metric
  618. norm = _compute_norm(t, self.n, self.dim)
  619. # largest=True --> top k; largest=False --> bottom k
  620. # Keep the largest k channels along dim=self.dim
  621. topk = torch.topk(norm, k=nparams_tokeep, largest=True)
  622. # topk will have .indices and .values
  623. # Compute binary mask by initializing it to all 0s and then filling in
  624. # 1s wherever topk.indices indicates, along self.dim.
  625. # mask has the same shape as tensor t
  626. def make_mask(t, dim, indices):
  627. # init mask to 0
  628. mask = torch.zeros_like(t)
  629. # e.g.: slc = [None, None, None], if len(t.shape) = 3
  630. slc = [slice(None)] * len(t.shape)
  631. # replace a None at position=dim with indices
  632. # e.g.: slc = [None, None, [0, 2, 3]] if dim=2 & indices=[0,2,3]
  633. slc[dim] = indices
  634. # use slc to slice mask and replace all its entries with 1s
  635. # e.g.: mask[:, :, [0, 2, 3]] = 1
  636. mask[slc] = 1
  637. return mask
  638. if nparams_toprune == 0: # k=0 not supported by torch.kthvalue
  639. mask = default_mask
  640. else:
  641. mask = make_mask(t, self.dim, topk.indices)
  642. mask *= default_mask.to(dtype=mask.dtype)
  643. return mask
  644. @classmethod
  645. def apply(cls, module, name, amount, n, dim, importance_scores=None):
  646. r"""Adds the forward pre-hook that enables pruning on the fly and
  647. the reparametrization of a tensor in terms of the original tensor
  648. and the pruning mask.
  649. Args:
  650. module (nn.Module): module containing the tensor to prune
  651. name (str): parameter name within ``module`` on which pruning
  652. will act.
  653. amount (int or float): quantity of parameters to prune.
  654. If ``float``, should be between 0.0 and 1.0 and represent the
  655. fraction of parameters to prune. If ``int``, it represents the
  656. absolute number of parameters to prune.
  657. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  658. entries for argument ``p`` in :func:`torch.norm`.
  659. dim (int): index of the dim along which we define channels to
  660. prune.
  661. importance_scores (torch.Tensor): tensor of importance scores (of same
  662. shape as module parameter) used to compute mask for pruning.
  663. The values in this tensor indicate the importance of the corresponding
  664. elements in the parameter being pruned.
  665. If unspecified or None, the module parameter will be used in its place.
  666. """
  667. return super(LnStructured, cls).apply(
  668. module,
  669. name,
  670. amount=amount,
  671. n=n,
  672. dim=dim,
  673. importance_scores=importance_scores,
  674. )
  675. class CustomFromMask(BasePruningMethod):
  676. PRUNING_TYPE = "global"
  677. def __init__(self, mask):
  678. self.mask = mask
  679. def compute_mask(self, t, default_mask):
  680. assert default_mask.shape == self.mask.shape
  681. mask = default_mask * self.mask.to(dtype=default_mask.dtype)
  682. return mask
  683. @classmethod
  684. def apply(cls, module, name, mask):
  685. r"""Adds the forward pre-hook that enables pruning on the fly and
  686. the reparametrization of a tensor in terms of the original tensor
  687. and the pruning mask.
  688. Args:
  689. module (nn.Module): module containing the tensor to prune
  690. name (str): parameter name within ``module`` on which pruning
  691. will act.
  692. """
  693. return super(CustomFromMask, cls).apply(module, name, mask=mask)
  694. def identity(module, name):
  695. r"""Applies pruning reparametrization to the tensor corresponding to the
  696. parameter called ``name`` in ``module`` without actually pruning any
  697. units. Modifies module in place (and also return the modified module)
  698. by:
  699. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  700. binary mask applied to the parameter ``name`` by the pruning method.
  701. 2) replacing the parameter ``name`` by its pruned version, while the
  702. original (unpruned) parameter is stored in a new parameter named
  703. ``name+'_orig'``.
  704. Note:
  705. The mask is a tensor of ones.
  706. Args:
  707. module (nn.Module): module containing the tensor to prune.
  708. name (str): parameter name within ``module`` on which pruning
  709. will act.
  710. Returns:
  711. module (nn.Module): modified (i.e. pruned) version of the input module
  712. Examples:
  713. >>> # xdoctest: +SKIP
  714. >>> m = prune.identity(nn.Linear(2, 3), 'bias')
  715. >>> print(m.bias_mask)
  716. tensor([1., 1., 1.])
  717. """
  718. Identity.apply(module, name)
  719. return module
  720. def random_unstructured(module, name, amount):
  721. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  722. by removing the specified ``amount`` of (currently unpruned) units
  723. selected at random.
  724. Modifies module in place (and also return the modified module) by:
  725. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  726. binary mask applied to the parameter ``name`` by the pruning method.
  727. 2) replacing the parameter ``name`` by its pruned version, while the
  728. original (unpruned) parameter is stored in a new parameter named
  729. ``name+'_orig'``.
  730. Args:
  731. module (nn.Module): module containing the tensor to prune
  732. name (str): parameter name within ``module`` on which pruning
  733. will act.
  734. amount (int or float): quantity of parameters to prune.
  735. If ``float``, should be between 0.0 and 1.0 and represent the
  736. fraction of parameters to prune. If ``int``, it represents the
  737. absolute number of parameters to prune.
  738. Returns:
  739. module (nn.Module): modified (i.e. pruned) version of the input module
  740. Examples:
  741. >>> # xdoctest: +SKIP
  742. >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1)
  743. >>> torch.sum(m.weight_mask == 0)
  744. tensor(1)
  745. """
  746. RandomUnstructured.apply(module, name, amount)
  747. return module
  748. def l1_unstructured(module, name, amount, importance_scores=None):
  749. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  750. by removing the specified `amount` of (currently unpruned) units with the
  751. lowest L1-norm.
  752. Modifies module in place (and also return the modified module)
  753. by:
  754. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  755. binary mask applied to the parameter ``name`` by the pruning method.
  756. 2) replacing the parameter ``name`` by its pruned version, while the
  757. original (unpruned) parameter is stored in a new parameter named
  758. ``name+'_orig'``.
  759. Args:
  760. module (nn.Module): module containing the tensor to prune
  761. name (str): parameter name within ``module`` on which pruning
  762. will act.
  763. amount (int or float): quantity of parameters to prune.
  764. If ``float``, should be between 0.0 and 1.0 and represent the
  765. fraction of parameters to prune. If ``int``, it represents the
  766. absolute number of parameters to prune.
  767. importance_scores (torch.Tensor): tensor of importance scores (of same
  768. shape as module parameter) used to compute mask for pruning.
  769. The values in this tensor indicate the importance of the corresponding
  770. elements in the parameter being pruned.
  771. If unspecified or None, the module parameter will be used in its place.
  772. Returns:
  773. module (nn.Module): modified (i.e. pruned) version of the input module
  774. Examples:
  775. >>> # xdoctest: +SKIP
  776. >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2)
  777. >>> m.state_dict().keys()
  778. odict_keys(['bias', 'weight_orig', 'weight_mask'])
  779. """
  780. L1Unstructured.apply(
  781. module, name, amount=amount, importance_scores=importance_scores
  782. )
  783. return module
  784. def random_structured(module, name, amount, dim):
  785. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  786. by removing the specified ``amount`` of (currently unpruned) channels
  787. along the specified ``dim`` selected at random.
  788. Modifies module in place (and also return the modified module)
  789. by:
  790. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  791. binary mask applied to the parameter ``name`` by the pruning method.
  792. 2) replacing the parameter ``name`` by its pruned version, while the
  793. original (unpruned) parameter is stored in a new parameter named
  794. ``name+'_orig'``.
  795. Args:
  796. module (nn.Module): module containing the tensor to prune
  797. name (str): parameter name within ``module`` on which pruning
  798. will act.
  799. amount (int or float): quantity of parameters to prune.
  800. If ``float``, should be between 0.0 and 1.0 and represent the
  801. fraction of parameters to prune. If ``int``, it represents the
  802. absolute number of parameters to prune.
  803. dim (int): index of the dim along which we define channels to prune.
  804. Returns:
  805. module (nn.Module): modified (i.e. pruned) version of the input module
  806. Examples:
  807. >>> # xdoctest: +SKIP
  808. >>> m = prune.random_structured(
  809. ... nn.Linear(5, 3), 'weight', amount=3, dim=1
  810. ... )
  811. >>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0))
  812. >>> print(columns_pruned)
  813. 3
  814. """
  815. RandomStructured.apply(module, name, amount, dim)
  816. return module
  817. def ln_structured(module, name, amount, n, dim, importance_scores=None):
  818. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  819. by removing the specified ``amount`` of (currently unpruned) channels
  820. along the specified ``dim`` with the lowest L\ ``n``-norm.
  821. Modifies module in place (and also return the modified module)
  822. by:
  823. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  824. binary mask applied to the parameter ``name`` by the pruning method.
  825. 2) replacing the parameter ``name`` by its pruned version, while the
  826. original (unpruned) parameter is stored in a new parameter named
  827. ``name+'_orig'``.
  828. Args:
  829. module (nn.Module): module containing the tensor to prune
  830. name (str): parameter name within ``module`` on which pruning
  831. will act.
  832. amount (int or float): quantity of parameters to prune.
  833. If ``float``, should be between 0.0 and 1.0 and represent the
  834. fraction of parameters to prune. If ``int``, it represents the
  835. absolute number of parameters to prune.
  836. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  837. entries for argument ``p`` in :func:`torch.norm`.
  838. dim (int): index of the dim along which we define channels to prune.
  839. importance_scores (torch.Tensor): tensor of importance scores (of same
  840. shape as module parameter) used to compute mask for pruning.
  841. The values in this tensor indicate the importance of the corresponding
  842. elements in the parameter being pruned.
  843. If unspecified or None, the module parameter will be used in its place.
  844. Returns:
  845. module (nn.Module): modified (i.e. pruned) version of the input module
  846. Examples:
  847. >>> from torch.nn.utils import prune
  848. >>> m = prune.ln_structured(
  849. ... nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf')
  850. ... )
  851. """
  852. LnStructured.apply(
  853. module, name, amount, n, dim, importance_scores=importance_scores
  854. )
  855. return module
  856. def global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs):
  857. r"""
  858. Globally prunes tensors corresponding to all parameters in ``parameters``
  859. by applying the specified ``pruning_method``.
  860. Modifies modules in place by:
  861. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  862. binary mask applied to the parameter ``name`` by the pruning method.
  863. 2) replacing the parameter ``name`` by its pruned version, while the
  864. original (unpruned) parameter is stored in a new parameter named
  865. ``name+'_orig'``.
  866. Args:
  867. parameters (Iterable of (module, name) tuples): parameters of
  868. the model to prune in a global fashion, i.e. by aggregating all
  869. weights prior to deciding which ones to prune. module must be of
  870. type :class:`nn.Module`, and name must be a string.
  871. pruning_method (function): a valid pruning function from this module,
  872. or a custom one implemented by the user that satisfies the
  873. implementation guidelines and has ``PRUNING_TYPE='unstructured'``.
  874. importance_scores (dict): a dictionary mapping (module, name) tuples to
  875. the corresponding parameter's importance scores tensor. The tensor
  876. should be the same shape as the parameter, and is used for computing
  877. mask for pruning.
  878. If unspecified or None, the parameter will be used in place of its
  879. importance scores.
  880. kwargs: other keyword arguments such as:
  881. amount (int or float): quantity of parameters to prune across the
  882. specified parameters.
  883. If ``float``, should be between 0.0 and 1.0 and represent the
  884. fraction of parameters to prune. If ``int``, it represents the
  885. absolute number of parameters to prune.
  886. Raises:
  887. TypeError: if ``PRUNING_TYPE != 'unstructured'``
  888. Note:
  889. Since global structured pruning doesn't make much sense unless the
  890. norm is normalized by the size of the parameter, we now limit the
  891. scope of global pruning to unstructured methods.
  892. Examples:
  893. >>> from torch.nn.utils import prune
  894. >>> from collections import OrderedDict
  895. >>> net = nn.Sequential(OrderedDict([
  896. ... ('first', nn.Linear(10, 4)),
  897. ... ('second', nn.Linear(4, 1)),
  898. ... ]))
  899. >>> parameters_to_prune = (
  900. ... (net.first, 'weight'),
  901. ... (net.second, 'weight'),
  902. ... )
  903. >>> prune.global_unstructured(
  904. ... parameters_to_prune,
  905. ... pruning_method=prune.L1Unstructured,
  906. ... amount=10,
  907. ... )
  908. >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0))
  909. tensor(10)
  910. """
  911. # ensure parameters is a list or generator of tuples
  912. if not isinstance(parameters, Iterable):
  913. raise TypeError("global_unstructured(): parameters is not an Iterable")
  914. importance_scores = importance_scores if importance_scores is not None else {}
  915. if not isinstance(importance_scores, dict):
  916. raise TypeError("global_unstructured(): importance_scores must be of type dict")
  917. # flatten importance scores to consider them all at once in global pruning
  918. relevant_importance_scores = torch.nn.utils.parameters_to_vector(
  919. [
  920. importance_scores.get((module, name), getattr(module, name))
  921. for (module, name) in parameters
  922. ]
  923. )
  924. # similarly, flatten the masks (if they exist), or use a flattened vector
  925. # of 1s of the same dimensions as t
  926. default_mask = torch.nn.utils.parameters_to_vector(
  927. [
  928. getattr(module, name + "_mask", torch.ones_like(getattr(module, name)))
  929. for (module, name) in parameters
  930. ]
  931. )
  932. # use the canonical pruning methods to compute the new mask, even if the
  933. # parameter is now a flattened out version of `parameters`
  934. container = PruningContainer()
  935. container._tensor_name = "temp" # to make it match that of `method`
  936. method = pruning_method(**kwargs)
  937. method._tensor_name = "temp" # to make it match that of `container`
  938. if method.PRUNING_TYPE != "unstructured":
  939. raise TypeError(
  940. 'Only "unstructured" PRUNING_TYPE supported for '
  941. "the `pruning_method`. Found method {} of type {}".format(
  942. pruning_method, method.PRUNING_TYPE
  943. )
  944. )
  945. container.add_pruning_method(method)
  946. # use the `compute_mask` method from `PruningContainer` to combine the
  947. # mask computed by the new method with the pre-existing mask
  948. final_mask = container.compute_mask(relevant_importance_scores, default_mask)
  949. # Pointer for slicing the mask to match the shape of each parameter
  950. pointer = 0
  951. for module, name in parameters:
  952. param = getattr(module, name)
  953. # The length of the parameter
  954. num_param = param.numel()
  955. # Slice the mask, reshape it
  956. param_mask = final_mask[pointer : pointer + num_param].view_as(param)
  957. # Assign the correct pre-computed mask to each parameter and add it
  958. # to the forward_pre_hooks like any other pruning method
  959. custom_from_mask(module, name, mask=param_mask)
  960. # Increment the pointer to continue slicing the final_mask
  961. pointer += num_param
  962. def custom_from_mask(module, name, mask):
  963. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  964. by applying the pre-computed mask in ``mask``.
  965. Modifies module in place (and also return the modified module)
  966. by:
  967. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  968. binary mask applied to the parameter ``name`` by the pruning method.
  969. 2) replacing the parameter ``name`` by its pruned version, while the
  970. original (unpruned) parameter is stored in a new parameter named
  971. ``name+'_orig'``.
  972. Args:
  973. module (nn.Module): module containing the tensor to prune
  974. name (str): parameter name within ``module`` on which pruning
  975. will act.
  976. mask (Tensor): binary mask to be applied to the parameter.
  977. Returns:
  978. module (nn.Module): modified (i.e. pruned) version of the input module
  979. Examples:
  980. >>> from torch.nn.utils import prune
  981. >>> m = prune.custom_from_mask(
  982. ... nn.Linear(5, 3), name='bias', mask=torch.tensor([0, 1, 0])
  983. ... )
  984. >>> print(m.bias_mask)
  985. tensor([0., 1., 0.])
  986. """
  987. CustomFromMask.apply(module, name, mask)
  988. return module
  989. def remove(module, name):
  990. r"""Removes the pruning reparameterization from a module and the
  991. pruning method from the forward hook. The pruned
  992. parameter named ``name`` remains permanently pruned, and the parameter
  993. named ``name+'_orig'`` is removed from the parameter list. Similarly,
  994. the buffer named ``name+'_mask'`` is removed from the buffers.
  995. Note:
  996. Pruning itself is NOT undone or reversed!
  997. Args:
  998. module (nn.Module): module containing the tensor to prune
  999. name (str): parameter name within ``module`` on which pruning
  1000. will act.
  1001. Examples:
  1002. >>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2)
  1003. >>> m = remove(m, name='weight')
  1004. """
  1005. for k, hook in module._forward_pre_hooks.items():
  1006. if isinstance(hook, BasePruningMethod) and hook._tensor_name == name:
  1007. hook.remove(module)
  1008. del module._forward_pre_hooks[k]
  1009. return module
  1010. raise ValueError(
  1011. "Parameter '{}' of module {} has to be pruned "
  1012. "before pruning can be removed".format(name, module)
  1013. )
  1014. def is_pruned(module):
  1015. r"""Check whether ``module`` is pruned by looking for
  1016. ``forward_pre_hooks`` in its modules that inherit from the
  1017. :class:`BasePruningMethod`.
  1018. Args:
  1019. module (nn.Module): object that is either pruned or unpruned
  1020. Returns:
  1021. binary answer to whether ``module`` is pruned.
  1022. Examples:
  1023. >>> from torch.nn.utils import prune
  1024. >>> m = nn.Linear(5, 7)
  1025. >>> print(prune.is_pruned(m))
  1026. False
  1027. >>> prune.random_unstructured(m, name='weight', amount=0.2)
  1028. >>> print(prune.is_pruned(m))
  1029. True
  1030. """
  1031. for _, submodule in module.named_modules():
  1032. for _, hook in submodule._forward_pre_hooks.items():
  1033. if isinstance(hook, BasePruningMethod):
  1034. return True
  1035. return False
  1036. def _validate_pruning_amount_init(amount):
  1037. r"""Validation helper to check the range of amount at init.
  1038. Args:
  1039. amount (int or float): quantity of parameters to prune.
  1040. If float, should be between 0.0 and 1.0 and represent the
  1041. fraction of parameters to prune. If int, it represents the
  1042. absolute number of parameters to prune.
  1043. Raises:
  1044. ValueError: if amount is a float not in [0, 1], or if it's a negative
  1045. integer.
  1046. TypeError: if amount is neither a float nor an integer.
  1047. Note:
  1048. This does not take into account the number of parameters in the
  1049. tensor to be pruned, which is known only at prune.
  1050. """
  1051. if not isinstance(amount, numbers.Real):
  1052. raise TypeError(
  1053. "Invalid type for amount: {}. Must be int or float." "".format(amount)
  1054. )
  1055. if (isinstance(amount, numbers.Integral) and amount < 0) or (
  1056. not isinstance(amount, numbers.Integral) # so it's a float
  1057. and (float(amount) > 1.0 or float(amount) < 0.0)
  1058. ):
  1059. raise ValueError(
  1060. "amount={} should either be a float in the "
  1061. "range [0, 1] or a non-negative integer"
  1062. "".format(amount)
  1063. )
  1064. def _validate_pruning_amount(amount, tensor_size):
  1065. r"""Validation helper to check that the amount of parameters to prune
  1066. is meaningful wrt to the size of the data (`tensor_size`).
  1067. Args:
  1068. amount (int or float): quantity of parameters to prune.
  1069. If float, should be between 0.0 and 1.0 and represent the
  1070. fraction of parameters to prune. If int, it represents the
  1071. absolute number of parameters to prune.
  1072. tensor_size (int): absolute number of parameters in the tensor
  1073. to prune.
  1074. """
  1075. # TODO: consider removing this check and allowing users to specify
  1076. # a number of units to prune that is greater than the number of units
  1077. # left to prune. In this case, the tensor will just be fully pruned.
  1078. if isinstance(amount, numbers.Integral) and amount > tensor_size:
  1079. raise ValueError(
  1080. "amount={} should be smaller than the number of "
  1081. "parameters to prune={}".format(amount, tensor_size)
  1082. )
  1083. def _validate_structured_pruning(t):
  1084. r"""Validation helper to check that the tensor to be pruned is multi-
  1085. dimensional, such that the concept of "channels" is well-defined.
  1086. Args:
  1087. t (torch.Tensor): tensor representing the parameter to prune
  1088. Raises:
  1089. ValueError: if the tensor `t` is not at least 2D.
  1090. """
  1091. shape = t.shape
  1092. if len(shape) <= 1:
  1093. raise ValueError(
  1094. "Structured pruning can only be applied to "
  1095. "multidimensional tensors. Found tensor of shape "
  1096. "{} with {} dims".format(shape, len(shape))
  1097. )
  1098. def _compute_nparams_toprune(amount, tensor_size):
  1099. r"""Since amount can be expressed either in absolute value or as a
  1100. percentage of the number of units/channels in a tensor, this utility
  1101. function converts the percentage to absolute value to standardize
  1102. the handling of pruning.
  1103. Args:
  1104. amount (int or float): quantity of parameters to prune.
  1105. If float, should be between 0.0 and 1.0 and represent the
  1106. fraction of parameters to prune. If int, it represents the
  1107. absolute number of parameters to prune.
  1108. tensor_size (int): absolute number of parameters in the tensor
  1109. to prune.
  1110. Returns:
  1111. int: the number of units to prune in the tensor
  1112. """
  1113. # incorrect type already checked in _validate_pruning_amount_init
  1114. if isinstance(amount, numbers.Integral):
  1115. return amount
  1116. else:
  1117. return round(amount * tensor_size)
  1118. def _validate_pruning_dim(t, dim):
  1119. r"""
  1120. Args:
  1121. t (torch.Tensor): tensor representing the parameter to prune
  1122. dim (int): index of the dim along which we define channels to prune
  1123. """
  1124. if dim >= t.dim():
  1125. raise IndexError("Invalid index {} for tensor of size {}".format(dim, t.shape))
  1126. def _compute_norm(t, n, dim):
  1127. r"""Compute the L_n-norm across all entries in tensor `t` along all dimension
  1128. except for the one identified by dim.
  1129. Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim),
  1130. then norm will have Size [4], and each entry will represent the
  1131. `L_n`-norm computed using the 3x2=6 entries for each of the 4 channels.
  1132. Args:
  1133. t (torch.Tensor): tensor representing the parameter to prune
  1134. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  1135. entries for argument p in torch.norm
  1136. dim (int): dim identifying the channels to prune
  1137. Returns:
  1138. norm (torch.Tensor): L_n norm computed across all dimensions except
  1139. for `dim`. By construction, `norm.shape = t.shape[-1]`.
  1140. """
  1141. # dims = all axes, except for the one identified by `dim`
  1142. dims = list(range(t.dim()))
  1143. # convert negative indexing
  1144. if dim < 0:
  1145. dim = dims[dim]
  1146. dims.remove(dim)
  1147. norm = torch.norm(t, p=n, dim=dims)
  1148. return norm