prune.py 57 KB

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