prune.py 57 KB

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