



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


SCREAMING_SNAKE_CASE__   			=   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 A    (							__UpperCamelCase			,						__UpperCamelCase			,						__UpperCamelCase = 16_000       )    ->   Union[str, Any]:
			A__	  =     int(round(sample_rate * max_length       )       )
			if len(__UpperCamelCase       ) <= sample_length:
						return wav
			A__	  =     randint(0			,						len(__UpperCamelCase       ) - sample_length - 1       )
			return wav[random_offset : random_offset + sample_length]


@dataclass
class   __lowerCAmelCase  :
					"""simple docstring"""






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







@dataclass
class   __lowerCAmelCase  :
					"""simple docstring"""






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



					def      _a				(  self       :							Dict       ):






								"""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`.'					,       _snake_case					,       )
								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 A    (							)    ->   List[str]:
			# See all possible arguments in src/transformers/training_args.py
			# or by passing the --help flag to this script.
			# We now keep distinct sets of args, for a cleaner separation of concerns.

			A__	  =     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
			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__	  =     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
			else:
						A__  ,			A__  ,			A__	  =     parser.parse_args_into_dataclasses()

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

			# Setup logging
			logging.basicConfig(
			    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'			,						datefmt='%m/%d/%Y %H:%M:%S'			,						handlers=[logging.StreamHandler(sys.stdout       )]			,						)

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

			A__	  =     training_args.get_process_log_level()
			logger.setLevel(__UpperCamelCase       )
			transformers.utils.logging.set_verbosity(__UpperCamelCase       )
			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__	  =     None
			if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
						A__	  =     get_last_checkpoint(training_args.output_dir       )
						if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
									raise ValueError(
									    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
									    'Use --overwrite_output_dir to 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__	  =     DatasetDict()
			A__	  =     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__	  =     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__	  =     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__	  =     raw_datasets.cast_column(
			    data_args.audio_column_name			,						datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate       )       )

			A__	  =     feature_extractor.model_input_names[0]

			def train_transforms(__UpperCamelCase       ):
						A__	  =     []
						for audio in batch[data_args.audio_column_name]:
									A__	  =     random_subsample(
									    audio['array']			,						max_length=data_args.max_length_seconds			,						sample_rate=feature_extractor.sampling_rate       )
									subsampled_wavs.append(__UpperCamelCase       )
						A__	  =     feature_extractor(__UpperCamelCase			,						sampling_rate=feature_extractor.sampling_rate       )
						A__	  =     {model_input_name: inputs.get(__UpperCamelCase       )}
						A__	  =     list(batch[data_args.label_column_name]       )

						return output_batch

			def val_transforms(__UpperCamelCase       ):
						A__	  =     [audio['array'] for audio in batch[data_args.audio_column_name]]
						A__	  =     feature_extractor(__UpperCamelCase			,						sampling_rate=feature_extractor.sampling_rate       )
						A__	  =     {model_input_name: inputs.get(__UpperCamelCase       )}
						A__	  =     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__	  =     raw_datasets['train'].features[data_args.label_column_name].names
			A__  ,			A__	  =     {}, {}
			for i, label in enumerate(__UpperCamelCase       ):
						A__	  =     str(__UpperCamelCase       )
						A__	  =     label

			# Load the accuracy metric from the datasets package
			A__	  =     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(__UpperCamelCase       ):
						A__	  =     np.argmax(eval_pred.predictions			,						axis=1       )
						return metric.compute(predictions=__UpperCamelCase			,						references=eval_pred.label_ids       )

			A__	  =     AutoConfig.from_pretrained(
			    model_args.config_name or model_args.model_name_or_path			,						num_labels=len(__UpperCamelCase       )			,						labelaid=__UpperCamelCase			,						idalabel=__UpperCamelCase			,						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__	  =     AutoModelForAudioClassification.from_pretrained(
			    model_args.model_name_or_path			,						from_tf=bool('.ckpt' in model_args.model_name_or_path       )			,						config=__UpperCamelCase			,						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__	  =     (
									    raw_datasets['train'].shuffle(seed=training_args.seed       ).select(range(data_args.max_train_samples       )       )
									)
						# Set the training transforms
						raw_datasets["train"].set_transform(__UpperCamelCase			,						output_all_columns=__UpperCamelCase       )

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

			# Initialize our trainer
			A__	  =     Trainer(
			    model=__UpperCamelCase			,						args=__UpperCamelCase			,						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=__UpperCamelCase			,						tokenizer=__UpperCamelCase			,						)

			# Training
			if training_args.do_train:
						A__	  =     None
						if training_args.resume_from_checkpoint is not None:
									A__	  =     training_args.resume_from_checkpoint
						elif last_checkpoint is not None:
									A__	  =     last_checkpoint
						A__	  =     trainer.train(resume_from_checkpoint=__UpperCamelCase       )
						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__	  =     trainer.evaluate()
						trainer.log_metrics('eval'			,						__UpperCamelCase       )
						trainer.save_metrics('eval'			,						__UpperCamelCase       )

			# Write model card and (optionally) push to hub
			A__	  =     {
			    '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(**__UpperCamelCase       )
			else:
						trainer.create_model_card(**__UpperCamelCase       )


if __name__ == "__main__":
							main()









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   __lowerCAmelCase  (		UpperCAmelCase_   ):
					"""simple docstring"""






					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								A__	  =     self.config_class(**self.inputs_dict       )
								self.parent.assertTrue(hasattr(_snake_case					,       'hidden_sizes'       )       )
								self.parent.assertTrue(hasattr(_snake_case					,       'num_attention_heads'       )       )
								self.parent.assertTrue(hasattr(_snake_case					,       'num_encoder_blocks'       )       )







class   __lowerCAmelCase  :
					"""simple docstring"""






					def __init__(  self       :							Any					,       _snake_case       :							str					,       _snake_case       :							Union[str, Any]=13					,       _snake_case       :							Any=64					,       _snake_case       :							Optional[Any]=3					,       _snake_case       :							Dict=4					,       _snake_case       :							Tuple=[2, 2, 2, 2]					,       _snake_case       :							str=[8, 4, 2, 1]					,       _snake_case       :							Union[str, Any]=[16, 32, 64, 1_28]					,       _snake_case       :							int=[1, 4, 8, 16]					,       _snake_case       :							List[str]=[1, 2, 4, 8]					,       _snake_case       :							int=True					,       _snake_case       :							int=True					,       _snake_case       :							Union[str, Any]="gelu"					,       _snake_case       :							Optional[int]=0.1					,       _snake_case       :							Tuple=0.1					,       _snake_case       :							Dict=0.02					,       _snake_case       :							Tuple=3					,       _snake_case       :							int=None					,       ):






								"""simple docstring"""


								A__	  =     parent
								A__	  =     batch_size
								A__	  =     image_size
								A__	  =     num_channels
								A__	  =     num_encoder_blocks
								A__	  =     sr_ratios
								A__	  =     depths
								A__	  =     hidden_sizes
								A__	  =     downsampling_rates
								A__	  =     num_attention_heads
								A__	  =     is_training
								A__	  =     use_labels
								A__	  =     hidden_act
								A__	  =     hidden_dropout_prob
								A__	  =     attention_probs_dropout_prob
								A__	  =     initializer_range
								A__	  =     num_labels
								A__	  =     scope



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								A__	  =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

								A__	  =     self.get_config()
								return config, pixel_values, labels



					def      _a				(  self       :							int       ):






								"""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      _a				(  self       :							int					,       _snake_case       :							Optional[Any]					,       _snake_case       :							int					,       _snake_case       :							Any       ):






								"""simple docstring"""


								A__	  =     SegformerModel(config=_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     model(_snake_case       )
								A__	  =     A__	  =     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      _a				(  self       :							Union[str, Any]					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Tuple					,       _snake_case       :							Dict       ):






								"""simple docstring"""


								A__	  =     self.num_labels
								A__	  =     SegformerForSemanticSegmentation(_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     model(_snake_case       )
								self.parent.assertEqual(
								    result.logits.shape					,       (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)       )
								A__	  =     model(_snake_case					,       labels=_snake_case       )
								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      _a				(  self       :							List[str]					,       _snake_case       :							Optional[Any]					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     1
								A__	  =     SegformerForSemanticSegmentation(config=_snake_case       )
								model.to(_snake_case       )
								model.eval()
								A__	  =     torch.randint(0					,       1					,       (self.batch_size, self.image_size, self.image_size)       ).to(_snake_case       )
								A__	  =     model(_snake_case					,       labels=_snake_case       )
								self.parent.assertGreater(result.loss					,       0.0       )



					def      _a				(  self       :							List[Any]       ):






								"""simple docstring"""


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







@require_torch
class   __lowerCAmelCase  (		UpperCAmelCase_				,  UpperCAmelCase_				,  unittest.TestCase   ):
					"""simple docstring"""






					A__					:		Optional[int]      							=     (
					    (
					        SegformerModel,
					        SegformerForSemanticSegmentation,
					        SegformerForImageClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					A__					:		Union[str, Any]      							=     (
					    {
					        "feature-extraction": SegformerModel,
					        "image-classification": SegformerForImageClassification,
					        "image-segmentation": SegformerForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					A__					:		Optional[Any]      							=     True
					A__					:		str      							=     False
					A__					:		Tuple      							=     False
					A__					:		Dict      							=     False



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






								"""simple docstring"""


								A__	  =     SegformerModelTester(self       )
								A__	  =     SegformerConfigTester(self					,       config_class=_snake_case       )



					def      _a				(  self       :							Optional[int]       ):






								"""simple docstring"""


								self.config_tester.run_common_tests()



					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case       )



					def      _a				(  self       :							List[Any]       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_binary_image_segmentation(*_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_segmentation(*_snake_case       )



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






								"""simple docstring"""


								pass



					@unittest.skip('SegFormer does not have get_input_embeddings method and get_output_embeddings methods'       )
					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								pass



					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()

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

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



					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()
								A__	  =     True

								for model_class in self.all_model_classes:
											A__	  =     True
											A__	  =     False
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )
											A__	  =     outputs.attentions

											A__	  =     sum(self.model_tester.depths       )
											self.assertEqual(len(_snake_case       )					,       _snake_case       )

											# check that output_attentions also work using config
											del inputs_dict["output_attentions"]
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )
											A__	  =     outputs.attentions

											self.assertEqual(len(_snake_case       )					,       _snake_case       )

											# verify the first attentions (first block, first layer)
											A__	  =     (self.model_tester.image_size // 4) ** 2
											A__	  =     (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__	  =     (self.model_tester.image_size // 32) ** 2
											A__	  =     (self.model_tester.image_size // (32 * 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__	  =     len(_snake_case       )

											# Check attention is always last and order is fine
											A__	  =     True
											A__	  =     True
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()
											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )

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

											A__	  =     outputs.attentions

											self.assertEqual(len(_snake_case       )					,       _snake_case       )
											# verify the first attentions (first block, first layer)
											A__	  =     (self.model_tester.image_size // 4) ** 2
											A__	  =     (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      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								def check_hidden_states_output(_snake_case       :							Dict					,       _snake_case       :							int					,       _snake_case       :							List[Any]       ):
											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.eval()

											with torch.no_grad():
														A__	  =     model(**self._prepare_for_class(_snake_case					,       _snake_case       )       )

											A__	  =     outputs.hidden_states

											A__	  =     self.model_tester.num_encoder_blocks
											self.assertEqual(len(_snake_case       )					,       _snake_case       )

											# 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__	  =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											A__	  =     True
											check_hidden_states_output(_snake_case					,       _snake_case					,       _snake_case       )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											A__	  =     True

											check_hidden_states_output(_snake_case					,       _snake_case					,       _snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								if not self.model_tester.is_training:
											return

								A__  ,			A__	  =     self.model_tester.prepare_config_and_inputs_for_common()
								A__	  =     True

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

											A__	  =     model_class(_snake_case       )
											model.to(_snake_case       )
											model.train()
											A__	  =     self._prepare_for_class(_snake_case					,       _snake_case					,       return_labels=_snake_case       )
											A__	  =     model(**_snake_case       ).loss
											loss.backward()



					@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'       )
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								pass



					@slow
					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											A__	  =     SegformerModel.from_pretrained(_snake_case       )
											self.assertIsNotNone(_snake_case       )







def A    (							)    ->   str:
			A__	  =     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
			return image






@require_torch
class   __lowerCAmelCase  (		unittest.TestCase   ):
					"""simple docstring"""






					@slow
					def      _a				(  self       :							Dict       ):






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
								    _snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     torch.Size((1, model.config.num_labels, 1_28, 1_28)       )
								self.assertEqual(outputs.logits.shape					,       _snake_case       )

								A__	  =     torch.tensor(
								    [
								        [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
								        [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
								        [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
								    ]       ).to(_snake_case       )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,       _snake_case					,       atol=1E-4       )       )



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






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained(
								    'nvidia/segformer-b1-finetuned-cityscapes-1024-1024'       ).to(_snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     torch.Size((1, model.config.num_labels, 1_28, 1_28)       )
								self.assertEqual(outputs.logits.shape					,       _snake_case       )

								A__	  =     torch.tensor(
								    [
								        [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
								        [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
								        [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
								    ]       ).to(_snake_case       )
								self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]					,       _snake_case					,       atol=1E-1       )       )



					@slow
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     SegformerImageProcessor(
								    image_scale=(5_12, 5_12)					,       keep_ratio=_snake_case					,       align=_snake_case					,       do_random_crop=_snake_case       )
								A__	  =     SegformerForSemanticSegmentation.from_pretrained('nvidia/segformer-b0-finetuned-ade-512-512'       ).to(
								    _snake_case       )

								A__	  =     prepare_img()
								A__	  =     image_processor(images=_snake_case					,       return_tensors='pt'       )
								A__	  =     encoded_inputs.pixel_values.to(_snake_case       )

								with torch.no_grad():
											A__	  =     model(_snake_case       )

								A__	  =     outputs.logits.detach().cpu()

								A__	  =     image_processor.post_process_semantic_segmentation(outputs=_snake_case					,       target_sizes=[(5_00, 3_00)]       )
								A__	  =     torch.Size((5_00, 3_00)       )
								self.assertEqual(segmentation[0].shape					,       _snake_case       )

								A__	  =     image_processor.post_process_semantic_segmentation(outputs=_snake_case       )
								A__	  =     torch.Size((1_28, 1_28)       )
								self.assertEqual(segmentation[0].shape					,       _snake_case       )




