






'''simple docstring'''

import inspect
import unittest

from transformers import BitConfig
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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch
						from torch import nn

						from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel
						from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
						from PIL import Image






class 							__magic_name__     :







	"""simple docstring"""



	def __init__(							self  ,      _lowercase  ,      _lowercase=3  ,      _lowercase=32  ,      _lowercase=3  ,      _lowercase=10  ,      _lowercase=[8, 16, 32, 64]  ,      _lowercase=[1, 1, 2, 1]  ,      _lowercase=True  ,      _lowercase=True  ,      _lowercase="relu"  ,      _lowercase=3  ,      _lowercase=None  ,      _lowercase=["stage2", "stage3", "stage4"]  ,      _lowercase=[2, 3, 4]  ,      _lowercase=1  ,      )						->  str:
							lowercase_      :   List[Any]        =			parent
							lowercase_      :   str        =			batch_size
							lowercase_      :   Optional[int]        =			image_size
							lowercase_      :   Union[str, Any]        =			num_channels
							lowercase_      :   Any        =			embeddings_size
							lowercase_      :   List[Any]        =			hidden_sizes
							lowercase_      :   str        =			depths
							lowercase_      :   Optional[Any]        =			is_training
							lowercase_      :   Any        =			use_labels
							lowercase_      :   Tuple        =			hidden_act
							lowercase_      :   Optional[Any]        =			num_labels
							lowercase_      :   Union[str, Any]        =			scope
							lowercase_      :   Union[str, Any]        =			len(_lowercase       )
							lowercase_      :   str        =			out_features
							lowercase_      :   Optional[Any]        =			out_indices
							lowercase_      :   List[Any]        =			num_groups
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   List[Any]        =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

							lowercase_      :   List[str]        =			None
							if self.use_labels:
													lowercase_      :   Any        =			ids_tensor([self.batch_size]  ,      self.num_labels       )

							lowercase_      :   Any        =			self.get_config()

							return config, pixel_values, labels
	def        lowerCamelCase__		(							self       )						->  Any:
							return BitConfig(
							    num_channels=self.num_channels  ,      embeddings_size=self.embeddings_size  ,      hidden_sizes=self.hidden_sizes  ,      depths=self.depths  ,      hidden_act=self.hidden_act  ,      num_labels=self.num_labels  ,      out_features=self.out_features  ,      out_indices=self.out_indices  ,      num_groups=self.num_groups  ,      )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  int:
							lowercase_      :   List[str]        =			BitModel(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Tuple        =			model(_lowercase       )
							self.parent.assertEqual(
							    result.last_hidden_state.shape  ,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)  ,      )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Union[str, Any]:
							lowercase_      :   Any        =			self.num_labels
							lowercase_      :   List[Any]        =			BitForImageClassification(_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[Any]        =			model(_lowercase  ,      labels=_lowercase       )
							self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.num_labels)       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase  ,      _lowercase       )						->  Optional[Any]:
							lowercase_      :   int        =			BitBackbone(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   str        =			model(_lowercase       )

							# 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.hidden_sizes[1], 4, 4]       )

							# 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
							lowercase_      :   int        =			None
							lowercase_      :   int        =			BitBackbone(config=_lowercase       )
							model.to(_lowercase       )
							model.eval()
							lowercase_      :   Optional[Any]        =			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, self.hidden_sizes[-1], 1, 1]       )

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







	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							lowercase_      :   Tuple        =			self.prepare_config_and_inputs()
							lowercase_  ,      lowercase_  ,      lowercase_      :   Optional[Any]        =			config_and_inputs
							lowercase_      :   int        =			{'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 							__magic_name__     (	UpperCAmelCase_,						UpperCAmelCase_,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      List[Any]        =  (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  (
	    {'feature-extraction': BitModel, 'image-classification': BitForImageClassification}
	    if is_torch_available()
	    else {}
	)

	SCREAMING_SNAKE_CASE_					:      Any        =  False
	SCREAMING_SNAKE_CASE_					:      List[Any]        =  False
	SCREAMING_SNAKE_CASE_					:      List[Any]        =  False
	SCREAMING_SNAKE_CASE_					:      List[str]        =  False
	SCREAMING_SNAKE_CASE_					:      str        =  False
	def        lowerCamelCase__		(							self       )						->  str:
							lowercase_      :   List[Any]        =			BitModelTester(self       )
							lowercase_      :   Optional[Any]        =			ConfigTester(self  ,      config_class=_lowercase  ,      has_text_modality=_lowercase       )
	def        lowerCamelCase__		(							self       )						->  str:
							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        lowerCamelCase__		(							self       )						->  List[Any]:
							return
	@unittest.skip(reason='Bit does not output attentions'       )
	def        lowerCamelCase__		(							self       )						->  str:
							pass
	@unittest.skip(reason='Bit does not use inputs_embeds'       )
	def        lowerCamelCase__		(							self       )						->  Any:
							pass
	@unittest.skip(reason='Bit does not support input and output embeddings'       )
	def        lowerCamelCase__		(							self       )						->  Any:
							pass
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_  ,      lowercase_      :   Optional[int]        =			self.model_tester.prepare_config_and_inputs_for_common()

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

													lowercase_      :   Tuple        =			['pixel_values']
													self.assertListEqual(arg_names[:1]  ,      _lowercase       )
	def        lowerCamelCase__		(							self       )						->  int:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Dict:
							lowercase_      :   Dict        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*_lowercase       )
	def        lowerCamelCase__		(							self       )						->  Any:
							lowercase_  ,      lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													lowercase_      :   Optional[int]        =			model_class(config=_lowercase       )
													for name, module in model.named_modules():
																			if isinstance(_lowercase  ,      (nn.BatchNormad, nn.GroupNorm)       ):
																									self.assertTrue(
																									    torch.all(module.weight == 1       )  ,      msg=f"Parameter {name} of model {model_class} seems not properly initialized"  ,      )
																									self.assertTrue(
																									    torch.all(module.bias == 0       )  ,      msg=f"Parameter {name} of model {model_class} seems not properly initialized"  ,      )
	def        lowerCamelCase__		(							self       )						->  str:
							def check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       ):
													lowercase_      :   int        =			model_class(_lowercase       )
													model.to(_lowercase       )
													model.eval()

													with torch.no_grad():
																			lowercase_      :   Optional[Any]        =			model(**self._prepare_for_class(_lowercase  ,      _lowercase       )       )

													lowercase_      :   List[Any]        =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													lowercase_      :   Dict        =			self.model_tester.num_stages
													self.assertEqual(len(_lowercase       )  ,      expected_num_stages + 1       )

													# Bit's feature maps are of shape (batch_size, num_channels, height, width)
													self.assertListEqual(
													    list(hidden_states[0].shape[-2:]       )  ,      [self.model_tester.image_size // 4, self.model_tester.image_size // 4]  ,      )

							lowercase_  ,      lowercase_      :   Any        =			self.model_tester.prepare_config_and_inputs_for_common()
							lowercase_      :   List[str]        =			['preactivation', 'bottleneck']
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			lowercase_      :   Dict        =			layer_type
																			lowercase_      :   Optional[int]        =			True
																			check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       )

																			# check that output_hidden_states also work using config
																			del inputs_dict["output_hidden_states"]
																			lowercase_      :   Union[str, Any]        =			True

																			check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase       )
	@unittest.skip(reason='Bit does not use feedforward chunking'       )
	def        lowerCamelCase__		(							self       )						->  Tuple:
							pass
	def        lowerCamelCase__		(							self       )						->  Tuple:
							lowercase_      :   int        =			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_lowercase       )







	@slow
	def        lowerCamelCase__		(							self       )						->  Dict:
							for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													lowercase_      :   Optional[Any]        =			BitModel.from_pretrained(_lowercase       )
													self.assertIsNotNone(_lowercase       )






def 	_UpperCAmelCase    (  )			->			str:





						"""simple docstring"""
						lowercase_      :   int        =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
						return image






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







	"""simple docstring"""



	@cached_property
	def        lowerCamelCase__		(							self       )						->  Any:
							return (
							    BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ) if is_vision_available() else None
							)







	@slow
	def        lowerCamelCase__		(							self       )						->  Optional[int]:
							lowercase_      :   Union[str, Any]        =			BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(_lowercase       )

							lowercase_      :   Optional[int]        =			self.default_image_processor
							lowercase_      :   List[Any]        =			prepare_img()
							lowercase_      :   List[Any]        =			image_processor(images=_lowercase  ,      return_tensors='pt'       ).to(_lowercase       )

							# forward pass
							with torch.no_grad():
													lowercase_      :   Union[str, Any]        =			model(**_lowercase       )

							# verify the logits
							lowercase_      :   Union[str, Any]        =			torch.Size((1, 1000)       )
							self.assertEqual(outputs.logits.shape  ,      _lowercase       )

							lowercase_      :   Dict        =			torch.tensor([[-0.65_26, -0.52_63, -1.43_98]]       ).to(_lowercase       )

							self.assertTrue(torch.allclose(outputs.logits[0, :3]  ,      _lowercase  ,      atol=1E-4       )       )






@require_torch
class 							__magic_name__     (	UpperCAmelCase_,						unittest.TestCase				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      int        =  (BitBackbone,) if is_torch_available() else ()
	SCREAMING_SNAKE_CASE_					:      List[Any]        =  BitConfig

	SCREAMING_SNAKE_CASE_					:      Optional[Any]        =  False
	def        lowerCamelCase__		(							self       )						->  Tuple:
							lowercase_      :   str        =			BitModelTester(self       )








'''simple docstring'''

from collections import OrderedDict
from typing import Mapping

from packaging import version

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


A:      Dict  				=				logging.get_logger(__name__)

A:      Optional[Any]  				=				{
    "google/vit-base-patch16-224": "https://huggingface.co/vit-base-patch16-224/resolve/main/config.json",
    # See all ViT models at https://huggingface.co/models?filter=vit
}






class 							__magic_name__     (	UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Optional[Any]        =  'vit'
	def __init__(							self  ,      _lowercase=768  ,      _lowercase=12  ,      _lowercase=12  ,      _lowercase=3072  ,      _lowercase="gelu"  ,      _lowercase=0.0  ,      _lowercase=0.0  ,      _lowercase=0.02  ,      _lowercase=1E-1_2  ,      _lowercase=224  ,      _lowercase=16  ,      _lowercase=3  ,      _lowercase=True  ,      _lowercase=16  ,      **_lowercase  ,      )						->  List[str]:
							super().__init__(**_lowercase       )

							lowercase_      :   Optional[int]        =			hidden_size
							lowercase_      :   str        =			num_hidden_layers
							lowercase_      :   str        =			num_attention_heads
							lowercase_      :   int        =			intermediate_size
							lowercase_      :   List[Any]        =			hidden_act
							lowercase_      :   Any        =			hidden_dropout_prob
							lowercase_      :   List[str]        =			attention_probs_dropout_prob
							lowercase_      :   str        =			initializer_range
							lowercase_      :   List[str]        =			layer_norm_eps
							lowercase_      :   Any        =			image_size
							lowercase_      :   Tuple        =			patch_size
							lowercase_      :   Optional[Any]        =			num_channels
							lowercase_      :   str        =			qkv_bias
							lowercase_      :   List[str]        =			encoder_stride






class 							__magic_name__     (	UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Any        =  version.parse('1.11'				)
	@property
	def        lowerCamelCase__		(							self       )						->  Mapping[str, Mapping[int, str]]:
							return OrderedDict(
							    [
							        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
							    ]       )







	@property
	def        lowerCamelCase__		(							self       )						->  float:
							return 1E-4
