prune.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  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. >>> m = prune.identity(nn.Linear(2, 3), 'bias')
  714. >>> print(m.bias_mask)
  715. tensor([1., 1., 1.])
  716. """
  717. Identity.apply(module, name)
  718. return module
  719. def random_unstructured(module, name, amount):
  720. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  721. by removing the specified ``amount`` of (currently unpruned) units
  722. selected at random.
  723. Modifies module in place (and also return the modified module) by:
  724. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  725. binary mask applied to the parameter ``name`` by the pruning method.
  726. 2) replacing the parameter ``name`` by its pruned version, while the
  727. original (unpruned) parameter is stored in a new parameter named
  728. ``name+'_orig'``.
  729. Args:
  730. module (nn.Module): module containing the tensor to prune
  731. name (str): parameter name within ``module`` on which pruning
  732. will act.
  733. amount (int or float): quantity of parameters to prune.
  734. If ``float``, should be between 0.0 and 1.0 and represent the
  735. fraction of parameters to prune. If ``int``, it represents the
  736. absolute number of parameters to prune.
  737. Returns:
  738. module (nn.Module): modified (i.e. pruned) version of the input module
  739. Examples:
  740. >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1)
  741. >>> torch.sum(m.weight_mask == 0)
  742. tensor(1)
  743. """
  744. RandomUnstructured.apply(module, name, amount)
  745. return module
  746. def l1_unstructured(module, name, amount, importance_scores=None):
  747. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  748. by removing the specified `amount` of (currently unpruned) units with the
  749. lowest L1-norm.
  750. Modifies module in place (and also return the modified module)
  751. by:
  752. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  753. binary mask applied to the parameter ``name`` by the pruning method.
  754. 2) replacing the parameter ``name`` by its pruned version, while the
  755. original (unpruned) parameter is stored in a new parameter named
  756. ``name+'_orig'``.
  757. Args:
  758. module (nn.Module): module containing the tensor to prune
  759. name (str): parameter name within ``module`` on which pruning
  760. will act.
  761. amount (int or float): quantity of parameters to prune.
  762. If ``float``, should be between 0.0 and 1.0 and represent the
  763. fraction of parameters to prune. If ``int``, it represents the
  764. absolute number of parameters to prune.
  765. importance_scores (torch.Tensor): tensor of importance scores (of same
  766. shape as module parameter) used to compute mask for pruning.
  767. The values in this tensor indicate the importance of the corresponding
  768. elements in the parameter being pruned.
  769. If unspecified or None, the module parameter will be used in its place.
  770. Returns:
  771. module (nn.Module): modified (i.e. pruned) version of the input module
  772. Examples:
  773. >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2)
  774. >>> m.state_dict().keys()
  775. odict_keys(['bias', 'weight_orig', 'weight_mask'])
  776. """
  777. L1Unstructured.apply(
  778. module, name, amount=amount, importance_scores=importance_scores
  779. )
  780. return module
  781. def random_structured(module, name, amount, dim):
  782. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  783. by removing the specified ``amount`` of (currently unpruned) channels
  784. along the specified ``dim`` selected at random.
  785. Modifies module in place (and also return the modified module)
  786. by:
  787. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  788. binary mask applied to the parameter ``name`` by the pruning method.
  789. 2) replacing the parameter ``name`` by its pruned version, while the
  790. original (unpruned) parameter is stored in a new parameter named
  791. ``name+'_orig'``.
  792. Args:
  793. module (nn.Module): module containing the tensor to prune
  794. name (str): parameter name within ``module`` on which pruning
  795. will act.
  796. amount (int or float): quantity of parameters to prune.
  797. If ``float``, should be between 0.0 and 1.0 and represent the
  798. fraction of parameters to prune. If ``int``, it represents the
  799. absolute number of parameters to prune.
  800. dim (int): index of the dim along which we define channels to prune.
  801. Returns:
  802. module (nn.Module): modified (i.e. pruned) version of the input module
  803. Examples:
  804. >>> m = prune.random_structured(
  805. nn.Linear(5, 3), 'weight', amount=3, dim=1
  806. )
  807. >>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0))
  808. >>> print(columns_pruned)
  809. 3
  810. """
  811. RandomStructured.apply(module, name, amount, dim)
  812. return module
  813. def ln_structured(module, name, amount, n, dim, importance_scores=None):
  814. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  815. by removing the specified ``amount`` of (currently unpruned) channels
  816. along the specified ``dim`` with the lowest L\ ``n``-norm.
  817. Modifies module in place (and also return the modified module)
  818. by:
  819. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  820. binary mask applied to the parameter ``name`` by the pruning method.
  821. 2) replacing the parameter ``name`` by its pruned version, while the
  822. original (unpruned) parameter is stored in a new parameter named
  823. ``name+'_orig'``.
  824. Args:
  825. module (nn.Module): module containing the tensor to prune
  826. name (str): parameter name within ``module`` on which pruning
  827. will act.
  828. amount (int or float): quantity of parameters to prune.
  829. If ``float``, should be between 0.0 and 1.0 and represent the
  830. fraction of parameters to prune. If ``int``, it represents the
  831. absolute number of parameters to prune.
  832. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  833. entries for argument ``p`` in :func:`torch.norm`.
  834. dim (int): index of the dim along which we define channels to prune.
  835. importance_scores (torch.Tensor): tensor of importance scores (of same
  836. shape as module parameter) used to compute mask for pruning.
  837. The values in this tensor indicate the importance of the corresponding
  838. elements in the parameter being pruned.
  839. If unspecified or None, the module parameter will be used in its place.
  840. Returns:
  841. module (nn.Module): modified (i.e. pruned) version of the input module
  842. Examples:
  843. >>> m = prune.ln_structured(
  844. nn.Conv2d(5, 3, 2), 'weight', amount=0.3, dim=1, n=float('-inf')
  845. )
  846. """
  847. LnStructured.apply(
  848. module, name, amount, n, dim, importance_scores=importance_scores
  849. )
  850. return module
  851. def global_unstructured(parameters, pruning_method, importance_scores=None, **kwargs):
  852. r"""
  853. Globally prunes tensors corresponding to all parameters in ``parameters``
  854. by applying the specified ``pruning_method``.
  855. Modifies modules in place by:
  856. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  857. binary mask applied to the parameter ``name`` by the pruning method.
  858. 2) replacing the parameter ``name`` by its pruned version, while the
  859. original (unpruned) parameter is stored in a new parameter named
  860. ``name+'_orig'``.
  861. Args:
  862. parameters (Iterable of (module, name) tuples): parameters of
  863. the model to prune in a global fashion, i.e. by aggregating all
  864. weights prior to deciding which ones to prune. module must be of
  865. type :class:`nn.Module`, and name must be a string.
  866. pruning_method (function): a valid pruning function from this module,
  867. or a custom one implemented by the user that satisfies the
  868. implementation guidelines and has ``PRUNING_TYPE='unstructured'``.
  869. importance_scores (dict): a dictionary mapping (module, name) tuples to
  870. the corresponding parameter's importance scores tensor. The tensor
  871. should be the same shape as the parameter, and is used for computing
  872. mask for pruning.
  873. If unspecified or None, the parameter will be used in place of its
  874. importance scores.
  875. kwargs: other keyword arguments such as:
  876. amount (int or float): quantity of parameters to prune across the
  877. specified parameters.
  878. If ``float``, should be between 0.0 and 1.0 and represent the
  879. fraction of parameters to prune. If ``int``, it represents the
  880. absolute number of parameters to prune.
  881. Raises:
  882. TypeError: if ``PRUNING_TYPE != 'unstructured'``
  883. Note:
  884. Since global structured pruning doesn't make much sense unless the
  885. norm is normalized by the size of the parameter, we now limit the
  886. scope of global pruning to unstructured methods.
  887. Examples:
  888. >>> net = nn.Sequential(OrderedDict([
  889. ('first', nn.Linear(10, 4)),
  890. ('second', nn.Linear(4, 1)),
  891. ]))
  892. >>> parameters_to_prune = (
  893. (net.first, 'weight'),
  894. (net.second, 'weight'),
  895. )
  896. >>> prune.global_unstructured(
  897. parameters_to_prune,
  898. pruning_method=prune.L1Unstructured,
  899. amount=10,
  900. )
  901. >>> print(sum(torch.nn.utils.parameters_to_vector(net.buffers()) == 0))
  902. tensor(10, dtype=torch.uint8)
  903. """
  904. # ensure parameters is a list or generator of tuples
  905. if not isinstance(parameters, Iterable):
  906. raise TypeError("global_unstructured(): parameters is not an Iterable")
  907. importance_scores = importance_scores if importance_scores is not None else {}
  908. if not isinstance(importance_scores, dict):
  909. raise TypeError("global_unstructured(): importance_scores must be of type dict")
  910. # flatten importance scores to consider them all at once in global pruning
  911. relevant_importance_scores = torch.nn.utils.parameters_to_vector(
  912. [
  913. importance_scores.get((module, name), getattr(module, name))
  914. for (module, name) in parameters
  915. ]
  916. )
  917. # similarly, flatten the masks (if they exist), or use a flattened vector
  918. # of 1s of the same dimensions as t
  919. default_mask = torch.nn.utils.parameters_to_vector(
  920. [
  921. getattr(module, name + "_mask", torch.ones_like(getattr(module, name)))
  922. for (module, name) in parameters
  923. ]
  924. )
  925. # use the canonical pruning methods to compute the new mask, even if the
  926. # parameter is now a flattened out version of `parameters`
  927. container = PruningContainer()
  928. container._tensor_name = "temp" # to make it match that of `method`
  929. method = pruning_method(**kwargs)
  930. method._tensor_name = "temp" # to make it match that of `container`
  931. if method.PRUNING_TYPE != "unstructured":
  932. raise TypeError(
  933. 'Only "unstructured" PRUNING_TYPE supported for '
  934. "the `pruning_method`. Found method {} of type {}".format(
  935. pruning_method, method.PRUNING_TYPE
  936. )
  937. )
  938. container.add_pruning_method(method)
  939. # use the `compute_mask` method from `PruningContainer` to combine the
  940. # mask computed by the new method with the pre-existing mask
  941. final_mask = container.compute_mask(relevant_importance_scores, default_mask)
  942. # Pointer for slicing the mask to match the shape of each parameter
  943. pointer = 0
  944. for module, name in parameters:
  945. param = getattr(module, name)
  946. # The length of the parameter
  947. num_param = param.numel()
  948. # Slice the mask, reshape it
  949. param_mask = final_mask[pointer : pointer + num_param].view_as(param)
  950. # Assign the correct pre-computed mask to each parameter and add it
  951. # to the forward_pre_hooks like any other pruning method
  952. custom_from_mask(module, name, mask=param_mask)
  953. # Increment the pointer to continue slicing the final_mask
  954. pointer += num_param
  955. def custom_from_mask(module, name, mask):
  956. r"""Prunes tensor corresponding to parameter called ``name`` in ``module``
  957. by applying the pre-computed mask in ``mask``.
  958. Modifies module in place (and also return the modified module)
  959. by:
  960. 1) adding a named buffer called ``name+'_mask'`` corresponding to the
  961. binary mask applied to the parameter ``name`` by the pruning method.
  962. 2) replacing the parameter ``name`` by its pruned version, while the
  963. original (unpruned) parameter is stored in a new parameter named
  964. ``name+'_orig'``.
  965. Args:
  966. module (nn.Module): module containing the tensor to prune
  967. name (str): parameter name within ``module`` on which pruning
  968. will act.
  969. mask (Tensor): binary mask to be applied to the parameter.
  970. Returns:
  971. module (nn.Module): modified (i.e. pruned) version of the input module
  972. Examples:
  973. >>> m = prune.custom_from_mask(
  974. nn.Linear(5, 3), name='bias', mask=torch.tensor([0, 1, 0])
  975. )
  976. >>> print(m.bias_mask)
  977. tensor([0., 1., 0.])
  978. """
  979. CustomFromMask.apply(module, name, mask)
  980. return module
  981. def remove(module, name):
  982. r"""Removes the pruning reparameterization from a module and the
  983. pruning method from the forward hook. The pruned
  984. parameter named ``name`` remains permanently pruned, and the parameter
  985. named ``name+'_orig'`` is removed from the parameter list. Similarly,
  986. the buffer named ``name+'_mask'`` is removed from the buffers.
  987. Note:
  988. Pruning itself is NOT undone or reversed!
  989. Args:
  990. module (nn.Module): module containing the tensor to prune
  991. name (str): parameter name within ``module`` on which pruning
  992. will act.
  993. Examples:
  994. >>> m = random_unstructured(nn.Linear(5, 7), name='weight', amount=0.2)
  995. >>> m = remove(m, name='weight')
  996. """
  997. for k, hook in module._forward_pre_hooks.items():
  998. if isinstance(hook, BasePruningMethod) and hook._tensor_name == name:
  999. hook.remove(module)
  1000. del module._forward_pre_hooks[k]
  1001. return module
  1002. raise ValueError(
  1003. "Parameter '{}' of module {} has to be pruned "
  1004. "before pruning can be removed".format(name, module)
  1005. )
  1006. def is_pruned(module):
  1007. r"""Check whether ``module`` is pruned by looking for
  1008. ``forward_pre_hooks`` in its modules that inherit from the
  1009. :class:`BasePruningMethod`.
  1010. Args:
  1011. module (nn.Module): object that is either pruned or unpruned
  1012. Returns:
  1013. binary answer to whether ``module`` is pruned.
  1014. Examples:
  1015. >>> m = nn.Linear(5, 7)
  1016. >>> print(prune.is_pruned(m))
  1017. False
  1018. >>> prune.random_unstructured(m, name='weight', amount=0.2)
  1019. >>> print(prune.is_pruned(m))
  1020. True
  1021. """
  1022. for _, submodule in module.named_modules():
  1023. for _, hook in submodule._forward_pre_hooks.items():
  1024. if isinstance(hook, BasePruningMethod):
  1025. return True
  1026. return False
  1027. def _validate_pruning_amount_init(amount):
  1028. r"""Validation helper to check the range of amount at init.
  1029. Args:
  1030. amount (int or float): quantity of parameters to prune.
  1031. If float, should be between 0.0 and 1.0 and represent the
  1032. fraction of parameters to prune. If int, it represents the
  1033. absolute number of parameters to prune.
  1034. Raises:
  1035. ValueError: if amount is a float not in [0, 1], or if it's a negative
  1036. integer.
  1037. TypeError: if amount is neither a float nor an integer.
  1038. Note:
  1039. This does not take into account the number of parameters in the
  1040. tensor to be pruned, which is known only at prune.
  1041. """
  1042. if not isinstance(amount, numbers.Real):
  1043. raise TypeError(
  1044. "Invalid type for amount: {}. Must be int or float." "".format(amount)
  1045. )
  1046. if (isinstance(amount, numbers.Integral) and amount < 0) or (
  1047. not isinstance(amount, numbers.Integral) # so it's a float
  1048. and (float(amount) > 1.0 or float(amount) < 0.0)
  1049. ):
  1050. raise ValueError(
  1051. "amount={} should either be a float in the "
  1052. "range [0, 1] or a non-negative integer"
  1053. "".format(amount)
  1054. )
  1055. def _validate_pruning_amount(amount, tensor_size):
  1056. r"""Validation helper to check that the amount of parameters to prune
  1057. is meaningful wrt to the size of the data (`tensor_size`).
  1058. Args:
  1059. amount (int or float): quantity of parameters to prune.
  1060. If float, should be between 0.0 and 1.0 and represent the
  1061. fraction of parameters to prune. If int, it represents the
  1062. absolute number of parameters to prune.
  1063. tensor_size (int): absolute number of parameters in the tensor
  1064. to prune.
  1065. """
  1066. # TODO: consider removing this check and allowing users to specify
  1067. # a number of units to prune that is greater than the number of units
  1068. # left to prune. In this case, the tensor will just be fully pruned.
  1069. if isinstance(amount, numbers.Integral) and amount > tensor_size:
  1070. raise ValueError(
  1071. "amount={} should be smaller than the number of "
  1072. "parameters to prune={}".format(amount, tensor_size)
  1073. )
  1074. def _validate_structured_pruning(t):
  1075. r"""Validation helper to check that the tensor to be pruned is multi-
  1076. dimensional, such that the concept of "channels" is well-defined.
  1077. Args:
  1078. t (torch.Tensor): tensor representing the parameter to prune
  1079. Raises:
  1080. ValueError: if the tensor `t` is not at least 2D.
  1081. """
  1082. shape = t.shape
  1083. if len(shape) <= 1:
  1084. raise ValueError(
  1085. "Structured pruning can only be applied to "
  1086. "multidimensional tensors. Found tensor of shape "
  1087. "{} with {} dims".format(shape, len(shape))
  1088. )
  1089. def _compute_nparams_toprune(amount, tensor_size):
  1090. r"""Since amount can be expressed either in absolute value or as a
  1091. percentage of the number of units/channels in a tensor, this utility
  1092. function converts the percentage to absolute value to standardize
  1093. the handling of pruning.
  1094. Args:
  1095. amount (int or float): quantity of parameters to prune.
  1096. If float, should be between 0.0 and 1.0 and represent the
  1097. fraction of parameters to prune. If int, it represents the
  1098. absolute number of parameters to prune.
  1099. tensor_size (int): absolute number of parameters in the tensor
  1100. to prune.
  1101. Returns:
  1102. int: the number of units to prune in the tensor
  1103. """
  1104. # incorrect type already checked in _validate_pruning_amount_init
  1105. if isinstance(amount, numbers.Integral):
  1106. return amount
  1107. else:
  1108. return int(round(amount * tensor_size)) # int needed for Python 2
  1109. def _validate_pruning_dim(t, dim):
  1110. r"""
  1111. Args:
  1112. t (torch.Tensor): tensor representing the parameter to prune
  1113. dim (int): index of the dim along which we define channels to prune
  1114. """
  1115. if dim >= t.dim():
  1116. raise IndexError("Invalid index {} for tensor of size {}".format(dim, t.shape))
  1117. def _compute_norm(t, n, dim):
  1118. r"""Compute the L_n-norm across all entries in tensor `t` along all dimension
  1119. except for the one identified by dim.
  1120. Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim),
  1121. then norm will have Size [4], and each entry will represent the
  1122. `L_n`-norm computed using the 3x2=6 entries for each of the 4 channels.
  1123. Args:
  1124. t (torch.Tensor): tensor representing the parameter to prune
  1125. n (int, float, inf, -inf, 'fro', 'nuc'): See documentation of valid
  1126. entries for argument p in torch.norm
  1127. dim (int): dim identifying the channels to prune
  1128. Returns:
  1129. norm (torch.Tensor): L_n norm computed across all dimensions except
  1130. for `dim`. By construction, `norm.shape = t.shape[-1]`.
  1131. """
  1132. # dims = all axes, except for the one identified by `dim`
  1133. dims = list(range(t.dim()))
  1134. # convert negative indexing
  1135. if dim < 0:
  1136. dim = dims[dim]
  1137. dims.remove(dim)
  1138. norm = torch.norm(t, p=n, dim=dims)
  1139. return norm