



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		, __UpperCAmelCase		, __UpperCAmelCase=3		, __UpperCAmelCase=32		, __UpperCAmelCase=3		, __UpperCAmelCase=10		, __UpperCAmelCase=[8, 16, 32, 64]		, __UpperCAmelCase=[1, 1, 2, 1]		, __UpperCAmelCase=True		, __UpperCAmelCase=True		, __UpperCAmelCase="relu"		, __UpperCAmelCase=3		, __UpperCAmelCase=None		, __UpperCAmelCase=["stage2", "stage3", "stage4"]		, __UpperCAmelCase=[2, 3, 4]		, __UpperCAmelCase=1		, ):



    '''simple docstring'''
    __lowerCamelCase  							=			parent
    __lowerCamelCase  							=			batch_size
    __lowerCamelCase  							=			image_size
    __lowerCamelCase  							=			num_channels
    __lowerCamelCase  							=			embeddings_size
    __lowerCamelCase  							=			hidden_sizes
    __lowerCamelCase  							=			depths
    __lowerCamelCase  							=			is_training
    __lowerCamelCase  							=			use_labels
    __lowerCamelCase  							=			hidden_act
    __lowerCamelCase  							=			num_labels
    __lowerCamelCase  							=			scope
    __lowerCamelCase  							=			len(__lowercase )
    __lowerCamelCase  							=			out_features
    __lowerCamelCase  							=			out_indices
    __lowerCamelCase  							=			num_groups




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

    __lowerCamelCase  							=			None
    if self.use_labels:
       __lowerCamelCase  							=			ids_tensor([self.batch_size]		, self.num_labels )

    __lowerCamelCase  							=			self.get_config()

    return config, pixel_values, labels




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



    '''simple docstring'''
    __lowerCamelCase  							=			BitModel(config=__lowercase )
    model.to(__lowercase )
    model.eval()
    __lowerCamelCase  							=			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		, __UpperCAmelCase		, __UpperCAmelCase		, __UpperCAmelCase ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.num_labels
    __lowerCamelCase  							=			BitForImageClassification(__lowercase )
    model.to(__lowercase )
    model.eval()
    __lowerCamelCase  							=			model(__lowercase		, labels=__lowercase )
    self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.num_labels) )




 def 				lowerCamelCase					(  self		, __UpperCAmelCase		, __UpperCAmelCase		, __UpperCAmelCase ):



    '''simple docstring'''
    __lowerCamelCase  							=			BitBackbone(config=__lowercase )
    model.to(__lowercase )
    model.eval()
    __lowerCamelCase  							=			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
    __lowerCamelCase  							=			None
    __lowerCamelCase  							=			BitBackbone(config=__lowercase )
    model.to(__lowercase )
    model.eval()
    __lowerCamelCase  							=			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 ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.prepare_config_and_inputs()
    __lowerCamelCase  							=			config_and_inputs
    __lowerCamelCase  							=			{'''pixel_values''': pixel_values}
    return config, inputs_dict



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

 lowerCAmelCase__				    =     False
 lowerCAmelCase__				    =     False
 lowerCAmelCase__				    =     False
 lowerCAmelCase__				    =     False
 lowerCAmelCase__				    =     False




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			BitModelTester(self )
    __lowerCamelCase  							=			ConfigTester(self		, config_class=__lowercase		, has_text_modality=__lowercase )




 def 				lowerCamelCase					(  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 				lowerCamelCase					(  self ):



    '''simple docstring'''
    return




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



    '''simple docstring'''
    pass




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



    '''simple docstring'''
    pass




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



    '''simple docstring'''
    pass




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

       __lowerCamelCase  							=			['''pixel_values''']
       self.assertListEqual(arg_names[:1]		, __lowercase )




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowercase )




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_backbone(*__lowercase )




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       __lowerCamelCase  							=			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 ):



    '''simple docstring'''
    def check_hidden_states_output(__UpperCAmelCase		, __UpperCAmelCase		, __UpperCAmelCase ):
       __lowerCamelCase  							=			model_class(__lowercase )
       model.to(__lowercase )
       model.eval()

       with torch.no_grad():
          __lowerCamelCase  							=			model(**self._prepare_for_class(__lowercase		, __lowercase ) )

       __lowerCamelCase  							=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase  							=			['''preactivation''', '''bottleneck''']
    for model_class in self.all_model_classes:
       for layer_type in layers_type:
          __lowerCamelCase  							=			layer_type
          __lowerCamelCase  							=			True
          check_hidden_states_output(__lowercase		, __lowercase		, __lowercase )

          # check that output_hidden_states also work using config
          del inputs_dict["output_hidden_states"]
          __lowerCamelCase  							=			True

          check_hidden_states_output(__lowercase		, __lowercase		, __lowercase )




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



    '''simple docstring'''
    pass




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowercase )




 @slow
 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowerCamelCase  							=			BitModel.from_pretrained(__lowercase )
       self.assertIsNotNone(__lowercase )





def 						a__	(						):
   __lowerCamelCase  							=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
   return image



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




 @cached_property
 def 				lowerCamelCase					(  self ):



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




 @slow
 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__lowercase )

    __lowerCamelCase  							=			self.default_image_processor
    __lowerCamelCase  							=			prepare_img()
    __lowerCamelCase  							=			image_processor(images=__lowercase		, return_tensors='''pt''' ).to(__lowercase )

    # forward pass
    with torch.no_grad():
       __lowerCamelCase  							=			model(**__lowercase )

    # verify the logits
    __lowerCamelCase  							=			torch.Size((1, 1000) )
    self.assertEqual(outputs.logits.shape		, __lowercase )

    __lowerCamelCase  							=			torch.tensor([[-0.6_526, -0.5_263, -1.4_398]] ).to(__lowercase )

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



@require_torch
class        __lowerCAmelCase   (		UpperCAmelCase__     ,		unittest.TestCase      ):
 lowerCAmelCase__				    =     (BitBackbone,) if is_torch_available() else ()
 lowerCAmelCase__				    =     BitConfig

 lowerCAmelCase__				    =     False




 def 				lowerCamelCase					(  self ):



    '''simple docstring'''
    __lowerCamelCase  							=			BitModelTester(self )










import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand



def 	lowerCAmelCase       (						lowerCAmelCase_       )->       Union[str, Any]:
				return EnvironmentCommand()







class  snake_case__(							UpperCAmelCase__							):







						'''simple docstring'''




						@staticmethod
						def   lowercase_       ( __lowercase							)    ->			List[Any]:
										lowerCAmelCase_       :					List[str]			 = parser.add_parser('''env'''							)
										download_parser.set_defaults(func=__lowercase							)




						def   lowercase_       ( self							)    ->			int:
										lowerCAmelCase_       :					Optional[Any]			 = huggingface_hub.__version__

										lowerCAmelCase_       :					str			 = '''not installed'''
										lowerCAmelCase_       :					str			 = '''NA'''
										if is_torch_available():
														import torch

														lowerCAmelCase_       :					Any			 = torch.__version__
														lowerCAmelCase_       :					str			 = torch.cuda.is_available()

										lowerCAmelCase_       :					List[str]			 = '''not installed'''
										if is_transformers_available():
														import transformers

														lowerCAmelCase_       :					Any			 = transformers.__version__

										lowerCAmelCase_       :					Optional[Any]			 = '''not installed'''
										if is_accelerate_available():
														import accelerate

														lowerCAmelCase_       :					List[Any]			 = accelerate.__version__

										lowerCAmelCase_       :					List[str]			 = '''not installed'''
										if is_xformers_available():
														import xformers

														lowerCAmelCase_       :					Optional[Any]			 = xformers.__version__

										lowerCAmelCase_       :					int			 = {
										    '''`diffusers` version''': version,
										    '''Platform''': platform.platform(),
										    '''Python version''': platform.python_version(),
										    '''PyTorch version (GPU?)''': f"""{pt_version} ({pt_cuda_available})""",
										    '''Huggingface_hub version''': hub_version,
										    '''Transformers version''': transformers_version,
										    '''Accelerate version''': accelerate_version,
										    '''xFormers version''': xformers_version,
										    '''Using GPU in script?''': '''<fill in>''',
										    '''Using distributed or parallel set-up in script?''': '''<fill in>''',
										}

										print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'''							)
										print(self.format_dict(__lowercase							)							)

										return info




						@staticmethod
						def   lowercase_       ( __lowercase							)    ->			str:
										return "\n".join([f"""- {prop}: {val}""" for prop, val in d.items()]							) + "\n"