
'''simple docstring'''
import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


a_											=						logging.getLogger()






@unittest.skip("""Temporarily disable the doc tests."""					)
@require_torch
@require_tf
@slow
class    UpperCAmelCase_				(	unittest.TestCase					):





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ = None ,       lowercase_ = None ,       lowercase_ = None ,       lowercase_ = True ,       ):
     snake_case_ :    Dict     			=						[file for file in os.listdir(lowercase_) if os.path.isfile(os.path.join(lowercase_ ,       lowercase_))]

     if identifier is not None:
         snake_case_ :    Union[str, Any]     			=						[file for file in files if identifier in file]

     if n_identifier is not None:
         if isinstance(lowercase_ ,       lowercase_):
             for n_ in n_identifier:
                 snake_case_ :    Optional[Any]     			=						[file for file in files if n_ not in file]
         else:
             snake_case_ :    Optional[Any]     			=						[file for file in files if n_identifier not in file]

     snake_case_ :    str     			=						ignore_files or []
     ignore_files.append("__init__.py")
     snake_case_ :    str     			=						[file for file in files if file not in ignore_files]

     for file in files:
         # Open all files
         print("Testing" ,       lowercase_)

         if only_modules:
             snake_case_ :    Optional[Any]     			=						file.split(".")[0]
             try:
                 snake_case_ :    int     			=						getattr(lowercase_ ,       lowercase_)
                 snake_case_ :    Dict     			=						doctest.DocTestSuite(lowercase_)
                 snake_case_ :    Dict     			=						unittest.TextTestRunner().run(lowercase_)
                 self.assertIs(len(result.failures) ,       0)
             except AttributeError:
                 logger.info(F'{module_identifier} is not a module.')
         else:
             snake_case_ :    int     			=						doctest.testfile(str(".." / directory / file) ,       optionflags=doctest.ELLIPSIS)
             self.assertIs(result.failed ,       0)





 def        snake_case__		(    self):
     snake_case_ :    List[str]     			=						Path("src/transformers")
     snake_case_ :    Dict     			=						"modeling"
     snake_case_ :    Tuple     			=						[
         "modeling_ctrl.py",
         "modeling_tf_ctrl.py",
     ]
     self.analyze_directory(lowercase_ ,       identifier=lowercase_ ,       ignore_files=lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    str     			=						Path("src/transformers")
     snake_case_ :    Optional[Any]     			=						"tokenization"
     self.analyze_directory(lowercase_ ,       identifier=lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    str     			=						Path("src/transformers")
     snake_case_ :    Union[str, Any]     			=						"configuration"
     self.analyze_directory(lowercase_ ,       identifier=lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    int     			=						Path("src/transformers")
     snake_case_ :    Dict     			=						["configuration", "modeling", "tokenization"]
     self.analyze_directory(lowercase_ ,       n_identifier=lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    Dict     			=						Path("docs/source")
     snake_case_ :    Any     			=						["favicon.ico"]
     self.analyze_directory(lowercase_ ,       ignore_files=lowercase_ ,       only_modules=lowercase_)






'''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 ,       lowercase_ ,       lowercase_=13 ,       lowercase_=32 ,       lowercase_=3 ,       lowercase_=4 ,       lowercase_=[10, 20, 30, 40] ,       lowercase_=[2, 2, 3, 2] ,       lowercase_=True ,       lowercase_=True ,       lowercase_=37 ,       lowercase_="gelu" ,       lowercase_=10 ,       lowercase_=0.02 ,       lowercase_=["stage2", "stage3", "stage4"] ,       lowercase_=[2, 3, 4] ,       lowercase_=None ,       ):
     snake_case_ :    Dict     			=						parent
     snake_case_ :    int     			=						batch_size
     snake_case_ :    List[str]     			=						image_size
     snake_case_ :    Tuple     			=						num_channels
     snake_case_ :    Dict     			=						num_stages
     snake_case_ :    Optional[int]     			=						hidden_sizes
     snake_case_ :    Optional[Any]     			=						depths
     snake_case_ :    Optional[int]     			=						is_training
     snake_case_ :    Any     			=						use_labels
     snake_case_ :    List[str]     			=						intermediate_size
     snake_case_ :    List[str]     			=						hidden_act
     snake_case_ :    Dict     			=						num_labels
     snake_case_ :    Union[str, Any]     			=						initializer_range
     snake_case_ :    int     			=						out_features
     snake_case_ :    List[str]     			=						out_indices
     snake_case_ :    int     			=						scope





 def        snake_case__		(    self):
     snake_case_ :    Any     			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

     snake_case_ :    Tuple     			=						None
     if self.use_labels:
         snake_case_ :    Any     			=						ids_tensor([self.batch_size] ,       self.num_labels)

     snake_case_ :    int     			=						self.get_config()

     return config, pixel_values, labels





 def        snake_case__		(    self):
     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=lowercase_ ,       initializer_range=self.initializer_range ,       out_features=self.out_features ,       out_indices=self.out_indices ,       num_labels=self.num_labels ,       )





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    Dict     			=						ConvNextVaModel(config=lowercase_)
     model.to(lowercase_)
     model.eval()
     snake_case_ :    Dict     			=						model(lowercase_)
     # 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        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    Tuple     			=						ConvNextVaForImageClassification(lowercase_)
     model.to(lowercase_)
     model.eval()
     snake_case_ :    int     			=						model(lowercase_ ,       labels=lowercase_)
     self.parent.assertEqual(result.logits.shape ,       (self.batch_size, self.num_labels))





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ ,       lowercase_):
     snake_case_ :    Tuple     			=						ConvNextVaBackbone(config=lowercase_)
     model.to(lowercase_)
     model.eval()
     snake_case_ :    Any     			=						model(lowercase_)

     # 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
     snake_case_ :    Dict     			=						None
     snake_case_ :    str     			=						ConvNextVaBackbone(config=lowercase_)
     model.to(lowercase_)
     model.eval()
     snake_case_ :    List[str]     			=						model(lowercase_)

     # 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        snake_case__		(    self):
     snake_case_ :    Optional[int]     			=						self.prepare_config_and_inputs()
     snake_case_			, snake_case_			, snake_case_ :    str     			=						config_and_inputs
     snake_case_ :    int     			=						{"pixel_values": pixel_values}
     return config, inputs_dict





 def        snake_case__		(    self):
     snake_case_ :    Union[str, Any]     			=						self.prepare_config_and_inputs()
     snake_case_			, snake_case_			, snake_case_ :    Dict     			=						config_and_inputs
     snake_case_ :    Union[str, Any]     			=						{"pixel_values": pixel_values, "labels": labels}
     return config, inputs_dict






@require_torch
class    UpperCAmelCase_				(	snake_case__    ,						snake_case__    ,						unittest.TestCase					):
 UpperCAmelCase_		    =						(
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 UpperCAmelCase_		    =						(
     {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False
 UpperCAmelCase_		    =						False





 def        snake_case__		(    self):
     snake_case_ :    List[Any]     			=						ConvNextVaModelTester(self)
     snake_case_ :    str     			=						ConfigTester(self ,       config_class=lowercase_ ,       has_text_modality=lowercase_ ,       hidden_size=37)





 def        snake_case__		(    self):
     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):
     return





 @unittest.skip(reason="ConvNextV2 does not use inputs_embeds")
 def        snake_case__		(    self):
     pass





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





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





 def        snake_case__		(    self):
     if not self.model_tester.is_training:
         return

     for model_class in self.all_model_classes:
         snake_case_			, snake_case_ :    Optional[Any]     			=						self.model_tester.prepare_config_and_inputs_with_labels()
         snake_case_ :    Union[str, Any]     			=						True

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

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





 def        snake_case__		(    self):
     if not self.model_tester.is_training:
         return

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

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

         snake_case_ :    Any     			=						model_class(lowercase_)
         model.to(lowercase_)
         model.gradient_checkpointing_enable()
         model.train()
         snake_case_ :    Any     			=						self._prepare_for_class(lowercase_ ,       lowercase_ ,       return_labels=lowercase_)
         snake_case_ :    Optional[int]     			=						model(**lowercase_).loss
         loss.backward()





 def        snake_case__		(    self):
     snake_case_			, snake_case_ :    Dict     			=						self.model_tester.prepare_config_and_inputs_for_common()

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

         snake_case_ :    str     			=						["pixel_values"]
         self.assertListEqual(arg_names[:1] ,       lowercase_)





 def        snake_case__		(    self):
     snake_case_ :    Tuple     			=						self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_)





 def        snake_case__		(    self):
     def check_hidden_states_output(lowercase_ ,       lowercase_ ,       lowercase_):
         snake_case_ :    int     			=						model_class(lowercase_)
         model.to(lowercase_)
         model.eval()

         with torch.no_grad():
             snake_case_ :    int     			=						model(**self._prepare_for_class(lowercase_ ,       lowercase_))

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

         snake_case_ :    Dict     			=						self.model_tester.num_stages
         self.assertEqual(len(lowercase_) ,       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] ,       )

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

     for model_class in self.all_model_classes:
         snake_case_ :    Tuple     			=						True
         check_hidden_states_output(lowercase_ ,       lowercase_ ,       lowercase_)

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

         check_hidden_states_output(lowercase_ ,       lowercase_ ,       lowercase_)





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





 @slow
 def        snake_case__		(    self):
     for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         snake_case_ :    Any     			=						ConvNextVaModel.from_pretrained(lowercase_)
         self.assertIsNotNone(lowercase_)


def 						UpperCamelCase_     (	):
    """simple docstring"""






    snake_case_ :    List[Any]     			=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
    return image






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





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





 @slow
 def        snake_case__		(    self):
     snake_case_ :    List[str]     			=						ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224").to(lowercase_)

     snake_case_ :    List[Any]     			=						self.default_image_processor
     snake_case_ :    str     			=						prepare_img()
     snake_case_ :    Any     			=						preprocessor(images=lowercase_ ,       return_tensors="pt").to(lowercase_)

     # forward pass
     with torch.no_grad():
         snake_case_ :    List[str]     			=						model(**lowercase_)

     # verify the logits
     snake_case_ :    str     			=						torch.Size((1, 10_00))
     self.assertEqual(outputs.logits.shape ,       lowercase_)

     snake_case_ :    str     			=						torch.tensor([0.9_996, 0.1_966, -0.4_386]).to(lowercase_)
     self.assertTrue(torch.allclose(outputs.logits[0, :3] ,       lowercase_ ,       atol=1E-4))




