


'''simple docstring'''



import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import numpy as np
import pandas as pd
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    BartForSequenceClassification,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    TapexTokenizer,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.17.0.dev0')

require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt')

__lowercase	:						str       =	logging.getLogger(__name__)





@dataclass
class 							__UpperCamelCase				:
	A_				=    field(
	    default="tab_fact"		,      metadata={"help": "The name of the dataset to use (via the datasets library)."}					)
	A_				=    field(
	    default="tab_fact"		,      metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}		,      )
	A_				=    field(
	    default=1024		,      metadata={
	        "help": (
	            "The maximum total input sequence length after tokenization. Sequences longer "
	            "than this will be truncated, sequences shorter will be padded."
	        )
	    }		,      )
	A_				=    field(
	    default=A_		,      metadata={"help": "Overwrite the cached preprocessed datasets or not."}					)
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "Whether to pad all samples to `max_seq_length`. "
	            "If False, will pad the samples dynamically when batching to the maximum length in the batch."
	        )
	    }		,      )
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of training examples to this "
	            "value if set."
	        )
	    }		,      )
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
	            "value if set."
	        )
	    }		,      )
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "For debugging purposes or quicker training, truncate the number of prediction examples to this "
	            "value if set."
	        )
	    }		,      )
	A_				=    field(
	    default=A_		,      metadata={"help": "A csv or a json file containing the training data."}					)
	A_				=    field(
	    default=A_		,      metadata={"help": "A csv or a json file containing the validation data."}					)
	A_				=    field(default=A_		,      metadata={"help": "A csv or a json file containing the test data."}					)




	def       __UpperCAmelCase							(   self							):

						'''simple docstring'''





						if self.dataset_name is not None:
											pass
						elif self.train_file is None or self.validation_file is None:
											raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.'							)
						else:
											__a			:       List[str]					    =  self.train_file.split('.'							)[-1]
											assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
											__a			:       Optional[int]					    =  self.validation_file.split('.'							)[-1]
											assert (
											    validation_extension == train_extension
											), "`validation_file` should have the same extension (csv or json) as `train_file`."





@dataclass
class 							__UpperCamelCase				:
	A_				=    field(
	    default=A_		,      metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}					)
	A_				=    field(
	    default=A_		,      metadata={"help": "Pretrained config name or path if not the same as model_name"}					)
	A_				=    field(
	    default=A_		,      metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}					)
	A_				=    field(
	    default=A_		,      metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}		,      )
	A_				=    field(
	    default=A_		,      metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}		,      )
	A_				=    field(
	    default="main"		,      metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}		,      )
	A_				=    field(
	    default=A_		,      metadata={
	        "help": (
	            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
	            "with private models)."
	        )
	    }		,      )






def   lowerCamelCase							():
					# See all possible arguments in src/transformers/training_args.py
					# or by passing the --help flag to this script.
					# We now keep distinct sets of args, for a cleaner separation of concerns.

					__a			:       Union[str, Any]					    =  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)   )
					if len(sys.argv   ) == 2 and sys.argv[1].endswith('.json'   ):
										# If we pass only one argument to the script and it's the path to a json file,
										# let's parse it to get our arguments.
										__a			:       Optional[Any]					    =  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
					else:
										__a			:       Optional[Any]					    =  parser.parse_args_into_dataclasses()

					# Setup logging
					logging.basicConfig(
					    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'						,      datefmt='%m/%d/%Y %H:%M:%S'						,      handlers=[logging.StreamHandler(sys.stdout   )]						,      )

					__a			:       Tuple					    =  training_args.get_process_log_level()
					logger.setLevel(__lowerCamelCase   )
					datasets.utils.logging.set_verbosity(__lowerCamelCase   )
					transformers.utils.logging.set_verbosity(__lowerCamelCase   )
					transformers.utils.logging.enable_default_handler()
					transformers.utils.logging.enable_explicit_format()

					# Log on each process the small summary:
					logger.warning(
					    F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
					    + F"""distributed training: {bool(training_args.local_rank != -1   )}, 16-bits training: {training_args.fpaa}"""   )
					logger.info(F"""Training/evaluation parameters {training_args}"""   )

					# Detecting last checkpoint.
					__a			:       List[Any]					    =  None
					if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
										__a			:       List[Any]					    =  get_last_checkpoint(training_args.output_dir   )
										if last_checkpoint is None and len(os.listdir(training_args.output_dir   )   ) > 0:
															raise ValueError(
															    F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
															    'Use --overwrite_output_dir to overcome.'   )
										elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
															logger.info(
															    F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
															    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'   )

    # Set seed before initializing model.
					set_seed(training_args.seed   )

					# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
					# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
					#
					# For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table.
					#
					# If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
					# single column. You can easily tweak this behavior (see below)
					#
					# In distributed training, the load_dataset function guarantee that only one local process can concurrently
					# download the dataset.
					if data_args.dataset_name is not None:
										# Downloading and loading a dataset from the hub.
										__a			:       Union[str, Any]					    =  load_dataset(
										    data_args.dataset_name						,      data_args.dataset_config_name						,      cache_dir=model_args.cache_dir   )
					else:
										# Loading a dataset from your local files.
										# CSV/JSON training and evaluation files are needed.
										__a			:       Any					    =  {'''train''': data_args.train_file, '''validation''': data_args.validation_file}

										# Get the test dataset: you can provide your own CSV/JSON test file (see below)
										# when you use `do_predict` without specifying a GLUE benchmark task.
										if training_args.do_predict:
															if data_args.test_file is not None:
																				__a			:       str					    =  data_args.train_file.split('.'   )[-1]
																				__a			:       Tuple					    =  data_args.test_file.split('.'   )[-1]
																				assert (
																				    test_extension == train_extension
																				), "`test_file` should have the same extension (csv or json) as `train_file`."
																				__a			:       Dict					    =  data_args.test_file
															else:
																				raise ValueError('Need either a GLUE task or a test file for `do_predict`.'   )

										for key in data_files.keys():
															logger.info(F"""load a local file for {key}: {data_files[key]}"""   )

										if data_args.train_file.endswith('.csv'   ):
															# Loading a dataset from local csv files
															__a			:       Union[str, Any]					    =  load_dataset('csv'						,      data_files=__lowerCamelCase						,      cache_dir=model_args.cache_dir   )
										else:
															# Loading a dataset from local json files
															__a			:       Optional[Any]					    =  load_dataset('json'						,      data_files=__lowerCamelCase						,      cache_dir=model_args.cache_dir   )
    # See more about loading any type of standard or custom dataset at
    # https://huggingface.co/docs/datasets/loading_datasets.html.

    # Labels
					__a			:       int					    =  raw_datasets['''train'''].features['''label'''].names
					__a			:       List[Any]					    =  len(__lowerCamelCase   )

					# Load pretrained model and tokenizer
					#
					# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.
					__a			:       int					    =  AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path						,      num_labels=__lowerCamelCase						,      cache_dir=model_args.cache_dir						,      revision=model_args.model_revision						,      use_auth_token=True if model_args.use_auth_token else None						,      )
					# load tapex tokenizer
					__a			:       List[Any]					    =  TapexTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path						,      cache_dir=model_args.cache_dir						,      use_fast=model_args.use_fast_tokenizer						,      revision=model_args.model_revision						,      use_auth_token=True if model_args.use_auth_token else None						,      add_prefix_space=__lowerCamelCase						,      )
					__a			:       Any					    =  BartForSequenceClassification.from_pretrained(
					    model_args.model_name_or_path						,      from_tf=bool('.ckpt' in model_args.model_name_or_path   )						,      config=__lowerCamelCase						,      cache_dir=model_args.cache_dir						,      revision=model_args.model_revision						,      use_auth_token=True if model_args.use_auth_token else None						,      )

					# Padding strategy
					if data_args.pad_to_max_length:
										__a			:       str					    =  '''max_length'''
					else:
										# We will pad later, dynamically at batch creation, to the max sequence length in each batch
										__a			:       List[Any]					    =  False

					# Some models have set the order of the labels to use, so let's make sure we do use it.
					__a			:       Any					    =  {'''Refused''': 0, '''Entailed''': 1}
					__a			:       str					    =  {0: '''Refused''', 1: '''Entailed'''}

					if data_args.max_seq_length > tokenizer.model_max_length:
										logger.warning(
										    F"""The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"""
										    F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""   )
					__a			:       str					    =  min(data_args.max_seq_length						,      tokenizer.model_max_length   )

					def preprocess_tabfact_function(_SCREAMING_SNAKE_CASE      :   Optional[int]   ):
										# Tokenize the texts
										def _convert_table_text_to_pandas(_SCREAMING_SNAKE_CASE      :   Optional[Any]   ):
															__a			:       Dict					    =  [_table_row.split('#'   ) for _table_row in _table_text.strip('\n'   ).split('\n'   )]
															__a			:       List[Any]					    =  pd.DataFrame.from_records(_table_content[1:]						,      columns=_table_content[0]   )
															return _table_pd

										__a			:       Tuple					    =  examples['''statement''']
										__a			:       str					    =  list(map(_convert_table_text_to_pandas						,      examples['table_text']   )   )
										__a			:       Dict					    =  tokenizer(__lowerCamelCase						,      __lowerCamelCase						,      padding=__lowerCamelCase						,      max_length=__lowerCamelCase						,      truncation=__lowerCamelCase   )

										__a			:       List[Any]					    =  examples['''label''']
										return result

					with training_args.main_process_first(desc='dataset map pre-processing'   ):
										__a			:       List[Any]					    =  raw_datasets.map(
										    __lowerCamelCase						,      batched=__lowerCamelCase						,      load_from_cache_file=not data_args.overwrite_cache						,      desc='Running tokenizer on dataset'						,      )
					if training_args.do_train:
										if "train" not in raw_datasets:
															raise ValueError('--do_train requires a train dataset'   )
										__a			:       str					    =  raw_datasets['''train''']
										if data_args.max_train_samples is not None:
															__a			:       Union[str, Any]					    =  train_dataset.select(range(data_args.max_train_samples   )   )

					if training_args.do_eval:
										if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
															raise ValueError('--do_eval requires a validation dataset'   )
										__a			:       Any					    =  raw_datasets['''validation''']
										if data_args.max_eval_samples is not None:
															__a			:       Optional[int]					    =  eval_dataset.select(range(data_args.max_eval_samples   )   )

					if training_args.do_predict or data_args.test_file is not None:
										if "test" not in raw_datasets and "test_matched" not in raw_datasets:
															raise ValueError('--do_predict requires a test dataset'   )
										__a			:       Optional[Any]					    =  raw_datasets['''test''']
										if data_args.max_predict_samples is not None:
															__a			:       str					    =  predict_dataset.select(range(data_args.max_predict_samples   )   )

    # Log a few random samples from the training set:
					if training_args.do_train:
										for index in random.sample(range(len(__lowerCamelCase   )   )						,      3   ):
															logger.info(F"""Sample {index} of the training set: {train_dataset[index]}."""   )

    # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
					def compute_metrics(_SCREAMING_SNAKE_CASE      :   Union[str, Any]   ):
										__a			:       Union[str, Any]					    =  p.predictions[0] if isinstance(p.predictions						,      __lowerCamelCase   ) else p.predictions
										__a			:       Dict					    =  np.argmax(__lowerCamelCase						,      axis=1   )
										return {"accuracy": (preds == p.label_ids).astype(np.floataa   ).mean().item()}

					# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
					if data_args.pad_to_max_length:
										__a			:       List[str]					    =  default_data_collator
					elif training_args.fpaa:
										__a			:       Any					    =  DataCollatorWithPadding(__lowerCamelCase						,      pad_to_multiple_of=8   )
					else:
										__a			:       List[Any]					    =  None

					# Initialize our Trainer
					__a			:       Union[str, Any]					    =  Trainer(
					    model=__lowerCamelCase						,      args=__lowerCamelCase						,      train_dataset=train_dataset if training_args.do_train else None						,      eval_dataset=eval_dataset if training_args.do_eval else None						,      compute_metrics=__lowerCamelCase						,      tokenizer=__lowerCamelCase						,      data_collator=__lowerCamelCase						,      )

					# Training
					if training_args.do_train:
										__a			:       Dict					    =  None
										if training_args.resume_from_checkpoint is not None:
															__a			:       Dict					    =  training_args.resume_from_checkpoint
										elif last_checkpoint is not None:
															__a			:       int					    =  last_checkpoint
										__a			:       List[str]					    =  trainer.train(resume_from_checkpoint=__lowerCamelCase   )
										__a			:       List[str]					    =  train_result.metrics
										__a			:       List[str]					    =  (
										    data_args.max_train_samples if data_args.max_train_samples is not None else len(__lowerCamelCase   )
										)
										__a			:       Any					    =  min(__lowerCamelCase						,      len(__lowerCamelCase   )   )

										trainer.save_model()  # Saves the tokenizer too for easy upload

										trainer.log_metrics('train'						,      __lowerCamelCase   )
										trainer.save_metrics('train'						,      __lowerCamelCase   )
										trainer.save_state()

					# Evaluation
					if training_args.do_eval:
										logger.info('*** Evaluate ***'   )

										__a			:       Union[str, Any]					    =  trainer.evaluate(eval_dataset=__lowerCamelCase   )
										__a			:       Union[str, Any]					    =  data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__lowerCamelCase   )
										__a			:       Tuple					    =  min(__lowerCamelCase						,      len(__lowerCamelCase   )   )

										trainer.log_metrics('eval'						,      __lowerCamelCase   )
										trainer.save_metrics('eval'						,      __lowerCamelCase   )

					if training_args.do_predict:
										logger.info('*** Predict ***'   )

										# Removing the `label` columns because it contains -1 and Trainer won't like that.
										__a			:       Tuple					    =  predict_dataset.remove_columns('label'   )
										__a			:       str					    =  trainer.predict(__lowerCamelCase						,      metric_key_prefix='predict'   ).predictions
										__a			:       Tuple					    =  np.argmax(__lowerCamelCase						,      axis=1   )

										__a			:       List[Any]					    =  os.path.join(training_args.output_dir						,      'predict_results_tabfact.txt'   )
										if trainer.is_world_process_zero():
															with open(__lowerCamelCase						,      'w'   ) as writer:
																				logger.info('***** Predict Results *****'   )
																				writer.write('index\tprediction\n'   )
																				for index, item in enumerate(__lowerCamelCase   ):
																									__a			:       Optional[Any]					    =  label_list[item]
																									writer.write(F"""{index}\t{item}\n"""   )

					__a			:       Dict					    =  {'''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''text-classification'''}

					if training_args.push_to_hub:
										trainer.push_to_hub(**__lowerCamelCase   )
					else:
										trainer.create_model_card(**__lowerCamelCase   )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE      :   Optional[int]   ):
					# For xla_spawn (TPUs)
					main()


if __name__ == "__main__":
	main()








"""simple docstring"""







import collections
import inspect
import unittest

from transformers import SwinvaConfig
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, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
							from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class        __A       :







		'''simple docstring'''





		def __init__(	self						:  Optional[int]			,_snake_case						:  Optional[Any]			,_snake_case						:  Union[str, Any]=13			,_snake_case						:  Any=32			,_snake_case						:  int=2			,_snake_case						:  str=3			,_snake_case						:  Optional[Any]=16			,_snake_case						:  List[Any]=[1, 2, 1]			,_snake_case						:  Dict=[2, 2, 4]			,_snake_case						:  List[Any]=2			,_snake_case						:  Any=2.0			,_snake_case						:  Optional[int]=True			,_snake_case						:  Optional[int]=0.0			,_snake_case						:  Union[str, Any]=0.0			,_snake_case						:  str=0.1			,_snake_case						:  List[Any]="gelu"			,_snake_case						:  Tuple=False			,_snake_case						:  Optional[int]=True			,_snake_case						:  str=0.02			,_snake_case						:  List[str]=1e-5			,_snake_case						:  int=True			,_snake_case						:  Dict=None			,_snake_case						:  str=True			,_snake_case						:  List[Any]=10			,_snake_case						:  Any=8			,)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Dict				=			parent
				lowercase__   :    Any				=			batch_size
				lowercase__   :    Union[str, Any]				=			image_size
				lowercase__   :    Dict				=			patch_size
				lowercase__   :    int				=			num_channels
				lowercase__   :    Any				=			embed_dim
				lowercase__   :    int				=			depths
				lowercase__   :    Dict				=			num_heads
				lowercase__   :    List[Any]				=			window_size
				lowercase__   :    int				=			mlp_ratio
				lowercase__   :    Optional[int]				=			qkv_bias
				lowercase__   :    str				=			hidden_dropout_prob
				lowercase__   :    List[Any]				=			attention_probs_dropout_prob
				lowercase__   :    Dict				=			drop_path_rate
				lowercase__   :    int				=			hidden_act
				lowercase__   :    Tuple				=			use_absolute_embeddings
				lowercase__   :    Tuple				=			patch_norm
				lowercase__   :    Tuple				=			layer_norm_eps
				lowercase__   :    Optional[Any]				=			initializer_range
				lowercase__   :    int				=			is_training
				lowercase__   :    Optional[int]				=			scope
				lowercase__   :    str				=			use_labels
				lowercase__   :    Dict				=			type_sequence_label_size
				lowercase__   :    Union[str, Any]				=			encoder_stride







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Any:






				"""simple docstring"""



				lowercase__   :    str				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

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

				return config, pixel_values, labels







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






				"""simple docstring"""



				return SwinvaConfig(
				    image_size=self.image_size			,patch_size=self.patch_size			,num_channels=self.num_channels			,embed_dim=self.embed_dim			,depths=self.depths			,num_heads=self.num_heads			,window_size=self.window_size			,mlp_ratio=self.mlp_ratio			,qkv_bias=self.qkv_bias			,hidden_dropout_prob=self.hidden_dropout_prob			,attention_probs_dropout_prob=self.attention_probs_dropout_prob			,drop_path_rate=self.drop_path_rate			,hidden_act=self.hidden_act			,use_absolute_embeddings=self.use_absolute_embeddings			,path_norm=self.patch_norm			,layer_norm_eps=self.layer_norm_eps			,initializer_range=self.initializer_range			,encoder_stride=self.encoder_stride			,)







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  Dict			,_snake_case						:  List[str]			,_snake_case						:  Optional[int]						)					->		Optional[int]:






				"""simple docstring"""



				lowercase__   :    Any				=			SwinvaModel(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    str				=			model(_snake_case						)

				lowercase__   :    List[Any]				=			((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
				lowercase__   :    Tuple				=			int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

				self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, expected_seq_len, expected_dim)						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]			,_snake_case						:  int						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			SwinvaForMaskedImageModeling(config=_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    Tuple				=			model(_snake_case						)
				self.parent.assertEqual(
				    result.logits.shape			,(self.batch_size, self.num_channels, self.image_size, self.image_size)						)

				# test greyscale images
				lowercase__   :    Optional[int]				=			1
				lowercase__   :    List[Any]				=			SwinvaForMaskedImageModeling(_snake_case						)
				model.to(_snake_case						)
				model.eval()

				lowercase__   :    Union[str, Any]				=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
				lowercase__   :    str				=			model(_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, 1, self.image_size, self.image_size)						)







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  str			,_snake_case						:  str			,_snake_case						:  Tuple						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Tuple				=			self.type_sequence_label_size
				lowercase__   :    Dict				=			SwinvaForImageClassification(_snake_case						)
				model.to(_snake_case						)
				model.eval()
				lowercase__   :    str				=			model(_snake_case			,labels=_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.type_sequence_label_size)						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Dict:






				"""simple docstring"""



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





@require_torch
class        __A       (	A_     ,A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Union[str, Any]   	=				(
		    (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
		)
		lowerCAmelCase			:					Optional[int]   	=				(
		    {"feature-extraction": SwinvaModel, "image-classification": SwinvaForImageClassification}
		    if is_torch_available()
		    else {}
		)

		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					Dict   	=				False
		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					Any   	=				False







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






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			SwinvaModelTester(self						)
				lowercase__   :    List[str]				=			ConfigTester(self			,config_class=_snake_case			,embed_dim=37						)







		def 					UpperCAmelCase    (	self						:  int						)					->		Any:






				"""simple docstring"""



				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						:  str						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    int				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







		@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.'''						)
		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Optional[int]:






				"""simple docstring"""



				pass







		@unittest.skip(reason='''Swinv2 does not use inputs_embeds'''						)
		def 					UpperCAmelCase    (	self						:  List[str]						)					->		str:






				"""simple docstring"""



				pass







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Tuple:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Optional[int]				=			self.model_tester.prepare_config_and_inputs_for_common()

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







		def 					UpperCAmelCase    (	self						:  int						)					->		List[Any]:






				"""simple docstring"""



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

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

						lowercase__   :    Tuple				=			['''pixel_values''']
						self.assertListEqual(arg_names[:1]			,_snake_case						)







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






				"""simple docstring"""



				lowercase__		,			lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    Tuple				=			True

				for model_class in self.all_model_classes:
						lowercase__   :    Optional[int]				=			True
						lowercase__   :    str				=			False
						lowercase__   :    Union[str, Any]				=			True
						lowercase__   :    Optional[Any]				=			model_class(_snake_case						)
						model.to(_snake_case						)
						model.eval()
						with torch.no_grad():
								lowercase__   :    str				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)
						lowercase__   :    Dict				=			outputs.attentions
						lowercase__   :    Any				=			len(self.model_tester.depths						)
						self.assertEqual(len(_snake_case						)			,_snake_case						)

						# check that output_attentions also work using config
						del inputs_dict["output_attentions"]
						lowercase__   :    List[Any]				=			True
						lowercase__   :    Optional[Any]				=			config.window_size**2
						lowercase__   :    Any				=			model_class(_snake_case						)
						model.to(_snake_case						)
						model.eval()
						with torch.no_grad():
								lowercase__   :    List[str]				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)
						lowercase__   :    Optional[Any]				=			outputs.attentions
						self.assertEqual(len(_snake_case						)			,_snake_case						)

						self.assertListEqual(
						    list(attentions[0].shape[-3:]						)			,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,)
						lowercase__   :    Optional[Any]				=			len(_snake_case						)

						# Check attention is always last and order is fine
						lowercase__   :    Optional[int]				=			True
						lowercase__   :    Tuple				=			True
						lowercase__   :    Optional[Any]				=			model_class(_snake_case						)
						model.to(_snake_case						)
						model.eval()
						with torch.no_grad():
								lowercase__   :    Optional[Any]				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)

						if hasattr(self.model_tester			,'''num_hidden_states_types'''						):
								lowercase__   :    int				=			self.model_tester.num_hidden_states_types
						else:
								# also another +1 for reshaped_hidden_states
								lowercase__   :    List[str]				=			2
						self.assertEqual(out_len + added_hidden_states			,len(_snake_case						)						)

						lowercase__   :    Optional[int]				=			outputs.attentions

						self.assertEqual(len(_snake_case						)			,_snake_case						)

						self.assertListEqual(
						    list(self_attentions[0].shape[-3:]						)			,[self.model_tester.num_heads[0], window_size_squared, window_size_squared]			,)







		def 					UpperCAmelCase    (	self						:  List[str]			,_snake_case						:  int			,_snake_case						:  List[str]			,_snake_case						:  Optional[int]			,_snake_case						:  List[Any]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			model_class(_snake_case						)
				model.to(_snake_case						)
				model.eval()

				with torch.no_grad():
						lowercase__   :    int				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)

				lowercase__   :    Optional[int]				=			outputs.hidden_states

				lowercase__   :    List[Any]				=			getattr(
				    self.model_tester			,'''expected_num_hidden_layers'''			,len(self.model_tester.depths						) + 1						)
				self.assertEqual(len(_snake_case						)			,_snake_case						)

				# Swinv2 has a different seq_length
				lowercase__   :    Dict				=			(
				    config.patch_size
				    if isinstance(config.patch_size			,collections.abc.Iterable						)
				    else (config.patch_size, config.patch_size)
				)

				lowercase__   :    int				=			(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

				self.assertListEqual(
				    list(hidden_states[0].shape[-2:]						)			,[num_patches, self.model_tester.embed_dim]			,)

				lowercase__   :    Tuple				=			outputs.reshaped_hidden_states
				self.assertEqual(len(_snake_case						)			,_snake_case						)

				lowercase__		,			lowercase__		,			lowercase__		,			lowercase__   :    List[str]				=			reshaped_hidden_states[0].shape
				lowercase__   :    int				=			(
				    reshaped_hidden_states[0].view(_snake_case			,_snake_case			,height * width						).permute(0			,2			,1						)
				)
				self.assertListEqual(
				    list(reshaped_hidden_states.shape[-2:]						)			,[num_patches, self.model_tester.embed_dim]			,)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		int:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Optional[int]				=			self.model_tester.prepare_config_and_inputs_for_common()

				lowercase__   :    str				=			(
				    self.model_tester.image_size
				    if isinstance(self.model_tester.image_size			,collections.abc.Iterable						)
				    else (self.model_tester.image_size, self.model_tester.image_size)
				)

				for model_class in self.all_model_classes:
						lowercase__   :    List[str]				=			True
						self.check_hidden_states_output(_snake_case			,_snake_case			,_snake_case			,_snake_case						)

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

						self.check_hidden_states_output(_snake_case			,_snake_case			,_snake_case			,_snake_case						)







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






				"""simple docstring"""



				lowercase__		,			lowercase__   :    List[str]				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    List[Any]				=			3

				lowercase__   :    Tuple				=			(
				    self.model_tester.image_size
				    if isinstance(self.model_tester.image_size			,collections.abc.Iterable						)
				    else (self.model_tester.image_size, self.model_tester.image_size)
				)
				lowercase__   :    Optional[int]				=			(
				    config.patch_size
				    if isinstance(config.patch_size			,collections.abc.Iterable						)
				    else (config.patch_size, config.patch_size)
				)

				lowercase__   :    Dict				=			image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
				lowercase__   :    Dict				=			image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

				for model_class in self.all_model_classes:
						lowercase__   :    str				=			True
						self.check_hidden_states_output(_snake_case			,_snake_case			,_snake_case			,(padded_height, padded_width)						)

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						lowercase__   :    Dict				=			True
						self.check_hidden_states_output(_snake_case			,_snake_case			,_snake_case			,(padded_height, padded_width)						)







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






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Tuple				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_snake_case						)







		@slow
		def 					UpperCAmelCase    (	self						:  List[str]						)					->		Optional[Any]:






				"""simple docstring"""



				for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowercase__   :    Union[str, Any]				=			SwinvaModel.from_pretrained(_snake_case						)
						self.assertIsNotNone(_snake_case						)







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






				"""simple docstring"""



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

				lowercase__   :    Tuple				=			_config_zero_init(_snake_case						)
				for model_class in self.all_model_classes:
						lowercase__   :    Optional[int]				=			model_class(config=_snake_case						)
						for name, param in model.named_parameters():
								if "embeddings" not in name and "logit_scale" not in name and 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"""			,)





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







		'''simple docstring'''





		@cached_property
		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		Tuple:






				"""simple docstring"""



				return (
				    AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''						)
				    if is_vision_available()
				    else None
				)







		@slow
		def 					UpperCAmelCase    (	self						:  Any						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    str				=			SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256'''						).to(
				    _snake_case						)
				lowercase__   :    Union[str, Any]				=			self.default_image_processor

				lowercase__   :    List[str]				=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
				lowercase__   :    Dict				=			image_processor(images=_snake_case			,return_tensors='''pt'''						).to(_snake_case						)

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

				# verify the logits
				lowercase__   :    str				=			torch.Size((1, 1_000)						)
				self.assertEqual(outputs.logits.shape			,_snake_case						)
				lowercase__   :    Dict				=			torch.tensor([-0.3947, -0.4306, 0.0026]						).to(_snake_case						)
				self.assertTrue(torch.allclose(outputs.logits[0, :3]			,_snake_case			,atol=1e-4						)						)
