






"""simple docstring"""
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
			lowerCAmelCase__							= '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 							lowercase__		(				lowerCamelCase,	lowerCamelCase,	lowerCamelCase=None,	lowerCamelCase=None,	lowerCamelCase=None,	lowerCamelCase=None,	lowerCamelCase=None,	lowerCamelCase=None,	):
				if attention_mask is None:
								_SCREAMING_SNAKE_CASE      :		List[str]							=						np.where(input_ids != config.pad_token_id,	1,	0					)
				if decoder_attention_mask is None:
								_SCREAMING_SNAKE_CASE      :		List[Any]							=						np.where(decoder_input_ids != config.pad_token_id,	1,	0					)
				if head_mask is None:
								_SCREAMING_SNAKE_CASE      :		Dict							=						np.ones((config.encoder_layers, config.encoder_attention_heads)					)
				if decoder_head_mask is None:
								_SCREAMING_SNAKE_CASE      :		int							=						np.ones((config.decoder_layers, config.decoder_attention_heads)					)
				if cross_attn_head_mask is None:
								_SCREAMING_SNAKE_CASE      :		Optional[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 _lowerCAmelCase	:







						def __init__(						self      ,							lowerCAmelCase_      ,							lowerCAmelCase_=1_3      ,							lowerCAmelCase_=7      ,							lowerCAmelCase_=True      ,							lowerCAmelCase_=False      ,							lowerCAmelCase_=9_9      ,							lowerCAmelCase_=1_6      ,							lowerCAmelCase_=2      ,							lowerCAmelCase_=4      ,							lowerCAmelCase_=4      ,							lowerCAmelCase_="gelu"      ,							lowerCAmelCase_=0.1      ,							lowerCAmelCase_=0.1      ,							lowerCAmelCase_=3_2      ,							lowerCAmelCase_=2      ,							lowerCAmelCase_=1      ,							lowerCAmelCase_=0      ,							lowerCAmelCase_=0.02      ,							)		->       List[str]:
										_SCREAMING_SNAKE_CASE      :		Any							=						parent
										_SCREAMING_SNAKE_CASE      :		Dict							=						batch_size
										_SCREAMING_SNAKE_CASE      :		str							=						seq_length
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						is_training
										_SCREAMING_SNAKE_CASE      :		Any							=						use_labels
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						vocab_size
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						hidden_size
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						num_hidden_layers
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						num_attention_heads
										_SCREAMING_SNAKE_CASE      :		str							=						intermediate_size
										_SCREAMING_SNAKE_CASE      :		Tuple							=						hidden_act
										_SCREAMING_SNAKE_CASE      :		List[str]							=						hidden_dropout_prob
										_SCREAMING_SNAKE_CASE      :		Tuple							=						attention_probs_dropout_prob
										_SCREAMING_SNAKE_CASE      :		int							=						max_position_embeddings
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						eos_token_id
										_SCREAMING_SNAKE_CASE      :		Tuple							=						pad_token_id
										_SCREAMING_SNAKE_CASE      :		Any							=						bos_token_id
										_SCREAMING_SNAKE_CASE      :		int							=						initializer_range







						def  A			(						self       )		->       Optional[Any]:
										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						np.clip(ids_tensor([self.batch_size, self.seq_length - 1]      ,							self.vocab_size       )      ,							3      ,							self.vocab_size       )
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)      ,							dtype=np.intaa       ))      ,							-1       )

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						shift_tokens_right(lowerCAmelCase_      ,							1      ,							2       )

										_SCREAMING_SNAKE_CASE      :		str							=						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=lowerCAmelCase_      ,							)
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						prepare_marian_inputs_dict(lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )
										return config, inputs_dict







						def  A			(						self       )		->       Dict:
										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		List[str]							=						self.prepare_config_and_inputs()
										return config, inputs_dict







						def  A			(						self      ,							lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )		->       str:
										_SCREAMING_SNAKE_CASE      :		int							=						2_0
										_SCREAMING_SNAKE_CASE      :		Tuple							=						model_class_name(lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		Dict							=						model.encode(inputs_dict['input_ids']       )

										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		List[str]							=						(
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

										_SCREAMING_SNAKE_CASE      :		str							=						model.init_cache(decoder_input_ids.shape[0]      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		int							=						jnp.ones((decoder_input_ids.shape[0], max_decoder_length)      ,							dtype='i4'       )

										_SCREAMING_SNAKE_CASE      :		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)      ,							)
										_SCREAMING_SNAKE_CASE      :		str							=						model.decode(
										    decoder_input_ids[:, :-1]      ,							lowerCAmelCase_      ,							decoder_attention_mask=lowerCAmelCase_      ,							past_key_values=lowerCAmelCase_      ,							decoder_position_ids=lowerCAmelCase_      ,							)

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,							dtype='i4'       )
										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						model.decode(
										    decoder_input_ids[:, -1:]      ,							lowerCAmelCase_      ,							decoder_attention_mask=lowerCAmelCase_      ,							past_key_values=outputs_cache.past_key_values      ,							decoder_position_ids=lowerCAmelCase_      ,							)

										_SCREAMING_SNAKE_CASE      :		List[Any]							=						model.decode(lowerCAmelCase_      ,							lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						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  A			(						self      ,							lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )		->       str:
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						2_0
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						model_class_name(lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		List[str]							=						model.encode(inputs_dict['input_ids']       )

										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		Optional[int]							=						(
										    inputs_dict['decoder_input_ids'],
										    inputs_dict['decoder_attention_mask'],
										)

										_SCREAMING_SNAKE_CASE      :		Any							=						jnp.concatenate(
										    [
										        decoder_attention_mask,
										        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])       ),
										    ]      ,							axis=-1      ,							)

										_SCREAMING_SNAKE_CASE      :		Any							=						model.init_cache(decoder_input_ids.shape[0]      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		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)      ,							)

										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						model.decode(
										    decoder_input_ids[:, :-1]      ,							lowerCAmelCase_      ,							decoder_attention_mask=lowerCAmelCase_      ,							past_key_values=lowerCAmelCase_      ,							decoder_position_ids=lowerCAmelCase_      ,							)
										_SCREAMING_SNAKE_CASE      :		List[str]							=						jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,							dtype='i4'       )
										_SCREAMING_SNAKE_CASE      :		Dict							=						model.decode(
										    decoder_input_ids[:, -1:]      ,							lowerCAmelCase_      ,							past_key_values=outputs_cache.past_key_values      ,							decoder_attention_mask=lowerCAmelCase_      ,							decoder_position_ids=lowerCAmelCase_      ,							)

										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						model.decode(lowerCAmelCase_      ,							lowerCAmelCase_      ,							decoder_attention_mask=lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		Dict							=						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 _lowerCAmelCase	(						__UpperCAmelCase      ,     unittest.TestCase      ,     __UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				str   				=							True
						SCREAMING_SNAKE_CASE_:				Any   				=							(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
						SCREAMING_SNAKE_CASE_:				Dict   				=							(FlaxMarianMTModel,) if is_flax_available() else ()







						def  A			(						self       )		->       str:
										_SCREAMING_SNAKE_CASE      :		Tuple							=						FlaxMarianModelTester(self       )







						def  A			(						self       )		->       int:
										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		str							=						self.model_tester.prepare_config_and_inputs()
										for model_class in self.all_model_classes:
														self.model_tester.check_use_cache_forward(lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )







						def  A			(						self       )		->       Any:
										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		Optional[int]							=						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(lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       )







						def  A			(						self       )		->       Optional[int]:
										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		List[str]							=						self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__       ):
																		_SCREAMING_SNAKE_CASE      :		Optional[int]							=						self._prepare_for_class(lowerCAmelCase_      ,							lowerCAmelCase_       )
																		_SCREAMING_SNAKE_CASE      :		Any							=						model_class(lowerCAmelCase_       )

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

																		with self.subTest('JIT Enabled'       ):
																						_SCREAMING_SNAKE_CASE      :		int							=						encode_jitted(**lowerCAmelCase_       ).to_tuple()

																		with self.subTest('JIT Disabled'       ):
																						with jax.disable_jit():
																										_SCREAMING_SNAKE_CASE      :		str							=						encode_jitted(**lowerCAmelCase_       ).to_tuple()

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







						def  A			(						self       )		->       Dict:
										_SCREAMING_SNAKE_CASE		,	_SCREAMING_SNAKE_CASE      :		Tuple							=						self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__       ):
																		_SCREAMING_SNAKE_CASE      :		str							=						model_class(lowerCAmelCase_       )
																		_SCREAMING_SNAKE_CASE      :		Dict							=						model.encode(inputs_dict['input_ids']      ,							inputs_dict['attention_mask']       )

																		_SCREAMING_SNAKE_CASE      :		Tuple							=						{
																		    '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(lowerCAmelCase_      ,							lowerCAmelCase_      ,							lowerCAmelCase_       ):
																						return model.decode(
																						    decoder_input_ids=lowerCAmelCase_      ,							decoder_attention_mask=lowerCAmelCase_      ,							encoder_outputs=lowerCAmelCase_      ,							)

																		with self.subTest('JIT Enabled'       ):
																						_SCREAMING_SNAKE_CASE      :		List[Any]							=						decode_jitted(**lowerCAmelCase_       ).to_tuple()

																		with self.subTest('JIT Disabled'       ):
																						with jax.disable_jit():
																										_SCREAMING_SNAKE_CASE      :		List[str]							=						decode_jitted(**lowerCAmelCase_       ).to_tuple()

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







						@slow
						def  A			(						self       )		->       Optional[int]:
										for model_class_name in self.all_model_classes:
														_SCREAMING_SNAKE_CASE      :		Optional[int]							=						model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de'       )
														# FlaxMarianForSequenceClassification expects eos token in input_ids
														_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						np.ones((1, 1)       ) * model.config.eos_token_id
														_SCREAMING_SNAKE_CASE      :		List[Any]							=						model(lowerCAmelCase_       )
														self.assertIsNotNone(lowerCAmelCase_       )







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						unittest.TestCase					):
						SCREAMING_SNAKE_CASE_:				Any   				=							None
						SCREAMING_SNAKE_CASE_:				Optional[Any]   				=							None







						@classmethod
						def  A			(						cls       )		->       None:
										_SCREAMING_SNAKE_CASE      :		Any							=						F"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
										return cls







						@cached_property
						def  A			(						self       )		->       Union[str, Any]:
										return MarianTokenizer.from_pretrained(self.model_name       )







						@property
						def  A			(						self       )		->       int:
										return self.tokenizer.eos_token_id







						@cached_property
						def  A			(						self       )		->       str:
										_SCREAMING_SNAKE_CASE      :		FlaxMarianMTModel							=						FlaxMarianMTModel.from_pretrained(self.model_name       )
										self.assertEqual(model.config.decoder_start_token_id      ,							model.config.pad_token_id       )
										return model







						def  A			(						self      ,							**lowerCAmelCase_       )		->       List[Any]:
										_SCREAMING_SNAKE_CASE      :		str							=						self.translate_src_text(**lowerCAmelCase_       )
										self.assertListEqual(self.expected_text      ,							lowerCAmelCase_       )







						def  A			(						self      ,							**lowerCAmelCase_       )		->       str:
										_SCREAMING_SNAKE_CASE      :		List[str]							=						self.tokenizer(self.src_text      ,							padding=lowerCAmelCase_      ,							return_tensors='np'      ,							**lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						self.model.generate(
										    model_inputs.input_ids      ,							attention_mask=model_inputs.attention_mask      ,							num_beams=2      ,							max_length=1_2_8      ,							).sequences
										_SCREAMING_SNAKE_CASE      :		int							=						self.tokenizer.batch_decode(lowerCAmelCase_      ,							skip_special_tokens=lowerCAmelCase_       )
										return generated_words







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				List[Any]   				=							'en'
						SCREAMING_SNAKE_CASE_:				Any   				=							'fr'
						SCREAMING_SNAKE_CASE_:				Any   				=							[
						    'I am a small frog.',
						    'Now I can forget the 100 words of german that I know.',
						]
						SCREAMING_SNAKE_CASE_:				Tuple   				=							[
						    'Je suis une petite grenouille.',
						    'Maintenant, je peux oublier les 100 mots d\'allemand que je connais.',
						]







						@slow
						def  A			(						self       )		->       Any:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				str   				=							'fr'
						SCREAMING_SNAKE_CASE_:				str   				=							'en'
						SCREAMING_SNAKE_CASE_:				str   				=							[
						    'Donnez moi le micro.',
						    'Tom et Mary étaient assis à une table.',  # Accents
						]
						SCREAMING_SNAKE_CASE_:				str   				=							[
						    'Give me the microphone.',
						    'Tom and Mary were sitting at a table.',
						]







						@slow
						def  A			(						self       )		->       Tuple:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				Union[str, Any]   				=							'mt'
						SCREAMING_SNAKE_CASE_:				List[Any]   				=							'en'
						SCREAMING_SNAKE_CASE_:				Optional[Any]   				=							['Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.']
						SCREAMING_SNAKE_CASE_:				Union[str, Any]   				=							['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.']







						@slow
						def  A			(						self       )		->       int:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				Optional[Any]   				=							'en'
						SCREAMING_SNAKE_CASE_:				Any   				=							'de'
						SCREAMING_SNAKE_CASE_:				Tuple   				=							[
						    '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.',
						]
						SCREAMING_SNAKE_CASE_:				int   				=							[
						    '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  A			(						self       )		->       Dict:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				int   				=							'en'
						SCREAMING_SNAKE_CASE_:				Optional[Any]   				=							'zh'
						SCREAMING_SNAKE_CASE_:				List[Any]   				=							['My name is Wolfgang and I live in Berlin']
						SCREAMING_SNAKE_CASE_:				Union[str, Any]   				=							['我叫沃尔夫冈 我住在柏林']







						@slow
						def  A			(						self       )		->       Any:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				str   				=							'ru'
						SCREAMING_SNAKE_CASE_:				List[str]   				=							'fr'
						SCREAMING_SNAKE_CASE_:				Optional[int]   				=							['Он показал мне рукопись своей новой пьесы.']
						SCREAMING_SNAKE_CASE_:				int   				=							['Il m\'a montré le manuscrit de sa nouvelle pièce.']







						@slow
						def  A			(						self       )		->       Optional[Any]:
										self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class _lowerCAmelCase	(						__UpperCAmelCase					):
						SCREAMING_SNAKE_CASE_:				Optional[Any]   				=							'en'
						SCREAMING_SNAKE_CASE_:				List[str]   				=							'ROMANCE'
						SCREAMING_SNAKE_CASE_:				List[str]   				=							[
						    '>>fr<< Don\'t spend so much time watching TV.',
						    '>>pt<< Your message has been sent.',
						    '>>es<< He\'s two years older than me.',
						]
						SCREAMING_SNAKE_CASE_:				Union[str, 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  A			(						self       )		->       str:
										self._assert_generated_batch_equal_expected()









"""simple docstring"""
import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()


class _lowerCAmelCase	(						__UpperCAmelCase      ,     __UpperCAmelCase      ,     unittest.TestCase					):
						SCREAMING_SNAKE_CASE_:				int   				=							StableDiffusionParadigmsPipeline
						SCREAMING_SNAKE_CASE_:				str   				=							TEXT_TO_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE_:				Any   				=							TEXT_TO_IMAGE_BATCH_PARAMS
						SCREAMING_SNAKE_CASE_:				str   				=							TEXT_TO_IMAGE_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE_:				List[Any]   				=							TEXT_TO_IMAGE_IMAGE_PARAMS







						def  A			(						self       )		->       int:
										torch.manual_seed(0       )
										_SCREAMING_SNAKE_CASE      :		Dict							=						UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4)      ,							layers_per_block=2      ,							sample_size=3_2      ,							in_channels=4      ,							out_channels=4      ,							down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')      ,							up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')      ,							cross_attention_dim=3_2      ,							attention_head_dim=(2, 4)      ,							use_linear_projection=lowerCAmelCase_      ,							)
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						DDIMParallelScheduler(
										    beta_start=0.00_085      ,							beta_end=0.012      ,							beta_schedule='scaled_linear'      ,							clip_sample=lowerCAmelCase_      ,							set_alpha_to_one=lowerCAmelCase_      ,							)
										torch.manual_seed(0       )
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						AutoencoderKL(
										    block_out_channels=[3_2, 6_4]      ,							in_channels=3      ,							out_channels=3      ,							down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']      ,							up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']      ,							latent_channels=4      ,							sample_size=1_2_8      ,							)
										torch.manual_seed(0       )
										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						CLIPTextConfig(
										    bos_token_id=0      ,							eos_token_id=2      ,							hidden_size=3_2      ,							intermediate_size=3_7      ,							layer_norm_eps=1e-05      ,							num_attention_heads=4      ,							num_hidden_layers=5      ,							pad_token_id=1      ,							vocab_size=1_0_0_0      ,							hidden_act='gelu'      ,							projection_dim=5_1_2      ,							)
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						CLIPTextModel(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'       )

										_SCREAMING_SNAKE_CASE      :		List[Any]							=						{
										    'unet': unet,
										    'scheduler': scheduler,
										    'vae': vae,
										    'text_encoder': text_encoder,
										    'tokenizer': tokenizer,
										    'safety_checker': None,
										    'feature_extractor': None,
										}
										return components







						def  A			(						self      ,							lowerCAmelCase_      ,							lowerCAmelCase_=0       )		->       Tuple:
										if str(lowerCAmelCase_       ).startswith('mps'       ):
														_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						torch.manual_seed(lowerCAmelCase_       )
										else:
														_SCREAMING_SNAKE_CASE      :		int							=						torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		str							=						{
										    'prompt': 'a photograph of an astronaut riding a horse',
										    'generator': generator,
										    'num_inference_steps': 1_0,
										    'guidance_scale': 6.0,
										    'output_type': 'numpy',
										    'parallel': 3,
										    'debug': True,
										}
										return inputs







						def  A			(						self       )		->       int:
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						'cpu'  # ensure determinism for the device-dependent torch.Generator
										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						self.get_dummy_components()
										_SCREAMING_SNAKE_CASE      :		Any							=						StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						sd_pipe.to(lowerCAmelCase_       )
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						self.get_dummy_inputs(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Dict							=						sd_pipe(**lowerCAmelCase_       ).images
										_SCREAMING_SNAKE_CASE      :		Dict							=						image[0, -3:, -3:, -1]
										assert image.shape == (1, 6_4, 6_4, 3)

										_SCREAMING_SNAKE_CASE      :		int							=						np.array([0.4_773, 0.5_417, 0.4_723, 0.4_925, 0.5_631, 0.4_752, 0.5_240, 0.4_935, 0.5_023]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2







						def  A			(						self       )		->       Tuple:
										_SCREAMING_SNAKE_CASE      :		Tuple							=						'cpu'  # ensure determinism for the device-dependent torch.Generator
										_SCREAMING_SNAKE_CASE      :		str							=						self.get_dummy_components()
										torch.manual_seed(0       )
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						DDPMParallelScheduler()
										torch.manual_seed(0       )
										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		int							=						sd_pipe.to(lowerCAmelCase_       )
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		Tuple							=						self.get_dummy_inputs(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						sd_pipe(**lowerCAmelCase_       ).images
										_SCREAMING_SNAKE_CASE      :		Dict							=						image[0, -3:, -3:, -1]
										assert image.shape == (1, 6_4, 6_4, 3)

										_SCREAMING_SNAKE_CASE      :		Dict							=						np.array([0.3_573, 0.4_420, 0.4_960, 0.4_799, 0.3_796, 0.3_879, 0.4_819, 0.4_365, 0.4_468]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2







						def  A			(						self       )		->       Optional[Any]:
										super().test_inference_batch_consistent(batch_sizes=[1, 2]       )







						def  A			(						self       )		->       Tuple:
										super().test_inference_batch_single_identical(batch_size=2      ,							expected_max_diff=3e-3       )







						def  A			(						self       )		->       List[str]:
										_SCREAMING_SNAKE_CASE      :		List[Any]							=						'cpu'  # ensure determinism for the device-dependent torch.Generator
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						self.get_dummy_components()
										_SCREAMING_SNAKE_CASE      :		Union[str, Any]							=						StableDiffusionParadigmsPipeline(**lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		List[str]							=						sd_pipe.to(lowerCAmelCase_       )
										sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

										_SCREAMING_SNAKE_CASE      :		int							=						self.get_dummy_inputs(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Tuple							=						'french fries'
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						sd_pipe(**lowerCAmelCase_      ,							negative_prompt=lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		Optional[Any]							=						output.images
										_SCREAMING_SNAKE_CASE      :		Dict							=						image[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						np.array([0.4_771, 0.5_420, 0.4_683, 0.4_918, 0.5_636, 0.4_725, 0.5_230, 0.4_923, 0.5_015]       )

										assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2







@slow
@require_torch_gpu
class _lowerCAmelCase	(						unittest.TestCase					):







						def  A			(						self       )		->       Tuple:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







						def  A			(						self      ,							lowerCAmelCase_=0       )		->       int:
										_SCREAMING_SNAKE_CASE      :		str							=						torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
										_SCREAMING_SNAKE_CASE      :		List[str]							=						{
										    'prompt': 'a photograph of an astronaut riding a horse',
										    'generator': generator,
										    'num_inference_steps': 1_0,
										    'guidance_scale': 7.5,
										    'output_type': 'numpy',
										    'parallel': 3,
										    'debug': True,
										}
										return inputs







						def  A			(						self       )		->       List[str]:
										_SCREAMING_SNAKE_CASE      :		Any							=						'stabilityai/stable-diffusion-2-base'
										_SCREAMING_SNAKE_CASE      :		Dict							=						DDIMParallelScheduler.from_pretrained(lowerCAmelCase_      ,							subfolder='scheduler'       )
										_SCREAMING_SNAKE_CASE      :		List[str]							=						StableDiffusionParadigmsPipeline.from_pretrained(lowerCAmelCase_      ,							scheduler=lowerCAmelCase_      ,							safety_checker=lowerCAmelCase_       )
										pipe.to(lowerCAmelCase_       )
										pipe.set_progress_bar_config(disable=lowerCAmelCase_       )
										pipe.enable_attention_slicing()

										_SCREAMING_SNAKE_CASE      :		Optional[int]							=						self.get_inputs()
										_SCREAMING_SNAKE_CASE      :		str							=						pipe(**lowerCAmelCase_       ).images
										_SCREAMING_SNAKE_CASE      :		Dict							=						image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)

										_SCREAMING_SNAKE_CASE      :		Any							=						np.array([0.9_622, 0.9_602, 0.9_748, 0.9_591, 0.9_630, 0.9_691, 0.9_661, 0.9_631, 0.9_741]       )

										assert np.abs(expected_slice - image_slice       ).max() < 1e-2

