
'''simple docstring'''
import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


a_      =  logging.get_logger(__name__)






class       UpperCAmelCase_ (		nn.Module    ):





 def __init__(			self):
     super().__init__()
     if version.parse(torch.__version__) < version.parse("1.12.0"):
         raise ImportError(
             F'You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use '
             "PytorchGELUTanh. Please upgrade torch.")





 def 				snake_case__						(			self       ,				lowercase_):
     return nn.functional.gelu(UpperCAmelCase_       ,				approximate="tanh")






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044_715 * torch.pow(UpperCAmelCase_       ,				3.0))))






class       UpperCAmelCase_ (		nn.Module    ):





 def __init__(			self       ,				lowercase_ = False):
     super().__init__()
     if use_gelu_python:
         snake_case_       :			str   	=  self._gelu_python
     else:
         snake_case_       :			List[str]   	=  nn.functional.gelu





 def 				snake_case__						(			self       ,				lowercase_):
     return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))





 def 				snake_case__						(			self       ,				lowercase_):
     return self.act(UpperCAmelCase_)






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     return 0.5 * input * (1.0 + torch.tanh(input * 0.7_978_845_608 * (1.0 + 0.044_715 * input * input)))






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     return input * torch.sigmoid(1.702 * input)






class       UpperCAmelCase_ (		nn.Module    ):





 def __init__(			self       ,				lowercase_       ,				lowercase_):
     if min > max:
         raise ValueError(F'min should be < max (got min: {min}, max: {max})')

     super().__init__()
     snake_case_       :			Tuple   	=  min
     snake_case_       :			List[Any]   	=  max





 def 				snake_case__						(			self       ,				lowercase_):
     return torch.clip(gelu(UpperCAmelCase_)       ,				self.min       ,				self.max)






class       UpperCAmelCase_ (		nn.Module    ):





 def __init__(			self):
     super().__init__()
     snake_case_       :			Dict   	=  math.sqrt(2 / math.pi)





 def 				snake_case__						(			self       ,				lowercase_):
     return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044_715 * torch.pow(UpperCAmelCase_       ,				3))))






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     return nn.functional.silu(UpperCAmelCase_)






class       UpperCAmelCase_ (		nn.Module    ):





 def __init__(			self):
     super().__init__()
     if version.parse(torch.__version__) < version.parse("1.9.0"):
         snake_case_       :			str   	=  self._mish_python
     else:
         snake_case_       :			str   	=  nn.functional.mish





 def 				snake_case__						(			self       ,				lowercase_):
     return input * torch.tanh(nn.functional.softplus(UpperCAmelCase_))





 def 				snake_case__						(			self       ,				lowercase_):
     return self.act(UpperCAmelCase_)






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     return input






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_       ,				lowercase_=0.707_107       ,				lowercase_=0.282_095):
     snake_case_       :			List[Any]   	=  (input - mu).div(sigma * math.sqrt(2.0))
     return 0.5 * (1.0 + torch.erf(UpperCAmelCase_))






class       UpperCAmelCase_ (		nn.Module    ):





 def 				snake_case__						(			self       ,				lowercase_):
     snake_case_       :			Any   	=  nn.functional.relu(UpperCAmelCase_)
     snake_case_       :			Tuple   	=  torch.square(UpperCAmelCase_)
     return squared






class       UpperCAmelCase_ (		snake_case__    ):





 def __getitem__(			self       ,				lowercase_):
     snake_case_       :			Any   	=  super().__getitem__(UpperCAmelCase_)
     snake_case_       :			Optional[int]   	=  content if isinstance(UpperCAmelCase_       ,				UpperCAmelCase_) else (content, {})
     return cls(**UpperCAmelCase_)


a_      =  {
    """gelu""": GELUActivation,
    """gelu_10""": (ClippedGELUActivation, {"""min""": -10, """max""": 10}),
    """gelu_fast""": FastGELUActivation,
    """gelu_new""": NewGELUActivation,
    """gelu_python""": (GELUActivation, {"""use_gelu_python""": True}),
    """gelu_pytorch_tanh""": PytorchGELUTanh,
    """gelu_accurate""": AccurateGELUActivation,
    """laplace""": LaplaceActivation,
    """linear""": LinearActivation,
    """mish""": MishActivation,
    """quick_gelu""": QuickGELUActivation,
    """relu""": nn.ReLU,
    """relu2""": ReLUSquaredActivation,
    """relu6""": nn.ReLUa,
    """sigmoid""": nn.Sigmoid,
    """silu""": SiLUActivation,
    """swish""": SiLUActivation,
    """tanh""": nn.Tanh,
}
a_      =  ClassInstantier(ACTaCLS)

def   UpperCamelCase_   (		__SCREAMING_SNAKE_CASE				):
    """simple docstring"""






    if activation_string in ACTaFN:
        return ACTaFN[activation_string]
    else:
        raise KeyError(f'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()				)}'				)


# For backwards compatibility with: from activations import gelu_python
a_      =  get_activation("gelu_python")
a_      =  get_activation("gelu_new")
a_      =  get_activation("gelu")
a_      =  get_activation("gelu_fast")
a_      =  get_activation("quick_gelu")
a_      =  get_activation("silu")
a_      =  get_activation("mish")


a_      =  get_activation("linear")









"""simple docstring"""







import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin





@require_tokenizers
class    UpperCamelCase     (			snake_case ,					unittest.TestCase    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    str		    =   PreTrainedTokenizerFast
	SCREAMING_SNAKE_CASE_				:    Optional[Any]		    =   False
	SCREAMING_SNAKE_CASE_				:    Optional[int]		    =   True
	SCREAMING_SNAKE_CASE_				:    int		    =   "tokenizer_file"






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Optional[int]			=					False  # because we don't have pretrained_vocab_files_map
			super().setUp()
			_lowercase							:      Tuple			=					True

			_lowercase							:      Optional[Any]			=					["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
			_lowercase							:      Dict			=					"""SaulLu/dummy-tokenizer-bytelevel-bpe"""

			# Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
			_lowercase							:      Dict			=					[(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

			_lowercase							:      Any			=					PreTrainedTokenizerFast.from_pretrained(model_paths[0]					)
			tokenizer.save_pretrained(self.tmpdirname					)






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
			# model
			pass






	def 					lowerCamelCase__ (			self					):
			# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
			pass






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[str]			=					self.tmpdirname
			# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""					):
							try:
									_lowercase							:      Optional[Any]			=					tempfile.mkdtemp()
									_lowercase							:      Any			=					self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_							,**UpperCAmelCase_					)

									tokenizer.save_pretrained(self.tmpdirname					)
									super().test_training_new_tokenizer()
							finally:
									# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
									# is restored
									shutil.rmtree(self.tmpdirname					)
									_lowercase							:      List[Any]			=					tmpdirname_orig






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[str]			=					self.tmpdirname
			# Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
			for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
					with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""					):
							try:
									_lowercase							:      Optional[int]			=					tempfile.mkdtemp()
									_lowercase							:      Tuple			=					self.rust_tokenizer_class.from_pretrained(UpperCAmelCase_							,**UpperCAmelCase_					)

									tokenizer.save_pretrained(self.tmpdirname					)
									super().test_training_new_tokenizer_with_special_tokens_change()
							finally:
									# Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
									# is restored
									shutil.rmtree(self.tmpdirname					)
									_lowercase							:      Optional[int]			=					tmpdirname_orig






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[Any]			=					self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name					)

			_lowercase							:      List[str]			=					("""a""" for _ in range(10_00					))
			_lowercase							:      Dict			=					tokenizer.train_new_from_iterator(text_iterator=UpperCAmelCase_							,length=10_00							,vocab_size=50					)

			_lowercase							:      List[str]			=					new_tokenizer.encode("""a🤗"""					)
			self.assertEqual(UpperCAmelCase_							,[64, 1_72, 2_53, 97, 2_45]					)







@require_tokenizers
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained("""bert-base-cased"""					)
			_lowercase							:      Optional[Any]			=					json.loads(tokenizer._tokenizer.to_str()					)
			_lowercase							:      Dict			=					len(UpperCAmelCase_					)

			with tempfile.TemporaryDirectory() as tmp_dir:
					# Hack to save this in the tokenizer_config.json
					_lowercase							:      str			=					["""tokenizer.4.0.0.json"""]
					tokenizer.save_pretrained(UpperCAmelCase_					)
					json.dump(UpperCAmelCase_							,open(os.path.join(UpperCAmelCase_							,"""tokenizer.4.0.0.json"""					)							,"""w"""					)					)

					# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
					_lowercase							:      int			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
					self.assertEqual(len(UpperCAmelCase_					)							,len(UpperCAmelCase_					) + 1					)
					_lowercase							:      List[str]			=					json.loads(new_tokenizer._tokenizer.to_str()					)
					self.assertIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)

					# Will need to be adjusted if we reach v42 and this test is still here.
					# Should pick the old tokenizer file as the version of Transformers is < 4.0.0
					shutil.move(os.path.join(UpperCAmelCase_							,"""tokenizer.4.0.0.json"""					)							,os.path.join(UpperCAmelCase_							,"""tokenizer.42.0.0.json"""					)					)
					_lowercase							:      Optional[int]			=					["""tokenizer.42.0.0.json"""]
					tokenizer.save_pretrained(UpperCAmelCase_					)
					_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
					self.assertEqual(len(UpperCAmelCase_					)							,len(UpperCAmelCase_					)					)
					_lowercase							:      List[Any]			=					json.loads(new_tokenizer._tokenizer.to_str()					)
					self.assertNotIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)






	def 					lowerCamelCase__ (			self					):
			# This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
			_lowercase							:      Tuple			=					"""hf-internal-testing/test-two-tokenizers"""

			# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
			_lowercase							:      List[Any]			=					AutoTokenizer.from_pretrained(UpperCAmelCase_					)
			self.assertEqual(len(UpperCAmelCase_					)							,2_89_97					)
			_lowercase							:      List[Any]			=					json.loads(tokenizer._tokenizer.to_str()					)
			self.assertIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)

			# Testing an older version by monkey-patching the version in the module it's used.
			import transformers as old_transformers

			_lowercase							:      Optional[Any]			=					"""3.0.0"""
			_lowercase							:      int			=					old_transformers.models.auto.AutoTokenizer.from_pretrained(UpperCAmelCase_					)
			self.assertEqual(len(UpperCAmelCase_					)							,2_89_96					)
			_lowercase							:      str			=					json.loads(old_tokenizer._tokenizer.to_str()					)
			self.assertNotIn("""huggingface"""							,json_tokenizer["""model"""]["""vocab"""]					)







@require_tokenizers
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






	def 					lowerCamelCase__ (			self					):
			# See https://github.com/huggingface/transformers/pull/12550
			# and https://github.com/huggingface/tokenizers/issues/537
			_lowercase							:      Optional[int]			=					PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""					)
			_lowercase							:      List[str]			=					"""The Matrix is a 1999 science fiction action film."""

			with concurrent.futures.ThreadPoolExecutor() as executor:
					_lowercase							:      Tuple			=					[executor.submit(self.fetch							,UpperCAmelCase_							,UpperCAmelCase_					) for i in range(10					)]
					_lowercase							:      str			=					[future.result() for future in futures]
					self.assertEqual(UpperCAmelCase_							,[[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10					)]					)






	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_					):
			return tokenizer.encode(UpperCAmelCase_							,truncation="""longest_first"""							,padding="""longest"""					)



