






"""simple docstring"""


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

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

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    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


_UpperCamelCase    :   Optional[Any]   			=						logging.getLogger(__name__)

# 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.14.0', 'To fix: pip install -r examples/pytorch/audio-classification/requirements.txt')




def       snake_case  (A_				:np.ndarray     ,      A_				:float     ,      A_				:int = 1_6_0_0_0				):







  '''simple docstring'''

  a					:      Union[str, Any]    =       int(round(sample_rate * max_length				)				)
  if len(A_				) <= sample_length:
    return wav
  a					:      Union[str, Any]    =       randint(0     ,      len(A_				) - sample_length - 1				)
  return wav[random_offset : random_offset + sample_length]






@dataclass
class 						snake_case  :
    __magic_name__   					=					field(default=UpperCAmelCase       ,			metadata={'''help''': '''Name of a dataset from the datasets package'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''A file containing the training audio paths and labels.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''A file containing the validation audio paths and labels.'''}	)
    __magic_name__   					=					field(
        default='''train'''       ,			metadata={
            '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
        }       ,			)
    __magic_name__   					=					field(
        default='''validation'''       ,			metadata={
            '''help''': (
                '''The name of the training data set split to use (via the datasets library). Defaults to \'validation\''''
            )
        }       ,			)
    __magic_name__   					=					field(
        default='''audio'''       ,			metadata={'''help''': '''The name of the dataset column containing the audio data. Defaults to \'audio\''''}       ,			)
    __magic_name__   					=					field(
        default='''label'''       ,			metadata={'''help''': '''The name of the dataset column containing the labels. Defaults to \'label\''''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': (
                '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                '''value if set.'''
            )
        }       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': (
                '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                '''value if set.'''
            )
        }       ,			)
    __magic_name__   					=					field(
        default=20       ,			metadata={'''help''': '''Audio clips will be randomly cut to this length during training if the value is set.'''}       ,			)






@dataclass
class 						snake_case  :
    __magic_name__   					=					field(
        default='''facebook/wav2vec2-base'''       ,			metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Where do you want to store the pretrained models downloaded from the Hub'''}	)
    __magic_name__   					=					field(
        default='''main'''       ,			metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Name or path of preprocessor config.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Whether to freeze the feature encoder layers of the model.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Whether to generate an attention mask in the feature extractor.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={
            '''help''': (
                '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                '''with private models).'''
            )
        }       ,			)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}	)
    __magic_name__   					=					field(
        default=UpperCAmelCase       ,			metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}       ,			)





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      if not self.freeze_feature_extractor and self.freeze_feature_encoder:
        warnings.warn(
            'The argument `--freeze_feature_extractor` is deprecated and '
            'will be removed in a future version. Use `--freeze_feature_encoder`'
            'instead. Setting `freeze_feature_encoder==True`.'    ,		A    ,		)
      if self.freeze_feature_extractor and not self.freeze_feature_encoder:
        raise ValueError(
            'The argument `--freeze_feature_extractor` is deprecated and '
            'should not be used in combination with `--freeze_feature_encoder`.'
            'Only make use of `--freeze_feature_encoder`.'      )




def       snake_case  ():







  '''simple docstring'''

  a					:      str    =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
  if len(sys.argv				) == 2 and sys.argv[1].endswith('.json'				):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    a,					a,					a					:      Tuple    =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
  else:
    a,					a,					a					:      Any    =       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_audio_classification'     ,      A_     ,      A_				)

  # 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					:      int    =       training_args.get_process_log_level()
  logger.setLevel(A_				)
  transformers.utils.logging.set_verbosity(A_				)
  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}'''				)

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

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

    # Initialize our dataset and prepare it for the audio classification task.
  a					:      Any    =       DatasetDict()
  a					:      List[str]    =       load_dataset(
      data_args.dataset_name     ,      data_args.dataset_config_name     ,      split=data_args.train_split_name     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )
  a					:      Optional[Any]    =       load_dataset(
      data_args.dataset_name     ,      data_args.dataset_config_name     ,      split=data_args.eval_split_name     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )

  if data_args.audio_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f'''--audio_column_name {data_args.audio_column_name} not found in dataset \'{data_args.dataset_name}\'. '''
        'Make sure to set `--audio_column_name` to the correct audio column - one of '
        f'''{', '.join(raw_datasets['train'].column_names				)}.'''				)

  if data_args.label_column_name not in raw_datasets["train"].column_names:
    raise ValueError(
        f'''--label_column_name {data_args.label_column_name} not found in dataset \'{data_args.dataset_name}\'. '''
        'Make sure to set `--label_column_name` to the correct text column - one of '
        f'''{', '.join(raw_datasets['train'].column_names				)}.'''				)

  # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
  # transformer outputs in the classifier, but it doesn't always lead to better accuracy
  a					:      List[str]    =       AutoFeatureExtractor.from_pretrained(
      model_args.feature_extractor_name or model_args.model_name_or_path     ,      return_attention_mask=model_args.attention_mask     ,      cache_dir=model_args.cache_dir     ,      revision=model_args.model_revision     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )

  # `datasets` takes care of automatically loading and resampling the audio,
  # so we just need to set the correct target sampling rate.
  a					:      Optional[Any]    =       raw_datasets.cast_column(
      data_args.audio_column_name     ,      datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate				)				)

  a					:      List[str]    =       feature_extractor.model_input_names[0]

  def train_transforms(A_				:List[Any]				):
    a					:      Tuple    =       []
    for audio in batch[data_args.audio_column_name]:
      a					:      Any    =       random_subsample(
          audio['array']     ,      max_length=data_args.max_length_seconds     ,      sample_rate=feature_extractor.sampling_rate				)
      subsampled_wavs.append(A_				)
    a					:      Optional[Any]    =       feature_extractor(A_     ,      sampling_rate=feature_extractor.sampling_rate				)
    a					:      str    =       {model_input_name: inputs.get(A_				)}
    a					:      Any    =       list(batch[data_args.label_column_name]				)

    return output_batch

  def val_transforms(A_				:Optional[Any]				):
    a					:      List[Any]    =       [audio['array'] for audio in batch[data_args.audio_column_name]]
    a					:      int    =       feature_extractor(A_     ,      sampling_rate=feature_extractor.sampling_rate				)
    a					:      Optional[int]    =       {model_input_name: inputs.get(A_				)}
    a					:      Optional[int]    =       list(batch[data_args.label_column_name]				)

    return output_batch

  # Prepare label mappings.
  # We'll include these in the model's config to get human readable labels in the Inference API.
  a					:      Optional[Any]    =       raw_datasets['train'].features[data_args.label_column_name].names
  a,					a					:      Any    =       {}, {}
  for i, label in enumerate(A_				):
    a					:      Any    =       str(A_				)
    a					:      Optional[int]    =       label

  # Load the accuracy metric from the datasets package
  a					:      int    =       evaluate.load('accuracy'				)

  # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
  # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
  def compute_metrics(A_				:List[str]				):
    a					:      Tuple    =       np.argmax(eval_pred.predictions     ,      axis=1				)
    return metric.compute(predictions=A_     ,      references=eval_pred.label_ids				)

  a					:      Tuple    =       AutoConfig.from_pretrained(
      model_args.config_name or model_args.model_name_or_path     ,      num_labels=len(A_				)     ,      labelaid=A_     ,      idalabel=A_     ,      finetuning_task='audio-classification'     ,      cache_dir=model_args.cache_dir     ,      revision=model_args.model_revision     ,      use_auth_token=True if model_args.use_auth_token else None     ,      )
  a					:      str    =       AutoModelForAudioClassification.from_pretrained(
      model_args.model_name_or_path     ,      from_tf=bool('.ckpt' in model_args.model_name_or_path				)     ,      config=A_     ,      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     ,      )

  # freeze the convolutional waveform encoder
  if model_args.freeze_feature_encoder:
    model.freeze_feature_encoder()

  if training_args.do_train:
    if data_args.max_train_samples is not None:
      a					:      Dict    =       (
          raw_datasets['train'].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
      )
    # Set the training transforms
    raw_datasets["train"].set_transform(A_     ,      output_all_columns=A_				)

  if training_args.do_eval:
    if data_args.max_eval_samples is not None:
      a					:      int    =       (
          raw_datasets['eval'].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
      )
    # Set the validation transforms
    raw_datasets["eval"].set_transform(A_     ,      output_all_columns=A_				)

  # Initialize our trainer
  a					:      Union[str, Any]    =       Trainer(
      model=A_     ,      args=A_     ,      train_dataset=raw_datasets['train'] if training_args.do_train else None     ,      eval_dataset=raw_datasets['eval'] if training_args.do_eval else None     ,      compute_metrics=A_     ,      tokenizer=A_     ,      )

  # Training
  if training_args.do_train:
    a					:      Optional[Any]    =       None
    if training_args.resume_from_checkpoint is not None:
      a					:      str    =       training_args.resume_from_checkpoint
    elif last_checkpoint is not None:
      a					:      Dict    =       last_checkpoint
    a					:      Any    =       trainer.train(resume_from_checkpoint=A_				)
    trainer.save_model()
    trainer.log_metrics('train'     ,      train_result.metrics				)
    trainer.save_metrics('train'     ,      train_result.metrics				)
    trainer.save_state()

  # Evaluation
  if training_args.do_eval:
    a					:      List[str]    =       trainer.evaluate()
    trainer.log_metrics('eval'     ,      A_				)
    trainer.save_metrics('eval'     ,      A_				)

  # Write model card and (optionally) push to hub
  a					:      List[Any]    =       {
      'finetuned_from': model_args.model_name_or_path,
      'tasks': 'audio-classification',
      'dataset': data_args.dataset_name,
      'tags': ['audio-classification'],
  }
  if training_args.push_to_hub:
    trainer.push_to_hub(**A_				)
  else:
    trainer.create_model_card(**A_				)


if __name__ == "__main__":
   main()












"""simple docstring"""


import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
   import torch

   from transformers import (
       MODEL_MAPPING,
       SegformerForImageClassification,
       SegformerForSemanticSegmentation,
       SegformerModel,
   )
   from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import SegformerImageProcessor






class 						snake_case  (  UpperCAmelCase	):





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a					:      Any    =       self.config_class(**self.inputs_dict      )
      self.parent.assertTrue(hasattr(A    ,		'hidden_sizes'      )      )
      self.parent.assertTrue(hasattr(A    ,		'num_attention_heads'      )      )
      self.parent.assertTrue(hasattr(A    ,		'num_encoder_blocks'      )      )






class 						snake_case  :





    def __init__(							self     : List[Any]    ,		A     : Dict    ,		A     : List[Any]=1_3    ,		A     : str=6_4    ,		A     : Union[str, Any]=3    ,		A     : Union[str, Any]=4    ,		A     : Union[str, Any]=[2, 2, 2, 2]    ,		A     : List[str]=[8, 4, 2, 1]    ,		A     : Optional[Any]=[1_6, 3_2, 6_4, 1_2_8]    ,		A     : Optional[Any]=[1, 4, 8, 1_6]    ,		A     : Tuple=[1, 2, 4, 8]    ,		A     : Optional[Any]=True    ,		A     : Any=True    ,		A     : Optional[Any]="gelu"    ,		A     : Optional[int]=0.1    ,		A     : List[Any]=0.1    ,		A     : List[str]=0.02    ,		A     : List[Any]=3    ,		A     : str=None    ,		):


      '''simple docstring'''




      a					:      Optional[Any]    =       parent
      a					:      Optional[Any]    =       batch_size
      a					:      Optional[Any]    =       image_size
      a					:      Optional[int]    =       num_channels
      a					:      List[str]    =       num_encoder_blocks
      a					:      Optional[Any]    =       sr_ratios
      a					:      Any    =       depths
      a					:      Any    =       hidden_sizes
      a					:      Union[str, Any]    =       downsampling_rates
      a					:      Any    =       num_attention_heads
      a					:      int    =       is_training
      a					:      Dict    =       use_labels
      a					:      str    =       hidden_act
      a					:      Optional[int]    =       hidden_dropout_prob
      a					:      Union[str, Any]    =       attention_probs_dropout_prob
      a					:      Optional[Any]    =       initializer_range
      a					:      Dict    =       num_labels
      a					:      Union[str, Any]    =       scope





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      Any    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

      a					:      int    =       None
      if self.use_labels:
        a					:      Dict    =       ids_tensor([self.batch_size, self.image_size, self.image_size]    ,		self.num_labels      )

      a					:      str    =       self.get_config()
      return config, pixel_values, labels





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      return SegformerConfig(
          image_size=self.image_size    ,		num_channels=self.num_channels    ,		num_encoder_blocks=self.num_encoder_blocks    ,		depths=self.depths    ,		hidden_sizes=self.hidden_sizes    ,		num_attention_heads=self.num_attention_heads    ,		hidden_act=self.hidden_act    ,		hidden_dropout_prob=self.hidden_dropout_prob    ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,		initializer_range=self.initializer_range    ,		)





    def     lowerCamelCase__				(							self     : int    ,		A     : str    ,		A     : List[Any]    ,		A     : List[Any]      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       SegformerModel(config=A      )
      model.to(A      )
      model.eval()
      a					:      Union[str, Any]    =       model(A      )
      a					:      Optional[int]    =       self.image_size // (self.downsampling_rates[-1] * 2)
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,		(self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)      )





    def     lowerCamelCase__				(							self     : Optional[int]    ,		A     : Union[str, Any]    ,		A     : str    ,		A     : Optional[Any]      ):


      '''simple docstring'''




      a					:      List[Any]    =       self.num_labels
      a					:      Optional[int]    =       SegformerForSemanticSegmentation(A      )
      model.to(A      )
      model.eval()
      a					:      str    =       model(A      )
      self.parent.assertEqual(
          result.logits.shape    ,		(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)      )
      a					:      int    =       model(A    ,		labels=A      )
      self.parent.assertEqual(
          result.logits.shape    ,		(self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)      )
      self.parent.assertGreater(result.loss    ,		0.0      )





    def     lowerCamelCase__				(							self     : Dict    ,		A     : Dict    ,		A     : Any    ,		A     : Optional[Any]      ):


      '''simple docstring'''




      a					:      Optional[int]    =       1
      a					:      List[Any]    =       SegformerForSemanticSegmentation(config=A      )
      model.to(A      )
      model.eval()
      a					:      Any    =       torch.randint(0    ,		1    ,		(self.batch_size, self.image_size, self.image_size)      ).to(A      )
      a					:      Dict    =       model(A    ,		labels=A      )
      self.parent.assertGreater(result.loss    ,		0.0      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      str    =       self.prepare_config_and_inputs()
      a,					a,					a					:      str    =       config_and_inputs
      a					:      Dict    =       {'pixel_values': pixel_values}
      return config, inputs_dict






@require_torch
class 						snake_case  (  UpperCAmelCase       ,			UpperCAmelCase       ,			unittest.TestCase	):
    __magic_name__   					=					(
        (
            SegformerModel,
            SegformerForSemanticSegmentation,
            SegformerForImageClassification,
        )
        if is_torch_available()
        else ()
    )
    __magic_name__   					=					(
        {
            '''feature-extraction''': SegformerModel,
            '''image-classification''': SegformerForImageClassification,
            '''image-segmentation''': SegformerForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    __magic_name__   					=					True
    __magic_name__   					=					False
    __magic_name__   					=					False
    __magic_name__   					=					False





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      Union[str, Any]    =       SegformerModelTester(self      )
      a					:      Tuple    =       SegformerConfigTester(self    ,		config_class=A      )





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




      self.config_tester.run_common_tests()





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a					:      Optional[int]    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*A      )





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




      a					:      Optional[int]    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_binary_image_segmentation(*A      )





    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      a					:      int    =       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_segmentation(*A      )





    @unittest.skip('SegFormer does not use inputs_embeds'      )
    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      pass





    @unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'      )
    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




      pass





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a,					a					:      int    =       self.model_tester.prepare_config_and_inputs_for_common()

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

        a					:      Optional[Any]    =       ['pixel_values']
        self.assertListEqual(arg_names[:1]    ,		A      )





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      a,					a					:      Any    =       self.model_tester.prepare_config_and_inputs_for_common()
      a					:      Any    =       True

      for model_class in self.all_model_classes:
        a					:      Optional[Any]    =       True
        a					:      Tuple    =       False
        a					:      int    =       True
        a					:      Any    =       model_class(A      )
        model.to(A      )
        model.eval()
        with torch.no_grad():
          a					:      Dict    =       model(**self._prepare_for_class(A    ,		A      )      )
        a					:      Union[str, Any]    =       outputs.attentions

        a					:      Tuple    =       sum(self.model_tester.depths      )
        self.assertEqual(len(A      )    ,		A      )

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

        self.assertEqual(len(A      )    ,		A      )

        # verify the first attentions (first block, first layer)
        a					:      Union[str, Any]    =       (self.model_tester.image_size // 4) ** 2
        a					:      List[str]    =       (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
        self.assertListEqual(
            list(attentions[0].shape[-3:]      )    ,		[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]    ,		)

        # verify the last attentions (last block, last layer)
        a					:      Tuple    =       (self.model_tester.image_size // 3_2) ** 2
        a					:      Tuple    =       (self.model_tester.image_size // (3_2 * self.model_tester.sr_ratios[-1])) ** 2
        self.assertListEqual(
            list(attentions[-1].shape[-3:]      )    ,		[self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]    ,		)
        a					:      str    =       len(A      )

        # Check attention is always last and order is fine
        a					:      str    =       True
        a					:      Tuple    =       True
        a					:      List[str]    =       model_class(A      )
        model.to(A      )
        model.eval()
        with torch.no_grad():
          a					:      Dict    =       model(**self._prepare_for_class(A    ,		A      )      )

        self.assertEqual(out_len + 1    ,		len(A      )      )

        a					:      str    =       outputs.attentions

        self.assertEqual(len(A      )    ,		A      )
        # verify the first attentions (first block, first layer)
        a					:      Union[str, Any]    =       (self.model_tester.image_size // 4) ** 2
        a					:      Optional[int]    =       (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
        self.assertListEqual(
            list(self_attentions[0].shape[-3:]      )    ,		[self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]    ,		)





    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      def check_hidden_states_output(A     : Optional[Any]    ,		A     : List[str]    ,		A     : Union[str, Any]      ):
        a					:      Optional[Any]    =       model_class(A      )
        model.to(A      )
        model.eval()

        with torch.no_grad():
          a					:      Optional[Any]    =       model(**self._prepare_for_class(A    ,		A      )      )

        a					:      Tuple    =       outputs.hidden_states

        a					:      Optional[Any]    =       self.model_tester.num_encoder_blocks
        self.assertEqual(len(A      )    ,		A      )

        # verify the first hidden states (first block)
        self.assertListEqual(
            list(hidden_states[0].shape[-3:]      )    ,		[
                self.model_tester.hidden_sizes[0],
                self.model_tester.image_size // 4,
                self.model_tester.image_size // 4,
            ]    ,		)

      a,					a					:      Any    =       self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(A    ,		A    ,		A      )





    def     lowerCamelCase__				(							self     : Optional[int]      ):


      '''simple docstring'''




      if not self.model_tester.is_training:
        return

      a,					a					:      List[str]    =       self.model_tester.prepare_config_and_inputs_for_common()
      a					:      List[Any]    =       True

      for model_class in self.all_model_classes:
        if model_class in get_values(A      ):
          continue

        a					:      List[Any]    =       model_class(A      )
        model.to(A      )
        model.train()
        a					:      Tuple    =       self._prepare_for_class(A    ,		A    ,		return_labels=A      )
        a					:      Any    =       model(**A      ).loss
        loss.backward()





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


      '''simple docstring'''




      pass





    @slow
    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a					:      Dict    =       SegformerModel.from_pretrained(A      )
        self.assertIsNotNone(A      )




def       snake_case  ():







  '''simple docstring'''

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






@require_torch
class 						snake_case  (  unittest.TestCase	):





    @slow
    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a					:      int    =       SegformerImageProcessor(
          image_scale=(5_1_2, 5_1_2)    ,		keep_ratio=A    ,		align=A    ,		do_random_crop=A      )
      a					:      Dict    =       SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'      ).to(
          A      )

      a					:      str    =       prepare_img()
      a					:      List[str]    =       image_processor(images=A    ,		return_tensors='pt'      )
      a					:      List[str]    =       encoded_inputs.pixel_values.to(A      )

      with torch.no_grad():
        a					:      Optional[int]    =       model(A      )

      a					:      Any    =       torch.Size((1, model.config.num_labels, 1_2_8, 1_2_8)      )
      self.assertEqual(outputs.logits.shape    ,		A      )

      a					:      str    =       torch.tensor(
          [
              [[-4.63_10, -5.52_32, -6.23_56], [-5.19_21, -6.14_44, -6.59_96], [-5.44_24, -6.27_90, -6.75_74]],
              [[-12.13_91, -13.31_22, -13.95_54], [-12.87_32, -13.93_52, -14.35_63], [-12.94_38, -13.82_26, -14.25_13]],
              [[-12.51_34, -13.46_86, -14.49_15], [-12.86_69, -14.43_43, -14.77_58], [-13.25_23, -14.58_19, -15.06_94]],
          ]      ).to(A      )
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]    ,		A    ,		atol=1E-4      )      )





    @slow
    def     lowerCamelCase__				(							self     : Optional[Any]      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       SegformerImageProcessor(
          image_scale=(5_1_2, 5_1_2)    ,		keep_ratio=A    ,		align=A    ,		do_random_crop=A      )
      a					:      Optional[Any]    =       SegformerForSemanticSegmentation.from_pretrained(
          'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'      ).to(A      )

      a					:      List[Any]    =       prepare_img()
      a					:      Optional[Any]    =       image_processor(images=A    ,		return_tensors='pt'      )
      a					:      int    =       encoded_inputs.pixel_values.to(A      )

      with torch.no_grad():
        a					:      Optional[Any]    =       model(A      )

      a					:      Tuple    =       torch.Size((1, model.config.num_labels, 1_2_8, 1_2_8)      )
      self.assertEqual(outputs.logits.shape    ,		A      )

      a					:      Optional[Any]    =       torch.tensor(
          [
              [[-13.57_48, -13.91_11, -12.65_00], [-14.35_00, -15.36_83, -14.23_28], [-14.75_32, -16.04_24, -15.60_87]],
              [[-17.16_51, -15.87_25, -12.96_53], [-17.25_80, -17.37_18, -14.82_23], [-16.60_58, -16.87_83, -16.74_52]],
              [[-3.64_56, -3.02_09, -1.42_03], [-3.07_97, -3.19_59, -2.00_00], [-1.87_57, -1.92_17, -1.69_97]],
          ]      ).to(A      )
      self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]    ,		A    ,		atol=1E-1      )      )





    @slow
    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




      a					:      str    =       SegformerImageProcessor(
          image_scale=(5_1_2, 5_1_2)    ,		keep_ratio=A    ,		align=A    ,		do_random_crop=A      )
      a					:      Optional[int]    =       SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'      ).to(
          A      )

      a					:      int    =       prepare_img()
      a					:      Any    =       image_processor(images=A    ,		return_tensors='pt'      )
      a					:      List[Any]    =       encoded_inputs.pixel_values.to(A      )

      with torch.no_grad():
        a					:      str    =       model(A      )

      a					:      str    =       outputs.logits.detach().cpu()

      a					:      Optional[Any]    =       image_processor.post_process_semantic_segmentation(outputs=A    ,		target_sizes=[(5_0_0, 3_0_0)]      )
      a					:      Dict    =       torch.Size((5_0_0, 3_0_0)      )
      self.assertEqual(segmentation[0].shape    ,		A      )

      a					:      int    =       image_processor.post_process_semantic_segmentation(outputs=A      )
      a					:      Any    =       torch.Size((1_2_8, 1_2_8)      )
      self.assertEqual(segmentation[0].shape    ,		A      )




