
'''simple docstring'''






import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
 from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor




class  UpperCAmelCase__						:



    def __init__(	self      :       Optional[Any],__A      :       Union[str, Any],__A      :       Dict=1_3,__A      :       List[str]=3_2,__A      :       Tuple=3,__A      :       Union[str, Any]=4,__A      :       Optional[int]=[1_0, 2_0, 3_0, 4_0],__A      :       List[Any]=[2, 2, 3, 2],__A      :       int=True,__A      :       Union[str, Any]=True,__A      :       str=3_7,__A      :       Tuple="gelu",__A      :       Tuple=1_0,__A      :       Any=0.02,__A      :       int=["stage2", "stage3", "stage4"],__A      :       List[str]=[2, 3, 4],__A      :       int=None,):
          _lowerCamelCase				:   Optional[Any]								=   parent
          _lowerCamelCase				:   Dict								=   batch_size
          _lowerCamelCase				:   Optional[int]								=   image_size
          _lowerCamelCase				:   List[str]								=   num_channels
          _lowerCamelCase				:   Any								=   num_stages
          _lowerCamelCase				:   List[Any]								=   hidden_sizes
          _lowerCamelCase				:   List[Any]								=   depths
          _lowerCamelCase				:   Optional[int]								=   is_training
          _lowerCamelCase				:   int								=   use_labels
          _lowerCamelCase				:   List[str]								=   intermediate_size
          _lowerCamelCase				:   Any								=   hidden_act
          _lowerCamelCase				:   Optional[int]								=   num_labels
          _lowerCamelCase				:   Optional[int]								=   initializer_range
          _lowerCamelCase				:   List[Any]								=   out_features
          _lowerCamelCase				:   Any								=   out_indices
          _lowerCamelCase				:   Optional[Any]								=   scope



    def   lowerCamelCase_  (	self      :       Union[str, Any]     ):
          _lowerCamelCase				:   Optional[Any]								=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

          _lowerCamelCase				:   str								=   self.get_config()

          return config, pixel_values, labels



    def   lowerCamelCase_  (	self      :       Any     ):
          return ConvNextVaConfig(
              num_channels=self.num_channels,hidden_sizes=self.hidden_sizes,depths=self.depths,num_stages=self.num_stages,hidden_act=self.hidden_act,is_decoder=__UpperCamelCase,initializer_range=self.initializer_range,out_features=self.out_features,out_indices=self.out_indices,num_labels=self.num_labels,)



    def   lowerCamelCase_  (	self      :       List[Any],__A      :       List[str],__A      :       List[str],__A      :       Union[str, Any]     ):
          _lowerCamelCase				:   List[str]								=   ConvNextVaModel(config=__UpperCamelCase     )
          model.to(__UpperCamelCase     )
          model.eval()
          _lowerCamelCase				:   int								=   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 // 3_2, self.image_size // 3_2),)



    def   lowerCamelCase_  (	self      :       Union[str, Any],__A      :       int,__A      :       Optional[int],__A      :       List[Any]     ):
          _lowerCamelCase				:   Tuple								=   ConvNextVaForImageClassification(__UpperCamelCase     )
          model.to(__UpperCamelCase     )
          model.eval()
          _lowerCamelCase				:   str								=   model(__UpperCamelCase,labels=__UpperCamelCase     )
          self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)     )



    def   lowerCamelCase_  (	self      :       Dict,__A      :       Union[str, Any],__A      :       Any,__A      :       List[str]     ):
          _lowerCamelCase				:   Any								=   ConvNextVaBackbone(config=__UpperCamelCase     )
          model.to(__UpperCamelCase     )
          model.eval()
          _lowerCamelCase				:   List[Any]								=   model(__UpperCamelCase     )

          # verify hidden states
          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
          _lowerCamelCase				:   List[str]								=   None
          _lowerCamelCase				:   Union[str, Any]								=   ConvNextVaBackbone(config=__UpperCamelCase     )
          model.to(__UpperCamelCase     )
          model.eval()
          _lowerCamelCase				:   List[str]								=   model(__UpperCamelCase     )

          # 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   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   str								=   self.prepare_config_and_inputs()
          _lowerCamelCase						,		_lowerCamelCase						,		_lowerCamelCase				:   str								=   config_and_inputs
          _lowerCamelCase				:   Dict								=   {"pixel_values": pixel_values}
          return config, inputs_dict



    def   lowerCamelCase_  (	self      :       str     ):
          _lowerCamelCase				:   List[Any]								=   self.prepare_config_and_inputs()
          _lowerCamelCase						,		_lowerCamelCase						,		_lowerCamelCase				:   Tuple								=   config_and_inputs
          _lowerCamelCase				:   Optional[Any]								=   {"pixel_values": pixel_values, "labels": labels}
          return config, inputs_dict




@require_torch
class  UpperCAmelCase__						(       __snake_case						,	__snake_case						,	unittest.TestCase ):
    lowerCAmelCase_				    =		(
        (
            ConvNextVaModel,
            ConvNextVaForImageClassification,
            ConvNextVaBackbone,
        )
        if is_torch_available()
        else ()
    )
    lowerCAmelCase_				    =		(
        {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification}
        if is_torch_available()
        else {}
    )

    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False
    lowerCAmelCase_				    =		False



    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          _lowerCamelCase				:   Tuple								=   ConvNextVaModelTester(self     )
          _lowerCamelCase				:   str								=   ConfigTester(self,config_class=__UpperCamelCase,has_text_modality=__UpperCamelCase,hidden_size=3_7     )



    def   lowerCamelCase_  (	self      :       Tuple     ):
          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   lowerCamelCase_  (	self      :       Any     ):
          return



    @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"     )
    def   lowerCamelCase_  (	self      :       Optional[Any]     ):
          pass



    @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    @unittest.skip(reason="ConvNextV2 does not use feedforward chunking"     )
    def   lowerCamelCase_  (	self      :       Tuple     ):
          pass



    def   lowerCamelCase_  (	self      :       List[Any]     ):


          if not self.model_tester.is_training:
                return

          for model_class in self.all_model_classes:
                _lowerCamelCase						,		_lowerCamelCase				:   str								=   self.model_tester.prepare_config_and_inputs_with_labels()
                _lowerCamelCase				:   List[str]								=   True

                if model_class.__name__ in [
                    *get_values(__UpperCamelCase     ),
                    *get_values(__UpperCamelCase     ),
                ]:
                      continue

                _lowerCamelCase				:   List[str]								=   model_class(__UpperCamelCase     )
                model.to(__UpperCamelCase     )
                model.train()
                _lowerCamelCase				:   List[str]								=   self._prepare_for_class(__UpperCamelCase,__UpperCamelCase,return_labels=__UpperCamelCase     )
                _lowerCamelCase				:   Union[str, Any]								=   model(**__UpperCamelCase     ).loss
                loss.backward()



    def   lowerCamelCase_  (	self      :       Tuple     ):


          if not self.model_tester.is_training:
                return

          for model_class in self.all_model_classes:
                _lowerCamelCase						,		_lowerCamelCase				:   Optional[Any]								=   self.model_tester.prepare_config_and_inputs_with_labels()
                _lowerCamelCase				:   List[str]								=   False
                _lowerCamelCase				:   Optional[Any]								=   True

                if (
                    model_class.__name__
                    in [*get_values(__UpperCamelCase     ), *get_values(__UpperCamelCase     )]
                    or not model_class.supports_gradient_checkpointing
                ):
                      continue

                _lowerCamelCase				:   int								=   model_class(__UpperCamelCase     )
                model.to(__UpperCamelCase     )
                model.gradient_checkpointing_enable()
                model.train()
                _lowerCamelCase				:   Union[str, Any]								=   self._prepare_for_class(__UpperCamelCase,__UpperCamelCase,return_labels=__UpperCamelCase     )
                _lowerCamelCase				:   Optional[Any]								=   model(**__UpperCamelCase     ).loss
                loss.backward()



    def   lowerCamelCase_  (	self      :       str     ):
          _lowerCamelCase						,		_lowerCamelCase				:   Optional[int]								=   self.model_tester.prepare_config_and_inputs_for_common()

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

                _lowerCamelCase				:   Tuple								=   ["pixel_values"]
                self.assertListEqual(arg_names[:1],__UpperCamelCase     )



    def   lowerCamelCase_  (	self      :       Tuple     ):
          _lowerCamelCase				:   int								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCamelCase     )



    def   lowerCamelCase_  (	self      :       Any     ):


          def check_hidden_states_output(__A      :       Union[str, Any],__A      :       Union[str, Any],__A      :       Optional[int]     ):
                _lowerCamelCase				:   Union[str, Any]								=   model_class(__UpperCamelCase     )
                model.to(__UpperCamelCase     )
                model.eval()

                with torch.no_grad():
                      _lowerCamelCase				:   List[Any]								=   model(**self._prepare_for_class(__UpperCamelCase,__UpperCamelCase     )     )

                _lowerCamelCase				:   int								=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                _lowerCamelCase				:   int								=   self.model_tester.num_stages
                self.assertEqual(len(__UpperCamelCase     ),expected_num_stages + 1     )

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

          _lowerCamelCase						,		_lowerCamelCase				:   Any								=   self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                _lowerCamelCase				:   str								=   True
                check_hidden_states_output(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase     )

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

                check_hidden_states_output(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase     )



    def   lowerCamelCase_  (	self      :       List[str]     ):
          _lowerCamelCase				:   List[str]								=   self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase     )



    @slow
    def   lowerCamelCase_  (	self      :       Dict     ):


          for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _lowerCamelCase				:   Any								=   ConvNextVaModel.from_pretrained(__UpperCamelCase     )
                self.assertIsNotNone(__UpperCamelCase     )







def 		A_       (	):



      """simple docstring"""




      _lowerCamelCase				:   Optional[int]								=   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
      return image




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



    @cached_property
    def   lowerCamelCase_  (	self      :       str     ):
          return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"     ) if is_vision_available() else None



    @slow
    def   lowerCamelCase_  (	self      :       Dict     ):
          _lowerCamelCase				:   int								=   ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"     ).to(__UpperCamelCase     )

          _lowerCamelCase				:   Dict								=   self.default_image_processor
          _lowerCamelCase				:   Optional[int]								=   prepare_img()
          _lowerCamelCase				:   Optional[int]								=   preprocessor(images=__UpperCamelCase,return_tensors="pt"     ).to(__UpperCamelCase     )

          # forward pass
          with torch.no_grad():
                _lowerCamelCase				:   int								=   model(**__UpperCamelCase     )

          # verify the logits
          _lowerCamelCase				:   List[Any]								=   torch.Size((1, 1_0_0_0)     )
          self.assertEqual(outputs.logits.shape,__UpperCamelCase     )

          _lowerCamelCase				:   List[str]								=   torch.tensor([0.9996, 0.1966, -0.4386]     ).to(__UpperCamelCase     )
          self.assertTrue(torch.allclose(outputs.logits[0, :3],__UpperCamelCase,atol=1e-4     )     )

'''simple docstring'''






def 		A_       (	_lowerCAmelCase   :    int							):



      """simple docstring"""




      if isinstance(_lowerCAmelCase				,	_lowerCAmelCase							):
            raise TypeError("'float' object cannot be interpreted as an integer"							)
      if isinstance(_lowerCAmelCase				,	_lowerCAmelCase							):
            raise TypeError("'str' object cannot be interpreted as an integer"							)

      if num == 0:
            return "0b0"

      _lowerCamelCase				:   Tuple								=   False

      if num < 0:
            _lowerCamelCase				:   List[Any]								=   True
            _lowerCamelCase				:   int								=   -num

      _lowerCamelCase				:   list[int]								=   []
      while num > 0:
            binary.insert(0				,	num % 2							)
            num >>= 1

      if negative:
            return "-0b" + "".join(str(_lowerCAmelCase							) for e in binary							)

      return "0b" + "".join(str(_lowerCAmelCase							) for e in binary							)


if __name__ == "__main__":
 import doctest

 doctest.testmod()