

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,    )							->    Tuple:






     """simple docstring"""






     a__  =parent
     a__  =batch_size
     a__  =image_size
     a__  =num_channels
     a__  =embeddings_size
     a__  =hidden_sizes
     a__  =depths
     a__  =is_training
     a__  =use_labels
     a__  =hidden_act
     a__  =num_labels
     a__  =scope
     a__  =len(lowercase_       )
     a__  =out_features
     a__  =out_indices
     a__  =num_groups



   def  _UpperCAmelCase (				self       )							->    str:






     """simple docstring"""






     a__  =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

     a__  =self.get_config()

     return config, pixel_values, labels



   def  _UpperCAmelCase (				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  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_       )							->    List[Any]:






     """simple docstring"""






     a__  =BitModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =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  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_       )							->    List[Any]:






     """simple docstring"""






     a__  =self.num_labels
     a__  =BitForImageClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    labels=lowercase_       )
     self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.num_labels)       )



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_       )							->    str:






     """simple docstring"""






     a__  =BitBackbone(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =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
     a__  =None
     a__  =BitBackbone(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =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  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






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







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

   '''simple docstring'''




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

   lowerCamelCase__ :	Optional[Any]    =   False
   lowerCamelCase__ :	Any    =   False
   lowerCamelCase__ :	str    =   False
   lowerCamelCase__ :	Dict    =   False
   lowerCamelCase__ :	str    =   False



   def  _UpperCAmelCase (				self       )							->    List[str]:






     """simple docstring"""






     a__  =BitModelTester(self       )
     a__  =ConfigTester(self,    config_class=lowercase_,    has_text_modality=lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Dict:






     """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       )							->    Tuple:






     """simple docstring"""






     return



   @unittest.skip(reason='''Bit does not output attentions'''       )
   def  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






     pass



   @unittest.skip(reason='''Bit does not use inputs_embeds'''       )
   def  _UpperCAmelCase (				self       )							->    Optional[int]:






     """simple docstring"""






     pass



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






     """simple docstring"""






     pass



   def  _UpperCAmelCase (				self       )							->    Union[str, Any]:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()

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

       a__  =['''pixel_values''']
       self.assertListEqual(arg_names[:1],    lowercase_       )



   def  _UpperCAmelCase (				self       )							->    int:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )



   def  _UpperCAmelCase (				self       )							->    str:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_backbone(*lowercase_       )



   def  _UpperCAmelCase (				self       )							->    Optional[int]:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
       a__  =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  _UpperCAmelCase (				self       )							->    Union[str, Any]:






     """simple docstring"""






     def check_hidden_states_output(lowercase_,    lowercase_,    lowercase_       ):
       a__  =model_class(lowercase_       )
       model.to(lowercase_       )
       model.eval()

       with torch.no_grad():
         a__  =model(**self._prepare_for_class(lowercase_,    lowercase_       )       )

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

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

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

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

         check_hidden_states_output(lowercase_,    lowercase_,    lowercase_       )



   @unittest.skip(reason='''Bit does not use feedforward chunking'''       )
   def  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






     pass



   def  _UpperCAmelCase (				self       )							->    Union[str, Any]:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowercase_       )



   @slow
   def  _UpperCAmelCase (				self       )							->    Optional[int]:






     """simple docstring"""






     for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       a__  =BitModel.from_pretrained(lowercase_       )
       self.assertIsNotNone(lowercase_       )





def 			UpperCAmelCase__				(			):





  '''simple docstring'''







  a__  =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  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






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



   @slow
   def  _UpperCAmelCase (				self       )							->    Tuple:






     """simple docstring"""






     a__  =BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(lowercase_       )

     a__  =self.default_image_processor
     a__  =prepare_img()
     a__  =image_processor(images=lowercase_,    return_tensors='''pt'''       ).to(lowercase_       )

     # forward pass
     with torch.no_grad():
       a__  =model(**lowercase_       )

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

     a__  =torch.tensor([[-0.6526, -0.5263, -1.4398]]       ).to(lowercase_       )

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







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

   '''simple docstring'''




   lowerCamelCase__ :	Any    =   (BitBackbone,) if is_torch_available() else ()
   lowerCamelCase__ :	Optional[int]    =   BitConfig

   lowerCamelCase__ :	List[Any]    =   False



   def  _UpperCAmelCase (				self       )							->    str:






     """simple docstring"""






     a__  =BitModelTester(self       )



from __future__ import annotations




def 			UpperCAmelCase__				(			_A      : float	,      _A      : float	,      _A      : float	,      ):





  '''simple docstring'''







  if (stress, tangential_force, area).count(0							) != 1:
    raise ValueError('''You cannot supply more or less than 2 values'''							)
  elif stress < 0:
    raise ValueError('''Stress cannot be negative'''							)
  elif tangential_force < 0:
    raise ValueError('''Tangential Force cannot be negative'''							)
  elif area < 0:
    raise ValueError('''Area cannot be negative'''							)
  elif stress == 0:
    return (
        "stress",
        tangential_force / area,
    )
  elif tangential_force == 0:
    return (
        "tangential_force",
        stress * area,
    )
  else:
    return (
        "area",
        tangential_force / stress,
    )


if __name__ == "__main__":
       import doctest

       doctest.testmod()
