class_docstr: Stores a constituency model and its optimizer
  
  Not inheriting from common/trainer.py because there's no concept of change_lr (yet?)
class_docstr_tok: ["Stores","a","constituency","model","and","its","optimizer","Not","inheriting","from","common\/trainer.py","because","there","'s","no","concept","of","change_lr","(","yet","?",")"]
docstr: Load back a model and possibly its optimizer.
code: def load(
      filename, args=None, load_optimizer=False, foundation_cache=None
  ):
      """
      Load back a model and possibly its optimizer.
      """
      if not os.path.exists(filename):
          if args.get("save_dir", None) is None:
              raise FileNotFoundError(
                  "Cannot find model in {} and args['save_dir'] is None".format(
                      filename
                  )
              )
          elif os.path.exists(os.path.join(args["save_dir"], filename)):
              filename = os.path.join(args["save_dir"], filename)
          else:
              raise FileNotFoundError(
                  "Cannot find model in {} or in {}".format(
                      filename, os.path.join(args["save_dir"], filename)
                  )
              )
      try:
          checkpoint = torch.load(
              filename, lambda storage, loc: storage
          )
      except BaseException:
          logger.exception("Cannot load model from %s", filename)
          raise
      logger.debug("Loaded model from %s", filename)
  
      params = checkpoint["params"]
      model = Trainer.model_from_params(params, args, foundation_cache)
  
      epochs_trained = checkpoint["epochs_trained"]
      batches_trained = checkpoint.get("batches_trained", 0)
      best_f1 = checkpoint["best_f1"]
      best_epoch = checkpoint["best_epoch"]
  
      if load_optimizer:
          # we use params['config'] here instead of model.args
          # because the args might have a different training
          # mechanism, but in order to reload the optimizer, we need
          # to match the optimizer we build with the one that was
          # used at training time
          build_simple_adadelta = (
              params["config"]["multistage"]
              and epochs_trained < params["config"]["epochs"] // 2
          )
          logger.debug(
              "Model loaded was built with multistage %s  epochs_trained %d out of total epochs %d  Building initial Adadelta optimizer: %s",
              params["config"]["multistage"],
              epochs_trained,
              params["config"]["epochs"],
              build_simple_adadelta,
          )
          optimizer = build_optimizer(
              model.args, model, build_simple_adadelta
          )
  
          if checkpoint.get("optimizer_state_dict", None) is not None:
              optimizer.load_state_dict(
                  checkpoint["optimizer_state_dict"]
              )
          else:
              logger.info(
                  "Attempted to load optimizer to resume training, but optimizer not saved.  Creating new optimizer"
              )
  
          scheduler = build_scheduler(
              model.args,
              optimizer,
              first_optimizer=build_simple_adadelta,
          )
          if "scheduler_state_dict" in checkpoint:
              scheduler.load_state_dict(
                  checkpoint["scheduler_state_dict"]
              )
      else:
          optimizer = None
          scheduler = None
  
      logger.debug("-- MODEL CONFIG --")
      for k in model.args.keys():
          logger.debug("  --%s: %s", k, model.args[k])
  
      return Trainer(
          model=model,
          optimizer=optimizer,
          scheduler=scheduler,
          epochs_trained=epochs_trained,
          batches_trained=batches_trained,
          best_f1=best_f1,
          best_epoch=best_epoch,
      )
  
imports: from collections import Counter
  from collections import namedtuple
  import copy
  from enum import Enum
  import logging
  from operator import itemgetter
  import os
  import random
  import re
  import sys
  import torch
  from torch import nn
  from stanza.models.common import pretrain
  from stanza.models.common import utils
  from stanza.models.common.foundation_cache import load_bert, load_charlm, load_pretrain, FoundationCache
  from stanza.models.common.large_margin_loss import LargeMarginInSoftmaxLoss
  from stanza.models.constituency import parse_transitions
  from stanza.models.constituency import parse_tree
  from stanza.models.constituency import transition_sequence
  from stanza.models.constituency import tree_reader
  from stanza.models.constituency.base_model import SimpleModel, UNARY_LIMIT
  from stanza.models.constituency.in_order_oracle import InOrderOracle
  from stanza.models.constituency.lstm_model import LSTMModel, StackHistory
  from stanza.models.constituency.parse_transitions import TransitionScheme
  from stanza.models.constituency.parse_tree import Tree
  from stanza.models.constituency.utils import retag_tags, retag_trees, build_optimizer, build_scheduler
  from stanza.models.constituency.utils import DEFAULT_LEARNING_EPS, DEFAULT_LEARNING_RATES, DEFAULT_LEARNING_RHO, DEFAULT_WEIGHT_DECAY
  from stanza.server.parser_eval import EvaluateParser, ParseResult
  from stanza.utils.get_tqdm import get_tqdm
  from stanza.utils.training.common import find_wordvec_pretrain, choose_charlm, find_charlm_file
  from stanza.resources.default_packages import default_charlms, default_pretrains
label_desc: Use image node_id 6 for calling the Trainer obj's underlying member method code with example usage: obj.load(filename, args, load_optimizer, foundation_cache) and returns: Trainer