


"""simple docstring"""






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_   (   _lowerCAmelCase     :					Dict,     _lowerCAmelCase     :					Optional[Any]=10       ):






     """simple docstring"""

     _a    	=				[]
     for _ in range(_lowerCAmelCase       ):
          lrs.append(scheduler.get_lr()[0]       )
          scheduler.step()
     return lrs
def       A_   (   _lowerCAmelCase     :					Optional[int],     _lowerCAmelCase     :					List[str]=10       ):






     """simple docstring"""

     _a    	=				[]
     for step in range(_lowerCAmelCase       ):
          lrs.append(scheduler.get_lr()[0]       )
          scheduler.step()
          if step == num_steps // 2:
               with tempfile.TemporaryDirectory() as tmpdirname:
                    _a    	=				os.path.join(_lowerCAmelCase,     '''schedule.bin'''       )
                    torch.save(scheduler.state_dict(),     _lowerCAmelCase       )

                    _a    	=				torch.load(_lowerCAmelCase       )
                    scheduler.load_state_dict(_lowerCAmelCase       )
     return lrs


@require_torch
class     __lowerCamelCase  (					unittest.TestCase				):

     '''simple docstring'''


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase    ,				__UpperCAmelCase							)       ->							List[str]:
          self.assertEqual(len(__UpperCAmelCase							)    ,				len(__UpperCAmelCase							)							)
          for a, b in zip(__UpperCAmelCase    ,				__UpperCAmelCase							):
               self.assertAlmostEqual(__UpperCAmelCase    ,				__UpperCAmelCase    ,				delta=__UpperCAmelCase							)


     def 							_UpperCAmelCase      (      self							)       ->							Optional[Any]:
          _a    	=				torch.tensor([0.1, -0.2, -0.1]    ,				requires_grad=__UpperCAmelCase							)
          _a    	=				torch.tensor([0.4, 0.2, -0.5]							)
          _a    	=				nn.MSELoss()
          # No warmup, constant schedule, no gradient clipping
          _a    	=				AdamW(params=[w]    ,				lr=2e-1    ,				weight_decay=0.0							)
          for _ in range(100							):
               _a    	=				criterion(__UpperCAmelCase    ,				__UpperCAmelCase							)
               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 							_UpperCAmelCase      (      self							)       ->							str:
          _a    	=				torch.tensor([0.1, -0.2, -0.1]    ,				requires_grad=__UpperCAmelCase							)
          _a    	=				torch.tensor([0.4, 0.2, -0.5]							)
          _a    	=				nn.MSELoss()
          # No warmup, constant schedule, no gradient clipping
          _a    	=				Adafactor(
              params=[w]    ,				lr=1e-2    ,				eps=(1e-3_0, 1e-3)    ,				clip_threshold=1.0    ,				decay_rate=-0.8    ,				betaa=__UpperCAmelCase    ,				weight_decay=0.0    ,				relative_step=__UpperCAmelCase    ,				scale_parameter=__UpperCAmelCase    ,				warmup_init=__UpperCAmelCase    ,				)
          for _ in range(1000							):
               _a    	=				criterion(__UpperCAmelCase    ,				__UpperCAmelCase							)
               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     __lowerCamelCase  (					unittest.TestCase				):

     '''simple docstring'''
     A_       :	Any    =		nn.Linear(50  ,					50				) if is_torch_available() else None
     A_       :	List[str]    =		AdamW(m.parameters()  ,					lr=10.0				) if is_torch_available() else None
     A_       :	List[Any]    =		10


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase    ,				__UpperCAmelCase    ,				__UpperCAmelCase=None							)       ->							int:
          self.assertEqual(len(__UpperCAmelCase							)    ,				len(__UpperCAmelCase							)							)
          for a, b in zip(__UpperCAmelCase    ,				__UpperCAmelCase							):
               self.assertAlmostEqual(__UpperCAmelCase    ,				__UpperCAmelCase    ,				delta=__UpperCAmelCase    ,				msg=__UpperCAmelCase							)





     def 							_UpperCAmelCase      (      self							)       ->							Optional[int]:
          _a    	=				{'''num_warmup_steps''': 2, '''num_training_steps''': 10}
          # schedulers doct format
          # function: (sched_args_dict, expected_learning_rates)
          _a    	=				{
              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():
               _a	,      _a    	=				data

               _a    	=				scheduler_func(self.optimizer    ,				**__UpperCAmelCase							)
               self.assertEqual(len([scheduler.get_lr()[0]]							)    ,				1							)
               _a    	=				unwrap_schedule(__UpperCAmelCase    ,				self.num_steps							)
               self.assertListAlmostEqual(
                   __UpperCAmelCase    ,				__UpperCAmelCase    ,				tol=1e-2    ,				msg=F'failed for {scheduler_func} in normal scheduler'    ,				)

               _a    	=				scheduler_func(self.optimizer    ,				**__UpperCAmelCase							)
               if scheduler_func.__name__ != "get_constant_schedule":
                    LambdaScheduleWrapper.wrap_scheduler(__UpperCAmelCase							)  # wrap to test picklability of the schedule
               _a    	=				unwrap_and_save_reload_schedule(__UpperCAmelCase    ,				self.num_steps							)
               self.assertListEqual(__UpperCAmelCase    ,				__UpperCAmelCase    ,				msg=F'failed for {scheduler_func} in save and reload'							)







class     __lowerCamelCase  :

     '''simple docstring'''


     def __init__(      self    ,				__UpperCAmelCase							)       ->							str:
          _a    	=				fn


     def __call__(      self    ,				*__UpperCAmelCase    ,				**__UpperCAmelCase							)       ->							Any:
          return self.fn(*__UpperCAmelCase    ,				**__UpperCAmelCase							)





     @classmethod
     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							List[str]:
          _a    	=				list(map(self    ,				scheduler.lr_lambdas							)							)




"""simple docstring"""






import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

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


__snake_case		=       logging.get_logger(__name__)
__snake_case		=       {'''vocab_file''': '''spiece.model'''}

__snake_case		=       {
    '''vocab_file''': {
        '''albert-base-v1''': '''https://huggingface.co/albert-base-v1/resolve/main/spiece.model''',
        '''albert-large-v1''': '''https://huggingface.co/albert-large-v1/resolve/main/spiece.model''',
        '''albert-xlarge-v1''': '''https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model''',
        '''albert-xxlarge-v1''': '''https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model''',
        '''albert-base-v2''': '''https://huggingface.co/albert-base-v2/resolve/main/spiece.model''',
        '''albert-large-v2''': '''https://huggingface.co/albert-large-v2/resolve/main/spiece.model''',
        '''albert-xlarge-v2''': '''https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model''',
        '''albert-xxlarge-v2''': '''https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model''',
    }
}

__snake_case		=       {
    '''albert-base-v1''': 512,
    '''albert-large-v1''': 512,
    '''albert-xlarge-v1''': 512,
    '''albert-xxlarge-v1''': 512,
    '''albert-base-v2''': 512,
    '''albert-large-v2''': 512,
    '''albert-xlarge-v2''': 512,
    '''albert-xxlarge-v2''': 512,
}

__snake_case		=       '''▁'''


class     __lowerCamelCase  (					a__				):

     '''simple docstring'''
     A_       :	Optional[int]    =		VOCAB_FILES_NAMES
     A_       :	int    =		PRETRAINED_VOCAB_FILES_MAP
     A_       :	Optional[int]    =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES


     def __init__(      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase=True    ,				__UpperCAmelCase=True    ,				__UpperCAmelCase=False    ,				__UpperCAmelCase="[CLS]"    ,				__UpperCAmelCase="[SEP]"    ,				__UpperCAmelCase="<unk>"    ,				__UpperCAmelCase="[SEP]"    ,				__UpperCAmelCase="<pad>"    ,				__UpperCAmelCase="[CLS]"    ,				__UpperCAmelCase="[MASK]"    ,				__UpperCAmelCase = None    ,				**__UpperCAmelCase    ,				)       ->							None:
          # Mask token behave like a normal word, i.e. include the space before it and
          # is included in the raw text, there should be a match in a non-normalized sentence.
          _a    	=				(
              AddedToken(__UpperCAmelCase    ,				lstrip=__UpperCAmelCase    ,				rstrip=__UpperCAmelCase    ,				normalized=__UpperCAmelCase							)
              if isinstance(__UpperCAmelCase    ,				__UpperCAmelCase							)
              else mask_token
          )

          _a    	=				{} if sp_model_kwargs is None else sp_model_kwargs

          super().__init__(
              do_lower_case=__UpperCAmelCase    ,				remove_space=__UpperCAmelCase    ,				keep_accents=__UpperCAmelCase    ,				bos_token=__UpperCAmelCase    ,				eos_token=__UpperCAmelCase    ,				unk_token=__UpperCAmelCase    ,				sep_token=__UpperCAmelCase    ,				pad_token=__UpperCAmelCase    ,				cls_token=__UpperCAmelCase    ,				mask_token=__UpperCAmelCase    ,				sp_model_kwargs=self.sp_model_kwargs    ,				**__UpperCAmelCase    ,				)

          _a    	=				do_lower_case
          _a    	=				remove_space
          _a    	=				keep_accents
          _a    	=				vocab_file

          _a    	=				spm.SentencePieceProcessor(**self.sp_model_kwargs							)
          self.sp_model.Load(__UpperCAmelCase							)


     @property
     def 							_UpperCAmelCase      (      self							)       ->							str:
          return len(self.sp_model							)


     def 							_UpperCAmelCase      (      self							)       ->							Optional[Any]:
          _a    	=				{self.convert_ids_to_tokens(__UpperCAmelCase							): i for i in range(self.vocab_size							)}
          vocab.update(self.added_tokens_encoder							)
          return vocab


     def __getstate__(      self							)       ->							int:
          _a    	=				self.__dict__.copy()
          _a    	=				None
          return state


     def __setstate__(      self    ,				__UpperCAmelCase							)       ->							Tuple:
          _a    	=				d

          # for backward compatibility
          if not hasattr(self    ,				'''sp_model_kwargs'''							):
               _a    	=				{}

          _a    	=				spm.SentencePieceProcessor(**self.sp_model_kwargs							)
          self.sp_model.Load(self.vocab_file							)


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							List[str]:
          if self.remove_space:
               _a    	=				''' '''.join(inputs.strip().split()							)
          else:
               _a    	=				inputs
          _a    	=				outputs.replace('''``'''    ,				'''"'''							).replace('''\'\''''    ,				'''"'''							)

          if not self.keep_accents:
               _a    	=				unicodedata.normalize('''NFKD'''    ,				__UpperCAmelCase							)
               _a    	=				''''''.join([c for c in outputs if not unicodedata.combining(__UpperCAmelCase							)]							)
          if self.do_lower_case:
               _a    	=				outputs.lower()

          return outputs


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							List[str]:
          _a    	=				self.preprocess_text(__UpperCAmelCase							)
          _a    	=				self.sp_model.encode(__UpperCAmelCase    ,				out_type=__UpperCAmelCase							)
          _a    	=				[]
          for piece in pieces:
               if len(__UpperCAmelCase							) > 1 and piece[-1] == str(''','''							) and piece[-2].isdigit():
                    _a    	=				self.sp_model.EncodeAsPieces(piece[:-1].replace(__UpperCAmelCase    ,				''''''							)							)
                    if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                         if len(cur_pieces[0]							) == 1:
                              _a    	=				cur_pieces[1:]
                         else:
                              _a    	=				cur_pieces[0][1:]
                    cur_pieces.append(piece[-1]							)
                    new_pieces.extend(__UpperCAmelCase							)
               else:
                    new_pieces.append(__UpperCAmelCase							)

          return new_pieces


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							str:
          return self.sp_model.PieceToId(__UpperCAmelCase							)


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							int:
          return self.sp_model.IdToPiece(__UpperCAmelCase							)


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase							)       ->							Optional[Any]:
          _a    	=				[]
          _a    	=				''''''
          _a    	=				False
          for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                    if not prev_is_special:
                         out_string += " "
                    out_string += self.sp_model.decode(__UpperCAmelCase							) + token
                    _a    	=				True
                    _a    	=				[]
               else:
                    current_sub_tokens.append(__UpperCAmelCase							)
                    _a    	=				False
          out_string += self.sp_model.decode(__UpperCAmelCase							)
          return out_string.strip()


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase = None							)       ->							List[int]:
          _a    	=				[self.sep_token_id]
          _a    	=				[self.cls_token_id]
          if token_ids_a is None:
               return cls + token_ids_a + sep
          return cls + token_ids_a + sep + token_ids_a + sep


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase = None    ,				__UpperCAmelCase = False							)       ->							List[int]:

          if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=__UpperCAmelCase    ,				token_ids_a=__UpperCAmelCase    ,				already_has_special_tokens=__UpperCAmelCase							)

          if token_ids_a is not None:
               return [1] + ([0] * len(__UpperCAmelCase							)) + [1] + ([0] * len(__UpperCAmelCase							)) + [1]
          return [1] + ([0] * len(__UpperCAmelCase							)) + [1]


     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase = None							)       ->							List[int]:
          _a    	=				[self.sep_token_id]
          _a    	=				[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							) * [0] + len(token_ids_a + sep							) * [1]





     def 							_UpperCAmelCase      (      self    ,				__UpperCAmelCase    ,				__UpperCAmelCase = None							)       ->							Tuple[str]:
          if not os.path.isdir(__UpperCAmelCase							):
               logger.error(F'Vocabulary path ({save_directory}) should be a directory'							)
               return
          _a    	=				os.path.join(
              __UpperCAmelCase    ,				(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']							)

          if os.path.abspath(self.vocab_file							) != os.path.abspath(__UpperCAmelCase							) and os.path.isfile(self.vocab_file							):
               copyfile(self.vocab_file    ,				__UpperCAmelCase							)
          elif not os.path.isfile(self.vocab_file							):
               with open(__UpperCAmelCase    ,				'''wb'''							) as fi:
                    _a    	=				self.sp_model.serialized_model_proto()
                    fi.write(__UpperCAmelCase							)

          return (out_vocab_file,)