class_docstr: A training loop.
class_docstr_tok: ["A","training","loop","."]
docstr: Load the state of the training loop from a checkpoint.
  
  :param path:
      Path of the file where to load the state from.
  :param triples_factory:
      The triples factory being used in the current training loop. This is being used to check whether the
      entity and relation to id mappings from the checkpoint match those provided by the current triples
      factory.
  
  :return:
      Temporary file path of the best epoch model and the best epoch when using early stoppers, None otherwise.
  
  :raises ValueError:
      If the internal optimizer is none
  :raises CheckpointMismatchError:
      If the given checkpoint file has a non-matching checksum, i.e. it was saved with a different configuration.
docstr_tok: ["Load","the","state","of","the","training","loop","from","a","checkpoint",".",":","param","path",":","Path","of","the","file","where","to","load","the","state","from",".",":","param","triples_factory",":","The","triples","factory","being","used","in","the","current","training","loop",".","This","is","being","used","to","check","whether","the","entity","and","relation","to","id","mappings","from","the","checkpoint","match","those","provided","by","the","current","triples","factory",".",":","return",":","Temporary","file","path","of","the","best","epoch","model","and","the","best","epoch","when","using","early","stoppers",",","None","otherwise",".",":","raises","ValueError",":","If","the","internal","optimizer","is","none",":","raises","CheckpointMismatchError",":","If","the","given","checkpoint","file","has","a","non-matching","checksum",",","i.e",".","it","was","saved","with","a","different","configuration","."]
code: def _load_state(
      self,
      path: Union[str, pathlib.Path],
      triples_factory: Optional[CoreTriplesFactory] = None,
  ) -> Tuple[Optional[pathlib.Path], Optional[int]]:
      """Load the state of the training loop from a checkpoint.
  
      :param path:
          Path of the file where to load the state from.
      :param triples_factory:
          The triples factory being used in the current training loop. This is being used to check whether the
          entity and relation to id mappings from the checkpoint match those provided by the current triples
          factory.
  
      :return:
          Temporary file path of the best epoch model and the best epoch when using early stoppers, None otherwise.
  
      :raises ValueError:
          If the internal optimizer is none
      :raises CheckpointMismatchError:
          If the given checkpoint file has a non-matching checksum, i.e. it was saved with a different configuration.
      """
      if self.optimizer is None:
          raise ValueError
  
      logger.info(f"=> loading checkpoint '{path}'")
      checkpoint = torch.load(path)
      if checkpoint["checksum"] != self.checksum:
          raise CheckpointMismatchError(
              f"The checkpoint file '{path}' that was provided already exists, but seems to be "
              f"from a different training loop setup.",
          )
      # Cuda requires its own random state, which can only be set when a cuda device is available
      torch_cuda_random_state = checkpoint["torch_cuda_random_state"]
      if (
          torch_cuda_random_state is not None
          and torch.cuda.is_available()
      ):
          torch.cuda.set_rng_state(torch_cuda_random_state)
      elif (
          torch_cuda_random_state is not None
          and not torch.cuda.is_available()
      ):
          logger.warning(
              "You're currently trying to resume the training loop on a CPU from a checkpoint that was saved "
              "with a GPU. Therefore, the random state for the CUDA devices can't be set and results may not "
              "be deterministic.",
          )
      elif (
          torch_cuda_random_state is None and torch.cuda.is_available()
      ):
          logger.warning(
              "You're currently trying to resume the training loop on a GPU from a checkpoint that was saved "
              "without a GPU. Therefore, the random state for the CUDA devices won't be set and results may not "
              "be deterministic.",
          )
  
      # If the checkpoint was saved with a best epoch model from the early stopper, this model has to be retrieved
      best_epoch_model_file_path = None
      best_epoch = None
      if checkpoint.get("best_epoch_model_checkpoint"):
          best_epoch_model_file_path = pathlib.Path(
              NamedTemporaryFile().name
          )
          best_epoch = checkpoint["best_epoch_model_checkpoint"][
              "epoch"
          ]
          torch.save(
              checkpoint["best_epoch_model_checkpoint"],
              best_epoch_model_file_path,
              pickle_protocol=pickle.HIGHEST_PROTOCOL,
          )
  
      # Check whether the triples factory mappings match those from the checkpoints
      relation_to_id_dict = checkpoint.get("relation_to_id_dict")
      entity_to_id_dict = checkpoint.get("entity_to_id_dict")
      if (
          relation_to_id_dict is not None
          and entity_to_id_dict is not None
          and triples_factory is not None
          and isinstance(triples_factory, TriplesFactory)
      ):
          if relation_to_id_dict != triples_factory.relation_to_id:
              logger.warning(
                  "The model provided by the checkpoint was trained on different relation_to_id mappings than the "
                  "ones provided by the current triples factory. This will most likely render the current learning "
                  "state of your model useless. This is usually caused by using a completely different dataset "
                  "or sampling a sub-dataset from a bigger dataset before handing it to the PyKEEN triples factory.",
              )
          if entity_to_id_dict != triples_factory.entity_to_id:
              logger.warning(
                  "The model provided by the checkpoint was trained on different entity_to_id mappings than the "
                  "ones provided by the current triples factory. This will most likely render the current learning "
                  "state of your model useless. This is usually caused by using a completely different dataset "
                  "or sampling a sub-dataset from a bigger dataset before handing it to the PyKEEN triples factory.",
              )
  
      self._epoch = checkpoint["epoch"]
      self.losses_per_epochs = checkpoint["loss"]
      self.model.load_state_dict(checkpoint["model_state_dict"])
      self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
      if self.lr_scheduler is not None:
          self.lr_scheduler.load_state_dict(
              checkpoint["lr_scheduler_state_dict"]
          )
      random.setstate(checkpoint["random_state"])
      np.random.set_state(checkpoint["np_random_state"])
      torch.random.set_rng_state(checkpoint["torch_random_state"])
      logger.info(
          f"=> loaded checkpoint '{path}' stopped after having finished epoch {checkpoint['epoch']}"
      )
  
      return best_epoch_model_file_path, best_epoch
  
imports: import gc
  import logging
  import os
  import pathlib
  import pickle
  import random
  import time
  from abc import ABC, abstractmethod
  from contextlib import ExitStack
  from datetime import datetime
  from hashlib import md5
  from tempfile import NamedTemporaryFile, TemporaryDirectory
  from typing import IO, Any, ClassVar, Generic, List, Mapping, Optional, Tuple, TypeVar, Union
  import numpy
  import torch
  from class_resolver import HintOrType, OptionalKwargs
  from class_resolver.contrib.torch import lr_scheduler_resolver, optimizer_resolver
  from torch.optim.optimizer import Optimizer
  from torch.utils.data import DataLoader
  from tqdm.autonotebook import tqdm, trange
  from .callbacks import GradientAbsClippingTrainingCallback, GradientNormClippingTrainingCallback, LearningRateSchedulerTrainingCallback, MultiTrainingCallback, OptimizerTrainingCallback, StopperTrainingCallback, TrackerTrainingCallback, TrainingCallback, TrainingCallbackHint, TrainingCallbackKwargsHint
  from ..constants import PYKEEN_CHECKPOINTS, PYKEEN_DEFAULT_CHECKPOINT
  from ..lr_schedulers import LRScheduler
  from ..models import RGCN, Model
  from ..stoppers import Stopper
  from ..trackers import ResultTracker, tracker_resolver
  from ..triples import CoreTriplesFactory, TriplesFactory
  from ..typing import InductiveMode
  from ..utils import format_relative_comparison, get_batchnorm_modules, get_preferred_device, is_cuda_oom_error, is_cudnn_error, normalize_string
label_desc: Use image node_id 19 for calling the TrainingLoop obj's underlying member method code with example usage: obj._load_state(path, triples_factory) and returns: best_epoch_model_file_path,  best_epoch