


# Copyright 2021 The HuggingFace 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 json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


lowerCAmelCase__       :	Any     				=os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
lowerCAmelCase__       :	Union[str, Any]     				=os.path.join(hf_cache_home, 'accelerate')
lowerCAmelCase__       :	Tuple     				=os.path.join(cache_dir, 'default_config.yaml')
lowerCAmelCase__       :	Any     				=os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
				lowerCAmelCase__       :	Tuple     				=default_yaml_config_file
else:
				lowerCAmelCase__       :	List[Any]     				=default_json_config_file






def 		a__       (							A__							):
			if config_file is not None:
						if not os.path.isfile(A__							):
									raise FileNotFoundError(
									    F'''The passed configuration file `{config_file}` does not exist. '''
									    'Please pass an existing file to `accelerate launch`, or use the the default one '
									    'created through `accelerate config` and run `accelerate launch` '
									    'without the `--config_file` argument.'							)
			else:
						SCREAMING_SNAKE_CASE_						:			str       						= default_config_file
			with open(A__,	'r',	encoding='utf-8'							) as f:
						if config_file.endswith('.json'							):
									if (
									    json.load(A__							).get('compute_environment',	ComputeEnvironment.LOCAL_MACHINE							)
									    == ComputeEnvironment.LOCAL_MACHINE
									):
												SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= ClusterConfig
									else:
												SCREAMING_SNAKE_CASE_						:			str       						= SageMakerConfig
									return config_class.from_json_file(json_file=A__							)
						else:
									if (
									    yaml.safe_load(A__							).get('compute_environment',	ComputeEnvironment.LOCAL_MACHINE							)
									    == ComputeEnvironment.LOCAL_MACHINE
									):
												SCREAMING_SNAKE_CASE_						:			List[Any]       						= ClusterConfig
									else:
												SCREAMING_SNAKE_CASE_						:			Tuple       						= SageMakerConfig
									return config_class.from_yaml_file(yaml_file=A__							)







@dataclass
class      __lowercase  :





							"""simple docstring"""







							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		42






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			List[Any]       						= self.__dict__
										# For serialization, it's best to convert Enums to strings (or their underlying value type).
										for key, value in result.items():
													if isinstance(lowerCAmelCase__       ,		lowerCAmelCase__    ):
																SCREAMING_SNAKE_CASE_						:			str       						= value.value
													if isinstance(lowerCAmelCase__       ,		lowerCAmelCase__    ) and not bool(lowerCAmelCase__    ):
																SCREAMING_SNAKE_CASE_						:			Dict       						= None
										SCREAMING_SNAKE_CASE_						:			int       						= {k: v for k, v in result.items() if v is not None}
										return result






							@classmethod
							def  UpperCamelCase__			(	cls       ,		lowerCAmelCase__=None    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			List[str]       						= default_json_config_file if json_file is None else json_file
										with open(lowerCAmelCase__       ,		'r'       ,		encoding='utf-8'    ) as f:
													SCREAMING_SNAKE_CASE_						:			Any       						= json.load(lowerCAmelCase__    )
										if "compute_environment" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			str       						= ComputeEnvironment.LOCAL_MACHINE
										if "mixed_precision" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			Optional[int]       						= 'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if "fp16" in config_dict:  # Convert the config to the new format.
													del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
													SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= config_dict.pop('dynamo_backend'    )
													SCREAMING_SNAKE_CASE_						:			List[Any]       						= {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= False
										return cls(**lowerCAmelCase__    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										with open(lowerCAmelCase__       ,		'w'       ,		encoding='utf-8'    ) as f:
													SCREAMING_SNAKE_CASE_						:			Any       						= json.dumps(self.to_dict()       ,		indent=2       ,		sort_keys=lowerCAmelCase__    ) + '\n'
													f.write(lowerCAmelCase__    )






							@classmethod
							def  UpperCamelCase__			(	cls       ,		lowerCAmelCase__=None    ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_						:			Any       						= default_yaml_config_file if yaml_file is None else yaml_file
										with open(lowerCAmelCase__       ,		'r'       ,		encoding='utf-8'    ) as f:
													SCREAMING_SNAKE_CASE_						:			List[Any]       						= yaml.safe_load(lowerCAmelCase__    )
										if "compute_environment" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			Optional[Any]       						= ComputeEnvironment.LOCAL_MACHINE

										if "mixed_precision" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			List[str]       						= 'fp16' if ('fp16' in config_dict and config_dict['fp16']) else None
										if isinstance(config_dict['mixed_precision']       ,		lowerCAmelCase__    ) and not config_dict["mixed_precision"]:
													SCREAMING_SNAKE_CASE_						:			int       						= 'no'
										if "fp16" in config_dict:  # Convert the config to the new format.
													del config_dict["fp16"]
										if "dynamo_backend" in config_dict:  # Convert the config to the new format.
													SCREAMING_SNAKE_CASE_						:			Any       						= config_dict.pop('dynamo_backend'    )
													SCREAMING_SNAKE_CASE_						:			Dict       						= {} if dynamo_backend == 'NO' else {'dynamo_backend': dynamo_backend}
										if "use_cpu" not in config_dict:
													SCREAMING_SNAKE_CASE_						:			int       						= False
										return cls(**lowerCAmelCase__    )






							def  UpperCamelCase__			(	self       ,		lowerCAmelCase__    ):





										"""simple docstring"""




										with open(lowerCAmelCase__       ,		'w'       ,		encoding='utf-8'    ) as f:
													yaml.safe_dump(self.to_dict()       ,		lowerCAmelCase__    )






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										if isinstance(self.compute_environment       ,		lowerCAmelCase__    ):
													SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= ComputeEnvironment(self.compute_environment    )
										if isinstance(self.distributed_type       ,		lowerCAmelCase__    ):
													if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																SCREAMING_SNAKE_CASE_						:			Dict       						= SageMakerDistributedType(self.distributed_type    )
													else:
																SCREAMING_SNAKE_CASE_						:			str       						= DistributedType(self.distributed_type    )
										if self.dynamo_config is None:
													SCREAMING_SNAKE_CASE_						:			Dict       						= {}







@dataclass
class      __lowercase  (__SCREAMING_SNAKE_CASE   ):





							"""simple docstring"""







							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		0
							_UpperCAmelCase     =		1
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		"static"
							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		"main"

							# args for deepspeed_plugin
							_UpperCAmelCase     =		None
							# args for fsdp
							_UpperCAmelCase     =		None
							# args for megatron_lm
							_UpperCAmelCase     =		None
							# args for ipex
							_UpperCAmelCase     =		None
							# args for TPU
							_UpperCAmelCase     =		False

							# args for TPU pods
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		False
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None

							# args for dynamo
							_UpperCAmelCase     =		None






							def  UpperCamelCase__			(	self    ):





										"""simple docstring"""




										if self.deepspeed_config is None:
													SCREAMING_SNAKE_CASE_						:			Union[str, Any]       						= {}
										if self.fsdp_config is None:
													SCREAMING_SNAKE_CASE_						:			Tuple       						= {}
										if self.megatron_lm_config is None:
													SCREAMING_SNAKE_CASE_						:			str       						= {}
										if self.ipex_config is None:
													SCREAMING_SNAKE_CASE_						:			Optional[int]       						= {}
										return super().__post_init__()







@dataclass
class      __lowercase  (__SCREAMING_SNAKE_CASE   ):





							"""simple docstring"""







							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		42
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		"us-east-1"
							_UpperCAmelCase     =		1
							_UpperCAmelCase     =		"all"
							_UpperCAmelCase     =		f"""accelerate-sagemaker-{num_machines}"""
							_UpperCAmelCase     =		SAGEMAKER_PYTORCH_VERSION
							_UpperCAmelCase     =		SAGEMAKER_TRANSFORMERS_VERSION
							_UpperCAmelCase     =		SAGEMAKER_PYTHON_VERSION
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None
							_UpperCAmelCase     =		None









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__    )





