'''simple docstring'''

from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
  import tensorflow as tf

  from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel



@require_tf
class 			UpperCAmelCase  :





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    PegasusConfig
       SCREAMING_SNAKE_CASE							=    {}
       SCREAMING_SNAKE_CASE							=    '''gelu'''

       def __init__(						self	,   __lowerCAmelCase	,   __lowerCAmelCase=13	,   __lowerCAmelCase=7	,   __lowerCAmelCase=True	,   __lowerCAmelCase=False	,   __lowerCAmelCase=99	,   __lowerCAmelCase=32	,   __lowerCAmelCase=2	,   __lowerCAmelCase=4	,   __lowerCAmelCase=37	,   __lowerCAmelCase=0.1	,   __lowerCAmelCase=0.1	,   __lowerCAmelCase=40	,   __lowerCAmelCase=2	,   __lowerCAmelCase=1	,   __lowerCAmelCase=0	,   )  ->  Optional[int]:
        lowercase__				:    Union[str, Any]  =					parent
        lowercase__				:    List[Any]  =					batch_size
        lowercase__				:    Dict  =					seq_length
        lowercase__				:    int  =					is_training
        lowercase__				:    Optional[int]  =					use_labels
        lowercase__				:    str  =					vocab_size
        lowercase__				:    Optional[Any]  =					hidden_size
        lowercase__				:    Optional[int]  =					num_hidden_layers
        lowercase__				:    str  =					num_attention_heads
        lowercase__				:    str  =					intermediate_size

        lowercase__				:    List[str]  =					hidden_dropout_prob
        lowercase__				:    Dict  =					attention_probs_dropout_prob
        lowercase__				:    Optional[Any]  =					max_position_embeddings
        lowercase__				:    Optional[Any]  =					eos_token_id
        lowercase__				:    Dict  =					pad_token_id
        lowercase__				:    Optional[Any]  =					bos_token_id

       def _lowerCAmelCase(						self )  ->  Any:
        lowercase__				:    List[Any]  =					ids_tensor([self.batch_size, self.seq_length - 1]	,   self.vocab_size )
        lowercase__				:    List[str]  =					tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )	,   1 )
        lowercase__				:    Union[str, Any]  =					tf.concat([input_ids, eos_tensor]	,   axis=1 )

        lowercase__				:    List[str]  =					ids_tensor([self.batch_size, self.seq_length]	,   self.vocab_size )

        lowercase__				:    List[str]  =					self.config_cls(
            vocab_size=self.vocab_size	,   d_model=self.hidden_size	,   encoder_layers=self.num_hidden_layers	,   decoder_layers=self.num_hidden_layers	,   encoder_attention_heads=self.num_attention_heads	,   decoder_attention_heads=self.num_attention_heads	,   encoder_ffn_dim=self.intermediate_size	,   decoder_ffn_dim=self.intermediate_size	,   dropout=self.hidden_dropout_prob	,   attention_dropout=self.attention_probs_dropout_prob	,   max_position_embeddings=self.max_position_embeddings	,   eos_token_ids=[2]	,   bos_token_id=self.bos_token_id	,   pad_token_id=self.pad_token_id	,   decoder_start_token_id=self.pad_token_id	,   **self.config_updates	,   )
        lowercase__				:    Any  =					prepare_pegasus_inputs_dict(__a	,   __a	,   __a )
        return config, inputs_dict


       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase )  ->  Union[str, Any]:
        lowercase__				:    Any  =					TFPegasusModel(config=__a ).get_decoder()
        lowercase__				:    int  =					inputs_dict["""input_ids"""]

        lowercase__				:    List[Any]  =					input_ids[:1, :]
        lowercase__				:    int  =					inputs_dict["""attention_mask"""][:1, :]
        lowercase__				:    List[Any]  =					inputs_dict["""head_mask"""]
        lowercase__				:    List[str]  =					1

        # first forward pass
        lowercase__				:    List[str]  =					model(__a	,   attention_mask=__a	,   head_mask=__a	,   use_cache=__a )

        lowercase__				:    List[str]  =					outputs.to_tuple()

        # create hypothetical next token and extent to next_input_ids
        lowercase__				:    Optional[Any]  =					ids_tensor((self.batch_size, 3)	,   config.vocab_size )
        lowercase__				:    Optional[int]  =					tf.cast(ids_tensor((self.batch_size, 3)	,   2 )	,   tf.inta )

        # append to next input_ids and
        lowercase__				:    List[Any]  =					tf.concat([input_ids, next_tokens]	,   axis=-1 )
        lowercase__				:    Tuple  =					tf.concat([attention_mask, next_attn_mask]	,   axis=-1 )

        lowercase__				:    List[str]  =					model(__a	,   attention_mask=__a )[0]
        lowercase__				:    Union[str, Any]  =					model(__a	,   attention_mask=__a	,   past_key_values=__a )[0]

        self.parent.assertEqual(next_tokens.shape[1]	,   output_from_past.shape[1] )

        # select random slice
        lowercase__				:    int  =					int(ids_tensor((1,)	,   output_from_past.shape[-1] ) )
        lowercase__				:    List[str]  =					output_from_no_past[:, -3:, random_slice_idx]
        lowercase__				:    Optional[int]  =					output_from_past[:, :, random_slice_idx]

        # test that outputs are equal for slice
        tf.debugging.assert_near(__a	,   __a	,   rtol=1E-3 )


def 			__UpperCamelCase       (   UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     UpperCAmelCase=None		,     ):
 if attention_mask is None:
  lowercase__				:    Union[str, Any]  =					tf.cast(tf.math.not_equal(lowerCAmelCase_		,     config.pad_token_id     )		,     tf.inta     )
 if decoder_attention_mask is None:
  lowercase__				:    Optional[int]  =					tf.concat(
      [
          tf.ones(decoder_input_ids[:, :1].shape		,     dtype=tf.inta     ),
          tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]		,     config.pad_token_id     )		,     tf.inta     ),
      ]		,     axis=-1		,     )
 if head_mask is None:
  lowercase__				:    str  =					tf.ones((config.encoder_layers, config.encoder_attention_heads)     )
 if decoder_head_mask is None:
  lowercase__				:    int  =					tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
 if cross_attn_head_mask is None:
  lowercase__				:    Union[str, Any]  =					tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
 return {
     "input_ids": input_ids,
     "decoder_input_ids": decoder_input_ids,
     "attention_mask": attention_mask,
     "decoder_attention_mask": decoder_attention_mask,
     "head_mask": head_mask,
     "decoder_head_mask": decoder_head_mask,
     "cross_attn_head_mask": cross_attn_head_mask,
 }



@require_tf
class 			UpperCAmelCase  (						__a    ,						__a    ,						unittest.TestCase					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
       SCREAMING_SNAKE_CASE							=    (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
       SCREAMING_SNAKE_CASE							=    (
           {
               '''conversational''': TFPegasusForConditionalGeneration,
               '''feature-extraction''': TFPegasusModel,
               '''summarization''': TFPegasusForConditionalGeneration,
               '''text2text-generation''': TFPegasusForConditionalGeneration,
               '''translation''': TFPegasusForConditionalGeneration,
           }
           if is_tf_available()
           else {}
       )
       SCREAMING_SNAKE_CASE							=    True
       SCREAMING_SNAKE_CASE							=    False
       SCREAMING_SNAKE_CASE							=    False

       def _lowerCAmelCase(						self )  ->  List[str]:
        lowercase__				:    Union[str, Any]  =					TFPegasusModelTester(self )
        lowercase__				:    List[str]  =					ConfigTester(self	,   config_class=__a )

       def _lowerCAmelCase(						self )  ->  str:
        self.config_tester.run_common_tests()


       def _lowerCAmelCase(						self )  ->  str:
        lowercase__				:    int  =					self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.check_decoder_model_past_large_inputs(*__a )



@require_sentencepiece
@require_tokenizers
@require_tf
class 			UpperCAmelCase  (						unittest.TestCase					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [
           ''' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.''',
           ''' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ''',
       ]
       SCREAMING_SNAKE_CASE							=    [
           '''California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'''
           ''' reduce the risk of wildfires.''',
           '''N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.''',
       ]  # differs slightly from pytorch, likely due to numerical differences in linear layers
       SCREAMING_SNAKE_CASE							=    '''google/pegasus-xsum'''

       @cached_property
       def _lowerCAmelCase(						self )  ->  int:
        return AutoTokenizer.from_pretrained(self.model_name )

       @cached_property
       def _lowerCAmelCase(						self )  ->  Optional[Any]:
        lowercase__				:    int  =					TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
        return model

       def _lowerCAmelCase(						self	,   **__lowerCAmelCase )  ->  Any:
        lowercase__				:    Union[str, Any]  =					self.translate_src_text(**__a )
        assert self.expected_text == generated_words

       def _lowerCAmelCase(						self	,   **__lowerCAmelCase )  ->  List[Any]:
        lowercase__				:    List[Any]  =					self.tokenizer(self.src_text	,   **__a	,   padding=__a	,   return_tensors='''tf''' )
        lowercase__				:    List[Any]  =					self.model.generate(
            model_inputs.input_ids	,   attention_mask=model_inputs.attention_mask	,   num_beams=2	,   use_cache=__a	,   )
        lowercase__				:    Any  =					self.tokenizer.batch_decode(generated_ids.numpy()	,   skip_special_tokens=__a )
        return generated_words


       @slow
       def _lowerCAmelCase(						self )  ->  Any:
        self._assert_generated_batch_equal_expected()









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 						lowerCAmelCase   :

					'''simple docstring'''

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


												"""simple docstring"""

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



					def 					lowerCAmelCase (     self :		List[Any]							)	->     List[Any]:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

												__lowercase					:							Union[str, Any]			=   self.get_config()

												return config, pixel_values, labels



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     str:


												"""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 					lowerCAmelCase (     self :		int						,   __a :		Tuple						,   __a :		Dict						,   __a :		List[str]							)	->     Dict:


												"""simple docstring"""

												__lowercase					:							str			=   ConvNextVaModel(config=__a							)
												model.to(__a							)
												model.eval()
												__lowercase					:							Union[str, 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 					lowerCAmelCase (     self :		Any						,   __a :		Tuple						,   __a :		Any						,   __a :		Union[str, Any]							)	->     Optional[int]:


												"""simple docstring"""

												__lowercase					:							int			=   ConvNextVaForImageClassification(__a							)
												model.to(__a							)
												model.eval()
												__lowercase					:							Union[str, Any]			=   model(__a						,   labels=__a							)
												self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)							)



					def 					lowerCAmelCase (     self :		int						,   __a :		str						,   __a :		Any						,   __a :		Optional[int]							)	->     Dict:


												"""simple docstring"""

												__lowercase					:							Union[str, Any]			=   ConvNextVaBackbone(config=__a							)
												model.to(__a							)
												model.eval()
												__lowercase					:							Dict			=   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
												__lowercase					:							List[str]			=   None
												__lowercase					:							str			=   ConvNextVaBackbone(config=__a							)
												model.to(__a							)
												model.eval()
												__lowercase					:							Optional[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 					lowerCAmelCase (     self :		str							)	->     List[str]:


												"""simple docstring"""

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



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     str:


												"""simple docstring"""

												__lowercase					:							Dict			=   self.prepare_config_and_inputs()
												__lowercase	,	__lowercase	,	__lowercase					:							Optional[Any]			=   config_and_inputs
												__lowercase					:							int			=   {"""pixel_values""": pixel_values, """labels""": labels}
												return config, inputs_dict







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

					'''simple docstring'''

					_A  :	Any     =					(
					    (
					        ConvNextVaModel,
					        ConvNextVaForImageClassification,
					        ConvNextVaBackbone,
					    )
					    if is_torch_available()
					    else ()
					)
					_A  :	Any     =					(
					    {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
					    if is_torch_available()
					    else {}
					)

					_A  :	str     =					False
					_A  :	Dict     =					False
					_A  :	str     =					False
					_A  :	str     =					False
					_A  :	Dict     =					False



					def 					lowerCAmelCase (     self :		Optional[Any]							)	->     Dict:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   ConvNextVaModelTester(self							)
												__lowercase					:							Optional[int]			=   ConfigTester(self						,   config_class=__a						,   has_text_modality=__a						,   hidden_size=37							)



					def 					lowerCAmelCase (     self :		int							)	->     Optional[int]:


												"""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 					lowerCAmelCase (     self :		int							)	->     str:


												"""simple docstring"""

												return



					@unittest.skip(reason="""ConvNextV2 does not use inputs_embeds"""							)
					def 					lowerCAmelCase (     self :		int							)	->     Any:


												"""simple docstring"""

												pass



					@unittest.skip(reason="""ConvNextV2 does not support input and output embeddings"""							)
					def 					lowerCAmelCase (     self :		Any							)	->     Union[str, Any]:


												"""simple docstring"""

												pass



					@unittest.skip(reason="""ConvNextV2 does not use feedforward chunking"""							)
					def 					lowerCAmelCase (     self :		Any							)	->     Optional[int]:


												"""simple docstring"""

												pass



					def 					lowerCAmelCase (     self :		Union[str, Any]							)	->     List[str]:


												"""simple docstring"""

												if not self.model_tester.is_training:
																			return

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

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

																			__lowercase					:							Union[str, Any]			=   model_class(__a							)
																			model.to(__a							)
																			model.train()
																			__lowercase					:							Tuple			=   self._prepare_for_class(__a						,   __a						,   return_labels=__a							)
																			__lowercase					:							Dict			=   model(**__a							).loss
																			loss.backward()



					def 					lowerCAmelCase (     self :		Optional[int]							)	->     int:


												"""simple docstring"""

												if not self.model_tester.is_training:
																			return

												for model_class in self.all_model_classes:
																			__lowercase	,	__lowercase					:							Tuple			=   self.model_tester.prepare_config_and_inputs_with_labels()
																			__lowercase					:							Dict			=   False
																			__lowercase					:							Optional[Any]			=   True

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

																			__lowercase					:							List[Any]			=   model_class(__a							)
																			model.to(__a							)
																			model.gradient_checkpointing_enable()
																			model.train()
																			__lowercase					:							List[str]			=   self._prepare_for_class(__a						,   __a						,   return_labels=__a							)
																			__lowercase					:							int			=   model(**__a							).loss
																			loss.backward()



					def 					lowerCAmelCase (     self :		Tuple							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase	,	__lowercase					:							List[str]			=   self.model_tester.prepare_config_and_inputs_for_common()

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

																			__lowercase					:							Optional[Any]			=   ["""pixel_values"""]
																			self.assertListEqual(arg_names[:1]						,   __a							)



					def 					lowerCAmelCase (     self :		List[str]							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__a							)



					def 					lowerCAmelCase (     self :		Dict							)	->     List[str]:


												"""simple docstring"""

												def check_hidden_states_output(__a :		Any						,   __a :		Tuple						,   __a :		Tuple							):
																			__lowercase					:							Optional[Any]			=   model_class(__a							)
																			model.to(__a							)
																			model.eval()

																			with torch.no_grad():
																										__lowercase					:							int			=   model(**self._prepare_for_class(__a						,   __a							)							)

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

																			__lowercase					:							Any			=   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]						,   )

												__lowercase	,	__lowercase					:							Optional[Any]			=   self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			__lowercase					:							int			=   True
																			check_hidden_states_output(__a						,   __a						,   __a							)

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

																			check_hidden_states_output(__a						,   __a						,   __a							)



					def 					lowerCAmelCase (     self :		Dict							)	->     Union[str, Any]:


												"""simple docstring"""

												__lowercase					:							List[Any]			=   self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__a							)



					@slow
					def 					lowerCAmelCase (     self :		Dict							)	->     Tuple:


												"""simple docstring"""

												for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__lowercase					:							Optional[int]			=   ConvNextVaModel.from_pretrained(__a							)
																			self.assertIsNotNone(__a							)







def 					snake_case_						(   ):
							__lowercase					:							int			=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
							return image



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

					'''simple docstring'''

					@cached_property
					def 					lowerCAmelCase (     self :		Any							)	->     List[str]:


												"""simple docstring"""

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



					@slow
					def 					lowerCAmelCase (     self :		Dict							)	->     str:


												"""simple docstring"""

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

												__lowercase					:							Dict			=   self.default_image_processor
												__lowercase					:							Any			=   prepare_img()
												__lowercase					:							int			=   preprocessor(images=__a						,   return_tensors="""pt"""							).to(__a							)

												# forward pass
												with torch.no_grad():
																			__lowercase					:							int			=   model(**__a							)

												# verify the logits
												__lowercase					:							List[str]			=   torch.Size((1, 1000)							)
												self.assertEqual(outputs.logits.shape						,   __a							)

												__lowercase					:							Tuple			=   torch.tensor([0.9996, 0.1966, -0.4386]							).to(__a							)
												self.assertTrue(torch.allclose(outputs.logits[0, :3]						,   __a						,   atol=1E-4							)							)