



'''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 	_lowerCAmelCase     :






		'''simple docstring'''
		def __init__(						self							:       Optional[int]      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       str=13      ,		UpperCamelCase_							:       Union[str, Any]=64      ,		UpperCamelCase_							:       Any=4      ,		UpperCamelCase_							:       str=3      ,		UpperCamelCase_							:       Any=16      ,		UpperCamelCase_							:       str=[1, 2, 1]      ,		UpperCamelCase_							:       Any=[2, 4, 8]      ,		UpperCamelCase_							:       Optional[Any]=3      ,		UpperCamelCase_							:       Dict=[[3], [1, 2], [1]]      ,		UpperCamelCase_							:       List[Any]=2.0      ,		UpperCamelCase_							:       Union[str, Any]=True      ,		UpperCamelCase_							:       Dict=0.0      ,		UpperCamelCase_							:       Tuple=0.0      ,		UpperCamelCase_							:       Tuple=0.1      ,		UpperCamelCase_							:       Dict="gelu"      ,		UpperCamelCase_							:       int=True      ,		UpperCamelCase_							:       List[str]=0.02      ,		UpperCamelCase_							:       List[Any]=1e-5      ,		UpperCamelCase_							:       int=True      ,		UpperCamelCase_							:       Union[str, Any]=None      ,		UpperCamelCase_							:       List[str]=True      ,		UpperCamelCase_							:       int=10      ,		UpperCamelCase_							:       str=["stage1", "stage2"]      ,		UpperCamelCase_							:       List[str]=[1, 2]      ,		)      ->			Optional[int]:







									'''simple docstring'''





									_lowercase							:		int				=   parent
									_lowercase							:		List[Any]				=   batch_size
									_lowercase							:		Optional[int]				=   image_size
									_lowercase							:		Any				=   patch_size
									_lowercase							:		int				=   num_channels
									_lowercase							:		Any				=   embed_dim
									_lowercase							:		Any				=   depths
									_lowercase							:		str				=   num_heads
									_lowercase							:		Optional[Any]				=   kernel_size
									_lowercase							:		Union[str, Any]				=   dilations
									_lowercase							:		Optional[Any]				=   mlp_ratio
									_lowercase							:		Tuple				=   qkv_bias
									_lowercase							:		Optional[int]				=   hidden_dropout_prob
									_lowercase							:		Dict				=   attention_probs_dropout_prob
									_lowercase							:		Dict				=   drop_path_rate
									_lowercase							:		int				=   hidden_act
									_lowercase							:		Optional[int]				=   patch_norm
									_lowercase							:		Any				=   layer_norm_eps
									_lowercase							:		Dict				=   initializer_range
									_lowercase							:		int				=   is_training
									_lowercase							:		Tuple				=   scope
									_lowercase							:		List[Any]				=   use_labels
									_lowercase							:		List[Any]				=   num_labels
									_lowercase							:		Union[str, Any]				=   out_features
									_lowercase							:		Tuple				=   out_indices
		def 						__lowercase      (						self							:       Tuple		)      ->			List[str]:







									'''simple docstring'''





									_lowercase							:		Tuple				=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

									_lowercase							:		Optional[int]				=   None
									if self.use_labels:
																_lowercase							:		Optional[int]				=   ids_tensor([self.batch_size]      ,		self.num_labels		)

									_lowercase							:		str				=   self.get_config()

									return config, pixel_values, labels
		def 						__lowercase      (						self							:       int		)      ->			List[Any]:







									'''simple docstring'''





									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 						__lowercase      (						self							:       int      ,		UpperCamelCase_							:       Dict      ,		UpperCamelCase_							:       Union[str, Any]      ,		UpperCamelCase_							:       Optional[int]		)      ->			List[str]:







									'''simple docstring'''





									_lowercase							:		Dict				=   DinatModel(config=UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()
									_lowercase							:		str				=   model(UpperCAmelCase_		)

									_lowercase							:		Tuple				=   (config.image_size // config.patch_size) // (2 ** (len(config.depths		) - 1))
									_lowercase							:		str				=   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 						__lowercase      (						self							:       Dict      ,		UpperCamelCase_							:       Dict      ,		UpperCamelCase_							:       Optional[int]      ,		UpperCamelCase_							:       List[str]		)      ->			Any:







									'''simple docstring'''





									_lowercase							:		Tuple				=   DinatForImageClassification(UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()
									_lowercase							:		str				=   model(UpperCAmelCase_      ,		labels=UpperCAmelCase_		)
									self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)		)

									# test greyscale images
									_lowercase							:		Dict				=   1
									_lowercase							:		List[Any]				=   DinatForImageClassification(UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()

									_lowercase							:		List[Any]				=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
									_lowercase							:		List[Any]				=   model(UpperCAmelCase_		)
									self.parent.assertEqual(result.logits.shape      ,		(self.batch_size, self.num_labels)		)
		def 						__lowercase      (						self							:       List[str]      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Optional[int]		)      ->			Optional[int]:







									'''simple docstring'''





									_lowercase							:		str				=   DinatBackbone(config=UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()
									_lowercase							:		List[Any]				=   model(UpperCAmelCase_		)

									# 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							:		Optional[int]				=   None
									_lowercase							:		Union[str, Any]				=   DinatBackbone(config=UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()
									_lowercase							:		Any				=   model(UpperCAmelCase_		)

									# 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 						__lowercase      (						self							:       Union[str, Any]		)      ->			Union[str, Any]:







									'''simple docstring'''





									_lowercase							:		str				=   self.prepare_config_and_inputs()
									_lowercase			, _lowercase			, _lowercase							:		Tuple				=   config_and_inputs
									_lowercase							:		Union[str, Any]				=   {'''pixel_values''': pixel_values}
									return config, inputs_dict




@require_natten
@require_torch
class 	_lowerCAmelCase     (    __A     ,		__A     ,		unittest.TestCase       ):






		'''simple docstring'''
		snake_case_							= (
		    (
		        DinatModel,
		        DinatForImageClassification,
		        DinatBackbone,
		    )
		    if is_torch_available()
		    else ()
		)
		snake_case_							= (
		    {'feature-extraction': DinatModel, 'image-classification': DinatForImageClassification}
		    if is_torch_available()
		    else {}
		)
		snake_case_							= False

		snake_case_							= False
		snake_case_							= False
		snake_case_							= False
		snake_case_							= False
		def 						__lowercase      (						self							:       int		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		Optional[Any]				=   DinatModelTester(self		)
									_lowercase							:		List[Any]				=   ConfigTester(self      ,		config_class=UpperCAmelCase_      ,		embed_dim=37		)
		def 						__lowercase      (						self							:       Any		)      ->			Optional[int]:







									'''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 						__lowercase      (						self							:       Optional[Any]		)      ->			Any:







									'''simple docstring'''





									return
		def 						__lowercase      (						self							:       List[Any]		)      ->			Tuple:







									'''simple docstring'''





									_lowercase							:		Tuple				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*UpperCAmelCase_		)
		def 						__lowercase      (						self							:       Union[str, Any]		)      ->			List[Any]:







									'''simple docstring'''





									_lowercase							:		Union[str, Any]				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_		)
		def 						__lowercase      (						self							:       Optional[int]		)      ->			Optional[Any]:







									'''simple docstring'''





									_lowercase							:		Union[str, Any]				=   self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_backbone(*UpperCAmelCase_		)
		@unittest.skip(reason='''Dinat does not use inputs_embeds'''		)
		def 						__lowercase      (						self							:       Optional[int]		)      ->			List[Any]:







									'''simple docstring'''





									pass
		@unittest.skip(reason='''Dinat does not use feedforward chunking'''		)
		def 						__lowercase      (						self							:       Tuple		)      ->			Optional[Any]:







									'''simple docstring'''





									pass
		def 						__lowercase      (						self							:       str		)      ->			Optional[int]:







									'''simple docstring'''





									_lowercase			, _lowercase							:		Optional[int]				=   self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
																_lowercase							:		List[Any]				=   model_class(UpperCAmelCase_		)
																self.assertIsInstance(model.get_input_embeddings()      ,		(nn.Module)		)
																_lowercase							:		Optional[Any]				=   model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(UpperCAmelCase_      ,		nn.Linear		)		)
		def 						__lowercase      (						self							:       Optional[int]		)      ->			str:







									'''simple docstring'''





									_lowercase			, _lowercase							:		Any				=   self.model_tester.prepare_config_and_inputs_for_common()

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

																_lowercase							:		Dict				=   ['''pixel_values''']
																self.assertListEqual(arg_names[:1]      ,		UpperCAmelCase_		)
		def 						__lowercase      (						self							:       str		)      ->			List[Any]:







									'''simple docstring'''





									self.skipTest('''Dinat\'s attention operation is handled entirely by NATTEN.'''		)
		def 						__lowercase      (						self							:       List[Any]      ,		UpperCamelCase_							:       Union[str, Any]      ,		UpperCamelCase_							:       Tuple      ,		UpperCamelCase_							:       Any      ,		UpperCamelCase_							:       Any		)      ->			Union[str, Any]:







									'''simple docstring'''





									_lowercase							:		Optional[Any]				=   model_class(UpperCAmelCase_		)
									model.to(UpperCAmelCase_		)
									model.eval()

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

									_lowercase							:		Dict				=   outputs.hidden_states

									_lowercase							:		str				=   getattr(
									    self.model_tester      ,		'''expected_num_hidden_layers'''      ,		len(self.model_tester.depths		) + 1		)
									self.assertEqual(len(UpperCAmelCase_		)      ,		UpperCAmelCase_		)

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

									_lowercase							:		Dict				=   image_size[0] // patch_size[0]
									_lowercase							:		Any				=   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":
																_lowercase							:		List[Any]				=   outputs.reshaped_hidden_states
																self.assertEqual(len(UpperCAmelCase_		)      ,		UpperCAmelCase_		)

																_lowercase			, _lowercase			, _lowercase			, _lowercase							:		int				=   reshaped_hidden_states[0].shape
																_lowercase							:		str				=   (
																    reshaped_hidden_states[0].view(UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_		).permute(0      ,		2      ,		3      ,		1		)
																)
																self.assertListEqual(
																    list(reshaped_hidden_states.shape[-3:]		)      ,		[height, width, self.model_tester.embed_dim]      ,		)
		def 						__lowercase      (						self							:       int		)      ->			Tuple:







									'''simple docstring'''





									_lowercase			, _lowercase							:		List[str]				=   self.model_tester.prepare_config_and_inputs_for_common()

									_lowercase							:		Any				=   (
									    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							:		List[str]				=   True
																self.check_hidden_states_output(UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_		)

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																_lowercase							:		Dict				=   True

																self.check_hidden_states_output(UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_      ,		UpperCAmelCase_		)
		@slow
		def 						__lowercase      (						self							:       Optional[Any]		)      ->			Optional[int]:







									'''simple docstring'''





									for model_name in DINAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_lowercase							:		Union[str, Any]				=   DinatModel.from_pretrained(UpperCAmelCase_		)
																self.assertIsNotNone(UpperCAmelCase_		)





		def 						__lowercase      (						self							:       Dict		)      ->			int:







									'''simple docstring'''





									_lowercase			, _lowercase							:		Optional[Any]				=   self.model_tester.prepare_config_and_inputs_for_common()

									_lowercase							:		Optional[int]				=   _config_zero_init(UpperCAmelCase_		)
									for model_class in self.all_model_classes:
																_lowercase							:		Optional[Any]				=   model_class(config=UpperCAmelCase_		)
																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 	_lowerCAmelCase     (    unittest.TestCase       ):






		'''simple docstring'''
		@cached_property
		def 						__lowercase      (						self							:       Tuple		)      ->			str:







									'''simple docstring'''





									return AutoImageProcessor.from_pretrained('''shi-labs/dinat-mini-in1k-224'''		) if is_vision_available() else None





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







									'''simple docstring'''





									_lowercase							:		Optional[Any]				=   DinatForImageClassification.from_pretrained('''shi-labs/dinat-mini-in1k-224'''		).to(UpperCAmelCase_		)
									_lowercase							:		Dict				=   self.default_image_processor

									_lowercase							:		str				=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
									_lowercase							:		int				=   image_processor(images=UpperCAmelCase_      ,		return_tensors='''pt'''		).to(UpperCAmelCase_		)

									# forward pass
									with torch.no_grad():
																_lowercase							:		List[str]				=   model(**UpperCAmelCase_		)

									# verify the logits
									_lowercase							:		Any				=   torch.Size((1, 1_000)		)
									self.assertEqual(outputs.logits.shape      ,		UpperCAmelCase_		)
									_lowercase							:		Optional[int]				=   torch.tensor([-0.1_545, -0.7_667, 0.4_642]		).to(UpperCAmelCase_		)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,		UpperCAmelCase_      ,		atol=1e-4		)		)




@require_torch
@require_natten
class 	_lowerCAmelCase     (    unittest.TestCase     ,		__A       ):






		'''simple docstring'''
		snake_case_							= (DinatBackbone,) if is_torch_available() else ()
		snake_case_							= DinatConfig
		def 						__lowercase      (						self							:       Dict		)      ->			str:







									'''simple docstring'''





									_lowercase							:		Dict				=   DinatModelTester(self		)






"""simple docstring"""

from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


a__			:						Dict							=			logging.get_logger(__name__)

a__			:						Any							=			{
    """google/long-t5-local-base""": """https://huggingface.co/google/long-t5-local-base/blob/main/config.json""",
    """google/long-t5-local-large""": """https://huggingface.co/google/long-t5-local-large/blob/main/config.json""",
    """google/long-t5-tglobal-base""": """https://huggingface.co/google/long-t5-tglobal-base/blob/main/config.json""",
    """google/long-t5-tglobal-large""": """https://huggingface.co/google/long-t5-tglobal-large/blob/main/config.json""",
}


class       _snake_case  (    UpperCamelCase							):
						__snake_case			      =  'longt5'
						__snake_case			      =  ['past_key_values']
						__snake_case			      =  {'hidden_size': 'd_model', 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}







						def __init__(self  ,				UpperCAmelCase_=3_2_1_2_8  ,				UpperCAmelCase_=5_1_2  ,				UpperCAmelCase_=6_4  ,				UpperCAmelCase_=2_0_4_8  ,				UpperCAmelCase_=6  ,				UpperCAmelCase_=None  ,				UpperCAmelCase_=8  ,				UpperCAmelCase_=1_2_7  ,				UpperCAmelCase_=1_6  ,				UpperCAmelCase_=3_2  ,				UpperCAmelCase_=1_2_8  ,				UpperCAmelCase_=0.1  ,				UpperCAmelCase_=1e-6  ,				UpperCAmelCase_=1.0  ,				UpperCAmelCase_="relu"  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_="local"  ,				UpperCAmelCase_=True  ,				UpperCAmelCase_=0  ,				UpperCAmelCase_=1  ,				**UpperCAmelCase_  ,				)      ->    int:
											__lowercase        =      vocab_size
											__lowercase        =      d_model
											__lowercase        =      d_kv
											__lowercase        =      d_ff
											__lowercase        =      num_layers
											# default = symmetry
											__lowercase        =      num_decoder_layers if num_decoder_layers is not None else self.num_layers
											__lowercase        =      num_heads
											__lowercase        =      local_radius
											__lowercase        =      global_block_size
											__lowercase        =      relative_attention_num_buckets
											__lowercase        =      relative_attention_max_distance
											__lowercase        =      dropout_rate
											__lowercase        =      layer_norm_epsilon
											__lowercase        =      initializer_factor
											__lowercase        =      feed_forward_proj
											__lowercase        =      encoder_attention_type
											__lowercase        =      use_cache

											__lowercase        =      self.feed_forward_proj.split('''-'''				)
											__lowercase        =      act_info[-1]
											__lowercase        =      act_info[0] == '''gated'''

											if len(UpperCAmelCase_				) > 1 and act_info[0] != "gated" or len(UpperCAmelCase_				) > 2:
																raise ValueError(
																    f'''`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'''
																    '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''
																    '''\'gated-gelu\' or \'relu\''''				)

											# for backwards compatibility
											if feed_forward_proj == "gated-gelu":
																__lowercase        =      '''gelu_new'''

											super().__init__(
											    pad_token_id=UpperCAmelCase_  ,				eos_token_id=UpperCAmelCase_  ,				is_encoder_decoder=UpperCAmelCase_  ,				**UpperCAmelCase_  ,				)



class       _snake_case  (    UpperCamelCase							):







						@property
						def 							_UpperCamelCase     (self				)      ->    Mapping[str, Mapping[int, str]]:
											__lowercase        =      {
											    '''input_ids''': {0: '''batch''', 1: '''encoder_sequence'''},
											    '''attention_mask''': {0: '''batch''', 1: '''encoder_sequence'''},
											}
											if self.use_past:
																__lowercase        =      '''past_encoder_sequence + sequence'''
																__lowercase        =      {0: '''batch'''}
																__lowercase        =      {0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
											else:
																__lowercase        =      {0: '''batch''', 1: '''decoder_sequence'''}
																__lowercase        =      {0: '''batch''', 1: '''decoder_sequence'''}

											if self.use_past:
																self.fill_with_past_key_values_(UpperCAmelCase_  ,				direction='''inputs'''				)

											return common_inputs







						@property
						def 							_UpperCamelCase     (self				)      ->    int:
											return 1_3


