




"""simple docstring"""


import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
					import tensorflow as tf
					from tensorflow.python.framework.errors_impl import ResourceExhaustedError

					from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
					import pyanvml.pyanvml as nvml

A_      			=       logging.get_logger(__name__)


def       UpperCAmelCase__ (snake_case__							:      bool	,     snake_case__							:      bool					):
		"""simple docstring"""

		def run_func(snake_case__							:      Tuple					):
				@wraps(snake_case__					)
				def run_in_eager_mode(*snake_case__							:      str	,     **snake_case__							:      Any					):
						return func(*snake_case__	,     **snake_case__					)

				@wraps(snake_case__					)
				@tf.function(experimental_compile=snake_case__					)
				def run_in_graph_mode(*snake_case__							:      Any	,     **snake_case__							:      Optional[int]					):
						return func(*snake_case__	,     **snake_case__					)

				if do_eager_mode is True:
						if use_xla is not False:
								raise ValueError(
								    """Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."""					)
						return run_in_eager_mode
				else:
						return run_in_graph_mode

		return run_func


def       UpperCAmelCase__ (snake_case__							:      int	,     snake_case__							:      int	,     snake_case__							:      int					):
		"""simple docstring"""

		_snake_case							:	List[str]			=						random.Random()
		_snake_case							:	Optional[int]			=						[rng.randint(0	,     vocab_size - 1					) for i in range(batch_size * sequence_length					)]
		return tf.constant(snake_case__	,     shape=(batch_size, sequence_length)	,     dtype=tf.intaa					)






class       lowercase(  __a				):







	'''simple docstring'''





	lowercase__				      =      42
	lowercase__				      =      42
	lowercase__				      =      "TensorFlow"


	@property
	def 				UpperCamelCase_     (       self:	List[str]	):




			'''simple docstring'''



			return tf.__version__


	def 				UpperCamelCase_     (       self:	List[str],   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			_snake_case							:	List[str]			=						self.args.strategy
			if strategy is None:
					raise ValueError("""A device strategy has to be initialized before using TensorFlow."""	)
			_snake_case							:	Optional[int]			=						self._prepare_inference_func(a_,   a_,   a_	)
			return self._measure_speed(_inference	)


	def 				UpperCamelCase_     (       self:	int,   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			_snake_case							:	Tuple			=						self.args.strategy
			if strategy is None:
					raise ValueError("""A device strategy has to be initialized before using TensorFlow."""	)
			_snake_case							:	Optional[Any]			=						self._prepare_train_func(a_,   a_,   a_	)
			return self._measure_speed(_train	)


	def 				UpperCamelCase_     (       self:	Dict,   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			if self.args.is_gpu:
					tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx],   a_	)
			_snake_case							:	str			=						self.args.strategy
			if strategy is None:
					raise ValueError("""A device strategy has to be initialized before using TensorFlow."""	)
			_snake_case							:	List[str]			=						self._prepare_inference_func(a_,   a_,   a_	)
			return self._measure_memory(_inference	)


	def 				UpperCamelCase_     (       self:	Tuple,   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			if self.args.is_gpu:
					tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx],   a_	)
			_snake_case							:	Dict			=						self.args.strategy
			if strategy is None:
					raise ValueError("""A device strategy has to be initialized before using TensorFlow."""	)

			_snake_case							:	Optional[int]			=						self._prepare_train_func(a_,   a_,   a_	)
			return self._measure_memory(_train	)


	def 				UpperCamelCase_     (       self:	Optional[Any],   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			_snake_case							:	List[Any]			=						self.config_dict[model_name]

			if self.args.fpaa:
					raise NotImplementedError("""Mixed precision is currently not supported."""	)

			_snake_case							:	List[Any]			=						(
			    hasattr(a_,   """architectures"""	)
			    and isinstance(config.architectures,   a_	)
			    and len(config.architectures	) > 0
			)
			if not self.args.only_pretrain_model and has_model_class_in_config:
					try:
							_snake_case							:	str			=						"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
							_snake_case							:	List[Any]			=						__import__("""transformers""",   fromlist=[model_class]	)
							_snake_case							:	Dict			=						getattr(a_,   a_	)
							_snake_case							:	Any			=						model_cls(a_	)
					except ImportError:
							raise ImportError(
							    f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
							    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""	)
			else:
					_snake_case							:	Any			=						TF_MODEL_MAPPING[config.__class__](a_	)

			# encoder-decoder has vocab size saved differently
			_snake_case							:	List[Any]			=						config.vocab_size if hasattr(a_,   """vocab_size"""	) else config.encoder.vocab_size
			_snake_case							:	List[str]			=						random_input_ids(a_,   a_,   a_	)

			@run_with_tf_optimizations(self.args.eager_mode,   self.args.use_xla	)
			def encoder_decoder_forward():
					return model(a_,   decoder_input_ids=a_,   training=a_	)

			@run_with_tf_optimizations(self.args.eager_mode,   self.args.use_xla	)
			def encoder_forward():
					return model(a_,   training=a_	)

			_snake_case							:	Optional[int]			=						encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

			return _inference


	def 				UpperCamelCase_     (       self:	Optional[int],   a_:	str,   a_:	int,   a_:	int	):




			'''simple docstring'''



			_snake_case							:	str			=						self.config_dict[model_name]

			if self.args.eager_mode is not False:
					raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."""	)

			if self.args.fpaa:
					raise NotImplementedError("""Mixed precision is currently not supported."""	)

			_snake_case							:	Tuple			=						(
			    hasattr(a_,   """architectures"""	)
			    and isinstance(config.architectures,   a_	)
			    and len(config.architectures	) > 0
			)
			if not self.args.only_pretrain_model and has_model_class_in_config:
					try:
							_snake_case							:	List[str]			=						"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
							_snake_case							:	str			=						__import__("""transformers""",   fromlist=[model_class]	)
							_snake_case							:	Tuple			=						getattr(a_,   a_	)
							_snake_case							:	Any			=						model_cls(a_	)
					except ImportError:
							raise ImportError(
							    f"{model_class} does not exist. If you just want to test the pretrained model, you might want to"
							    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""	)
			else:
					_snake_case							:	Optional[Any]			=						TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](a_	)

			# encoder-decoder has vocab size saved differently
			_snake_case							:	List[Any]			=						config.vocab_size if hasattr(a_,   """vocab_size"""	) else config.encoder.vocab_size
			_snake_case							:	int			=						random_input_ids(a_,   a_,   a_	)

			@run_with_tf_optimizations(self.args.eager_mode,   self.args.use_xla	)
			def encoder_decoder_train():
					_snake_case							:	Dict			=						model(a_,   decoder_input_ids=a_,   labels=a_,   training=a_	)[0]
					_snake_case							:	str			=						tf.gradients(a_,   model.trainable_variables	)
					return gradients

			@run_with_tf_optimizations(self.args.eager_mode,   self.args.use_xla	)
			def encoder_train():
					_snake_case							:	Optional[Any]			=						model(a_,   labels=a_,   training=a_	)[0]
					_snake_case							:	Optional[Any]			=						tf.gradients(a_,   model.trainable_variables	)
					return gradients

			_snake_case							:	int			=						encoder_decoder_train if config.is_encoder_decoder else encoder_train

			return _train


	def 				UpperCamelCase_     (       self:	Union[str, Any],   a_:	str	):




			'''simple docstring'''



			with self.args.strategy.scope():
					try:
							if self.args.is_tpu or self.args.use_xla:
									# run additional 10 times to stabilize compilation for tpu
									logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation"""	)
									timeit.repeat(a_,   repeat=1,   number=5	)

							# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
							_snake_case							:	Dict			=						timeit.repeat(
							    a_,   repeat=self.args.repeat,   number=10,   )

							return min(a_	) / 10.0
					except ResourceExhaustedError as e:
							self.print_fn(f"Doesn't fit on GPU. {e}"	)


	def 				UpperCamelCase_     (       self:	Optional[Any],   a_:	Callable[[], None]	):




			'''simple docstring'''



			logger.info(
			    """Note that TensorFlow allocates more memory than """
			    """it might need to speed up computation. """
			    """The memory reported here corresponds to the memory """
			    """reported by `nvidia-smi`, which can vary depending """
			    """on total available memory on the GPU that is used."""	)
			with self.args.strategy.scope():
					try:
							if self.args.trace_memory_line_by_line:
									if not self.args.eager_mode:
											raise ValueError(
											    """`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"""
											    """ consumption line by line."""	)
									_snake_case							:	List[Any]			=						start_memory_tracing("""transformers"""	)

							if self.args.is_tpu:
									# tpu
									raise NotImplementedError(
									    """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"""
									    """ with `args.memory=False`"""	)
							elif self.args.is_gpu:
									# gpu
									if not is_pyanvml_available():
											logger.warning(
											    """py3nvml not installed, we won't log GPU memory usage. """
											    """Install py3nvml (pip install py3nvml) to log information about GPU."""	)
											_snake_case							:	Optional[Any]			=						"""N/A"""
									else:
											logger.info(
											    """Measuring total GPU usage on GPU device. Make sure to not have additional processes"""
											    """ running on the same GPU."""	)
											# init nvml
											nvml.nvmlInit()
											func()
											_snake_case							:	List[str]			=						nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
											_snake_case							:	Tuple			=						nvml.nvmlDeviceGetMemoryInfo(a_	)
											_snake_case							:	List[str]			=						meminfo.used
											_snake_case							:	Any			=						Memory(a_	)
											# shutdown nvml
											nvml.nvmlShutdown()
							else:
									# cpu
									if self.args.trace_memory_line_by_line:
											logger.info(
											    """When enabling line by line tracing, the max peak memory for CPU is inaccurate in"""
											    """ TensorFlow."""	)
											_snake_case							:	List[Any]			=						None
									else:
											_snake_case							:	int			=						measure_peak_memory_cpu(a_	)
											_snake_case							:	List[str]			=						Memory(a_	) if isinstance(a_,   a_	) else memory_bytes
							if self.args.trace_memory_line_by_line:
									_snake_case							:	Tuple			=						stop_memory_tracing(a_	)
									if memory is None:
											_snake_case							:	int			=						summary.total
							else:
									_snake_case							:	int			=						None

							return memory, summary
					except ResourceExhaustedError as e:
							self.print_fn(f"Doesn't fit on GPU. {e}"	)
							return "N/A", None








"""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       lowercase:







 '''simple docstring'''





 def __init__(       self:	List[str],   a_:	List[Any],   a_:	str=13,   a_:	Dict=32,   a_:	Union[str, Any]=3,   a_:	Union[str, Any]=4,   a_:	Tuple=[10, 20, 30, 40],   a_:	Dict=[2, 2, 3, 2],   a_:	Tuple=True,   a_:	Optional[Any]=True,   a_:	Any=37,   a_:	Any="gelu",   a_:	int=10,   a_:	Tuple=0.02,   a_:	str=["stage2", "stage3", "stage4"],   a_:	List[str]=[2, 3, 4],   a_:	List[str]=None,   ):




   '''simple docstring'''



   _snake_case							:	int			=						parent
   _snake_case							:	int			=						batch_size
   _snake_case							:	List[Any]			=						image_size
   _snake_case							:	List[str]			=						num_channels
   _snake_case							:	Tuple			=						num_stages
   _snake_case							:	Union[str, Any]			=						hidden_sizes
   _snake_case							:	List[Any]			=						depths
   _snake_case							:	Tuple			=						is_training
   _snake_case							:	List[str]			=						use_labels
   _snake_case							:	Tuple			=						intermediate_size
   _snake_case							:	List[str]			=						hidden_act
   _snake_case							:	Optional[Any]			=						num_labels
   _snake_case							:	Tuple			=						initializer_range
   _snake_case							:	Tuple			=						out_features
   _snake_case							:	Tuple			=						out_indices
   _snake_case							:	Dict			=						scope


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

   _snake_case							:	Optional[Any]			=						self.get_config()

   return config, pixel_values, labels


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   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=a_,   initializer_range=self.initializer_range,   out_features=self.out_features,   out_indices=self.out_indices,   num_labels=self.num_labels,   )


 def 				UpperCamelCase_     (       self:	int,   a_:	Tuple,   a_:	Any,   a_:	Dict	):




   '''simple docstring'''



   _snake_case							:	int			=						ConvNextVaModel(config=a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	Any			=						model(a_	)
   # 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 				UpperCamelCase_     (       self:	Optional[int],   a_:	List[str],   a_:	Tuple,   a_:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						ConvNextVaForImageClassification(a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	Optional[int]			=						model(a_,   labels=a_	)
   self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)	)


 def 				UpperCamelCase_     (       self:	Union[str, Any],   a_:	Tuple,   a_:	Tuple,   a_:	Tuple	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						ConvNextVaBackbone(config=a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	int			=						model(a_	)

   # 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							:	Tuple			=						None
   _snake_case							:	Tuple			=						ConvNextVaBackbone(config=a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	List[Any]			=						model(a_	)

   # 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 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



   _snake_case							:	Dict			=						self.prepare_config_and_inputs()
   _snake_case	,      _snake_case	,      _snake_case							:	Any			=						config_and_inputs
   _snake_case							:	str			=						{"""pixel_values""": pixel_values}
   return config, inputs_dict


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						self.prepare_config_and_inputs()
   _snake_case	,      _snake_case	,      _snake_case							:	List[str]			=						config_and_inputs
   _snake_case							:	Any			=						{"""pixel_values""": pixel_values, """labels""": labels}
   return config, inputs_dict







@require_torch
class       lowercase(  __a ,    __a ,    unittest.TestCase				):







 '''simple docstring'''





 lowercase__				      =      (
     (
         ConvNextVaModel,
         ConvNextVaForImageClassification,
         ConvNextVaBackbone,
     )
     if is_torch_available()
     else ()
 )
 lowercase__				      =      (
     {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
     if is_torch_available()
     else {}
 )

 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						ConvNextVaModelTester(self	)
   _snake_case							:	int			=						ConfigTester(self,   config_class=a_,   has_text_modality=a_,   hidden_size=37	)


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   self.create_and_test_config_common_properties()
   self.config_tester.create_and_test_config_to_json_string()
   self.config_tester.create_and_test_config_to_json_file()
   self.config_tester.create_and_test_config_from_and_save_pretrained()
   self.config_tester.create_and_test_config_with_num_labels()
   self.config_tester.check_config_can_be_init_without_params()
   self.config_tester.check_config_arguments_init()


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   return


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




   '''simple docstring'''



   pass


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




   '''simple docstring'''



   pass


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




   '''simple docstring'''



   pass


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   if not self.model_tester.is_training:
     return

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

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

     _snake_case							:	Tuple			=						model_class(a_	)
     model.to(a_	)
     model.train()
     _snake_case							:	Optional[Any]			=						self._prepare_for_class(a_,   a_,   return_labels=a_	)
     _snake_case							:	Any			=						model(**a_	).loss
     loss.backward()


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   if not self.model_tester.is_training:
     return

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

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

     _snake_case							:	Dict			=						model_class(a_	)
     model.to(a_	)
     model.gradient_checkpointing_enable()
     model.train()
     _snake_case							:	str			=						self._prepare_for_class(a_,   a_,   return_labels=a_	)
     _snake_case							:	Optional[int]			=						model(**a_	).loss
     loss.backward()


 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



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

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

     _snake_case							:	Union[str, Any]			=						["""pixel_values"""]
     self.assertListEqual(arg_names[:1],   a_	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_	)


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   def check_hidden_states_output(a_:	str,   a_:	Tuple,   a_:	Tuple	):
     _snake_case							:	Optional[Any]			=						model_class(a_	)
     model.to(a_	)
     model.eval()

     with torch.no_grad():
       _snake_case							:	Any			=						model(**self._prepare_for_class(a_,   a_	)	)

     _snake_case							:	Optional[int]			=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     _snake_case							:	Optional[int]			=						self.model_tester.num_stages
     self.assertEqual(len(a_	),   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							:	Optional[Any]			=						self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _snake_case							:	Optional[Any]			=						True
     check_hidden_states_output(a_,   a_,   a_	)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     _snake_case							:	List[str]			=						True

     check_hidden_states_output(a_,   a_,   a_	)


 def 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*a_	)


 @slow
 def 				UpperCamelCase_     (       self:	Dict	):




   '''simple docstring'''



   for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:	str			=						ConvNextVaModel.from_pretrained(a_	)
     self.assertIsNotNone(a_	)







def       UpperCAmelCase__ ():
  """simple docstring"""

  _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:	Optional[Any]	):




   '''simple docstring'''



   return AutoImageProcessor.from_pretrained("""facebook/convnextv2-tiny-1k-224"""	) if is_vision_available() else None


 @slow
 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						ConvNextVaForImageClassification.from_pretrained("""facebook/convnextv2-tiny-1k-224"""	).to(a_	)

   _snake_case							:	Union[str, Any]			=						self.default_image_processor
   _snake_case							:	List[Any]			=						prepare_img()
   _snake_case							:	Optional[int]			=						preprocessor(images=a_,   return_tensors="""pt"""	).to(a_	)

   # forward pass
   with torch.no_grad():
     _snake_case							:	Optional[int]			=						model(**a_	)

   # verify the logits
   _snake_case							:	Optional[int]			=						torch.Size((1, 1_000)	)
   self.assertEqual(outputs.logits.shape,   a_	)

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


