





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







				def __init__(							self   :					str      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					str=3      ,     _lowerCamelCase   :					str=32      ,     _lowerCamelCase   :					List[str]=3      ,     _lowerCamelCase   :					Union[str, Any]=10      ,     _lowerCamelCase   :					Optional[int]=[8, 16, 32, 64]      ,     _lowerCamelCase   :					List[Any]=[1, 1, 2, 1]      ,     _lowerCamelCase   :					Optional[Any]=True      ,     _lowerCamelCase   :					Optional[int]=True      ,     _lowerCamelCase   :					List[Any]="relu"      ,     _lowerCamelCase   :					Tuple=3      ,     _lowerCamelCase   :					Tuple=None      ,     _lowerCamelCase   :					List[Any]=["stage2", "stage3", "stage4"]      ,     _lowerCamelCase   :					List[str]=[2, 3, 4]      ,     _lowerCamelCase   :					int=1      ,     ):



					"""simple docstring"""

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







				def 					a_  (							self   :					Tuple       ):



					"""simple docstring"""

					A_  :				Optional[Any]	   =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

					A_  :				Optional[Any]	   =		None
					if self.use_labels:
						A_  :				Tuple	   =		ids_tensor([self.batch_size]      ,     self.num_labels       )

					A_  :				Optional[Any]	   =		self.get_config()

					return config, pixel_values, labels







				def 					a_  (							self   :					Union[str, Any]       ):



					"""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 					a_  (							self   :					List[str]      ,     _lowerCamelCase   :					int      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					List[Any]       ):



					"""simple docstring"""

					A_  :				Dict	   =		BitModel(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				str	   =		model(_lowerCamelCase       )
					self.parent.assertEqual(
					    result.last_hidden_state.shape      ,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)      ,     )







				def 					a_  (							self   :					List[Any]      ,     _lowerCamelCase   :					Any      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					Tuple       ):



					"""simple docstring"""

					A_  :				Tuple	   =		self.num_labels
					A_  :				Dict	   =		BitForImageClassification(_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Tuple	   =		model(_lowerCamelCase      ,     labels=_lowerCamelCase       )
					self.parent.assertEqual(result.logits.shape      ,     (self.batch_size, self.num_labels)       )







				def 					a_  (							self   :					Dict      ,     _lowerCamelCase   :					Optional[int]      ,     _lowerCamelCase   :					List[Any]      ,     _lowerCamelCase   :					Optional[int]       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		BitBackbone(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				Tuple	   =		model(_lowerCamelCase       )

					# 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_  :				Union[str, Any]	   =		None
					A_  :				List[Any]	   =		BitBackbone(config=_lowerCamelCase       )
					model.to(_lowerCamelCase       )
					model.eval()
					A_  :				int	   =		model(_lowerCamelCase       )

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



					"""simple docstring"""

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

@require_torch
class        lowercase      (    __UpperCAmelCase     ,	__UpperCAmelCase     ,	unittest.TestCase):
				__lowerCAmelCase    :    List[Any]         =   (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
				__lowerCAmelCase    :    Optional[int]         =   (
				    {"""feature-extraction""": BitModel, """image-classification""": BitForImageClassification}
				    if is_torch_available()
				    else {}
				)

				__lowerCAmelCase    :    int         =   False
				__lowerCAmelCase    :    List[str]         =   False
				__lowerCAmelCase    :    Union[str, Any]         =   False
				__lowerCAmelCase    :    List[str]         =   False
				__lowerCAmelCase    :    Tuple         =   False







				def 					a_  (							self   :					str       ):



					"""simple docstring"""

					A_  :				str	   =		BitModelTester(self       )
					A_  :				Optional[int]	   =		ConfigTester(self      ,     config_class=_lowerCamelCase      ,     has_text_modality=_lowerCamelCase       )







				def 					a_  (							self   :					Union[str, Any]       ):



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



					"""simple docstring"""

					return







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



					"""simple docstring"""

					pass







				@unittest.skip(reason='''Bit does not use inputs_embeds'''       )
				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					pass







				@unittest.skip(reason='''Bit does not support input and output embeddings'''       )
				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					pass







				def 					a_  (							self   :					Union[str, Any]       ):



					"""simple docstring"""

					A_  :				Tuple	   =		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						A_  :				Any	   =		model_class(_lowerCamelCase       )
						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_  :				Optional[int]	   =		['''pixel_values''']
						self.assertListEqual(arg_names[:1]      ,     _lowerCamelCase       )







				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*_lowerCamelCase       )







				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_backbone(*_lowerCamelCase       )







				def 					a_  (							self   :					int       ):



					"""simple docstring"""

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

					for model_class in self.all_model_classes:
						A_  :				Optional[int]	   =		model_class(config=_lowerCamelCase       )
						for name, module in model.named_modules():
							if isinstance(_lowerCamelCase      ,     (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 					a_  (							self   :					Tuple       ):



					"""simple docstring"""

					def check_hidden_states_output(_lowerCamelCase   :					Tuple      ,     _lowerCamelCase   :					str      ,     _lowerCamelCase   :					Optional[int]       ):
						A_  :				Union[str, Any]	   =		model_class(_lowerCamelCase       )
						model.to(_lowerCamelCase       )
						model.eval()

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

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

						A_  :				Tuple	   =		self.model_tester.num_stages
						self.assertEqual(len(_lowerCamelCase       )      ,     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_  :				Any	   =		self.model_tester.prepare_config_and_inputs_for_common()
					A_  :				List[str]	   =		['''preactivation''', '''bottleneck''']
					for model_class in self.all_model_classes:
						for layer_type in layers_type:
							A_  :				int	   =		layer_type
							A_  :				Tuple	   =		True
							check_hidden_states_output(_lowerCamelCase      ,     _lowerCamelCase      ,     _lowerCamelCase       )

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

							check_hidden_states_output(_lowerCamelCase      ,     _lowerCamelCase      ,     _lowerCamelCase       )







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



					"""simple docstring"""

					pass







				def 					a_  (							self   :					int       ):



					"""simple docstring"""

					A_  :				List[Any]	   =		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase       )







				@slow
				def 					a_  (							self   :					List[str]       ):



					"""simple docstring"""

					for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						A_  :				List[str]	   =		BitModel.from_pretrained(_lowerCamelCase       )
						self.assertIsNotNone(_lowerCamelCase       )

def 		lowercase_      (		):




	"""simple docstring"""






	A_  :				Tuple	   =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
	return image

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







				@cached_property
				def 					a_  (							self   :					Any       ):



					"""simple docstring"""

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







				@slow
				def 					a_  (							self   :					str       ):



					"""simple docstring"""

					A_  :				List[str]	   =		BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(_lowerCamelCase       )

					A_  :				Tuple	   =		self.default_image_processor
					A_  :				List[str]	   =		prepare_img()
					A_  :				Optional[int]	   =		image_processor(images=_lowerCamelCase      ,     return_tensors='''pt'''       ).to(_lowerCamelCase       )

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

					# verify the logits
					A_  :				Optional[int]	   =		torch.Size((1, 10_00)       )
					self.assertEqual(outputs.logits.shape      ,     _lowerCamelCase       )

					A_  :				List[Any]	   =		torch.tensor([[-0.6526, -0.5263, -1.4398]]       ).to(_lowerCamelCase       )

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

@require_torch
class        lowercase      (    __UpperCAmelCase     ,	unittest.TestCase):
				__lowerCAmelCase    :    Union[str, Any]         =   (BitBackbone,) if is_torch_available() else ()
				__lowerCAmelCase    :    List[Any]         =   BitConfig

				__lowerCAmelCase    :    Optional[Any]         =   False







				def 					a_  (							self   :					str       ):



					"""simple docstring"""

					A_  :				Optional[int]	   =		BitModelTester(self       )











"""simple docstring"""

from collections import OrderedDict
from typing import Mapping

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


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

_lowerCamelCase  :			Tuple        =       {
    'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/config.json',
    'umberto-commoncrawl-cased-v1': (
        'https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json'
    ),
    'umberto-wikipedia-uncased-v1': (
        'https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json'
    ),
}

class        lowercase      (    __UpperCAmelCase):
				__lowerCAmelCase    :    Optional[Any]         =   """camembert"""







				def __init__(							self   :					List[Any]      ,     _lowerCamelCase   :					Optional[Any]=3_05_22      ,     _lowerCamelCase   :					List[str]=7_68      ,     _lowerCamelCase   :					Optional[Any]=12      ,     _lowerCamelCase   :					List[str]=12      ,     _lowerCamelCase   :					Any=30_72      ,     _lowerCamelCase   :					List[str]="gelu"      ,     _lowerCamelCase   :					Optional[Any]=0.1      ,     _lowerCamelCase   :					Optional[int]=0.1      ,     _lowerCamelCase   :					Union[str, Any]=5_12      ,     _lowerCamelCase   :					str=2      ,     _lowerCamelCase   :					Optional[Any]=0.02      ,     _lowerCamelCase   :					int=1E-12      ,     _lowerCamelCase   :					str=1      ,     _lowerCamelCase   :					Union[str, Any]=0      ,     _lowerCamelCase   :					Optional[int]=2      ,     _lowerCamelCase   :					List[str]="absolute"      ,     _lowerCamelCase   :					str=True      ,     _lowerCamelCase   :					List[Any]=None      ,     **_lowerCamelCase   :					Union[str, Any]      ,     ):



					"""simple docstring"""

					super().__init__(pad_token_id=_lowerCamelCase      ,     bos_token_id=_lowerCamelCase      ,     eos_token_id=_lowerCamelCase      ,     **_lowerCamelCase       )

					A_  :				Any	   =		vocab_size
					A_  :				Optional[Any]	   =		hidden_size
					A_  :				Any	   =		num_hidden_layers
					A_  :				List[Any]	   =		num_attention_heads
					A_  :				List[Any]	   =		hidden_act
					A_  :				Optional[int]	   =		intermediate_size
					A_  :				Tuple	   =		hidden_dropout_prob
					A_  :				Union[str, Any]	   =		attention_probs_dropout_prob
					A_  :				int	   =		max_position_embeddings
					A_  :				Tuple	   =		type_vocab_size
					A_  :				Dict	   =		initializer_range
					A_  :				Tuple	   =		layer_norm_eps
					A_  :				List[Any]	   =		position_embedding_type
					A_  :				Any	   =		use_cache
					A_  :				Dict	   =		classifier_dropout

class        lowercase      (    __UpperCAmelCase):







				@property
				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					if self.task == "multiple-choice":
						A_  :				Union[str, Any]	   =		{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
					else:
						A_  :				Dict	   =		{0: '''batch''', 1: '''sequence'''}
					return OrderedDict(
					    [
					        ('''input_ids''', dynamic_axis),
					        ('''attention_mask''', dynamic_axis),
					    ]       )





