

import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
					import os

					# The slow tests are often failing with OOM error on GPU
					# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
					# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
					lowercase     :       List[str]        =       "platform"

					import jax
					import jax.numpy as jnp

					from transformers import MarianTokenizer
					from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right







def  UpperCAmelCase_   (_lowerCAmelCase :		Optional[int]     ,			_lowerCAmelCase :		Tuple     ,			_lowerCAmelCase :		Tuple=None     ,			_lowerCAmelCase :		List[str]=None     ,			_lowerCAmelCase :		List[str]=None     ,			_lowerCAmelCase :		Optional[Any]=None     ,			_lowerCAmelCase :		Tuple=None     ,			_lowerCAmelCase :		Dict=None     ,			):
			if attention_mask is None:
						__UpperCamelCase    :    Dict								=      np.where(input_ids != config.pad_token_id     ,			1     ,			0		)
			if decoder_attention_mask is None:
						__UpperCamelCase    :    Union[str, Any]								=      np.where(decoder_input_ids != config.pad_token_id     ,			1     ,			0		)
			if head_mask is None:
						__UpperCamelCase    :    Optional[Any]								=      np.ones((config.encoder_layers, config.encoder_attention_heads)		)
			if decoder_head_mask is None:
						__UpperCamelCase    :    List[str]								=      np.ones((config.decoder_layers, config.decoder_attention_heads)		)
			if cross_attn_head_mask is None:
						__UpperCamelCase    :    Union[str, Any]								=      np.ones((config.decoder_layers, config.decoder_attention_heads)		)
			return {
			    "input_ids": input_ids,
			    "decoder_input_ids": decoder_input_ids,
			    "attention_mask": attention_mask,
			    "decoder_attention_mask": attention_mask,
			}
class 		SCREAMING_SNAKE_CASE__					:







						"""simple docstring"""




						def __init__(				self , __UpperCamelCase , __UpperCamelCase=13 , __UpperCamelCase=7 , __UpperCamelCase=True , __UpperCamelCase=False , __UpperCamelCase=99 , __UpperCamelCase=16 , __UpperCamelCase=2 , __UpperCamelCase=4 , __UpperCamelCase=4 , __UpperCamelCase="gelu" , __UpperCamelCase=0.1 , __UpperCamelCase=0.1 , __UpperCamelCase=32 , __UpperCamelCase=2 , __UpperCamelCase=1 , __UpperCamelCase=0 , __UpperCamelCase=0.02 , )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      parent
									__UpperCamelCase    :    Optional[Any]								=      batch_size
									__UpperCamelCase    :    Any								=      seq_length
									__UpperCamelCase    :    Tuple								=      is_training
									__UpperCamelCase    :    Dict								=      use_labels
									__UpperCamelCase    :    Optional[Any]								=      vocab_size
									__UpperCamelCase    :    Dict								=      hidden_size
									__UpperCamelCase    :    int								=      num_hidden_layers
									__UpperCamelCase    :    int								=      num_attention_heads
									__UpperCamelCase    :    Optional[Any]								=      intermediate_size
									__UpperCamelCase    :    Tuple								=      hidden_act
									__UpperCamelCase    :    Optional[int]								=      hidden_dropout_prob
									__UpperCamelCase    :    Dict								=      attention_probs_dropout_prob
									__UpperCamelCase    :    str								=      max_position_embeddings
									__UpperCamelCase    :    Tuple								=      eos_token_id
									__UpperCamelCase    :    Optional[Any]								=      pad_token_id
									__UpperCamelCase    :    Tuple								=      bos_token_id
									__UpperCamelCase    :    Dict								=      initializer_range

						def __lowerCamelCase					(				self    )							->	Tuple:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[Any]								=      np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size    ) , 3 , self.vocab_size    )
									__UpperCamelCase    :    Any								=      np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa    )) , -1    )

									__UpperCamelCase    :    Tuple								=      shift_tokens_right(__UpperCamelCase , 1 , 2    )

									__UpperCamelCase    :    Tuple								=      MarianConfig(
									    vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=__UpperCamelCase , )
									__UpperCamelCase    :    int								=      prepare_marian_inputs_dict(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )
									return config, inputs_dict

						def __lowerCamelCase					(				self    )							->	Tuple:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase    :    Union[str, Any]								=      self.prepare_config_and_inputs()
									return config, inputs_dict

						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )							->	Optional[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    int								=      20
									__UpperCamelCase    :    Dict								=      model_class_name(__UpperCamelCase    )

									__UpperCamelCase    :    str								=      model.encode(inputs_dict["input_ids"]    )

									__UpperCamelCase							,				__UpperCamelCase    :    str								=      (
									    inputs_dict["decoder_input_ids"],
									    inputs_dict["decoder_attention_mask"],
									)

									__UpperCamelCase    :    List[str]								=      model.init_cache(decoder_input_ids.shape[0] , __UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    Tuple								=      jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4"    )

									__UpperCamelCase    :    Union[str, Any]								=      jnp.broadcast_to(
									    jnp.arange(decoder_input_ids.shape[-1] - 1    )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
									__UpperCamelCase    :    int								=      model.decode(
									    decoder_input_ids[:, :-1] , __UpperCamelCase , decoder_attention_mask=__UpperCamelCase , past_key_values=__UpperCamelCase , decoder_position_ids=__UpperCamelCase , )

									__UpperCamelCase    :    Tuple								=      jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4"    )
									__UpperCamelCase    :    Union[str, Any]								=      model.decode(
									    decoder_input_ids[:, -1:] , __UpperCamelCase , decoder_attention_mask=__UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=__UpperCamelCase , )

									__UpperCamelCase    :    Any								=      model.decode(__UpperCamelCase , __UpperCamelCase    )

									__UpperCamelCase    :    List[str]								=      np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])    )    )
									self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}'''    )




						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      20
									__UpperCamelCase    :    int								=      model_class_name(__UpperCamelCase    )

									__UpperCamelCase    :    Optional[Any]								=      model.encode(inputs_dict["input_ids"]    )

									__UpperCamelCase							,				__UpperCamelCase    :    int								=      (
									    inputs_dict["decoder_input_ids"],
									    inputs_dict["decoder_attention_mask"],
									)

									__UpperCamelCase    :    Optional[int]								=      jnp.concatenate(
									    [
									        decoder_attention_mask,
									        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])    ),
									    ] , axis=-1 , )

									__UpperCamelCase    :    Union[str, Any]								=      model.init_cache(decoder_input_ids.shape[0] , __UpperCamelCase , __UpperCamelCase    )
									__UpperCamelCase    :    List[Any]								=      jnp.broadcast_to(
									    jnp.arange(decoder_input_ids.shape[-1] - 1    )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )

									__UpperCamelCase    :    Optional[int]								=      model.decode(
									    decoder_input_ids[:, :-1] , __UpperCamelCase , decoder_attention_mask=__UpperCamelCase , past_key_values=__UpperCamelCase , decoder_position_ids=__UpperCamelCase , )
									__UpperCamelCase    :    Tuple								=      jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4"    )
									__UpperCamelCase    :    str								=      model.decode(
									    decoder_input_ids[:, -1:] , __UpperCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=__UpperCamelCase , decoder_position_ids=__UpperCamelCase , )

									__UpperCamelCase    :    str								=      model.decode(__UpperCamelCase , __UpperCamelCase , decoder_attention_mask=__UpperCamelCase    )

									__UpperCamelCase    :    Optional[Any]								=      np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])    )    )
									self.parent.assertTrue(diff < 1E-3 , msg=f'''Max diff is {diff}'''    )







@require_flax
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__						,	unittest.TestCase						,	lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				List[str]											=							True
						lowercase  :				List[str]											=							(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
						lowercase  :				List[Any]											=							(FlaxMarianMTModel,) if is_flax_available() else ()

						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase    :    List[str]								=      FlaxMarianModelTester(self    )

						def __lowerCamelCase					(				self    )							->	str:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase    :    Dict								=      self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
												self.model_tester.check_use_cache_forward(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )

						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase    :    Tuple								=      self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
												self.model_tester.check_use_cache_forward_with_attn_mask(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase    )

						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase    :    Dict								=      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												with self.subTest(model_class.__name__    ):
															__UpperCamelCase    :    str								=      self._prepare_for_class(__UpperCamelCase , __UpperCamelCase    )
															__UpperCamelCase    :    Union[str, Any]								=      model_class(__UpperCamelCase    )

															@jax.jit
															def encode_jitted(__UpperCamelCase , __UpperCamelCase=None , **__UpperCamelCase    ):
																		return model.encode(input_ids=__UpperCamelCase , attention_mask=__UpperCamelCase    )

															with self.subTest("JIT Enabled"    ):
																		__UpperCamelCase    :    Optional[Any]								=      encode_jitted(**__UpperCamelCase    ).to_tuple()

															with self.subTest("JIT Disabled"    ):
																		with jax.disable_jit():
																					__UpperCamelCase    :    int								=      encode_jitted(**__UpperCamelCase    ).to_tuple()

															self.assertEqual(len(__UpperCamelCase    ) , len(__UpperCamelCase    )    )
															for jitted_output, output in zip(__UpperCamelCase , __UpperCamelCase    ):
																		self.assertEqual(jitted_output.shape , output.shape    )

						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									__UpperCamelCase							,				__UpperCamelCase    :    int								=      self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												with self.subTest(model_class.__name__    ):
															__UpperCamelCase    :    Optional[Any]								=      model_class(__UpperCamelCase    )
															__UpperCamelCase    :    Any								=      model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"]    )

															__UpperCamelCase    :    Any								=      {
															    "decoder_input_ids": inputs_dict["decoder_input_ids"],
															    "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
															    "encoder_outputs": encoder_outputs,
															}

															@jax.jit
															def decode_jitted(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase    ):
																		return model.decode(
																		    decoder_input_ids=__UpperCamelCase , decoder_attention_mask=__UpperCamelCase , encoder_outputs=__UpperCamelCase , )

															with self.subTest("JIT Enabled"    ):
																		__UpperCamelCase    :    Tuple								=      decode_jitted(**__UpperCamelCase    ).to_tuple()

															with self.subTest("JIT Disabled"    ):
																		with jax.disable_jit():
																					__UpperCamelCase    :    Optional[int]								=      decode_jitted(**__UpperCamelCase    ).to_tuple()

															self.assertEqual(len(__UpperCamelCase    ) , len(__UpperCamelCase    )    )
															for jitted_output, output in zip(__UpperCamelCase , __UpperCamelCase    ):
																		self.assertEqual(jitted_output.shape , output.shape    )




						@slow
						def __lowerCamelCase					(				self    )							->	Dict:




									'''simple docstring'''


									for model_class_name in self.all_model_classes:
												__UpperCamelCase    :    str								=      model_class_name.from_pretrained("Helsinki-NLP/opus-mt-en-de"    )
												# FlaxMarianForSequenceClassification expects eos token in input_ids
												__UpperCamelCase    :    List[str]								=      np.ones((1, 1)    ) * model.config.eos_token_id
												__UpperCamelCase    :    int								=      model(__UpperCamelCase    )
												self.assertIsNotNone(__UpperCamelCase    )







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):







						"""simple docstring"""




						lowercase  :				Dict											=							None
						lowercase  :				str											=							None

						@classmethod
						def __lowerCamelCase					(				cls    )							->	None:




									'''simple docstring'''


									__UpperCamelCase    :    Any								=      f'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
									return cls

						@cached_property
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									return MarianTokenizer.from_pretrained(self.model_name    )

						@property
						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									return self.tokenizer.eos_token_id

						@cached_property
						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									__UpperCamelCase    :    FlaxMarianMTModel								=      FlaxMarianMTModel.from_pretrained(self.model_name    )
									self.assertEqual(model.config.decoder_start_token_id , model.config.pad_token_id    )
									return model

						def __lowerCamelCase					(				self , **__UpperCamelCase    )							->	str:




									'''simple docstring'''


									__UpperCamelCase    :    Union[str, Any]								=      self.translate_src_text(**__UpperCamelCase    )
									self.assertListEqual(self.expected_text , __UpperCamelCase    )




						def __lowerCamelCase					(				self , **__UpperCamelCase    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      self.tokenizer(self.src_text , padding=__UpperCamelCase , return_tensors="np" , **__UpperCamelCase    )
									__UpperCamelCase    :    Optional[Any]								=      self.model.generate(
									    model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2 , max_length=1_28 , ).sequences
									__UpperCamelCase    :    Optional[Any]								=      self.tokenizer.batch_decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase    )
									return generated_words







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				str											=							'en'
						lowercase  :				Optional[int]											=							'fr'
						lowercase  :				Tuple											=							[
						    'I am a small frog.',
						    'Now I can forget the 100 words of german that I know.',
						]
						lowercase  :				Optional[Any]											=							[
						    'Je suis une petite grenouille.',
						    'Maintenant, je peux oublier les 100 mots d\'allemand que je connais.',
						]

						@slow
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				Dict											=							'fr'
						lowercase  :				Tuple											=							'en'
						lowercase  :				Optional[int]											=							[
						    'Donnez moi le micro.',
						    'Tom et Mary étaient assis à une table.',  # Accents
						]
						lowercase  :				str											=							[
						    'Give me the microphone.',
						    'Tom and Mary were sitting at a table.',
						]

						@slow
						def __lowerCamelCase					(				self    )							->	Optional[Any]:




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				List[str]											=							'mt'
						lowercase  :				int											=							'en'
						lowercase  :				Tuple											=							['Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.']
						lowercase  :				Any											=							['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.']

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




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				Dict											=							'en'
						lowercase  :				Optional[int]											=							'de'
						lowercase  :				Any											=							[
						    'I am a small frog.',
						    'Now I can forget the 100 words of german that I know.',
						    'Tom asked his teacher for advice.',
						    'That\'s how I would do it.',
						    'Tom really admired Mary\'s courage.',
						    'Turn around and close your eyes.',
						]
						lowercase  :				Optional[Any]											=							[
						    'Ich bin ein kleiner Frosch.',
						    'Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.',
						    'Tom bat seinen Lehrer um Rat.',
						    'So würde ich das machen.',
						    'Tom bewunderte Marias Mut wirklich.',
						    'Drehen Sie sich um und schließen Sie die Augen.',
						]

						@slow
						def __lowerCamelCase					(				self    )							->	Optional[Any]:




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				str											=							'en'
						lowercase  :				str											=							'zh'
						lowercase  :				List[Any]											=							['My name is Wolfgang and I live in Berlin']
						lowercase  :				Any											=							['我叫沃尔夫冈 我住在柏林']

						@slow
						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				Optional[int]											=							'ru'
						lowercase  :				Optional[Any]											=							'fr'
						lowercase  :				str											=							['Он показал мне рукопись своей новой пьесы.']
						lowercase  :				Optional[int]											=							['Il m\'a montré le manuscrit de sa nouvelle pièce.']

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




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 		SCREAMING_SNAKE_CASE__					(		lowerCamelCase__   ):







						"""simple docstring"""




						lowercase  :				Dict											=							'en'
						lowercase  :				Optional[int]											=							'ROMANCE'
						lowercase  :				str											=							[
						    '>>fr<< Don\'t spend so much time watching TV.',
						    '>>pt<< Your message has been sent.',
						    '>>es<< He\'s two years older than me.',
						]
						lowercase  :				List[Any]											=							[
						    'Ne passez pas autant de temps à regarder la télé.',
						    'A sua mensagem foi enviada.',
						    'Es dos años más viejo que yo.',
						]

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




									'''simple docstring'''


									self._assert_generated_batch_equal_expected()


import os
import pickle
import tempfile
import unittest
from typing import Callable, Optional

import numpy as np

from transformers import (
    BatchEncoding,
    BertTokenizer,
    BertTokenizerFast,
    PreTrainedTokenizer,
    PreTrainedTokenizerFast,
    TensorType,
    TokenSpan,
    is_tokenizers_available,
)
from transformers.models.gpta.tokenization_gpta import GPTaTokenizer
from transformers.testing_utils import CaptureStderr, require_flax, require_tf, require_tokenizers, require_torch, slow


if is_tokenizers_available():
					from tokenizers import Tokenizer
					from tokenizers.models import WordPiece
class 		SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):







						"""simple docstring"""




						def __lowerCamelCase					(				self , __UpperCamelCase    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    List[str]								=      list(tokenizer_class.max_model_input_sizes.keys()    )
									for model_name in sa_models[:1]:
												__UpperCamelCase    :    int								=      tokenizer_class.from_pretrained(__UpperCamelCase    )
												self.assertIsNotNone(__UpperCamelCase    )
												self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )
												self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )

												for special_tok in tokenizer.all_special_tokens:
															self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )
															__UpperCamelCase    :    str								=      tokenizer.convert_tokens_to_ids(__UpperCamelCase    )
															self.assertIsInstance(__UpperCamelCase , __UpperCamelCase    )

						def __lowerCamelCase					(				self , __UpperCamelCase , __UpperCamelCase = None    )							->	Tuple:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[Any]								=      pickle.dumps(__UpperCamelCase    )
									self.assertIsNotNone(__UpperCamelCase    )

									__UpperCamelCase    :    List[str]								=      pickle.loads(__UpperCamelCase    )

									# Ensure is_fast is correctly restored
									self.assertEqual(be_restored.is_fast , be_original.is_fast    )

									# Ensure encodings are potentially correctly restored
									if be_original.is_fast:
												self.assertIsNotNone(be_restored.encodings    )
									else:
												self.assertIsNone(be_restored.encodings    )

									# Ensure the keys are the same
									for original_v, restored_v in zip(be_original.values() , be_restored.values()    ):
												if equal_op:
															self.assertTrue(equal_op(__UpperCamelCase , __UpperCamelCase    )    )
												else:
															self.assertEqual(__UpperCamelCase , __UpperCamelCase    )

						@slow
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									self.check_tokenizer_from_pretrained(__UpperCamelCase    )

						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									self.assertEqual(TensorType("tf"    ) , TensorType.TENSORFLOW    )
									self.assertEqual(TensorType("pt"    ) , TensorType.PYTORCH    )
									self.assertEqual(TensorType("np"    ) , TensorType.NUMPY    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									import numpy as np

									__UpperCamelCase    :    str								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Optional[Any]								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									# Python no tensor
									with self.subTest("BatchEncoding (Python, return_tensors=None)"    ):
												self.assert_dump_and_restore(tokenizer_p("Small example to encode"    )    )

									with self.subTest("BatchEncoding (Python, return_tensors=NUMPY)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.NUMPY    ) , np.array_equal    )

									with self.subTest("BatchEncoding (Rust, return_tensors=None)"    ):
												self.assert_dump_and_restore(tokenizer_r("Small example to encode"    )    )

									with self.subTest("BatchEncoding (Rust, return_tensors=NUMPY)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.NUMPY    ) , np.array_equal    )

						@require_tf
						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									import tensorflow as tf

									def tf_array_equals(__UpperCamelCase , __UpperCamelCase    ):
												return tf.reduce_all(tf.equal(__UpperCamelCase , __UpperCamelCase    )    )

									__UpperCamelCase    :    int								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Dict								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("BatchEncoding (Python, return_tensors=TENSORFLOW)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.TENSORFLOW    ) , __UpperCamelCase    )

									with self.subTest("BatchEncoding (Rust, return_tensors=TENSORFLOW)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.TENSORFLOW    ) , __UpperCamelCase    )

						@require_torch
						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									import torch

									__UpperCamelCase    :    List[Any]								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Optional[Any]								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("BatchEncoding (Python, return_tensors=PYTORCH)"    ):
												self.assert_dump_and_restore(
												    tokenizer_p("Small example to encode" , return_tensors=TensorType.PYTORCH    ) , torch.equal    )

									with self.subTest("BatchEncoding (Rust, return_tensors=PYTORCH)"    ):
												self.assert_dump_and_restore(
												    tokenizer_r("Small example to encode" , return_tensors=TensorType.PYTORCH    ) , torch.equal    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Any:




									'''simple docstring'''


									__UpperCamelCase    :    Optional[int]								=      BertTokenizer.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Tuple								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )

									with self.subTest("Python Tokenizer"    ):
												self.assertFalse(tokenizer_p("Small example to_encode"    ).is_fast    )

									with self.subTest("Rust Tokenizer"    ):
												self.assertTrue(tokenizer_r("Small example to_encode"    ).is_fast    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Union[str, Any]:




									'''simple docstring'''


									__UpperCamelCase    :    Any								=      BertTokenizerFast.from_pretrained("bert-base-cased"    )
									__UpperCamelCase    :    Dict								=      tokenizer_r(["Test", "\xad", "test"] , is_split_into_words=__UpperCamelCase    )

									self.assertEqual(encoded.word_to_tokens(0    ) , TokenSpan(start=1 , end=2    )    )
									self.assertEqual(encoded.word_to_tokens(1    ) , __UpperCamelCase    )
									self.assertEqual(encoded.word_to_tokens(2    ) , TokenSpan(start=2 , end=3    )    )

						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    List[str]								=      batch.convert_to_tensors(tensor_type="np"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Optional[Any]								=      batch.convert_to_tensors(tensor_type="np"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Union[str, Any]								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    int								=      batch.convert_to_tensors(tensor_type="np" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_torch
						def __lowerCamelCase					(				self    )							->	List[str]:




									'''simple docstring'''


									__UpperCamelCase    :    Dict								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    List[Any]								=      batch.convert_to_tensors(tensor_type="pt"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Tuple								=      batch.convert_to_tensors(tensor_type="pt"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Union[str, Any]								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    List[Any]								=      batch.convert_to_tensors(tensor_type="pt" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_tf
						def __lowerCamelCase					(				self    )							->	Optional[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    Tuple								=      batch.convert_to_tensors(tensor_type="tf"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Optional[int]								=      batch.convert_to_tensors(tensor_type="tf"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    Union[str, Any]								=      batch.convert_to_tensors(tensor_type="tf" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						@require_flax
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}    )
									__UpperCamelCase    :    int								=      batch.convert_to_tensors(tensor_type="jax"    )
									self.assertEqual(tensor_batch["inputs"].shape , (2, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (2,)    )
									# test converting the converted
									with CaptureStderr() as cs:
												__UpperCamelCase    :    Dict								=      batch.convert_to_tensors(tensor_type="jax"    )
									self.assertFalse(len(cs.err    ) , msg=f'''should have no warning, but got {cs.err}'''    )

									__UpperCamelCase    :    Tuple								=      BatchEncoding({"inputs": [1, 2, 3], "labels": 0}    )
									__UpperCamelCase    :    Union[str, Any]								=      batch.convert_to_tensors(tensor_type="jax" , prepend_batch_axis=__UpperCamelCase    )
									self.assertEqual(tensor_batch["inputs"].shape , (1, 3)    )
									self.assertEqual(tensor_batch["labels"].shape , (1,)    )

						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    str								=      [{"input_ids": np.array([0, 1, 2]    )}, {"input_ids": np.array([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    Any								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , np.ndarray    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="np"    )
									self.assertTrue(isinstance(batch["input_ids"] , np.ndarray    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_torch
						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									import torch

									__UpperCamelCase    :    List[str]								=      [{"input_ids": torch.tensor([0, 1, 2]    )}, {"input_ids": torch.tensor([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    str								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    str								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , torch.Tensor    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    int								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="pt"    )
									self.assertTrue(isinstance(batch["input_ids"] , torch.Tensor    )    )
									self.assertEqual(batch["input_ids"].tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_tf
						def __lowerCamelCase					(				self    )							->	List[Any]:




									'''simple docstring'''


									import tensorflow as tf

									__UpperCamelCase    :    List[Any]								=      [{"input_ids": tf.constant([0, 1, 2]    )}, {"input_ids": tf.constant([0, 1, 2, 3]    )}]
									__UpperCamelCase    :    int								=      BertTokenizer.from_pretrained("bert-base-cased"    )

									__UpperCamelCase    :    Optional[Any]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase    )
									self.assertTrue(isinstance(batch["input_ids"] , tf.Tensor    )    )
									self.assertEqual(batch["input_ids"].numpy().tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )
									__UpperCamelCase    :    List[str]								=      tokenizer.pad(__UpperCamelCase , padding=__UpperCamelCase , return_tensors="tf"    )
									self.assertTrue(isinstance(batch["input_ids"] , tf.Tensor    )    )
									self.assertEqual(batch["input_ids"].numpy().tolist() , [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]    )

						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	int:




									'''simple docstring'''


									__UpperCamelCase    :    List[Any]								=      Tokenizer(WordPiece(unk_token="[UNK]"    )    )
									PreTrainedTokenizerFast(tokenizer_object=__UpperCamelCase    )




						@require_tokenizers
						def __lowerCamelCase					(				self    )							->	Optional[int]:




									'''simple docstring'''


									__UpperCamelCase    :    Union[str, Any]								=      Tokenizer(WordPiece(unk_token="[UNK]"    )    )
									with tempfile.TemporaryDirectory() as tmpdirname:
												bert_tokenizer.save(os.path.join(__UpperCamelCase , "tokenizer.json"    )    )
												PreTrainedTokenizerFast(tokenizer_file=os.path.join(__UpperCamelCase , "tokenizer.json"    )    )