





import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO
)
lowerCAmelCase_        =							logging.getLogger(__name__)






def 	lowerCamelCase_		(							_UpperCamelCase					,							_UpperCamelCase					)						->		Optional[Any]:






				"""simple docstring"""


				snake_case_		:       List[str]           =    np.argmax(_UpperCamelCase					,							axis=1					)
				return np.sum(outputs == labels					)






def 	lowerCamelCase_		(							_UpperCamelCase					)						->		List[Any]:






				"""simple docstring"""


				with open(_UpperCamelCase					,							encoding='''utf_8'''					) as f:
								snake_case_		:       List[str]           =    csv.reader(_UpperCamelCase					)
								snake_case_		:       Dict           =    []
								next(_UpperCamelCase					)  # skip the first line
								for line in tqdm(_UpperCamelCase					):
												output.append((''' '''.join(line[1:5]					), line[5], line[6], int(line[-1]					) - 1)					)
				return output






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






				"""simple docstring"""


				snake_case_		:       Dict           =    []
				for dataset in encoded_datasets:
								snake_case_		:       List[str]           =    len(_UpperCamelCase					)
								snake_case_		:       Dict           =    np.zeros((n_batch, 2, input_len)					,							dtype=np.intaa					)
								snake_case_		:       Optional[Any]           =    np.zeros((n_batch, 2)					,							dtype=np.intaa					)
								snake_case_		:       List[Any]           =    np.full((n_batch, 2, input_len)					,							fill_value=-100					,							dtype=np.intaa					)
								snake_case_		:       Dict           =    np.zeros((n_batch,)					,							dtype=np.intaa					)
								for (
								    i,
								    (story, conta, conta, mc_label),
								) in enumerate(_UpperCamelCase					):
												snake_case_		:       Union[str, Any]           =    [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
												snake_case_		:       Any           =    [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
												snake_case_		:       List[Any]           =    with_conta
												snake_case_		:       List[str]           =    with_conta
												snake_case_		:       Optional[Any]           =    len(_UpperCamelCase					) - 1
												snake_case_		:       int           =    len(_UpperCamelCase					) - 1
												snake_case_		:       Optional[Any]           =    with_conta
												snake_case_		:       Union[str, Any]           =    with_conta
												snake_case_		:       Any           =    mc_label
								snake_case_		:       List[str]           =    (input_ids, mc_token_ids, lm_labels, mc_labels)
								tensor_datasets.append(tuple(torch.tensor(_UpperCamelCase					) for t in all_inputs					)					)
				return tensor_datasets






def 	lowerCamelCase_		(							)						->		int:






				"""simple docstring"""


				snake_case_		:       str           =    argparse.ArgumentParser()
				parser.add_argument('''--model_name'''					,							type=_UpperCamelCase					,							default='''openai-gpt'''					,							help='''pretrained model name'''					)
				parser.add_argument('''--do_train'''					,							action='''store_true'''					,							help='''Whether to run training.'''					)
				parser.add_argument('''--do_eval'''					,							action='''store_true'''					,							help='''Whether to run eval on the dev set.'''					)
				parser.add_argument(
				    '''--output_dir'''					,							default=_UpperCamelCase					,							type=_UpperCamelCase					,							required=_UpperCamelCase					,							help='''The output directory where the model predictions and checkpoints will be written.'''					,							)
				parser.add_argument('''--train_dataset'''					,							type=_UpperCamelCase					,							default=''''''					)
				parser.add_argument('''--eval_dataset'''					,							type=_UpperCamelCase					,							default=''''''					)
				parser.add_argument('''--seed'''					,							type=_UpperCamelCase					,							default=42					)
				parser.add_argument('''--num_train_epochs'''					,							type=_UpperCamelCase					,							default=3					)
				parser.add_argument('''--train_batch_size'''					,							type=_UpperCamelCase					,							default=8					)
				parser.add_argument('''--eval_batch_size'''					,							type=_UpperCamelCase					,							default=16					)
				parser.add_argument('''--adam_epsilon'''					,							default=1E-8					,							type=_UpperCamelCase					,							help='''Epsilon for Adam optimizer.'''					)
				parser.add_argument('''--max_grad_norm'''					,							type=_UpperCamelCase					,							default=1					)
				parser.add_argument(
				    '''--max_steps'''					,							default=-1					,							type=_UpperCamelCase					,							help=(
				        '''If > 0: set total number of training                         steps to perform. Override num_train_epochs.'''
				    )					,							)
				parser.add_argument(
				    '''--gradient_accumulation_steps'''					,							type=_UpperCamelCase					,							default=1					,							help='''Number of updates steps to accumulate before                        performing a backward/update pass.'''					,							)
				parser.add_argument('''--learning_rate'''					,							type=_UpperCamelCase					,							default=6.25E-5					)
				parser.add_argument('''--warmup_steps'''					,							default=0					,							type=_UpperCamelCase					,							help='''Linear warmup over warmup_steps.'''					)
				parser.add_argument('''--lr_schedule'''					,							type=_UpperCamelCase					,							default='''warmup_linear'''					)
				parser.add_argument('''--weight_decay'''					,							type=_UpperCamelCase					,							default=0.01					)
				parser.add_argument('''--lm_coef'''					,							type=_UpperCamelCase					,							default=0.9					)
				parser.add_argument('''--n_valid'''					,							type=_UpperCamelCase					,							default=374					)

				parser.add_argument('''--server_ip'''					,							type=_UpperCamelCase					,							default=''''''					,							help='''Can be used for distant debugging.'''					)
				parser.add_argument('''--server_port'''					,							type=_UpperCamelCase					,							default=''''''					,							help='''Can be used for distant debugging.'''					)
				snake_case_		:       List[Any]           =    parser.parse_args()
				print(_UpperCamelCase					)

				if args.server_ip and args.server_port:
								# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
								import ptvsd

								print('''Waiting for debugger attach'''					)
								ptvsd.enable_attach(address=(args.server_ip, args.server_port)					,							redirect_output=_UpperCamelCase					)
								ptvsd.wait_for_attach()

				random.seed(args.seed					)
				np.random.seed(args.seed					)
				torch.manual_seed(args.seed					)
				torch.cuda.manual_seed_all(args.seed					)

				snake_case_		:       int           =    torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''					)
				snake_case_		:       str           =    torch.cuda.device_count()
				logger.info('''device: {}, n_gpu {}'''.format(_UpperCamelCase					,							_UpperCamelCase					)					)

				if not args.do_train and not args.do_eval:
								raise ValueError('''At least one of `do_train` or `do_eval` must be True.'''					)

				if not os.path.exists(args.output_dir					):
								os.makedirs(args.output_dir					)

				# Load tokenizer and model
				# This loading functions also add new tokens and embeddings called `special tokens`
				# These new embeddings will be fine-tuned on the RocStories dataset
				snake_case_		:       Dict           =    ['''_start_''', '''_delimiter_''', '''_classify_''']
				snake_case_		:       Any           =    OpenAIGPTTokenizer.from_pretrained(args.model_name					)
				tokenizer.add_tokens(_UpperCamelCase					)
				snake_case_		:       Tuple           =    tokenizer.convert_tokens_to_ids(_UpperCamelCase					)
				snake_case_		:       Dict           =    OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name					)
				model.resize_token_embeddings(len(_UpperCamelCase					)					)
				model.to(_UpperCamelCase					)

				# Load and encode the datasets
				def tokenize_and_encode(_UpperCamelCase					):
								if isinstance(_UpperCamelCase					,							_UpperCamelCase					):
												return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_UpperCamelCase					)					)
								elif isinstance(_UpperCamelCase					,							_UpperCamelCase					):
												return obj
								return [tokenize_and_encode(_UpperCamelCase					) for o in obj]

				logger.info('''Encoding dataset...'''					)
				snake_case_		:       Tuple           =    load_rocstories_dataset(args.train_dataset					)
				snake_case_		:       Dict           =    load_rocstories_dataset(args.eval_dataset					)
				snake_case_		:       Optional[Any]           =    (train_dataset, eval_dataset)
				snake_case_		:       Union[str, Any]           =    tokenize_and_encode(_UpperCamelCase					)

				# Compute the max input length for the Transformer
				snake_case_		:       Dict           =    model.config.n_positions // 2 - 2
				snake_case_		:       int           =    max(
				    len(story[:max_length]					) + max(len(conta[:max_length]					)					,							len(conta[:max_length]					)					) + 3
				    for dataset in encoded_datasets
				    for story, conta, conta, _ in dataset					)
				snake_case_		:       str           =    min(_UpperCamelCase					,							model.config.n_positions					)  # Max size of input for the pre-trained model

				# Prepare inputs tensors and dataloaders
				snake_case_		:       int           =    pre_process_datasets(_UpperCamelCase					,							_UpperCamelCase					,							_UpperCamelCase					,							*_UpperCamelCase					)
				snake_case_     ,				snake_case_		:       str           =    tensor_datasets[0], tensor_datasets[1]

				snake_case_		:       List[str]           =    TensorDataset(*_UpperCamelCase					)
				snake_case_		:       int           =    RandomSampler(_UpperCamelCase					)
				snake_case_		:       Union[str, Any]           =    DataLoader(_UpperCamelCase					,							sampler=_UpperCamelCase					,							batch_size=args.train_batch_size					)

				snake_case_		:       Any           =    TensorDataset(*_UpperCamelCase					)
				snake_case_		:       str           =    SequentialSampler(_UpperCamelCase					)
				snake_case_		:       int           =    DataLoader(_UpperCamelCase					,							sampler=_UpperCamelCase					,							batch_size=args.eval_batch_size					)

				# Prepare optimizer
				if args.do_train:
								if args.max_steps > 0:
												snake_case_		:       Tuple           =    args.max_steps
												snake_case_		:       Union[str, Any]           =    args.max_steps // (len(_UpperCamelCase					) // args.gradient_accumulation_steps) + 1
								else:
												snake_case_		:       List[Any]           =    len(_UpperCamelCase					) // args.gradient_accumulation_steps * args.num_train_epochs

								snake_case_		:       Optional[Any]           =    list(model.named_parameters()					)
								snake_case_		:       List[str]           =    ['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight''']
								snake_case_		:       str           =    [
								    {
								        '''params''': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay					)],
								        '''weight_decay''': args.weight_decay,
								    },
								    {'''params''': [p for n, p in param_optimizer if any(nd in n for nd in no_decay					)], '''weight_decay''': 0.0},
								]
								snake_case_		:       Optional[int]           =    AdamW(_UpperCamelCase					,							lr=args.learning_rate					,							eps=args.adam_epsilon					)
								snake_case_		:       Optional[int]           =    get_linear_schedule_with_warmup(
								    _UpperCamelCase					,							num_warmup_steps=args.warmup_steps					,							num_training_steps=_UpperCamelCase					)

				if args.do_train:
								snake_case_     ,				snake_case_     ,				snake_case_		:       List[str]           =    0, 0, None
								model.train()
								for _ in trange(int(args.num_train_epochs					)					,							desc='''Epoch'''					):
												snake_case_		:       Tuple           =    0
												snake_case_		:       Union[str, Any]           =    0
												snake_case_		:       Any           =    tqdm(_UpperCamelCase					,							desc='''Training'''					)
												for step, batch in enumerate(_UpperCamelCase					):
																snake_case_		:       Dict           =    tuple(t.to(_UpperCamelCase					) for t in batch					)
																snake_case_     ,				snake_case_     ,				snake_case_     ,				snake_case_		:       int           =    batch
																snake_case_		:       Union[str, Any]           =    model(_UpperCamelCase					,							mc_token_ids=_UpperCamelCase					,							lm_labels=_UpperCamelCase					,							mc_labels=_UpperCamelCase					)
																snake_case_		:       str           =    args.lm_coef * losses[0] + losses[1]
																loss.backward()
																optimizer.step()
																scheduler.step()
																optimizer.zero_grad()
																tr_loss += loss.item()
																snake_case_		:       Optional[Any]           =    (
																    loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
																)
																nb_tr_steps += 1
																snake_case_		:       int           =    '''Training loss: {:.2e} lr: {:.2e}'''.format(_UpperCamelCase					,							scheduler.get_lr()[0]					)

    # Save a trained model
				if args.do_train:
								# Save a trained model, configuration and tokenizer
								snake_case_		:       List[Any]           =    model.module if hasattr(_UpperCamelCase					,							'''module'''					) else model  # Only save the model itself

								# If we save using the predefined names, we can load using `from_pretrained`
								snake_case_		:       Any           =    os.path.join(args.output_dir					,							_UpperCamelCase					)
								snake_case_		:       Optional[Any]           =    os.path.join(args.output_dir					,							_UpperCamelCase					)

								torch.save(model_to_save.state_dict()					,							_UpperCamelCase					)
								model_to_save.config.to_json_file(_UpperCamelCase					)
								tokenizer.save_vocabulary(args.output_dir					)

								# Load a trained model and vocabulary that you have fine-tuned
								snake_case_		:       int           =    OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir					)
								snake_case_		:       str           =    OpenAIGPTTokenizer.from_pretrained(args.output_dir					)
								model.to(_UpperCamelCase					)

				if args.do_eval:
								model.eval()
								snake_case_     ,				snake_case_		:       str           =    0, 0
								snake_case_     ,				snake_case_		:       Any           =    0, 0
								for batch in tqdm(_UpperCamelCase					,							desc='''Evaluating'''					):
												snake_case_		:       Any           =    tuple(t.to(_UpperCamelCase					) for t in batch					)
												snake_case_     ,				snake_case_     ,				snake_case_     ,				snake_case_		:       int           =    batch
												with torch.no_grad():
																snake_case_     ,				snake_case_     ,				snake_case_     ,				snake_case_		:       Optional[int]           =    model(
																    _UpperCamelCase					,							mc_token_ids=_UpperCamelCase					,							lm_labels=_UpperCamelCase					,							mc_labels=_UpperCamelCase					)

												snake_case_		:       Optional[Any]           =    mc_logits.detach().cpu().numpy()
												snake_case_		:       List[Any]           =    mc_labels.to('''cpu'''					).numpy()
												snake_case_		:       Any           =    accuracy(_UpperCamelCase					,							_UpperCamelCase					)

												eval_loss += mc_loss.mean().item()
												eval_accuracy += tmp_eval_accuracy

												nb_eval_examples += input_ids.size(0					)
												nb_eval_steps += 1

								snake_case_		:       Any           =    eval_loss / nb_eval_steps
								snake_case_		:       Optional[int]           =    eval_accuracy / nb_eval_examples
								snake_case_		:       int           =    tr_loss / nb_tr_steps if args.do_train else None
								snake_case_		:       Optional[Any]           =    {'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

								snake_case_		:       List[str]           =    os.path.join(args.output_dir					,							'''eval_results.txt'''					)
								with open(_UpperCamelCase					,							'''w'''					) as writer:
												logger.info('''***** Eval results *****'''					)
												for key in sorted(result.keys()					):
																logger.info('''  %s = %s'''					,							_UpperCamelCase					,							str(result[key]					)					)
																writer.write('''%s = %s\n''' % (key, str(result[key]					))					)


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       )




