




# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


snake_case_ : List[Any]    		=       float("nan")







class __snake_case			:







   def __init__(      self		:						Optional[int]					,						_snake_case		:						int):

        """simple docstring"""


        UpperCAmelCase_          =							sys.stdout
        UpperCAmelCase_          =							open(_snake_case					,						'''a''')







   def __getattr__(      self		:						List[str]					,						_snake_case		:						Tuple):

        """simple docstring"""


        return getattr(self.stdout					,						_snake_case)







   def lowerCamelCase						(      self		:						int					,						_snake_case		:						List[Any]):

        """simple docstring"""


        self.stdout.write(_snake_case)
        # strip tqdm codes
        self.file.write(re.sub(r'''^.*\r'''					,						''''''					,						_snake_case					,						0					,						re.M))







def    A						(__A   :    Optional[Any]=80   ,				__A   :    Union[str, Any]=False       )   ->      Optional[int]:







     """simple docstring"""


     UpperCAmelCase_          =							[]

     # deal with critical env vars
     UpperCAmelCase_          =							['''CUDA_VISIBLE_DEVICES''']
     for key in env_keys:
          UpperCAmelCase_          =							os.environ.get(__A   ,				__A       )
          if val is not None:
               cmd.append(F"""{key}={val}"""       )

    # python executable (not always needed if the script is executable)
     UpperCAmelCase_          =							sys.executable if full_python_path else sys.executable.split('''/'''       )[-1]
     cmd.append(__A       )

     # now the normal args
     cmd += list(map(shlex.quote   ,				sys.argv       )       )

     # split up into up to MAX_WIDTH lines with shell multi-line escapes
     UpperCAmelCase_          =							[]
     UpperCAmelCase_          =							''''''
     while len(__A       ) > 0:
          current_line += F"""{cmd.pop(0       )} """
          if len(__A       ) == 0 or len(__A       ) + len(cmd[0]       ) + 1 > max_width - 1:
               lines.append(__A       )
               UpperCAmelCase_          =							''''''
     return "\\\n".join(__A       )


def    A						(__A   :    Union[str, Any]   ,				__A   :    List[Any]       )   ->      Dict:







     """simple docstring"""


     UpperCAmelCase_          =							re.sub(R'''[\\\n]+'''   ,				''' '''   ,				args.base_cmd       )

     # remove --output_dir if any and set our own
     UpperCAmelCase_          =							re.sub('''--output_dir\s+[^\s]+'''   ,				''''''   ,				args.base_cmd       )
     args.base_cmd += F""" --output_dir {output_dir}"""

     # ensure we have --overwrite_output_dir
     UpperCAmelCase_          =							re.sub('''--overwrite_output_dir\s+'''   ,				''''''   ,				args.base_cmd       )
     args.base_cmd += " --overwrite_output_dir"

     return [sys.executable] + shlex.split(args.base_cmd       )


def    A						(__A   :    str   ,				__A   :    List[str]   ,				__A   :    Optional[Any]   ,				__A   :    List[Any]   ,				__A   :    Optional[int]   ,				__A   :    Tuple   ,				__A   :    Union[str, Any]       )   ->      Dict:







     """simple docstring"""


     if 0:
          import random
          from time import sleep

          sleep(0       )
          return dict(
              {k: random.uniform(0   ,				100       ) for k in metric_keys}   ,				**{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222]       )}   ,				)

     UpperCAmelCase_          =							subprocess.run(__A   ,				capture_output=__A   ,				text=__A       )

     if verbose:
          print('''STDOUT'''   ,				result.stdout       )
          print('''STDERR'''   ,				result.stderr       )

     # save the streams
     UpperCAmelCase_          =							variation.replace(''' '''   ,				'''-'''       )
     with open(Path(__A       ) / F"""log.{prefix}.stdout.txt"""   ,				'''w'''       ) as f:
          f.write(result.stdout       )
     with open(Path(__A       ) / F"""log.{prefix}.stderr.txt"""   ,				'''w'''       ) as f:
          f.write(result.stderr       )

     if result.returncode != 0:
          if verbose:
               print('''failed'''       )
          return {target_metric_key: nan}

     with io.open(F"""{output_dir}/all_results.json"""   ,				'''r'''   ,				encoding='''utf-8'''       ) as f:
          UpperCAmelCase_          =							json.load(__A       )

     # filter out just the keys we want
     return {k: v for k, v in metrics.items() if k in metric_keys}


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







     """simple docstring"""


     UpperCAmelCase_          =							[]
     UpperCAmelCase_          =							[]
     UpperCAmelCase_          =							F"""{id}: {variation:<{longest_variation_len}}"""
     UpperCAmelCase_          =							F"""{preamble}: """
     UpperCAmelCase_          =							set(report_metric_keys + [target_metric_key]       )
     for i in tqdm(range(__A       )   ,				desc=__A   ,				leave=__A       ):
          UpperCAmelCase_          =							process_run_single(
              __A   ,				__A   ,				__A   ,				__A   ,				__A   ,				__A   ,				__A       )
          UpperCAmelCase_          =							single_run_metrics[target_metric_key]
          if not math.isnan(__A       ):
               metrics.append(__A       )
               results.append(__A       )
               outcome += "✓"
          else:
               outcome += "✘"
     UpperCAmelCase_          =							F"""\33[2K\r{outcome}"""
     if len(__A       ) > 0:
          UpperCAmelCase_          =							{k: fmean([x[k] for x in metrics]       ) for k in metrics[0].keys()}
          UpperCAmelCase_          =							round(mean_metrics[target_metric_key]   ,				2       )
          UpperCAmelCase_          =							F"""{outcome} {mean_target}"""
          if len(__A       ) > 1:
               results_str += F""" {tuple(round(__A   ,				2       ) for x in results       )}"""
          print(__A       )
          UpperCAmelCase_          =							variation
          return mean_metrics
     else:
          print(__A       )
          return {variation_key: variation, target_metric_key: nan}


def    A						()   ->      Dict:







     """simple docstring"""


     UpperCAmelCase_          =							torch.cuda.get_device_properties(torch.device('''cuda'''       )       )
     return F"""
Datetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"       )}

Software:
transformers: {transformers.__version__}
torch       : {torch.__version__}
cuda        : {torch.version.cuda}
python      : {platform.python_version()}

Hardware:
{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB
"""


def    A						(__A   :    Optional[Any]   ,				__A   :    str   ,				__A   :    str   ,				__A   :    List[str]   ,				__A   :    Tuple       )   ->      List[Any]:







     """simple docstring"""


     UpperCAmelCase_          =							pd.DataFrame(__A       )
     UpperCAmelCase_          =							'''variation'''
     UpperCAmelCase_          =							'''diff_%'''

     UpperCAmelCase_          =							nan
     if base_variation is not None and len(df[df[variation_key] == base_variation]       ):
          # this may still return nan
          UpperCAmelCase_          =							df.loc[df[variation_key] == base_variation][target_metric_key].item()
     if math.isnan(__A       ):
          # as a fallback, use the minimal value as the sentinel
          UpperCAmelCase_          =							df.loc[df[target_metric_key] != nan][target_metric_key].min()

     # create diff column if possible
     if not math.isnan(__A       ):
          UpperCAmelCase_          =							df.apply(
              lambda __A       : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value       )
              if not math.isnan(r[target_metric_key]       )
              else 0   ,				axis='''columns'''   ,				)

     # re-order columns
     UpperCAmelCase_          =							[variation_key, target_metric_key, diff_key, *report_metric_keys]
     UpperCAmelCase_          =							df.reindex(__A   ,				axis='''columns'''       )  # reorder cols

     # capitalize
     UpperCAmelCase_          =							df.rename(str.capitalize   ,				axis='''columns'''       )

     # make the cols as narrow as possible
     UpperCAmelCase_          =							df.rename(lambda __A       : c.replace('''_'''   ,				'''<br>'''       )   ,				axis='''columns'''       )
     UpperCAmelCase_          =							df.rename(lambda __A       : c.replace('''_'''   ,				'''\n'''       )   ,				axis='''columns'''       )

     UpperCAmelCase_          =							['''''', '''Copy between the cut-here-lines and paste as is to github or a forum''']
     report += ["----------8<-----------------8<--------"]
     report += ["*** Results:", df_github.to_markdown(index=__A   ,				floatfmt='''.2f'''       )]
     report += ["```"]
     report += ["*** Setup:", get_versions()]
     report += ["*** The benchmark command line was:", get_original_command()]
     report += ["```"]
     report += ["----------8<-----------------8<--------"]
     report += ["*** Results (console):", df_console.to_markdown(index=__A   ,				floatfmt='''.2f'''       )]

     print('''\n\n'''.join(__A       )       )


def    A						()   ->      int:







     """simple docstring"""


     UpperCAmelCase_          =							argparse.ArgumentParser()
     parser.add_argument(
         '''--base-cmd'''   ,				default=__A   ,				type=__A   ,				required=__A   ,				help='''Base cmd'''   ,				)
     parser.add_argument(
         '''--variations'''   ,				default=__A   ,				type=__A   ,				nargs='''+'''   ,				required=__A   ,				help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\''''   ,				)
     parser.add_argument(
         '''--base-variation'''   ,				default=__A   ,				type=__A   ,				help='''Baseline variation to compare to. if None the minimal target value will be used to compare against'''   ,				)
     parser.add_argument(
         '''--target-metric-key'''   ,				default=__A   ,				type=__A   ,				required=__A   ,				help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second'''   ,				)
     parser.add_argument(
         '''--report-metric-keys'''   ,				default=''''''   ,				type=__A   ,				help='''Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples'''   ,				)
     parser.add_argument(
         '''--repeat-times'''   ,				default=1   ,				type=__A   ,				help='''How many times to re-run each variation - an average will be reported'''   ,				)
     parser.add_argument(
         '''--output_dir'''   ,				default='''output_benchmark'''   ,				type=__A   ,				help='''The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked'''   ,				)
     parser.add_argument(
         '''--verbose'''   ,				default=__A   ,				action='''store_true'''   ,				help='''Whether to show the outputs of each run or just the benchmark progress'''   ,				)
     UpperCAmelCase_          =							parser.parse_args()

     UpperCAmelCase_          =							args.output_dir
     Path(__A       ).mkdir(exist_ok=__A       )
     UpperCAmelCase_          =							get_base_command(__A   ,				__A       )

     # split each dimension into its --foo variations
     UpperCAmelCase_          =							[list(map(str.strip   ,				re.split(R'''\|'''   ,				__A       )       )       ) for x in args.variations]
     # build a cartesian product of dimensions and convert those back into cmd-line arg strings,
     # while stripping white space for inputs that were empty
     UpperCAmelCase_          =							list(map(str.strip   ,				map(''' '''.join   ,				itertools.product(*__A       )       )       )       )
     UpperCAmelCase_          =							max(len(__A       ) for x in variations       )

     # split wanted keys
     UpperCAmelCase_          =							args.report_metric_keys.split()

     # capture prints into a log file for convenience
     UpperCAmelCase_          =							F"""benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"       )}.txt"""
     print(F"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt"""       )
     print(F"""and this script's output is also piped into {report_fn}"""       )

     UpperCAmelCase_          =							Tee(__A       )

     print(F"""\n*** Running {len(__A       )} benchmarks:"""       )
     print(F"""Base command: {" ".join(__A       )}"""       )

     UpperCAmelCase_          =							'''variation'''
     UpperCAmelCase_          =							[]
     for id, variation in enumerate(tqdm(__A   ,				desc='''Total completion: '''   ,				leave=__A       )       ):
          UpperCAmelCase_          =							base_cmd + variation.split()
          results.append(
              process_run(
                  id + 1   ,				__A   ,				__A   ,				__A   ,				__A   ,				args.target_metric_key   ,				__A   ,				args.repeat_times   ,				__A   ,				args.verbose   ,				)       )

     process_results(__A   ,				args.target_metric_key   ,				__A   ,				args.base_variation   ,				__A       )


if __name__ == "__main__":
    main()












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







   def __init__(      self		:						List[str]					,						_snake_case		:						Union[str, Any]					,						_snake_case		:						List[str]=2					,						_snake_case		:						Any=True					,						_snake_case		:						Any=False					,						_snake_case		:						List[str]=10					,						_snake_case		:						Any=3					,						_snake_case		:						Union[str, Any]=32 * 4					,						_snake_case		:						List[Any]=32 * 6					,						_snake_case		:						Tuple=4					,						_snake_case		:						Dict=32					,						):

        """simple docstring"""


        UpperCAmelCase_          =							parent
        UpperCAmelCase_          =							batch_size
        UpperCAmelCase_          =							is_training
        UpperCAmelCase_          =							use_auxiliary_loss
        UpperCAmelCase_          =							num_queries
        UpperCAmelCase_          =							num_channels
        UpperCAmelCase_          =							min_size
        UpperCAmelCase_          =							max_size
        UpperCAmelCase_          =							num_labels
        UpperCAmelCase_          =							mask_feature_size







   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        UpperCAmelCase_          =							floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
            _snake_case)

        UpperCAmelCase_          =							torch.ones([self.batch_size, self.min_size, self.max_size]					,						device=_snake_case)

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

        UpperCAmelCase_          =							self.get_config()
        return config, pixel_values, pixel_mask, mask_labels, class_labels







   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        return MaskFormerConfig.from_backbone_and_decoder_configs(
            backbone_config=SwinConfig(
                depths=[1, 1, 1, 1]					,						)					,						decoder_config=DetrConfig(
                decoder_ffn_dim=128					,						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 lowerCamelCase						(      self		:						int):

        """simple docstring"""


        UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_          =							self.prepare_config_and_inputs()
        UpperCAmelCase_          =							{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
        return config, inputs_dict







   def lowerCamelCase						(      self		:						str					,						_snake_case		:						List[Any]					,						_snake_case		:						List[str]):

        """simple docstring"""


        UpperCAmelCase_          =							output.encoder_hidden_states
        UpperCAmelCase_          =							output.pixel_decoder_hidden_states
        UpperCAmelCase_          =							output.transformer_decoder_hidden_states

        self.parent.assertTrue(len(_snake_case)					,						len(config.backbone_config.depths))
        self.parent.assertTrue(len(_snake_case)					,						len(config.backbone_config.depths))
        self.parent.assertTrue(len(_snake_case)					,						config.decoder_config.decoder_layers)







   def lowerCamelCase						(      self		:						Union[str, Any]					,						_snake_case		:						List[str]					,						_snake_case		:						int					,						_snake_case		:						Optional[Any]					,						_snake_case		:						str=False):

        """simple docstring"""


        with torch.no_grad():
             UpperCAmelCase_          =							MaskFormerModel(config=_snake_case)
             model.to(_snake_case)
             model.eval()

             UpperCAmelCase_          =							model(pixel_values=_snake_case					,						pixel_mask=_snake_case)
             UpperCAmelCase_          =							model(_snake_case					,						output_hidden_states=_snake_case)
        # 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(_snake_case					,						_snake_case)







   def lowerCamelCase						(      self		:						List[Any]					,						_snake_case		:						List[Any]					,						_snake_case		:						List[Any]					,						_snake_case		:						str					,						_snake_case		:						Optional[int]					,						_snake_case		:						Union[str, Any]):

        """simple docstring"""


        UpperCAmelCase_          =							MaskFormerForInstanceSegmentation(config=_snake_case)
        model.to(_snake_case)
        model.eval()

        def comm_check_on_output(_snake_case		:						Tuple):
             # 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():
             UpperCAmelCase_          =							model(pixel_values=_snake_case					,						pixel_mask=_snake_case)
             UpperCAmelCase_          =							model(_snake_case)

             comm_check_on_output(_snake_case)

             UpperCAmelCase_          =							model(
                 pixel_values=_snake_case					,						pixel_mask=_snake_case					,						mask_labels=_snake_case					,						class_labels=_snake_case)

        comm_check_on_output(_snake_case)

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







@require_torch
class __snake_case			(			a ,  a ,  unittest.TestCase		):
   UpperCAmelCase__  :    Union[str, Any]          =  (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
   UpperCAmelCase__  :    Optional[Any]          =  (
       {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
       if is_torch_available()
       else {}
   )

   UpperCAmelCase__  :    Dict          =  False
   UpperCAmelCase__  :    List[str]          =  False
   UpperCAmelCase__  :    Optional[Any]          =  False
   UpperCAmelCase__  :    Union[str, Any]          =  False







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							MaskFormerModelTester(self)
        UpperCAmelCase_          =							ConfigTester(self					,						config_class=_snake_case					,						has_text_modality=_snake_case)







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        self.config_tester.run_common_tests()







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskformer_model(_snake_case					,						**_snake_case					,						output_hidden_states=_snake_case)







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_snake_case)







   @unittest.skip(reason='''MaskFormer does not use inputs_embeds''')
   def lowerCamelCase						(      self		:						Dict):

        """simple docstring"""


        pass







   @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''')
   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        pass







   @unittest.skip(reason='''MaskFormer is not a generative model''')
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        pass







   @unittest.skip(reason='''MaskFormer does not use token embeddings''')
   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        pass







   @require_torch_multi_gpu
   @unittest.skip(
       reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''')
   def lowerCamelCase						(      self		:						Any):

        """simple docstring"""


        pass







   @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        pass







   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs_for_common()

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

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







   @slow
   def lowerCamelCase						(      self		:						Union[str, Any]):

        """simple docstring"""


        for model_name in ["facebook/maskformer-swin-small-coco"]:
             UpperCAmelCase_          =							MaskFormerModel.from_pretrained(_snake_case)
             self.assertIsNotNone(_snake_case)







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_          =							(self.model_tester.min_size,) * 2
        UpperCAmelCase_          =							{
            '''pixel_values''': torch.randn((2, 3, *size)					,						device=_snake_case),
            '''mask_labels''': torch.randn((2, 10, *size)					,						device=_snake_case),
            '''class_labels''': torch.zeros(2					,						10					,						device=_snake_case).long(),
        }

        UpperCAmelCase_          =							MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(_snake_case)
        UpperCAmelCase_          =							model(**_snake_case)
        self.assertTrue(outputs.loss is not None)







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs_for_common()
        self.model_tester.create_and_check_maskformer_model(_snake_case					,						**_snake_case					,						output_hidden_states=_snake_case)







   def lowerCamelCase						(      self		:						str):

        """simple docstring"""


        UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             UpperCAmelCase_          =							model_class(_snake_case).to(_snake_case)
             UpperCAmelCase_          =							model(**_snake_case					,						output_attentions=_snake_case)
             self.assertTrue(outputs.attentions is not None)







   def lowerCamelCase						(      self		:						int):

        """simple docstring"""


        if not self.model_tester.is_training:
             return
        # only MaskFormerForInstanceSegmentation has the loss
        UpperCAmelCase_          =							self.all_model_classes[1]
        UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs()

        UpperCAmelCase_          =							model_class(_snake_case)
        model.to(_snake_case)
        model.train()

        UpperCAmelCase_          =							model(_snake_case					,						mask_labels=_snake_case					,						class_labels=_snake_case).loss
        loss.backward()







   def lowerCamelCase						(      self		:						Optional[int]):

        """simple docstring"""


        UpperCAmelCase_          =							self.all_model_classes[1]
        UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_     ,       UpperCAmelCase_          =							self.model_tester.prepare_config_and_inputs()
        UpperCAmelCase_          =							True
        UpperCAmelCase_          =							True

        UpperCAmelCase_          =							model_class(_snake_case)
        model.to(_snake_case)
        model.train()

        UpperCAmelCase_          =							model(_snake_case					,						mask_labels=_snake_case					,						class_labels=_snake_case)

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

        UpperCAmelCase_          =							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
        UpperCAmelCase_          =							outputs.transformer_decoder_hidden_states[0]
        transformer_decoder_hidden_states.retain_grad()

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

        outputs.loss.backward(retain_graph=_snake_case)

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







snake_case_ : Dict    		=       1e-4


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







     """simple docstring"""


     UpperCAmelCase_          =							Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
     return image







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







   @cached_property
   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        return (
            MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''')
            if is_vision_available()
            else None
        )







   def lowerCamelCase						(      self		:						List[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''').to(_snake_case)
        UpperCAmelCase_          =							self.default_image_processor
        UpperCAmelCase_          =							prepare_img()
        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''pt''').to(_snake_case)
        UpperCAmelCase_          =							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(_snake_case					,						(1, 3, 800, 1088))

        with torch.no_grad():
             UpperCAmelCase_          =							model(**_snake_case)

        UpperCAmelCase_          =							torch.tensor(
            [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]]).to(_snake_case)
        self.assertTrue(
            torch.allclose(
                outputs.encoder_last_hidden_state[0, 0, :3, :3]					,						_snake_case					,						atol=_snake_case))

        UpperCAmelCase_          =							torch.tensor(
            [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]]).to(_snake_case)
        self.assertTrue(
            torch.allclose(
                outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]					,						_snake_case					,						atol=_snake_case))

        UpperCAmelCase_          =							torch.tensor(
            [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]]).to(_snake_case)
        self.assertTrue(
            torch.allclose(
                outputs.transformer_decoder_last_hidden_state[0, :3, :3]					,						_snake_case					,						atol=_snake_case))







   def lowerCamelCase						(      self		:						List[str]):

        """simple docstring"""


        UpperCAmelCase_          =							(
            MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''')
            .to(_snake_case)
            .eval()
        )
        UpperCAmelCase_          =							self.default_image_processor
        UpperCAmelCase_          =							prepare_img()
        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''pt''').to(_snake_case)
        UpperCAmelCase_          =							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(_snake_case					,						(1, 3, 800, 1088))

        with torch.no_grad():
             UpperCAmelCase_          =							model(**_snake_case)
        # masks_queries_logits
        UpperCAmelCase_          =							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)					,						)
        UpperCAmelCase_          =							[
            [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3],
            [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5],
            [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2],
        ]
        UpperCAmelCase_          =							torch.tensor(_snake_case).to(_snake_case)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]					,						_snake_case					,						atol=_snake_case))
        # class_queries_logits
        UpperCAmelCase_          =							outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape					,						(1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
        UpperCAmelCase_          =							torch.tensor(
            [
                [1.65_12e00, -5.25_72e00, -3.35_19e00],
                [3.61_69e-02, -5.90_25e00, -2.93_13e00],
                [1.07_66e-04, -7.76_30e00, -5.12_63e00],
            ]).to(_snake_case)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]					,						_snake_case					,						atol=_snake_case))







   def lowerCamelCase						(      self		:						Optional[Any]):

        """simple docstring"""


        UpperCAmelCase_          =							(
            MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''')
            .to(_snake_case)
            .eval()
        )
        UpperCAmelCase_          =							self.default_image_processor
        UpperCAmelCase_          =							prepare_img()
        UpperCAmelCase_          =							image_processor(_snake_case					,						return_tensors='''pt''').to(_snake_case)
        UpperCAmelCase_          =							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(_snake_case					,						(1, 3, 800, 1088))

        with torch.no_grad():
             UpperCAmelCase_          =							model(**_snake_case)
        # masks_queries_logits
        UpperCAmelCase_          =							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)					,						)
        UpperCAmelCase_          =							[[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]]
        UpperCAmelCase_          =							torch.tensor(_snake_case).to(_snake_case)
        self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]					,						_snake_case					,						atol=_snake_case))
        # class_queries_logits
        UpperCAmelCase_          =							outputs.class_queries_logits
        self.assertEqual(
            class_queries_logits.shape					,						(1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
        UpperCAmelCase_          =							torch.tensor(
            [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]]).to(_snake_case)
        self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]					,						_snake_case					,						atol=_snake_case))







   def lowerCamelCase						(      self		:						Tuple):

        """simple docstring"""


        UpperCAmelCase_          =							(
            MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''')
            .to(_snake_case)
            .eval()
        )
        UpperCAmelCase_          =							self.default_image_processor

        UpperCAmelCase_          =							image_processor(
            [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))]					,						segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)]					,						return_tensors='''pt'''					,						)

        UpperCAmelCase_          =							inputs['''pixel_values'''].to(_snake_case)
        UpperCAmelCase_          =							[el.to(_snake_case) for el in inputs['''mask_labels''']]
        UpperCAmelCase_          =							[el.to(_snake_case) for el in inputs['''class_labels''']]

        with torch.no_grad():
             UpperCAmelCase_          =							model(**_snake_case)

        self.assertTrue(outputs.loss is not None)






