





from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_lowerCamelCase       =	logging.get_logger(__name__)

_lowerCamelCase       =	{
    'facebook/mbart-large-cc25': 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/config.json',
    # See all MBART models at https://huggingface.co/models?filter=mbart
}




class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    "mbart"
							lowerCamelCase_							=    ["past_key_values"]
							lowerCamelCase_							=    {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}


							def __init__(							self			:int							, __A			:List[str]=5_0265							, __A			:Optional[Any]=1024							, __A			:Optional[Any]=12							, __A			:str=4096							, __A			:List[str]=16							, __A			:List[str]=12							, __A			:Dict=4096							, __A			:Optional[int]=16							, __A			:Optional[Any]=0.0							, __A			:Optional[int]=0.0							, __A			:Optional[int]=True							, __A			:Dict=True							, __A			:Dict="gelu"							, __A			:Dict=1024							, __A			:Tuple=0.1							, __A			:List[Any]=0.0							, __A			:int=0.0							, __A			:Union[str, Any]=0.0_2							, __A			:int=0.0							, __A			:Any=False							, __A			:List[str]=1							, __A			:Optional[int]=0							, __A			:Dict=2							, __A			:Optional[int]=2							, **__A			:List[str]							, )      ->      Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					vocab_size
									SCREAMING_SNAKE_CASE__								=					max_position_embeddings
									SCREAMING_SNAKE_CASE__								=					d_model
									SCREAMING_SNAKE_CASE__								=					encoder_ffn_dim
									SCREAMING_SNAKE_CASE__								=					encoder_layers
									SCREAMING_SNAKE_CASE__								=					encoder_attention_heads
									SCREAMING_SNAKE_CASE__								=					decoder_ffn_dim
									SCREAMING_SNAKE_CASE__								=					decoder_layers
									SCREAMING_SNAKE_CASE__								=					decoder_attention_heads
									SCREAMING_SNAKE_CASE__								=					dropout
									SCREAMING_SNAKE_CASE__								=					attention_dropout
									SCREAMING_SNAKE_CASE__								=					activation_dropout
									SCREAMING_SNAKE_CASE__								=					activation_function
									SCREAMING_SNAKE_CASE__								=					init_std
									SCREAMING_SNAKE_CASE__								=					encoder_layerdrop
									SCREAMING_SNAKE_CASE__								=					decoder_layerdrop
									SCREAMING_SNAKE_CASE__								=					classifier_dropout
									SCREAMING_SNAKE_CASE__								=					use_cache
									SCREAMING_SNAKE_CASE__								=					encoder_layers
									SCREAMING_SNAKE_CASE__								=					scale_embedding  # scale factor will be sqrt(d_model) if True
									super().__init__(
									    pad_token_id=__A							, bos_token_id=__A							, eos_token_id=__A							, is_encoder_decoder=__A							, forced_eos_token_id=__A							, **__A							, )




class      UpperCamelCase_				(   UpperCamelCase__			):


							@property
							def    _snake_case     (							self			:List[str]						)      ->      Mapping[str, Mapping[int, str]]:



									"""simple docstring"""



									if self.task in ["default", "seq2seq-lm"]:
											SCREAMING_SNAKE_CASE__								=					OrderedDict(
											    [
											        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
											        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
											    ]						)

											if self.use_past:
													SCREAMING_SNAKE_CASE__								=					{0: """batch"""}
													SCREAMING_SNAKE_CASE__								=					{0: """batch""", 1: """past_decoder_sequence + sequence"""}
											else:
													SCREAMING_SNAKE_CASE__								=					{0: """batch""", 1: """decoder_sequence"""}
													SCREAMING_SNAKE_CASE__								=					{0: """batch""", 1: """decoder_sequence"""}

											if self.use_past:
													self.fill_with_past_key_values_(__A							, direction="""inputs"""						)
									elif self.task == "causal-lm":
											# TODO: figure this case out.
											SCREAMING_SNAKE_CASE__								=					OrderedDict(
											    [
											        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
											        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
											    ]						)
											if self.use_past:
													SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_layers
													for i in range(__A						):
															SCREAMING_SNAKE_CASE__								=					{0: """batch""", 2: """past_sequence + sequence"""}
															SCREAMING_SNAKE_CASE__								=					{0: """batch""", 2: """past_sequence + sequence"""}
									else:
											SCREAMING_SNAKE_CASE__								=					OrderedDict(
											    [
											        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
											        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
											        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
											        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
											    ]						)

									return common_inputs


							@property
							def    _snake_case     (							self			:Any						)      ->      Mapping[str, Mapping[int, str]]:



									"""simple docstring"""



									if self.task in ["default", "seq2seq-lm"]:
											SCREAMING_SNAKE_CASE__								=					super().outputs
									else:
											SCREAMING_SNAKE_CASE__								=					super(__A							, self						).outputs
											if self.use_past:
													SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_layers
													for i in range(__A						):
															SCREAMING_SNAKE_CASE__								=					{0: """batch""", 2: """past_sequence + sequence"""}
															SCREAMING_SNAKE_CASE__								=					{0: """batch""", 2: """past_sequence + sequence"""}
									return common_outputs


							def    _snake_case     (							self			:Any							, __A			:PreTrainedTokenizer							, __A			:int = -1							, __A			:int = -1							, __A			:bool = False							, __A			:Optional[TensorType] = None							, )      ->      Mapping[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    __A							, __A							, __A							, __A							, __A						)

									# Generate decoder inputs
									SCREAMING_SNAKE_CASE__								=					seq_length if not self.use_past else 1
									SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    __A							, __A							, __A							, __A							, __A						)
									SCREAMING_SNAKE_CASE__								=					{f'''decoder_{name}''': tensor for name, tensor in decoder_inputs.items()}
									SCREAMING_SNAKE_CASE__								=					dict(**__A							, **__A						)

									if self.use_past:
											if not is_torch_available():
													raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""						)
											else:
													import torch
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					common_inputs["""input_ids"""].shape
											SCREAMING_SNAKE_CASE__								=					common_inputs["""decoder_input_ids"""].shape[1]
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_attention_heads
											SCREAMING_SNAKE_CASE__								=					(
											    batch,
											    num_encoder_attention_heads,
											    encoder_seq_length,
											    self._config.hidden_size // num_encoder_attention_heads,
											)
											SCREAMING_SNAKE_CASE__								=					decoder_seq_length + 3
											SCREAMING_SNAKE_CASE__								=					(
											    batch,
											    num_decoder_attention_heads,
											    decoder_past_length,
											    self._config.hidden_size // num_decoder_attention_heads,
											)

											SCREAMING_SNAKE_CASE__								=					torch.cat(
											    [common_inputs["""decoder_attention_mask"""], torch.ones(__A							, __A						)]							, dim=1						)

											SCREAMING_SNAKE_CASE__								=					[]
											# If the number of encoder and decoder layers are present in the model configuration, both are considered
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_layers
											SCREAMING_SNAKE_CASE__								=					min(__A							, __A						)
											SCREAMING_SNAKE_CASE__								=					max(__A							, __A						) - min_num_layers
											SCREAMING_SNAKE_CASE__								=					"""encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

											for _ in range(__A						):
													common_inputs["past_key_values"].append(
													    (
													        torch.zeros(__A						),
													        torch.zeros(__A						),
													        torch.zeros(__A						),
													        torch.zeros(__A						),
													    )						)
											# TODO: test this.
											SCREAMING_SNAKE_CASE__								=					encoder_shape if remaining_side_name == """encoder""" else decoder_shape
											for _ in range(__A							, __A						):
													common_inputs["past_key_values"].append((torch.zeros(__A						), torch.zeros(__A						))						)
									return common_inputs


							def    _snake_case     (							self			:Tuple							, __A			:PreTrainedTokenizer							, __A			:int = -1							, __A			:int = -1							, __A			:bool = False							, __A			:Optional[TensorType] = None							, )      ->      Mapping[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    __A							, __A							, __A							, __A							, __A						)

									if self.use_past:
											if not is_torch_available():
													raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""						)
											else:
													import torch
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					common_inputs["""input_ids"""].shape
											# Not using the same length for past_key_values
											SCREAMING_SNAKE_CASE__								=					seqlen + 2
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_layers
											SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.num_attention_heads
											SCREAMING_SNAKE_CASE__								=					(
											    batch,
											    num_encoder_attention_heads,
											    past_key_values_length,
											    self._config.hidden_size // num_encoder_attention_heads,
											)

											SCREAMING_SNAKE_CASE__								=					common_inputs["""attention_mask"""].dtype
											SCREAMING_SNAKE_CASE__								=					torch.cat(
											    [common_inputs["""attention_mask"""], torch.ones(__A							, __A							, dtype=__A						)]							, dim=1						)
											SCREAMING_SNAKE_CASE__								=					[
											    (torch.zeros(__A						), torch.zeros(__A						)) for _ in range(__A						)
											]
									return common_inputs


							def    _snake_case     (							self			:Any							, __A			:PreTrainedTokenizer							, __A			:int = -1							, __A			:int = -1							, __A			:bool = False							, __A			:Optional[TensorType] = None							, )      ->      Mapping[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					compute_effective_axis_dimension(
									    __A							, fixed_dimension=OnnxConfig.default_fixed_batch							, num_token_to_add=0						)

									# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
									SCREAMING_SNAKE_CASE__								=					tokenizer.num_special_tokens_to_add(__A						)
									SCREAMING_SNAKE_CASE__								=					compute_effective_axis_dimension(
									    __A							, fixed_dimension=OnnxConfig.default_fixed_sequence							, num_token_to_add=__A						)

									# Generate dummy inputs according to compute batch and sequence
									SCREAMING_SNAKE_CASE__								=					[""" """.join([tokenizer.unk_token]						) * seq_length] * batch_size
									SCREAMING_SNAKE_CASE__								=					dict(tokenizer(__A							, return_tensors=__A						)						)
									return common_inputs


							def    _snake_case     (							self			:Optional[int]							, __A			:PreTrainedTokenizer							, __A			:int = -1							, __A			:int = -1							, __A			:bool = False							, __A			:Optional[TensorType] = None							, )      ->      Mapping[str, Any]:



									"""simple docstring"""



									if self.task in ["default", "seq2seq-lm"]:
											SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_default_and_seqaseq_lm(
											    __A							, batch_size=__A							, seq_length=__A							, is_pair=__A							, framework=__A						)

									elif self.task == "causal-lm":
											SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_causal_lm(
											    __A							, batch_size=__A							, seq_length=__A							, is_pair=__A							, framework=__A						)
									else:
											SCREAMING_SNAKE_CASE__								=					self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
											    __A							, batch_size=__A							, seq_length=__A							, is_pair=__A							, framework=__A						)

									return common_inputs


							def    _snake_case     (							self			:List[str]							, __A			:Tuple							, __A			:Optional[int]							, __A			:int							, __A			:List[Any]						)      ->      Dict:



									"""simple docstring"""



									if self.task in ["default", "seq2seq-lm"]:
											SCREAMING_SNAKE_CASE__								=					super()._flatten_past_key_values_(__A							, __A							, __A							, __A						)
									else:
											SCREAMING_SNAKE_CASE__								=					super(__A							, self						)._flatten_past_key_values_(
											    __A							, __A							, __A							, __A						)






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


							def __init__(							self			:Optional[Any]							, __A			:Union[str, Any]							, __A			:int=13							, __A			:Dict=7							, __A			:Tuple=True							, __A			:Optional[Any]=False							, __A			:Optional[int]=99							, __A			:int=16							, __A			:Optional[Any]=2							, __A			:List[Any]=4							, __A			:List[Any]=4							, __A			:Optional[Any]="gelu"							, __A			:List[str]=0.1							, __A			:List[Any]=0.1							, __A			:str=32							, __A			:Dict=2							, __A			:Optional[Any]=1							, __A			:List[Any]=0							, __A			:List[str]=0.0_2							, )      ->      Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					parent
									SCREAMING_SNAKE_CASE__								=					batch_size
									SCREAMING_SNAKE_CASE__								=					seq_length
									SCREAMING_SNAKE_CASE__								=					is_training
									SCREAMING_SNAKE_CASE__								=					use_labels
									SCREAMING_SNAKE_CASE__								=					vocab_size
									SCREAMING_SNAKE_CASE__								=					hidden_size
									SCREAMING_SNAKE_CASE__								=					num_hidden_layers
									SCREAMING_SNAKE_CASE__								=					num_attention_heads
									SCREAMING_SNAKE_CASE__								=					intermediate_size
									SCREAMING_SNAKE_CASE__								=					hidden_act
									SCREAMING_SNAKE_CASE__								=					hidden_dropout_prob
									SCREAMING_SNAKE_CASE__								=					attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE__								=					max_position_embeddings
									SCREAMING_SNAKE_CASE__								=					eos_token_id
									SCREAMING_SNAKE_CASE__								=					pad_token_id
									SCREAMING_SNAKE_CASE__								=					bos_token_id
									SCREAMING_SNAKE_CASE__								=					initializer_range


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



									"""simple docstring"""



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

									SCREAMING_SNAKE_CASE__								=					shift_tokens_right(__A							, 1							, 2						)

									SCREAMING_SNAKE_CASE__								=					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=__A							, )
									SCREAMING_SNAKE_CASE__								=					prepare_marian_inputs_dict(__A							, __A							, __A						)
									return config, inputs_dict


							def    _snake_case     (							self			:List[Any]						)      ->      Union[str, Any]:



									"""simple docstring"""



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


							def    _snake_case     (							self			:Any							, __A			:Any							, __A			:List[Any]							, __A			:Optional[int]						)      ->      Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					20
									SCREAMING_SNAKE_CASE__								=					model_class_name(__A						)

									SCREAMING_SNAKE_CASE__								=					model.encode(inputs_dict["""input_ids"""]						)

									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					(
									    inputs_dict["""decoder_input_ids"""],
									    inputs_dict["""decoder_attention_mask"""],
									)

									SCREAMING_SNAKE_CASE__								=					model.init_cache(decoder_input_ids.shape[0]							, __A							, __A						)
									SCREAMING_SNAKE_CASE__								=					jnp.ones((decoder_input_ids.shape[0], max_decoder_length)							, dtype="""i4"""						)

									SCREAMING_SNAKE_CASE__								=					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__								=					model.decode(
									    decoder_input_ids[:, :-1]							, __A							, decoder_attention_mask=__A							, past_key_values=__A							, decoder_position_ids=__A							, )

									SCREAMING_SNAKE_CASE__								=					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]							, dtype="""i4"""						)
									SCREAMING_SNAKE_CASE__								=					model.decode(
									    decoder_input_ids[:, -1:]							, __A							, decoder_attention_mask=__A							, past_key_values=outputs_cache.past_key_values							, decoder_position_ids=__A							, )

									SCREAMING_SNAKE_CASE__								=					model.decode(__A							, __A						)

									SCREAMING_SNAKE_CASE__								=					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    _snake_case     (							self			:Optional[int]							, __A			:Optional[int]							, __A			:List[str]							, __A			:int						)      ->      str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					20
									SCREAMING_SNAKE_CASE__								=					model_class_name(__A						)

									SCREAMING_SNAKE_CASE__								=					model.encode(inputs_dict["""input_ids"""]						)

									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					(
									    inputs_dict["""decoder_input_ids"""],
									    inputs_dict["""decoder_attention_mask"""],
									)

									SCREAMING_SNAKE_CASE__								=					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__								=					model.init_cache(decoder_input_ids.shape[0]							, __A							, __A						)
									SCREAMING_SNAKE_CASE__								=					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__								=					model.decode(
									    decoder_input_ids[:, :-1]							, __A							, decoder_attention_mask=__A							, past_key_values=__A							, decoder_position_ids=__A							, )
									SCREAMING_SNAKE_CASE__								=					jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]							, dtype="""i4"""						)
									SCREAMING_SNAKE_CASE__								=					model.decode(
									    decoder_input_ids[:, -1:]							, __A							, past_key_values=outputs_cache.past_key_values							, decoder_attention_mask=__A							, decoder_position_ids=__A							, )

									SCREAMING_SNAKE_CASE__								=					model.decode(__A							, __A							, decoder_attention_mask=__A						)

									SCREAMING_SNAKE_CASE__								=					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      UpperCamelCase_				(   UpperCamelCase__ ,     unittest.TestCase ,     UpperCamelCase__			):
							lowerCamelCase_							=    True
							lowerCamelCase_							=    (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
							lowerCamelCase_							=    (FlaxMarianMTModel,) if is_flax_available() else ()


							def    _snake_case     (							self			:Any						)      ->      str:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					FlaxMarianModelTester(self						)


							def    _snake_case     (							self			:Any						)      ->      Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
											self.model_tester.check_use_cache_forward(__A							, __A							, __A						)


							def    _snake_case     (							self			:Union[str, Any]						)      ->      List[Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					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(__A							, __A							, __A						)


							def    _snake_case     (							self			:List[Any]						)      ->      Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					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__								=					self._prepare_for_class(__A							, __A						)
													SCREAMING_SNAKE_CASE__								=					model_class(__A						)

													@jax.jit
													def encode_jitted(__A			:List[str]							, __A			:List[str]=None							, **__A			:Tuple						):
															return model.encode(input_ids=__A							, attention_mask=__A						)

													with self.subTest("""JIT Enabled"""						):
															SCREAMING_SNAKE_CASE__								=					encode_jitted(**__A						).to_tuple()

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

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


							def    _snake_case     (							self			:Tuple						)      ->      Optional[int]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__		,  SCREAMING_SNAKE_CASE__								=					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__								=					model_class(__A						)
													SCREAMING_SNAKE_CASE__								=					model.encode(inputs_dict["""input_ids"""]							, inputs_dict["""attention_mask"""]						)

													SCREAMING_SNAKE_CASE__								=					{
													    """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(__A			:Union[str, Any]							, __A			:Optional[Any]							, __A			:List[Any]						):
															return model.decode(
															    decoder_input_ids=__A							, decoder_attention_mask=__A							, encoder_outputs=__A							, )

													with self.subTest("""JIT Enabled"""						):
															SCREAMING_SNAKE_CASE__								=					decode_jitted(**__A						).to_tuple()

													with self.subTest("""JIT Disabled"""						):
															with jax.disable_jit():
																	SCREAMING_SNAKE_CASE__								=					decode_jitted(**__A						).to_tuple()

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


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



									"""simple docstring"""



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




@require_flax
@require_sentencepiece
@require_tokenizers
class      UpperCamelCase_				(   unittest.TestCase			):
							lowerCamelCase_							=    None
							lowerCamelCase_							=    None


							@classmethod
							def    _snake_case     (							cls			:int						)      ->      None:



									"""simple docstring"""



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


							@cached_property
							def    _snake_case     (							self			:Any						)      ->      int:



									"""simple docstring"""



									return MarianTokenizer.from_pretrained(self.model_name						)


							@property
							def    _snake_case     (							self			:Optional[int]						)      ->      int:



									"""simple docstring"""



									return self.tokenizer.eos_token_id


							@cached_property
							def    _snake_case     (							self			:Optional[int]						)      ->      str:



									"""simple docstring"""



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


							def    _snake_case     (							self			:Optional[int]							, **__A			:int						)      ->      Any:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.translate_src_text(**__A						)
									self.assertListEqual(self.expected_text							, __A						)


							def    _snake_case     (							self			:Union[str, Any]							, **__A			:List[Any]						)      ->      Tuple:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__								=					self.tokenizer(self.src_text							, padding=__A							, return_tensors="""np"""							, **__A						)
									SCREAMING_SNAKE_CASE__								=					self.model.generate(
									    model_inputs.input_ids							, attention_mask=model_inputs.attention_mask							, num_beams=2							, max_length=128							, ).sequences
									SCREAMING_SNAKE_CASE__								=					self.tokenizer.batch_decode(__A							, skip_special_tokens=__A						)
									return generated_words




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


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



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




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


							@slow
							def    _snake_case     (							self			:Any						)      ->      Tuple:



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




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


							@slow
							def    _snake_case     (							self			:List[str]						)      ->      int:



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    "en"
							lowerCamelCase_							=    "de"
							lowerCamelCase_							=    [
							    "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.",
							]
							lowerCamelCase_							=    [
							    "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    _snake_case     (							self			:List[Any]						)      ->      List[str]:



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    "en"
							lowerCamelCase_							=    "zh"
							lowerCamelCase_							=    ["My name is Wolfgang and I live in Berlin"]
							lowerCamelCase_							=    ["我叫沃尔夫冈 我住在柏林"]


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



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    "ru"
							lowerCamelCase_							=    "fr"
							lowerCamelCase_							=    ["Он показал мне рукопись своей новой пьесы."]
							lowerCamelCase_							=    ["Il m'a montré le manuscrit de sa nouvelle pièce."]


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



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class      UpperCamelCase_				(   UpperCamelCase__			):
							lowerCamelCase_							=    "en"
							lowerCamelCase_							=    "ROMANCE"
							lowerCamelCase_							=    [
							    ">>fr<< Don't spend so much time watching TV.",
							    ">>pt<< Your message has been sent.",
							    ">>es<< He's two years older than me.",
							]
							lowerCamelCase_							=    [
							    "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    _snake_case     (							self			:str						)      ->      int:



									"""simple docstring"""



									self._assert_generated_batch_equal_expected()