




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


__SCREAMING_SNAKE_CASE    :   str       =os.path.expanduser(
    os.getenv("""HF_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """huggingface"""))
)
__SCREAMING_SNAKE_CASE    :   Optional[int]       =os.path.join(hf_cache_home, """accelerate""")
__SCREAMING_SNAKE_CASE    :   Tuple       =os.path.join(cache_dir, """default_config.yaml""")
__SCREAMING_SNAKE_CASE    :   Any       =os.path.join(cache_dir, """default_config.yaml""")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
      __SCREAMING_SNAKE_CASE    :   List[Any]       =default_yaml_config_file
else:
      __SCREAMING_SNAKE_CASE    :   Dict       =default_json_config_file

def 			lowerCAmelCase_			(  lowerCamelCase:       Tuple						)					->			Any:


      '''simple docstring'''




      if config_file is not None:
            if not os.path.isfile(lowerCamelCase						):
                  raise FileNotFoundError(
                      f"""The passed configuration file `{config_file}` does not exist. """
                      'Please pass an existing file to `accelerate launch`, or use the the default one '
                      'created through `accelerate config` and run `accelerate launch` '
                      'without the `--config_file` argument.'						)
      else:
            lowerCamelCase__        =				default_config_file
      with open(lowerCamelCase     ,				'r'     ,				encoding='utf-8'						) as f:
            if config_file.endswith('.json'						):
                  if (
                      json.load(lowerCamelCase						).get('compute_environment'     ,				ComputeEnvironment.LOCAL_MACHINE						)
                      == ComputeEnvironment.LOCAL_MACHINE
                  ):
                        lowerCamelCase__        =				ClusterConfig
                  else:
                        lowerCamelCase__        =				SageMakerConfig
                  return config_class.from_json_file(json_file=lowerCamelCase						)
            else:
                  if (
                      yaml.safe_load(lowerCamelCase						).get('compute_environment'     ,				ComputeEnvironment.LOCAL_MACHINE						)
                      == ComputeEnvironment.LOCAL_MACHINE
                  ):
                        lowerCamelCase__        =				ClusterConfig
                  else:
                        lowerCamelCase__        =				SageMakerConfig
                  return config_class.from_yaml_file(yaml_file=lowerCamelCase						)






@dataclass
class 			A			:
     """simple docstring"""

     _snake_case:	ComputeEnvironment
     _snake_case:	Union[DistributedType, SageMakerDistributedType]
     _snake_case:	str
     _snake_case:	bool




     def  __snake_case   (    self  :   List[str]			)				->       List[Any]:
           lowerCamelCase__        =				self.__dict__
           # For serialization, it's best to convert Enums to strings (or their underlying value type).
           for key, value in result.items():
                 if isinstance(A__	,  A__			):
                       lowerCamelCase__        =				value.value
                 if isinstance(A__	,  A__			) and not bool(A__			):
                       lowerCamelCase__        =				None
           lowerCamelCase__        =				{k: v for k, v in result.items() if v is not None}
           return result




     @classmethod
     def  __snake_case   (    cls  :   Union[str, Any]	,  A__  :   int=None			)				->       List[str]:
           lowerCamelCase__        =				default_json_config_file if json_file is None else json_file
           with open(A__	,  'r'	,  encoding='utf-8'			) as f:
                 lowerCamelCase__        =				json.load(A__			)
           if "compute_environment" not in config_dict:
                 lowerCamelCase__        =				ComputeEnvironment.LOCAL_MACHINE
           if "mixed_precision" not in config_dict:
                 lowerCamelCase__        =				'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
           if "fp16" in config_dict:  # Convert the config to the new format.
                 del config_dict["fp16"]
           if "dynamo_backend" in config_dict:  # Convert the config to the new format.
                 lowerCamelCase__        =				config_dict.pop('dynamo_backend'			)
                 lowerCamelCase__        =				{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
           if "use_cpu" not in config_dict:
                 lowerCamelCase__        =				False
           return cls(**A__			)




     def  __snake_case   (    self  :   str	,  A__  :   int			)				->       List[str]:
           with open(A__	,  'w'	,  encoding='utf-8'			) as f:
                 lowerCamelCase__        =				json.dumps(self.to_dict()	,  indent=2	,  sort_keys=A__			) + '\n'
                 f.write(A__			)




     @classmethod
     def  __snake_case   (    cls  :   Optional[Any]	,  A__  :   Optional[Any]=None			)				->       List[Any]:
           lowerCamelCase__        =				default_yaml_config_file if yaml_file is None else yaml_file
           with open(A__	,  'r'	,  encoding='utf-8'			) as f:
                 lowerCamelCase__        =				yaml.safe_load(A__			)
           if "compute_environment" not in config_dict:
                 lowerCamelCase__        =				ComputeEnvironment.LOCAL_MACHINE

           if "mixed_precision" not in config_dict:
                 lowerCamelCase__        =				'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
           if isinstance(config_dict['mixed_precision']	,  A__			) and not config_dict["mixed_precision"]:
                 lowerCamelCase__        =				'no'
           if "fp16" in config_dict:  # Convert the config to the new format.
                 del config_dict["fp16"]
           if "dynamo_backend" in config_dict:  # Convert the config to the new format.
                 lowerCamelCase__        =				config_dict.pop('dynamo_backend'			)
                 lowerCamelCase__        =				{} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
           if "use_cpu" not in config_dict:
                 lowerCamelCase__        =				False
           return cls(**A__			)




     def  __snake_case   (    self  :   Tuple	,  A__  :   Union[str, Any]			)				->       Tuple:
           with open(A__	,  'w'	,  encoding='utf-8'			) as f:
                 yaml.safe_dump(self.to_dict()	,  A__			)




     def  __snake_case   (    self  :   Union[str, Any]			)				->       Dict:
           if isinstance(self.compute_environment	,  A__			):
                 lowerCamelCase__        =				ComputeEnvironment(self.compute_environment			)
           if isinstance(self.distributed_type	,  A__			):
                 if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                       lowerCamelCase__        =				SageMakerDistributedType(self.distributed_type			)
                 else:
                       lowerCamelCase__        =				DistributedType(self.distributed_type			)
           if self.dynamo_config is None:
                 lowerCamelCase__        =				{}






@dataclass
class 			A			(		_lowerCAmelCase		):
     """simple docstring"""

     _snake_case:	int
     _snake_case:	int     =0
     _snake_case:	int     =1
     _snake_case:	Optional[str]     =None
     _snake_case:	Optional[str]     =None
     _snake_case:	Optional[int]     =None
     _snake_case:	Optional[str]     ="static"
     _snake_case:	Optional[bool]     =False
     _snake_case:	str     ="main"

     # args for deepspeed_plugin
     _snake_case:	dict     =None
     # args for fsdp
     _snake_case:	dict     =None
     # args for megatron_lm
     _snake_case:	dict     =None
     # args for ipex
     _snake_case:	dict     =None
     # args for TPU
     _snake_case:	bool     =False

     # args for TPU pods
     _snake_case:	str     =None
     _snake_case:	str     =None
     _snake_case:	bool     =False
     _snake_case:	bool     =False
     _snake_case:	str     =None
     _snake_case:	List[str]     =None
     _snake_case:	List[str]     =None
     _snake_case:	List[str]     =None

     # args for dynamo
     _snake_case:	dict     =None




     def  __snake_case   (    self  :   Optional[int]			)				->       List[str]:
           if self.deepspeed_config is None:
                 lowerCamelCase__        =				{}
           if self.fsdp_config is None:
                 lowerCamelCase__        =				{}
           if self.megatron_lm_config is None:
                 lowerCamelCase__        =				{}
           if self.ipex_config is None:
                 lowerCamelCase__        =				{}
           return super().__post_init__()






@dataclass
class 			A			(		_lowerCAmelCase		):
     """simple docstring"""

     _snake_case:	str
     _snake_case:	str
     _snake_case:	Optional[str]     =None
     _snake_case:	Optional[str]     =None
     _snake_case:	str     ="us-east-1"
     _snake_case:	int     =1
     _snake_case:	str     ="all"
     _snake_case:	str     =f"""accelerate-sagemaker-{num_machines}"""
     _snake_case:	str     =SAGEMAKER_PYTORCH_VERSION
     _snake_case:	str     =SAGEMAKER_TRANSFORMERS_VERSION
     _snake_case:	str     =SAGEMAKER_PYTHON_VERSION
     _snake_case:	str     =None
     _snake_case:	str     =None
     _snake_case:	dict     =None
     _snake_case:	dict     =None





import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_longformer import LongformerTokenizer


__SCREAMING_SNAKE_CASE    :   Dict       =logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE    :   str       ={"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

__SCREAMING_SNAKE_CASE    :   Dict       ={
    """vocab_file""": {
        """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json""",
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json"""
        ),
    },
    """merges_file""": {
        """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt""",
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt"""
        ),
    },
    """tokenizer_file""": {
        """allenai/longformer-base-4096""": (
            """https://huggingface.co/allenai/longformer-base-4096/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096""": (
            """https://huggingface.co/allenai/longformer-large-4096/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096-finetuned-triviaqa""": (
            """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-base-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/tokenizer.json"""
        ),
        """allenai/longformer-large-4096-extra.pos.embd.only""": (
            """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/tokenizer.json"""
        ),
    },
}

__SCREAMING_SNAKE_CASE    :   int       ={
    """allenai/longformer-base-4096""": 4_096,
    """allenai/longformer-large-4096""": 4_096,
    """allenai/longformer-large-4096-finetuned-triviaqa""": 4_096,
    """allenai/longformer-base-4096-extra.pos.embd.only""": 4_096,
    """allenai/longformer-large-4096-extra.pos.embd.only""": 4_096,
}






class 			A			(		_lowerCAmelCase		):
     """simple docstring"""

     _snake_case:	Optional[Any]     =VOCAB_FILES_NAMES
     _snake_case:	List[str]     =PRETRAINED_VOCAB_FILES_MAP
     _snake_case:	str     =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _snake_case:	str     =["input_ids", "attention_mask"]
     _snake_case:	Union[str, Any]     =LongformerTokenizer




     def __init__(    self  :   str	,  A__  :   Optional[Any]=None	,  A__  :   Dict=None	,  A__  :   Any=None	,  A__  :   Optional[Any]="replace"	,  A__  :   Tuple="<s>"	,  A__  :   Any="</s>"	,  A__  :   Dict="</s>"	,  A__  :   Any="<s>"	,  A__  :   Optional[Any]="<unk>"	,  A__  :   Tuple="<pad>"	,  A__  :   Union[str, Any]="<mask>"	,  A__  :   List[str]=False	,  A__  :   List[str]=True	,  **A__  :   Optional[int]	,  )				->       List[str]:
           super().__init__(
               A__	,  A__	,  tokenizer_file=A__	,  errors=A__	,  bos_token=A__	,  eos_token=A__	,  sep_token=A__	,  cls_token=A__	,  unk_token=A__	,  pad_token=A__	,  mask_token=A__	,  add_prefix_space=A__	,  trim_offsets=A__	,  **A__	,  )

           lowerCamelCase__        =				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()			)
           if pre_tok_state.get('add_prefix_space'	,  A__			) != add_prefix_space:
                 lowerCamelCase__        =				getattr(A__	,  pre_tok_state.pop('type'			)			)
                 lowerCamelCase__        =				add_prefix_space
                 lowerCamelCase__        =				pre_tok_class(**A__			)

           lowerCamelCase__        =				add_prefix_space

           lowerCamelCase__        =				'post_processor'
           lowerCamelCase__        =				getattr(self.backend_tokenizer	,  A__	,  A__			)
           if tokenizer_component_instance:
                 lowerCamelCase__        =				json.loads(tokenizer_component_instance.__getstate__()			)

                 # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
                 if "sep" in state:
                       lowerCamelCase__        =				tuple(state['sep']			)
                 if "cls" in state:
                       lowerCamelCase__        =				tuple(state['cls']			)

                 lowerCamelCase__        =				False

                 if state.get('add_prefix_space'	,  A__			) != add_prefix_space:
                       lowerCamelCase__        =				add_prefix_space
                       lowerCamelCase__        =				True

                 if state.get('trim_offsets'	,  A__			) != trim_offsets:
                       lowerCamelCase__        =				trim_offsets
                       lowerCamelCase__        =				True

                 if changes_to_apply:
                       lowerCamelCase__        =				getattr(A__	,  state.pop('type'			)			)
                       lowerCamelCase__        =				component_class(**A__			)
                       setattr(self.backend_tokenizer	,  A__	,  A__			)




     @property
     def  __snake_case   (    self  :   Tuple			)				->       str:
           if self._mask_token is None:
                 if self.verbose:
                       logger.error('Using mask_token, but it is not set yet.'			)
                 return None
           return str(self._mask_token			)




     @mask_token.setter
     def  __snake_case   (    self  :   Dict	,  A__  :   Tuple			)				->       int:
           lowerCamelCase__        =				AddedToken(A__	,  lstrip=A__	,  rstrip=A__			) if isinstance(A__	,  A__			) else value
           lowerCamelCase__        =				value




     def  __snake_case   (    self  :   Any	,  *A__  :   Any	,  **A__  :   Any			)				->       BatchEncoding:
           lowerCamelCase__        =				kwargs.get('is_split_into_words'	,  A__			)
           assert self.add_prefix_space or not is_split_into_words, (
               F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
               "to use it with pretokenized inputs."
           )

           return super()._batch_encode_plus(*A__	,  **A__			)




     def  __snake_case   (    self  :   Tuple	,  *A__  :   str	,  **A__  :   int			)				->       BatchEncoding:
           lowerCamelCase__        =				kwargs.get('is_split_into_words'	,  A__			)

           assert self.add_prefix_space or not is_split_into_words, (
               F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
               "to use it with pretokenized inputs."
           )

           return super()._encode_plus(*A__	,  **A__			)




     def  __snake_case   (    self  :   Union[str, Any]	,  A__  :   str	,  A__  :   Optional[str] = None			)				->       Tuple[str]:
           lowerCamelCase__        =				self._tokenizer.model.save(A__	,  name=A__			)
           return tuple(A__			)




     def  __snake_case   (    self  :   Any	,  A__  :   int	,  A__  :   List[str]=None			)				->       Dict:
           lowerCamelCase__        =				[self.bos_token_id] + token_ids_a + [self.eos_token_id]
           if token_ids_a is None:
                 return output

           return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]




     def  __snake_case   (    self  :   Union[str, Any]	,  A__  :   List[int]	,  A__  :   Optional[List[int]] = None			)				->       List[int]:
           lowerCamelCase__        =				[self.sep_token_id]
           lowerCamelCase__        =				[self.cls_token_id]

           if token_ids_a is None:
                 return len(cls + token_ids_a + sep			) * [0]
           return len(cls + token_ids_a + sep + sep + token_ids_a + sep			) * [0]