

import copy
import tempfile
import unittest

from transformers import MaMaaaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from transformers.utils import cached_property

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer
				from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder



def       __lowerCAmelCase      (						A       ,     A       ,     A       ,     A=None       ,     A=None       ,     A=None       ,     A=None       ,     A=None       ,     ):
	if attention_mask is None:
		UpperCAmelCase_       				=			input_ids.ne(config.pad_token_id    )
	if decoder_attention_mask is None:
		UpperCAmelCase_       				=			decoder_input_ids.ne(config.pad_token_id    )
	if head_mask is None:
		UpperCAmelCase_       				=			torch.ones(config.encoder_layers       ,     config.encoder_attention_heads       ,     device=A    )
	if decoder_head_mask is None:
		UpperCAmelCase_       				=			torch.ones(config.decoder_layers       ,     config.decoder_attention_heads       ,     device=A    )
	if cross_attn_head_mask is None:
		UpperCAmelCase_       				=			torch.ones(config.decoder_layers       ,     config.decoder_attention_heads       ,     device=A    )
	return {
	    "input_ids": input_ids,
	    "decoder_input_ids": decoder_input_ids,
	    "attention_mask": attention_mask,
	    "decoder_attention_mask": attention_mask,
	    "head_mask": head_mask,
	    "decoder_head_mask": decoder_head_mask,
	    "cross_attn_head_mask": cross_attn_head_mask,
	}

class 						__UpperCamelCase    :




	def __init__(		self	:						Dict		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Tuple=13		,	lowerCAmelCase	:						Tuple=7		,	lowerCAmelCase	:						str=True		,	lowerCAmelCase	:						Optional[int]=False		,	lowerCAmelCase	:						Dict=99		,	lowerCAmelCase	:						Any=16		,	lowerCAmelCase	:						Tuple=2		,	lowerCAmelCase	:						Optional[int]=4		,	lowerCAmelCase	:						List[Any]=4		,	lowerCAmelCase	:						Optional[Any]="relu"		,	lowerCAmelCase	:						Union[str, Any]=0.1		,	lowerCAmelCase	:						Dict=0.1		,	lowerCAmelCase	:						List[str]=0.0		,	lowerCAmelCase	:						Any=0.0		,	lowerCAmelCase	:						Union[str, Any]=20		,	lowerCAmelCase	:						Any=2		,	lowerCAmelCase	:						int=1		,	lowerCAmelCase	:						Union[str, Any]=0		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			parent
		UpperCAmelCase_       				=			batch_size
		UpperCAmelCase_       				=			seq_length
		UpperCAmelCase_       				=			is_training
		UpperCAmelCase_       				=			use_labels
		UpperCAmelCase_       				=			vocab_size
		UpperCAmelCase_       				=			hidden_size
		UpperCAmelCase_       				=			num_hidden_layers
		UpperCAmelCase_       				=			num_attention_heads
		UpperCAmelCase_       				=			intermediate_size
		UpperCAmelCase_       				=			hidden_act
		UpperCAmelCase_       				=			hidden_dropout_prob
		UpperCAmelCase_       				=			attention_probs_dropout_prob
		UpperCAmelCase_       				=			encoder_layerdrop
		UpperCAmelCase_       				=			decoder_layerdrop
		UpperCAmelCase_       				=			max_position_embeddings
		UpperCAmelCase_       				=			eos_token_id
		UpperCAmelCase_       				=			pad_token_id
		UpperCAmelCase_       				=			bos_token_id




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.vocab_size							)
		UpperCAmelCase_       				=			self.eos_token_id  # Eos Token
		UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.vocab_size							)

		# we need to clamp the input ids here to avoid having pad token in between
		# this is because for M2M100 the position_ids are prepared such that
		# all pad tokens have pos id = 2 and rest are between 2..seq_length
		# and the seq_length here is seq_length - num_pad_tokens
		# but when using past, there is no way of knowing if the past input ids had
		# pad tokens in them, which results in incorrect seq_lenth and which in turn results in
		# position_ids being off by num_pad_tokens in past input
		UpperCAmelCase_       				=			input_ids.clamp(self.pad_token_id + 1							)
		UpperCAmelCase_       				=			decoder_input_ids.clamp(self.pad_token_id + 1							)

		UpperCAmelCase_       				=			self.get_config()
		UpperCAmelCase_       				=			prepare_mam_aaa_inputs_dict(lowerCAmelCase		,	lowerCAmelCase		,	lowerCAmelCase							)
		return config, inputs_dict




	def       __A					(		self	:						int							):


		'''simple docstring'''







		return MaMaaaConfig(
		    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		,	encoder_layerdrop=self.encoder_layerdrop		,	decoder_layerdrop=self.decoder_layerdrop		,	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		,	)




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_				,   UpperCAmelCase_       				=			self.prepare_config_and_inputs()
		return config, inputs_dict




	def       __A					(		self	:						Tuple		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaModel(config=lowerCAmelCase							).get_decoder().to(lowerCAmelCase							).eval()
		UpperCAmelCase_       				=			inputs_dict["input_ids"]
		UpperCAmelCase_       				=			inputs_dict["attention_mask"]
		UpperCAmelCase_       				=			inputs_dict["head_mask"]

		# first forward pass
		UpperCAmelCase_       				=			model(lowerCAmelCase		,	attention_mask=lowerCAmelCase		,	head_mask=lowerCAmelCase		,	use_cache=lowerCAmelCase							)

		UpperCAmelCase_				,   UpperCAmelCase_       				=			outputs.to_tuple()

		# create hypothetical multiple next token and extent to next_input_ids
		UpperCAmelCase_       				=			ids_tensor((self.batch_size, 3)		,	config.vocab_size							)
		UpperCAmelCase_       				=			ids_tensor((self.batch_size, 3)		,	2							)

		# append to next input_ids and
		UpperCAmelCase_       				=			torch.cat([input_ids, next_tokens]		,	dim=-1							)
		UpperCAmelCase_       				=			torch.cat([attention_mask, next_attn_mask]		,	dim=-1							)

		UpperCAmelCase_       				=			model(lowerCAmelCase		,	attention_mask=lowerCAmelCase							)["last_hidden_state"]
		UpperCAmelCase_       				=			model(lowerCAmelCase		,	attention_mask=lowerCAmelCase		,	past_key_values=lowerCAmelCase							)[
		    "last_hidden_state"
		]

		# select random slice
		UpperCAmelCase_       				=			ids_tensor((1,)		,	output_from_past.shape[-1]							).item()
		UpperCAmelCase_       				=			output_from_no_past[:, -3:, random_slice_idx].detach()
		UpperCAmelCase_       				=			output_from_past[:, :, random_slice_idx].detach()

		self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]							)

		# test that outputs are equal for slice
		self.parent.assertTrue(torch.allclose(lowerCAmelCase		,	lowerCAmelCase		,	atol=1e-2							)							)




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						Optional[Any]		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaModel(config=lowerCAmelCase							).to(lowerCAmelCase							).eval()
		UpperCAmelCase_       				=			model(**lowerCAmelCase							)

		UpperCAmelCase_       				=			outputs.encoder_last_hidden_state
		UpperCAmelCase_       				=			outputs.last_hidden_state

		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			model.get_encoder()
			encoder.save_pretrained(lowerCAmelCase							)
			UpperCAmelCase_       				=			MaMaaaEncoder.from_pretrained(lowerCAmelCase							).to(lowerCAmelCase							)

		UpperCAmelCase_       				=			encoder(inputs_dict["input_ids"]		,	attention_mask=inputs_dict["attention_mask"]							)[
		    0
		]

		self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3							)

		with tempfile.TemporaryDirectory() as tmpdirname:
			UpperCAmelCase_       				=			model.get_decoder()
			decoder.save_pretrained(lowerCAmelCase							)
			UpperCAmelCase_       				=			MaMaaaDecoder.from_pretrained(lowerCAmelCase							).to(lowerCAmelCase							)

		UpperCAmelCase_       				=			decoder(
		    input_ids=inputs_dict["decoder_input_ids"]		,	attention_mask=inputs_dict["decoder_attention_mask"]		,	encoder_hidden_states=lowerCAmelCase		,	encoder_attention_mask=inputs_dict["attention_mask"]		,	)[0]

		self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3							)


@require_torch
class 						__UpperCamelCase    (					lowercase     ,     lowercase     ,     lowercase     ,     unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     (
	    (
	        MaMaaaModel,
	        MaMaaaForConditionalGeneration,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE__    				=     (MaMaaaForConditionalGeneration,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE__    				=     (
	    {
	        'conversational': MaMaaaForConditionalGeneration,
	        'feature-extraction': MaMaaaModel,
	        'summarization': MaMaaaForConditionalGeneration,
	        'text2text-generation': MaMaaaForConditionalGeneration,
	        'translation': MaMaaaForConditionalGeneration,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE__    				=     True
	SCREAMING_SNAKE_CASE__    				=     True
	SCREAMING_SNAKE_CASE__    				=     False
	SCREAMING_SNAKE_CASE__    				=     False




	def       __A					(		self	:						int		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		if pipeline_test_casse_name == "TranslationPipelineTests":
			# Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
			# `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer.
			return True

		return False




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaModelTester(self							)
		UpperCAmelCase_       				=			ConfigTester(self		,	config_class=lowerCAmelCase							)




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		self.config_tester.run_common_tests()




	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_				,   UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		for model_class in self.all_model_classes:
			UpperCAmelCase_       				=			model_class(lowerCAmelCase							)

			with tempfile.TemporaryDirectory() as tmpdirname:
				model.save_pretrained(lowerCAmelCase							)
				UpperCAmelCase_				,   UpperCAmelCase_       				=			model_class.from_pretrained(lowerCAmelCase		,	output_loading_info=lowerCAmelCase							)
			self.assertEqual(info["missing_keys"]		,	[]							)




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCAmelCase							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.check_encoder_decoder_model_standalone(*lowerCAmelCase							)




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_				,   UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration):
			UpperCAmelCase_       				=			model_class(lowerCAmelCase							)
			model.to(lowerCAmelCase							)
			model.eval()

			UpperCAmelCase_       				=			copy.deepcopy(self._prepare_for_class(lowerCAmelCase		,	lowerCAmelCase							)							)

			if not self.is_encoder_decoder:
				UpperCAmelCase_       				=			inputs["input_ids"]
				del inputs["input_ids"]
			else:
				UpperCAmelCase_       				=			inputs["input_ids"]
				UpperCAmelCase_       				=			inputs.get("decoder_input_ids"		,	lowerCAmelCase							)
				del inputs["input_ids"]
				inputs.pop("decoder_input_ids"		,	lowerCAmelCase							)

			UpperCAmelCase_       				=			model.get_input_embeddings()
			if not self.is_encoder_decoder:
				UpperCAmelCase_       				=			wte(lowerCAmelCase							)
			else:
				UpperCAmelCase_       				=			wte(lowerCAmelCase							)
				UpperCAmelCase_       				=			wte(lowerCAmelCase							)

			with torch.no_grad():
				model(**lowerCAmelCase							)[0]




	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_				,   UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		UpperCAmelCase_       				=			input_dict["input_ids"]
		UpperCAmelCase_       				=			input_ids.ne(1							).to(lowerCAmelCase							)
		UpperCAmelCase_       				=			MaMaaaForConditionalGeneration(lowerCAmelCase							).eval().to(lowerCAmelCase							)
		if torch_device == "cuda":
			model.half()
		model.generate(lowerCAmelCase		,	attention_mask=lowerCAmelCase							)
		model.generate(num_beams=4		,	do_sample=lowerCAmelCase		,	early_stopping=lowerCAmelCase		,	num_return_sequences=3							)



def       __lowerCAmelCase      (						A    ):
	return torch.tensor(A       ,     dtype=torch.long       ,     device=A    )


_a:    Optional[int] 							=			1e-4




@require_torch
@require_sentencepiece
@require_tokenizers
@slow
class 						__UpperCamelCase    (					unittest.TestCase						):




	@cached_property
	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		return MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaModel.from_pretrained("facebook/m2m100_418M"							).to(lowerCAmelCase							)
		UpperCAmelCase_       				=			_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]							)
		UpperCAmelCase_       				=			_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]							)
		UpperCAmelCase_       				=			prepare_mam_aaa_inputs_dict(model.config		,	lowerCAmelCase		,	lowerCAmelCase							)
		with torch.no_grad():
			UpperCAmelCase_       				=			model(**lowerCAmelCase							)[0]
		UpperCAmelCase_       				=			torch.Size((1, 11, 1_024)							)
		self.assertEqual(output.shape		,	lowerCAmelCase							)
		# change to expected output here
		UpperCAmelCase_       				=			torch.tensor(
		    [[-0.7_780, -0.1_676, 0.1_038], [-6.7_556, -1.3_992, 0.0_567], [-7.5_383, -0.5_920, -0.2_779]]		,	device=lowerCAmelCase							)
		self.assertTrue(torch.allclose(output[:, :3, :3]		,	lowerCAmelCase		,	atol=lowerCAmelCase							)							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"							).to(lowerCAmelCase							)

		# change to intended input
		UpperCAmelCase_       				=			_long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]]							)
		UpperCAmelCase_       				=			_long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]]							)
		UpperCAmelCase_       				=			prepare_mam_aaa_inputs_dict(model.config		,	lowerCAmelCase		,	lowerCAmelCase							)
		with torch.no_grad():
			UpperCAmelCase_       				=			model(**lowerCAmelCase							)[0]
		UpperCAmelCase_       				=			torch.Size((1, 11, model.config.vocab_size)							)
		self.assertEqual(output.shape		,	lowerCAmelCase							)
		# change to expected output here
		UpperCAmelCase_       				=			torch.tensor(
		    [[-1.0_448, -1.0_411, 3.7_992], [-3.2_191, -3.2_386, -1.3_451], [-3.6_210, -3.5_993, 0.4_925]]		,	device=lowerCAmelCase							)
		self.assertTrue(torch.allclose(output[:, :3, :3]		,	lowerCAmelCase		,	atol=lowerCAmelCase							)							)




	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			MaMaaaForConditionalGeneration.from_pretrained("facebook/m2m100_418M"							).to(lowerCAmelCase							)
		UpperCAmelCase_       				=			MaMaaaTokenizer.from_pretrained("facebook/m2m100_418M"		,	src_lang="fr"		,	tgt_lang="en"							)

		UpperCAmelCase_       				=			[
		    "L'affaire NSA souligne l'absence totale de débat sur le renseignement",
		    "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.",
		    "Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent"
		    " Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de"
		    " l'ampleur de la surveillance américaine sur l'ensemble des communications en France.",
		]

		# The below article tests that we don't add any hypotheses outside of the top n_beams
		UpperCAmelCase_       				=			tokenizer(lowerCAmelCase		,	padding=lowerCAmelCase		,	return_tensors="pt"							)

		UpperCAmelCase_       				=			model.generate(
		    input_ids=dct["input_ids"].to(lowerCAmelCase							)		,	attention_mask=dct["attention_mask"].to(lowerCAmelCase							)		,	num_beams=5		,	forced_bos_token_id=tokenizer.get_lang_id("en"							)		,	)

		UpperCAmelCase_       				=			[
		    "The NSA case highlights the total absence of intelligence debate",
		    "I think there are two levels of response from the French government.",
		    "When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S."
		    " Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all"
		    " communications in France.",
		]

		UpperCAmelCase_       				=			tokenizer.batch_decode(
		    hypotheses_batch.tolist()		,	clean_up_tokenization_spaces=lowerCAmelCase		,	skip_special_tokens=lowerCAmelCase							)
		assert generated == expected_en


import json
import os
import shutil
import tempfile
import unittest

from transformers import BatchEncoding, CanineTokenizer
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.tokenization_utils import AddedToken
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin

class 						__UpperCamelCase    (					lowercase     ,     unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     CanineTokenizer
	SCREAMING_SNAKE_CASE__    				=     False




	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		super().setUp()
		UpperCAmelCase_       				=			CanineTokenizer()
		tokenizer.save_pretrained(self.tmpdirname							)




	@cached_property
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		return CanineTokenizer.from_pretrained("google/canine-s"							)




	def       __A					(		self	:						List[str]		,	**lowerCAmelCase	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.tokenizer_class.from_pretrained(self.tmpdirname		,	**lowerCAmelCase							)
		UpperCAmelCase_       				=			1_024
		return tokenizer




	@require_torch
	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.canine_tokenizer
		UpperCAmelCase_       				=			["Life is like a box of chocolates.", "You never know what you're gonna get."]
		# fmt: off
		UpperCAmelCase_       				=			[57_344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 57_345, 0, 0, 0, 0]
		# fmt: on
		UpperCAmelCase_       				=			tokenizer(lowerCAmelCase		,	padding=lowerCAmelCase		,	return_tensors="pt"							)
		self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)

		UpperCAmelCase_       				=			list(batch.input_ids.numpy()[0]							)

		self.assertListEqual(lowerCAmelCase		,	lowerCAmelCase							)

		self.assertEqual((2, 39)		,	batch.input_ids.shape							)
		self.assertEqual((2, 39)		,	batch.attention_mask.shape							)




	@require_torch
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.canine_tokenizer
		UpperCAmelCase_       				=			["Once there was a man.", "He wrote a test in HuggingFace Tranformers."]
		UpperCAmelCase_       				=			tokenizer(lowerCAmelCase		,	padding=lowerCAmelCase		,	return_tensors="pt"							)
		# check if input_ids, attention_mask and token_type_ids are returned
		self.assertIn("input_ids"		,	lowerCAmelCase							)
		self.assertIn("attention_mask"		,	lowerCAmelCase							)
		self.assertIn("token_type_ids"		,	lowerCAmelCase							)




	@require_torch
	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.canine_tokenizer
		UpperCAmelCase_       				=			[
		    "What's the weater?",
		    "It's about 25 degrees.",
		]
		UpperCAmelCase_       				=			tokenizer(
		    text_target=lowerCAmelCase		,	max_length=32		,	padding="max_length"		,	truncation=lowerCAmelCase		,	return_tensors="pt"							)
		self.assertEqual(32		,	targets["input_ids"].shape[1]							)




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers()
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				self.assertNotEqual(tokenizer.model_max_length		,	42							)

        # Now let's start the test
		UpperCAmelCase_       				=			self.get_tokenizers()
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				# Isolate this from the other tests because we save additional tokens/etc
				UpperCAmelCase_       				=			tempfile.mkdtemp()

				UpperCAmelCase_       				=			" He is very happy, UNwant\u00E9d,running"
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				tokenizer.save_pretrained(lowerCAmelCase							)

				UpperCAmelCase_       				=			tokenizer.__class__.from_pretrained(lowerCAmelCase							)
				UpperCAmelCase_       				=			after_tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				self.assertListEqual(lowerCAmelCase		,	lowerCAmelCase							)

				shutil.rmtree(lowerCAmelCase							)

		UpperCAmelCase_       				=			self.get_tokenizers(model_max_length=42							)
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				# Isolate this from the other tests because we save additional tokens/etc
				UpperCAmelCase_       				=			tempfile.mkdtemp()

				UpperCAmelCase_       				=			" He is very happy, UNwant\u00E9d,running"

				UpperCAmelCase_       				=			tokenizer.additional_special_tokens

				# We can add a new special token for Canine as follows:
				UpperCAmelCase_       				=			chr(0XE007							)
				additional_special_tokens.append(lowerCAmelCase							)
				tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens}							)
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				tokenizer.save_pretrained(lowerCAmelCase							)

				UpperCAmelCase_       				=			tokenizer.__class__.from_pretrained(lowerCAmelCase							)
				UpperCAmelCase_       				=			after_tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				self.assertListEqual(lowerCAmelCase		,	lowerCAmelCase							)
				self.assertIn(lowerCAmelCase		,	after_tokenizer.additional_special_tokens							)
				self.assertEqual(after_tokenizer.model_max_length		,	42							)

				UpperCAmelCase_       				=			tokenizer.__class__.from_pretrained(lowerCAmelCase		,	model_max_length=43							)
				self.assertEqual(tokenizer.model_max_length		,	43							)

				shutil.rmtree(lowerCAmelCase							)




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers(do_lower_case=lowerCAmelCase							)
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				UpperCAmelCase_				,   UpperCAmelCase_       				=			self.get_clean_sequence(lowerCAmelCase							)

				# a special token for Canine can be defined as follows:
				UpperCAmelCase_       				=			0XE005
				UpperCAmelCase_       				=			chr(lowerCAmelCase							)

				tokenizer.add_special_tokens({"cls_token": special_token}							)
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				self.assertEqual(len(lowerCAmelCase							)		,	1							)

				UpperCAmelCase_       				=			tokenizer.decode(ids + encoded_special_token		,	clean_up_tokenization_spaces=lowerCAmelCase							)
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)

				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				self.assertEqual(lowerCAmelCase		,	input_encoded + special_token_id							)

				UpperCAmelCase_       				=			tokenizer.decode(lowerCAmelCase		,	skip_special_tokens=lowerCAmelCase							)
				self.assertTrue(special_token not in decoded							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers(do_lower_case=lowerCAmelCase							)
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				UpperCAmelCase_       				=			chr(0XE005							)
				UpperCAmelCase_       				=			chr(0XE006							)

				# `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py)
				tokenizer.add_tokens([SPECIAL_TOKEN_1]		,	special_tokens=lowerCAmelCase							)
				# `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`,
				# which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py)
				tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]}							)

				UpperCAmelCase_       				=			tokenizer.tokenize(lowerCAmelCase							)
				UpperCAmelCase_       				=			tokenizer.tokenize(lowerCAmelCase							)

				self.assertEqual(len(lowerCAmelCase							)		,	1							)
				self.assertEqual(len(lowerCAmelCase							)		,	1							)
				self.assertEqual(token_a[0]		,	lowerCAmelCase							)
				self.assertEqual(token_a[0]		,	lowerCAmelCase							)




	@require_tokenizers
	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers(do_lower_case=lowerCAmelCase							)
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				# a special token for Canine can be defined as follows:
				UpperCAmelCase_       				=			0XE006
				UpperCAmelCase_       				=			chr(lowerCAmelCase							)

				UpperCAmelCase_       				=			AddedToken(lowerCAmelCase		,	lstrip=lowerCAmelCase							)
				tokenizer.add_special_tokens({"additional_special_tokens": [new_token]}							)

				with tempfile.TemporaryDirectory() as tmp_dir_name:
					tokenizer.save_pretrained(lowerCAmelCase							)
					tokenizer.from_pretrained(lowerCAmelCase							)




	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		if self.test_slow_tokenizer:
			tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())							)

		if self.test_rust_tokenizer:
			tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())							)

		for tokenizer_class, tokenizer_utils in tokenizer_list:
			with tempfile.TemporaryDirectory() as tmp_dir:
				tokenizer_utils.save_pretrained(lowerCAmelCase							)

				with open(os.path.join(lowerCAmelCase		,	"special_tokens_map.json"							)		,	encoding="utf-8"							) as json_file:
					UpperCAmelCase_       				=			json.load(lowerCAmelCase							)

				with open(os.path.join(lowerCAmelCase		,	"tokenizer_config.json"							)		,	encoding="utf-8"							) as json_file:
					UpperCAmelCase_       				=			json.load(lowerCAmelCase							)

				# a special token for Canine can be defined as follows:
				UpperCAmelCase_       				=			0XE006
				UpperCAmelCase_       				=			chr(lowerCAmelCase							)

				UpperCAmelCase_       				=			[new_token_a]
				UpperCAmelCase_       				=			[new_token_a]

				with open(os.path.join(lowerCAmelCase		,	"special_tokens_map.json"							)		,	"w"		,	encoding="utf-8"							) as outfile:
					json.dump(lowerCAmelCase		,	lowerCAmelCase							)
				with open(os.path.join(lowerCAmelCase		,	"tokenizer_config.json"							)		,	"w"		,	encoding="utf-8"							) as outfile:
					json.dump(lowerCAmelCase		,	lowerCAmelCase							)

				# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
				# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
				# "special_tokens_map.json" files
				UpperCAmelCase_       				=			tokenizer_class.from_pretrained(lowerCAmelCase		,	extra_ids=0							)
				self.assertIn(lowerCAmelCase		,	tokenizer_without_change_in_init.additional_special_tokens							)
				# self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
				self.assertEqual(
				    [new_token_a]		,	tokenizer_without_change_in_init.convert_ids_to_tokens(
				        tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a]							)							)		,	)

				UpperCAmelCase_       				=			0XE007
				UpperCAmelCase_       				=			chr(lowerCAmelCase							)
				# Now we test that we can change the value of additional_special_tokens in the from_pretrained
				UpperCAmelCase_       				=			[AddedToken(lowerCAmelCase		,	lstrip=lowerCAmelCase							)]
				UpperCAmelCase_       				=			tokenizer_class.from_pretrained(
				    lowerCAmelCase		,	additional_special_tokens=lowerCAmelCase		,	extra_ids=0							)

				self.assertIn(lowerCAmelCase		,	tokenizer.additional_special_tokens							)
				# self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab
				self.assertEqual(
				    [new_token_a]		,	tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a]							)							)							)




	@require_tokenizers
	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers(do_lower_case=lowerCAmelCase							)
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				UpperCAmelCase_       				=			"hello world"
				if self.space_between_special_tokens:
					UpperCAmelCase_       				=			"[CLS] hello world [SEP]"
				else:
					UpperCAmelCase_       				=			input
				UpperCAmelCase_       				=			tokenizer.encode(lowerCAmelCase		,	add_special_tokens=lowerCAmelCase							)
				UpperCAmelCase_       				=			tokenizer.decode(lowerCAmelCase		,	spaces_between_special_tokens=self.space_between_special_tokens							)
				self.assertIn(lowerCAmelCase		,	[output, output.lower()]							)




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.get_tokenizers()
		for tokenizer in tokenizers:
			with self.subTest(F"{tokenizer.__class__.__name__}"							):
				UpperCAmelCase_       				=			[
				    "bos_token",
				    "eos_token",
				    "unk_token",
				    "sep_token",
				    "pad_token",
				    "cls_token",
				    "mask_token",
				]

		UpperCAmelCase_       				=			"a"
		UpperCAmelCase_       				=			ord(lowerCAmelCase							)

		for attr in attributes_list:
			setattr(lowerCAmelCase		,	attr + "_id"		,	lowerCAmelCase							)
			self.assertEqual(getattr(lowerCAmelCase		,	lowerCAmelCase							)		,	lowerCAmelCase							)
			self.assertEqual(getattr(lowerCAmelCase		,	attr + "_id"							)		,	lowerCAmelCase							)

			setattr(lowerCAmelCase		,	attr + "_id"		,	lowerCAmelCase							)
			self.assertEqual(getattr(lowerCAmelCase		,	lowerCAmelCase							)		,	lowerCAmelCase							)
			self.assertEqual(getattr(lowerCAmelCase		,	attr + "_id"							)		,	lowerCAmelCase							)

		setattr(lowerCAmelCase		,	"additional_special_tokens_ids"		,	[]							)
		self.assertListEqual(getattr(lowerCAmelCase		,	"additional_special_tokens"							)		,	[]							)
		self.assertListEqual(getattr(lowerCAmelCase		,	"additional_special_tokens_ids"							)		,	[]							)

		UpperCAmelCase_       				=			0XE006
		UpperCAmelCase_       				=			chr(lowerCAmelCase							)
		setattr(lowerCAmelCase		,	"additional_special_tokens_ids"		,	[additional_special_token_id]							)
		self.assertListEqual(getattr(lowerCAmelCase		,	"additional_special_tokens"							)		,	[additional_special_token]							)
		self.assertListEqual(getattr(lowerCAmelCase		,	"additional_special_tokens_ids"							)		,	[additional_special_token_id]							)




	def       __A					(		self	:						int							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Dict							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		pass




	def       __A					(		self	:						int							):


		'''simple docstring'''







		pass