


# 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


_A		:				List[str]									=       float('''nan''')



class        a					:





     def __init__(    self					:				str    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]							):
        __lowerCamelCase:				str     =	sys.stdout
        __lowerCamelCase:				Union[str, Any]     =	open(SCREAMING_SNAKE_CASE_    ,	"""a"""							)





     def __getattr__(    self					:				str    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]							):
        return getattr(self.stdout    ,	SCREAMING_SNAKE_CASE_							)







     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]							):
        self.stdout.write(SCREAMING_SNAKE_CASE_							)
        # strip tqdm codes
        self.file.write(re.sub(R"""^.*\r"""    ,	""""""    ,	SCREAMING_SNAKE_CASE_    ,	0    ,	re.M							)							)



def     __lowerCAmelCase						(							snake_case	:    str=80						,      snake_case	:    int=False )       ->							Optional[Any]:
   __lowerCamelCase:				Any     =	[]

   # deal with critical env vars
   __lowerCamelCase:				Optional[int]     =	["""CUDA_VISIBLE_DEVICES"""]
   for key in env_keys:
      __lowerCamelCase:				Any     =	os.environ.get(snake_case						,      snake_case )
      if val is not None:
         cmd.append(f'{key}={val}' )

    # python executable (not always needed if the script is executable)
   __lowerCamelCase:				int     =	sys.executable if full_python_path else sys.executable.split("""/""" )[-1]
   cmd.append(snake_case )

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

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



def     __lowerCAmelCase						(							snake_case	:    Union[str, Any]						,      snake_case	:    List[Any] )       ->							int:
   # unwrap multi-line input
   __lowerCamelCase:				Optional[Any]     =	re.sub(r"""[\\\n]+"""						,      """ """						,      args.base_cmd )

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

   # ensure we have --overwrite_output_dir
   __lowerCamelCase:				Optional[int]     =	re.sub("""--overwrite_output_dir\s+"""						,      """"""						,      args.base_cmd )
   args.base_cmd += " --overwrite_output_dir"

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



def     __lowerCAmelCase						(							snake_case	:    Optional[Any]						,      snake_case	:    Optional[int]						,      snake_case	:    Optional[Any]						,      snake_case	:    Union[str, Any]						,      snake_case	:    Tuple						,      snake_case	:    Any						,      snake_case	:    Tuple )       ->							Dict:
   # Enable to debug everything but the run itself, to do it fast and see the progress.
   # This is useful for debugging the output formatting quickly - we can remove it later once
   # everybody is happy with the output
   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] )}						,      )

   __lowerCamelCase:				Union[str, Any]     =	subprocess.run(snake_case						,      capture_output=snake_case						,      text=snake_case )

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

   # save the streams
   __lowerCamelCase:				List[str]     =	variation.replace(""" """						,      """-""" )
   with open(Path(snake_case ) / f'log.{prefix}.stdout.txt'						,      """w""" ) as f:
      f.write(result.stdout )
   with open(Path(snake_case ) / 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:
      __lowerCamelCase:				Dict     =	json.load(snake_case )

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



def     __lowerCAmelCase						(							snake_case	:    Union[str, Any]						,      snake_case	:    List[Any]						,      snake_case	:    Tuple						,      snake_case	:    str						,      snake_case	:    Dict						,      snake_case	:    str						,      snake_case	:    List[str]						,      snake_case	:    List[str]						,      snake_case	:    List[Any]						,      snake_case	:    Optional[Any]						,      )       ->							int:
   __lowerCamelCase:				Optional[Any]     =	[]
   __lowerCamelCase:				List[Any]     =	[]
   __lowerCamelCase:				Any     =	f'{id}: {variation:<{longest_variation_len}}'
   __lowerCamelCase:				Tuple     =	f'{preamble}: '
   __lowerCamelCase:				Dict     =	set(report_metric_keys + [target_metric_key] )
   for i in tqdm(range(snake_case )						,      desc=snake_case						,      leave=snake_case ):
      __lowerCamelCase:				Dict     =	process_run_single(
          snake_case						,      snake_case						,      snake_case						,      snake_case						,      snake_case						,      snake_case						,      snake_case )
      __lowerCamelCase:				Optional[int]     =	single_run_metrics[target_metric_key]
      if not math.isnan(snake_case ):
         metrics.append(snake_case )
         results.append(snake_case )
         outcome += "✓"
      else:
         outcome += "✘"
   __lowerCamelCase:				Dict     =	f'\33[2K\r{outcome}'
   if len(snake_case ) > 0:
      __lowerCamelCase:				str     =	{k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()}
      __lowerCamelCase:				List[Any]     =	round(mean_metrics[target_metric_key]						,      2 )
      __lowerCamelCase:				str     =	f'{outcome} {mean_target}'
      if len(snake_case ) > 1:
         results_str += f' {tuple(round(snake_case						,      2 ) for x in results )}'
      print(snake_case )
      __lowerCamelCase:				Dict     =	variation
      return mean_metrics
   else:
      print(snake_case )
      return {variation_key: variation, target_metric_key: nan}



def     __lowerCAmelCase						(							)       ->							int:
   __lowerCamelCase:				Dict     =	torch.cuda.get_device_properties(torch.device("""cuda""" ) )
   return f'\nDatetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch       : {torch.__version__}\ncuda        : {torch.version.cuda}\npython      : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n'



def     __lowerCAmelCase						(							snake_case	:    Tuple						,      snake_case	:    List[Any]						,      snake_case	:    Dict						,      snake_case	:    int						,      snake_case	:    int )       ->							Dict:
   __lowerCamelCase:				int     =	pd.DataFrame(snake_case )
   __lowerCamelCase:				List[Any]     =	"""variation"""
   __lowerCamelCase:				List[str]     =	"""diff_%"""

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

   # create diff column if possible
   if not math.isnan(snake_case ):
      __lowerCamelCase:				List[Any]     =	df.apply(
          lambda snake_case : 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
   __lowerCamelCase:				int     =	[variation_key, target_metric_key, diff_key, *report_metric_keys]
   __lowerCamelCase:				Optional[Any]     =	df.reindex(snake_case						,      axis="""columns""" )  # reorder cols

   # capitalize
   __lowerCamelCase:				int     =	df.rename(str.capitalize						,      axis="""columns""" )

   # make the cols as narrow as possible
   __lowerCamelCase:				Optional[Any]     =	df.rename(lambda snake_case : c.replace("""_"""						,      """<br>""" )						,      axis="""columns""" )
   __lowerCamelCase:				Dict     =	df.rename(lambda snake_case : c.replace("""_"""						,      """\n""" )						,      axis="""columns""" )

   __lowerCamelCase:				Any     =	["""""", """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=snake_case						,      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=snake_case						,      floatfmt=""".2f""" )]

   print("""\n\n""".join(snake_case ) )



def     __lowerCAmelCase						(							)       ->							int:
   __lowerCamelCase:				List[Any]     =	argparse.ArgumentParser()
   parser.add_argument(
       """--base-cmd"""						,      default=snake_case						,      type=snake_case						,      required=snake_case						,      help="""Base cmd"""						,      )
   parser.add_argument(
       """--variations"""						,      default=snake_case						,      type=snake_case						,      nargs="""+"""						,      required=snake_case						,      help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'"""						,      )
   parser.add_argument(
       """--base-variation"""						,      default=snake_case						,      type=snake_case						,      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=snake_case						,      type=snake_case						,      required=snake_case						,      help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second"""						,      )
   parser.add_argument(
       """--report-metric-keys"""						,      default=""""""						,      type=snake_case						,      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=snake_case						,      help="""How many times to re-run each variation - an average will be reported"""						,      )
   parser.add_argument(
       """--output_dir"""						,      default="""output_benchmark"""						,      type=snake_case						,      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=snake_case						,      action="""store_true"""						,      help="""Whether to show the outputs of each run or just the benchmark progress"""						,      )
   __lowerCamelCase:				List[str]     =	parser.parse_args()

   __lowerCamelCase:				Dict     =	args.output_dir
   Path(snake_case ).mkdir(exist_ok=snake_case )
   __lowerCamelCase:				Optional[Any]     =	get_base_command(snake_case						,      snake_case )

   # split each dimension into its --foo variations
   __lowerCamelCase:				str     =	[list(map(str.strip						,      re.split(r"""\|"""						,      snake_case ) ) ) 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
   __lowerCamelCase:				Any     =	list(map(str.strip						,      map(""" """.join						,      itertools.product(*snake_case ) ) ) )
   __lowerCamelCase:				Any     =	max(len(snake_case ) for x in variations )

   # split wanted keys
   __lowerCamelCase:				int     =	args.report_metric_keys.split()

   # capture prints into a log file for convenience
   __lowerCamelCase:				Any     =	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}' )

   __lowerCamelCase:				List[str]     =	Tee(snake_case )

   print(f'\n*** Running {len(snake_case )} benchmarks:' )
   print(f'Base command: {" ".join(snake_case )}' )

   __lowerCamelCase:				List[Any]     =	"""variation"""
   __lowerCamelCase:				Union[str, Any]     =	[]
   for id, variation in enumerate(tqdm(snake_case						,      desc="""Total completion: """						,      leave=snake_case ) ):
      __lowerCamelCase:				Optional[Any]     =	base_cmd + variation.split()
      results.append(
          process_run(
              id + 1						,      snake_case						,      snake_case						,      snake_case						,      snake_case						,      args.target_metric_key						,      snake_case						,      args.repeat_times						,      snake_case						,      args.verbose						,      ) )

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


if __name__ == "__main__":
   main()






import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
   import torch
   from torch import nn

   from transformers import YolosForObjectDetection, YolosModel
   from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor



class        a					:





     def __init__(    self					:				Dict    ,	SCREAMING_SNAKE_CASE_					:				List[str]    ,	SCREAMING_SNAKE_CASE_					:				int=13    ,	SCREAMING_SNAKE_CASE_					:				str=[30, 30]    ,	SCREAMING_SNAKE_CASE_					:				str=2    ,	SCREAMING_SNAKE_CASE_					:				List[Any]=3    ,	SCREAMING_SNAKE_CASE_					:				Dict=True    ,	SCREAMING_SNAKE_CASE_					:				Any=True    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]=32    ,	SCREAMING_SNAKE_CASE_					:				Tuple=5    ,	SCREAMING_SNAKE_CASE_					:				Tuple=4    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]=37    ,	SCREAMING_SNAKE_CASE_					:				Dict="gelu"    ,	SCREAMING_SNAKE_CASE_					:				Any=0.1    ,	SCREAMING_SNAKE_CASE_					:				Tuple=0.1    ,	SCREAMING_SNAKE_CASE_					:				Tuple=10    ,	SCREAMING_SNAKE_CASE_					:				List[str]=0.02    ,	SCREAMING_SNAKE_CASE_					:				Dict=3    ,	SCREAMING_SNAKE_CASE_					:				List[str]=None    ,	SCREAMING_SNAKE_CASE_					:				int=8    ,	SCREAMING_SNAKE_CASE_					:				Dict=10    ,	):
        __lowerCamelCase:				Optional[int]     =	parent
        __lowerCamelCase:				Tuple     =	batch_size
        __lowerCamelCase:				Optional[Any]     =	image_size
        __lowerCamelCase:				str     =	patch_size
        __lowerCamelCase:				Dict     =	num_channels
        __lowerCamelCase:				Optional[int]     =	is_training
        __lowerCamelCase:				Union[str, Any]     =	use_labels
        __lowerCamelCase:				Union[str, Any]     =	hidden_size
        __lowerCamelCase:				Dict     =	num_hidden_layers
        __lowerCamelCase:				int     =	num_attention_heads
        __lowerCamelCase:				Optional[int]     =	intermediate_size
        __lowerCamelCase:				Union[str, Any]     =	hidden_act
        __lowerCamelCase:				List[str]     =	hidden_dropout_prob
        __lowerCamelCase:				Optional[int]     =	attention_probs_dropout_prob
        __lowerCamelCase:				List[str]     =	type_sequence_label_size
        __lowerCamelCase:				Dict     =	initializer_range
        __lowerCamelCase:				Optional[Any]     =	num_labels
        __lowerCamelCase:				Tuple     =	scope
        __lowerCamelCase:				Tuple     =	n_targets
        __lowerCamelCase:				Tuple     =	num_detection_tokens
        # we set the expected sequence length (which is used in several tests)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
        __lowerCamelCase:				Any     =	(image_size[1] // patch_size) * (image_size[0] // patch_size)
        __lowerCamelCase:				str     =	num_patches + 1 + self.num_detection_tokens





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        __lowerCamelCase:				List[str]     =	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)

        __lowerCamelCase:				Optional[int]     =	None
        if self.use_labels:
           # labels is a list of Dict (each Dict being the labels for a given example in the batch)
           __lowerCamelCase:				Optional[int]     =	[]
           for i in range(self.batch_size							):
              __lowerCamelCase:				Optional[int]     =	{}
              __lowerCamelCase:				Optional[int]     =	torch.randint(
                  high=self.num_labels    ,	size=(self.n_targets,)    ,	device=SCREAMING_SNAKE_CASE_							)
              __lowerCamelCase:				List[str]     =	torch.rand(self.n_targets    ,	4    ,	device=SCREAMING_SNAKE_CASE_							)
              labels.append(SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				int     =	self.get_config()

        return config, pixel_values, labels





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        return YolosConfig(
            image_size=self.image_size    ,	patch_size=self.patch_size    ,	num_channels=self.num_channels    ,	hidden_size=self.hidden_size    ,	num_hidden_layers=self.num_hidden_layers    ,	num_attention_heads=self.num_attention_heads    ,	intermediate_size=self.intermediate_size    ,	hidden_act=self.hidden_act    ,	hidden_dropout_prob=self.hidden_dropout_prob    ,	attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,	is_decoder=SCREAMING_SNAKE_CASE_    ,	initializer_range=self.initializer_range    ,	num_detection_tokens=self.num_detection_tokens    ,	num_labels=self.num_labels    ,	)





     def  SCREAMING_SNAKE_CASE__       (    self					:				int    ,	SCREAMING_SNAKE_CASE_					:				str    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				Dict							):
        __lowerCamelCase:				List[Any]     =	YolosModel(config=SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()
        __lowerCamelCase:				Optional[int]     =	model(SCREAMING_SNAKE_CASE_							)
        self.parent.assertEqual(
            result.last_hidden_state.shape    ,	(self.batch_size, self.expected_seq_len, self.hidden_size)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				List[Any]    ,	SCREAMING_SNAKE_CASE_					:				str							):
        __lowerCamelCase:				int     =	YolosForObjectDetection(SCREAMING_SNAKE_CASE_							)
        model.to(SCREAMING_SNAKE_CASE_							)
        model.eval()

        __lowerCamelCase:				List[Any]     =	model(pixel_values=SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				str     =	model(SCREAMING_SNAKE_CASE_							)

        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.num_detection_tokens, self.num_labels + 1)							)
        self.parent.assertEqual(result.pred_boxes.shape    ,	(self.batch_size, self.num_detection_tokens, 4)							)

        __lowerCamelCase:				Any     =	model(pixel_values=SCREAMING_SNAKE_CASE_    ,	labels=SCREAMING_SNAKE_CASE_							)

        self.parent.assertEqual(result.loss.shape    ,	()							)
        self.parent.assertEqual(result.logits.shape    ,	(self.batch_size, self.num_detection_tokens, self.num_labels + 1)							)
        self.parent.assertEqual(result.pred_boxes.shape    ,	(self.batch_size, self.num_detection_tokens, 4)							)







     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				Union[str, Any]     =	self.prepare_config_and_inputs()
        __lowerCamelCase   ,     __lowerCamelCase   ,     __lowerCamelCase:				Optional[int]     =	config_and_inputs
        __lowerCamelCase:				Optional[Any]     =	{"""pixel_values""": pixel_values}
        return config, inputs_dict



@require_torch
class        a					(			_UpperCAmelCase     ,_UpperCAmelCase     ,unittest.TestCase   ):
     UpperCAmelCase__ :  Any						      =	(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
     UpperCAmelCase__ :  Optional[int]						      =	(
         {"feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {}
     )

     UpperCAmelCase__ :  Dict						      =	False
     UpperCAmelCase__ :  Tuple						      =	False
     UpperCAmelCase__ :  str						      =	False
     UpperCAmelCase__ :  List[str]						      =	False





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				Optional[int]    ,	SCREAMING_SNAKE_CASE_					:				Any    ,	SCREAMING_SNAKE_CASE_					:				List[str]=False							):
        __lowerCamelCase:				Any     =	super()._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	return_labels=SCREAMING_SNAKE_CASE_							)

        if return_labels:
           if model_class.__name__ == "YolosForObjectDetection":
              __lowerCamelCase:				str     =	[]
              for i in range(self.model_tester.batch_size							):
                 __lowerCamelCase:				List[Any]     =	{}
                 __lowerCamelCase:				List[Any]     =	torch.ones(
                     size=(self.model_tester.n_targets,)    ,	device=SCREAMING_SNAKE_CASE_    ,	dtype=torch.long							)
                 __lowerCamelCase:				Optional[int]     =	torch.ones(
                     self.model_tester.n_targets    ,	4    ,	device=SCREAMING_SNAKE_CASE_    ,	dtype=torch.float							)
                 labels.append(SCREAMING_SNAKE_CASE_							)
              __lowerCamelCase:				Optional[Any]     =	labels

        return inputs_dict





     def  SCREAMING_SNAKE_CASE__       (    self					:				Dict							):
        __lowerCamelCase:				Dict     =	YolosModelTester(self							)
        __lowerCamelCase:				str     =	ConfigTester(self    ,	config_class=SCREAMING_SNAKE_CASE_    ,	has_text_modality=SCREAMING_SNAKE_CASE_    ,	hidden_size=37							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Optional[Any]							):
        self.config_tester.run_common_tests()





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        # YOLOS does not use inputs_embeds
        pass





     def  SCREAMING_SNAKE_CASE__       (    self					:				int							):
        __lowerCamelCase   ,     __lowerCamelCase:				Optional[int]     =	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           __lowerCamelCase:				int     =	model_class(SCREAMING_SNAKE_CASE_							)
           self.assertIsInstance(model.get_input_embeddings()    ,	(nn.Module)							)
           __lowerCamelCase:				Optional[Any]     =	model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_    ,	nn.Linear							)							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase   ,     __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs_for_common()

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

           __lowerCamelCase:				Optional[int]     =	["""pixel_values"""]
           self.assertListEqual(arg_names[:1]    ,	SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase:				str     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        __lowerCamelCase   ,     __lowerCamelCase:				Any     =	self.model_tester.prepare_config_and_inputs_for_common()
        __lowerCamelCase:				str     =	True

        # in YOLOS, the seq_len is different
        __lowerCamelCase:				List[Any]     =	self.model_tester.expected_seq_len
        for model_class in self.all_model_classes:
           __lowerCamelCase:				Dict     =	True
           __lowerCamelCase:				Union[str, Any]     =	False
           __lowerCamelCase:				Any     =	True
           __lowerCamelCase:				str     =	model_class(SCREAMING_SNAKE_CASE_							)
           model.to(SCREAMING_SNAKE_CASE_							)
           model.eval()
           with torch.no_grad():
              __lowerCamelCase:				Tuple     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)
           __lowerCamelCase:				str     =	outputs.attentions
           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	self.model_tester.num_hidden_layers							)

           # check that output_attentions also work using config
           del inputs_dict["output_attentions"]
           __lowerCamelCase:				Tuple     =	True
           __lowerCamelCase:				Optional[int]     =	model_class(SCREAMING_SNAKE_CASE_							)
           model.to(SCREAMING_SNAKE_CASE_							)
           model.eval()
           with torch.no_grad():
              __lowerCamelCase:				str     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)
           __lowerCamelCase:				str     =	outputs.attentions
           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	self.model_tester.num_hidden_layers							)

           self.assertListEqual(
               list(attentions[0].shape[-3:]							)    ,	[self.model_tester.num_attention_heads, seq_len, seq_len]    ,	)
           __lowerCamelCase:				List[str]     =	len(SCREAMING_SNAKE_CASE_							)

           # Check attention is always last and order is fine
           __lowerCamelCase:				Any     =	True
           __lowerCamelCase:				Optional[Any]     =	True
           __lowerCamelCase:				List[str]     =	model_class(SCREAMING_SNAKE_CASE_							)
           model.to(SCREAMING_SNAKE_CASE_							)
           model.eval()
           with torch.no_grad():
              __lowerCamelCase:				Optional[Any]     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)

           __lowerCamelCase:				Tuple     =	1
           self.assertEqual(out_len + added_hidden_states    ,	len(SCREAMING_SNAKE_CASE_							)							)

           __lowerCamelCase:				Any     =	outputs.attentions

           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	self.model_tester.num_hidden_layers							)
           self.assertListEqual(
               list(self_attentions[0].shape[-3:]							)    ,	[self.model_tester.num_attention_heads, seq_len, seq_len]    ,	)





     def  SCREAMING_SNAKE_CASE__       (    self					:				Union[str, Any]							):
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_					:				Optional[Any]    ,	SCREAMING_SNAKE_CASE_					:				str    ,	SCREAMING_SNAKE_CASE_					:				Union[str, Any]							):
           __lowerCamelCase:				List[Any]     =	model_class(SCREAMING_SNAKE_CASE_							)
           model.to(SCREAMING_SNAKE_CASE_							)
           model.eval()

           with torch.no_grad():
              __lowerCamelCase:				str     =	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)							)

           __lowerCamelCase:				Any     =	outputs.hidden_states

           __lowerCamelCase:				int     =	getattr(
               self.model_tester    ,	"""expected_num_hidden_layers"""    ,	self.model_tester.num_hidden_layers + 1							)
           self.assertEqual(len(SCREAMING_SNAKE_CASE_							)    ,	SCREAMING_SNAKE_CASE_							)

           # YOLOS has a different seq_length
           __lowerCamelCase:				Optional[int]     =	self.model_tester.expected_seq_len

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

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

        for model_class in self.all_model_classes:
           __lowerCamelCase:				Any     =	True
           check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)

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

           check_hidden_states_output(SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_    ,	SCREAMING_SNAKE_CASE_							)





     def  SCREAMING_SNAKE_CASE__       (    self					:				List[str]							):
        __lowerCamelCase:				int     =	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_object_detection(*SCREAMING_SNAKE_CASE_							)







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				Any							):
        for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           __lowerCamelCase:				str     =	YolosModel.from_pretrained(SCREAMING_SNAKE_CASE_							)
           self.assertIsNotNone(SCREAMING_SNAKE_CASE_							)



def     __lowerCAmelCase						(							)       ->							Optional[Any]:
   __lowerCamelCase:				Optional[int]     =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image







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





     @cached_property
     def  SCREAMING_SNAKE_CASE__       (    self					:				str							):
        return AutoImageProcessor.from_pretrained("""hustvl/yolos-small"""							) if is_vision_available() else None







     @slow
     def  SCREAMING_SNAKE_CASE__       (    self					:				List[Any]							):
        __lowerCamelCase:				int     =	YolosForObjectDetection.from_pretrained("""hustvl/yolos-small"""							).to(SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				List[Any]     =	self.default_image_processor
        __lowerCamelCase:				Optional[int]     =	prepare_img()
        __lowerCamelCase:				Optional[Any]     =	image_processor(images=SCREAMING_SNAKE_CASE_    ,	return_tensors="""pt"""							).to(SCREAMING_SNAKE_CASE_							)

        # forward pass
        with torch.no_grad():
           __lowerCamelCase:				str     =	model(inputs.pixel_values							)

        # verify outputs
        __lowerCamelCase:				Optional[int]     =	torch.Size((1, 100, 92)							)
        self.assertEqual(outputs.logits.shape    ,	SCREAMING_SNAKE_CASE_							)

        __lowerCamelCase:				List[str]     =	torch.tensor(
            [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]    ,	device=SCREAMING_SNAKE_CASE_    ,	)
        __lowerCamelCase:				Optional[Any]     =	torch.tensor(
            [[0.2559, 0.5455, 0.4706], [0.2989, 0.7279, 0.1875], [0.7732, 0.4017, 0.4462]]    ,	device=SCREAMING_SNAKE_CASE_							)
        self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]    ,	SCREAMING_SNAKE_CASE_    ,	atol=1E-4							)							)
        self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]    ,	SCREAMING_SNAKE_CASE_    ,	atol=1E-4							)							)

        # verify postprocessing
        __lowerCamelCase:				Union[str, Any]     =	image_processor.post_process_object_detection(
            SCREAMING_SNAKE_CASE_    ,	threshold=0.3    ,	target_sizes=[image.size[::-1]]							)[0]
        __lowerCamelCase:				Optional[Any]     =	torch.tensor([0.9994, 0.9790, 0.9964, 0.9972, 0.9861]							).to(SCREAMING_SNAKE_CASE_							)
        __lowerCamelCase:				Any     =	[75, 75, 17, 63, 17]
        __lowerCamelCase:				Optional[Any]     =	torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]							).to(SCREAMING_SNAKE_CASE_							)

        self.assertEqual(len(results["""scores"""]							)    ,	5							)
        self.assertTrue(torch.allclose(results["""scores"""]    ,	SCREAMING_SNAKE_CASE_    ,	atol=1E-4							)							)
        self.assertSequenceEqual(results["""labels"""].tolist()    ,	SCREAMING_SNAKE_CASE_							)
        self.assertTrue(torch.allclose(results["""boxes"""][0, :]    ,	SCREAMING_SNAKE_CASE_							)							)


