'''simple docstring'''






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

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
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.31.0''')

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

_UpperCAmelCase    :     List[Any]         =       logging.getLogger(__name__)







@dataclass
class lowercase_       :







   """simple docstring"""

   __lowerCAmelCase         =   field(
       default=1_2_8    ,    metadata={
           "help": (
               "The maximum total input sequence length after tokenization. Sequences longer "
               "than this will be truncated, sequences shorter will be padded."
           )
       }    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Overwrite the cached preprocessed datasets or not."}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    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."
           )
       }    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of training examples to this "
               "value if set."
           )
       }    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
               "value if set."
           )
       }    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of prediction examples to this "
               "value if set."
           )
       }    ,    )







@dataclass
class lowercase_       :







   """simple docstring"""

   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Train language if it is different from the evaluation language."}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Pretrained config name or path if not the same as model_name"}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}			)
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"}    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}    ,    )
   __lowerCAmelCase         =   field(
       default="main"    ,    metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={
           "help": (
               "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
               "with private models)."
           )
       }    ,    )
   __lowerCAmelCase         =   field(
       default=_UpperCamelCase    ,    metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}    ,    )






def  _SCREAMING_SNAKE_CASE		(      ):
     # 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    		=  HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
     _A		,       _A		,       _A    		=  parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('run_xnli'   ,		__snake_case				)

     # 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				)]   ,		)

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     _A    		=  training_args.get_process_log_level()
     logger.setLevel(__snake_case				)
     datasets.utils.logging.set_verbosity(__snake_case				)
     transformers.utils.logging.set_verbosity(__snake_case				)
     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    		=  None
     if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
          _A    		=  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:
               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				)

     # In distributed training, the load_dataset function guarantees that only one local process can concurrently
     # download the dataset.
     # Downloading and loading xnli dataset from the hub.
     if training_args.do_train:
          if model_args.train_language is None:
               _A    		=  load_dataset(
                   'xnli'   ,		model_args.language   ,		split='train'   ,		cache_dir=model_args.cache_dir   ,		use_auth_token=True if model_args.use_auth_token else None   ,		)
          else:
               _A    		=  load_dataset(
                   'xnli'   ,		model_args.train_language   ,		split='train'   ,		cache_dir=model_args.cache_dir   ,		use_auth_token=True if model_args.use_auth_token else None   ,		)
          _A    		=  train_dataset.features['label'].names

     if training_args.do_eval:
          _A    		=  load_dataset(
              'xnli'   ,		model_args.language   ,		split='validation'   ,		cache_dir=model_args.cache_dir   ,		use_auth_token=True if model_args.use_auth_token else None   ,		)
          _A    		=  eval_dataset.features['label'].names

     if training_args.do_predict:
          _A    		=  load_dataset(
              'xnli'   ,		model_args.language   ,		split='test'   ,		cache_dir=model_args.cache_dir   ,		use_auth_token=True if model_args.use_auth_token else None   ,		)
          _A    		=  predict_dataset.features['label'].names

     # Labels
     _A    		=  len(__snake_case				)

     # Load pretrained model and tokenizer
     # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
     # download model & vocab.
     _A    		=  AutoConfig.from_pretrained(
         model_args.config_name if model_args.config_name else model_args.model_name_or_path   ,		num_labels=__snake_case   ,		idalabel={str(__snake_case				): label for i, label in enumerate(__snake_case				)}   ,		labelaid={label: i for i, label in enumerate(__snake_case				)}   ,		finetuning_task='xnli'   ,		cache_dir=model_args.cache_dir   ,		revision=model_args.model_revision   ,		use_auth_token=True if model_args.use_auth_token else None   ,		)
     _A    		=  AutoTokenizer.from_pretrained(
         model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path   ,		do_lower_case=model_args.do_lower_case   ,		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   ,		)
     _A    		=  AutoModelForSequenceClassification.from_pretrained(
         model_args.model_name_or_path   ,		from_tf=bool('.ckpt' in model_args.model_name_or_path				)   ,		config=__snake_case   ,		cache_dir=model_args.cache_dir   ,		revision=model_args.model_revision   ,		use_auth_token=True if model_args.use_auth_token else None   ,		ignore_mismatched_sizes=model_args.ignore_mismatched_sizes   ,		)

     # Preprocessing the datasets
     # Padding strategy
     if data_args.pad_to_max_length:
          _A    		=  'max_length'
     else:
          # We will pad later, dynamically at batch creation, to the max sequence length in each batch
          _A    		=  False

     def preprocess_function(__snake_case							:			List[Any]				):
          # Tokenize the texts
          return tokenizer(
              examples['premise']   ,		examples['hypothesis']   ,		padding=__snake_case   ,		max_length=data_args.max_seq_length   ,		truncation=__snake_case   ,		)

     if training_args.do_train:
          if data_args.max_train_samples is not None:
               _A    		=  min(len(__snake_case				)   ,		data_args.max_train_samples				)
               _A    		=  train_dataset.select(range(__snake_case				)				)
          with training_args.main_process_first(desc='train dataset map pre-processing'				):
               _A    		=  train_dataset.map(
                   __snake_case   ,		batched=__snake_case   ,		load_from_cache_file=not data_args.overwrite_cache   ,		desc='Running tokenizer on train dataset'   ,		)
          # Log a few random samples from the training set:
          for index in random.sample(range(len(__snake_case				)				)   ,		3				):
               logger.info(F'Sample {index} of the training set: {train_dataset[index]}.'				)

     if training_args.do_eval:
          if data_args.max_eval_samples is not None:
               _A    		=  min(len(__snake_case				)   ,		data_args.max_eval_samples				)
               _A    		=  eval_dataset.select(range(__snake_case				)				)
          with training_args.main_process_first(desc='validation dataset map pre-processing'				):
               _A    		=  eval_dataset.map(
                   __snake_case   ,		batched=__snake_case   ,		load_from_cache_file=not data_args.overwrite_cache   ,		desc='Running tokenizer on validation dataset'   ,		)

     if training_args.do_predict:
          if data_args.max_predict_samples is not None:
               _A    		=  min(len(__snake_case				)   ,		data_args.max_predict_samples				)
               _A    		=  predict_dataset.select(range(__snake_case				)				)
          with training_args.main_process_first(desc='prediction dataset map pre-processing'				):
               _A    		=  predict_dataset.map(
                   __snake_case   ,		batched=__snake_case   ,		load_from_cache_file=not data_args.overwrite_cache   ,		desc='Running tokenizer on prediction dataset'   ,		)

    # Get the metric function
     _A    		=  evaluate.load('xnli'				)

     # 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(__snake_case							:			EvalPrediction				):
          _A    		=  p.predictions[0] if isinstance(p.predictions   ,		__snake_case				) else p.predictions
          _A    		=  np.argmax(__snake_case   ,		axis=1				)
          return metric.compute(predictions=__snake_case   ,		references=p.label_ids				)

     # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
     if data_args.pad_to_max_length:
          _A    		=  default_data_collator
     elif training_args.fpaa:
          _A    		=  DataCollatorWithPadding(__snake_case   ,		pad_to_multiple_of=8				)
     else:
          _A    		=  None

     # Initialize our Trainer
     _A    		=  Trainer(
         model=__snake_case   ,		args=__snake_case   ,		train_dataset=train_dataset if training_args.do_train else None   ,		eval_dataset=eval_dataset if training_args.do_eval else None   ,		compute_metrics=__snake_case   ,		tokenizer=__snake_case   ,		data_collator=__snake_case   ,		)

     # Training
     if training_args.do_train:
          _A    		=  None
          if training_args.resume_from_checkpoint is not None:
               _A    		=  training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               _A    		=  last_checkpoint
          _A    		=  trainer.train(resume_from_checkpoint=__snake_case				)
          _A    		=  train_result.metrics
          _A    		=  (
              data_args.max_train_samples if data_args.max_train_samples is not None else len(__snake_case				)
          )
          _A    		=  min(__snake_case   ,		len(__snake_case				)				)

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

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

     # Evaluation
     if training_args.do_eval:
          logger.info('*** Evaluate ***'				)
          _A    		=  trainer.evaluate(eval_dataset=__snake_case				)

          _A    		=  data_args.max_eval_samples if data_args.max_eval_samples is not None else len(__snake_case				)
          _A    		=  min(__snake_case   ,		len(__snake_case				)				)

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

     # Prediction
     if training_args.do_predict:
          logger.info('*** Predict ***'				)
          _A		,       _A		,       _A    		=  trainer.predict(__snake_case   ,		metric_key_prefix='predict'				)

          _A    		=  (
              data_args.max_predict_samples if data_args.max_predict_samples is not None else len(__snake_case				)
          )
          _A    		=  min(__snake_case   ,		len(__snake_case				)				)

          trainer.log_metrics('predict'   ,		__snake_case				)
          trainer.save_metrics('predict'   ,		__snake_case				)

          _A    		=  np.argmax(__snake_case   ,		axis=1				)
          _A    		=  os.path.join(training_args.output_dir   ,		'predictions.txt'				)
          if trainer.is_world_process_zero():
               with open(__snake_case   ,		'w'				) as writer:
                    writer.write('index\tprediction\n'				)
                    for index, item in enumerate(__snake_case				):
                         _A    		=  label_list[item]
                         writer.write(F'{index}\t{item}\n'				)


if __name__ == "__main__":
   main()




'''simple docstring'''






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

   if is_vision_available():
      from transformers import MaskFormerImageProcessor

if is_vision_available():
   from PIL import Image







class lowercase_       :







   """simple docstring"""

   def __init__(      self      :			Optional[Any], UpperCamelCase__      :			Tuple, UpperCamelCase__      :			Any=2, UpperCamelCase__      :			Union[str, Any]=True, UpperCamelCase__      :			Optional[Any]=False, UpperCamelCase__      :			int=10, UpperCamelCase__      :			List[str]=3, UpperCamelCase__      :			List[str]=32 * 4, UpperCamelCase__      :			List[Any]=32 * 6, UpperCamelCase__      :			Dict=4, UpperCamelCase__      :			str=32, )  ->			Dict:
        _A    		=  parent
        _A    		=  batch_size
        _A    		=  is_training
        _A    		=  use_auxiliary_loss
        _A    		=  num_queries
        _A    		=  num_channels
        _A    		=  min_size
        _A    		=  max_size
        _A    		=  num_labels
        _A    		=  mask_feature_size
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			Tuple:
        _A    		=  floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]     ).to(
            UpperCamelCase__     )

        _A    		=  torch.ones([self.batch_size, self.min_size, self.max_size], device=UpperCamelCase__     )

        _A    		=  (
            torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=UpperCamelCase__     ) > 0.5
        ).float()
        _A    		=  (torch.rand((self.batch_size, self.num_labels), device=UpperCamelCase__     ) > 0.5).long()

        _A    		=  self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels
   def 	__UpperCAmelCase   (      self      :			Tuple     )  ->			Optional[int]:
        return MaskFormerConfig.from_backbone_and_decoder_configs(
            backbone_config=SwinConfig(
                depths=[1, 1, 1, 1], ), decoder_config=DetrConfig(
                decoder_ffn_dim=1_28, num_queries=self.num_queries, decoder_attention_heads=2, d_model=self.mask_feature_size, ), mask_feature_size=self.mask_feature_size, fpn_feature_size=self.mask_feature_size, num_channels=self.num_channels, num_labels=self.num_labels, )
   def 	__UpperCAmelCase   (      self      :			int     )  ->			Tuple:
        _A		,       _A		,       _A		,       _A		,       _A    		=  self.prepare_config_and_inputs()
        _A    		=  {'pixel_values': pixel_values, 'pixel_mask': pixel_mask}
        return config, inputs_dict
   def 	__UpperCAmelCase   (      self      :			Optional[int], UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Dict     )  ->			List[Any]:
        _A    		=  output.encoder_hidden_states
        _A    		=  output.pixel_decoder_hidden_states
        _A    		=  output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(UpperCamelCase__     ), len(config.backbone_config.depths     )     )
        self.parent.assertTrue(len(UpperCamelCase__     ), len(config.backbone_config.depths     )     )
        self.parent.assertTrue(len(UpperCamelCase__     ), config.decoder_config.decoder_layers     )
   def 	__UpperCAmelCase   (      self      :			Any, UpperCamelCase__      :			Any, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Optional[int], UpperCamelCase__      :			Optional[Any]=False     )  ->			Optional[Any]:
        with torch.no_grad():
             _A    		=  MaskFormerModel(config=UpperCamelCase__     )
             model.to(UpperCamelCase__     )
             model.eval()

             _A    		=  model(pixel_values=UpperCamelCase__, pixel_mask=UpperCamelCase__     )
             _A    		=  model(UpperCamelCase__, output_hidden_states=UpperCamelCase__     )
        # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
        # encoder and pixel decoder
        self.parent.assertEqual(
            output.transformer_decoder_last_hidden_state.shape, (self.batch_size, self.num_queries, self.mask_feature_size), )
        # let's ensure the other two hidden state exists
        self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None     )
        self.parent.assertTrue(output.encoder_last_hidden_state is not None     )

        if output_hidden_states:
             self.check_output_hidden_state(UpperCamelCase__, UpperCamelCase__     )

   def 	__UpperCAmelCase   (      self      :			List[Any], UpperCamelCase__      :			Tuple, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			int, UpperCamelCase__      :			Optional[Any], UpperCamelCase__      :			Tuple     )  ->			str:
        _A    		=  MaskFormerForInstanceSegmentation(config=UpperCamelCase__     )
        model.to(UpperCamelCase__     )
        model.eval()

        def comm_check_on_output(UpperCamelCase__      :			Any     ):
             # let's still check that all the required stuff is there
             self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None     )
             self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None     )
             self.parent.assertTrue(result.encoder_last_hidden_state is not None     )
             # okay, now we need to check the logits shape
             # due to the encoder compression, masks have a //4 spatial size
             self.parent.assertEqual(
                 result.masks_queries_logits.shape, (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4), )
             # + 1 for null class
             self.parent.assertEqual(
                 result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)     )

        with torch.no_grad():
             _A    		=  model(pixel_values=UpperCamelCase__, pixel_mask=UpperCamelCase__     )
             _A    		=  model(UpperCamelCase__     )

             comm_check_on_output(UpperCamelCase__     )

             _A    		=  model(
                 pixel_values=UpperCamelCase__, pixel_mask=UpperCamelCase__, mask_labels=UpperCamelCase__, class_labels=UpperCamelCase__     )

        comm_check_on_output(UpperCamelCase__     )

        self.parent.assertTrue(result.loss is not None     )
        self.parent.assertEqual(result.loss.shape, torch.Size([1]     )     )







@require_torch
class lowercase_       (		_UpperCamelCase    ,    _UpperCamelCase    ,    unittest.TestCase			):







   """simple docstring"""

   __lowerCAmelCase         =   (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
   __lowerCAmelCase         =   (
       {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation}
       if is_torch_available()
       else {}
   )

   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   __lowerCAmelCase         =   False
   def 	__UpperCAmelCase   (      self      :			Optional[Any]     )  ->			Tuple:
        _A    		=  MaskFormerModelTester(self     )
        _A    		=  ConfigTester(self, config_class=UpperCamelCase__, has_text_modality=UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			List[str]     )  ->			int:
        self.config_tester.run_common_tests()
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			int:
        _A		,       _A    		=  self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskformer_model(UpperCamelCase__, **UpperCamelCase__, output_hidden_states=UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			List[str]     )  ->			Optional[int]:
        _A    		=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*UpperCamelCase__     )
   @unittest.skip(reason='MaskFormer does not use inputs_embeds'     )
   def 	__UpperCAmelCase   (      self      :			Optional[Any]     )  ->			Any:
        pass
   @unittest.skip(reason='MaskFormer does not have a get_input_embeddings method'     )
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			Union[str, Any]:
        pass
   @unittest.skip(reason='MaskFormer is not a generative model'     )
   def 	__UpperCAmelCase   (      self      :			Tuple     )  ->			Union[str, Any]:
        pass
   @unittest.skip(reason='MaskFormer does not use token embeddings'     )
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Union[str, Any]:
        pass
   @require_torch_multi_gpu
   @unittest.skip(
       reason='MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'     )
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			Union[str, Any]:
        pass
   @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'     )
   def 	__UpperCAmelCase   (      self      :			Any     )  ->			Any:
        pass
   def 	__UpperCAmelCase   (      self      :			Union[str, Any]     )  ->			List[str]:
        _A		,       _A    		=  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             _A    		=  model_class(UpperCamelCase__     )
             _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], UpperCamelCase__     )
   @slow
   def 	__UpperCAmelCase   (      self      :			Optional[int]     )  ->			Optional[int]:
        for model_name in ["facebook/maskformer-swin-small-coco"]:
             _A    		=  MaskFormerModel.from_pretrained(UpperCamelCase__     )
             self.assertIsNotNone(UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			Optional[Any]     )  ->			List[Any]:
        _A    		=  (self.model_tester.min_size,) * 2
        _A    		=  {
            'pixel_values': torch.randn((2, 3, *size), device=UpperCamelCase__     ),
            'mask_labels': torch.randn((2, 10, *size), device=UpperCamelCase__     ),
            'class_labels': torch.zeros(2, 10, device=UpperCamelCase__     ).long(),
        }

        _A    		=  MaskFormerForInstanceSegmentation(MaskFormerConfig()     ).to(UpperCamelCase__     )
        _A    		=  model(**UpperCamelCase__     )
        self.assertTrue(outputs.loss is not None     )
   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			Dict:
        _A		,       _A    		=  self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskformer_model(UpperCamelCase__, **UpperCamelCase__, output_hidden_states=UpperCamelCase__     )
   def 	__UpperCAmelCase   (      self      :			int     )  ->			Tuple:
        _A		,       _A    		=  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             _A    		=  model_class(UpperCamelCase__     ).to(UpperCamelCase__     )
             _A    		=  model(**UpperCamelCase__, output_attentions=UpperCamelCase__     )
             self.assertTrue(outputs.attentions is not None     )
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			List[Any]:
        if not self.model_tester.is_training:
             return
        # only MaskFormerForInstanceSegmentation has the loss
        _A    		=  self.all_model_classes[1]
        _A		,       _A		,       _A		,       _A		,       _A    		=  self.model_tester.prepare_config_and_inputs()

        _A    		=  model_class(UpperCamelCase__     )
        model.to(UpperCamelCase__     )
        model.train()

        _A    		=  model(UpperCamelCase__, mask_labels=UpperCamelCase__, class_labels=UpperCamelCase__     ).loss
        loss.backward()

   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			List[str]:
        # only MaskFormerForInstanceSegmentation has the loss
        _A    		=  self.all_model_classes[1]
        _A		,       _A		,       _A		,       _A		,       _A    		=  self.model_tester.prepare_config_and_inputs()
        _A    		=  True
        _A    		=  True

        _A    		=  model_class(UpperCamelCase__     )
        model.to(UpperCamelCase__     )
        model.train()

        _A    		=  model(UpperCamelCase__, mask_labels=UpperCamelCase__, class_labels=UpperCamelCase__     )

        _A    		=  outputs.encoder_hidden_states[0]
        encoder_hidden_states.retain_grad()

        _A    		=  outputs.pixel_decoder_hidden_states[0]
        pixel_decoder_hidden_states.retain_grad()
        # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
        _A    		=  outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

        _A    		=  outputs.attentions[0]
        attentions.retain_grad()

        outputs.loss.backward(retain_graph=UpperCamelCase__     )

        self.assertIsNotNone(encoder_hidden_states.grad     )
        self.assertIsNotNone(pixel_decoder_hidden_states.grad     )
        self.assertIsNotNone(transformer_decoder_hidden_states.grad     )
        self.assertIsNotNone(attentions.grad     )






_UpperCAmelCase    :     Any         =       1E-4





def  _SCREAMING_SNAKE_CASE		(      ):
     _A    		=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
     return image







@require_vision
@slow
class lowercase_       (		unittest.TestCase			):







   """simple docstring"""

   @cached_property
   def 	__UpperCAmelCase   (      self      :			str     )  ->			Optional[int]:
        return (
            MaskFormerImageProcessor.from_pretrained('facebook/maskformer-swin-small-coco'     )
            if is_vision_available()
            else None
        )
   def 	__UpperCAmelCase   (      self      :			Any     )  ->			List[str]:
        _A    		=  MaskFormerModel.from_pretrained('facebook/maskformer-swin-small-coco'     ).to(UpperCamelCase__     )
        _A    		=  self.default_image_processor
        _A    		=  prepare_img()
        _A    		=  image_processor(UpperCamelCase__, return_tensors='pt'     ).to(UpperCamelCase__     )
        _A    		=  inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
        # check size
        self.assertEqual(UpperCamelCase__, (1, 3, 8_00, 10_88)     )

        with torch.no_grad():
             _A    		=  model(**UpperCamelCase__     )

        _A    		=  torch.tensor(
            [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]     ).to(UpperCamelCase__     )
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )

        _A    		=  torch.tensor(
            [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]     ).to(UpperCamelCase__     )
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )

        _A    		=  torch.tensor(
            [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]     ).to(UpperCamelCase__     )
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )
   def 	__UpperCAmelCase   (      self      :			Union[str, Any]     )  ->			Optional[int]:
        _A    		=  (
            MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco'     )
            .to(UpperCamelCase__     )
            .eval()
        )
        _A    		=  self.default_image_processor
        _A    		=  prepare_img()
        _A    		=  image_processor(UpperCamelCase__, return_tensors='pt'     ).to(UpperCamelCase__     )
        _A    		=  inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
        # check size
        self.assertEqual(UpperCamelCase__, (1, 3, 8_00, 10_88)     )

        with torch.no_grad():
             _A    		=  model(**UpperCamelCase__     )
        # masks_queries_logits
        _A    		=  outputs.masks_queries_logits
        self.assertEqual(
            masks_queries_logits.shape, (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4), )
        _A    		=  [
            [-1.3_737_124, -1.7_724_937, -1.9_364_233],
            [-1.5_977_281, -1.9_867_939, -2.1_523_695],
            [-1.5_795_398, -1.9_269_832, -2.093_942],
        ]
        _A    		=  torch.tensor(UpperCamelCase__     ).to(UpperCamelCase__     )
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )
        # class_queries_logits
        _A    		=  outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape, (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
        _A    		=  torch.tensor(
            [
                [1.6512e00, -5.2572e00, -3.3519e00],
                [3.6169e-02, -5.9025e00, -2.9313e00],
                [1.0766e-04, -7.7630e00, -5.1263e00],
            ]     ).to(UpperCamelCase__     )
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )
   def 	__UpperCAmelCase   (      self      :			List[Any]     )  ->			Optional[Any]:
        _A    		=  (
            MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-resnet101-coco-stuff'     )
            .to(UpperCamelCase__     )
            .eval()
        )
        _A    		=  self.default_image_processor
        _A    		=  prepare_img()
        _A    		=  image_processor(UpperCamelCase__, return_tensors='pt'     ).to(UpperCamelCase__     )
        _A    		=  inputs['pixel_values'].shape
        # check size is divisible by 32
        self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0     )
        # check size
        self.assertEqual(UpperCamelCase__, (1, 3, 8_00, 10_88)     )

        with torch.no_grad():
             _A    		=  model(**UpperCamelCase__     )
        # masks_queries_logits
        _A    		=  outputs.masks_queries_logits
        self.assertEqual(
            masks_queries_logits.shape, (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4), )
        _A    		=  [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
        _A    		=  torch.tensor(UpperCamelCase__     ).to(UpperCamelCase__     )
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )
        # class_queries_logits
        _A    		=  outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape, (1, model.config.decoder_config.num_queries, model.config.num_labels + 1)     )
        _A    		=  torch.tensor(
            [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]     ).to(UpperCamelCase__     )
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], UpperCamelCase__, atol=UpperCamelCase__     )     )

   def 	__UpperCAmelCase   (      self      :			Dict     )  ->			int:
        _A    		=  (
            MaskFormerForInstanceSegmentation.from_pretrained('facebook/maskformer-swin-small-coco'     )
            .to(UpperCamelCase__     )
            .eval()
        )
        _A    		=  self.default_image_processor

        _A    		=  image_processor(
            [np.zeros((3, 8_00, 13_33)     ), np.zeros((3, 8_00, 13_33)     )], segmentation_maps=[np.zeros((3_84, 3_84)     ).astype(np.floataa     ), np.zeros((3_84, 3_84)     ).astype(np.floataa     )], return_tensors='pt', )

        _A    		=  inputs['pixel_values'].to(UpperCamelCase__     )
        _A    		=  [el.to(UpperCamelCase__     ) for el in inputs['mask_labels']]
        _A    		=  [el.to(UpperCamelCase__     ) for el in inputs['class_labels']]

        with torch.no_grad():
             _A    		=  model(**UpperCamelCase__     )

        self.assertTrue(outputs.loss is not None     )



