

import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


A_		:     Dict        =     logging.getLogger(__name__)



@dataclass
class 		_lowercase		:
   _UpperCAmelCase     	=			42
   _UpperCAmelCase     	=			42
   _UpperCAmelCase     	=			42



@dataclass
class 		_lowercase		:
   _UpperCAmelCase     	=			42
   _UpperCAmelCase     	=			42
   _UpperCAmelCase     	=			None
   _UpperCAmelCase     	=			None



class 		_lowercase		(       UpperCAmelCase__	):
   _UpperCAmelCase     	=			'''train'''
   _UpperCAmelCase     	=			'''dev'''
   _UpperCAmelCase     	=			'''test'''



class 		_lowercase		:

   @staticmethod
   def 		A							(      __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       List[str]							)       ->				List[InputExample]:


    """simple docstring"""






    raise NotImplementedError

   @staticmethod
   def 		A							(      __lowerCAmelCase			:       Dict							)       ->				List[str]:


    """simple docstring"""






    raise NotImplementedError




   @staticmethod
   def 		A							(      __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Union[str, Any]=False							,   __lowerCAmelCase			:       Optional[int]="[CLS]"							,   __lowerCAmelCase			:       List[str]=1							,   __lowerCAmelCase			:       Tuple="[SEP]"							,   __lowerCAmelCase			:       Dict=False							,   __lowerCAmelCase			:       str=False							,   __lowerCAmelCase			:       List[str]=0							,   __lowerCAmelCase			:       str=0							,   __lowerCAmelCase			:       List[str]=-100							,   __lowerCAmelCase			:       List[Any]=0							,   __lowerCAmelCase			:       List[Any]=True							,   )       ->				List[InputFeatures]:


    """simple docstring"""






    a						=		{label: i for i, label in enumerate(_SCREAMING_SNAKE_CASE							)}

    a						=		[]
    for ex_index, example in enumerate(_SCREAMING_SNAKE_CASE							):
     if ex_index % 1_0000 == 0:
      logger.info("Writing example %d of %d"							,   _SCREAMING_SNAKE_CASE							,   len(_SCREAMING_SNAKE_CASE							)							)

     a						=		[]
     a						=		[]
     for word, label in zip(example.words							,   example.labels							):
      a						=		tokenizer.tokenize(_SCREAMING_SNAKE_CASE							)

      # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
      if len(_SCREAMING_SNAKE_CASE							) > 0:
       tokens.extend(_SCREAMING_SNAKE_CASE							)
       # Use the real label id for the first token of the word, and padding ids for the remaining tokens
       label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_SCREAMING_SNAKE_CASE							) - 1)							)

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
     a						=		tokenizer.num_special_tokens_to_add()
     if len(_SCREAMING_SNAKE_CASE							) > max_seq_length - special_tokens_count:
      a						=		tokens[: (max_seq_length - special_tokens_count)]
      a						=		label_ids[: (max_seq_length - special_tokens_count)]

     # The convention in BERT is:
     # (a) For sequence pairs:
     #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
     #  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
     # (b) For single sequences:
     #  tokens:   [CLS] the dog is hairy . [SEP]
     #  type_ids:   0   0   0   0  0     0   0
     #
     # Where "type_ids" are used to indicate whether this is the first
     # sequence or the second sequence. The embedding vectors for `type=0` and
     # `type=1` were learned during pre-training and are added to the wordpiece
     # embedding vector (and position vector). This is not *strictly* necessary
     # since the [SEP] token unambiguously separates the sequences, but it makes
     # it easier for the model to learn the concept of sequences.
     #
     # For classification tasks, the first vector (corresponding to [CLS]) is
     # used as the "sentence vector". Note that this only makes sense because
     # the entire model is fine-tuned.
     tokens += [sep_token]
     label_ids += [pad_token_label_id]
     if sep_token_extra:
      # roberta uses an extra separator b/w pairs of sentences
      tokens += [sep_token]
      label_ids += [pad_token_label_id]
     a						=		[sequence_a_segment_id] * len(_SCREAMING_SNAKE_CASE							)

     if cls_token_at_end:
      tokens += [cls_token]
      label_ids += [pad_token_label_id]
      segment_ids += [cls_token_segment_id]
     else:
      a						=		[cls_token] + tokens
      a						=		[pad_token_label_id] + label_ids
      a						=		[cls_token_segment_id] + segment_ids

     a						=		tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE							)

     # The mask has 1 for real tokens and 0 for padding tokens. Only real
     # tokens are attended to.
     a						=		[1 if mask_padding_with_zero else 0] * len(_SCREAMING_SNAKE_CASE							)

     # Zero-pad up to the sequence length.
     a						=		max_seq_length - len(_SCREAMING_SNAKE_CASE							)
     if pad_on_left:
      a						=		([pad_token] * padding_length) + input_ids
      a						=		([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
      a						=		([pad_token_segment_id] * padding_length) + segment_ids
      a						=		([pad_token_label_id] * padding_length) + label_ids
     else:
      input_ids += [pad_token] * padding_length
      input_mask += [0 if mask_padding_with_zero else 1] * padding_length
      segment_ids += [pad_token_segment_id] * padding_length
      label_ids += [pad_token_label_id] * padding_length

     assert len(_SCREAMING_SNAKE_CASE							) == max_seq_length
     assert len(_SCREAMING_SNAKE_CASE							) == max_seq_length
     assert len(_SCREAMING_SNAKE_CASE							) == max_seq_length
     assert len(_SCREAMING_SNAKE_CASE							) == max_seq_length

     if ex_index < 5:
      logger.info("*** Example ***"							)
      logger.info("guid: %s"							,   example.guid							)
      logger.info("tokens: %s"							,   " ".join([str(_SCREAMING_SNAKE_CASE							) for x in tokens]							)							)
      logger.info("input_ids: %s"							,   " ".join([str(_SCREAMING_SNAKE_CASE							) for x in input_ids]							)							)
      logger.info("input_mask: %s"							,   " ".join([str(_SCREAMING_SNAKE_CASE							) for x in input_mask]							)							)
      logger.info("segment_ids: %s"							,   " ".join([str(_SCREAMING_SNAKE_CASE							) for x in segment_ids]							)							)
      logger.info("label_ids: %s"							,   " ".join([str(_SCREAMING_SNAKE_CASE							) for x in label_ids]							)							)

     if "token_type_ids" not in tokenizer.model_input_names:
      a						=		None

     features.append(
         InputFeatures(
             input_ids=_SCREAMING_SNAKE_CASE							,   attention_mask=_SCREAMING_SNAKE_CASE							,   token_type_ids=_SCREAMING_SNAKE_CASE							,   label_ids=_SCREAMING_SNAKE_CASE							)							)
    return features


if is_torch_available():
     import torch
     from torch import nn
     from torch.utils.data import Dataset



     class 		_lowercase		(       UpperCAmelCase__	):
        _UpperCAmelCase     	=			42
        _UpperCAmelCase     	=			nn.CrossEntropyLoss().ignore_index

        def __init__(      self			:       Any							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Dict = None							,   __lowerCAmelCase			:       Optional[int]=False							,   __lowerCAmelCase			:       Optional[Any] = Split.train							,   )       ->				Optional[int]:


         """simple docstring"""






         a						=		os.path.join(
             _SCREAMING_SNAKE_CASE							,   "cached_{}_{}_{}".format(mode.value							,   tokenizer.__class__.__name__							,   str(_SCREAMING_SNAKE_CASE							)							)							,   )

         # Make sure only the first process in distributed training processes the dataset,
         # and the others will use the cache.
         a						=		cached_features_file + ".lock"
         with FileLock(_SCREAMING_SNAKE_CASE							):
          if os.path.exists(_SCREAMING_SNAKE_CASE							) and not overwrite_cache:
           logger.info(f"""Loading features from cached file {cached_features_file}"""							)
           a						=		torch.load(_SCREAMING_SNAKE_CASE							)
          else:
           logger.info(f"""Creating features from dataset file at {data_dir}"""							)
           a						=		token_classification_task.read_examples_from_file(_SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							)
           # TODO clean up all this to leverage built-in features of tokenizers
           a						=		token_classification_task.convert_examples_to_features(
               _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   cls_token_at_end=bool(model_type in ["xlnet"]							)							,   cls_token=tokenizer.cls_token							,   cls_token_segment_id=2 if model_type in ["xlnet"] else 0							,   sep_token=tokenizer.sep_token							,   sep_token_extra=_SCREAMING_SNAKE_CASE							,   pad_on_left=bool(tokenizer.padding_side == "left"							)							,   pad_token=tokenizer.pad_token_id							,   pad_token_segment_id=tokenizer.pad_token_type_id							,   pad_token_label_id=self.pad_token_label_id							,   )
           logger.info(f"""Saving features into cached file {cached_features_file}"""							)
           torch.save(self.features							,   _SCREAMING_SNAKE_CASE							)

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


         """simple docstring"""






         return len(self.features							)




        def __getitem__(      self			:       Dict							,   __lowerCAmelCase			:       int							)       ->				InputFeatures:


         """simple docstring"""






         return self.features[i]


if is_tf_available():
     import tensorflow as tf



     class 		_lowercase		:
        _UpperCAmelCase     	=			42
        _UpperCAmelCase     	=			-100

        def __init__(      self			:       List[Any]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       List[Any] = None							,   __lowerCAmelCase			:       Any=False							,   __lowerCAmelCase			:       Dict = Split.train							,   )       ->				str:


         """simple docstring"""






         a						=		token_classification_task.read_examples_from_file(_SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							)
         # TODO clean up all this to leverage built-in features of tokenizers
         a						=		token_classification_task.convert_examples_to_features(
             _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   _SCREAMING_SNAKE_CASE							,   cls_token_at_end=bool(model_type in ["xlnet"]							)							,   cls_token=tokenizer.cls_token							,   cls_token_segment_id=2 if model_type in ["xlnet"] else 0							,   sep_token=tokenizer.sep_token							,   sep_token_extra=_SCREAMING_SNAKE_CASE							,   pad_on_left=bool(tokenizer.padding_side == "left"							)							,   pad_token=tokenizer.pad_token_id							,   pad_token_segment_id=tokenizer.pad_token_type_id							,   pad_token_label_id=self.pad_token_label_id							,   )

         def gen():
          for ex in self.features:
           if ex.token_type_ids is None:
            yield (
                {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
                ex.label_ids,
            )
           else:
            yield (
                {
                    "input_ids": ex.input_ids,
                    "attention_mask": ex.attention_mask,
                    "token_type_ids": ex.token_type_ids,
                },
                ex.label_ids,
            )

         if "token_type_ids" not in tokenizer.model_input_names:
          a						=		tf.data.Dataset.from_generator(
              _SCREAMING_SNAKE_CASE							,   ({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa)							,   (
                  {"input_ids": tf.TensorShape([None]							), "attention_mask": tf.TensorShape([None]							)},
                  tf.TensorShape([None]							),
              )							,   )
         else:
          a						=		tf.data.Dataset.from_generator(
              _SCREAMING_SNAKE_CASE							,   ({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa)							,   (
                  {
                      "input_ids": tf.TensorShape([None]							),
                      "attention_mask": tf.TensorShape([None]							),
                      "token_type_ids": tf.TensorShape([None]							),
                  },
                  tf.TensorShape([None]							),
              )							,   )

        def 		A							(      self			:       List[Any]							)       ->				Optional[Any]:


         """simple docstring"""






         a						=		self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features							)							)							)

         return self.dataset

        def __len__(      self			:       List[str]							)       ->				int:


         """simple docstring"""






         return len(self.features							)




        def __getitem__(      self			:       Optional[int]							,   __lowerCAmelCase			:       Optional[int]							)       ->				InputFeatures:


         """simple docstring"""






         return self.features[i]






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		:

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


    """simple docstring"""






    a						=		parent
    a						=		batch_size
    a						=		image_size
    a						=		num_channels
    a						=		num_stages
    a						=		hidden_sizes
    a						=		depths
    a						=		is_training
    a						=		use_labels
    a						=		intermediate_size
    a						=		hidden_act
    a						=		num_labels
    a						=		initializer_range
    a						=		out_features
    a						=		out_indices
    a						=		scope

   def 		A							(      self			:       Optional[Any]							)       ->				int:


    """simple docstring"""






    a						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

    a						=		None
    if self.use_labels:
     a						=		ids_tensor([self.batch_size]							,   self.num_labels							)

    a						=		self.get_config()

    return config, pixel_values, labels

   def 		A							(      self			:       Union[str, Any]							)       ->				Optional[int]:


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

   def 		A							(      self			:       Any							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Dict							)       ->				Optional[int]:


    """simple docstring"""






    a						=		ConvNextVaModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)
    # 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 		A							(      self			:       int							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Union[str, Any]							)       ->				Dict:


    """simple docstring"""






    a						=		ConvNextVaForImageClassification(__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)							)

   def 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[int]							)       ->				int:


    """simple docstring"""






    a						=		ConvNextVaBackbone(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)

    # 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
    a						=		None
    a						=		ConvNextVaBackbone(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							)

    # 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 		A							(      self			:       Union[str, Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    a		,  a		,  a						=		config_and_inputs
    a						=		{"pixel_values": pixel_values}
    return config, inputs_dict




   def 		A							(      self			:       Dict							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.prepare_config_and_inputs()
    a		,  a		,  a						=		config_and_inputs
    a						=		{"pixel_values": pixel_values, "labels": labels}
    return config, inputs_dict



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   unittest.TestCase	):
   _UpperCAmelCase     	=			(
       (
           ConvNextVaModel,
           ConvNextVaForImageClassification,
           ConvNextVaBackbone,
       )
       if is_torch_available()
       else ()
   )
   _UpperCAmelCase     	=			(
       {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
       if is_torch_available()
       else {}
   )

   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False
   _UpperCAmelCase     	=			False

   def 		A							(      self			:       List[str]							)       ->				List[Any]:


    """simple docstring"""






    a						=		ConvNextVaModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   has_text_modality=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       Tuple							)       ->				Dict:


    """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 		A							(      self			:       List[Any]							)       ->				List[Any]:


    """simple docstring"""






    return

   @unittest.skip(reason="ConvNextV2 does not use inputs_embeds"							)
   def 		A							(      self			:       List[Any]							)       ->				List[Any]:


    """simple docstring"""






    pass

   @unittest.skip(reason="ConvNextV2 does not support input and output embeddings"							)
   def 		A							(      self			:       int							)       ->				List[Any]:


    """simple docstring"""






    pass

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


    """simple docstring"""






    pass

   def 		A							(      self			:       List[str]							)       ->				List[str]:


    """simple docstring"""






    if not self.model_tester.is_training:
     return

    for model_class in self.all_model_classes:
     a		,  a						=		self.model_tester.prepare_config_and_inputs_with_labels()
     a						=		True

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

     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.train()
     a						=		self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)
     a						=		model(**__lowerCAmelCase							).loss
     loss.backward()

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


    """simple docstring"""






    if not self.model_tester.is_training:
     return

    for model_class in self.all_model_classes:
     a		,  a						=		self.model_tester.prepare_config_and_inputs_with_labels()
     a						=		False
     a						=		True

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

     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.gradient_checkpointing_enable()
     model.train()
     a						=		self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)
     a						=		model(**__lowerCAmelCase							).loss
     loss.backward()

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


    """simple docstring"""






    a		,  a						=		self.model_tester.prepare_config_and_inputs_for_common()

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

     a						=		["pixel_values"]
     self.assertListEqual(arg_names[:1]							,   __lowerCAmelCase							)

   def 		A							(      self			:       Dict							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase							)

   def 		A							(      self			:       Tuple							)       ->				List[Any]:


    """simple docstring"""






    def check_hidden_states_output(__lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Tuple							):
     a						=		model_class(__lowerCAmelCase							)
     model.to(__lowerCAmelCase							)
     model.eval()

     with torch.no_grad():
      a						=		model(**self._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							)							)

     a						=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     a						=		self.model_tester.num_stages
     self.assertEqual(len(__lowerCAmelCase							)							,   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]							,   )

    a		,  a						=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     a						=		True
     check_hidden_states_output(__lowerCAmelCase							,   __lowerCAmelCase							,   __lowerCAmelCase							)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     a						=		True

     check_hidden_states_output(__lowerCAmelCase							,   __lowerCAmelCase							,   __lowerCAmelCase							)

   def 		A							(      self			:       Optional[Any]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase							)




   @slow
   def 		A							(      self			:       Tuple							)       ->				List[str]:


    """simple docstring"""






    for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     a						=		ConvNextVaModel.from_pretrained(__lowerCAmelCase							)
     self.assertIsNotNone(__lowerCAmelCase							)


def 	UpperCAmelCase__      (      ):






 '''simple docstring'''

 a						=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
 return image




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

   @cached_property
   def 		A							(      self			:       Optional[int]							)       ->				str:


    """simple docstring"""






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




   @slow
   def 		A							(      self			:       List[str]							)       ->				Union[str, Any]:


    """simple docstring"""






    a						=		ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"							).to(__lowerCAmelCase							)

    a						=		self.default_image_processor
    a						=		prepare_img()
    a						=		preprocessor(images=__lowerCAmelCase							,   return_tensors="pt"							).to(__lowerCAmelCase							)

    # forward pass
    with torch.no_grad():
     a						=		model(**__lowerCAmelCase							)

    # verify the logits
    a						=		torch.Size((1, 1000)							)
    self.assertEqual(outputs.logits.shape							,   __lowerCAmelCase							)

    a						=		torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6]							).to(__lowerCAmelCase							)
    self.assertTrue(torch.allclose(outputs.logits[0, :3]							,   __lowerCAmelCase							,   atol=1E-4							)							)

