


'''simple docstring'''






from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowercase							=logging.get_logger(__name__)

lowercase							={
    """flaubert/flaubert_small_cased""": """https://huggingface.co/flaubert/flaubert_small_cased/resolve/main/config.json""",
    """flaubert/flaubert_base_uncased""": """https://huggingface.co/flaubert/flaubert_base_uncased/resolve/main/config.json""",
    """flaubert/flaubert_base_cased""": """https://huggingface.co/flaubert/flaubert_base_cased/resolve/main/config.json""",
    """flaubert/flaubert_large_cased""": """https://huggingface.co/flaubert/flaubert_large_cased/resolve/main/config.json""",
}






class 					__magic_name__							(		_lowerCAmelCase				):
       UpperCAmelCase						      ="flaubert"
       UpperCAmelCase						      ={
           "hidden_size": "emb_dim",
           "num_attention_heads": "n_heads",
           "num_hidden_layers": "n_layers",
           "n_words": "vocab_size",  # For backward compatibility
       }






       def __init__(			self  ,							snake_case=False  ,							snake_case=0.0  ,							snake_case=3_0_1_4_5  ,							snake_case=2_0_4_8  ,							snake_case=1_2  ,							snake_case=1_6  ,							snake_case=0.1  ,							snake_case=0.1  ,							snake_case=True  ,							snake_case=False  ,							snake_case=False  ,							snake_case=False  ,							snake_case=1  ,							snake_case=True  ,							snake_case=5_1_2  ,							snake_case=2_0_4_8**-0.5  ,							snake_case=1E-1_2  ,							snake_case=0.02  ,							snake_case=0  ,							snake_case=1  ,							snake_case=2  ,							snake_case=3  ,							snake_case=5  ,							snake_case=True  ,							snake_case="first"  ,							snake_case=True  ,							snake_case=None  ,							snake_case=True  ,							snake_case=0.1  ,							snake_case=5  ,							snake_case=5  ,							snake_case=0  ,							snake_case=0  ,							snake_case=2  ,							snake_case=0  ,							**snake_case  ,							)						->  Any:




          '''simple docstring'''
          _UpperCAmelCase   :   List[Any]							    =pre_norm
          _UpperCAmelCase   :   Tuple							    =layerdrop
          _UpperCAmelCase   :   Union[str, Any]							    =vocab_size
          _UpperCAmelCase   :   Optional[int]							    =emb_dim
          _UpperCAmelCase   :   int							    =n_layers
          _UpperCAmelCase   :   Optional[Any]							    =n_heads
          _UpperCAmelCase   :   Optional[Any]							    =dropout
          _UpperCAmelCase   :   Union[str, Any]							    =attention_dropout
          _UpperCAmelCase   :   List[str]							    =gelu_activation
          _UpperCAmelCase   :   str							    =sinusoidal_embeddings
          _UpperCAmelCase   :   Optional[int]							    =causal
          _UpperCAmelCase   :   Union[str, Any]							    =asm
          _UpperCAmelCase   :   str							    =n_langs
          _UpperCAmelCase   :   Any							    =use_lang_emb
          _UpperCAmelCase   :   Dict							    =layer_norm_eps
          _UpperCAmelCase   :   List[Any]							    =bos_index
          _UpperCAmelCase   :   Dict							    =eos_index
          _UpperCAmelCase   :   List[Any]							    =pad_index
          _UpperCAmelCase   :   Tuple							    =unk_index
          _UpperCAmelCase   :   Any							    =mask_index
          _UpperCAmelCase   :   List[str]							    =is_encoder
          _UpperCAmelCase   :   Union[str, Any]							    =max_position_embeddings
          _UpperCAmelCase   :   Union[str, Any]							    =embed_init_std
          _UpperCAmelCase   :   int							    =init_std
          _UpperCAmelCase   :   Tuple							    =summary_type
          _UpperCAmelCase   :   Optional[Any]							    =summary_use_proj
          _UpperCAmelCase   :   int							    =summary_activation
          _UpperCAmelCase   :   int							    =summary_proj_to_labels
          _UpperCAmelCase   :   Union[str, Any]							    =summary_first_dropout
          _UpperCAmelCase   :   int							    =start_n_top
          _UpperCAmelCase   :   List[str]							    =end_n_top
          _UpperCAmelCase   :   Optional[int]							    =mask_token_id
          _UpperCAmelCase   :   int							    =lang_id

          if "n_words" in kwargs:
             _UpperCAmelCase   :   Dict							    =kwargs['n_words']

          super().__init__(pad_token_id=A__  ,							bos_token_id=A__  ,							**A__)






class 					__magic_name__							(		_lowerCAmelCase				):






       @property
       def 			lowerCAmelCase		(			self)						->  Mapping[str, Mapping[int, str]]:




          '''simple docstring'''
          if self.task == "multiple-choice":
             _UpperCAmelCase   :   Any							    ={0: 'batch', 1: 'choice', 2: 'sequence'}
          else:
             _UpperCAmelCase   :   List[str]							    ={0: 'batch', 1: 'sequence'}
          return OrderedDict(
              [
                  ('input_ids', dynamic_axis),
                  ('attention_mask', dynamic_axis),
              ])







import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


__SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=get_logger(__name__)

def 	lowerCAmelCase_	(     lowerCamelCase:				str   , lowerCamelCase:				List[dict]   , lowerCamelCase:				list   , lowerCamelCase:				list   , lowerCamelCase:				int   , lowerCamelCase:				GradScaler = None   , )    ->	Any:


      '''simple docstring'''




      for i, state in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Model weights saved in {output_model_file}"""  )
      # Optimizer states
      for i, opt in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = opt.state_dict()
            lowerCamelCase__					     = f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Optimizer state saved in {output_optimizer_file}"""  )
      # Scheduler states
      for i, scheduler in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = scheduler.state_dict()
            lowerCamelCase__					     = f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Scheduler state saved in {output_scheduler_file}"""  )
      # GradScaler state
      if scaler is not None:
            lowerCamelCase__					     = scaler.state_dict()
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            torch.save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Gradient scaler state saved in {output_scaler_file}"""  )
      # Random number generator states
      lowerCamelCase__					     = {}
      lowerCamelCase__					     = f"""{RNG_STATE_NAME}_{process_index}.pkl"""
      lowerCamelCase__					     = random.getstate()
      lowerCamelCase__					     = np.random.get_state()
      lowerCamelCase__					     = torch.get_rng_state()
      if is_xpu_available():
            lowerCamelCase__					     = torch.xpu.get_rng_state_all()
      else:
            lowerCamelCase__					     = torch.cuda.get_rng_state_all()
      if is_tpu_available():
            lowerCamelCase__					     = xm.get_rng_state()
      lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
      torch.save(lowerCamelCase   , lowerCamelCase  )
      logger.info(f"""Random states saved in {output_states_file}"""  )
      return output_dir

def 	lowerCAmelCase_	(     lowerCamelCase:				int   , lowerCamelCase:				Dict   , lowerCamelCase:				Union[str, Any]   , lowerCamelCase:				Any   , lowerCamelCase:				Any   , lowerCamelCase:				Any=None   , lowerCamelCase:				Dict=None   , **lowerCamelCase:				Optional[Any]   , )    ->	Any:


      '''simple docstring'''




      if map_location not in [None, "cpu", "on_device"]:
            raise TypeError(
                'Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'  )
      if map_location is None:
            lowerCamelCase__					     = 'cpu'
      elif map_location == "on_device":
            lowerCamelCase__					     = PartialState().device
      # Model states
      for i, model in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            models[i].load_state_dict(torch.load(lowerCamelCase   , map_location=lowerCamelCase  )   , **lowerCamelCase  )
      logger.info('All model weights loaded successfully'  )

      # Optimizer states
      for i, opt in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            lowerCamelCase__					     = torch.load(lowerCamelCase   , map_location=lowerCamelCase  )
            optimizers[i].load_state_dict(lowerCamelCase  )
      logger.info('All optimizer states loaded successfully'  )

      # Scheduler states
      for i, scheduler in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            scheduler.load_state_dict(torch.load(lowerCamelCase  )  )
      logger.info('All scheduler states loaded successfully'  )

      # GradScaler state
      if scaler is not None:
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            scaler.load_state_dict(torch.load(lowerCamelCase  )  )
            logger.info('GradScaler state loaded successfully'  )

      # Random states
      try:
            lowerCamelCase__					     = torch.load(os.path.join(lowerCamelCase   , f"""{RNG_STATE_NAME}_{process_index}.pkl"""  )  )
            random.setstate(states['random_state']  )
            np.random.set_state(states['numpy_random_seed']  )
            torch.set_rng_state(states['torch_manual_seed']  )
            if is_xpu_available():
                  torch.xpu.set_rng_state_all(states['torch_xpu_manual_seed']  )
            else:
                  torch.cuda.set_rng_state_all(states['torch_cuda_manual_seed']  )
            if is_tpu_available():
                  xm.set_rng_state(states['xm_seed']  )
            logger.info('All random states loaded successfully'  )
      except Exception:
            logger.info('Could not load random states'  )

def 	lowerCAmelCase_	(     lowerCamelCase:				Dict   , lowerCamelCase:				Any   , lowerCamelCase:				int = 0  )    ->	Union[str, Any]:


      '''simple docstring'''




      lowerCamelCase__					     = Path(lowerCamelCase  ) / f"""custom_checkpoint_{index}.pkl"""
      logger.info(f"""Saving the state of {get_pretty_name(lowerCamelCase  )} to {save_location}"""  )
      torch.save(obj.state_dict()   , lowerCamelCase  )


def 	lowerCAmelCase_	(     lowerCamelCase:				int   , lowerCamelCase:				Optional[int]   , lowerCamelCase:				int = 0  )    ->	Any:


      '''simple docstring'''




      lowerCamelCase__					     = f"""{path}/custom_checkpoint_{index}.pkl"""
      logger.info(f"""Loading the state of {get_pretty_name(lowerCamelCase  )} from {load_location}"""  )
      obj.load_state_dict(torch.load(lowerCamelCase   , map_location='cpu'  )  )