import unittest

from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


UpperCamelCase__											=					get_tests_dir('fixtures/spiece.model')





@require_sentencepiece
@require_tokenizers
class      A							(				UpperCAmelCase_		,				unittest.TestCase     ):
   __UpperCAmelCase : int      =			AlbertTokenizer
   __UpperCAmelCase : Tuple      =			AlbertTokenizerFast
   __UpperCAmelCase : int      =			True
   __UpperCAmelCase : List[str]      =			True
   __UpperCAmelCase : Tuple      =			True


   def 			lowercase_      (self     :						Optional[Any]		)						->				int:
         """simple docstring"""



         super().setUp()

         # We have a SentencePiece fixture for testing
         UpperCAmelCase__								=  AlbertTokenizer(lowerCAmelCase__		)
         tokenizer.save_pretrained(self.tmpdirname		)


   def 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						Dict		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  "this is a test"
         UpperCAmelCase__								=  "this is a test"
         return input_text, output_text


   def 			lowercase_      (self     :						Optional[int]		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  "<pad>"
         UpperCAmelCase__								=  0

         self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase__		)       ,  lowerCAmelCase__		)
         self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase__		)       ,  lowerCAmelCase__		)


   def 			lowercase_      (self     :						Optional[Any]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  list(self.get_tokenizer().get_vocab().keys()		)

         self.assertEqual(vocab_keys[0]       ,  "<pad>"		)
         self.assertEqual(vocab_keys[1]       ,  "<unk>"		)
         self.assertEqual(vocab_keys[-1]       ,  "▁eloquent"		)
         self.assertEqual(len(lowerCAmelCase__		)       ,  3_0_0_0_0		)


   def 			lowercase_      (self     :						int		)						->				Union[str, Any]:
         """simple docstring"""



         self.assertEqual(self.get_tokenizer().vocab_size       ,  3_0_0_0_0		)


   def 			lowercase_      (self     :						List[str]		)						->				Tuple:
         """simple docstring"""



         if not self.test_rust_tokenizer:
               return

         UpperCAmelCase__								=  self.get_tokenizer()
         UpperCAmelCase__								=  self.get_rust_tokenizer()

         UpperCAmelCase__								=  "I was born in 92000, and this is falsé."

         UpperCAmelCase__								=  tokenizer.tokenize(lowerCAmelCase__		)
         UpperCAmelCase__								=  rust_tokenizer.tokenize(lowerCAmelCase__		)
         self.assertListEqual(lowerCAmelCase__       ,  lowerCAmelCase__		)

         UpperCAmelCase__								=  tokenizer.encode(lowerCAmelCase__       ,  add_special_tokens=lowerCAmelCase__		)
         UpperCAmelCase__								=  rust_tokenizer.encode(lowerCAmelCase__       ,  add_special_tokens=lowerCAmelCase__		)
         self.assertListEqual(lowerCAmelCase__       ,  lowerCAmelCase__		)

         UpperCAmelCase__								=  self.get_rust_tokenizer()
         UpperCAmelCase__								=  tokenizer.encode(lowerCAmelCase__		)
         UpperCAmelCase__								=  rust_tokenizer.encode(lowerCAmelCase__		)
         self.assertListEqual(lowerCAmelCase__       ,  lowerCAmelCase__		)


   def 			lowercase_      (self     :						Optional[int]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  AlbertTokenizer(lowerCAmelCase__       ,  keep_accents=lowerCAmelCase__		)

         UpperCAmelCase__								=  tokenizer.tokenize("This is a test"		)
         self.assertListEqual(lowerCAmelCase__       ,  ["▁this", "▁is", "▁a", "▁test"]		)

         self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase__		)       ,  [4_8, 2_5, 2_1, 1_2_8_9]		)

         UpperCAmelCase__								=  tokenizer.tokenize("I was born in 92000, and this is falsé."		)
         self.assertListEqual(
             lowerCAmelCase__       ,  ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."]		)
         UpperCAmelCase__								=  tokenizer.convert_tokens_to_ids(lowerCAmelCase__		)
         self.assertListEqual(lowerCAmelCase__       ,  [3_1, 2_3, 3_8_6, 1_9, 5_6_1, 3_0_5_0, 1_5, 1_7, 4_8, 2_5, 8_2_5_6, 1_8, 1, 9]		)

         UpperCAmelCase__								=  tokenizer.convert_ids_to_tokens(lowerCAmelCase__		)
         self.assertListEqual(
             lowerCAmelCase__       ,  ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."]       ,  )


   def 			lowercase_      (self     :						Tuple		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  AlbertTokenizer(lowerCAmelCase__		)

         UpperCAmelCase__								=  tokenizer.encode("sequence builders"		)
         UpperCAmelCase__								=  tokenizer.encode("multi-sequence build"		)

         UpperCAmelCase__								=  tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__		)
         UpperCAmelCase__								=  tokenizer.build_inputs_with_special_tokens(lowerCAmelCase__       ,  lowerCAmelCase__		)

         assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
         assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
             tokenizer.sep_token_id
         ]





   @slow
   def 			lowercase_      (self     :						str		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  {"attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
         # fmt: on

         self.tokenizer_integration_test_util(
             expected_encoding=lowerCAmelCase__       ,  model_name="albert-base-v2"       ,  revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e"       ,  )






import os
import tempfile
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    Adafactor,
						    AdamW,
						    get_constant_schedule,
						    get_constant_schedule_with_warmup,
						    get_cosine_schedule_with_warmup,
						    get_cosine_with_hard_restarts_schedule_with_warmup,
						    get_inverse_sqrt_schedule,
						    get_linear_schedule_with_warmup,
						    get_polynomial_decay_schedule_with_warmup,
						)







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase=10    ):
						SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       []
						for _ in range(_UpperCAmelCase    ):
												lrs.append(scheduler.get_lr()[0]    )
												scheduler.step()
						return lrs







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase=10    ):
						SCREAMING_SNAKE_CASE_: List[str]  		=       []
						for step in range(_UpperCAmelCase    ):
												lrs.append(scheduler.get_lr()[0]    )
												scheduler.step()
												if step == num_steps // 2:
																		with tempfile.TemporaryDirectory() as tmpdirname:
																								SCREAMING_SNAKE_CASE_: Optional[int]  		=       os.path.join(_UpperCAmelCase				,	"schedule.bin"    )
																								torch.save(scheduler.state_dict()				,	_UpperCAmelCase    )

																								SCREAMING_SNAKE_CASE_: Optional[Any]  		=       torch.load(_UpperCAmelCase    )
																								scheduler.load_state_dict(_UpperCAmelCase    )
						return lrs



@require_torch
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     Dict   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Dict   ,						lowerCAmelCase__  :     Tuple):
									self.assertEqual(len(lowerCAmelCase__)   ,						len(lowerCAmelCase__))
									for a, b in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
															self.assertAlmostEqual(lowerCAmelCase__   ,						lowerCAmelCase__   ,						delta=lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor([0.1, -0.2, -0.1]   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: str  		=       torch.tensor([0.4, 0.2, -0.5])
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       nn.MSELoss()
									# No warmup, constant schedule, no gradient clipping
									SCREAMING_SNAKE_CASE_: int  		=       AdamW(params=[w]   ,						lr=2E-1   ,						weight_decay=0.0)
									for _ in range(100):
															SCREAMING_SNAKE_CASE_: Dict  		=       criterion(lowerCAmelCase__   ,						lowerCAmelCase__)
															loss.backward()
															optimizer.step()
															w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
															w.grad.zero_()
									self.assertListAlmostEqual(w.tolist()   ,						[0.4, 0.2, -0.5]   ,						tol=1E-2)




			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor([0.1, -0.2, -0.1]   ,						requires_grad=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: int  		=       torch.tensor([0.4, 0.2, -0.5])
									SCREAMING_SNAKE_CASE_: Any  		=       nn.MSELoss()
									# No warmup, constant schedule, no gradient clipping
									SCREAMING_SNAKE_CASE_: int  		=       Adafactor(
									    params=[w]   ,						lr=1E-2   ,						eps=(1E-30, 1E-3)   ,						clip_threshold=1.0   ,						decay_rate=-0.8   ,						betaa=lowerCAmelCase__   ,						weight_decay=0.0   ,						relative_step=lowerCAmelCase__   ,						scale_parameter=lowerCAmelCase__   ,						warmup_init=lowerCAmelCase__   ,						)
									for _ in range(1000):
															SCREAMING_SNAKE_CASE_: List[Any]  		=       criterion(lowerCAmelCase__   ,						lowerCAmelCase__)
															loss.backward()
															optimizer.step()
															w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
															w.grad.zero_()
									self.assertListAlmostEqual(w.tolist()   ,						[0.4, 0.2, -0.5]   ,						tol=1E-2)







@require_torch
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							Union[str, Any]										=     nn.Linear(50		,       50	) if is_torch_available() else None
			_UpperCAmelCase   :							List[Any]										=     AdamW(m.parameters()		,       lr=10.0	) if is_torch_available() else None
			_UpperCAmelCase   :							Optional[Any]										=     10



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Optional[Any]=None):
									self.assertEqual(len(lowerCAmelCase__)   ,						len(lowerCAmelCase__))
									for a, b in zip(lowerCAmelCase__   ,						lowerCAmelCase__):
															self.assertAlmostEqual(lowerCAmelCase__   ,						lowerCAmelCase__   ,						delta=lowerCAmelCase__   ,						msg=lowerCAmelCase__)




			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: Dict  		=       {"num_warmup_steps": 2, "num_training_steps": 10}
									# schedulers doct format
									# function: (sched_args_dict, expected_learning_rates)
									SCREAMING_SNAKE_CASE_: Dict  		=       {
									    get_constant_schedule: ({}, [10.0] * self.num_steps),
									    get_constant_schedule_with_warmup: (
									        {"num_warmup_steps": 4},
									        [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
									    ),
									    get_linear_schedule_with_warmup: (
									        {**common_kwargs},
									        [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
									    ),
									    get_cosine_schedule_with_warmup: (
									        {**common_kwargs},
									        [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
									    ),
									    get_cosine_with_hard_restarts_schedule_with_warmup: (
									        {**common_kwargs, "num_cycles": 2},
									        [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
									    ),
									    get_polynomial_decay_schedule_with_warmup: (
									        {**common_kwargs, "power": 2.0, "lr_end": 1E-7},
									        [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
									    ),
									    get_inverse_sqrt_schedule: (
									        {"num_warmup_steps": 2},
									        [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
									    ),
									}

									for scheduler_func, data in scheds.items():
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Tuple  		=       data

															SCREAMING_SNAKE_CASE_: List[Any]  		=       scheduler_func(self.optimizer   ,						**lowerCAmelCase__)
															self.assertEqual(len([scheduler.get_lr()[0]])   ,						1)
															SCREAMING_SNAKE_CASE_: int  		=       unwrap_schedule(lowerCAmelCase__   ,						self.num_steps)
															self.assertListAlmostEqual(
															    lowerCAmelCase__   ,						lowerCAmelCase__   ,						tol=1E-2   ,						msg=F"failed for {scheduler_func} in normal scheduler"   ,						)

															SCREAMING_SNAKE_CASE_: List[str]  		=       scheduler_func(self.optimizer   ,						**lowerCAmelCase__)
															if scheduler_func.__name__ != "get_constant_schedule":
																					LambdaScheduleWrapper.wrap_scheduler(lowerCAmelCase__)  # wrap to test picklability of the schedule
															SCREAMING_SNAKE_CASE_: Tuple  		=       unwrap_and_save_reload_schedule(lowerCAmelCase__   ,						self.num_steps)
															self.assertListEqual(lowerCAmelCase__   ,						lowerCAmelCase__   ,						msg=F"failed for {scheduler_func} in save and reload")







class   __lowercase				:




			"""simple docstring"""







			def __init__( self  :     str   ,						lowerCAmelCase__  :     List[str]):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       fn



			def __call__( self  :     Optional[int]   ,						*lowerCAmelCase__  :     List[Any]   ,						**lowerCAmelCase__  :     Tuple):
									return self.fn(*lowerCAmelCase__   ,						**lowerCAmelCase__)




			@classmethod
			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     str):
									SCREAMING_SNAKE_CASE_: str  		=       list(map(self   ,						scheduler.lr_lambdas))






