





'''simple docstring'''


import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


_lowerCamelCase				:	Tuple				    =       logging.get_logger(__name__)

if is_tf_available():
    import tensorflow as tf



@dataclass
class 							__UpperCAmelCase  (       a_						):







  '''simple docstring'''







  __lowerCAmelCase 				=    'tf'
  __lowerCAmelCase 				=    field(
      default=a_		,					metadata={'''help''': '''Name of TPU'''}		,					)

  __lowerCAmelCase 				=    field(
      default=a_		,					metadata={'''help''': '''Zone of TPU'''}		,					)

  __lowerCAmelCase 				=    field(
      default=a_		,					metadata={'''help''': '''Name of Cloud TPU-enabled project'''}		,					)

  __lowerCAmelCase 				=    field(
      default=1.0		,					metadata={'''help''': '''Power for the Polynomial decay LR scheduler.'''}		,					)

  __lowerCAmelCase 				=    field(default=a_		,					metadata={'''help''': '''Whether to activate the XLA compilation or not'''}						)







  @cached_property
  def        A     (self						:      int      ):
   requires_backends(self      ,      ["""tf"""]      )
   logger.info("""Tensorflow: setting up strategy"""      )

   A							  =      tf.config.list_physical_devices("""GPU"""      )

   # Set to float16 at first
   if self.fpaa:
    tf.keras.mixed_precision.set_global_policy("""mixed_float16"""      )

   if self.no_cuda:
    A							  =      tf.distribute.OneDeviceStrategy(device="""/cpu:0"""      )
   else:
    try:
     if self.tpu_name:
      A							  =      tf.distribute.cluster_resolver.TPUClusterResolver(
          self.tpu_name      ,      zone=self.tpu_zone      ,      project=self.gcp_project      )
     else:
      A							  =      tf.distribute.cluster_resolver.TPUClusterResolver()
    except ValueError:
     if self.tpu_name:
      raise RuntimeError(F"""Couldn\'t connect to TPU {self.tpu_name}!"""      )
     else:
      A							  =      None

    if tpu:
     # Set to bfloat16 in case of TPU
     if self.fpaa:
      tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16"""      )

     tf.config.experimental_connect_to_cluster(_snake_case      )
     tf.tpu.experimental.initialize_tpu_system(_snake_case      )

     A							  =      tf.distribute.TPUStrategy(_snake_case      )

    elif len(_snake_case      ) == 0:
     A							  =      tf.distribute.OneDeviceStrategy(device="""/cpu:0"""      )
    elif len(_snake_case      ) == 1:
     A							  =      tf.distribute.OneDeviceStrategy(device="""/gpu:0"""      )
    elif len(_snake_case      ) > 1:
     # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
     A							  =      tf.distribute.MirroredStrategy()
    else:
     raise ValueError("""Cannot find the proper strategy, please check your environment properties."""      )

   return strategy







  @property
  def        A     (self						:      Tuple      ):
   requires_backends(self      ,      ["""tf"""]      )
   return self._setup_strategy







  @property
  def        A     (self						:      Tuple      ):
   requires_backends(self      ,      ["""tf"""]      )
   return self._setup_strategy.num_replicas_in_sync







  @property
  def        A     (self						:      int      ):
   return False  # TF Logging is handled by Keras not the Trainer







  @property
  def        A     (self						:      List[str]      ):
   if self.per_gpu_train_batch_size:
    logger.warning(
        """Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future """
        """version. Using `--per_device_train_batch_size` is preferred."""      )
   A							  =      self.per_gpu_train_batch_size or self.per_device_train_batch_size
   return per_device_batch_size * self.n_replicas







  @property
  def        A     (self						:      List[Any]      ):
   if self.per_gpu_eval_batch_size:
    logger.warning(
        """Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future """
        """version. Using `--per_device_eval_batch_size` is preferred."""      )
   A							  =      self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
   return per_device_batch_size * self.n_replicas







  @property
  def        A     (self						:      int      ):
   requires_backends(self      ,      ["""tf"""]      )
   warnings.warn(
       """The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead."""      ,      _snake_case      ,      )
   return self._setup_strategy.num_replicas_in_sync








'''simple docstring'''


from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_lowerCamelCase				:	int				    =       logging.get_logger(__name__)



class 							__UpperCAmelCase  (       A__						):







		'''simple docstring'''







		__lowerCAmelCase 				=    ['''input_ids''', '''attention_mask''']







		def __init__(self						:      Tuple      ,      _lowerCAmelCase						:      str="[PAD]"      ,      _lowerCAmelCase						:      Dict="[BOS]"      ,      _lowerCAmelCase						:      Any="[EOS]"      ,      _lowerCAmelCase						:      List[Any]="[MASK]"      ,      _lowerCAmelCase						:      int="[CLS]"      ,      _lowerCAmelCase						:      Optional[Any]="[SEP]"      ,      _lowerCAmelCase						:      List[str]=2048      ,      **_lowerCAmelCase						:      Dict      ,      ):
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else pad_token
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else bos_token
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else eos_token
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else mask_token
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else cls_token
			A							  =      AddedToken(_lowerCAmelCase      ,      lstrip=_lowerCAmelCase      ,      rstrip=_lowerCAmelCase      ) if isinstance(_lowerCAmelCase      ,      _lowerCAmelCase      ) else sep_token

			super().__init__(
			    pad_token=_lowerCAmelCase      ,      bos_token=_lowerCAmelCase      ,      eos_token=_lowerCAmelCase      ,      mask_token=_lowerCAmelCase      ,      cls_token=_lowerCAmelCase      ,      sep_token=_lowerCAmelCase      ,      model_max_length=_lowerCAmelCase      ,      **_lowerCAmelCase      ,      )

			A							  =      2**8  # utf is 8 bits

			# define special tokens dict
			A							  =      {
			    self.pad_token: 0,
			    self.bos_token: 1,
			    self.eos_token: 2,
			    self.mask_token: 3,
			    self.cls_token: 4,
			    self.sep_token: 5,
			}
			A							  =      len(self.special_tokens_encoder      )
			A							  =      {v: k for k, v in self.special_tokens_encoder.items()}







		def        A     (self						:      Tuple      ):
			A							  =      self.special_tokens_encoder.copy()
			vocab.update(self.added_tokens_encoder      )
			for i in range(self._utf_vocab_size      ):
				A							  =      chr(_lowerCAmelCase      )
				A							  =      i + len(self.special_tokens_encoder      )
			return vocab







		@property
		def        A     (self						:      Tuple      ):
			return self._utf_vocab_size + self._num_special_tokens







		def        A     (self						:      Union[str, Any]      ,      _lowerCAmelCase						:      List[int]      ,      _lowerCAmelCase						:      Optional[List[int]] = None      ,      _lowerCAmelCase						:      bool = False      ):
			if already_has_special_tokens:
				return super().get_special_tokens_mask(
				    token_ids_a=_lowerCAmelCase      ,      token_ids_a=_lowerCAmelCase      ,      already_has_special_tokens=_lowerCAmelCase      )

			# normal case: some special tokens
			if token_ids_a is None:
				return [1] + [0] * len(_lowerCAmelCase      ) + [1]
			return [1] + ([0] * len(_lowerCAmelCase      )) + [1] + ([0] * len(_lowerCAmelCase      )) + [1]







		def        A     (self						:      List[Any]      ,      _lowerCAmelCase						:      List[int]      ,      _lowerCAmelCase						:      Optional[List[int]] = None      ):
			if token_ids_a is None:
				return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
			else:
				return [self.cls_token_id] + token_ids_a + [self.sep_token_id] + token_ids_a + [self.sep_token_id]







		def        A     (self						:      str      ,      _lowerCAmelCase						:      str      ):
			A							  =      [chr(_lowerCAmelCase      ) for i in text.encode("""utf-8"""      )]
			return tokens







		def        A     (self						:      int      ,      _lowerCAmelCase						:      List[str]      ):
			if token in self.special_tokens_encoder:
				A							  =      self.special_tokens_encoder[token]
			elif token in self.added_tokens_encoder:
				A							  =      self.added_tokens_encoder[token]
			elif len(_lowerCAmelCase      ) != 1:
				A							  =      self.unk_token_id
			else:
				A							  =      ord(_lowerCAmelCase      ) + self._num_special_tokens
			return token_id







		def        A     (self						:      Optional[int]      ,      _lowerCAmelCase						:      Any      ):
			if index in self.special_tokens_decoder:
				A							  =      self.special_tokens_decoder[index]
			elif index in self.added_tokens_decoder:
				A							  =      self.added_tokens_decoder[index]
			else:
				A							  =      chr(index - self._num_special_tokens      )
			return token







		def        A     (self						:      Dict      ,      _lowerCAmelCase						:      List[str]      ):
			A							  =      b""""""
			for token in tokens:
				if token in self.special_tokens_decoder:
					A							  =      self.special_tokens_decoder[token].encode("""utf-8"""      )
				elif token in self.added_tokens_decoder:
					A							  =      self.special_tokens_decoder[token].encode("""utf-8"""      )
				elif token in self.special_tokens_encoder:
					A							  =      token.encode("""utf-8"""      )
				elif token in self.added_tokens_encoder:
					A							  =      token.encode("""utf-8"""      )
				else:
					A							  =      bytes([ord(_lowerCAmelCase      )]      )
				bstring += tok_string
			A							  =      bstring.decode("""utf-8"""      ,      errors="""replace"""      )
			return string







		def        A     (self						:      Tuple      ,      _lowerCAmelCase						:      str      ,      _lowerCAmelCase						:      Optional[str] = None      ):
			return ()

