






'''simple docstring'''



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TFResNetForImageClassification, TFResNetModel
      from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor
class UpperCAmelCase_       :




      """simple docstring"""




      def __init__(			self      :		str  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		str=3  ,   UpperCAmelCase      :		Optional[Any]=32  ,   UpperCAmelCase      :		str=3  ,   UpperCAmelCase      :		List[Any]=10  ,   UpperCAmelCase      :		Optional[Any]=[10, 20, 30, 40]  ,   UpperCAmelCase      :		List[Any]=[1, 1, 2, 1]  ,   UpperCAmelCase      :		List[str]=True  ,   UpperCAmelCase      :		str=True  ,   UpperCAmelCase      :		Optional[int]="relu"  ,   UpperCAmelCase      :		int=3  ,   UpperCAmelCase      :		str=None  ,   )	->	List[str]:


       '''simple docstring'''

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






      def 					A__   (			self      :		int		)	->	Tuple:


       '''simple docstring'''

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

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

       lowercase       : Optional[int]						=self.get_config()

       return config, pixel_values, labels






      def 					A__   (			self      :		List[Any]		)	->	int:


       '''simple docstring'''

       return ResNetConfig(
           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  ,   image_size=self.image_size  ,   )






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		Any		)	->	List[str]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=TFResNetModel(config=UpperCAmelCase		)
       lowercase       : Dict						=model(UpperCAmelCase		)
       # 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      :		Optional[Any]  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		List[Any]		)	->	Optional[int]:


       '''simple docstring'''

       lowercase       : Optional[Any]						=self.num_labels
       lowercase       : Any						=TFResNetForImageClassification(UpperCAmelCase		)
       lowercase       : Tuple						=model(UpperCAmelCase  ,   labels=UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_labels)		)






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


       '''simple docstring'''

       lowercase       : int						=self.prepare_config_and_inputs()
       lowercase	,		lowercase	,		lowercase       : Any						=config_and_inputs
       lowercase       : str						={'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_tf
class UpperCAmelCase_       (     __A					,							__A					,							unittest.TestCase					):




      """simple docstring"""




      UpperCamelCase_             =      (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
      UpperCamelCase_             =      (
          {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
          if is_tf_available()
          else {}
      )

      UpperCamelCase_             =      False
      UpperCamelCase_             =      False
      UpperCamelCase_             =      False
      UpperCamelCase_             =      False
      UpperCamelCase_             =      False






      def 					A__   (			self      :		Optional[Any]		)	->	str:


       '''simple docstring'''

       lowercase       : List[Any]						=TFResNetModelTester(self		)
       lowercase       : Any						=ConfigTester(self  ,   config_class=UpperCAmelCase  ,   has_text_modality=UpperCAmelCase		)






      def 					A__   (			self      :		Dict		)	->	List[Any]:


       '''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      :		Any		)	->	Dict:


       '''simple docstring'''

       return






      @unittest.skip(reason='''ResNet does not use inputs_embeds'''		)
      def 					A__   (			self      :		List[str]		)	->	Union[str, Any]:


       '''simple docstring'''

       pass






      @unittest.skip(reason='''ResNet does not support input and output embeddings'''		)
      def 					A__   (			self      :		List[str]		)	->	str:


       '''simple docstring'''

       pass






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


       '''simple docstring'''

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

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

        lowercase       : int						=['''pixel_values''']
        self.assertListEqual(arg_names[:1]  ,   UpperCAmelCase		)






      def 					A__   (			self      :		int		)	->	Any:


       '''simple docstring'''

       lowercase       : List[Any]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase		)






      def 					A__   (			self      :		List[str]		)	->	Optional[int]:


       '''simple docstring'''

       def check_hidden_states_output(UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		List[Any]		):
        lowercase       : Union[str, Any]						=model_class(UpperCAmelCase		)
        lowercase       : int						=model(**self._prepare_for_class(UpperCAmelCase  ,   UpperCAmelCase		)		)

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

        lowercase       : List[Any]						=self.model_tester.num_stages
        self.assertEqual(len(UpperCAmelCase		)  ,   expected_num_stages + 1		)

        # ResNet'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]  ,   )

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

         # check that output_hidden_states also work using config
         del inputs_dict["output_hidden_states"]
         lowercase       : Union[str, Any]						=True

         check_hidden_states_output(UpperCAmelCase  ,   UpperCAmelCase  ,   UpperCAmelCase		)






      def 					A__   (			self      :		Any		)	->	Dict:


       '''simple docstring'''

       lowercase       : List[str]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase		)






      @slow
      def 					A__   (			self      :		int		)	->	Dict:


       '''simple docstring'''

       for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase       : Dict						=TFResNetModel.from_pretrained(UpperCAmelCase		)
        self.assertIsNotNone(UpperCAmelCase		)





def 				lowercase_					(     )							->   int:



 """simple docstring"""




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





@require_tf
@require_vision
class UpperCAmelCase_       (     unittest.TestCase					):




      """simple docstring"""




      @cached_property
      def 					A__   (			self      :		Union[str, Any]		)	->	str:


       '''simple docstring'''

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






      @slow
      def 					A__   (			self      :		int		)	->	str:


       '''simple docstring'''

       lowercase       : int						=TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

       lowercase       : Optional[Any]						=self.default_image_processor
       lowercase       : Any						=prepare_img()
       lowercase       : Tuple						=image_processor(images=UpperCAmelCase  ,   return_tensors='''tf'''		)

       # forward pass
       lowercase       : List[str]						=model(**UpperCAmelCase		)

       # verify the logits
       lowercase       : Optional[int]						=tf.TensorShape((1, 1000)		)
       self.assertEqual(outputs.logits.shape  ,   UpperCAmelCase		)

       lowercase       : List[str]						=tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]		)

       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()  ,   UpperCAmelCase  ,   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 copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
      import torch


SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)
@dataclass
class UpperCAmelCase_       :




      """simple docstring"""




      def __init__(			self      :		List[Any]  ,   UpperCAmelCase      :		List[Any]=False  ,   UpperCAmelCase      :		Union[str, Any]=False  ,   UpperCAmelCase      :		Union[str, Any]=6.0  ,   UpperCAmelCase      :		Any=None  ,   UpperCAmelCase      :		Optional[Any]=False  ,   UpperCAmelCase      :		List[Any]=False  ,   UpperCAmelCase      :		Dict=None  ,   UpperCAmelCase      :		Tuple="fp4"  ,   UpperCAmelCase      :		str=False  ,   **UpperCAmelCase      :		Union[str, Any]  ,   )	->	str:


       '''simple docstring'''

       lowercase       : Optional[int]						=load_in_abit
       lowercase       : Union[str, Any]						=load_in_abit
       lowercase       : Tuple						=llm_inta_threshold
       lowercase       : Optional[Any]						=llm_inta_skip_modules
       lowercase       : int						=llm_inta_enable_fpaa_cpu_offload
       lowercase       : Dict						=llm_inta_has_fpaa_weight
       lowercase       : str						=bnb_abit_quant_type
       lowercase       : int						=bnb_abit_use_double_quant

       if bnb_abit_compute_dtype is None:
        lowercase       : str						=torch.floataa
       elif isinstance(UpperCAmelCase  ,   UpperCAmelCase		):
        lowercase       : Tuple						=getattr(UpperCAmelCase  ,   UpperCAmelCase		)
       elif isinstance(UpperCAmelCase  ,   torch.dtype		):
        lowercase       : Optional[int]						=bnb_abit_compute_dtype
       else:
        raise ValueError('''bnb_4bit_compute_dtype must be a string or a torch.dtype'''		)

       self.post_init()






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


       '''simple docstring'''

       if not isinstance(self.llm_inta_threshold  ,   UpperCAmelCase		):
        raise ValueError('''llm_int8_threshold must be a float'''		)

       if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules  ,   UpperCAmelCase		):
        raise ValueError('''llm_int8_skip_modules must be a list of strings'''		)
       if not isinstance(self.llm_inta_enable_fpaa_cpu_offload  ,   UpperCAmelCase		):
        raise ValueError('''llm_int8_enable_fp32_cpu_offload must be a boolean'''		)

       if not isinstance(self.llm_inta_has_fpaa_weight  ,   UpperCAmelCase		):
        raise ValueError('''llm_int8_has_fp16_weight must be a boolean'''		)

       if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype  ,   torch.dtype		):
        raise ValueError('''bnb_4bit_compute_dtype must be torch.dtype'''		)

       if not isinstance(self.bnb_abit_quant_type  ,   UpperCAmelCase		):
        raise ValueError('''bnb_4bit_quant_type must be a string'''		)

       if not isinstance(self.bnb_abit_use_double_quant  ,   UpperCAmelCase		):
        raise ValueError('''bnb_4bit_use_double_quant must be a boolean'''		)

       if self.load_in_abit and not version.parse(importlib.metadata.version('''bitsandbytes'''		)		) >= version.parse(
           '''0.39.0'''		):
        raise ValueError(
            '''4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version'''		)






      def 					A__   (			self      :		Any		)	->	Tuple:


       '''simple docstring'''

       return self.load_in_abit or self.load_in_abit






      def 					A__   (			self      :		Tuple		)	->	Any:


       '''simple docstring'''

       if self.load_in_abit:
        return "llm_int8"
       elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
        return "fp4"
       elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
        return "nf4"
       else:
        return None






      @classmethod
      def 					A__   (			cls      :		Union[str, Any]  ,   UpperCAmelCase      :		Optional[Any]  ,   UpperCAmelCase      :		Any  ,   **UpperCAmelCase      :		List[str]		)	->	Tuple:


       '''simple docstring'''

       lowercase       : Dict						=cls(**UpperCAmelCase		)

       lowercase       : Dict						=[]
       for key, value in kwargs.items():
        if hasattr(UpperCAmelCase  ,   UpperCAmelCase		):
         setattr(UpperCAmelCase  ,   UpperCAmelCase  ,   UpperCAmelCase		)
         to_remove.append(UpperCAmelCase		)
       for key in to_remove:
        kwargs.pop(UpperCAmelCase  ,   UpperCAmelCase		)

       if return_unused_kwargs:
        return config, kwargs
       else:
        return config






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, os.PathLike]		)	->	Dict:


       '''simple docstring'''

       with open(UpperCAmelCase  ,   '''w'''  ,   encoding='''utf-8'''		) as writer:
        lowercase       : Any						=self.to_dict()
        lowercase       : List[Any]						=json.dumps(UpperCAmelCase  ,   indent=2  ,   sort_keys=UpperCAmelCase		) + '''\n'''

        writer.write(UpperCAmelCase		)






      def 					A__   (			self      :		Optional[Any]		)	->	Dict[str, Any]:


       '''simple docstring'''

       lowercase       : Tuple						=copy.deepcopy(self.__dict__		)
       lowercase       : Optional[Any]						=str(output['''bnb_4bit_compute_dtype''']		).split('''.'''		)[1]

       return output






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


       '''simple docstring'''

       return f'{self.__class__.__name__} {self.to_json_string()}'






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		bool = True		)	->	str:


       '''simple docstring'''

       if use_diff is True:
        lowercase       : int						=self.to_diff_dict()
       else:
        lowercase       : List[str]						=self.to_dict()
       return json.dumps(UpperCAmelCase  ,   indent=2  ,   sort_keys=UpperCAmelCase		) + "\n"






      def 					A__   (			self      :		Any		)	->	Dict[str, Any]:


       '''simple docstring'''

       lowercase       : Any						=self.to_dict()

       # get the default config dict
       lowercase       : Union[str, Any]						=BitsAndBytesConfig().to_dict()

       lowercase       : int						={}

       # only serialize values that differ from the default config
       for key, value in config_dict.items():
        if value != default_config_dict[key]:
         lowercase       : Dict						=value

       return serializable_config_dict



