






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     lowerCamelCase_					:







				def __init__(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=3							,       __lowerCAmelCase=3_2							,       __lowerCAmelCase=3							,       __lowerCAmelCase=1_0							,       __lowerCAmelCase=[8, 1_6, 3_2, 6_4]							,       __lowerCAmelCase=[1, 1, 2, 1]							,       __lowerCAmelCase=True							,       __lowerCAmelCase=True							,       __lowerCAmelCase="relu"							,       __lowerCAmelCase=3							,       __lowerCAmelCase=None							,       __lowerCAmelCase=["stage2", "stage3", "stage4"]							,       __lowerCAmelCase=[2, 3, 4]							,       __lowerCAmelCase=1							,       ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   parent
								__magic_name__		:str   =   batch_size
								__magic_name__		:List[Any]   =   image_size
								__magic_name__		:Any   =   num_channels
								__magic_name__		:Optional[Any]   =   embeddings_size
								__magic_name__		:Any   =   hidden_sizes
								__magic_name__		:Tuple   =   depths
								__magic_name__		:Any   =   is_training
								__magic_name__		:Union[str, Any]   =   use_labels
								__magic_name__		:List[str]   =   hidden_act
								__magic_name__		:Optional[int]   =   num_labels
								__magic_name__		:Any   =   scope
								__magic_name__		:Dict   =   len(__lowerCAmelCase  )
								__magic_name__		:Any   =   out_features
								__magic_name__		:str   =   out_indices
								__magic_name__		:Tuple   =   num_groups







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

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

								return config, pixel_values, labels







				def       A						(    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       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   BitModel(config=__lowerCAmelCase  )
								model.to(__lowerCAmelCase  )
								model.eval()
								__magic_name__		:Optional[Any]   =   model(__lowerCAmelCase  )
								self.parent.assertEqual(
								    result.last_hidden_state.shape							,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)							,       )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:Optional[int]   =   self.num_labels
								__magic_name__		:int   =   BitForImageClassification(__lowerCAmelCase  )
								model.to(__lowerCAmelCase  )
								model.eval()
								__magic_name__		:str   =   model(__lowerCAmelCase							,       labels=__lowerCAmelCase  )
								self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.num_labels)  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
								"""simple docstring"""
								__magic_name__		:List[Any]   =   BitBackbone(config=__lowerCAmelCase  )
								model.to(__lowerCAmelCase  )
								model.eval()
								__magic_name__		:Optional[int]   =   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
								__magic_name__		:Any   =   None
								__magic_name__		:Union[str, Any]   =   BitBackbone(config=__lowerCAmelCase  )
								model.to(__lowerCAmelCase  )
								model.eval()
								__magic_name__		:Optional[Any]   =   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  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.prepare_config_and_inputs()
								__magic_name__  ,					__magic_name__  ,					__magic_name__		:int   =   config_and_inputs
								__magic_name__		:str   =   {'''pixel_values''': pixel_values}
								return config, inputs_dict







@require_torch
class     lowerCamelCase_					(   lowerCamelCase      ,					lowerCamelCase      ,					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       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   BitModelTester(self  )
								__magic_name__		:List[str]   =   ConfigTester(self							,       config_class=__lowerCAmelCase							,       has_text_modality=__lowerCAmelCase  )







				def       A						(    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       A						(    self  ):
								"""simple docstring"""
								return







				@unittest.skip(reason='''Bit does not output attentions'''  )
				def       A						(    self  ):
								"""simple docstring"""
								pass







				@unittest.skip(reason='''Bit does not use inputs_embeds'''  )
				def       A						(    self  ):
								"""simple docstring"""
								pass







				@unittest.skip(reason='''Bit does not support input and output embeddings'''  )
				def       A						(    self  ):
								"""simple docstring"""
								pass







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__  ,					__magic_name__		:int   =   self.model_tester.prepare_config_and_inputs_for_common()

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

												__magic_name__		:Optional[int]   =   ['''pixel_values''']
												self.assertListEqual(arg_names[:1]							,       __lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Tuple   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:str   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_backbone(*__lowerCAmelCase  )







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__  ,					__magic_name__		:Optional[int]   =   self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
												__magic_name__		:Tuple   =   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  ):
								"""simple docstring"""
								def check_hidden_states_output(__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  ):
												__magic_name__		:Optional[int]   =   model_class(__lowerCAmelCase  )
												model.to(__lowerCAmelCase  )
												model.eval()

												with torch.no_grad():
																__magic_name__		:Tuple   =   model(**self._prepare_for_class(__lowerCAmelCase							,       __lowerCAmelCase  )  )

												__magic_name__		:List[str]   =   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												__magic_name__		:Dict   =   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]							,       )

								__magic_name__  ,					__magic_name__		:Tuple   =   self.model_tester.prepare_config_and_inputs_for_common()
								__magic_name__		:Tuple   =   ['''preactivation''', '''bottleneck''']
								for model_class in self.all_model_classes:
												for layer_type in layers_type:
																__magic_name__		:int   =   layer_type
																__magic_name__		:Tuple   =   True
																check_hidden_states_output(__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  )

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

																check_hidden_states_output(__lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase  )







				@unittest.skip(reason='''Bit does not use feedforward chunking'''  )
				def       A						(    self  ):
								"""simple docstring"""
								pass







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:List[Any]   =   self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase  )







				@slow
				def       A						(    self  ):
								"""simple docstring"""
								for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												__magic_name__		:List[str]   =   BitModel.from_pretrained(__lowerCAmelCase  )
												self.assertIsNotNone(__lowerCAmelCase  )







def   __lowercase       (			):







				"""simple docstring"""






				__magic_name__		:Union[str, Any]   =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
				return image
@require_torch
@require_vision
class     lowerCamelCase_					(   unittest.TestCase			):







				@cached_property
				def       A						(    self  ):
								"""simple docstring"""
								return (
								    BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  ) if is_vision_available() else None
								)







				@slow
				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Any   =   BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]  ).to(__lowerCAmelCase  )

								__magic_name__		:Union[str, Any]   =   self.default_image_processor
								__magic_name__		:int   =   prepare_img()
								__magic_name__		:Tuple   =   image_processor(images=__lowerCAmelCase							,       return_tensors='''pt'''  ).to(__lowerCAmelCase  )

								# forward pass
								with torch.no_grad():
												__magic_name__		:Tuple   =   model(**__lowerCAmelCase  )

								# verify the logits
								__magic_name__		:Optional[Any]   =   torch.Size((1, 1_0_0_0)  )
								self.assertEqual(outputs.logits.shape							,       __lowerCAmelCase  )

								__magic_name__		:int   =   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     lowerCamelCase_					(   lowerCamelCase      ,					unittest.TestCase			):
				a__       							=	(BitBackbone,) if is_torch_available() else ()
				a__       							=	BitConfig

				a__       							=	False







				def       A						(    self  ):
								"""simple docstring"""
								__magic_name__		:Dict   =   BitModelTester(self  )














from pathlib import PurePosixPath
from typing import Optional

import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo

from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url
class     lowerCamelCase_					(   lowerCamelCase			):
				a__       							=	''''''
				a__       							=	'''hf-legacy'''  # "hf://"" is reserved for hffs







				def __init__(    self							,       __lowerCAmelCase = None							,       __lowerCAmelCase = None							,       **__lowerCAmelCase							,       ):
								"""simple docstring"""
								super().__init__(self							,       **__lowerCAmelCase  )
								__magic_name__		:List[Any]   =   repo_info
								__magic_name__		:Dict   =   token
								__magic_name__		:Optional[Any]   =   None







				def       A						(    self  ):
								"""simple docstring"""
								if self.dir_cache is None:
												__magic_name__		:Any   =   {}
												for hf_file in self.repo_info.siblings:
																# TODO(QL): add sizes
																__magic_name__		:Optional[int]   =   {
																    '''name''': hf_file.rfilename,
																    '''size''': None,
																    '''type''': '''file''',
																}
																self.dir_cache.update(
																    {
																        str(__lowerCAmelCase  ): {'''name''': str(__lowerCAmelCase  ), '''size''': None, '''type''': '''directory'''}
																        for d in list(PurePosixPath(hf_file.rfilename  ).parents  )[:-1]
																    }  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase = "rb"							,       **__lowerCAmelCase							,       ):
								"""simple docstring"""
								if not isinstance(self.repo_info							,       __lowerCAmelCase  ):
												raise NotImplementedError(F'''Open is only implemented for dataset repositories, but got {self.repo_info}'''  )
								__magic_name__		:Union[str, Any]   =   hf_hub_url(self.repo_info.id							,       __lowerCAmelCase							,       revision=self.repo_info.sha  )
								return fsspec.open(
								    __lowerCAmelCase							,       mode=__lowerCAmelCase							,       headers=get_authentication_headers_for_url(__lowerCAmelCase							,       use_auth_token=self.token  )							,       client_kwargs={'''trust_env''': True}							,       ).open()







				def       A						(    self							,       __lowerCAmelCase							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								self._get_dirs()
								__magic_name__		:str   =   self._strip_protocol(__lowerCAmelCase  )
								if path in self.dir_cache:
												return self.dir_cache[path]
								else:
												raise FileNotFoundError(__lowerCAmelCase  )







				def       A						(    self							,       __lowerCAmelCase							,       __lowerCAmelCase=False							,       **__lowerCAmelCase  ):
								"""simple docstring"""
								self._get_dirs()
								__magic_name__		:Union[str, Any]   =   PurePosixPath(path.strip('''/'''  )  )
								__magic_name__		:Dict   =   {}
								for p, f in self.dir_cache.items():
												__magic_name__		:int   =   PurePosixPath(p.strip('''/'''  )  )
												__magic_name__		:Tuple   =   p.parent
												if root == path:
																__magic_name__		:Optional[Any]   =   f
								__magic_name__		:List[Any]   =   list(paths.values()  )
								if detail:
												return out
								else:
												return sorted(f['''name'''] for f in out  )






