




'''simple docstring'''


import json
import os
import unittest

from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin

class       A   (		_a					,unittest.TestCase   ):
							lowercase_          =    DebertaTokenizer
							lowercase_          =    True
							lowercase_          =    DebertaTokenizerFast







							def        __lowerCAmelCase      (  self	:  Optional[int] )      ->							Union[str, Any]:


														"""simple docstring"""


														super().setUp()

														# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
														_a     					=    [
														    '''l''',
														    '''o''',
														    '''w''',
														    '''e''',
														    '''r''',
														    '''s''',
														    '''t''',
														    '''i''',
														    '''d''',
														    '''n''',
														    '''\u0120''',
														    '''\u0120l''',
														    '''\u0120n''',
														    '''\u0120lo''',
														    '''\u0120low''',
														    '''er''',
														    '''\u0120lowest''',
														    '''\u0120newer''',
														    '''\u0120wider''',
														    '''[UNK]''',
														]
														_a     					=    dict(zip(_snake_case							,      range(len(_snake_case ) ) ) )
														_a     					=    ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
														_a     					=    {'''unk_token''': '''[UNK]'''}

														_a     					=    os.path.join(self.tmpdirname							,      VOCAB_FILES_NAMES['''vocab_file'''] )
														_a     					=    os.path.join(self.tmpdirname							,      VOCAB_FILES_NAMES['''merges_file'''] )
														with open(self.vocab_file							,      '''w'''							,      encoding='''utf-8''' ) as fp:
																					fp.write(json.dumps(_snake_case ) + '''\n''' )
														with open(self.merges_file							,      '''w'''							,      encoding='''utf-8''' ) as fp:
																					fp.write('''\n'''.join(_snake_case ) )







							def        __lowerCAmelCase      (  self	:  str							,      **lowerCAmelCase_	:  List[str] )      ->							int:


														"""simple docstring"""


														kwargs.update(self.special_tokens_map )
														return self.tokenizer_class.from_pretrained(self.tmpdirname							,      **_snake_case )







							def        __lowerCAmelCase      (  self	:  Optional[Any]							,      lowerCAmelCase_	:  Optional[Any] )      ->							Optional[Any]:


														"""simple docstring"""


														_a     					=    '''lower newer'''
														_a     					=    '''lower newer'''
														return input_text, output_text







							def        __lowerCAmelCase      (  self	:  Optional[int] )      ->							List[Any]:


														"""simple docstring"""


														_a     					=    self.get_tokenizer()
														_a     					=    '''lower newer'''
														_a     					=    ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er''']
														_a     					=    tokenizer.tokenize(_snake_case )
														self.assertListEqual(_snake_case							,      _snake_case )

														_a     					=    tokens + [tokenizer.unk_token]
														_a     					=    [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
														self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case )							,      _snake_case )







							def        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							int:


														"""simple docstring"""


														_a     					=    self.get_tokenizer()
														_a     					=    tokenizer('''Hello'''							,      '''World''' )
														_a     					=    [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
														self.assertListEqual(tokd['''token_type_ids''']							,      _snake_case )







							@slow
							def        __lowerCAmelCase      (  self	:  Any )      ->							Union[str, Any]:


														"""simple docstring"""


														_a     					=    self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' )

														_a     					=    tokenizer.encode('''sequence builders'''							,      add_special_tokens=_snake_case )
														_a     					=    tokenizer.encode('''multi-sequence build'''							,      add_special_tokens=_snake_case )

														_a     					=    tokenizer.encode(
														    '''sequence builders'''							,      add_special_tokens=_snake_case							,      add_prefix_space=_snake_case )
														_a     					=    tokenizer.encode(
														    '''sequence builders'''							,      '''multi-sequence build'''							,      add_special_tokens=_snake_case							,      add_prefix_space=_snake_case )

														_a     					=    tokenizer.build_inputs_with_special_tokens(_snake_case )
														_a     					=    tokenizer.build_inputs_with_special_tokens(_snake_case							,      _snake_case )

														assert encoded_sentence == encoded_text_from_decode
														assert encoded_pair == encoded_pair_from_decode







							@slow
							def        __lowerCAmelCase      (  self	:  Union[str, Any] )      ->							Dict:


														"""simple docstring"""


														_a     					=    [self.tokenizer_class]
														if self.test_rust_tokenizer:
																					tokenizer_classes.append(self.rust_tokenizer_class )

														for tokenizer_class in tokenizer_classes:
																					_a     					=    tokenizer_class.from_pretrained('''microsoft/deberta-base''' )

																					_a     					=    [
																					    '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
																					    '''ALBERT incorporates two parameter reduction techniques''',
																					    '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
																					    ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
																					    ''' vocabulary embedding.''',
																					]

																					_a     					=    tokenizer(_snake_case							,      padding=_snake_case )
																					_a     					=    [tokenizer.decode(_snake_case							,      skip_special_tokens=_snake_case ) for seq in encoding['''input_ids''']]

																					# fmt: off
																					_a     					=    {
																					    '''input_ids''': [
																					        [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2]
																					    ],
																					    '''token_type_ids''': [
																					        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
																					    ],
																					    '''attention_mask''': [
																					        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
																					        [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]
																					    ]
																					}
																					# fmt: on

																					_a     					=    [
																					    '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''',
																					    '''ALBERT incorporates two parameter reduction techniques''',
																					    '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary'''
																					    ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'''
																					    ''' vocabulary embedding.''',
																					]

																					self.assertDictEqual(encoding.data							,      _snake_case )

																					for expected, decoded in zip(_snake_case							,      _snake_case ):
																												self.assertEqual(_snake_case							,      _snake_case )







'''simple docstring'''


import tempfile
import unittest

import numpy as np
from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import BertConfig, is_flax_available
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax


if is_flax_available():
				import os

				from flax.core.frozen_dict import unfreeze
				from flax.traverse_util import flatten_dict

				from transformers import FlaxBertModel

				_snake_case				:				Optional[Any]       							=		'0.12'  # assumed parallelism: 8

@require_flax
@is_staging_test
class       A   (		unittest.TestCase   ):







							@classmethod
							def        __lowerCAmelCase      (  cls	:  Tuple )      ->							int:


														"""simple docstring"""


														_a     					=    TOKEN
														HfFolder.save_token(lowerCAmelCase_ )







							@classmethod
							def        __lowerCAmelCase      (  cls	:  Tuple )      ->							Optional[int]:


														"""simple docstring"""


														try:
																					delete_repo(token=cls._token							,      repo_id='''test-model-flax''' )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token							,      repo_id='''valid_org/test-model-flax-org''' )
														except HTTPError:
																					pass







							def        __lowerCAmelCase      (  self	:  Any )      ->							Optional[Any]:


														"""simple docstring"""


														_a     					=    BertConfig(
														    vocab_size=99							,      hidden_size=32							,      num_hidden_layers=5							,      num_attention_heads=4							,      intermediate_size=37 )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )
														model.push_to_hub('''test-model-flax'''							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained(F'{USER}/test-model-flax' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )

														# Reset repo
														delete_repo(token=self._token							,      repo_id='''test-model-flax''' )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(lowerCAmelCase_							,      repo_id='''test-model-flax'''							,      push_to_hub=lowerCAmelCase_							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained(F'{USER}/test-model-flax' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )







							def        __lowerCAmelCase      (  self	:  int )      ->							Tuple:


														"""simple docstring"""


														_a     					=    BertConfig(
														    vocab_size=99							,      hidden_size=32							,      num_hidden_layers=5							,      num_attention_heads=4							,      intermediate_size=37 )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )
														model.push_to_hub('''valid_org/test-model-flax-org'''							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )

														# Reset repo
														delete_repo(token=self._token							,      repo_id='''valid_org/test-model-flax-org''' )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(
																					    lowerCAmelCase_							,      repo_id='''valid_org/test-model-flax-org'''							,      push_to_hub=lowerCAmelCase_							,      use_auth_token=self._token )

														_a     					=    FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' )

														_a     					=    flatten_dict(unfreeze(model.params ) )
														_a     					=    flatten_dict(unfreeze(new_model.params ) )

														for key in base_params.keys():
																					_a     					=    (base_params[key] - new_params[key]).sum().item()
																					self.assertLessEqual(lowerCAmelCase_							,      1e-3							,      msg=F'{key} not identical' )



def 		snake_case_   (UpperCamelCase	:  List[str]			,						UpperCamelCase	:  Optional[Any]				):





							'''simple docstring'''


							_a     					=    True
							_a     					=    flatten_dict(modela.params				)
							_a     					=    flatten_dict(modela.params				)
							for key in flat_params_a.keys():
														if np.sum(np.abs(flat_params_a[key] - flat_params_a[key]				)				) > 1e-4:
																					_a     					=    False

							return models_are_equal

@require_flax
class       A   (		unittest.TestCase   ):







							def        __lowerCAmelCase      (  self	:  Dict )      ->							int:


														"""simple docstring"""


														_a     					=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )

														_a     					=    '''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCAmelCase_							,      lowerCAmelCase_ ) )

																					with self.assertRaises(lowerCAmelCase_ ):
																												_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertTrue(check_models_equal(lowerCAmelCase_							,      lowerCAmelCase_ ) )







							def        __lowerCAmelCase      (  self	:  Union[str, Any] )      ->							Optional[int]:


														"""simple docstring"""


														_a     					=    BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' )
														_a     					=    FlaxBertModel(lowerCAmelCase_ )

														_a     					=    '''bert'''
														with tempfile.TemporaryDirectory() as tmp_dir:
																					model.save_pretrained(os.path.join(lowerCAmelCase_							,      lowerCAmelCase_ )							,      max_shard_size='''10KB''' )

																					with self.assertRaises(lowerCAmelCase_ ):
																												_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertTrue(check_models_equal(lowerCAmelCase_							,      lowerCAmelCase_ ) )







							def        __lowerCAmelCase      (  self	:  Optional[Any] )      ->							List[str]:


														"""simple docstring"""


														_a     					=    '''bert'''
														_a     					=    '''hf-internal-testing/tiny-random-bert-subfolder'''

														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

														_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertIsNotNone(lowerCAmelCase_ )







							def        __lowerCAmelCase      (  self	:  Tuple )      ->							Tuple:


														"""simple docstring"""


														_a     					=    '''bert'''
														_a     					=    '''hf-internal-testing/tiny-random-bert-sharded-subfolder'''
														with self.assertRaises(lowerCAmelCase_ ):
																					_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_ )

														_a     					=    FlaxBertModel.from_pretrained(lowerCAmelCase_							,      subfolder=lowerCAmelCase_ )

														self.assertIsNotNone(lowerCAmelCase_ )

