



import inspect
import unittest

from transformers import ViTMSNConfig
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_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 ViTMSNForImageClassification, ViTMSNModel
     from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor



class      _SCREAMING_SNAKE_CASE		:







 '''simple docstring'''

 def __init__(self       :     Union[str, Any] ,				UpperCAmelCase_       :     Any ,				UpperCAmelCase_       :     Tuple=13 ,				UpperCAmelCase_       :     List[Any]=30 ,				UpperCAmelCase_       :     Union[str, Any]=2 ,				UpperCAmelCase_       :     Any=3 ,				UpperCAmelCase_       :     Any=True ,				UpperCAmelCase_       :     Dict=True ,				UpperCAmelCase_       :     List[str]=32 ,				UpperCAmelCase_       :     Any=5 ,				UpperCAmelCase_       :     Optional[Any]=4 ,				UpperCAmelCase_       :     str=37 ,				UpperCAmelCase_       :     str="gelu" ,				UpperCAmelCase_       :     int=0.1 ,				UpperCAmelCase_       :     str=0.1 ,				UpperCAmelCase_       :     Optional[Any]=10 ,				UpperCAmelCase_       :     Union[str, Any]=0.02 ,				UpperCAmelCase_       :     Tuple=None ,				) ->List[Any]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=parent
   lowerCamelCase__:   Optional[int]    						=batch_size
   lowerCamelCase__:   int    						=image_size
   lowerCamelCase__:   int    						=patch_size
   lowerCamelCase__:   Tuple    						=num_channels
   lowerCamelCase__:   List[Any]    						=is_training
   lowerCamelCase__:   Any    						=use_labels
   lowerCamelCase__:   Any    						=hidden_size
   lowerCamelCase__:   Union[str, Any]    						=num_hidden_layers
   lowerCamelCase__:   Union[str, Any]    						=num_attention_heads
   lowerCamelCase__:   Dict    						=intermediate_size
   lowerCamelCase__:   Any    						=hidden_act
   lowerCamelCase__:   Optional[int]    						=hidden_dropout_prob
   lowerCamelCase__:   Optional[int]    						=attention_probs_dropout_prob
   lowerCamelCase__:   Dict    						=type_sequence_label_size
   lowerCamelCase__:   Union[str, Any]    						=initializer_range
   lowerCamelCase__:   List[str]    						=scope

   # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
   lowerCamelCase__:   Optional[int]    						=(image_size // patch_size) ** 2
   lowerCamelCase__:   Optional[Any]    						=num_patches + 1

 def 							SCREAMING_SNAKE_CASE_      (self       :     List[Any]) ->List[str]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowerCamelCase__:   Dict    						=None
   if self.use_labels:
     lowerCamelCase__:   List[Any]    						=ids_tensor([self.batch_size] ,				self.type_sequence_label_size)

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

   return config, pixel_values, labels

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->str:



   '''simple docstring'''



   return ViTMSNConfig(
       image_size=self.image_size ,				patch_size=self.patch_size ,				num_channels=self.num_channels ,				hidden_size=self.hidden_size ,				num_hidden_layers=self.num_hidden_layers ,				num_attention_heads=self.num_attention_heads ,				intermediate_size=self.intermediate_size ,				hidden_act=self.hidden_act ,				hidden_dropout_prob=self.hidden_dropout_prob ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob ,				initializer_range=self.initializer_range ,				)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple ,				UpperCAmelCase_       :     Optional[Any] ,				UpperCAmelCase_       :     int ,				UpperCAmelCase_       :     Optional[int]) ->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=ViTMSNModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Tuple    						=model(UpperCAmelCase_)
   self.parent.assertEqual(result.last_hidden_state.shape ,				(self.batch_size, self.seq_length, self.hidden_size))

 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple ,				UpperCAmelCase_       :     Any ,				UpperCAmelCase_       :     List[Any] ,				UpperCAmelCase_       :     Any) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   Any    						=self.type_sequence_label_size
   lowerCamelCase__:   Optional[int]    						=ViTMSNForImageClassification(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:   Any    						=model(UpperCAmelCase_ ,				labels=UpperCAmelCase_)
   print("Pixel and labels shape: {pixel_values.shape}, {labels.shape}")
   print("Labels: {labels}")
   self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.type_sequence_label_size))

   # test greyscale images
   lowerCamelCase__:   Any    						=1
   lowerCamelCase__:   Dict    						=ViTMSNForImageClassification(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()

   lowerCamelCase__:   int    						=floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
   lowerCamelCase__:   str    						=model(UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.type_sequence_label_size))







 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[Any]) ->Dict:



   '''simple docstring'''



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



@require_torch
class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					,							__SCREAMING_SNAKE_CASE					,							unittest.TestCase					):







 '''simple docstring'''
 lowercase_	=    (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
 lowercase_	=    (
     {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification}
     if is_torch_available()
     else {}
 )

 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False
 lowercase_	=    False

 def 							SCREAMING_SNAKE_CASE_      (self       :     str) ->Dict:



   '''simple docstring'''



   lowerCamelCase__:   int    						=ViTMSNModelTester(self)
   lowerCamelCase__:   str    						=ConfigTester(self ,				config_class=UpperCAmelCase_ ,				has_text_modality=UpperCAmelCase_ ,				hidden_size=37)

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



   '''simple docstring'''



   self.config_tester.run_common_tests()

 @unittest.skip(reason="ViTMSN does not use inputs_embeds")
 def 							SCREAMING_SNAKE_CASE_      (self       :     str) ->Dict:



   '''simple docstring'''



   pass

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



   '''simple docstring'''



   lowerCamelCase__:   str    						=self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     lowerCamelCase__:   Any    						=model_class(UpperCAmelCase_)
     self.assertIsInstance(model.get_input_embeddings() ,				(nn.Module))
     lowerCamelCase__:   Tuple    						=model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(UpperCAmelCase_ ,				nn.Linear))

 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Any:



   '''simple docstring'''



   lowerCamelCase__:   Optional[Any]    						=self.model_tester.prepare_config_and_inputs_for_common()

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

     lowerCamelCase__:   Union[str, Any]    						=["pixel_values"]
     self.assertListEqual(arg_names[:1] ,				UpperCAmelCase_)

 def 							SCREAMING_SNAKE_CASE_      (self       :     Dict) ->int:



   '''simple docstring'''



   lowerCamelCase__:   str    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

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



   '''simple docstring'''



   lowerCamelCase__:   Union[str, Any]    						=self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->Union[str, Any]:



   '''simple docstring'''



   for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__:   Tuple    						=ViTMSNModel.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)





def   lowerCAmelCase_				( )  ->	Any:







  """simple docstring"""





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






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







 '''simple docstring'''

 @cached_property
 def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int]) ->str:



   '''simple docstring'''



   return ViTImageProcessor.from_pretrained("facebook/vit-msn-small") if is_vision_available() else None







 @slow
 def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple) ->List[str]:



   '''simple docstring'''



   torch.manual_seed(2)
   lowerCamelCase__:   List[Any]    						=ViTMSNForImageClassification.from_pretrained("facebook/vit-msn-small").to(UpperCAmelCase_)

   lowerCamelCase__:   str    						=self.default_image_processor
   lowerCamelCase__:   Tuple    						=prepare_img()
   lowerCamelCase__:   List[Any]    						=image_processor(images=UpperCAmelCase_ ,				return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:   List[Any]    						=model(**UpperCAmelCase_)

   # verify the logits
   lowerCamelCase__:   int    						=torch.Size((1, 1_000))
   self.assertEqual(outputs.logits.shape ,				UpperCAmelCase_)

   lowerCamelCase__:   Optional[Any]    						=torch.tensor([-0.0803, -0.4454, -0.2375]).to(UpperCAmelCase_)

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








from __future__ import annotations





def   lowerCAmelCase_				( __a			,					__a			,					__a			,					)  ->	tuple:







  """simple docstring"""





  if (electron_conc, hole_conc, intrinsic_conc).count(0	) != 1:
    raise ValueError("You cannot supply more or less than 2 values"	)
  elif electron_conc < 0:
    raise ValueError("Electron concentration cannot be negative in a semiconductor"	)
  elif hole_conc < 0:
    raise ValueError("Hole concentration cannot be negative in a semiconductor"	)
  elif intrinsic_conc < 0:
    raise ValueError(
        "Intrinsic concentration cannot be negative in a semiconductor"	)
  elif electron_conc == 0:
    return (
        "electron_conc",
        intrinsic_conc**2 / hole_conc,
    )
  elif hole_conc == 0:
    return (
        "hole_conc",
        intrinsic_conc**2 / electron_conc,
    )
  elif intrinsic_conc == 0:
    return (
        "intrinsic_conc",
        (electron_conc * hole_conc) ** 0.5,
    )
  else:
    return (-1, -1)


if __name__ == "__main__":
     import doctest

     doctest.testmod()

