


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




	def __init__(   self						,				__a						,				__a=3						,				__a=32						,				__a=3						,				__a=10						,				__a=[8, 16, 32, 64]						,				__a=[1, 1, 2, 1]						,				__a=True						,				__a=True						,				__a="relu"						,				__a=3						,				__a=None						,				__a=["stage2", "stage3", "stage4"]						,				__a=[2, 3, 4]						,				__a=1						,				):

						'''simple docstring'''





						__a			:       Any					    =  parent
						__a			:       Dict					    =  batch_size
						__a			:       Any					    =  image_size
						__a			:       Dict					    =  num_channels
						__a			:       int					    =  embeddings_size
						__a			:       str					    =  hidden_sizes
						__a			:       Tuple					    =  depths
						__a			:       Tuple					    =  is_training
						__a			:       str					    =  use_labels
						__a			:       int					    =  hidden_act
						__a			:       List[Any]					    =  num_labels
						__a			:       Dict					    =  scope
						__a			:       Dict					    =  len(_snake_case							)
						__a			:       Optional[int]					    =  out_features
						__a			:       List[str]					    =  out_indices
						__a			:       Any					    =  num_groups




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       int					    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

						__a			:       Optional[int]					    =  self.get_config()

						return config, pixel_values, labels




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						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       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Tuple					    =  BitModel(config=_snake_case							)
						model.to(_snake_case							)
						model.eval()
						__a			:       Union[str, Any]					    =  model(_snake_case							)
						self.parent.assertEqual(
						    result.last_hidden_state.shape						,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,				)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       Optional[int]					    =  self.num_labels
						__a			:       List[str]					    =  BitForImageClassification(_snake_case							)
						model.to(_snake_case							)
						model.eval()
						__a			:       int					    =  model(_snake_case						,				labels=_snake_case							)
						self.parent.assertEqual(result.logits.shape						,				(self.batch_size, self.num_labels)							)




	def       __UpperCAmelCase							(   self						,				__a						,				__a						,				__a							):

						'''simple docstring'''





						__a			:       int					    =  BitBackbone(config=_snake_case							)
						model.to(_snake_case							)
						model.eval()
						__a			:       str					    =  model(_snake_case							)

						# 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
						__a			:       Tuple					    =  None
						__a			:       Optional[int]					    =  BitBackbone(config=_snake_case							)
						model.to(_snake_case							)
						model.eval()
						__a			:       int					    =  model(_snake_case							)

						# 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       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  self.prepare_config_and_inputs()
						__a			:       Optional[Any]					    =  config_and_inputs
						__a			:       Any					    =  {'''pixel_values''': pixel_values}
						return config, inputs_dict





@require_torch
class 							__UpperCamelCase				(		A_		,      A_		,      unittest.TestCase					):
	A_				=    (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
	A_				=    (
	    {"feature-extraction": BitModel, "image-classification": BitForImageClassification}
	    if is_torch_available()
	    else {}
	)

	A_				=    False
	A_				=    False
	A_				=    False
	A_				=    False
	A_				=    False




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Optional[Any]					    =  BitModelTester(self							)
						__a			:       Tuple					    =  ConfigTester(self						,				config_class=_snake_case						,				has_text_modality=_snake_case							)




	def       __UpperCAmelCase							(   self							):

						'''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       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return




	@unittest.skip(reason='Bit does not output attentions'							)
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						pass




	@unittest.skip(reason='Bit does not use inputs_embeds'							)
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						pass




	@unittest.skip(reason='Bit does not support input and output embeddings'							)
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						pass




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Dict					    =  self.model_tester.prepare_config_and_inputs_for_common()

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

											__a			:       List[Any]					    =  ['''pixel_values''']
											self.assertListEqual(arg_names[:1]						,				_snake_case							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       List[str]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*_snake_case							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       str					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_backbone(*_snake_case							)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Any					    =  self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__a			:       List[Any]					    =  model_class(config=_snake_case							)
											for name, module in model.named_modules():
																if isinstance(_snake_case						,				(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       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						def check_hidden_states_output(__a						,				__a						,				__a							):
											__a			:       Optional[int]					    =  model_class(_snake_case							)
											model.to(_snake_case							)
											model.eval()

											with torch.no_grad():
																__a			:       Tuple					    =  model(**self._prepare_for_class(_snake_case						,				_snake_case							)							)

											__a			:       Optional[Any]					    =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											__a			:       int					    =  self.model_tester.num_stages
											self.assertEqual(len(_snake_case							)						,				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]						,				)

						__a			:       List[str]					    =  self.model_tester.prepare_config_and_inputs_for_common()
						__a			:       str					    =  ['''preactivation''', '''bottleneck''']
						for model_class in self.all_model_classes:
											for layer_type in layers_type:
																__a			:       Dict					    =  layer_type
																__a			:       Tuple					    =  True
																check_hidden_states_output(_snake_case						,				_snake_case						,				_snake_case							)

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																__a			:       List[Any]					    =  True

																check_hidden_states_output(_snake_case						,				_snake_case						,				_snake_case							)




	@unittest.skip(reason='Bit does not use feedforward chunking'							)
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						pass




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       List[str]					    =  self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*_snake_case							)





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__a			:       Dict					    =  BitModel.from_pretrained(_snake_case							)
											self.assertIsNotNone(_snake_case							)






def   lowerCamelCase							():
					__a			:       int					    =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
					return image





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




	@cached_property
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						return (
						    BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							) if is_vision_available() else None
						)





	@slow
	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Union[str, Any]					    =  BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							).to(_snake_case							)

						__a			:       List[Any]					    =  self.default_image_processor
						__a			:       str					    =  prepare_img()
						__a			:       str					    =  image_processor(images=_snake_case						,				return_tensors='pt'							).to(_snake_case							)

						# forward pass
						with torch.no_grad():
											__a			:       Optional[int]					    =  model(**_snake_case							)

						# verify the logits
						__a			:       Tuple					    =  torch.Size((1, 1000)							)
						self.assertEqual(outputs.logits.shape						,				_snake_case							)

						__a			:       List[str]					    =  torch.tensor([[-0.6526, -0.5263, -1.4398]]							).to(_snake_case							)

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





@require_torch
class 							__UpperCamelCase				(		A_		,      unittest.TestCase					):
	A_				=    (BitBackbone,) if is_torch_available() else ()
	A_				=    BitConfig

	A_				=    False




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						__a			:       Tuple					    =  BitModelTester(self							)








"""simple docstring"""







from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
							from PIL import Image

							from ..image_utils import load_image

if is_torch_available():
							from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
							from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
							from ..tf_utils import stable_softmax

lowerCAmelCase_   						=   logging.get_logger(__name__)
@add_end_docstrings(A_    )
class        __A       (	A_    ):







		'''simple docstring'''





		def __init__(	self						:  List[str]			,**_snake_case						:  Dict						)					->		List[Any]:






				"""simple docstring"""



				super().__init__(**_snake_case						)

				requires_backends(self			,'''vision'''						)
				self.check_model_type(
				    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
				    if self.framework == '''tf'''
				    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING						)







		def __call__(	self						:  Optional[int]			,_snake_case						:  Union[str, List[str], "Image", List["Image"]]			,**_snake_case						:  int						)					->		Optional[Any]:






				"""simple docstring"""



				return super().__call__(_snake_case			,**_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict			,**_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    List[str]				=			{}
				if "candidate_labels" in kwargs:
						lowercase__   :    Any				=			kwargs['''candidate_labels''']
				if "hypothesis_template" in kwargs:
						lowercase__   :    Optional[Any]				=			kwargs['''hypothesis_template''']

				return preprocess_params, {}, {}







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]			,_snake_case						:  Dict=None			,_snake_case						:  Union[str, Any]="This is a photo of {}."						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			load_image(_snake_case						)
				lowercase__   :    int				=			self.image_processor(images=[image]			,return_tensors=self.framework						)
				lowercase__   :    str				=			candidate_labels
				lowercase__   :    Dict				=			[hypothesis_template.format(_snake_case						) for x in candidate_labels]
				lowercase__   :    Any				=			self.tokenizer(_snake_case			,return_tensors=self.framework			,padding=_snake_case						)
				lowercase__   :    Optional[int]				=			[text_inputs]
				return inputs







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  Optional[int]						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			model_inputs.pop('''candidate_labels'''						)
				lowercase__   :    Union[str, Any]				=			model_inputs.pop('''text_inputs'''						)
				if isinstance(text_inputs[0]			,_snake_case						):
						lowercase__   :    List[str]				=			text_inputs[0]
				else:
						# Batching case.
						lowercase__   :    int				=			text_inputs[0][0]

				lowercase__   :    Tuple				=			self.model(**_snake_case			,**_snake_case						)

				lowercase__   :    Union[str, Any]				=			{
				    '''candidate_labels''': candidate_labels,
				    '''logits''': outputs.logits_per_image,
				}
				return model_outputs







		def 					UpperCAmelCase    (	self						:  Any			,_snake_case						:  Tuple						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Dict				=			model_outputs.pop('''candidate_labels'''						)
				lowercase__   :    Optional[Any]				=			model_outputs['''logits'''][0]
				if self.framework == "pt":
						lowercase__   :    Optional[int]				=			logits.softmax(dim=-1						).squeeze(-1						)
						lowercase__   :    Tuple				=			probs.tolist()
						if not isinstance(_snake_case			,_snake_case						):
								lowercase__   :    Any				=			[scores]
				elif self.framework == "tf":
						lowercase__   :    List[str]				=			stable_softmax(_snake_case			,axis=-1						)
						lowercase__   :    Optional[Any]				=			probs.numpy().tolist()
				else:
						raise ValueError(f"""Unsupported framework: {self.framework}"""						)

				lowercase__   :    Union[str, Any]				=			[
				    {'''score''': score, '''label''': candidate_label}
				    for score, candidate_label in sorted(zip(_snake_case			,_snake_case						)			,key=lambda _snake_case						: -x[0]						)
				]
				return result
