


"""simple docstring"""



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






       def __init__(   self  :    Optional[int]  ,     snake_case__  :    Union[str, Any]  ,     snake_case__  :    Optional[Any]=3  ,     snake_case__  :    int=3_2  ,     snake_case__  :    List[str]=3  ,     snake_case__  :    Any=1_0  ,     snake_case__  :    Optional[int]=[1_0, 2_0, 3_0, 4_0]  ,     snake_case__  :    Any=[1, 1, 2, 1]  ,     snake_case__  :    Optional[Any]=True  ,     snake_case__  :    Any=True  ,     snake_case__  :    Optional[int]="relu"  ,     snake_case__  :    List[Any]=3  ,     snake_case__  :    int=None  ,     ):

              '''simple docstring'''






              lowercase		:Any       							=				parent
              lowercase		:List[str]       							=				batch_size
              lowercase		:Dict       							=				image_size
              lowercase		:Dict       							=				num_channels
              lowercase		:Tuple       							=				embeddings_size
              lowercase		:Any       							=				hidden_sizes
              lowercase		:Any       							=				depths
              lowercase		:Optional[int]       							=				is_training
              lowercase		:int       							=				use_labels
              lowercase		:Tuple       							=				hidden_act
              lowercase		:Union[str, Any]       							=				num_labels
              lowercase		:Any       							=				scope
              lowercase		:int       							=				len(snake_case__				)






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:str       							=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

              lowercase		:int       							=				None
              if self.use_labels:
                     lowercase		:Dict       							=				ids_tensor([self.batch_size]  ,     self.num_labels				)

              lowercase		:str       							=				self.get_config()

              return config, pixel_values, labels






       def  __snake_case						(   self  :    int				):

              '''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  __snake_case						(   self  :    Optional[int]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    List[Any]  ,     snake_case__  :    Dict				):

              '''simple docstring'''






              lowercase		:Optional[Any]       							=				RegNetModel(config=snake_case__				)
              model.to(snake_case__				)
              model.eval()
              lowercase		:Union[str, Any]       							=				model(snake_case__				)
              # 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 // 3_2, self.image_size // 3_2)  ,     )






       def  __snake_case						(   self  :    Union[str, Any]  ,     snake_case__  :    Tuple  ,     snake_case__  :    Any  ,     snake_case__  :    Any				):

              '''simple docstring'''






              lowercase		:int       							=				self.num_labels
              lowercase		:List[str]       							=				RegNetForImageClassification(snake_case__				)
              model.to(snake_case__				)
              model.eval()
              lowercase		:Tuple       							=				model(snake_case__  ,     labels=snake_case__				)
              self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.num_labels)				)







       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              lowercase		:List[Any]       							=				self.prepare_config_and_inputs()
              lowercase							,  lowercase							,  lowercase		:Optional[Any]       							=				config_and_inputs
              lowercase		:Optional[Any]       							=				{'''pixel_values''': pixel_values}
              return config, inputs_dict







@require_torch
class 					__magic_name__		(			__UpperCAmelCase			,						__UpperCAmelCase			,						unittest.TestCase     ):
       __A			:      Union[str, Any]        =   (RegNetModel, RegNetForImageClassification) if is_torch_available() else ()
       __A			:      List[str]        =   (
           {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification}
           if is_torch_available()
           else {}
       )

       __A			:      Any        =   False
       __A			:      int        =   False
       __A			:      Any        =   False
       __A			:      Optional[Any]        =   False






       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              lowercase		:Any       							=				RegNetModelTester(self				)
              lowercase		:int       							=				ConfigTester(self  ,     config_class=snake_case__  ,     has_text_modality=snake_case__				)






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

              '''simple docstring'''






              return






       @unittest.skip(reason='''RegNet does not use inputs_embeds'''				)
       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              pass






       @unittest.skip(reason='''RegNet does not support input and output embeddings'''				)
       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              pass






       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              lowercase							,  lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()

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

                     lowercase		:Dict       							=				['''pixel_values''']
                     self.assertListEqual(arg_names[:1]  ,     snake_case__				)






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*snake_case__				)






       def  __snake_case						(   self  :    Any				):

              '''simple docstring'''






              lowercase							,  lowercase		:List[str]       							=				self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     lowercase		:List[Any]       							=				model_class(config=snake_case__				)
                     for name, module in model.named_modules():
                            if isinstance(snake_case__  ,     (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  __snake_case						(   self  :    str				):

              '''simple docstring'''






              def check_hidden_states_output(snake_case__  :    Optional[int]  ,     snake_case__  :    Optional[int]  ,     snake_case__  :    Dict				):
                     lowercase		:Union[str, Any]       							=				model_class(snake_case__				)
                     model.to(snake_case__				)
                     model.eval()

                     with torch.no_grad():
                            lowercase		:Optional[Any]       							=				model(**self._prepare_for_class(snake_case__  ,     snake_case__				)				)

                     lowercase		:Tuple       							=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                     lowercase		:Any       							=				self.model_tester.num_stages
                     self.assertEqual(len(snake_case__				)  ,     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]  ,     )

              lowercase							,  lowercase		:Union[str, Any]       							=				self.model_tester.prepare_config_and_inputs_for_common()
              lowercase		:Optional[int]       							=				['''basic''', '''bottleneck''']
              for model_class in self.all_model_classes:
                     for layer_type in layers_type:
                            lowercase		:int       							=				layer_type
                            lowercase		:Optional[int]       							=				True
                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)

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

                            check_hidden_states_output(snake_case__  ,     snake_case__  ,     snake_case__				)






       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






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







       @slow
       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     lowercase		:Tuple       							=				RegNetModel.from_pretrained(snake_case__				)
                     self.assertIsNotNone(snake_case__				)







def       lowerCamelCase					()     ->							Dict:
       lowercase		:Any       							=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
       return image




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






       @cached_property
       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






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







       @slow
       def  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]				).to(snake_case__				)

              lowercase		:Optional[int]       							=				self.default_image_processor
              lowercase		:Optional[int]       							=				prepare_img()
              lowercase		:str       							=				image_processor(images=snake_case__  ,     return_tensors='''pt'''				).to(snake_case__				)

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

              # verify the logits
              lowercase		:str       							=				torch.Size((1, 1_0_0_0)				)
              self.assertEqual(outputs.logits.shape  ,     snake_case__				)

              lowercase		:Optional[int]       							=				torch.tensor([-0.41_80, -1.50_51, -3.48_36]				).to(snake_case__				)

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





"""simple docstring"""



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from ..utils import cached_file


# docstyle-ignore
UpperCAmelCase      		=			'''
Human: <<task>>

Assistant: '''


UpperCAmelCase      		=			'''huggingface-tools/default-prompts'''
UpperCAmelCase      		=			{'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''}






def       lowerCamelCase					(a_						:int				,				a_						:str				,				a_						:Dict="run")     ->							Optional[Any]:
       if prompt_or_repo_id is None:
              lowercase		:Tuple       							=				DEFAULT_PROMPTS_REPO

       # prompt is considered a repo ID when it does not contain any kind of space
       if re.search('''\\s'''				,				a_) is not None:
              return prompt_or_repo_id

       lowercase		:List[str]       							=				cached_file(
           a_				,				PROMPT_FILES[mode]				,				repo_type='''dataset'''				,				user_agent={'''agent''': agent_name})
       with open(a_				,				'''r'''				,				encoding='''utf-8''') as f:
              return f.read()

