class_docstr: Checkpoint handler can be used to periodically save and load objects which have attribute
  ``state_dict/load_state_dict``. This class can use specific save handlers to store on the disk or a cloud
  storage, etc. The Checkpoint handler (if used with :class:`~ignite.handlers.DiskSaver`) also handles automatically
  moving data on TPU to CPU before writing the checkpoint.
  
  Args:
      to_save: Dictionary with the objects to save. Objects should have implemented ``state_dict`` and
          ``load_state_dict`` methods. If contains objects of type torch `DistributedDataParallel`_ or
          `DataParallel`_, their internal wrapped model is automatically saved (to avoid additional key ``module.`` in
          the state dictionary).
      save_handler: String, function or callable object.
          used to save engine and other provided objects. Function receives two objects: checkpoint as a dictionary
          and filename. If ``save_handler`` is callable class, it can
          inherit of :class:`~ignite.handlers.checkpoint.BaseSaveHandler` and optionally implement ``remove`` method
          to keep a fixed number of saved checkpoints. In case if user needs to save engine's checkpoint on a disk,
          ``save_handler`` can be defined with :class:`~ignite.handlers.DiskSaver` or a string specifying
          directory name can be passed to ``save_handler``.
      filename_prefix: Prefix for the file name to which objects will be saved. See Note for details.
      score_function: If not None, it should be a function taking a single argument,
          :class:`~ignite.engine.engine.Engine` object, and returning a score (`float`). Objects with highest scores
          will be retained.
      score_name: If ``score_function`` not None, it is possible to store its value using
          ``score_name``. If ``score_function`` is None, ``score_name`` can be used alone to define ``score_function``
          as ``Checkpoint.get_default_score_fn(score_name)`` by default.
      n_saved: Number of objects that should be kept on disk. Older files will be removed. If set to
          `None`, all objects are kept.
      global_step_transform: global step transform function to output a desired global step.
          Input of the function is ``(engine, event_name)``. Output of function should be an integer.
          Default is None, global_step based on attached engine. If provided, uses function output as global_step.
          To setup global step from another engine, please use :meth:`~ignite.handlers.global_step_from_engine`.
      filename_pattern: If ``filename_pattern`` is provided, this pattern will be used to render
          checkpoint filenames. If the pattern is not defined, the default pattern would be used. See Note for
          details.
      include_self: Whether to include the `state_dict` of this object in the checkpoint. If `True`, then
          there must not be another object in ``to_save`` with key ``checkpointer``.
      greater_or_equal: if `True`, the latest equally scored model is stored. Otherwise, the first model.
          Default, `False`.
      save_on_rank: Which rank to save the objects on, in the distributed configuration. If ``save_handler`` is
          string or :class:`~pathlib.Path`, this is also used to instantiate a :class:`~ignite.handlers.DiskSaver`.
  
  .. _DistributedDataParallel: https://pytorch.org/docs/stable/generated/
      torch.nn.parallel.DistributedDataParallel.html
  .. _DataParallel: https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html
  
  Note:
      This class stores a single file as a dictionary of provided objects to save.
      The filename is defined by ``filename_pattern`` and by default has the following
      structure: ``{filename_prefix}_{name}_{suffix}.{ext}`` where
  
      - ``filename_prefix`` is the argument passed to the constructor,
      - `name` is the key in ``to_save`` if a single object is to store, otherwise `name` is "checkpoint".
      - `suffix` is composed as following ``{global_step}_{score_name}={score}``.
  
  +----------------+------------+-----------------------+----------------------------------------------+
  | score_function | score_name | global_step_transform |  suffix                                      |
  +================+============+=======================+==============================================+
  |      None      |   None     |        None           | ``{engine.state.iteration}``                 |
  +----------------+------------+-----------------------+----------------------------------------------+
  |       X        |   None     |        None           | ``{score}``                                  |
  +----------------+------------+-----------------------+----------------------------------------------+
  |       X        |   None     |         X             | ``{global_step}_{score}``                    |
  +----------------+------------+-----------------------+----------------------------------------------+
  |       X        |    X       |         X             | ``{global_step}_{score_name}={score}``       |
  +----------------+------------+-----------------------+----------------------------------------------+
  |      None      |   None     |         X             | ``{global_step}``                            |
  +----------------+------------+-----------------------+----------------------------------------------+
  |       X        |    X       |        None           | ``{score_name}={score}``                     |
  +----------------+------------+-----------------------+----------------------------------------------+
  
  Above `global_step` defined by the output of `global_step_transform` and `score` defined by the output
  of `score_function`.
  
  By default, none of ``score_function``, ``score_name``, ``global_step_transform`` is defined, then suffix is
  setup by attached engine's current iteration. The filename will be
  `{filename_prefix}_{name}_{engine.state.iteration}.{ext}`.
  
  For example, ``score_name="neg_val_loss"`` and ``score_function`` that returns `-loss` (as objects with highest
  scores will be retained), then saved filename will be ``{filename_prefix}_{name}_neg_val_loss=-0.1234.pt``.
  
  Note:
      If ``filename_pattern`` is given, it will be used to render the filenames. ``filename_pattern`` is a string
      that can contain ``{filename_prefix}``, ``{name}``, ``{score}``, ``{score_name}`` and ``{global_step}`` as
      templates.
  
      For example, let ``filename_pattern="{global_step}-{name}-{score}.pt"`` then the saved filename will be
      ``30000-checkpoint-94.pt``
  
      **Warning:** Please, keep in mind that if filename collide with already used one to saved a checkpoint,
      new checkpoint will replace the older one. This means that filename like ``checkpoint.pt`` will be saved
      every call and will always be overwritten by newer checkpoints.
  
  Note:
      To get the last stored filename, handler exposes attribute ``last_checkpoint``:
  
      .. code-block:: python
  
          handler = Checkpoint(...)
          ...
          print(handler.last_checkpoint)
          > checkpoint_12345.pt
  
  Note:
      This class is distributed configuration-friendly: it is not required to instantiate the class in rank 0 only
      process. This class supports automatically distributed configuration and if used with
      :class:`~ignite.handlers.DiskSaver`, checkpoint is stored by rank 0 process.
  
  .. warning::
  
      When running on XLA devices or using :class:`~torch.distributed.optim.ZeroRedundancyOptimizer`, it
      should be run in all processes, otherwise application can get stuck while saving the checkpoint.
  
      .. code-block:: python
  
          # Wrong:
          # if idist.get_rank() == 0:
          #     handler = Checkpoint(...)
          #     trainer.add_event_handler(Events.ITERATION_COMPLETED(every=1000), handler)
  
          # Correct:
          handler = Checkpoint(...)
          trainer.add_event_handler(Events.ITERATION_COMPLETED(every=1000), handler)
  
  Examples:
      Attach the handler to make checkpoints during training:
  
      .. code-block:: python
  
          from ignite.engine import Engine, Events
          from ignite.handlers import Checkpoint
  
          trainer = ...
          model = ...
          optimizer = ...
          lr_scheduler = ...
  
          to_save = {'model': model, 'optimizer': optimizer, 'lr_scheduler': lr_scheduler, 'trainer': trainer}
  
          if (checkpoint_iters):
              # A: Output is "checkpoint_<iteration>.pt"
              handler = Checkpoint(
                  to_save, '/tmp/models', n_saved=2
              )
              trainer.add_event_handler(Events.ITERATION_COMPLETED(every=1000), handler)
          else:
              # B:Output is "checkpoint_<epoch>.pt"
              gst = lambda *_: trainer.state.epoch
              handler = Checkpoint(
                  to_save, '/tmp/models', n_saved=2, global_step_transform=gst
              )
              trainer.add_event_handler(Events.EPOCH_COMPLETED, handler)
  
          trainer.run(data_loader, max_epochs=6)
          > A: ["checkpoint_7000.pt", "checkpoint_8000.pt", ]
          > B: ["checkpoint_5.pt", "checkpoint_6.pt", ]
  
      Attach the handler to an evaluator to save best model during the training
      according to computed validation metric:
  
      .. code-block:: python
  
          from ignite.engine import Engine, Events
          from ignite.handlers import Checkpoint, global_step_from_engine
  
          trainer = ...
          evaluator = ...
          # Setup Accuracy metric computation on evaluator.
          # evaluator.state.metrics contain 'accuracy',
          # which will be used to define ``score_function`` automatically.
          # Run evaluation on epoch completed event
          # ...
  
          to_save = {'model': model}
          handler = Checkpoint(
              to_save, '/tmp/models',
              n_saved=2, filename_prefix='best',
              score_name="accuracy",
              global_step_transform=global_step_from_engine(trainer)
          )
  
          evaluator.add_event_handler(Events.COMPLETED, handler)
  
          trainer.run(data_loader, max_epochs=10)
          > ["best_model_9_accuracy=0.77.pt", "best_model_10_accuracy=0.78.pt", ]
  
      Customise the ``save_handler``:
  
      .. code-block:: python
  
          handler = Checkpoint(
              to_save, save_handler=DiskSaver('/tmp/models', create_dir=True, **kwargs), n_saved=2
          )
  
  .. versionchanged:: 0.4.3
  
      - Checkpoint can save model with same filename.
      - Added ``greater_or_equal`` argument.
  
  .. versionchanged:: 0.4.7
  
      - `score_name` can be used to define `score_function` automatically without providing `score_function`.
      - `save_handler` automatically saves to disk if path to directory is provided.
      - `save_on_rank` saves objects on this rank in a distributed configuration.
class_docstr_tok: ["Checkpoint","handler","can","be","used","to","periodically","save","and","load","objects","which","have","attribute","``","state_dict\/load_state_dict","``",".","This","class","can","use","specific","save","handlers","to","store","on","the","disk","or","a","cloud","storage",",","etc",".","The","Checkpoint","handler","(","if","used","with",":","class",":","`","~ignite.handlers.DiskSaver","`",")","also","handles","automatically","moving","data","on","TPU","to","CPU","before","writing","the","checkpoint",".","Args",":","to_save",":","Dictionary","with","the","objects","to","save",".","Objects","should","have","implemented","``","state_dict","``","and","``","load_state_dict","``","methods",".","If","contains","objects","of","type","torch","`","DistributedDataParallel","`","_","or","`","DataParallel","`","_",",","their","internal","wrapped","model","is","automatically","saved","(","to","avoid","additional","key","``","module.","``","in","the","state","dictionary",")",".","save_handler",":","String",",","function","or","callable","object",".","used","to","save","engine","and","other","provided","objects",".","Function","receives","two","objects",":","checkpoint","as","a","dictionary","and","filename",".","If","``","save_handler","``","is","callable","class",",","it","can","inherit","of",":","class",":","`","~ignite.handlers.checkpoint.BaseSaveHandler","`","and","optionally","implement","``","remove","``","method","to","keep","a","fixed","number","of","saved","checkpoints",".","In","case","if","user","needs","to","save","engine","'s","checkpoint","on","a","disk",",","``","save_handler","``","can","be","defined","with",":","class",":","`","~ignite.handlers.DiskSaver","`","or","a","string","specifying","directory","name","can","be","passed","to","``","save_handler","``",".","filename_prefix",":","Prefix","for","the","file","name","to","which","objects","will","be","saved",".","See","Note","for","details",".","score_function",":","If","not","None",",","it","should","be","a","function","taking","a","single","argument",",",":","class",":","`","~ignite.engine.engine.Engine","`","object",",","and","returning","a","score","(","`","float","`",")",".","Objects","with","highest","scores","will","be","retained",".","score_name",":","If","``","score_function","``","not","None",",","it","is","possible","to","store","its","value","using","``","score_name","``",".","If","``","score_function","``","is","None",",","``","score_name","``","can","be","used","alone","to","define","``","score_function","``","as","``","Checkpoint.get_default_score_fn","(","score_name",")","``","by","default",".","n_saved",":","Number","of","objects","that","should","be","kept","on","disk",".","Older","files","will","be","removed",".","If","set","to","`","None","`",",","all","objects","are","kept",".","global_step_transform",":","global","step","transform","function","to","output","a","desired","global","step",".","Input","of","the","function","is","``","(","engine",",","event_name",")","``",".","Output","of","function","should","be","an","integer",".","Default","is","None",",","global_step","based","on","attached","engine",".","If","provided",",","uses","function","output","as","global_step",".","To","setup","global","step","from","another","engine",",","please","use",":","meth",":","`","~ignite.handlers.global_step_from_engine","`",".","filename_pattern",":","If","``","filename_pattern","``","is","provided",",","this","pattern","will","be","used","to","render","checkpoint","filenames",".","If","the","pattern","is","not","defined",",","the","default","pattern","would","be","used",".","See","Note","for","details",".","include_self",":","Whether","to","include","the","`","state_dict","`","of","this","object","in","the","checkpoint",".","If","`","True","`",",","then","there","must","not","be","another","object","in","``","to_save","``","with","key","``","checkpointer","``",".","greater_or_equal",":","if","`","True","`",",","the","latest","equally","scored","model","is","stored",".","Otherwise",",","the","first","model",".","Default",",","`","False","`",".","save_on_rank",":","Which","rank","to","save","the","objects","on",",","in","the","distributed","configuration",".","If","``","save_handler","``","is","string","or",":","class",":","`","~pathlib.Path","`",",","this","is","also","used","to","instantiate","a",":","class",":","`","~ignite.handlers.DiskSaver","`",".","..","_DistributedDataParallel",":","https",":","\/\/pytorch.org\/docs\/stable\/generated\/","torch.nn.parallel.DistributedDataParallel.html","..","_DataParallel",":","https",":","\/\/pytorch.org\/docs\/stable\/generated\/torch.nn.DataParallel.html","Note",":","This","class","stores","a","single","file","as","a","dictionary","of","provided","objects","to","save",".","The","filename","is","defined","by","``","filename_pattern","``","and","by","default","has","the","following","structure",":","``","{","filename_prefix","}","_","{","name","}","_","{","suffix","}",".","{","ext","}","``","where","-","``","filename_prefix","``","is","the","argument","passed","to","the","constructor",",","-","`","name","`","is","the","key","in","``","to_save","``","if","a","single","object","is","to","store",",","otherwise","`","name","`","is","``","checkpoint","''",".","-","`","suffix","`","is","composed","as","following","``","{","global_step","}","_","{","score_name","}","=","{","score","}","``",".","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","score_function","|","score_name","|","global_step_transform","|","suffix","|","+================+============+=======================+==============================================+","|","None","|","None","|","None","|","``","{","engine.state.iteration","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","X","|","None","|","None","|","``","{","score","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","X","|","None","|","X","|","``","{","global_step","}","_","{","score","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","X","|","X","|","X","|","``","{","global_step","}","_","{","score_name","}","=","{","score","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","None","|","None","|","X","|","``","{","global_step","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","|","X","|","X","|","None","|","``","{","score_name","}","=","{","score","}","``","|","+","--","--","--","--","--","--","--","--","+","--","--","--","--","--","--","+","--","--","--","--","--","--","--","--","--","--","--","-+","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","--","+","Above","`","global_step","`","defined","by","the","output","of","`","global_step_transform","`","and","`","score","`","defined","by","the","output","of","`","score_function","`",".","By","default",",","none","of","``","score_function","``",",","``","score_name","``",",","``","global_step_transform","``","is","defined",",","then","suffix","is","setup","by","attached","engine","'s","current","iteration",".","The","filename","will","be","`","{","filename_prefix","}","_","{","name","}","_","{","engine.state.iteration","}",".","{","ext","}","`",".","For","example",",","``","score_name=","''","neg_val_loss","''","``","and","``","score_function","``","that","returns","`","-loss","`","(","as","objects","with","highest","scores","will","be","retained",")",",","then","saved","filename","will","be","``","{","filename_prefix","}","_","{","name","}","_neg_val_loss=-0.1234.pt","``",".","Note",":","If","``","filename_pattern","``","is","given",",","it","will","be","used","to","render","the","filenames",".","``","filename_pattern","``","is","a","string","that","can","contain","``","{","filename_prefix","}","``",",","``","{","name","}","``",",","``","{","score","}","``",",","``","{","score_name","}","``","and","``","{","global_step","}","``","as","templates",".","For","example",",","let","``","filename_pattern=","''","{","global_step","}","-","{","name","}","-","{","score","}",".pt","''","``","then","the","saved","filename","will","be","``","30000-checkpoint-94.pt","``","*","*","Warning",":","*","*","Please",",","keep","in","mind","that","if","filename","collide","with","already","used","one","to","saved","a","checkpoint",",","new","checkpoint","will","replace","the","older","one",".","This","means","that","filename","like","``","checkpoint.pt","``","will","be","saved","every","call","and","will","always","be","overwritten","by","newer","checkpoints",".","Note",":","To","get","the","last","stored","filename",",","handler","exposes","attribute","``","last_checkpoint","``",":","..","code-block",":",":","python","handler","=","Checkpoint","(","...",")","...","print","(","handler.last_checkpoint",")",">","checkpoint_12345.pt","Note",":","This","class","is","distributed","configuration-friendly",":","it","is","not","required","to","instantiate","the","class","in","rank","0","only","process",".","This","class","supports","automatically","distributed","configuration","and","if","used","with",":","class",":","`","~ignite.handlers.DiskSaver","`",",","checkpoint","is","stored","by","rank","0","process",".","..","warning",":",":","When","running","on","XLA","devices","or","using",":","class",":","`","~torch.distributed.optim.ZeroRedundancyOptimizer","`",",","it","should","be","run","in","all","processes",",","otherwise","application","can","get","stuck","while","saving","the","checkpoint",".","..","code-block",":",":","python","#","Wrong",":","#","if","idist.get_rank","(",")","==","0",":","#","handler","=","Checkpoint","(","...",")","#","trainer.add_event_handler","(","Events.ITERATION_COMPLETED","(","every=1000",")",",","handler",")","#","Correct",":","handler","=","Checkpoint","(","...",")","trainer.add_event_handler","(","Events.ITERATION_COMPLETED","(","every=1000",")",",","handler",")","Examples",":","Attach","the","handler","to","make","checkpoints","during","training",":","..","code-block",":",":","python","from","ignite.engine","import","Engine",",","Events","from","ignite.handlers","import","Checkpoint","trainer","=","...","model","=","...","optimizer","=","...","lr_scheduler","=","...","to_save","=","{","'model","'",":","model",",","'optimizer","'",":","optimizer",",","'lr_scheduler","'",":","lr_scheduler",",","'trainer","'",":","trainer","}","if","(","checkpoint_iters",")",":","#","A",":","Output","is","``","checkpoint_","<","iteration",">",".pt","''","handler","=","Checkpoint","(","to_save",",","'\/tmp\/models","'",",","n_saved=2",")","trainer.add_event_handler","(","Events.ITERATION_COMPLETED","(","every=1000",")",",","handler",")","else",":","#","B",":","Output","is","``","checkpoint_","<","epoch",">",".pt","''","gst","=","lambda","*","_",":","trainer.state.epoch","handler","=","Checkpoint","(","to_save",",","'\/tmp\/models","'",",","n_saved=2",",","global_step_transform=gst",")","trainer.add_event_handler","(","Events.EPOCH_COMPLETED",",","handler",")","trainer.run","(","data_loader",",","max_epochs=6",")",">","A",":","[","``","checkpoint_7000.pt","''",",","``","checkpoint_8000.pt","''",",","]",">","B",":","[","``","checkpoint_5.pt","''",",","``","checkpoint_6.pt","''",",","]","Attach","the","handler","to","an","evaluator","to","save","best","model","during","the","training","according","to","computed","validation","metric",":","..","code-block",":",":","python","from","ignite.engine","import","Engine",",","Events","from","ignite.handlers","import","Checkpoint",",","global_step_from_engine","trainer","=","...","evaluator","=","...","#","Setup","Accuracy","metric","computation","on","evaluator",".","#","evaluator.state.metrics","contain","'accuracy","'",",","#","which","will","be","used","to","define","``","score_function","``","automatically",".","#","Run","evaluation","on","epoch","completed","event","#","...","to_save","=","{","'model","'",":","model","}","handler","=","Checkpoint","(","to_save",",","'\/tmp\/models","'",",","n_saved=2",",","filename_prefix='best","'",",","score_name=","''","accuracy","''",",","global_step_transform=global_step_from_engine","(","trainer",")",")","evaluator.add_event_handler","(","Events.COMPLETED",",","handler",")","trainer.run","(","data_loader",",","max_epochs=10",")",">","[","``","best_model_9_accuracy=0.77.pt","''",",","``","best_model_10_accuracy=0.78.pt","''",",","]","Customise","the","``","save_handler","``",":","..","code-block",":",":","python","handler","=","Checkpoint","(","to_save",",","save_handler=DiskSaver","(","'\/tmp\/models","'",",","create_dir=True",",","*","*","kwargs",")",",","n_saved=2",")","..","versionchanged",":",":","0.4.3","-","Checkpoint","can","save","model","with","same","filename",".","-","Added","``","greater_or_equal","``","argument",".","..","versionchanged",":",":","0.4.7","-","`","score_name","`","can","be","used","to","define","`","score_function","`","automatically","without","providing","`","score_function","`",".","-","`","save_handler","`","automatically","saves","to","disk","if","path","to","directory","is","provided",".","-","`","save_on_rank","`","saves","objects","on","this","rank","in","a","distributed","configuration","."]
docstr: Helper method to apply ``load_state_dict`` on the objects from ``to_load`` using states from ``checkpoint``.
  
  Args:
      to_load: a dictionary with objects, e.g. `{"model": model, "optimizer": optimizer, ...}`
      checkpoint: a path, a string filepath or a dictionary with state_dicts to load, e.g.
          `{"model": model_state_dict, "optimizer": opt_state_dict}`. If `to_load` contains a single key,
          then checkpoint can contain directly corresponding state_dict.
      kwargs: Keyword arguments accepted for `nn.Module.load_state_dict()`. Passing `strict=False` enables
          the user to load part of the pretrained model (useful for example, in Transfer Learning)
  
  Examples:
      .. code-block:: python
  
          import tempfile
          from pathlib import Path
  
          import torch
  
          from ignite.engine import Engine, Events
          from ignite.handlers import ModelCheckpoint, Checkpoint
  
          trainer = Engine(lambda engine, batch: None)
  
          with tempfile.TemporaryDirectory() as tmpdirname:
              handler = ModelCheckpoint(tmpdirname, 'myprefix', n_saved=None, create_dir=True)
  
              model = torch.nn.Linear(3, 3)
              optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
  
              to_save = {"weights": model, "optimizer": optimizer}
  
              trainer.add_event_handler(Events.EPOCH_COMPLETED(every=2), handler, to_save)
              trainer.run(torch.randn(10, 1), 5)
  
              to_load = to_save
              checkpoint_fp = Path(tmpdirname) / 'myprefix_checkpoint_40.pt'
              checkpoint = torch.load(checkpoint_fp)
              Checkpoint.load_objects(to_load=to_load, checkpoint=checkpoint)
  
              # or using a string for checkpoint filepath
  
              to_load = to_save
              checkpoint_fp = Path(tmpdirname) / 'myprefix_checkpoint_40.pt'
              Checkpoint.load_objects(to_load=to_load, checkpoint=checkpoint_fp)
  
  Note:
      If ``to_load`` contains objects of type torch `DistributedDataParallel`_ or
      `DataParallel`_, method ``load_state_dict`` will applied to their internal wrapped model (``obj.module``).
  
  .. _DistributedDataParallel: https://pytorch.org/docs/stable/generated/
      torch.nn.parallel.DistributedDataParallel.html
  .. _DataParallel: https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html
docstr_tok: ["Helper","method","to","apply","``","load_state_dict","``","on","the","objects","from","``","to_load","``","using","states","from","``","checkpoint","``",".","Args",":","to_load",":","a","dictionary","with","objects",",","e.g",".","`","{","``","model","''",":","model",",","``","optimizer","''",":","optimizer",",","...","}","`","checkpoint",":","a","path",",","a","string","filepath","or","a","dictionary","with","state_dicts","to","load",",","e.g",".","`","{","``","model","''",":","model_state_dict",",","``","optimizer","''",":","opt_state_dict","}","`",".","If","`","to_load","`","contains","a","single","key",",","then","checkpoint","can","contain","directly","corresponding","state_dict",".","kwargs",":","Keyword","arguments","accepted","for","`","nn.Module.load_state_dict","(",")","`",".","Passing","`","strict=False","`","enables","the","user","to","load","part","of","the","pretrained","model","(","useful","for","example",",","in","Transfer","Learning",")","Examples",":","..","code-block",":",":","python","import","tempfile","from","pathlib","import","Path","import","torch","from","ignite.engine","import","Engine",",","Events","from","ignite.handlers","import","ModelCheckpoint",",","Checkpoint","trainer","=","Engine","(","lambda","engine",",","batch",":","None",")","with","tempfile.TemporaryDirectory","(",")","as","tmpdirname",":","handler","=","ModelCheckpoint","(","tmpdirname",",","'myprefix","'",",","n_saved=None",",","create_dir=True",")","model","=","torch.nn.Linear","(","3",",","3",")","optimizer","=","torch.optim.SGD","(","model.parameters","(",")",",","lr=1e-3",")","to_save","=","{","``","weights","''",":","model",",","``","optimizer","''",":","optimizer","}","trainer.add_event_handler","(","Events.EPOCH_COMPLETED","(","every=2",")",",","handler",",","to_save",")","trainer.run","(","torch.randn","(","10",",","1",")",",","5",")","to_load","=","to_save","checkpoint_fp","=","Path","(","tmpdirname",")","\/","'myprefix_checkpoint_40.pt'","checkpoint","=","torch.load","(","checkpoint_fp",")","Checkpoint.load_objects","(","to_load=to_load",",","checkpoint=checkpoint",")","#","or","using","a","string","for","checkpoint","filepath","to_load","=","to_save","checkpoint_fp","=","Path","(","tmpdirname",")","\/","'myprefix_checkpoint_40.pt'","Checkpoint.load_objects","(","to_load=to_load",",","checkpoint=checkpoint_fp",")","Note",":","If","``","to_load","``","contains","objects","of","type","torch","`","DistributedDataParallel","`","_","or","`","DataParallel","`","_",",","method","``","load_state_dict","``","will","applied","to","their","internal","wrapped","model","(","``","obj.module","``",")",".","..","_DistributedDataParallel",":","https",":","\/\/pytorch.org\/docs\/stable\/generated\/","torch.nn.parallel.DistributedDataParallel.html","..","_DataParallel",":","https",":","\/\/pytorch.org\/docs\/stable\/generated\/torch.nn.DataParallel.html"]
code: def load_objects(
      to_load: Mapping,
      checkpoint: Union[str, Mapping, Path],
      **kwargs: Any,
  ) -> None:
      """Helper method to apply ``load_state_dict`` on the objects from ``to_load`` using states from ``checkpoint``.
  
      Args:
          to_load: a dictionary with objects, e.g. `{"model": model, "optimizer": optimizer, ...}`
          checkpoint: a path, a string filepath or a dictionary with state_dicts to load, e.g.
              `{"model": model_state_dict, "optimizer": opt_state_dict}`. If `to_load` contains a single key,
              then checkpoint can contain directly corresponding state_dict.
          kwargs: Keyword arguments accepted for `nn.Module.load_state_dict()`. Passing `strict=False` enables
              the user to load part of the pretrained model (useful for example, in Transfer Learning)
  
      Examples:
          .. code-block:: python
  
              import tempfile
              from pathlib import Path
  
              import torch
  
              from ignite.engine import Engine, Events
              from ignite.handlers import ModelCheckpoint, Checkpoint
  
              trainer = Engine(lambda engine, batch: None)
  
              with tempfile.TemporaryDirectory() as tmpdirname:
                  handler = ModelCheckpoint(tmpdirname, 'myprefix', n_saved=None, create_dir=True)
  
                  model = torch.nn.Linear(3, 3)
                  optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
  
                  to_save = {"weights": model, "optimizer": optimizer}
  
                  trainer.add_event_handler(Events.EPOCH_COMPLETED(every=2), handler, to_save)
                  trainer.run(torch.randn(10, 1), 5)
  
                  to_load = to_save
                  checkpoint_fp = Path(tmpdirname) / 'myprefix_checkpoint_40.pt'
                  checkpoint = torch.load(checkpoint_fp)
                  Checkpoint.load_objects(to_load=to_load, checkpoint=checkpoint)
  
                  # or using a string for checkpoint filepath
  
                  to_load = to_save
                  checkpoint_fp = Path(tmpdirname) / 'myprefix_checkpoint_40.pt'
                  Checkpoint.load_objects(to_load=to_load, checkpoint=checkpoint_fp)
  
      Note:
          If ``to_load`` contains objects of type torch `DistributedDataParallel`_ or
          `DataParallel`_, method ``load_state_dict`` will applied to their internal wrapped model (``obj.module``).
  
      .. _DistributedDataParallel: https://pytorch.org/docs/stable/generated/
          torch.nn.parallel.DistributedDataParallel.html
      .. _DataParallel: https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html
      """
      if not isinstance(checkpoint, (collections.Mapping, str, Path)):
          raise TypeError(
              f"Argument checkpoint should be a string or a dictionary, but given {type(checkpoint)}"
          )
  
      Checkpoint._check_objects(to_load, "load_state_dict")
  
      if isinstance(checkpoint, (str, Path)):
          checkpoint_obj = torch.load(checkpoint)
      else:
          checkpoint_obj = checkpoint
  
      def _load_object(obj: Any, chkpt_obj: Any) -> None:
          if isinstance(
              obj,
              (nn.DataParallel, nn.parallel.DistributedDataParallel),
          ):
              obj = obj.module
  
          if isinstance(obj, torch.nn.Module):
              obj.load_state_dict(chkpt_obj, **kwargs)
          else:
              obj.load_state_dict(chkpt_obj)
  
      if len(to_load) == 1:
          # single object and checkpoint is directly a state_dict
          key, obj = list(to_load.items())[0]
          if key not in checkpoint_obj:
              _load_object(obj, checkpoint_obj)
              return
  
      _tree_apply2(_load_object, to_load, checkpoint_obj)
  
imports: import collections.abc
  import numbers
  import os
  import stat
  import tempfile
  from abc import ABCMeta, abstractmethod
  from collections import OrderedDict
  from pathlib import Path
  from typing import Any, Callable, cast, Dict, List, Mapping, NamedTuple, Optional, Union
  import torch
  import torch.nn
  from packaging.version import Version
  import ignite.distributed
  from ignite.base import Serializable
  from ignite.engine import Engine, Events
  from ignite.utils import _tree_apply2, _tree_map
label_desc: Use image node_id 11 for calling the Checkpoint obj's underlying member method code with example usage: obj.load_objects(to_load, checkpoint) without return types