class_docstr: A pruning algorithm based on `To prune, or not to prune: exploring the efficacy of
  pruning for model compression <https://arxiv.org/pdf/1710.01878.pdf>`_. It extends the idea in the paper
  to different kinds of structured sparsity modes, in addition to unstructured sparsity. In order to
  achieve the desired sparsity, this algorithm sorts a module's weight matrix by the magnitude of
  its elements, and sets all elements less than a threshold to zero.
  
  Four different modes of sparsity are supported, encompassing both structured and unstructured
  sparsity. For details on how to select these different sparsity modes, please see
  :py:class:`ModuleMagnitudePrunerConfig`.
  
  Example:
          .. code-block:: python
  
              import torch
              from collections import OrderedDict
              from coremltools.optimize.torch.pruning import MagnitudePruner, MagnitudePrunerConfig
  
              # define model and loss function
              model = torch.nn.Sequential(
                  OrderedDict(
                      [
                          ("conv1", torch.nn.Conv2d(3, 32, 3, padding="same")),
                          ("conv2", torch.nn.Conv2d(32, 32, 3, padding="same")),
                      ]
                  )
              )
              loss_fn = define_loss()  # define the loss function
  
              # initialize pruner and configure it
              # we only prune the first conv layer
              config = MagnitudePrunerConfig.from_dict(
                  {
                      "module_name_configs": {
                          "conv1": {
                              "scheduler": {"update_steps": [3, 5, 7]},
                              "target_sparsity": 0.75,
                              "granularity": "per_channel",
                          },
                      }
                  }
              )
  
              pruner = MagnitudePruner(model, config)
  
              # insert pruning layers in the model
              model = pruner.prepare()
  
              for inputs, labels in data:
                  output = model(inputs)
                  loss = loss_fn(output, labels)
                  loss.backward()
                  optimizer.step()
                  pruner.step()
  
              # commit pruning masks to model parameters
              pruner.finalize(inplace=True)
  
  Args:
      model (:py:class:`torch.nn.Module`): Model on which the pruner will act.
      config (:py:class:`MagnitudePrunerConfig`): Config which specifies how
          different submodules in the model will be configured for pruning.
          Default config is used when passed as ``None``.
class_docstr_tok: ["A","pruning","algorithm","based","on","`","To","prune",",","or","not","to","prune",":","exploring","the","efficacy","of","pruning","for","model","compression","<","https",":","\/\/arxiv.org\/pdf\/1710.01878.pdf",">","`","_",".","It","extends","the","idea","in","the","paper","to","different","kinds","of","structured","sparsity","modes",",","in","addition","to","unstructured","sparsity",".","In","order","to","achieve","the","desired","sparsity",",","this","algorithm","sorts","a","module","'s","weight","matrix","by","the","magnitude","of","its","elements",",","and","sets","all","elements","less","than","a","threshold","to","zero",".","Four","different","modes","of","sparsity","are","supported",",","encompassing","both","structured","and","unstructured","sparsity",".","For","details","on","how","to","select","these","different","sparsity","modes",",","please","see",":","py",":","class",":","`","ModuleMagnitudePrunerConfig","`",".","Example",":","..","code-block",":",":","python","import","torch","from","collections","import","OrderedDict","from","coremltools.optimize.torch.pruning","import","MagnitudePruner",",","MagnitudePrunerConfig","#","define","model","and","loss","function","model","=","torch.nn.Sequential","(","OrderedDict","(","[","(","``","conv1","''",",","torch.nn.Conv2d","(","3",",","32",",","3",",","padding=","''","same","''",")",")",",","(","``","conv2","''",",","torch.nn.Conv2d","(","32",",","32",",","3",",","padding=","''","same","''",")",")",",","]",")",")","loss_fn","=","define_loss","(",")","#","define","the","loss","function","#","initialize","pruner","and","configure","it","#","we","only","prune","the","first","conv","layer","config","=","MagnitudePrunerConfig.from_dict","(","{","``","module_name_configs","''",":","{","``","conv1","''",":","{","``","scheduler","''",":","{","``","update_steps","''",":","[","3",",","5",",","7","]","}",",","``","target_sparsity","''",":","0.75",",","``","granularity","''",":","``","per_channel","''",",","}",",","}","}",")","pruner","=","MagnitudePruner","(","model",",","config",")","#","insert","pruning","layers","in","the","model","model","=","pruner.prepare","(",")","for","inputs",",","labels","in","data",":","output","=","model","(","inputs",")","loss","=","loss_fn","(","output",",","labels",")","loss.backward","(",")","optimizer.step","(",")","pruner.step","(",")","#","commit","pruning","masks","to","model","parameters","pruner.finalize","(","inplace=True",")","Args",":","model","(",":","py",":","class",":","`","torch.nn.Module","`",")",":","Model","on","which","the","pruner","will","act",".","config","(",":","py",":","class",":","`","MagnitudePrunerConfig","`",")",":","Config","which","specifies","how","different","submodules","in","the","model","will","be","configured","for","pruning",".","Default","config","is","used","when","passed","as","``","None","``","."]
code: def prepare(self, inplace: bool = False) -> _torch.nn.Module:
      if self._is_prepared:
          _logger.warning(
              "Model has already been prepared for pruning. This API call "
              "will be a no-op."
          )
          return self._model
      self._model = super().prepare(inplace=inplace)
      for name, submodule in self._model.named_modules(
          remove_duplicate=True
      ):
          submod_config = self._config.get_module_config(
              name, submodule
          )
          if (
              isinstance(submodule, self._supported_modules)
              and submod_config is not None
          ):
              submod_config = _copy.deepcopy(submod_config)
              if submod_config.n_m_ratio is not None:
                  num_zeros, block_size = submod_config.n_m_ratio
                  # Add target sparsity to make scheduler work
                  submod_config.target_sparsity = float(
                      num_zeros
                  ) / float(block_size)
              _MagnitudePruningMethod.from_module_and_params(
                  submodule,
                  param_name=submod_config.param_name,
                  amount=submod_config.initial_sparsity,
                  block_size=submod_config.block_size,
                  granularity=submod_config.granularity,
                  n_m_ratio=submod_config.n_m_ratio,
                  dim=submod_config.dim,
              )
              self._pruner_info[name] = _MagnitudePrunerInfo(
                  config=submod_config,
                  module=submodule,
                  sparsity_level=submod_config.initial_sparsity,
              )
      return self._model
  
imports: import copy
  import logging
  from collections import OrderedDict
  from typing import Any
  from typing import Callable
  from typing import Dict
  from typing import NewType
  from typing import Optional
  from typing import Tuple
  from typing import Union
  import attrs
  import cattrs
  import torch
  from attr import define
  from attr import field
  from attrs import validators
  from coremltools.optimize.torch._typing import ParamsDict
  from coremltools.optimize.torch.optimization_config import ModuleOptimizationConfig
  from coremltools.optimize.torch.optimization_config import OptimizationConfig
  from coremltools.optimize.torch.optimization_config import _structure_from_dict_hook_factory, _validate_module_type_keys_factory
  from coremltools.optimize.torch.pruning._base_pruner import BasePrunerWithPruningMethod
  from coremltools.optimize.torch.pruning._base_pruner import _allowed_granularity_values
  from coremltools.optimize.torch.pruning._base_pruning_method import ScheduledBaseDynamicPruningMethod
  from coremltools.optimize.torch.pruning._utils import magnitude_ranked_mask
  from coremltools.optimize.torch.pruning._utils import n_m_mask
  from coremltools.optimize.torch.pruning.pruning_scheduler import ConstantSparsityScheduler
  from coremltools.optimize.torch.pruning.pruning_scheduler import PruningScheduler
  from coremltools.optimize.torch.pruning.pruning_scheduler import _PruningSchedulerType
label_desc: Use image node_id 2 for calling the MagnitudePruner obj's underlying member method code with example usage: obj.prepare(inplace) and returns: self, self