class_docstr: Saves checkpoints and recovers from them.
  
  Arguments:
  
  checkpoints_dir : str, pathlib.Path
      Path to directory where to save checkpoints.
  recoverables : mapping, optional
      Objects to to recover. They need a (unique) name: this is used
      to connect the parameters in a checkpoint to the correct recoverable.
      The name is also used in the filename of the
      savefile for the objects parameters. These can also be added with
      add_recoverable or add_recoverables or just modifying
      checkpointer.recoverables directly.
  custom_load_hooks : mapping, optional
      A mapping from name [same as in recoverables] to function or method.
      Sets a custom loading hook for a particular object. The
      function/method must be callable with signature (instance, path)
      using positional arguments. This is satisfied by for example:
      `def loader(self, path)`.
  custom_save_hooks : mapping, optional
      Mapping from name [same as in recoverables] to function or method.
      Sets a custom saving hook for a particular object. The
      function/method must be callable with
      signature (instance, path) using positional arguments. This is
      satisfied by for example: def saver(self, path):
  allow_partial_load : bool, optional
      If True, allows loading a checkpoint where a savefile is not found
      for every registered recoverable. In that case, only the found
      savefiles are loaded. When False, loading such a save will raise
      RuntimeError. (default: False)
  
  Example
  -------
  >>> import torch
  >>> #SETUP:
  >>> tempdir = getfixture('tmpdir')
  >>> class Recoverable(torch.nn.Module):
  ...     def __init__(self, param):
  ...         super().__init__()
  ...         self.param = torch.nn.Parameter(torch.tensor([param]))
  ...     def forward(self, x):
  ...         return x * self.param
  >>> recoverable = Recoverable(1.)
  >>> recoverables = {'recoverable': recoverable}
  >>> # SETUP DONE.
  >>> checkpointer = Checkpointer(tempdir, recoverables)
  >>> first_ckpt = checkpointer.save_checkpoint()
  >>> recoverable.param.data = torch.tensor([2.])
  >>> loaded_ckpt = checkpointer.recover_if_possible()
  >>> # Parameter has been loaded:
  >>> assert recoverable.param.data == torch.tensor([1.])
  >>> # With this call, by default, oldest checkpoints are deleted:
  >>> checkpointer.save_and_keep_only()
  >>> assert first_ckpt not in checkpointer.list_checkpoints()
class_docstr_tok: ["Saves","checkpoints","and","recovers","from","them",".","Arguments",":","checkpoints_dir",":","str",",","pathlib.Path","Path","to","directory","where","to","save","checkpoints",".","recoverables",":","mapping",",","optional","Objects","to","to","recover",".","They","need","a","(","unique",")","name",":","this","is","used","to","connect","the","parameters","in","a","checkpoint","to","the","correct","recoverable",".","The","name","is","also","used","in","the","filename","of","the","savefile","for","the","objects","parameters",".","These","can","also","be","added","with","add_recoverable","or","add_recoverables","or","just","modifying","checkpointer.recoverables","directly",".","custom_load_hooks",":","mapping",",","optional","A","mapping","from","name","[","same","as","in","recoverables","]","to","function","or","method",".","Sets","a","custom","loading","hook","for","a","particular","object",".","The","function\/method","must","be","callable","with","signature","(","instance",",","path",")","using","positional","arguments",".","This","is","satisfied","by","for","example",":","`","def","loader","(","self",",","path",")","`",".","custom_save_hooks",":","mapping",",","optional","Mapping","from","name","[","same","as","in","recoverables","]","to","function","or","method",".","Sets","a","custom","saving","hook","for","a","particular","object",".","The","function\/method","must","be","callable","with","signature","(","instance",",","path",")","using","positional","arguments",".","This","is","satisfied","by","for","example",":","def","saver","(","self",",","path",")",":","allow_partial_load",":","bool",",","optional","If","True",",","allows","loading","a","checkpoint","where","a","savefile","is","not","found","for","every","registered","recoverable",".","In","that","case",",","only","the","found","savefiles","are","loaded",".","When","False",",","loading","such","a","save","will","raise","RuntimeError",".","(","default",":","False",")","Example","--","--","--","-",">",">",">","import","torch",">",">",">","#","SETUP",":",">",">",">","tempdir","=","getfixture","(","'tmpdir","'",")",">",">",">","class","Recoverable","(","torch.nn.Module",")",":","...","def","__init__","(","self",",","param",")",":","...","super","(",")",".__init__","(",")","...","self.param","=","torch.nn.Parameter","(","torch.tensor","(","[","param","]",")",")","...","def","forward","(","self",",","x",")",":","...","return","x","*","self.param",">",">",">","recoverable","=","Recoverable","(","1",".",")",">",">",">","recoverables","=","{","'recoverable","'",":","recoverable","}",">",">",">","#","SETUP","DONE",".",">",">",">","checkpointer","=","Checkpointer","(","tempdir",",","recoverables",")",">",">",">","first_ckpt","=","checkpointer.save_checkpoint","(",")",">",">",">","recoverable.param.data","=","torch.tensor","(","[","2",".","]",")",">",">",">","loaded_ckpt","=","checkpointer.recover_if_possible","(",")",">",">",">","#","Parameter","has","been","loaded",":",">",">",">","assert","recoverable.param.data","==","torch.tensor","(","[","1",".","]",")",">",">",">","#","With","this","call",",","by","default",",","oldest","checkpoints","are","deleted",":",">",">",">","checkpointer.save_and_keep_only","(",")",">",">",">","assert","first_ckpt","not","in","checkpointer.list_checkpoints","(",")"]
docstr: Deletes least important checkpoints.
  
  Since there can be many ways to define importance (e.g. lowest WER,
  lowest loss), the user should provide a list of sort key functions,
  each defining a particular importance order. In essence, each
  importance key function extracts one importance metric (higher is more
  important). For each of these orders, num_to_keep checkpoints are kept.
  However if there is overlap between each orders' preserved checkpoints,
  the additional checkpoints are not preserved, so the total number of
  preserved checkpoints can be less than::
  
      num_to_keep * len(importance_keys)
  
  Arguments
  ---------
  num_to_keep : int, optional
      Number of checkpoints to keep.
      Defaults to 10. You choose to keep 0. This deletes all
      checkpoints remaining after filtering. Must be >=0
  min_keys : list, optional
      List of strings representing keys in the meta. The lowest of
      these values will be kept, up to num_to_keep.
  max_keys : list, optional
      List of strings representing keys in the meta. The highest of
      these values will be kept, up to num_to_keep.
  importance_keys : list, optional
      A list of key functions used in sorting (see the sorted built-in).
      Each callable defines a sort order and num_to_keep checkpoints are
      kept for  callable. To be clear, those with the highest key are
      kept.
      The functions are called with Checkpoint namedtuples
      (see above). See also the default (ckpt_recency,
      above). The default deletes all but the latest checkpoint.
  ckpt_predicate : callable, optional
      Use this to exclude some checkpoints from deletion. Before any
      sorting, the list of checkpoints is filtered with this predicate.
      Only the checkpoints for which ckpt_predicate is True can be
      deleted. The function is called with Checkpoint namedtuples
      (see above).
  verbosity : logging level
      Set logging level for this deletion.
  
  Note
  ----
  Must be called with keyword arguments, as a signoff that you
  know what you are doing. Deletion is permanent.
docstr_tok: ["Deletes","least","important","checkpoints",".","Since","there","can","be","many","ways","to","define","importance","(","e.g",".","lowest","WER",",","lowest","loss",")",",","the","user","should","provide","a","list","of","sort","key","functions",",","each","defining","a","particular","importance","order",".","In","essence",",","each","importance","key","function","extracts","one","importance","metric","(","higher","is","more","important",")",".","For","each","of","these","orders",",","num_to_keep","checkpoints","are","kept",".","However","if","there","is","overlap","between","each","orders","'","preserved","checkpoints",",","the","additional","checkpoints","are","not","preserved",",","so","the","total","number","of","preserved","checkpoints","can","be","less","than",":",":","num_to_keep","*","len","(","importance_keys",")","Arguments","--","--","--","--","-","num_to_keep",":","int",",","optional","Number","of","checkpoints","to","keep",".","Defaults","to","10",".","You","choose","to","keep","0",".","This","deletes","all","checkpoints","remaining","after","filtering",".","Must","be",">","=0","min_keys",":","list",",","optional","List","of","strings","representing","keys","in","the","meta",".","The","lowest","of","these","values","will","be","kept",",","up","to","num_to_keep",".","max_keys",":","list",",","optional","List","of","strings","representing","keys","in","the","meta",".","The","highest","of","these","values","will","be","kept",",","up","to","num_to_keep",".","importance_keys",":","list",",","optional","A","list","of","key","functions","used","in","sorting","(","see","the","sorted","built-in",")",".","Each","callable","defines","a","sort","order","and","num_to_keep","checkpoints","are","kept","for","callable",".","To","be","clear",",","those","with","the","highest","key","are","kept",".","The","functions","are","called","with","Checkpoint","namedtuples","(","see","above",")",".","See","also","the","default","(","ckpt_recency",",","above",")",".","The","default","deletes","all","but","the","latest","checkpoint",".","ckpt_predicate",":","callable",",","optional","Use","this","to","exclude","some","checkpoints","from","deletion",".","Before","any","sorting",",","the","list","of","checkpoints","is","filtered","with","this","predicate",".","Only","the","checkpoints","for","which","ckpt_predicate","is","True","can","be","deleted",".","The","function","is","called","with","Checkpoint","namedtuples","(","see","above",")",".","verbosity",":","logging","level","Set","logging","level","for","this","deletion",".","Note","--","--","Must","be","called","with","keyword","arguments",",","as","a","signoff","that","you","know","what","you","are","doing",".","Deletion","is","permanent","."]
code: def delete_checkpoints(
      self,
      *,
      num_to_keep=1,
      min_keys=None,
      max_keys=None,
      importance_keys=[ckpt_recency],
      ckpt_predicate=None,
      verbosity=logging.INFO,
  ):
      """Deletes least important checkpoints.
  
      Since there can be many ways to define importance (e.g. lowest WER,
      lowest loss), the user should provide a list of sort key functions,
      each defining a particular importance order. In essence, each
      importance key function extracts one importance metric (higher is more
      important). For each of these orders, num_to_keep checkpoints are kept.
      However if there is overlap between each orders' preserved checkpoints,
      the additional checkpoints are not preserved, so the total number of
      preserved checkpoints can be less than::
  
          num_to_keep * len(importance_keys)
  
      Arguments
      ---------
      num_to_keep : int, optional
          Number of checkpoints to keep.
          Defaults to 10. You choose to keep 0. This deletes all
          checkpoints remaining after filtering. Must be >=0
      min_keys : list, optional
          List of strings representing keys in the meta. The lowest of
          these values will be kept, up to num_to_keep.
      max_keys : list, optional
          List of strings representing keys in the meta. The highest of
          these values will be kept, up to num_to_keep.
      importance_keys : list, optional
          A list of key functions used in sorting (see the sorted built-in).
          Each callable defines a sort order and num_to_keep checkpoints are
          kept for  callable. To be clear, those with the highest key are
          kept.
          The functions are called with Checkpoint namedtuples
          (see above). See also the default (ckpt_recency,
          above). The default deletes all but the latest checkpoint.
      ckpt_predicate : callable, optional
          Use this to exclude some checkpoints from deletion. Before any
          sorting, the list of checkpoints is filtered with this predicate.
          Only the checkpoints for which ckpt_predicate is True can be
          deleted. The function is called with Checkpoint namedtuples
          (see above).
      verbosity : logging level
          Set logging level for this deletion.
  
      Note
      ----
      Must be called with keyword arguments, as a signoff that you
      know what you are doing. Deletion is permanent.
      """
      if num_to_keep < 0:
          raise ValueError(
              "Number of checkpoints to keep must be positive."
          )
  
      # Build a list of potential deletions and protected checkpoints
      potential_deletions = set()
      protected_checkpoints = set()
      keys = [{"min_key": key} for key in min_keys or []]
      keys.extend([{"max_key": key} for key in max_keys or []])
      keys.extend([{"importance_key": key} for key in importance_keys])
  
      # Don't consider checkpoints for deletion that don't have a listed key
      for key_kwargs in keys:
          key_kwargs["ckpt_predicate"] = ckpt_predicate
          potential_deletions.update(
              self.find_checkpoints(**key_kwargs)
          )
          protected_checkpoints.update(
              self.find_checkpoints(
                  max_num_checkpoints=num_to_keep, **key_kwargs
              )
          )
  
      # Sync before deleting to avoid another process saving at the same time.
      # This has led to errors as documented here:
      # https://github.com/speechbrain/speechbrain/issues/2250
      ddp_barrier()
  
      # Delete unprotected checkpoints
      for ckpt in potential_deletions:
          if ckpt not in protected_checkpoints:
              Checkpointer._delete_checkpoint(ckpt, verbosity=verbosity)
  
      # Sync after deleting to avoid another process saving at the same time.
      # This has led to errors as documented here:
      # https://github.com/speechbrain/speechbrain/issues/2250
      ddp_barrier()
  
imports: import torch
  import collections
  import collections.abc
  import os
  import time
  import yaml
  import pathlib
  import inspect
  import shutil
  import logging
  import warnings
  from packaging import version
  import speechbrain.utils._workarounds
  from speechbrain.utils.distributed import main_process_only, if_main_process, ddp_barrier
label_desc: Use image node_id 11 for calling the Checkpointer obj's underlying member method code with example usage: obj.delete_checkpoints() without return types