





'''simple docstring'''



import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
			import os

			# The slow tests are often failing with OOM error on GPU
			# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
			# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
			snake_case_   :  Tuple								=      '''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__(		_UpperCamelCase  : Dict ,   _UpperCamelCase  : Dict ,   _UpperCamelCase  : List[Any]=None ,   _UpperCamelCase  : Optional[int]=None ,   _UpperCamelCase  : List[Any]=None ,   _UpperCamelCase  : Dict=None ,   _UpperCamelCase  : Any=None ,   _UpperCamelCase  : Any=None ,   )->   Optional[Any]:






					"""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_ :

			'''simple docstring'''





			def __init__(					self			,     A_			,     A_=13			,     A_=7			,     A_=True			,     A_=False			,     A_=99			,     A_=16			,     A_=2			,     A_=4			,     A_=4			,     A_="gelu"			,     A_=0.1			,     A_=0.1			,     A_=32			,     A_=2			,     A_=1			,     A_=0			,     A_=0.02			,     ):
								_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   ):
								_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(A_			,     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=A_			,     )
								_UpperCamelCase											=   prepare_marian_inputs_dict(A_			,     A_			,     A_   )
								return config, inputs_dict




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   self.prepare_config_and_inputs()
								return config, inputs_dict




			def       a	(					self			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   20
								_UpperCamelCase											=   model_class_name(A_   )

								_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]			,     A_			,     A_   )
								_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]			,     A_			,     decoder_attention_mask=A_			,     past_key_values=A_			,     decoder_position_ids=A_			,     )

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

								_UpperCamelCase											=   model.decode(A_			,     A_   )

								_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			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   20
								_UpperCamelCase											=   model_class_name(A_   )

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

								_UpperCamelCase											=   model.decode(A_			,     A_			,     decoder_attention_mask=A_   )

								_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_ (  lowerCAmelCase_    ,			unittest.TestCase    ,			lowerCAmelCase_  ):

			'''simple docstring'''





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




			def       a	(					self   ):
								_UpperCamelCase											=   FlaxMarianModelTester(self   )




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   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       a	(					self   ):
								_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(A_			,     A_			,     A_   )




			def       a	(					self   ):
								_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(A_			,     A_   )
																		_UpperCamelCase											=   model_class(A_   )

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

																		with self.subTest("JIT Enabled"   ):
																							_UpperCamelCase											=   encode_jitted(**A_   ).to_tuple()

																		with self.subTest("JIT Disabled"   ):
																							with jax.disable_jit():
																												_UpperCamelCase											=   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       a	(					self   ):
								_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(A_   )
																		_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(A_			,     A_			,     A_   ):
																							return model.decode(
																							    decoder_input_ids=A_			,     decoder_attention_mask=A_			,     encoder_outputs=A_			,     )

																		with self.subTest("JIT Enabled"   ):
																							_UpperCamelCase											=   decode_jitted(**A_   ).to_tuple()

																		with self.subTest("JIT Disabled"   ):
																							with jax.disable_jit():
																												_UpperCamelCase											=   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       a	(					self   ):
								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(A_   )
													self.assertIsNotNone(A_   )




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

			'''simple docstring'''





			_lowerCAmelCase						=    None
			_lowerCAmelCase						=    None




			@classmethod
			def       a	(					cls   ):
								_UpperCamelCase											=   F"Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"
								return cls




			@cached_property
			def       a	(					self   ):
								return MarianTokenizer.from_pretrained(self.model_name   )




			@property
			def       a	(					self   ):
								return self.tokenizer.eos_token_id




			@cached_property
			def       a	(					self   ):
								_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			,     **A_   ):
								_UpperCamelCase											=   self.translate_src_text(**A_   )
								self.assertListEqual(self.expected_text			,     A_   )




			def       a	(					self			,     **A_   ):
								_UpperCamelCase											=   self.tokenizer(self.src_text			,     padding=A_			,     return_tensors="np"			,     **A_   )
								_UpperCamelCase											=   self.model.generate(
								    model_inputs.input_ids			,     attention_mask=model_inputs.attention_mask			,     num_beams=2			,     max_length=1_28			,     ).sequences
								_UpperCamelCase											=   self.tokenizer.batch_decode(A_			,     skip_special_tokens=A_   )
								return generated_words




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_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       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_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       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_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       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_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       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





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




			@slow
			def       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





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




			@slow
			def       a	(					self   ):
								self._assert_generated_batch_equal_expected()




@require_flax
@require_sentencepiece
@require_tokenizers
class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_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       a	(					self   ):
								self._assert_generated_batch_equal_expected()










'''simple docstring'''



import collections
import inspect
import unittest

from transformers import DinatConfig
from transformers.testing_utils import require_natten, 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 DinatBackbone, DinatForImageClassification, DinatModel
			from transformers.models.dinat.modeling_dinat import DINAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor

class     A_ :

			'''simple docstring'''





			def __init__(					self			,     A_			,     A_=13			,     A_=64			,     A_=4			,     A_=3			,     A_=16			,     A_=[1, 2, 1]			,     A_=[2, 4, 8]			,     A_=3			,     A_=[[3], [1, 2], [1]]			,     A_=2.0			,     A_=True			,     A_=0.0			,     A_=0.0			,     A_=0.1			,     A_="gelu"			,     A_=True			,     A_=0.02			,     A_=1e-5			,     A_=True			,     A_=None			,     A_=True			,     A_=10			,     A_=["stage1", "stage2"]			,     A_=[1, 2]			,     ):
								_UpperCamelCase											=   parent
								_UpperCamelCase											=   batch_size
								_UpperCamelCase											=   image_size
								_UpperCamelCase											=   patch_size
								_UpperCamelCase											=   num_channels
								_UpperCamelCase											=   embed_dim
								_UpperCamelCase											=   depths
								_UpperCamelCase											=   num_heads
								_UpperCamelCase											=   kernel_size
								_UpperCamelCase											=   dilations
								_UpperCamelCase											=   mlp_ratio
								_UpperCamelCase											=   qkv_bias
								_UpperCamelCase											=   hidden_dropout_prob
								_UpperCamelCase											=   attention_probs_dropout_prob
								_UpperCamelCase											=   drop_path_rate
								_UpperCamelCase											=   hidden_act
								_UpperCamelCase											=   patch_norm
								_UpperCamelCase											=   layer_norm_eps
								_UpperCamelCase											=   initializer_range
								_UpperCamelCase											=   is_training
								_UpperCamelCase											=   scope
								_UpperCamelCase											=   use_labels
								_UpperCamelCase											=   num_labels
								_UpperCamelCase											=   out_features
								_UpperCamelCase											=   out_indices




			def       a	(					self   ):
								_UpperCamelCase											=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

								_UpperCamelCase											=   None
								if self.use_labels:
													_UpperCamelCase											=   ids_tensor([self.batch_size]			,     self.num_labels   )

								_UpperCamelCase											=   self.get_config()

								return config, pixel_values, labels




			def       a	(					self   ):
								return DinatConfig(
								    num_labels=self.num_labels			,     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			,     kernel_size=self.kernel_size			,     dilations=self.dilations			,     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			,     patch_norm=self.patch_norm			,     layer_norm_eps=self.layer_norm_eps			,     initializer_range=self.initializer_range			,     out_features=self.out_features			,     out_indices=self.out_indices			,     )




			def       a	(					self			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   DinatModel(config=A_   )
								model.to(A_   )
								model.eval()
								_UpperCamelCase											=   model(A_   )

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

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




			def       a	(					self			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   DinatForImageClassification(A_   )
								model.to(A_   )
								model.eval()
								_UpperCamelCase											=   model(A_			,     labels=A_   )
								self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)   )

								# test greyscale images
								_UpperCamelCase											=   1
								_UpperCamelCase											=   DinatForImageClassification(A_   )
								model.to(A_   )
								model.eval()

								_UpperCamelCase											=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
								_UpperCamelCase											=   model(A_   )
								self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)   )




			def       a	(					self			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   DinatBackbone(config=A_   )
								model.to(A_   )
								model.eval()
								_UpperCamelCase											=   model(A_   )

								# 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
								_UpperCamelCase											=   None
								_UpperCamelCase											=   DinatBackbone(config=A_   )
								model.to(A_   )
								model.eval()
								_UpperCamelCase											=   model(A_   )

								# 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       a	(					self   ):
								_UpperCamelCase											=   self.prepare_config_and_inputs()
								_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase											=   config_and_inputs
								_UpperCamelCase											=   {"pixel_values": pixel_values}
								return config, inputs_dict




@require_natten
@require_torch
class     A_ (  lowerCAmelCase_    ,			lowerCAmelCase_    ,			unittest.TestCase  ):

			'''simple docstring'''





			_lowerCAmelCase						=    (
			    (
			        DinatModel,
			        DinatForImageClassification,
			        DinatBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			_lowerCAmelCase						=    (
			    {"""feature-extraction""": DinatModel, """image-classification""": DinatForImageClassification}
			    if is_torch_available()
			    else {}
			)
			_lowerCAmelCase						=    False

			_lowerCAmelCase						=    False
			_lowerCAmelCase						=    False
			_lowerCAmelCase						=    False
			_lowerCAmelCase						=    False




			def       a	(					self   ):
								_UpperCamelCase											=   DinatModelTester(self   )
								_UpperCamelCase											=   ConfigTester(self			,     config_class=A_			,     embed_dim=37   )




			def       a	(					self   ):
								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       a	(					self   ):
								return




			def       a	(					self   ):
								_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A_   )




			def       a	(					self   ):
								_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*A_   )




			def       a	(					self   ):
								_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*A_   )




			@unittest.skip(reason="Dinat does not use inputs_embeds"   )
			def       a	(					self   ):
								pass




			@unittest.skip(reason="Dinat does not use feedforward chunking"   )
			def       a	(					self   ):
								pass




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs_for_common()

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




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCamelCase											=   ["pixel_values"]
													self.assertListEqual(arg_names[:1]			,     A_   )




			def       a	(					self   ):
								self.skipTest("Dinat's attention operation is handled entirely by NATTEN."   )




			def       a	(					self			,     A_			,     A_			,     A_			,     A_   ):
								_UpperCamelCase											=   model_class(A_   )
								model.to(A_   )
								model.eval()

								with torch.no_grad():
													_UpperCamelCase											=   model(**self._prepare_for_class(A_			,     A_   )   )

								_UpperCamelCase											=   outputs.hidden_states

								_UpperCamelCase											=   getattr(
								    self.model_tester			,     "expected_num_hidden_layers"			,     len(self.model_tester.depths   ) + 1   )
								self.assertEqual(len(A_   )			,     A_   )

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

								_UpperCamelCase											=   image_size[0] // patch_size[0]
								_UpperCamelCase											=   image_size[1] // patch_size[1]

								self.assertListEqual(
								    list(hidden_states[0].shape[-3:]   )			,     [height, width, self.model_tester.embed_dim]			,     )

								if model_class.__name__ != "DinatBackbone":
													_UpperCamelCase											=   outputs.reshaped_hidden_states
													self.assertEqual(len(A_   )			,     A_   )

													_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase				,	_UpperCamelCase											=   reshaped_hidden_states[0].shape
													_UpperCamelCase											=   (
													    reshaped_hidden_states[0].view(A_			,     A_			,     A_			,     A_   ).permute(0			,     2			,     3			,     1   )
													)
													self.assertListEqual(
													    list(reshaped_hidden_states.shape[-3:]   )			,     [height, width, self.model_tester.embed_dim]			,     )




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs_for_common()

								_UpperCamelCase											=   (
								    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:
													_UpperCamelCase											=   True
													self.check_hidden_states_output(A_			,     A_			,     A_			,     A_   )

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

													self.check_hidden_states_output(A_			,     A_			,     A_			,     A_   )




			@slow
			def       a	(					self   ):
								for model_name in DINAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_UpperCamelCase											=   DinatModel.from_pretrained(A_   )
													self.assertIsNotNone(A_   )




			def       a	(					self   ):
								_UpperCamelCase				,	_UpperCamelCase											=   self.model_tester.prepare_config_and_inputs_for_common()

								_UpperCamelCase											=   _config_zero_init(A_   )
								for model_class in self.all_model_classes:
													_UpperCamelCase											=   model_class(config=A_   )
													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_natten
@require_vision
@require_torch
class     A_ (  unittest.TestCase  ):

			'''simple docstring'''





			@cached_property
			def       a	(					self   ):
								return AutoImageProcessor.from_pretrained("shi-labs/dinat-mini-in1k-224"   ) if is_vision_available() else None




			@slow
			def       a	(					self   ):
								_UpperCamelCase											=   DinatForImageClassification.from_pretrained("shi-labs/dinat-mini-in1k-224"   ).to(A_   )
								_UpperCamelCase											=   self.default_image_processor

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

								# forward pass
								with torch.no_grad():
													_UpperCamelCase											=   model(**A_   )

								# verify the logits
								_UpperCamelCase											=   torch.Size((1, 10_00)   )
								self.assertEqual(outputs.logits.shape			,     A_   )
								_UpperCamelCase											=   torch.tensor([-0.1545, -0.7667, 0.4642]   ).to(A_   )
								self.assertTrue(torch.allclose(outputs.logits[0, :3]			,     A_			,     atol=1e-4   )   )




@require_torch
@require_natten
class     A_ (  unittest.TestCase    ,			lowerCAmelCase_  ):

			'''simple docstring'''





			_lowerCAmelCase						=    (DinatBackbone,) if is_torch_available() else ()
			_lowerCAmelCase						=    DinatConfig




			def       a	(					self   ):
								_UpperCamelCase											=   DinatModelTester(self   )



