




import inspect
import unittest

from transformers import RegNetConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

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 RegNetForImageClassification, RegNetModel
      from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor





class     SCREAMING_SNAKE_CASE__		:
     def __init__(						self	:		Union[str, Any]       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		Optional[int]=3       ,						__lowerCamelCase	:		int=32       ,						__lowerCamelCase	:		List[str]=3       ,						__lowerCamelCase	:		str=10       ,						__lowerCamelCase	:		List[str]=[10, 20, 30, 40]       ,						__lowerCamelCase	:		List[str]=[1, 1, 2, 1]       ,						__lowerCamelCase	:		int=True       ,						__lowerCamelCase	:		List[str]=True       ,						__lowerCamelCase	:		Optional[int]="relu"       ,						__lowerCamelCase	:		List[Any]=3       ,						__lowerCamelCase	:		List[Any]=None       ,						):



       """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(__lowerCamelCase						)
     def        A__      (						self	:		str						):



       """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        A__      (						self	:		Union[str, Any]						):



       """simple docstring"""
       return RegNetConfig(
           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       ,						)
     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		Optional[int]       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		List[str]						):



       """simple docstring"""
       lowerCAmelCase__										=      RegNetModel(config=__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()
       lowerCAmelCase__										=      model(__lowerCamelCase						)
       # expected last hidden states: B, C, H // 32, W // 32
       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	:		str       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		Union[str, Any]       ,						__lowerCamelCase	:		Union[str, Any]						):



       """simple docstring"""
       lowerCAmelCase__										=      self.num_labels
       lowerCAmelCase__										=      RegNetForImageClassification(__lowerCamelCase						)
       model.to(__lowerCamelCase						)
       model.eval()
       lowerCAmelCase__										=      model(__lowerCamelCase       ,						labels=__lowerCamelCase						)
       self.parent.assertEqual(result.logits.shape       ,						(self.batch_size, self.num_labels)						)



     def        A__      (						self	:		Optional[int]						):



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





@require_torch
class     SCREAMING_SNAKE_CASE__		(_a    ,					_a    ,					unittest.TestCase			):
     lowercase_ :      Tuple				= (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
     lowercase_ :      Any				= (
         {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
         if is_torch_available()
         else {}
     )

     lowercase_ :      int				= False
     lowercase_ :      Optional[Any]				= False
     lowercase_ :      int				= False
     lowercase_ :      Optional[Any]				= False
     def        A__      (						self	:		Tuple						):



       """simple docstring"""
       lowerCAmelCase__										=      RegNetModelTester(self						)
       lowerCAmelCase__										=      ConfigTester(self       ,						config_class=__lowerCamelCase       ,						has_text_modality=__lowerCamelCase						)
     def        A__      (						self	:		int						):



       """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='''RegNet does not use inputs_embeds'''						)
     def        A__      (						self	:		Any						):



       """simple docstring"""
       pass
     @unittest.skip(reason='''RegNet does not support input and output embeddings'''						)
     def        A__      (						self	:		Optional[int]						):



       """simple docstring"""
       pass
     def        A__      (						self	:		Dict						):



       """simple docstring"""
       lowerCAmelCase__				,      lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         lowerCAmelCase__										=      model_class(__lowerCamelCase						)
         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]       ,						__lowerCamelCase						)
     def        A__      (						self	:		str						):



       """simple docstring"""
       lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase						)
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       lowerCAmelCase__				,      lowerCAmelCase__										=      self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
         lowerCAmelCase__										=      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	:		Optional[int]						):



       """simple docstring"""
       def check_hidden_states_output(__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		Any						):
         lowerCAmelCase__										=      model_class(__lowerCamelCase						)
         model.to(__lowerCamelCase						)
         model.eval()

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

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

         lowerCAmelCase__										=      self.model_tester.num_stages
         self.assertEqual(len(__lowerCamelCase						)       ,						expected_num_stages + 1						)

         # RegNet'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 // 2, self.model_tester.image_size // 2]       ,						)

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

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

           check_hidden_states_output(__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase						)
     def        A__      (						self	:		Any						):



       """simple docstring"""
       lowerCAmelCase__										=      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 REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowerCAmelCase__										=      RegNetModel.from_pretrained(__lowerCamelCase						)
         self.assertIsNotNone(__lowerCamelCase						)



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





@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE__		(unittest.TestCase			):
     @cached_property
     def        A__      (						self	:		List[Any]						):



       """simple docstring"""
       return (
           AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
           if is_vision_available()
           else None
       )



     @slow
     def        A__      (						self	:		Optional[int]						):



       """simple docstring"""
       lowerCAmelCase__										=      RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(__lowerCamelCase						)

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

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

       # verify the logits
       lowerCAmelCase__										=      torch.Size((1, 10_00)						)
       self.assertEqual(outputs.logits.shape       ,						__lowerCamelCase						)

       lowerCAmelCase__										=      torch.tensor([-0.4180, -1.5051, -3.4836]						).to(__lowerCamelCase						)

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







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


__magic_name__  :  Any					=       {
    """configuration_layoutlmv2""": ["""LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LayoutLMv2Config"""],
    """processing_layoutlmv2""": ["""LayoutLMv2Processor"""],
    """tokenization_layoutlmv2""": ["""LayoutLMv2Tokenizer"""],
}

try:
      if not is_tokenizers_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  List[str]					=       ["""LayoutLMv2TokenizerFast"""]

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  Any					=       ["""LayoutLMv2FeatureExtractor"""]
      __magic_name__  :  Any					=       ["""LayoutLMv2ImageProcessor"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __magic_name__  :  Any					=       [
          """LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """LayoutLMv2ForQuestionAnswering""",
          """LayoutLMv2ForSequenceClassification""",
          """LayoutLMv2ForTokenClassification""",
          """LayoutLMv2Layer""",
          """LayoutLMv2Model""",
          """LayoutLMv2PreTrainedModel""",
      ]

if TYPE_CHECKING:
      from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig
      from .processing_layoutlmva import LayoutLMvaProcessor
      from .tokenization_layoutlmva import LayoutLMvaTokenizer

      try:
            if not is_tokenizers_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_layoutlmva import (
                LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST,
                LayoutLMvaForQuestionAnswering,
                LayoutLMvaForSequenceClassification,
                LayoutLMvaForTokenClassification,
                LayoutLMvaLayer,
                LayoutLMvaModel,
                LayoutLMvaPreTrainedModel,
            )
else:
      import sys

      __magic_name__  :  Union[str, Any]					=       _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

