

# 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


A__        =			os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
A__        =			os.path.join(hf_cache_home, "accelerate")
A__        =			os.path.join(cache_dir, "default_config.yaml")
A__        =			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):
  A__        =			default_yaml_config_file
else:
  A__        =			default_json_config_file





def 							__a       (					__A	):
    if config_file is not None:
        if not os.path.isfile(__A	):
            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:
        SCREAMING_SNAKE_CASE__					     =						default_config_file
    with open(__A ,       "r" ,       encoding="utf-8"	) as f:
        if config_file.endswith(".json"	):
            if (
                json.load(__A	).get("compute_environment" ,       ComputeEnvironment.LOCAL_MACHINE	)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                SCREAMING_SNAKE_CASE__					     =						ClusterConfig
            else:
                SCREAMING_SNAKE_CASE__					     =						SageMakerConfig
            return config_class.from_json_file(json_file=__A	)
        else:
            if (
                yaml.safe_load(__A	).get("compute_environment" ,       ComputeEnvironment.LOCAL_MACHINE	)
                == ComputeEnvironment.LOCAL_MACHINE
            ):
                SCREAMING_SNAKE_CASE__					     =						ClusterConfig
            else:
                SCREAMING_SNAKE_CASE__					     =						SageMakerConfig
            return config_class.from_yaml_file(yaml_file=__A	)







@dataclass
class    UpperCamelCase_			:


  """simple docstring"""
  SCREAMING_SNAKE_CASE__				: ComputeEnvironment
  SCREAMING_SNAKE_CASE__				: Union[DistributedType, SageMakerDistributedType]
  SCREAMING_SNAKE_CASE__				: str
  SCREAMING_SNAKE_CASE__				: bool



  def      _UpperCamelCase    (	self    :				int	)					-> int:
      SCREAMING_SNAKE_CASE__					     =						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_	):
              SCREAMING_SNAKE_CASE__					     =						value.value
          if isinstance(A_     ,  A_	) and not bool(A_	):
              SCREAMING_SNAKE_CASE__					     =						None
      SCREAMING_SNAKE_CASE__					     =						{k: v for k, v in result.items() if v is not None}
      return result



  @classmethod
  def      _UpperCamelCase    (	cls    :				Union[str, Any]     ,  A_    :				Union[str, Any]=None	)					-> int:
      SCREAMING_SNAKE_CASE__					     =						default_json_config_file if json_file is None else json_file
      with open(A_     ,  "r"     ,  encoding="utf-8"	) as f:
          SCREAMING_SNAKE_CASE__					     =						json.load(A_	)
      if "compute_environment" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						ComputeEnvironment.LOCAL_MACHINE
      if "mixed_precision" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						"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.
          SCREAMING_SNAKE_CASE__					     =						config_dict.pop("dynamo_backend"	)
          SCREAMING_SNAKE_CASE__					     =						{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						False
      return cls(**A_	)



  def      _UpperCamelCase    (	self    :				Any     ,  A_    :				Any	)					-> Optional[Any]:
      with open(A_     ,  "w"     ,  encoding="utf-8"	) as f:
          SCREAMING_SNAKE_CASE__					     =						json.dumps(self.to_dict()     ,  indent=2     ,  sort_keys=A_	) + "\n"
          f.write(A_	)



  @classmethod
  def      _UpperCamelCase    (	cls    :				Union[str, Any]     ,  A_    :				List[str]=None	)					-> Tuple:
      SCREAMING_SNAKE_CASE__					     =						default_yaml_config_file if yaml_file is None else yaml_file
      with open(A_     ,  "r"     ,  encoding="utf-8"	) as f:
          SCREAMING_SNAKE_CASE__					     =						yaml.safe_load(A_	)
      if "compute_environment" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						ComputeEnvironment.LOCAL_MACHINE

      if "mixed_precision" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						"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"]:
          SCREAMING_SNAKE_CASE__					     =						"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.
          SCREAMING_SNAKE_CASE__					     =						config_dict.pop("dynamo_backend"	)
          SCREAMING_SNAKE_CASE__					     =						{} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend}
      if "use_cpu" not in config_dict:
          SCREAMING_SNAKE_CASE__					     =						False
      return cls(**A_	)



  def      _UpperCamelCase    (	self    :				Tuple     ,  A_    :				Optional[int]	)					-> Any:
      with open(A_     ,  "w"     ,  encoding="utf-8"	) as f:
          yaml.safe_dump(self.to_dict()     ,  A_	)







  def      _UpperCamelCase    (	self    :				int	)					-> Dict:
      if isinstance(self.compute_environment     ,  A_	):
          SCREAMING_SNAKE_CASE__					     =						ComputeEnvironment(self.compute_environment	)
      if isinstance(self.distributed_type     ,  A_	):
          if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
              SCREAMING_SNAKE_CASE__					     =						SageMakerDistributedType(self.distributed_type	)
          else:
              SCREAMING_SNAKE_CASE__					     =						DistributedType(self.distributed_type	)
      if self.dynamo_config is None:
          SCREAMING_SNAKE_CASE__					     =						{}







@dataclass
class    UpperCamelCase_			(  _snake_case			):


  """simple docstring"""
  SCREAMING_SNAKE_CASE__				: int
  SCREAMING_SNAKE_CASE__				: int										=      0
  SCREAMING_SNAKE_CASE__				: int										=      1
  SCREAMING_SNAKE_CASE__				: Optional[str]										=      None
  SCREAMING_SNAKE_CASE__				: Optional[str]										=      None
  SCREAMING_SNAKE_CASE__				: Optional[int]										=      None
  SCREAMING_SNAKE_CASE__				: Optional[str]										=      "static"
  SCREAMING_SNAKE_CASE__				: Optional[bool]										=      False
  SCREAMING_SNAKE_CASE__				: str										=      "main"

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

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

  # args for dynamo
  SCREAMING_SNAKE_CASE__				: dict										=      None



  def      _UpperCamelCase    (	self    :				Dict	)					-> str:
      if self.deepspeed_config is None:
          SCREAMING_SNAKE_CASE__					     =						{}
      if self.fsdp_config is None:
          SCREAMING_SNAKE_CASE__					     =						{}
      if self.megatron_lm_config is None:
          SCREAMING_SNAKE_CASE__					     =						{}
      if self.ipex_config is None:
          SCREAMING_SNAKE_CASE__					     =						{}
      return super().__post_init__()







@dataclass
class    UpperCamelCase_			(  _snake_case			):


  """simple docstring"""
  SCREAMING_SNAKE_CASE__				: str
  SCREAMING_SNAKE_CASE__				: str
  SCREAMING_SNAKE_CASE__				: Optional[str]										=      None
  SCREAMING_SNAKE_CASE__				: Optional[str]										=      None
  SCREAMING_SNAKE_CASE__				: str										=      "us-east-1"
  SCREAMING_SNAKE_CASE__				: int										=      1
  SCREAMING_SNAKE_CASE__				: str										=      "all"
  SCREAMING_SNAKE_CASE__				: str										=      F'''accelerate-sagemaker-{num_machines}'''
  SCREAMING_SNAKE_CASE__				: str										=      SAGEMAKER_PYTORCH_VERSION
  SCREAMING_SNAKE_CASE__				: str										=      SAGEMAKER_TRANSFORMERS_VERSION
  SCREAMING_SNAKE_CASE__				: str										=      SAGEMAKER_PYTHON_VERSION
  SCREAMING_SNAKE_CASE__				: str										=      None
  SCREAMING_SNAKE_CASE__				: str										=      None
  SCREAMING_SNAKE_CASE__				: dict										=      None
  SCREAMING_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


A__        =			logging.get_logger(__name__)

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

A__        =			{
    "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"
        ),
    },
}

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







class    UpperCamelCase_			(  _snake_case			):


  """simple docstring"""
  SCREAMING_SNAKE_CASE__				: str										=      VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE__				: Optional[int]										=      PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE__				: Any										=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE__				: List[str]										=      ["""input_ids""", """attention_mask"""]
  SCREAMING_SNAKE_CASE__				: List[str]										=      LongformerTokenizer



  def __init__(	self    :				List[Any]     ,  A_    :				Any=None     ,  A_    :				Union[str, Any]=None     ,  A_    :				Optional[int]=None     ,  A_    :				int="replace"     ,  A_    :				Any="<s>"     ,  A_    :				int="</s>"     ,  A_    :				str="</s>"     ,  A_    :				Optional[Any]="<s>"     ,  A_    :				Optional[int]="<unk>"     ,  A_    :				Optional[int]="<pad>"     ,  A_    :				List[str]="<mask>"     ,  A_    :				Optional[int]=False     ,  A_    :				List[str]=True     ,  **A_    :				List[str]     ,  )					-> Any:
      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_     ,  )

      SCREAMING_SNAKE_CASE__					     =						json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()	)
      if pre_tok_state.get("add_prefix_space"     ,  A_	) != add_prefix_space:
          SCREAMING_SNAKE_CASE__					     =						getattr(A_     ,  pre_tok_state.pop("type"	)	)
          SCREAMING_SNAKE_CASE__					     =						add_prefix_space
          SCREAMING_SNAKE_CASE__					     =						pre_tok_class(**A_	)

      SCREAMING_SNAKE_CASE__					     =						add_prefix_space

      SCREAMING_SNAKE_CASE__					     =						"post_processor"
      SCREAMING_SNAKE_CASE__					     =						getattr(self.backend_tokenizer     ,  A_     ,  A_	)
      if tokenizer_component_instance:
          SCREAMING_SNAKE_CASE__					     =						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:
              SCREAMING_SNAKE_CASE__					     =						tuple(state["sep"]	)
          if "cls" in state:
              SCREAMING_SNAKE_CASE__					     =						tuple(state["cls"]	)

          SCREAMING_SNAKE_CASE__					     =						False

          if state.get("add_prefix_space"     ,  A_	) != add_prefix_space:
              SCREAMING_SNAKE_CASE__					     =						add_prefix_space
              SCREAMING_SNAKE_CASE__					     =						True

          if state.get("trim_offsets"     ,  A_	) != trim_offsets:
              SCREAMING_SNAKE_CASE__					     =						trim_offsets
              SCREAMING_SNAKE_CASE__					     =						True

          if changes_to_apply:
              SCREAMING_SNAKE_CASE__					     =						getattr(A_     ,  state.pop("type"	)	)
              SCREAMING_SNAKE_CASE__					     =						component_class(**A_	)
              setattr(self.backend_tokenizer     ,  A_     ,  A_	)



  @property
  def      _UpperCamelCase    (	self    :				Dict	)					-> 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      _UpperCamelCase    (	self    :				int     ,  A_    :				Optional[Any]	)					-> int:
      SCREAMING_SNAKE_CASE__					     =						AddedToken(A_     ,  lstrip=A_     ,  rstrip=A_	) if isinstance(A_     ,  A_	) else value
      SCREAMING_SNAKE_CASE__					     =						value



  def      _UpperCamelCase    (	self    :				int     ,  *A_    :				int     ,  **A_    :				Dict	)					-> BatchEncoding:
      SCREAMING_SNAKE_CASE__					     =						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      _UpperCamelCase    (	self    :				Dict     ,  *A_    :				int     ,  **A_    :				Union[str, Any]	)					-> BatchEncoding:
      SCREAMING_SNAKE_CASE__					     =						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      _UpperCamelCase    (	self    :				int     ,  A_    :				str     ,  A_    :				Optional[str] = None	)					-> Tuple[str]:
      SCREAMING_SNAKE_CASE__					     =						self._tokenizer.model.save(A_     ,  name=A_	)
      return tuple(A_	)



  def      _UpperCamelCase    (	self    :				Tuple     ,  A_    :				List[str]     ,  A_    :				str=None	)					-> List[str]:
      SCREAMING_SNAKE_CASE__					     =						[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      _UpperCamelCase    (	self    :				List[str]     ,  A_    :				List[int]     ,  A_    :				Optional[List[int]] = None	)					-> List[int]:
      SCREAMING_SNAKE_CASE__					     =						[self.sep_token_id]
      SCREAMING_SNAKE_CASE__					     =						[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]


