




__lowerCamelCase :    int      						=      10_00







def 		lowercase__ (		__A:						float					):





					'''simple docstring'''






					return x * x







def 		lowercase__ (		__A:						Dict				,__A:						float				,__A:						float				,__A:						int = 4					):





					'''simple docstring'''






					assert callable(
					    __A					), F'''the function(object) passed should be callable your input : {function}'''
					assert isinstance(__A				,(float, int)					), F'''a should be float or integer your input : {a}'''
					assert isinstance(function(__A					)				,(float, int)					), (
					    "the function should return integer or float return type of your function, "
					    F'''{type(__A					)}'''
					)
					assert isinstance(__A				,(float, int)					), F'''b should be float or integer your input : {b}'''
					assert (
					    isinstance(__A				,__A					) and precision > 0
					), F'''precision should be positive integer your input : {precision}'''

					# just applying the formula of simpson for approximate integration written in
					# mentioned article in first comment of this file and above this function

					__magic_name__				:						List[str]     				=				(b - a) / N_STEPS
					__magic_name__				:						Dict     				=				function(__A					) + function(__A					)

					for i in range(1				,__A					):
										__magic_name__				:						Optional[int]     				=				a + h * i
										result += function(__A					) * (4 if i % 2 else 2)

					result *= h / 3
					return round(__A				,__A					)


if __name__ == "__main__":
	import doctest

	doctest.testmod()









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 :    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 		lowercase__ (		__A:						Optional[int]				,__A:						int				,__A:						Optional[int]=None				,__A:						str=None				,__A:						Optional[Any]=None				,__A:						Dict=None				,__A:						Union[str, Any]=None				,__A:						Dict=None				,):





					'''simple docstring'''






					if attention_mask is None:
										__magic_name__				:						Tuple     				=				np.where(input_ids != config.pad_token_id				,1				,0					)
					if decoder_attention_mask is None:
										__magic_name__				:						str     				=				np.where(decoder_input_ids != config.pad_token_id				,1				,0					)
					if head_mask is None:
										__magic_name__				:						List[str]     				=				np.ones((config.encoder_layers, config.encoder_attention_heads)					)
					if decoder_head_mask is None:
										__magic_name__				:						Any     				=				np.ones((config.decoder_layers, config.decoder_attention_heads)					)
					if cross_attn_head_mask is None:
										__magic_name__				:						str     				=				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     :






			'''simple docstring'''





			def __init__(			self      : Tuple							,    lowerCamelCase_      : Optional[int]							,    lowerCamelCase_      : List[str]=13							,    lowerCamelCase_      : str=7							,    lowerCamelCase_      : Optional[Any]=True							,    lowerCamelCase_      : int=False							,    lowerCamelCase_      : List[str]=99							,    lowerCamelCase_      : Tuple=16							,    lowerCamelCase_      : Optional[Any]=2							,    lowerCamelCase_      : Optional[int]=4							,    lowerCamelCase_      : int=4							,    lowerCamelCase_      : List[str]="gelu"							,    lowerCamelCase_      : List[str]=0.1							,    lowerCamelCase_      : Optional[Any]=0.1							,    lowerCamelCase_      : Optional[Any]=32							,    lowerCamelCase_      : Optional[Any]=2							,    lowerCamelCase_      : Any=1							,    lowerCamelCase_      : List[Any]=0							,    lowerCamelCase_      : Union[str, Any]=0.0_2							,    )    -> Dict:
								__magic_name__				:						Optional[int]     				=				parent
								__magic_name__				:						Optional[Any]     				=				batch_size
								__magic_name__				:						Any     				=				seq_length
								__magic_name__				:						Any     				=				is_training
								__magic_name__				:						Union[str, Any]     				=				use_labels
								__magic_name__				:						Optional[Any]     				=				vocab_size
								__magic_name__				:						List[str]     				=				hidden_size
								__magic_name__				:						Optional[Any]     				=				num_hidden_layers
								__magic_name__				:						Tuple     				=				num_attention_heads
								__magic_name__				:						Optional[int]     				=				intermediate_size
								__magic_name__				:						Any     				=				hidden_act
								__magic_name__				:						Optional[int]     				=				hidden_dropout_prob
								__magic_name__				:						Union[str, Any]     				=				attention_probs_dropout_prob
								__magic_name__				:						Any     				=				max_position_embeddings
								__magic_name__				:						Optional[Any]     				=				eos_token_id
								__magic_name__				:						str     				=				pad_token_id
								__magic_name__				:						int     				=				bos_token_id
								__magic_name__				:						Union[str, Any]     				=				initializer_range

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

								__magic_name__				:						Union[str, Any]     				=				shift_tokens_right(lowerCamelCase_							,    1							,    2	)

								__magic_name__				:						Any     				=				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_							,    )
								__magic_name__				:						int     				=				prepare_marian_inputs_dict(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_	)
								return config, inputs_dict

			def 				UpperCAmelCase__							(			self      : List[str]	)    -> Any:
								__magic_name__				,     __magic_name__				:						int     				=				self.prepare_config_and_inputs()
								return config, inputs_dict

			def 				UpperCAmelCase__							(			self      : Any							,    lowerCamelCase_      : List[Any]							,    lowerCamelCase_      : str							,    lowerCamelCase_      : Union[str, Any]	)    -> Any:
								__magic_name__				:						int     				=				20
								__magic_name__				:						Union[str, Any]     				=				model_class_name(lowerCamelCase_	)

								__magic_name__				:						List[Any]     				=				model.encode(inputs_dict['''input_ids''']	)

								__magic_name__				,     __magic_name__				:						Any     				=				(
								    inputs_dict['''decoder_input_ids'''],
								    inputs_dict['''decoder_attention_mask'''],
								)

								__magic_name__				:						Union[str, Any]     				=				model.init_cache(decoder_input_ids.shape[0]							,    lowerCamelCase_							,    lowerCamelCase_	)
								__magic_name__				:						Dict     				=				jnp.ones((decoder_input_ids.shape[0], max_decoder_length)							,    dtype='''i4'''	)

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

								__magic_name__				:						List[str]     				=				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]							,    dtype='''i4'''	)
								__magic_name__				:						List[str]     				=				model.decode(
								    decoder_input_ids[:, -1:]							,    lowerCamelCase_							,    decoder_attention_mask=lowerCamelCase_							,    past_key_values=outputs_cache.past_key_values							,    decoder_position_ids=lowerCamelCase_							,    )

								__magic_name__				:						Optional[int]     				=				model.decode(lowerCamelCase_							,    lowerCamelCase_	)

								__magic_name__				:						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}'''	)


			def 				UpperCAmelCase__							(			self      : Tuple							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : Optional[Any]							,    lowerCamelCase_      : Any	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				20
								__magic_name__				:						Union[str, Any]     				=				model_class_name(lowerCamelCase_	)

								__magic_name__				:						Tuple     				=				model.encode(inputs_dict['''input_ids''']	)

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

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

								__magic_name__				:						List[Any]     				=				model.init_cache(decoder_input_ids.shape[0]							,    lowerCamelCase_							,    lowerCamelCase_	)
								__magic_name__				:						Optional[Any]     				=				jnp.broadcast_to(
								    jnp.arange(decoder_input_ids.shape[-1] - 1	)[None, :]							,    (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)							,    )

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

								__magic_name__				:						Union[str, Any]     				=				model.decode(lowerCamelCase_							,    lowerCamelCase_							,    decoder_attention_mask=lowerCamelCase_	)

								__magic_name__				:						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}'''	)






@require_flax
class  lowerCamelCase     (		_lowerCamelCase					,unittest.TestCase					,_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										=True
			UpperCamelCase__										=(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
			UpperCamelCase__										=(FlaxMarianMTModel,) if is_flax_available() else ()

			def 				UpperCAmelCase__							(			self      : Dict	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				FlaxMarianModelTester(self	)

			def 				UpperCAmelCase__							(			self      : str	)    -> Dict:
								__magic_name__				,     __magic_name__				:						Dict     				=				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 				UpperCAmelCase__							(			self      : str	)    -> List[str]:
								__magic_name__				,     __magic_name__				:						List[str]     				=				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 				UpperCAmelCase__							(			self      : Optional[int]	)    -> Any:
								__magic_name__				,     __magic_name__				:						Dict     				=				self.model_tester.prepare_config_and_inputs_for_common()

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

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

																		with self.subTest('''JIT Enabled'''	):
																							__magic_name__				:						Any     				=				encode_jitted(**lowerCamelCase_	).to_tuple()

																		with self.subTest('''JIT Disabled'''	):
																							with jax.disable_jit():
																												__magic_name__				:						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 				UpperCAmelCase__							(			self      : List[str]	)    -> Union[str, Any]:
								__magic_name__				,     __magic_name__				:						Optional[int]     				=				self.model_tester.prepare_config_and_inputs_for_common()

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

																		__magic_name__				:						List[str]     				=				{
																		    '''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_      : Optional[int]							,    lowerCamelCase_      : List[str]							,    lowerCamelCase_      : Tuple	):
																							return model.decode(
																							    decoder_input_ids=lowerCamelCase_							,    decoder_attention_mask=lowerCamelCase_							,    encoder_outputs=lowerCamelCase_							,    )

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

																		with self.subTest('''JIT Disabled'''	):
																							with jax.disable_jit():
																												__magic_name__				:						int     				=				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 				UpperCAmelCase__							(			self      : Any	)    -> Tuple:
								for model_class_name in self.all_model_classes:
													__magic_name__				:						List[Any]     				=				model_class_name.from_pretrained('''Helsinki-NLP/opus-mt-en-de'''	)
													# FlaxMarianForSequenceClassification expects eos token in input_ids
													__magic_name__				:						Dict     				=				np.ones((1, 1)	) * model.config.eos_token_id
													__magic_name__				:						Optional[int]     				=				model(lowerCamelCase_	)
													self.assertIsNotNone(lowerCamelCase_	)






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






			'''simple docstring'''





			UpperCamelCase__										=None
			UpperCamelCase__										=None

			@classmethod
			def 				UpperCAmelCase__							(			cls      : Dict	)    -> None:
								__magic_name__				:						Tuple     				=				F'''Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}'''
								return cls

			@cached_property
			def 				UpperCAmelCase__							(			self      : str	)    -> Any:
								return MarianTokenizer.from_pretrained(self.model_name	)

			@property
			def 				UpperCAmelCase__							(			self      : List[str]	)    -> int:
								return self.tokenizer.eos_token_id

			@cached_property
			def 				UpperCAmelCase__							(			self      : List[Any]	)    -> Optional[Any]:
								__magic_name__				:						FlaxMarianMTModel     				=				FlaxMarianMTModel.from_pretrained(self.model_name	)
								self.assertEqual(model.config.decoder_start_token_id							,    model.config.pad_token_id	)
								return model

			def 				UpperCAmelCase__							(			self      : List[Any]							,    **lowerCamelCase_      : Dict	)    -> Optional[int]:
								__magic_name__				:						List[str]     				=				self.translate_src_text(**lowerCamelCase_	)
								self.assertListEqual(self.expected_text							,    lowerCamelCase_	)


			def 				UpperCAmelCase__							(			self      : int							,    **lowerCamelCase_      : Optional[int]	)    -> Optional[Any]:
								__magic_name__				:						List[str]     				=				self.tokenizer(self.src_text							,    padding=lowerCamelCase_							,    return_tensors='''np'''							,    **lowerCamelCase_	)
								__magic_name__				:						Union[str, Any]     				=				self.model.generate(
								    model_inputs.input_ids							,    attention_mask=model_inputs.attention_mask							,    num_beams=2							,    max_length=128							,    ).sequences
								__magic_name__				:						Dict     				=				self.tokenizer.batch_decode(lowerCamelCase_							,    skip_special_tokens=lowerCamelCase_	)
								return generated_words






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





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

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





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

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





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

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''de'''
			UpperCamelCase__										=[
			    '''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.''',
			]
			UpperCamelCase__										=[
			    '''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 				UpperCAmelCase__							(			self      : List[str]	)    -> Optional[Any]:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





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

			@slow
			def 				UpperCAmelCase__							(			self      : Optional[int]	)    -> str:
								self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





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

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






@require_flax
@require_sentencepiece
@require_tokenizers
class  lowerCamelCase     (		_lowerCamelCase    ):






			'''simple docstring'''





			UpperCamelCase__										='''en'''
			UpperCamelCase__										='''ROMANCE'''
			UpperCamelCase__										=[
			    '''>>fr<< Don\'t spend so much time watching TV.''',
			    '''>>pt<< Your message has been sent.''',
			    '''>>es<< He\'s two years older than me.''',
			]
			UpperCamelCase__										=[
			    '''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 				UpperCAmelCase__							(			self      : Tuple	)    -> Optional[int]:
								self._assert_generated_batch_equal_expected()



