





import argparse
import glob
import inspect
import os
import re
import unittest

from get_test_info import get_test_classes

from tests.test_pipeline_mixin import pipeline_test_mapping


UpperCamelCase__          ={}
for task, _ in pipeline_test_mapping.items():
       UpperCamelCase__          ={'pt': None, 'tf': None}


# DO **NOT** add item to this set (unless the reason is approved)
UpperCamelCase__          ={
    'tests/models/esm/test_modeling_esmfold.py',  # The pipeline test mapping is added to `test_modeling_esm.py`
}






def 			lowerCamelCase__	(__lowerCamelCase		):

     if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
          return "pt"
     elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
          return "tf"
     elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
          return "flax"
     else:
          return None






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase		):
     # Use the cached results
     if PIPELINE_TEST_MAPPING[task].get(__lowerCamelCase,				__lowerCamelCase		) is not None:
          return PIPELINE_TEST_MAPPING[task][framework]

     _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							pipeline_test_mapping[task]["test"]
     _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							None

     if framework == "pt":
          _SCREAMING_SNAKE_CASE				:		Tuple  			=							getattr(__lowerCamelCase,				"model_mapping",				__lowerCamelCase		)
     elif framework == "tf":
          _SCREAMING_SNAKE_CASE				:		Tuple  			=							getattr(__lowerCamelCase,				"tf_model_mapping",				__lowerCamelCase		)

     if mapping is not None:
          _SCREAMING_SNAKE_CASE				:		List[Any]  			=							dict(mapping.items()		)

     # cache the results
     _SCREAMING_SNAKE_CASE				:		int  			=							mapping
     return mapping






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		int  			=							get_framework(__lowerCamelCase		)
     if framework is None:
          return None
     _SCREAMING_SNAKE_CASE				:		Any  			=							get_mapping_for_task(__lowerCamelCase,				__lowerCamelCase		)
     if mapping is None:
          return None

     _SCREAMING_SNAKE_CASE				:		Tuple  			=							list({model_class.config_class for model_class in test_class.all_model_classes}		)
     if len(__lowerCamelCase		) != 1:
          raise ValueError("There should be exactly one configuration class from `test_class.all_model_classes`."		)

     # This could be a list/tuple of model classes, but it's rare.
     _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							mapping.get(config_classes[0],				__lowerCamelCase		)
     if isinstance(__lowerCamelCase,				(tuple, list)		):
          _SCREAMING_SNAKE_CASE				:		List[str]  			=							sorted(__lowerCamelCase,				key=lambda __lowerCamelCase		: x.__name__		)

     return model_class






def 			lowerCamelCase__	(__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		Any  			=							[(task, get_model_for_pipeline_test(__lowerCamelCase,				__lowerCamelCase		)) for task in pipeline_test_mapping]
     _SCREAMING_SNAKE_CASE				:		List[str]  			=							sorted([(task, model) for task, model in mapping if model is not None],				key=lambda __lowerCamelCase		: x[0]		)

     return dict(__lowerCamelCase		)






def 			lowerCamelCase__	(__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		str  			=							get_framework(__lowerCamelCase		)
     if framework == "pt":
          _SCREAMING_SNAKE_CASE				:		Tuple  			=							"torch"
     _SCREAMING_SNAKE_CASE				:		List[str]  			=							"{}"

     _SCREAMING_SNAKE_CASE				:		int  			=							get_pipeline_model_mapping(__lowerCamelCase		)
     if len(__lowerCamelCase		) == 0:
          return ""

     _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							[]
     for task, model_classes in mapping.items():
          if isinstance(__lowerCamelCase,				(tuple, list)		):
               # A list/tuple of model classes
               _SCREAMING_SNAKE_CASE				:		Any  			=							"(" + ", ".join([x.__name__ for x in model_classes]		) + ")"
          else:
               # A single model class
               _SCREAMING_SNAKE_CASE				:		List[Any]  			=							model_classes.__name__
          texts.append(f"""\"{task}\": {value}"""		)
     _SCREAMING_SNAKE_CASE				:		Dict  			=							"{" + ", ".join(__lowerCamelCase		) + "}"
     _SCREAMING_SNAKE_CASE				:		Any  			=							f"""pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}"""

     return text






def 			lowerCamelCase__	(__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		Any  			=							{"ModelTesterMixin", "TFModelTesterMixin", "FlaxModelTesterMixin"}
     if not issubclass(__lowerCamelCase,				unittest.TestCase		):
          return False
     return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__]		)		) > 0






def 			lowerCamelCase__	(__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							[x for x in get_test_classes(__lowerCamelCase		) if is_valid_test_class(__lowerCamelCase		)]

     _SCREAMING_SNAKE_CASE				:		str  			=							None
     for test_class in test_classes:
          # If a test class has defined `pipeline_model_mapping`, let's take it
          if getattr(__lowerCamelCase,				"pipeline_model_mapping",				__lowerCamelCase		) is not None:
               _SCREAMING_SNAKE_CASE				:		int  			=							test_class
               break
    # Take the test class with the shortest name (just a heuristic)
     if target_test_class is None and len(__lowerCamelCase		) > 0:
          _SCREAMING_SNAKE_CASE				:		Dict  			=							sorted(__lowerCamelCase,				key=lambda __lowerCamelCase		: (len(x.__name__		), x.__name__)		)[0]

     return target_test_class






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase,				__lowerCamelCase		):
     _SCREAMING_SNAKE_CASE				:		int  			=							start_idx
     for idx, line in enumerate(lines[start_idx:]		):
          _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							len(__lowerCamelCase		) - len(line.lstrip()		)
          if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"):
               _SCREAMING_SNAKE_CASE				:		int  			=							start_idx + idx
          elif idx > 0 and indent <= indent_level:
               # Outside the definition block of `pipeline_model_mapping`
               break

     return end_idx






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase=False		):
     if getattr(__lowerCamelCase,				"pipeline_model_mapping",				__lowerCamelCase		) is not None:
          if not overwrite:
               return "", -1

     _SCREAMING_SNAKE_CASE				:		Tuple  			=							get_pipeline_model_mapping_string(__lowerCamelCase		)
     if len(__lowerCamelCase		) == 0:
          return "", -1
     _SCREAMING_SNAKE_CASE				:		Tuple  			=							line_to_add + "\n"

     # The code defined the class `test_class`
     _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE				:		Dict  			=							inspect.getsourcelines(__lowerCamelCase		)
     # `inspect` gives the code for an object, including decorator(s) if any.
     # We (only) need the exact line of the class definition.
     for idx, line in enumerate(__lowerCamelCase		):
          if line.lstrip().startswith("class "		):
               _SCREAMING_SNAKE_CASE				:		int  			=							class_lines[idx:]
               class_start_line_no += idx
               break
     _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							class_start_line_no + len(__lowerCamelCase		) - 1

     # The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or
     # `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last
     # block that appears in a `test_class`.
     _SCREAMING_SNAKE_CASE				:		str  			=							None
     # The indent level of the line at `class_lines[start_idx]` (if defined)
     _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							0
     # To record if `pipeline_model_mapping` is found in `test_class`.
     _SCREAMING_SNAKE_CASE				:		int  			=							None
     for idx, line in enumerate(__lowerCamelCase		):
          if line.strip().startswith("all_model_classes = "		):
               _SCREAMING_SNAKE_CASE				:		str  			=							len(__lowerCamelCase		) - len(line.lstrip()		)
               _SCREAMING_SNAKE_CASE				:		Any  			=							idx
          elif line.strip().startswith("all_generative_model_classes = "		):
               _SCREAMING_SNAKE_CASE				:		Any  			=							len(__lowerCamelCase		) - len(line.lstrip()		)
               _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							idx
          elif line.strip().startswith("pipeline_model_mapping = "		):
               _SCREAMING_SNAKE_CASE				:		List[Any]  			=							len(__lowerCamelCase		) - len(line.lstrip()		)
               _SCREAMING_SNAKE_CASE				:		Any  			=							idx
               _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							line
               break

     if start_idx is None:
          return "", -1
     # Find the ending index (inclusive) of the above found block.
     _SCREAMING_SNAKE_CASE				:		int  			=							find_block_ending(__lowerCamelCase,				__lowerCamelCase,				__lowerCamelCase		)

     # Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use
     # `is_timm_available()` instead of `is_torch_available()`.
     # Keep leading and trailing whitespaces
     _SCREAMING_SNAKE_CASE				:		Tuple  			=							re.compile(R"\s(is_\S+?_available\(\))\s"		)
     for line in class_lines[start_idx : end_idx + 1]:
          _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							r.search(__lowerCamelCase		)
          if backend_condition is not None:
               # replace the leading and trailing whitespaces to the space character " ".
               _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							" " + backend_condition[0][1:-1] + " "
               _SCREAMING_SNAKE_CASE				:		List[str]  			=							r.sub(__lowerCamelCase,				__lowerCamelCase		)
               break

     if def_line is None:
          # `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of
          # `all_model_classes` or `all_generative_model_classes`.
          _SCREAMING_SNAKE_CASE				:		Any  			=							end_idx
     else:
          # `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index.
          _SCREAMING_SNAKE_CASE				:		Tuple  			=							start_idx - 1
          # mark the lines of the currently existing `pipeline_model_mapping` to be removed.
          for idx in range(__lowerCamelCase,				end_idx + 1		):
               # These lines are going to be removed before writing to the test file.
               _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							None  # noqa

    # Make sure the test class is a subclass of `PipelineTesterMixin`.
     _SCREAMING_SNAKE_CASE				:		List[Any]  			=							[x.__name__ for x in test_class.__bases__]
     if "PipelineTesterMixin" not in parent_classes:
          # Put `PipelineTesterMixin` just before `unittest.TestCase`
          _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							[x for x in parent_classes if x != "TestCase"] + ["PipelineTesterMixin"]
          if "TestCase" in parent_classes:
               # Here we **assume** the original string is always with `unittest.TestCase`.
               _parent_classes.append("unittest.TestCase"		)
          _SCREAMING_SNAKE_CASE				:		List[str]  			=							", ".join(_parent_classes		)
          for idx, line in enumerate(__lowerCamelCase		):
               # Find the ending of the declaration of `test_class`
               if line.strip().endswith("):"		):
                    # mark the lines of the declaration of `test_class` to be removed
                    for _idx in range(idx + 1		):
                         _SCREAMING_SNAKE_CASE				:		Tuple  			=							None  # noqa
                    break
        # Add the new, one-line, class declaration for `test_class`
          _SCREAMING_SNAKE_CASE				:		Any  			=							f"""class {test_class.__name__}({parent_classes}):\n"""

     # Add indentation
     _SCREAMING_SNAKE_CASE				:		Tuple  			=							" " * indent_level + line_to_add
     # Insert `pipeline_model_mapping` to `class_lines`.
     # (The line at `target_idx` should be kept by definition!)
     _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :]
     # Remove the lines that are marked to be removed
     _SCREAMING_SNAKE_CASE				:		List[Any]  			=							[x for x in class_lines if x is not None]

     # Move from test class to module (in order to write to the test file)
     _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							inspect.getsourcelines(inspect.getmodule(__lowerCamelCase		)		)[0]
     # Be careful with the 1-off between line numbers and array indices
     _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:]
     _SCREAMING_SNAKE_CASE				:		Dict  			=							"".join(__lowerCamelCase		)

     _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							inspect.getsourcefile(__lowerCamelCase		)
     with open(__lowerCamelCase,				"w",				encoding="UTF-8",				newline="\n"		) as fp:
          fp.write(__lowerCamelCase		)

     return line_to_add






def 			lowerCamelCase__	(__lowerCamelCase,				__lowerCamelCase=False		):
     _SCREAMING_SNAKE_CASE				:		str  			=							find_test_class(__lowerCamelCase		)
     if test_class:
          add_pipeline_model_mapping(__lowerCamelCase,				overwrite=__lowerCamelCase		)


if __name__ == "__main__":
       UpperCamelCase__          =argparse.ArgumentParser()
       parser.add_argument(
           '--test_file', type=str, help='A path to the test file, starting with the repository\'s `tests` directory.'
       )
       parser.add_argument(
           '--all',
           action='store_true',
           help='If to check and modify all test files.',
       )
       parser.add_argument(
           '--overwrite',
           action='store_true',
           help='If to overwrite a test class if it has already defined `pipeline_model_mapping`.',
       )
       UpperCamelCase__          =parser.parse_args()

       if not args.all and not args.test_file:
              raise ValueError('Please specify either `test_file` or pass `--all` to check/modify all test files.')
       elif args.all and args.test_file:
              raise ValueError('Only one of `--test_file` and `--all` could be specified.')

       UpperCamelCase__          =[]
       if args.test_file:
              UpperCamelCase__          =[args.test_file]
       else:
              UpperCamelCase__          =os.path.join('tests', 'models', '**', 'test_modeling_*.py')
              for test_file in glob.glob(pattern):
                     # `Flax` is not concerned at this moment
                     if not test_file.startswith('test_modeling_flax_'):
                            test_files.append(test_file)

       for test_file in test_files:
              if test_file in TEST_FILE_TO_IGNORE:
                     print(f"[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.")
                     continue
              add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite)



import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch
				from torch import nn

				from transformers import (
				    MODEL_MAPPING,
				    DataaVecVisionForImageClassification,
				    DataaVecVisionForSemanticSegmentation,
				    DataaVecVisionModel,
				)
				from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import BeitImageProcessor







class      __lowercase  :





							"""simple docstring"""







							def __init__(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__=1_0_0       ,		lowerCAmelCase__=1_3       ,		lowerCAmelCase__=3_0       ,		lowerCAmelCase__=2       ,		lowerCAmelCase__=3       ,		lowerCAmelCase__=True       ,		lowerCAmelCase__=True       ,		lowerCAmelCase__=3_2       ,		lowerCAmelCase__=4       ,		lowerCAmelCase__=4       ,		lowerCAmelCase__=3_7       ,		lowerCAmelCase__="gelu"       ,		lowerCAmelCase__=0.1       ,		lowerCAmelCase__=0.1       ,		lowerCAmelCase__=1_0       ,		lowerCAmelCase__=0.02       ,		lowerCAmelCase__=3       ,		lowerCAmelCase__=None       ,		lowerCAmelCase__=[0, 1, 2, 3]       ,		):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Tuple       						= parent
										SCREAMING_SNAKE_CASE_						:			Tuple       						= 1_0_0
										SCREAMING_SNAKE_CASE_						:			int       						= batch_size
										SCREAMING_SNAKE_CASE_						:			str       						= image_size
										SCREAMING_SNAKE_CASE_						:			str       						= patch_size
										SCREAMING_SNAKE_CASE_						:			str       						= num_channels
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= is_training
										SCREAMING_SNAKE_CASE_						:			Any       						= use_labels
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= hidden_size
										SCREAMING_SNAKE_CASE_						:			Tuple       						= num_hidden_layers
										SCREAMING_SNAKE_CASE_						:			Dict       						= num_attention_heads
										SCREAMING_SNAKE_CASE_						:			Any       						= intermediate_size
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= hidden_act
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= hidden_dropout_prob
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE_						:			Tuple       						= type_sequence_label_size
										SCREAMING_SNAKE_CASE_						:			str       						= initializer_range
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= scope
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= out_indices
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= num_labels

										# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										SCREAMING_SNAKE_CASE_						:			List[str]       						= (image_size // patch_size) ** 2
										SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= num_patches + 1






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Dict       						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= None
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= None
										if self.use_labels:
													SCREAMING_SNAKE_CASE_						:			List[str]       						= ids_tensor([self.batch_size]       ,		self.type_sequence_label_size    )
													SCREAMING_SNAKE_CASE_						:			Tuple       						= ids_tensor([self.batch_size, self.image_size, self.image_size]       ,		self.num_labels    )

										SCREAMING_SNAKE_CASE_						:			str       						= self.get_config()

										return config, pixel_values, labels, pixel_labels






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										return DataaVecVisionConfig(
										    vocab_size=self.vocab_size       ,		image_size=self.image_size       ,		patch_size=self.patch_size       ,		num_channels=self.num_channels       ,		hidden_size=self.hidden_size       ,		num_hidden_layers=self.num_hidden_layers       ,		num_attention_heads=self.num_attention_heads       ,		intermediate_size=self.intermediate_size       ,		hidden_act=self.hidden_act       ,		hidden_dropout_prob=self.hidden_dropout_prob       ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,		is_decoder=lowerCAmelCase__       ,		initializer_range=self.initializer_range       ,		out_indices=self.out_indices       ,		)






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= DataaVecVisionModel(config=lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			Dict       						= model(lowerCAmelCase__    )
										# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= (self.image_size // self.patch_size) ** 2
										self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, num_patches + 1, self.hidden_size)    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= self.type_sequence_label_size
										SCREAMING_SNAKE_CASE_						:			Tuple       						= DataaVecVisionForImageClassification(lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			int       						= model(lowerCAmelCase__       ,		labels=lowerCAmelCase__    )
										self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size)    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= self.num_labels
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= DataaVecVisionForSemanticSegmentation(lowerCAmelCase__    )
										model.to(lowerCAmelCase__    )
										model.eval()
										SCREAMING_SNAKE_CASE_						:			Dict       						= model(lowerCAmelCase__    )
										self.parent.assertEqual(
										    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= model(lowerCAmelCase__       ,		labels=lowerCAmelCase__    )
										self.parent.assertEqual(
										    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




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







@require_torch
class      __lowercase  (__SCREAMING_SNAKE_CASE     ,    __SCREAMING_SNAKE_CASE     ,    unittest.TestCase   ):





							"""simple docstring"""







							_UpperCAmelCase     =		(
							    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase     =		(
							    {
							        """feature-extraction""": DataaVecVisionModel,
							        """image-classification""": DataaVecVisionForImageClassification,
							        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		False






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Tuple       						= DataaVecVisionModelTester(self    )
										SCREAMING_SNAKE_CASE_						:			int       						= ConfigTester(
										    self       ,		config_class=lowerCAmelCase__       ,		has_text_modality=lowerCAmelCase__       ,		hidden_size=3_7    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										self.config_tester.run_common_tests()






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										pass






							@require_torch_multi_gpu
							@unittest.skip(
							    reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'    )
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										pass






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			Dict       						= self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= model_class(lowerCAmelCase__    )
													self.assertIsInstance(model.get_input_embeddings()       ,		(nn.Module)    )
													SCREAMING_SNAKE_CASE_						:			List[str]       						= model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCAmelCase__       ,		nn.Linear    )    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			str       						= self.model_tester.prepare_config_and_inputs_for_common()

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

													SCREAMING_SNAKE_CASE_						:			Optional[int]       						= ['pixel_values']
													self.assertListEqual(arg_names[:1]       ,		lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			int       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			str       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_segmentation(*lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										if not self.model_tester.is_training:
													return

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

										for model_class in self.all_model_classes:
													if model_class in [*get_values(lowerCAmelCase__    )]:
																continue

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






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			Any       						= self.model_tester.prepare_config_and_inputs_for_common()
										if not self.model_tester.is_training:
													return

										SCREAMING_SNAKE_CASE_						:			Tuple       						= False
										SCREAMING_SNAKE_CASE_						:			Any       						= True

										for model_class in self.all_model_classes:
													if model_class in [*get_values(lowerCAmelCase__    )] or not model_class.supports_gradient_checkpointing:
																continue
													# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
													# this can then be incorporated into _prepare_for_class in test_modeling_common.py
													elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
																SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			str       						= inputs_dict['pixel_values'].shape
																SCREAMING_SNAKE_CASE_						:			Optional[int]       						= torch.zeros(
																    [self.model_tester.batch_size, height, width]       ,		device=lowerCAmelCase__    ).long()
													SCREAMING_SNAKE_CASE_						:			Tuple       						= model_class(lowerCAmelCase__    )
													model.gradient_checkpointing_enable()
													model.to(lowerCAmelCase__    )
													model.train()
													SCREAMING_SNAKE_CASE_						:			str       						= self._prepare_for_class(lowerCAmelCase__       ,		lowerCAmelCase__       ,		return_labels=lowerCAmelCase__    )
													SCREAMING_SNAKE_CASE_						:			Dict       						= model(**lowerCAmelCase__    ).loss
													loss.backward()






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						,	SCREAMING_SNAKE_CASE_						:			List[Any]       						= self.model_tester.prepare_config_and_inputs_for_common()

										SCREAMING_SNAKE_CASE_						:			str       						= _config_zero_init(lowerCAmelCase__    )
										for model_class in self.all_model_classes:
													SCREAMING_SNAKE_CASE_						:			List[Any]       						= model_class(config=lowerCAmelCase__    )
													for name, param in model.named_parameters():
																# we skip lambda parameters as these require special initial values
																# determined by config.layer_scale_init_value
																if "lambda" in name:
																			continue
																if param.requires_grad:
																			self.assertIn(
																			    ((param.data.mean() * 1E9).round() / 1E9).item()       ,		[0.0, 1.0]       ,		msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''       ,		)






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__=2E-4       ,		lowerCAmelCase__="outputs"       ,		lowerCAmelCase__=None    ):





										"""simple docstring"""




										super().check_pt_tf_outputs(lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__       ,		lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			List[str]       						= self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__    )






							@slow
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													SCREAMING_SNAKE_CASE_						:			Any       						= DataaVecVisionModel.from_pretrained(lowerCAmelCase__    )
													self.assertIsNotNone(lowerCAmelCase__    )







def 		a__       (							):
			SCREAMING_SNAKE_CASE_						:			List[Any]       						= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
			return image







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





							"""simple docstring"""







							@cached_property
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										return (
										    BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'    ) if is_vision_available() else None
										)






							@slow
							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'    ).to(
										    lowerCAmelCase__    )

										SCREAMING_SNAKE_CASE_						:			Dict       						= self.default_image_processor
										SCREAMING_SNAKE_CASE_						:			List[Any]       						= prepare_img()
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= image_processor(images=lowerCAmelCase__       ,		return_tensors='pt'    ).to(lowerCAmelCase__    )

										# forward pass
										with torch.no_grad():
													SCREAMING_SNAKE_CASE_						:			List[str]       						= model(**lowerCAmelCase__    )
										SCREAMING_SNAKE_CASE_						:			Optional[int]       						= outputs.logits

										# verify the logits
										SCREAMING_SNAKE_CASE_						:			Tuple       						= torch.Size((1, 1_0_0_0)    )
										self.assertEqual(logits.shape       ,		lowerCAmelCase__    )

										SCREAMING_SNAKE_CASE_						:			Any       						= torch.tensor([0.3_277, -0.1_395, 0.0_911]    ).to(lowerCAmelCase__    )

										self.assertTrue(torch.allclose(logits[0, :3]       ,		lowerCAmelCase__       ,		atol=1E-4    )    )

										SCREAMING_SNAKE_CASE_						:			Tuple       						= [model.config.labelaid[i] for i in ['remote control, remote', 'tabby, tabby cat']]
										self.assertEqual(logits[0].topk(2    ).indices.cpu().tolist()       ,		lowerCAmelCase__    )





