

'''simple docstring'''



import argparse
import glob
import logging
import os
import time
from argparse import Namespace

import numpy as np
import torch
from lightning_base import BaseTransformer, add_generic_args, generic_train
from torch.utils.data import DataLoader, TensorDataset

from transformers import glue_compute_metrics as compute_metrics
from transformers import glue_convert_examples_to_features as convert_examples_to_features
from transformers import glue_output_modes, glue_tasks_num_labels
from transformers import glue_processors as processors


UpperCAmelCase					:			str       =	logging.getLogger(__name__)







class 		lowerCAmelCase__  ( a   ):



 """simple docstring"""



 lowerCAmelCase__       = "sequence-classification"
 def __init__(						self   :			str   ,				__SCREAMING_SNAKE_CASE   :			str     )    ->					Optional[Any]:


      """simple docstring"""




      if type(lowerCamelCase__     ) == dict:
           __SCREAMING_SNAKE_CASE      = Namespace(**lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = glue_output_modes[hparams.task]
      __SCREAMING_SNAKE_CASE      = glue_tasks_num_labels[hparams.task]

      super().__init__(lowerCamelCase__   ,				lowerCamelCase__   ,				self.mode     )
 def  UpperCAmelCase__						(						self   :			Tuple   ,				**__SCREAMING_SNAKE_CASE   :			List[Any]     )    ->					Dict:


      """simple docstring"""




      return self.model(**lowerCamelCase__     )
 def  UpperCAmelCase__						(						self   :			str   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]   ,				__SCREAMING_SNAKE_CASE   :			Optional[Any]     )    ->					Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}

      if self.config.model_type not in ["distilbert", "bart"]:
           __SCREAMING_SNAKE_CASE      = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None

      __SCREAMING_SNAKE_CASE      = self(**lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = outputs[0]

      __SCREAMING_SNAKE_CASE      = self.trainer.lr_schedulers[0]['scheduler']
      __SCREAMING_SNAKE_CASE      = {'loss': loss, 'rate': lr_scheduler.get_last_lr()[-1]}
      return {"loss": loss, "log": tensorboard_logs}
 def  UpperCAmelCase__						(						self   :			List[Any]     )    ->					Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self.hparams
      __SCREAMING_SNAKE_CASE      = processors[args.task]()
      __SCREAMING_SNAKE_CASE      = processor.get_labels()

      for mode in ["train", "dev"]:
           __SCREAMING_SNAKE_CASE      = self._feature_file(lowerCamelCase__     )
           if os.path.exists(lowerCamelCase__     ) and not args.overwrite_cache:
                logger.info("""Loading features from cached file %s"""   ,				lowerCamelCase__     )
           else:
                logger.info("""Creating features from dataset file at %s"""   ,				args.data_dir     )
                __SCREAMING_SNAKE_CASE      = (
                    processor.get_dev_examples(args.data_dir     )
                    if mode == 'dev'
                    else processor.get_train_examples(args.data_dir     )
                )
                __SCREAMING_SNAKE_CASE      = convert_examples_to_features(
                    lowerCamelCase__   ,				self.tokenizer   ,				max_length=args.max_seq_length   ,				label_list=self.labels   ,				output_mode=args.glue_output_mode   ,				)
                logger.info("""Saving features into cached file %s"""   ,				lowerCamelCase__     )
                torch.save(lowerCamelCase__   ,				lowerCamelCase__     )
 def  UpperCAmelCase__						(						self   :			List[str]   ,				__SCREAMING_SNAKE_CASE   :			str   ,				__SCREAMING_SNAKE_CASE   :			int   ,				__SCREAMING_SNAKE_CASE   :			bool = False     )    ->					Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = 'dev' if mode == 'test' else mode

      __SCREAMING_SNAKE_CASE      = self._feature_file(lowerCamelCase__     )
      logger.info("""Loading features from cached file %s"""   ,				lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = torch.load(lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = torch.tensor([f.input_ids for f in features]   ,				dtype=torch.long     )
      __SCREAMING_SNAKE_CASE      = torch.tensor([f.attention_mask for f in features]   ,				dtype=torch.long     )
      __SCREAMING_SNAKE_CASE      = torch.tensor([f.token_type_ids for f in features]   ,				dtype=torch.long     )
      if self.hparams.glue_output_mode == "classification":
           __SCREAMING_SNAKE_CASE      = torch.tensor([f.label for f in features]   ,				dtype=torch.long     )
      elif self.hparams.glue_output_mode == "regression":
           __SCREAMING_SNAKE_CASE      = torch.tensor([f.label for f in features]   ,				dtype=torch.float     )

      return DataLoader(
          TensorDataset(lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__   ,				lowerCamelCase__     )   ,				batch_size=lowerCamelCase__   ,				shuffle=lowerCamelCase__   ,				)
 def  UpperCAmelCase__						(						self   :			List[Any]   ,				__SCREAMING_SNAKE_CASE   :			Tuple   ,				__SCREAMING_SNAKE_CASE   :			List[str]     )    ->					Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]}

      if self.config.model_type not in ["distilbert", "bart"]:
           __SCREAMING_SNAKE_CASE      = batch[2] if self.config.model_type in ['bert', 'xlnet', 'albert'] else None

      __SCREAMING_SNAKE_CASE      = self(**lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = outputs[:2]
      __SCREAMING_SNAKE_CASE      = logits.detach().cpu().numpy()
      __SCREAMING_SNAKE_CASE      = inputs['labels'].detach().cpu().numpy()

      return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids}
 def  UpperCAmelCase__						(						self   :			int   ,				__SCREAMING_SNAKE_CASE   :			Union[str, Any]     )    ->					str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = torch.stack([x["""val_loss"""] for x in outputs]     ).mean().detach().cpu().item()
      __SCREAMING_SNAKE_CASE      = np.concatenate([x["""pred"""] for x in outputs]   ,				axis=0     )

      if self.hparams.glue_output_mode == "classification":
           __SCREAMING_SNAKE_CASE      = np.argmax(lowerCamelCase__   ,				axis=1     )
      elif self.hparams.glue_output_mode == "regression":
           __SCREAMING_SNAKE_CASE      = np.squeeze(lowerCamelCase__     )

      __SCREAMING_SNAKE_CASE      = np.concatenate([x["""target"""] for x in outputs]   ,				axis=0     )
      __SCREAMING_SNAKE_CASE      = [[] for _ in range(out_label_ids.shape[0]     )]
      __SCREAMING_SNAKE_CASE      = [[] for _ in range(out_label_ids.shape[0]     )]

      __SCREAMING_SNAKE_CASE      = {**{'val_loss': val_loss_mean}, **compute_metrics(self.hparams.task   ,				lowerCamelCase__   ,				lowerCamelCase__     )}

      __SCREAMING_SNAKE_CASE      = dict(results.items()     )
      __SCREAMING_SNAKE_CASE      = results
      return ret, preds_list, out_label_list
 def  UpperCAmelCase__						(						self   :			str   ,				__SCREAMING_SNAKE_CASE   :			list     )    ->					str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self._eval_end(lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = ret['log']
      return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs}
 def  UpperCAmelCase__						(						self   :			Optional[Any]   ,				__SCREAMING_SNAKE_CASE   :			Any     )    ->					Optional[int]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE      = self._eval_end(lowerCamelCase__     )
      __SCREAMING_SNAKE_CASE      = ret['log']
      # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss`
      return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs}


 @staticmethod
 def  UpperCAmelCase__						(						__SCREAMING_SNAKE_CASE   :			Any   ,				__SCREAMING_SNAKE_CASE   :			List[str]     )    ->					int:


      """simple docstring"""




      BaseTransformer.add_model_specific_args(lowerCamelCase__   ,				lowerCamelCase__     )
      parser.add_argument(
          """--max_seq_length"""   ,				default=128   ,				type=lowerCamelCase__   ,				help=(
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )   ,				)

      parser.add_argument(
          """--task"""   ,				default=""""""   ,				type=lowerCamelCase__   ,				required=lowerCamelCase__   ,				help="""The GLUE task to run"""   ,				)
      parser.add_argument(
          """--gpus"""   ,				default=0   ,				type=lowerCamelCase__   ,				help="""The number of GPUs allocated for this, it is by default 0 meaning none"""   ,				)

      parser.add_argument(
          """--overwrite_cache"""   ,				action="""store_true"""   ,				help="""Overwrite the cached training and evaluation sets"""     )

      return parser







def   a__			(    ):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE      = argparse.ArgumentParser()
     add_generic_args(UpperCAmelCase_ ,       os.getcwd()		)
     __SCREAMING_SNAKE_CASE      = GLUETransformer.add_model_specific_args(UpperCAmelCase_ ,       os.getcwd()		)
     __SCREAMING_SNAKE_CASE      = parser.parse_args()

     # If output_dir not provided, a folder will be generated in pwd
     if args.output_dir is None:
          __SCREAMING_SNAKE_CASE      = os.path.join(
              """./results""" ,       F'{args.task}_{time.strftime("%Y%m%d_%H%M%S"		)}' ,       )
          os.makedirs(args.output_dir		)

     __SCREAMING_SNAKE_CASE      = GLUETransformer(UpperCAmelCase_		)
     __SCREAMING_SNAKE_CASE      = generic_train(UpperCAmelCase_ ,       UpperCAmelCase_		)

     # Optionally, predict on dev set and write to output_dir
     if args.do_predict:
          __SCREAMING_SNAKE_CASE      = sorted(glob.glob(os.path.join(args.output_dir ,       """checkpoint-epoch=*.ckpt"""		) ,       recursive=UpperCAmelCase_		)		)
          __SCREAMING_SNAKE_CASE      = model.load_from_checkpoint(checkpoints[-1]		)
          return trainer.test(UpperCAmelCase_		)


if __name__ == "__main__":
  main()











'''simple docstring'''
import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

from ...test_backbone_common import BackboneTesterMixin
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 torch import nn

					from transformers import MaskFormerSwinBackbone
					from transformers.models.maskformer import MaskFormerSwinModel






class 				lowercase__      :





	def __init__(					self   :							Tuple					,lowerCamelCase__   :							str					,lowerCamelCase__   :							str=13					,lowerCamelCase__   :							List[Any]=32					,lowerCamelCase__   :							Optional[int]=2					,lowerCamelCase__   :							str=3					,lowerCamelCase__   :							Optional[int]=16					,lowerCamelCase__   :							Union[str, Any]=[1, 2, 1]					,lowerCamelCase__   :							Optional[int]=[2, 2, 4]					,lowerCamelCase__   :							int=2					,lowerCamelCase__   :							Any=2.0					,lowerCamelCase__   :							Dict=True					,lowerCamelCase__   :							List[Any]=0.0					,lowerCamelCase__   :							List[str]=0.0					,lowerCamelCase__   :							Union[str, Any]=0.1					,lowerCamelCase__   :							List[Any]="gelu"					,lowerCamelCase__   :							int=False					,lowerCamelCase__   :							Any=True					,lowerCamelCase__   :							List[Any]=0.0_2					,lowerCamelCase__   :							Dict=1E-5					,lowerCamelCase__   :							Optional[int]=True					,lowerCamelCase__   :							int=None					,lowerCamelCase__   :							int=True					,lowerCamelCase__   :							List[Any]=10					,lowerCamelCase__   :							int=8					,lowerCamelCase__   :							Any=["stage1", "stage2", "stage3"]					,lowerCamelCase__   :							List[str]=[1, 2, 3]					,):







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





	def       UpperCamelCase_    (					self   :							Any					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

							_UpperCamelCase   :						Dict												=  self.get_config()

							return config, pixel_values, labels





	def       UpperCamelCase_    (					self   :							List[str]					):







							'''simple docstring'''
							return MaskFormerSwinConfig(
							    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					,out_features=self.out_features					,out_indices=self.out_indices					,)





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







							'''simple docstring'''
							_UpperCamelCase   :						Tuple												=  MaskFormerSwinModel(config=lowerCamelCase__					)
							model.to(lowerCamelCase__					)
							model.eval()
							_UpperCamelCase   :						Dict												=  model(lowerCamelCase__					)

							_UpperCamelCase   :						Tuple												=  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
							_UpperCamelCase   :						Optional[Any]												=  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   :							int					,lowerCamelCase__   :							Union[str, Any]					,lowerCamelCase__   :							Optional[Any]					,lowerCamelCase__   :							Union[str, Any]					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  MaskFormerSwinBackbone(config=lowerCamelCase__					)
							model.to(lowerCamelCase__					)
							model.eval()
							_UpperCamelCase   :						List[Any]												=  model(lowerCamelCase__					)

							# verify feature maps
							self.parent.assertEqual(len(result.feature_maps					)					,len(config.out_features					)					)
							self.parent.assertListEqual(list(result.feature_maps[0].shape					)					,[13, 16, 16, 16]					)

							# verify channels
							self.parent.assertEqual(len(model.channels					)					,len(config.out_features					)					)
							self.parent.assertListEqual(model.channels					,[16, 32, 64]					)

							# verify ValueError
							with self.parent.assertRaises(lowerCamelCase__					):
													_UpperCamelCase   :						Union[str, Any]												=  ['stem']
													_UpperCamelCase   :						int												=  MaskFormerSwinBackbone(config=lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							Dict					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  self.prepare_config_and_inputs()
							_UpperCamelCase							,     _UpperCamelCase							,     _UpperCamelCase   :						str												=  config_and_inputs
							_UpperCamelCase   :						int												=  {'pixel_values': pixel_values}
							return config, inputs_dict






@require_torch
class 				lowercase__      (				lowercase		,   lowercase		,   unittest.TestCase  ):
	lowercase__    							=     (
	    (
	        MaskFormerSwinModel,
	        MaskFormerSwinBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__    							=     {"""feature-extraction""": MaskFormerSwinModel} if is_torch_available() else {}
	lowercase__    							=     False
	lowercase__    							=     False
	lowercase__    							=     False
	lowercase__    							=     False
	lowercase__    							=     False





	def       UpperCamelCase_    (					self   :							Tuple					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  MaskFormerSwinModelTester(self					)
							_UpperCamelCase   :						Union[str, Any]												=  ConfigTester(self					,config_class=lowerCamelCase__					,embed_dim=37					)





	@require_torch_multi_gpu
	@unittest.skip(
	    reason=(
	        '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with'
	        ' `nn.DataParallel`'
	    )					)
	def       UpperCamelCase_    (					self   :							Optional[Any]					):







							'''simple docstring'''
							pass





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







							'''simple docstring'''
							return





	def       UpperCamelCase_    (					self   :							Optional[int]					):







							'''simple docstring'''
							_UpperCamelCase   :						str												=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							Optional[Any]					):







							'''simple docstring'''
							_UpperCamelCase   :						Dict												=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_backbone(*lowerCamelCase__					)





	@unittest.skip('Swin does not use inputs_embeds'					)
	def       UpperCamelCase_    (					self   :							Dict					):







							'''simple docstring'''
							pass





	@unittest.skip('Swin does not support feedforward chunking'					)
	def       UpperCamelCase_    (					self   :							Tuple					):







							'''simple docstring'''
							pass





	def       UpperCamelCase_    (					self   :							List[str]					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						Dict												=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCamelCase   :						Any												=  model_class(lowerCamelCase__					)
													self.assertIsInstance(model.get_input_embeddings()					,(nn.Module)					)
													_UpperCamelCase   :						str												=  model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCamelCase__					,nn.Linear					)					)





	def       UpperCamelCase_    (					self   :							int					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						Optional[Any]												=  self.model_tester.prepare_config_and_inputs_for_common()

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

													_UpperCamelCase   :						Union[str, Any]												=  ['pixel_values']
													self.assertListEqual(arg_names[:1]					,lowerCamelCase__					)





	@unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions'					)
	def       UpperCamelCase_    (					self   :							Optional[int]					):







							'''simple docstring'''
							pass





	@unittest.skip(reason='MaskFormerSwin is only used as an internal backbone'					)
	def       UpperCamelCase_    (					self   :							Optional[int]					):







							'''simple docstring'''
							pass





	def       UpperCamelCase_    (					self   :							Optional[Any]					,lowerCamelCase__   :							Union[str, Any]					,lowerCamelCase__   :							Tuple					,lowerCamelCase__   :							List[Any]					,lowerCamelCase__   :							Tuple					):







							'''simple docstring'''
							_UpperCamelCase   :						Tuple												=  model_class(lowerCamelCase__					)
							model.to(lowerCamelCase__					)
							model.eval()

							with torch.no_grad():
													_UpperCamelCase   :						List[Any]												=  model(**self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					)					)

							_UpperCamelCase   :						List[Any]												=  outputs.hidden_states

							_UpperCamelCase   :						Any												=  getattr(
							    self.model_tester					,'expected_num_hidden_layers'					,len(self.model_tester.depths					) + 1					)
							self.assertEqual(len(lowerCamelCase__					)					,lowerCamelCase__					)

							# Swin has a different seq_length
							_UpperCamelCase   :						Tuple												=  (
							    config.patch_size
							    if isinstance(config.patch_size					,collections.abc.Iterable					)
							    else (config.patch_size, config.patch_size)
							)

							_UpperCamelCase   :						Optional[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]					,)





	def       UpperCamelCase_    (					self   :							Optional[Any]					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						Optional[int]												=  self.model_tester.prepare_config_and_inputs_for_common()

							_UpperCamelCase   :						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:
													_UpperCamelCase   :						Union[str, Any]												=  True
													self.check_hidden_states_output(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					)

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

													self.check_hidden_states_output(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					)





	def       UpperCamelCase_    (					self   :							Dict					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						Union[str, Any]												=  self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase   :						List[Any]												=  3

							_UpperCamelCase   :						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)
							)
							_UpperCamelCase   :						Tuple												=  (
							    config.patch_size
							    if isinstance(config.patch_size					,collections.abc.Iterable					)
							    else (config.patch_size, config.patch_size)
							)

							_UpperCamelCase   :						List[Any]												=  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							_UpperCamelCase   :						Optional[Any]												=  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes:
													_UpperCamelCase   :						Dict												=  True
													self.check_hidden_states_output(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,(padded_height, padded_width)					)

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





	@unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints'					)
	def       UpperCamelCase_    (					self   :							Tuple					):







							'''simple docstring'''
							pass





	@unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin'					)
	def       UpperCamelCase_    (					self   :							int					):







							'''simple docstring'''
							pass





	@unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin'					)
	def       UpperCamelCase_    (					self   :							Optional[int]					):







							'''simple docstring'''
							pass





	def       UpperCamelCase_    (					self   :							Any					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						str												=  self.model_tester.prepare_config_and_inputs_for_common()

							def set_nan_tensor_to_zero(lowerCamelCase__   :							str					):
													_UpperCamelCase   :						List[str]												=  0
													return t

							def check_equivalence(lowerCamelCase__   :							Optional[Any]					,lowerCamelCase__   :							Optional[int]					,lowerCamelCase__   :							Optional[int]					,lowerCamelCase__   :							Optional[int]={}					):
													with torch.no_grad():
																			_UpperCamelCase   :						List[str]												=  model(**lowerCamelCase__					,return_dict=lowerCamelCase__					,**lowerCamelCase__					)
																			_UpperCamelCase   :						Optional[Any]												=  model(**lowerCamelCase__					,return_dict=lowerCamelCase__					,**lowerCamelCase__					).to_tuple()

																			def recursive_check(lowerCamelCase__   :							Optional[int]					,lowerCamelCase__   :							int					):
																									if isinstance(lowerCamelCase__					,(List, Tuple)					):
																															for tuple_iterable_value, dict_iterable_value in zip(lowerCamelCase__					,lowerCamelCase__					):
																																					recursive_check(lowerCamelCase__					,lowerCamelCase__					)
																									elif isinstance(lowerCamelCase__					,lowerCamelCase__					):
																															for tuple_iterable_value, dict_iterable_value in zip(
																															    tuple_object.values()					,dict_object.values()					):
																																					recursive_check(lowerCamelCase__					,lowerCamelCase__					)
																									elif tuple_object is None:
																															return
																									else:
																															self.assertTrue(
																															    torch.allclose(
																															        set_nan_tensor_to_zero(lowerCamelCase__					)					,set_nan_tensor_to_zero(lowerCamelCase__					)					,atol=1E-5					)					,msg=(
																															        'Tuple and dict output are not equal. Difference:'
																															        F' {torch.max(torch.abs(tuple_object - dict_object					)					)}. Tuple has `nan`:'
																															        F' {torch.isnan(lowerCamelCase__					).any()} and `inf`: {torch.isinf(lowerCamelCase__					)}. Dict has'
																															        F' `nan`: {torch.isnan(lowerCamelCase__					).any()} and `inf`: {torch.isinf(lowerCamelCase__					)}.'
																															    )					,)

																			recursive_check(lowerCamelCase__					,lowerCamelCase__					)

							for model_class in self.all_model_classes:
													_UpperCamelCase   :						List[str]												=  model_class(lowerCamelCase__					)
													model.to(lowerCamelCase__					)
													model.eval()

													_UpperCamelCase   :						Optional[Any]												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					)
													_UpperCamelCase   :						Dict												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					)
													check_equivalence(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					)

													_UpperCamelCase   :						int												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					,return_labels=lowerCamelCase__					)
													_UpperCamelCase   :						Optional[Any]												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					,return_labels=lowerCamelCase__					)
													check_equivalence(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					)

													_UpperCamelCase   :						Optional[Any]												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					)
													_UpperCamelCase   :						Any												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					)
													check_equivalence(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,{'output_hidden_states': True}					)

													_UpperCamelCase   :						Union[str, Any]												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					,return_labels=lowerCamelCase__					)
													_UpperCamelCase   :						str												=  self._prepare_for_class(lowerCamelCase__					,lowerCamelCase__					,return_labels=lowerCamelCase__					)
													check_equivalence(lowerCamelCase__					,lowerCamelCase__					,lowerCamelCase__					,{'output_hidden_states': True}					)






@require_torch
class 				lowercase__      (				unittest.TestCase		,   lowercase  ):
	lowercase__    							=     (MaskFormerSwinBackbone,) if is_torch_available() else ()
	lowercase__    							=     MaskFormerSwinConfig





	def       UpperCamelCase_    (					self   :							Dict					):







							'''simple docstring'''
							_UpperCamelCase   :						Union[str, Any]												=  MaskFormerSwinModelTester(self					)





	def       UpperCamelCase_    (					self   :							List[Any]					):







							'''simple docstring'''
							_UpperCamelCase							,     _UpperCamelCase   :						List[str]												=  self.model_tester.prepare_config_and_inputs_for_common()
							_UpperCamelCase   :						str												=  inputs_dict['pixel_values'].shape[0]

							for backbone_class in self.all_model_classes:
													_UpperCamelCase   :						List[Any]												=  backbone_class(lowerCamelCase__					)
													backbone.to(lowerCamelCase__					)
													backbone.eval()

													_UpperCamelCase   :						Optional[Any]												=  backbone(**lowerCamelCase__					)

													# Test default outputs and verify feature maps
													self.assertIsInstance(outputs.feature_maps					,lowerCamelCase__					)
													self.assertTrue(len(outputs.feature_maps					) == len(backbone.channels					)					)
													for feature_map, n_channels in zip(outputs.feature_maps					,backbone.channels					):
																			self.assertTrue(feature_map.shape[:2]					,(batch_size, n_channels)					)
													self.assertIsNone(outputs.hidden_states					)
													self.assertIsNone(outputs.attentions					)

													# Test output_hidden_states=True
													_UpperCamelCase   :						List[str]												=  backbone(**lowerCamelCase__					,output_hidden_states=lowerCamelCase__					)
													self.assertIsNotNone(outputs.hidden_states					)
													self.assertTrue(len(outputs.hidden_states					)					,len(backbone.stage_names					)					)
													# We skip the stem layer
													for hidden_states, n_channels in zip(outputs.hidden_states[1:]					,backbone.channels					):
																			for hidden_state in hidden_states:
																									# Hidden states are in the format (batch_size, (height * width), n_channels)
																									_UpperCamelCase							,     _UpperCamelCase							,     _UpperCamelCase   :						Optional[Any]												=  hidden_state.shape
																									self.assertTrue((h_batch_size, h_n_channels)					,(batch_size, n_channels)					)

            # Test output_attentions=True
													if self.has_attentions:
																			_UpperCamelCase   :						int												=  backbone(**lowerCamelCase__					,output_attentions=lowerCamelCase__					)
																			self.assertIsNotNone(outputs.attentions					)


