




'''simple docstring'''
import collections
import inspect
import unittest

from transformers import SwinConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel
  from transformers.models.swin.modeling_swin import SWIN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class        SCREAMING_SNAKE_CASE:

       def __init__(    self					,		lowerCamelCase__					,		lowerCamelCase__=13					,		lowerCamelCase__=32					,		lowerCamelCase__=2					,		lowerCamelCase__=3					,		lowerCamelCase__=16					,		lowerCamelCase__=[1, 2, 1]					,		lowerCamelCase__=[2, 2, 4]					,		lowerCamelCase__=2					,		lowerCamelCase__=2.0					,		lowerCamelCase__=True					,		lowerCamelCase__=0.0					,		lowerCamelCase__=0.0					,		lowerCamelCase__=0.1					,		lowerCamelCase__="gelu"					,		lowerCamelCase__=False					,		lowerCamelCase__=True					,		lowerCamelCase__=0.02					,		lowerCamelCase__=1E-5					,		lowerCamelCase__=True					,		lowerCamelCase__=None					,		lowerCamelCase__=True					,		lowerCamelCase__=10					,		lowerCamelCase__=8					,		lowerCamelCase__=["stage1", "stage2"]					,		lowerCamelCase__=[1, 2]					,		)    ->					Tuple:

           """simple docstring"""



           __lowercase							=						parent
           __lowercase							=						batch_size
           __lowercase							=						image_size
           __lowercase							=						patch_size
           __lowercase							=						num_channels
           __lowercase							=						embed_dim
           __lowercase							=						depths
           __lowercase							=						num_heads
           __lowercase							=						window_size
           __lowercase							=						mlp_ratio
           __lowercase							=						qkv_bias
           __lowercase							=						hidden_dropout_prob
           __lowercase							=						attention_probs_dropout_prob
           __lowercase							=						drop_path_rate
           __lowercase							=						hidden_act
           __lowercase							=						use_absolute_embeddings
           __lowercase							=						patch_norm
           __lowercase							=						layer_norm_eps
           __lowercase							=						initializer_range
           __lowercase							=						is_training
           __lowercase							=						scope
           __lowercase							=						use_labels
           __lowercase							=						type_sequence_label_size
           __lowercase							=						encoder_stride
           __lowercase							=						out_features
           __lowercase							=						out_indices

       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           __lowercase							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

           __lowercase							=						None
           if self.use_labels:
               __lowercase							=						ids_tensor([self.batch_size]					,		self.type_sequence_label_size     )

           __lowercase							=						self.get_config()

           return config, pixel_values, labels

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

           """simple docstring"""



           return SwinConfig(
               image_size=self.image_size					,		patch_size=self.patch_size					,		num_channels=self.num_channels					,		embed_dim=self.embed_dim					,		depths=self.depths					,		num_heads=self.num_heads					,		window_size=self.window_size					,		mlp_ratio=self.mlp_ratio					,		qkv_bias=self.qkv_bias					,		hidden_dropout_prob=self.hidden_dropout_prob					,		attention_probs_dropout_prob=self.attention_probs_dropout_prob					,		drop_path_rate=self.drop_path_rate					,		hidden_act=self.hidden_act					,		use_absolute_embeddings=self.use_absolute_embeddings					,		path_norm=self.patch_norm					,		layer_norm_eps=self.layer_norm_eps					,		initializer_range=self.initializer_range					,		encoder_stride=self.encoder_stride					,		out_features=self.out_features					,		out_indices=self.out_indices					,		)

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Dict:

           """simple docstring"""



           __lowercase							=						SwinModel(config=_lowercase     )
           model.to(_lowercase     )
           model.eval()
           __lowercase							=						model(_lowercase     )

           __lowercase							=						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths     ) - 1))
           __lowercase							=						int(config.embed_dim * 2 ** (len(config.depths     ) - 1)     )

           self.parent.assertEqual(result.last_hidden_state.shape					,		(self.batch_size, expected_seq_len, expected_dim)     )

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						SwinBackbone(config=_lowercase     )
           model.to(_lowercase     )
           model.eval()
           __lowercase							=						model(_lowercase     )

           # verify hidden states
           self.parent.assertEqual(len(result.feature_maps     )					,		len(config.out_features     )     )
           self.parent.assertListEqual(list(result.feature_maps[0].shape     )					,		[self.batch_size, model.channels[0], 16, 16]     )

           # verify channels
           self.parent.assertEqual(len(model.channels     )					,		len(config.out_features     )     )

           # verify backbone works with out_features=None
           __lowercase							=						None
           __lowercase							=						SwinBackbone(config=_lowercase     )
           model.to(_lowercase     )
           model.eval()
           __lowercase							=						model(_lowercase     )

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps     )					,		1     )
           self.parent.assertListEqual(list(result.feature_maps[0].shape     )					,		[self.batch_size, model.channels[-1], 4, 4]     )

           # verify channels
           self.parent.assertEqual(len(model.channels     )					,		1     )

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					List[str]:

           """simple docstring"""



           __lowercase							=						SwinForMaskedImageModeling(config=_lowercase     )
           model.to(_lowercase     )
           model.eval()
           __lowercase							=						model(_lowercase     )
           self.parent.assertEqual(
               result.logits.shape					,		(self.batch_size, self.num_channels, self.image_size, self.image_size)     )

           # test greyscale images
           __lowercase							=						1
           __lowercase							=						SwinForMaskedImageModeling(_lowercase     )
           model.to(_lowercase     )
           model.eval()

           __lowercase							=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
           __lowercase							=						model(_lowercase     )
           self.parent.assertEqual(result.logits.shape					,		(self.batch_size, 1, self.image_size, self.image_size)     )

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					Optional[Any]:

           """simple docstring"""



           __lowercase							=						self.type_sequence_label_size
           __lowercase							=						SwinForImageClassification(_lowercase     )
           model.to(_lowercase     )
           model.eval()
           __lowercase							=						model(_lowercase					,		labels=_lowercase     )
           self.parent.assertEqual(result.logits.shape					,		(self.batch_size, self.type_sequence_label_size)     )

           # test greyscale images
           __lowercase							=						1
           __lowercase							=						SwinForImageClassification(_lowercase     )
           model.to(_lowercase     )
           model.eval()

           __lowercase							=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
           __lowercase							=						model(_lowercase     )
           self.parent.assertEqual(result.logits.shape					,		(self.batch_size, self.type_sequence_label_size)     )




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

           """simple docstring"""



           __lowercase							=						self.prepare_config_and_inputs()
           (
               (
               __lowercase      
           )				,(
               __lowercase      
           )				,(
               __lowercase      
           )				,      
           )							=						config_and_inputs
           __lowercase							=						{"""pixel_values""": pixel_values}
           return config, inputs_dict






@require_torch
class        SCREAMING_SNAKE_CASE(				_snake_case   ,      _snake_case   ,      unittest.TestCase     ):
       snake_case_ :     Tuple    =					(
           (
               SwinModel,
               SwinBackbone,
               SwinForImageClassification,
               SwinForMaskedImageModeling,
           )
           if is_torch_available()
           else ()
       )
       snake_case_ :     Any    =					(
           {"feature-extraction": SwinModel, "image-classification": SwinForImageClassification}
           if is_torch_available()
           else {}
       )
       snake_case_ :     str    =					True

       snake_case_ :     List[str]    =					False
       snake_case_ :     List[Any]    =					False
       snake_case_ :     Dict    =					False

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase							=						SwinModelTester(self     )
           __lowercase							=						ConfigTester(self					,		config_class=_lowercase					,		embed_dim=37     )

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           self.create_and_test_config_common_properties()
           self.config_tester.create_and_test_config_to_json_string()
           self.config_tester.create_and_test_config_to_json_file()
           self.config_tester.create_and_test_config_from_and_save_pretrained()
           self.config_tester.create_and_test_config_with_num_labels()
           self.config_tester.check_config_can_be_init_without_params()
           self.config_tester.check_config_arguments_init()

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           return

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_lowercase     )

       @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""     )
       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           pass

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           super().test_training_gradient_checkpointing()

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

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*_lowercase     )

       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase     )

       def     snake_case__			(    self     )    ->					Tuple:

           """simple docstring"""



           __lowercase							=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_lowercase     )

       @unittest.skip(reason="""Swin does not use inputs_embeds"""     )
       def     snake_case__			(    self     )    ->					Optional[int]:

           """simple docstring"""



           pass

       @unittest.skip(reason="""Swin Transformer does not use feedforward chunking"""     )
       def     snake_case__			(    self     )    ->					Optional[Any]:

           """simple docstring"""



           pass

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

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __lowercase							=						model_class(_lowercase     )
               self.assertIsInstance(model.get_input_embeddings()					,		(nn.Module)     )
               __lowercase							=						model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(_lowercase					,		nn.Linear     )     )

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

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               __lowercase							=						model_class(_lowercase     )
               __lowercase							=						inspect.signature(model.forward     )
               # signature.parameters is an OrderedDict => so arg_names order is deterministic
               __lowercase							=						[*signature.parameters.keys()]

               __lowercase							=						["""pixel_values"""]
               self.assertListEqual(arg_names[:1]					,		_lowercase     )

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

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
           __lowercase							=						True

           for model_class in self.all_model_classes:
               __lowercase							=						True
               __lowercase							=						False
               __lowercase							=						True
               __lowercase							=						model_class(_lowercase     )
               model.to(_lowercase     )
               model.eval()
               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(_lowercase					,		_lowercase     )     )
               __lowercase							=						outputs.attentions
               __lowercase							=						len(self.model_tester.depths     )
               self.assertEqual(len(_lowercase     )					,		_lowercase     )

               # check that output_attentions also work using config
               del inputs_dict["output_attentions"]
               __lowercase							=						True
               __lowercase							=						config.window_size**2
               __lowercase							=						model_class(_lowercase     )
               model.to(_lowercase     )
               model.eval()
               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(_lowercase					,		_lowercase     )     )
               __lowercase							=						outputs.attentions
               self.assertEqual(len(_lowercase     )					,		_lowercase     )

               self.assertListEqual(
                   list(attentions[0].shape[-3:]     )					,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,		)
               __lowercase							=						len(_lowercase     )

               # Check attention is always last and order is fine
               __lowercase							=						True
               __lowercase							=						True
               __lowercase							=						model_class(_lowercase     )
               model.to(_lowercase     )
               model.eval()
               with torch.no_grad():
                   __lowercase							=						model(**self._prepare_for_class(_lowercase					,		_lowercase     )     )

               # also another +1 for reshaped_hidden_states
               __lowercase							=						1 if model_class.__name__ == """SwinBackbone""" else 2
               self.assertEqual(out_len + added_hidden_states					,		len(_lowercase     )     )

               __lowercase							=						outputs.attentions

               self.assertEqual(len(_lowercase     )					,		_lowercase     )

               self.assertListEqual(
                   list(self_attentions[0].shape[-3:]     )					,		[self.model_tester.num_heads[0], window_size_squared, window_size_squared]					,		)

       def     snake_case__			(    self					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__					,		lowerCamelCase__     )    ->					str:

           """simple docstring"""



           __lowercase							=						model_class(_lowercase     )
           model.to(_lowercase     )
           model.eval()

           with torch.no_grad():
               __lowercase							=						model(**self._prepare_for_class(_lowercase					,		_lowercase     )     )

           __lowercase							=						outputs.hidden_states

           __lowercase							=						getattr(
               self.model_tester					,		"""expected_num_hidden_layers"""					,		len(self.model_tester.depths     ) + 1     )
           self.assertEqual(len(_lowercase     )					,		_lowercase     )

           # Swin has a different seq_length
           __lowercase							=						(
               config.patch_size
               if isinstance(config.patch_size					,		collections.abc.Iterable     )
               else (config.patch_size, config.patch_size)
           )

           __lowercase							=						(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

           self.assertListEqual(
               list(hidden_states[0].shape[-2:]     )					,		[num_patches, self.model_tester.embed_dim]					,		)

           if not model_class.__name__ == "SwinBackbone":
               __lowercase							=						outputs.reshaped_hidden_states
               self.assertEqual(len(_lowercase     )					,		_lowercase     )

               __lowercase				,__lowercase				,__lowercase				,__lowercase							=						reshaped_hidden_states[0].shape
               __lowercase							=						(
                   reshaped_hidden_states[0].view(_lowercase					,		_lowercase					,		height * width     ).permute(0					,		2					,		1     )
               )
               self.assertListEqual(
                   list(reshaped_hidden_states.shape[-2:]     )					,		[num_patches, self.model_tester.embed_dim]					,		)

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

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           __lowercase							=						(
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size					,		collections.abc.Iterable     )
               else (self.model_tester.image_size, self.model_tester.image_size)
           )

           for model_class in self.all_model_classes:
               __lowercase							=						True
               self.check_hidden_states_output(_lowercase					,		_lowercase					,		_lowercase					,		_lowercase     )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __lowercase							=						True

               self.check_hidden_states_output(_lowercase					,		_lowercase					,		_lowercase					,		_lowercase     )

       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()
           __lowercase							=						3

           __lowercase							=						(
               self.model_tester.image_size
               if isinstance(self.model_tester.image_size					,		collections.abc.Iterable     )
               else (self.model_tester.image_size, self.model_tester.image_size)
           )
           __lowercase							=						(
               config.patch_size
               if isinstance(config.patch_size					,		collections.abc.Iterable     )
               else (config.patch_size, config.patch_size)
           )

           __lowercase							=						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
           __lowercase							=						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

           for model_class in self.all_model_classes:
               __lowercase							=						True
               self.check_hidden_states_output(_lowercase					,		_lowercase					,		_lowercase					,		(padded_height, padded_width)     )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               __lowercase							=						True
               self.check_hidden_states_output(_lowercase					,		_lowercase					,		_lowercase					,		(padded_height, padded_width)     )

       @slow
       def     snake_case__			(    self     )    ->					int:

           """simple docstring"""



           for model_name in SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __lowercase							=						SwinModel.from_pretrained(_lowercase     )
               self.assertIsNotNone(_lowercase     )




       def     snake_case__			(    self     )    ->					Any:

           """simple docstring"""



           __lowercase				,__lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

           __lowercase							=						_config_zero_init(_lowercase     )
           for model_class in self.all_model_classes:
               __lowercase							=						model_class(config=_lowercase     )
               for name, param in model.named_parameters():
                   if "embeddings" not in name and param.requires_grad:
                       self.assertIn(
                           ((param.data.mean() * 1E9).round() / 1E9).item()					,		[0.0, 1.0]					,		msg=F'Parameter {name} of model {model_class} seems not properly initialized'					,		)






@require_vision
@require_torch
class        SCREAMING_SNAKE_CASE(				unittest.TestCase     ):

       @cached_property
       def     snake_case__			(    self     )    ->					Union[str, Any]:

           """simple docstring"""



           return (
               AutoImageProcessor.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""     )
               if is_vision_available()
               else None
           )




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

           """simple docstring"""



           __lowercase							=						SwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""     ).to(_lowercase     )
           __lowercase							=						self.default_image_processor

           __lowercase							=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
           __lowercase							=						image_processor(images=_lowercase					,		return_tensors="""pt"""     ).to(_lowercase     )

           # forward pass
           with torch.no_grad():
               __lowercase							=						model(**_lowercase     )

           # verify the logits
           __lowercase							=						torch.Size((1, 1000)     )
           self.assertEqual(outputs.logits.shape					,		_lowercase     )
           __lowercase							=						torch.tensor([-0.09_48, -0.64_54, -0.09_21]     ).to(_lowercase     )
           self.assertTrue(torch.allclose(outputs.logits[0, :3]					,		_lowercase					,		atol=1E-4     )     )






@require_torch
class        SCREAMING_SNAKE_CASE(				unittest.TestCase   ,      _snake_case     ):
       snake_case_ :     Union[str, Any]    =					(SwinBackbone,) if is_torch_available() else ()
       snake_case_ :     Tuple    =					SwinConfig

       def     snake_case__			(    self     )    ->					str:

           """simple docstring"""



           __lowercase							=						SwinModelTester(self     )









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
							UpperCamelCase_	       =   "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 				A			(		__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase=None							,					__UpperCAmelCase=None							,					__UpperCAmelCase=None							,					__UpperCAmelCase=None							,					__UpperCAmelCase=None							,					__UpperCAmelCase=None							,					)       ->       Optional[int]:



						'''simple docstring'''






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

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

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

												UpperCAmelCase_     							=     shift_tokens_right(_lowercase   ,						1   ,						2)

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

						def 	__a       (    self	:List[str])		->					Optional[Any]:
												UpperCAmelCase_							,      UpperCAmelCase_     							=     self.prepare_config_and_inputs()
												return config, inputs_dict

						def 	__a       (    self	:Optional[Any]   ,						_lowercase	:Any   ,						_lowercase	:Any   ,						_lowercase	:List[str])		->					List[Any]:
												UpperCAmelCase_     							=     20
												UpperCAmelCase_     							=     model_class_name(_lowercase)

												UpperCAmelCase_     							=     model.encode(inputs_dict['''input_ids'''])

												UpperCAmelCase_							,      UpperCAmelCase_     							=     (
												    inputs_dict['''decoder_input_ids'''],
												    inputs_dict['''decoder_attention_mask'''],
												)

												UpperCAmelCase_     							=     model.init_cache(decoder_input_ids.shape[0]   ,						_lowercase   ,						_lowercase)
												UpperCAmelCase_     							=     jnp.ones((decoder_input_ids.shape[0], max_decoder_length)   ,						dtype='''i4''')

												UpperCAmelCase_     							=     jnp.broadcast_to(
												    jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]   ,						(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)   ,						)
												UpperCAmelCase_     							=     model.decode(
												    decoder_input_ids[:, :-1]   ,						_lowercase   ,						decoder_attention_mask=_lowercase   ,						past_key_values=_lowercase   ,						decoder_position_ids=_lowercase   ,						)

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

												UpperCAmelCase_     							=     model.decode(_lowercase   ,						_lowercase)

												UpperCAmelCase_     							=     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	:str   ,						_lowercase	:Union[str, Any]   ,						_lowercase	:List[Any]   ,						_lowercase	:Dict)		->					List[Any]:
												UpperCAmelCase_     							=     20
												UpperCAmelCase_     							=     model_class_name(_lowercase)

												UpperCAmelCase_     							=     model.encode(inputs_dict['''input_ids'''])

												UpperCAmelCase_							,      UpperCAmelCase_     							=     (
												    inputs_dict['''decoder_input_ids'''],
												    inputs_dict['''decoder_attention_mask'''],
												)

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

												UpperCAmelCase_     							=     model.init_cache(decoder_input_ids.shape[0]   ,						_lowercase   ,						_lowercase)
												UpperCAmelCase_     							=     jnp.broadcast_to(
												    jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :]   ,						(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)   ,						)

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

												UpperCAmelCase_     							=     model.decode(_lowercase   ,						_lowercase   ,						decoder_attention_mask=_lowercase)

												UpperCAmelCase_     							=     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 							a_  (		_snake_case					, unittest.TestCase					, _snake_case				):
						UpperCamelCase__      :						Optional[Any]				       =True
						UpperCamelCase__      :						str				       =(FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
						UpperCamelCase__      :						Any				       =(FlaxMarianMTModel,) if is_flax_available() else ()

						def 	__a       (    self	:List[Any])		->					Tuple:
												UpperCAmelCase_     							=     FlaxMarianModelTester(self)

						def 	__a       (    self	:Tuple)		->					Optional[Any]:
												UpperCAmelCase_							,      UpperCAmelCase_     							=     self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																		self.model_tester.check_use_cache_forward(_lowercase   ,						_lowercase   ,						_lowercase)

						def 	__a       (    self	:Tuple)		->					str:
												UpperCAmelCase_							,      UpperCAmelCase_     							=     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(_lowercase   ,						_lowercase   ,						_lowercase)

						def 	__a       (    self	:Dict)		->					str:
												UpperCAmelCase_							,      UpperCAmelCase_     							=     self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		with self.subTest(model_class.__name__):
																								UpperCAmelCase_     							=     self._prepare_for_class(_lowercase   ,						_lowercase)
																								UpperCAmelCase_     							=     model_class(_lowercase)

																								@jax.jit
																								def encode_jitted(_lowercase	:Optional[Any]   ,						_lowercase	:Optional[Any]=None   ,						**_lowercase	:Any):
																														return model.encode(input_ids=_lowercase   ,						attention_mask=_lowercase)

																								with self.subTest('''JIT Enabled'''):
																														UpperCAmelCase_     							=     encode_jitted(**_lowercase).to_tuple()

																								with self.subTest('''JIT Disabled'''):
																														with jax.disable_jit():
																																				UpperCAmelCase_     							=     encode_jitted(**_lowercase).to_tuple()

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

						def 	__a       (    self	:Optional[int])		->					str:
												UpperCAmelCase_							,      UpperCAmelCase_     							=     self.model_tester.prepare_config_and_inputs_for_common()

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

																								UpperCAmelCase_     							=     {
																								    '''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(_lowercase	:Dict   ,						_lowercase	:Optional[Any]   ,						_lowercase	:int):
																														return model.decode(
																														    decoder_input_ids=_lowercase   ,						decoder_attention_mask=_lowercase   ,						encoder_outputs=_lowercase   ,						)

																								with self.subTest('''JIT Enabled'''):
																														UpperCAmelCase_     							=     decode_jitted(**_lowercase).to_tuple()

																								with self.subTest('''JIT Disabled'''):
																														with jax.disable_jit():
																																				UpperCAmelCase_     							=     decode_jitted(**_lowercase).to_tuple()

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




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







@require_flax
@require_sentencepiece
@require_tokenizers
class 							a_  (		unittest.TestCase				):
						UpperCamelCase__      :						str				       =None
						UpperCamelCase__      :						List[str]				       =None

						@classmethod
						def 	__a       (    cls	:Optional[int])		->					None:
												UpperCAmelCase_     							=     f"Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"
												return cls

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

						@property
						def 	__a       (    self	:Optional[int])		->					int:
												return self.tokenizer.eos_token_id

						@cached_property
						def 	__a       (    self	:Dict)		->					Optional[int]:
												UpperCAmelCase_     							=     FlaxMarianMTModel.from_pretrained(self.model_name)
												self.assertEqual(model.config.decoder_start_token_id   ,						model.config.pad_token_id)
												return model

						def 	__a       (    self	:List[Any]   ,						**_lowercase	:Any)		->					Union[str, Any]:
												UpperCAmelCase_     							=     self.translate_src_text(**_lowercase)
												self.assertListEqual(self.expected_text   ,						_lowercase)




						def 	__a       (    self	:List[str]   ,						**_lowercase	:List[str])		->					Any:
												UpperCAmelCase_     							=     self.tokenizer(self.src_text   ,						padding=_lowercase   ,						return_tensors='''np'''   ,						**_lowercase)
												UpperCAmelCase_     							=     self.model.generate(
												    model_inputs.input_ids   ,						attention_mask=model_inputs.attention_mask   ,						num_beams=2   ,						max_length=128   ,						).sequences
												UpperCAmelCase_     							=     self.tokenizer.batch_decode(_lowercase   ,						skip_special_tokens=_lowercase)
												return generated_words







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

						@slow
						def 	__a       (    self	:List[Any])		->					Dict:
												self._assert_generated_batch_equal_expected()







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

						@slow
						def 	__a       (    self	:Union[str, Any])		->					int:
												self._assert_generated_batch_equal_expected()







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

						@slow
						def 	__a       (    self	:Union[str, Any])		->					Union[str, Any]:
												self._assert_generated_batch_equal_expected()







@require_flax
@require_sentencepiece
@require_tokenizers
class 							a_  (		_snake_case				):
						UpperCamelCase__      :						str				       ="en"
						UpperCamelCase__      :						List[str]				       ="de"
						UpperCamelCase__      :						List[str]				       =[
						    "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__      :						Any				       =[
						    "Ich bin ein kleiner Frosch.",
						    "Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.",
						    "Tom bat seinen Lehrer um Rat.",
						    "So würde ich das machen.",
						    "Tom bewunderte Marias Mut wirklich.",
						    "Drehen Sie sich um und schließen Sie die Augen.",
						]

						@slow
						def 	__a       (    self	:List[Any])		->					Dict:
												self._assert_generated_batch_equal_expected()







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

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







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

						@slow
						def 	__a       (    self	:Optional[Any])		->					Union[str, Any]:
												self._assert_generated_batch_equal_expected()







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





