



'''simple docstring'''

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

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


SCREAMING_SNAKE_CASE__     :						List[Any]	=  logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__     :						Any	=  {
    '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json''',
    # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}

class 							a__( snake_case__     ):
			a_	: Union[str, Any]									=      '''blenderbot-small'''
			a_	: Dict									=      ['''past_key_values''']
			a_	: Optional[int]									=      {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}






			def __init__(     self					,   _UpperCAmelCase=5_0265					,   _UpperCAmelCase=512					,   _UpperCAmelCase=8					,   _UpperCAmelCase=2048					,   _UpperCAmelCase=16					,   _UpperCAmelCase=8					,   _UpperCAmelCase=2048					,   _UpperCAmelCase=16					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=True					,   _UpperCAmelCase=True					,   _UpperCAmelCase="gelu"					,   _UpperCAmelCase=512					,   _UpperCAmelCase=0.1					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.02					,   _UpperCAmelCase=1					,   _UpperCAmelCase=False					,   _UpperCAmelCase=0					,   _UpperCAmelCase=1					,   _UpperCAmelCase=2					,   _UpperCAmelCase=2					,   **_UpperCAmelCase					,   )							->							str:
					snake_case__	     =vocab_size
					snake_case__	     =max_position_embeddings
					snake_case__	     =d_model
					snake_case__	     =encoder_ffn_dim
					snake_case__	     =encoder_layers
					snake_case__	     =encoder_attention_heads
					snake_case__	     =decoder_ffn_dim
					snake_case__	     =decoder_layers
					snake_case__	     =decoder_attention_heads
					snake_case__	     =dropout
					snake_case__	     =attention_dropout
					snake_case__	     =activation_dropout
					snake_case__	     =activation_function
					snake_case__	     =init_std
					snake_case__	     =encoder_layerdrop
					snake_case__	     =decoder_layerdrop
					snake_case__	     =use_cache
					snake_case__	     =encoder_layers
					snake_case__	     =scale_embedding  # scale factor will be sqrt(d_model) if True

					super().__init__(
					    pad_token_id=_UpperCAmelCase					,   bos_token_id=_UpperCAmelCase					,   eos_token_id=_UpperCAmelCase					,   is_encoder_decoder=_UpperCAmelCase					,   decoder_start_token_id=_UpperCAmelCase					,   forced_eos_token_id=_UpperCAmelCase					,   **_UpperCAmelCase					,   )





class 							a__( snake_case__     ):






			@property
			def 						_lowercase  (     self						)							->							Mapping[str, Mapping[int, str]]:
					if self.task in ["default", "seq2seq-lm"]:
							snake_case__	     =OrderedDict(
							    [
							        ('input_ids', {0: 'batch', 1: 'encoder_sequence'}),
							        ('attention_mask', {0: 'batch', 1: 'encoder_sequence'}),
							    ]						)

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

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

					return common_inputs






			@property
			def 						_lowercase  (     self						)							->							Mapping[str, Mapping[int, str]]:
					if self.task in ["default", "seq2seq-lm"]:
							snake_case__	     =super().outputs
					else:
							snake_case__	     =super(_UpperCAmelCase					,   self						).outputs
							if self.use_past:
									snake_case__     ,	snake_case__	     =self.num_layers
									for i in range(_UpperCAmelCase						):
											snake_case__	     ={0: 'batch', 2: 'past_sequence + sequence'}
											snake_case__	     ={0: 'batch', 2: 'past_sequence + sequence'}
					return common_outputs






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = False					,   _UpperCAmelCase = None					,   )							->							Mapping[str, Any]:
					snake_case__	     =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
					    _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)

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

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

							snake_case__	     =torch.cat(
							    [common_inputs['decoder_attention_mask'], torch.ones(_UpperCAmelCase					,   _UpperCAmelCase						)]					,   dim=1						)

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

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






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = False					,   _UpperCAmelCase = None					,   )							->							Mapping[str, Any]:
					snake_case__	     =self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
					    _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)

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

							snake_case__	     =common_inputs['attention_mask'].dtype
							snake_case__	     =torch.cat(
							    [common_inputs['attention_mask'], torch.ones(_UpperCAmelCase					,   _UpperCAmelCase					,   dtype=_UpperCAmelCase						)]					,   dim=1						)
							snake_case__	     =[
							    (torch.zeros(_UpperCAmelCase						), torch.zeros(_UpperCAmelCase						)) for _ in range(_UpperCAmelCase						)
							]
					return common_inputs






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = False					,   _UpperCAmelCase = None					,   )							->							Mapping[str, Any]:
					# Copied from OnnxConfig.generate_dummy_inputs
					# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
					# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
					snake_case__	     =compute_effective_axis_dimension(
					    _UpperCAmelCase					,   fixed_dimension=OnnxConfig.default_fixed_batch					,   num_token_to_add=0						)

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

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






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = -1					,   _UpperCAmelCase = False					,   _UpperCAmelCase = None					,   )							->							Mapping[str, Any]:
					if self.task in ["default", "seq2seq-lm"]:
							snake_case__	     =self._generate_dummy_inputs_for_default_and_seqaseq_lm(
							    _UpperCAmelCase					,   batch_size=_UpperCAmelCase					,   seq_length=_UpperCAmelCase					,   is_pair=_UpperCAmelCase					,   framework=_UpperCAmelCase						)

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

					return common_inputs






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Dict:
					if self.task in ["default", "seq2seq-lm"]:
							snake_case__	     =super()._flatten_past_key_values_(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)
					else:
							snake_case__	     =super(_UpperCAmelCase					,   self						)._flatten_past_key_values_(
							    _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)









'''simple docstring'''

import collections
import inspect
import unittest

from transformers import FocalNetConfig
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 (
			    FocalNetBackbone,
			    FocalNetForImageClassification,
			    FocalNetForMaskedImageModeling,
			    FocalNetModel,
			)
			from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor

class 							a__:






			def __init__(     self					,   _UpperCAmelCase					,   _UpperCAmelCase=13					,   _UpperCAmelCase=32					,   _UpperCAmelCase=2					,   _UpperCAmelCase=3					,   _UpperCAmelCase=16					,   _UpperCAmelCase=[32, 64, 128]					,   _UpperCAmelCase=[1, 2, 1]					,   _UpperCAmelCase=[2, 2, 4]					,   _UpperCAmelCase=2					,   _UpperCAmelCase=2.0					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.0					,   _UpperCAmelCase=0.1					,   _UpperCAmelCase="gelu"					,   _UpperCAmelCase=False					,   _UpperCAmelCase=True					,   _UpperCAmelCase=0.02					,   _UpperCAmelCase=1E-5					,   _UpperCAmelCase=True					,   _UpperCAmelCase=None					,   _UpperCAmelCase=True					,   _UpperCAmelCase=10					,   _UpperCAmelCase=8					,   _UpperCAmelCase=["stage1", "stage2"]					,   _UpperCAmelCase=[1, 2]					,   )							->							int:
					snake_case__	     =parent
					snake_case__	     =batch_size
					snake_case__	     =image_size
					snake_case__	     =patch_size
					snake_case__	     =num_channels
					snake_case__	     =embed_dim
					snake_case__	     =hidden_sizes
					snake_case__	     =depths
					snake_case__	     =num_heads
					snake_case__	     =window_size
					snake_case__	     =mlp_ratio
					snake_case__	     =qkv_bias
					snake_case__	     =hidden_dropout_prob
					snake_case__	     =attention_probs_dropout_prob
					snake_case__	     =drop_path_rate
					snake_case__	     =hidden_act
					snake_case__	     =use_absolute_embeddings
					snake_case__	     =patch_norm
					snake_case__	     =layer_norm_eps
					snake_case__	     =initializer_range
					snake_case__	     =is_training
					snake_case__	     =scope
					snake_case__	     =use_labels
					snake_case__	     =type_sequence_label_size
					snake_case__	     =encoder_stride
					snake_case__	     =out_features
					snake_case__	     =out_indices






			def 						_lowercase  (     self						)							->							Dict:
					snake_case__	     =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

					snake_case__	     =self.get_config()

					return config, pixel_values, labels






			def 						_lowercase  (     self						)							->							Any:
					return FocalNetConfig(
					    image_size=self.image_size					,   patch_size=self.patch_size					,   num_channels=self.num_channels					,   embed_dim=self.embed_dim					,   hidden_sizes=self.hidden_sizes					,   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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =FocalNetModel(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					snake_case__	     =((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
					snake_case__	     =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 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Optional[int]:
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)

					# verify feature maps
					self.parent.assertEqual(len(result.feature_maps						)					,   len(config.out_features						)						)
					self.parent.assertListEqual(list(result.feature_maps[0].shape						)					,   [self.batch_size, self.image_size, 8, 8]						)

					# verify channels
					self.parent.assertEqual(len(model.channels						)					,   len(config.out_features						)						)
					self.parent.assertListEqual(model.channels					,   config.hidden_sizes[:-1]						)

					# verify backbone works with out_features=None
					snake_case__	     =None
					snake_case__	     =FocalNetBackbone(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =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, self.image_size * 2, 4, 4]						)

					# verify channels
					self.parent.assertEqual(len(model.channels						)					,   1						)
					self.parent.assertListEqual(model.channels					,   [config.hidden_sizes[-1]]						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Any:
					snake_case__	     =FocalNetForMaskedImageModeling(config=_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(
					    result.reconstruction.shape					,   (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForMaskedImageModeling(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					snake_case__	     =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
					snake_case__	     =model(_UpperCAmelCase						)
					self.parent.assertEqual(result.reconstruction.shape					,   (self.batch_size, 1, self.image_size, self.image_size)						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Tuple:
					snake_case__	     =self.type_sequence_label_size
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()
					snake_case__	     =model(_UpperCAmelCase					,   labels=_UpperCAmelCase						)
					self.parent.assertEqual(result.logits.shape					,   (self.batch_size, self.type_sequence_label_size)						)

					# test greyscale images
					snake_case__	     =1
					snake_case__	     =FocalNetForImageClassification(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

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






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__	     =self.prepare_config_and_inputs()

					snake_case__     ,	snake_case__     ,	snake_case__	     =config_and_inputs
					snake_case__	     ={'pixel_values': pixel_values}
					return config, inputs_dict





@require_torch
class 							a__( snake_case__   ,      snake_case__   ,      unittest.TestCase     ):
			a_	: str									=      (
			    (
			        FocalNetModel,
			        FocalNetForImageClassification,
			        FocalNetForMaskedImageModeling,
			        FocalNetBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			a_	: Union[str, Any]									=      (
			    {'''feature-extraction''': FocalNetModel, '''image-classification''': FocalNetForImageClassification}
			    if is_torch_available()
			    else {}
			)
			a_	: Dict									=      False

			a_	: Any									=      False
			a_	: List[str]									=      False
			a_	: List[Any]									=      False
			a_	: Optional[Any]									=      False






			def 						_lowercase  (     self						)							->							Optional[int]:
					snake_case__	     =FocalNetModelTester(self						)
					snake_case__	     =ConfigTester(self					,   config_class=_UpperCAmelCase					,   embed_dim=37					,   has_text_modality=_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					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						)							->							str:
					return






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							Union[str, Any]:
					snake_case__	     =self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)






			@unittest.skip(reason='FocalNet does not use inputs_embeds'						)
			def 						_lowercase  (     self						)							->							str:
					pass






			@unittest.skip(reason='FocalNet does not use feedforward chunking'						)
			def 						_lowercase  (     self						)							->							int:
					pass






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =model_class(_UpperCAmelCase						)
							self.assertIsInstance(model.get_input_embeddings()					,   (nn.Module)						)
							snake_case__	     =model.get_output_embeddings()
							self.assertTrue(x is None or isinstance(_UpperCAmelCase					,   nn.Linear						)						)






			def 						_lowercase  (     self						)							->							Optional[Any]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

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

							snake_case__	     =['pixel_values']
							self.assertListEqual(arg_names[:1]					,   _UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)							->							Union[str, Any]:
					snake_case__	     =model_class(_UpperCAmelCase						)
					model.to(_UpperCAmelCase						)
					model.eval()

					with torch.no_grad():
							snake_case__	     =model(**self._prepare_for_class(_UpperCAmelCase					,   _UpperCAmelCase						)						)

					snake_case__	     =outputs.hidden_states

					snake_case__	     =getattr(
					    self.model_tester					,   'expected_num_hidden_layers'					,   len(self.model_tester.depths						) + 1						)
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

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

					snake_case__	     =(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]					,   )

					snake_case__	     =outputs.reshaped_hidden_states
					self.assertEqual(len(_UpperCAmelCase						)					,   _UpperCAmelCase						)

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






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =(
					    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[:-1]:
							snake_case__	     =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"]
							snake_case__	     =True

							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							List[str]:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()
					snake_case__	     =3

					snake_case__	     =(
					    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)
					)
					snake_case__	     =(
					    config.patch_size
					    if isinstance(config.patch_size					,   collections.abc.Iterable						)
					    else (config.patch_size, config.patch_size)
					)

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

					for model_class in self.all_model_classes[:-1]:
							snake_case__	     =True
							self.check_hidden_states_output(_UpperCAmelCase					,   _UpperCAmelCase					,   _UpperCAmelCase					,   (padded_height, padded_width)						)

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






			@slow
			def 						_lowercase  (     self						)							->							Optional[Any]:
					for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							snake_case__	     =FocalNetModel.from_pretrained(_UpperCAmelCase						)
							self.assertIsNotNone(_UpperCAmelCase						)






			def 						_lowercase  (     self						)							->							int:
					snake_case__     ,	snake_case__	     =self.model_tester.prepare_config_and_inputs_for_common()

					snake_case__	     =_config_zero_init(_UpperCAmelCase						)
					for model_class in self.all_model_classes:
							snake_case__	     =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_vision
@require_torch
class 							a__( unittest.TestCase     ):






			@cached_property
			def 						_lowercase  (     self						)							->							Any:
					# TODO update organization
					return AutoImageProcessor.from_pretrained('microsoft/focalnet-tiny'						) if is_vision_available() else None






			@slow
			def 						_lowercase  (     self						)							->							str:
					snake_case__	     =FocalNetForImageClassification.from_pretrained('microsoft/focalnet-tiny'						).to(_UpperCAmelCase						)
					snake_case__	     =self.default_image_processor

					snake_case__	     =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
					snake_case__	     =image_processor(images=_UpperCAmelCase					,   return_tensors='pt'						).to(_UpperCAmelCase						)

					# forward pass
					with torch.no_grad():
							snake_case__	     =model(**_UpperCAmelCase						)

					# verify the logits
					snake_case__	     =torch.Size((1, 1000)						)
					self.assertEqual(outputs.logits.shape					,   _UpperCAmelCase						)
					snake_case__	     =torch.tensor([0.2_166, -0.4_368, 0.2_191]						).to(_UpperCAmelCase						)
					self.assertTrue(torch.allclose(outputs.logits[0, :3]					,   _UpperCAmelCase					,   atol=1E-4						)						)
					self.assertTrue(outputs.logits.argmax(dim=-1						).item()					,   281						)





@require_torch
class 							a__( snake_case__   ,      unittest.TestCase     ):
			a_	: int									=      (FocalNetBackbone,) if is_torch_available() else ()
			a_	: Any									=      FocalNetConfig

			a_	: int									=      False






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




