



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
)
a_      :      Optional[int]    =     logging.getLogger(__name__)






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase       ):
 a__												= np.argmax(SCREAMING_SNAKE_CASE_							,  axis=1       )
 return np.sum(outputs == labels       )






def     __a					(		__UpperCAmelCase       ):
 with open(SCREAMING_SNAKE_CASE_							,  encoding='''utf_8'''       ) as f:
  a__												= csv.reader(SCREAMING_SNAKE_CASE_       )
  a__												= []
  next(SCREAMING_SNAKE_CASE_       )  # skip the first line
  for line in tqdm(SCREAMING_SNAKE_CASE_       ):
   output.append((''' '''.join(line[1:5]       ), line[5], line[6], int(line[-1]       ) - 1)       )
 return output






def     __a					(		__UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase							,  __UpperCAmelCase       ):
 a__												= []
 for dataset in encoded_datasets:
  a__												= len(SCREAMING_SNAKE_CASE_       )
  a__												= np.zeros((n_batch, 2, input_len)							,  dtype=np.intaa       )
  a__												= np.zeros((n_batch, 2)							,  dtype=np.intaa       )
  a__												= np.full((n_batch, 2, input_len)							,  fill_value=-100							,  dtype=np.intaa       )
  a__												= np.zeros((n_batch,)							,  dtype=np.intaa       )
  for (
      i,
      (story, conta, conta, mc_label),
  ) in enumerate(SCREAMING_SNAKE_CASE_       ):
   a__												= [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
   a__												= [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
   a__												= with_conta
   a__												= with_conta
   a__												= len(SCREAMING_SNAKE_CASE_       ) - 1
   a__												= len(SCREAMING_SNAKE_CASE_       ) - 1
   a__												= with_conta
   a__												= with_conta
   a__												= mc_label
  a__												= (input_ids, mc_token_ids, lm_labels, mc_labels)
  tensor_datasets.append(tuple(torch.tensor(SCREAMING_SNAKE_CASE_       ) for t in all_inputs       )       )
 return tensor_datasets






def     __a					(		):
 a__												= argparse.ArgumentParser()
 parser.add_argument('''--model_name'''							,  type=SCREAMING_SNAKE_CASE_							,  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=SCREAMING_SNAKE_CASE_							,  type=SCREAMING_SNAKE_CASE_							,  required=SCREAMING_SNAKE_CASE_							,  help='''The output directory where the model predictions and checkpoints will be written.'''							,  )
 parser.add_argument('''--train_dataset'''							,  type=SCREAMING_SNAKE_CASE_							,  default=''''''       )
 parser.add_argument('''--eval_dataset'''							,  type=SCREAMING_SNAKE_CASE_							,  default=''''''       )
 parser.add_argument('''--seed'''							,  type=SCREAMING_SNAKE_CASE_							,  default=42       )
 parser.add_argument('''--num_train_epochs'''							,  type=SCREAMING_SNAKE_CASE_							,  default=3       )
 parser.add_argument('''--train_batch_size'''							,  type=SCREAMING_SNAKE_CASE_							,  default=8       )
 parser.add_argument('''--eval_batch_size'''							,  type=SCREAMING_SNAKE_CASE_							,  default=16       )
 parser.add_argument('''--adam_epsilon'''							,  default=1e-8							,  type=SCREAMING_SNAKE_CASE_							,  help='''Epsilon for Adam optimizer.'''       )
 parser.add_argument('''--max_grad_norm'''							,  type=SCREAMING_SNAKE_CASE_							,  default=1       )
 parser.add_argument(
     '''--max_steps'''							,  default=-1							,  type=SCREAMING_SNAKE_CASE_							,  help=(
         '''If > 0: set total number of training                         steps to perform. Override num_train_epochs.'''
     )							,  )
 parser.add_argument(
     '''--gradient_accumulation_steps'''							,  type=SCREAMING_SNAKE_CASE_							,  default=1							,  help='''Number of updates steps to accumulate before                        performing a backward/update pass.'''							,  )
 parser.add_argument('''--learning_rate'''							,  type=SCREAMING_SNAKE_CASE_							,  default=6.25e-5       )
 parser.add_argument('''--warmup_steps'''							,  default=0							,  type=SCREAMING_SNAKE_CASE_							,  help='''Linear warmup over warmup_steps.'''       )
 parser.add_argument('''--lr_schedule'''							,  type=SCREAMING_SNAKE_CASE_							,  default='''warmup_linear'''       )
 parser.add_argument('''--weight_decay'''							,  type=SCREAMING_SNAKE_CASE_							,  default=0.01       )
 parser.add_argument('''--lm_coef'''							,  type=SCREAMING_SNAKE_CASE_							,  default=0.9       )
 parser.add_argument('''--n_valid'''							,  type=SCREAMING_SNAKE_CASE_							,  default=374       )

 parser.add_argument('''--server_ip'''							,  type=SCREAMING_SNAKE_CASE_							,  default=''''''							,  help='''Can be used for distant debugging.'''       )
 parser.add_argument('''--server_port'''							,  type=SCREAMING_SNAKE_CASE_							,  default=''''''							,  help='''Can be used for distant debugging.'''       )
 a__												= parser.parse_args()
 print(SCREAMING_SNAKE_CASE_       )

 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=SCREAMING_SNAKE_CASE_       )
  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       )

 a__												= torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''       )
 a__												= torch.cuda.device_count()
 logger.info('''device: {}, n_gpu {}'''.format(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_       )       )

 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
 a__												= ['''_start_''', '''_delimiter_''', '''_classify_''']
 a__												= OpenAIGPTTokenizer.from_pretrained(args.model_name       )
 tokenizer.add_tokens(SCREAMING_SNAKE_CASE_       )
 a__												= tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE_       )
 a__												= OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name       )
 model.resize_token_embeddings(len(SCREAMING_SNAKE_CASE_       )       )
 model.to(SCREAMING_SNAKE_CASE_       )

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

 logger.info('''Encoding dataset...'''       )
 a__												= load_rocstories_dataset(args.train_dataset       )
 a__												= load_rocstories_dataset(args.eval_dataset       )
 a__												= (train_dataset, eval_dataset)
 a__												= tokenize_and_encode(SCREAMING_SNAKE_CASE_       )

 # Compute the max input length for the Transformer
 a__												= model.config.n_positions // 2 - 2
 a__												= 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       )
 a__												= min(SCREAMING_SNAKE_CASE_							,  model.config.n_positions       )  # Max size of input for the pre-trained model

 # Prepare inputs tensors and dataloaders
 a__												= pre_process_datasets(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_							,  *SCREAMING_SNAKE_CASE_       )
 a__							,			a__												= tensor_datasets[0], tensor_datasets[1]

 a__												= TensorDataset(*SCREAMING_SNAKE_CASE_       )
 a__												= RandomSampler(SCREAMING_SNAKE_CASE_       )
 a__												= DataLoader(SCREAMING_SNAKE_CASE_							,  sampler=SCREAMING_SNAKE_CASE_							,  batch_size=args.train_batch_size       )

 a__												= TensorDataset(*SCREAMING_SNAKE_CASE_       )
 a__												= SequentialSampler(SCREAMING_SNAKE_CASE_       )
 a__												= DataLoader(SCREAMING_SNAKE_CASE_							,  sampler=SCREAMING_SNAKE_CASE_							,  batch_size=args.eval_batch_size       )

 # Prepare optimizer
 if args.do_train:
  if args.max_steps > 0:
   a__												= args.max_steps
   a__												= args.max_steps // (len(SCREAMING_SNAKE_CASE_       ) // args.gradient_accumulation_steps) + 1
  else:
   a__												= len(SCREAMING_SNAKE_CASE_       ) // args.gradient_accumulation_steps * args.num_train_epochs

  a__												= list(model.named_parameters()       )
  a__												= ['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight''']
  a__												= [
      {
          '''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},
  ]
  a__												= AdamW(SCREAMING_SNAKE_CASE_							,  lr=args.learning_rate							,  eps=args.adam_epsilon       )
  a__												= get_linear_schedule_with_warmup(
      SCREAMING_SNAKE_CASE_							,  num_warmup_steps=args.warmup_steps							,  num_training_steps=SCREAMING_SNAKE_CASE_       )

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

    # Save a trained model
 if args.do_train:
  # Save a trained model, configuration and tokenizer
  a__												= model.module if hasattr(SCREAMING_SNAKE_CASE_							,  '''module'''       ) else model  # Only save the model itself

  # If we save using the predefined names, we can load using `from_pretrained`
  a__												= os.path.join(args.output_dir							,  SCREAMING_SNAKE_CASE_       )
  a__												= os.path.join(args.output_dir							,  SCREAMING_SNAKE_CASE_       )

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

  # Load a trained model and vocabulary that you have fine-tuned
  a__												= OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir       )
  a__												= OpenAIGPTTokenizer.from_pretrained(args.output_dir       )
  model.to(SCREAMING_SNAKE_CASE_       )

 if args.do_eval:
  model.eval()
  a__							,			a__												= 0, 0
  a__							,			a__												= 0, 0
  for batch in tqdm(SCREAMING_SNAKE_CASE_							,  desc='''Evaluating'''       ):
   a__												= tuple(t.to(SCREAMING_SNAKE_CASE_       ) for t in batch       )
   a__							,			a__							,			a__							,			a__												= batch
   with torch.no_grad():
    a__							,			a__							,			a__							,			a__												= model(
        SCREAMING_SNAKE_CASE_							,  mc_token_ids=SCREAMING_SNAKE_CASE_							,  lm_labels=SCREAMING_SNAKE_CASE_							,  mc_labels=SCREAMING_SNAKE_CASE_       )

   a__												= mc_logits.detach().cpu().numpy()
   a__												= mc_labels.to('''cpu'''       ).numpy()
   a__												= accuracy(SCREAMING_SNAKE_CASE_							,  SCREAMING_SNAKE_CASE_       )

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

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

  a__												= eval_loss / nb_eval_steps
  a__												= eval_accuracy / nb_eval_examples
  a__												= tr_loss / nb_tr_steps if args.do_train else None
  a__												= {'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

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


if __name__ == "__main__":
     main()







import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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


if is_torch_available():
		import torch

		from transformers import UperNetForSemanticSegmentation
		from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor



class    a_ :






			def __init__(      self				,			__UpperCamelCase				,			__UpperCamelCase=13				,			__UpperCamelCase=32				,			__UpperCamelCase=3				,			__UpperCamelCase=4				,			__UpperCamelCase=[10, 20, 30, 40]				,			__UpperCamelCase=[2, 2, 3, 2]				,			__UpperCamelCase=True				,			__UpperCamelCase=True				,			__UpperCamelCase=37				,			__UpperCamelCase="gelu"				,			__UpperCamelCase=10				,			__UpperCamelCase=0.02				,			__UpperCamelCase=["stage2", "stage3", "stage4"]				,			__UpperCamelCase=3				,			__UpperCamelCase=None				,			):
									_lowercase					       =					parent
									_lowercase					       =					batch_size
									_lowercase					       =					image_size
									_lowercase					       =					num_channels
									_lowercase					       =					num_stages
									_lowercase					       =					hidden_sizes
									_lowercase					       =					depths
									_lowercase					       =					is_training
									_lowercase					       =					use_labels
									_lowercase					       =					intermediate_size
									_lowercase					       =					hidden_act
									_lowercase					       =					type_sequence_label_size
									_lowercase					       =					initializer_range
									_lowercase					       =					out_features
									_lowercase					       =					num_labels
									_lowercase					       =					scope
									_lowercase					       =					num_stages






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

									_lowercase					       =					None
									if self.use_labels:
															_lowercase					       =					ids_tensor([self.batch_size]				,			self.type_sequence_label_size  )

									_lowercase					       =					self.get_config()

									return config, pixel_values, labels






			def    UpperCamelCase_				(      self  ):
									return ConvNextConfig(
									    num_channels=self.num_channels				,			num_stages=self.num_stages				,			hidden_sizes=self.hidden_sizes				,			depths=self.depths				,			is_training=self.is_training				,			intermediate_size=self.intermediate_size				,			hidden_act=self.hidden_act				,			out_features=self.out_features				,			)






			def    UpperCamelCase_				(      self  ):
									return UperNetConfig(
									    backbone_config=self.get_backbone_config()				,			hidden_size=512				,			pool_scales=[1, 2, 3, 6]				,			use_auxiliary_head=__UpperCamelCase				,			auxiliary_loss_weight=0.4				,			auxiliary_in_channels=40				,			auxiliary_channels=256				,			auxiliary_num_convs=1				,			auxiliary_concat_input=__UpperCamelCase				,			loss_ignore_index=255				,			num_labels=self.num_labels				,			)






			def    UpperCamelCase_				(      self				,			__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  ):
									_lowercase					       =					UperNetForSemanticSegmentation(config=__UpperCamelCase  )
									model.to(__UpperCamelCase  )
									model.eval()
									_lowercase					       =					model(__UpperCamelCase  )
									self.parent.assertEqual(
									    result.logits.shape				,			(self.batch_size, self.num_labels, self.image_size, self.image_size)  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.prepare_config_and_inputs()
									(
									    (
									    _lowercase
									)       ,						(
									    _lowercase
									)       ,						(
									    _lowercase
									)       ,						
									)					       =					config_and_inputs
									_lowercase					       =					{"""pixel_values""": pixel_values}
									return config, inputs_dict







@require_torch
class    a_ (			_a					,			_a					,			unittest.TestCase    ):
			a	:			Optional[int]					   =							(UperNetForSemanticSegmentation,) if is_torch_available() else ()
			a	:			Optional[Any]					   =							{'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
			a	:			Any					   =							False
			a	:			Union[str, Any]					   =							False
			a	:			Optional[Any]					   =							False
			a	:			int					   =							False
			a	:			Optional[int]					   =							False
			a	:			List[str]					   =							False






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					UperNetModelTester(self  )
									_lowercase					       =					ConfigTester(self				,			config_class=__UpperCamelCase				,			has_text_modality=__UpperCamelCase				,			hidden_size=37  )






			def    UpperCamelCase_				(      self  ):
									self.create_and_test_config_common_properties()
									self.config_tester.create_and_test_config_to_json_string()
									self.config_tester.create_and_test_config_to_json_file()
									self.config_tester.create_and_test_config_from_and_save_pretrained()
									self.config_tester.create_and_test_config_with_num_labels()
									self.config_tester.check_config_can_be_init_without_params()
									self.config_tester.check_config_arguments_init()






			def    UpperCamelCase_				(      self  ):
									return






			def    UpperCamelCase_				(      self  ):
									_lowercase       ,						_lowercase					       =					self.model_tester.prepare_config_and_inputs_for_common()

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

															_lowercase					       =					["""pixel_values"""]
															self.assertListEqual(arg_names[:1]				,			__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase  )






			@unittest.skip(reason="""UperNet does not use inputs_embeds"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@unittest.skip(reason="""UperNet does not support input and output embeddings"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@unittest.skip(reason="""UperNet does not have a base model"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@unittest.skip(reason="""UperNet does not have a base model"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@require_torch_multi_gpu
			@unittest.skip(reason="""UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""  )
			def    UpperCamelCase_				(      self  ):
									pass






			def    UpperCamelCase_				(      self  ):
									def check_hidden_states_output(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  ):
															_lowercase					       =					model_class(__UpperCamelCase  )
															model.to(__UpperCamelCase  )
															model.eval()

															with torch.no_grad():
																					_lowercase					       =					model(**self._prepare_for_class(__UpperCamelCase				,			__UpperCamelCase  )  )

															_lowercase					       =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															_lowercase					       =					self.model_tester.num_stages
															self.assertEqual(len(__UpperCamelCase  )				,			expected_num_stages + 1  )

															# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
															self.assertListEqual(
															    list(hidden_states[0].shape[-2:]  )				,			[self.model_tester.image_size // 4, self.model_tester.image_size // 4]				,			)

									_lowercase       ,						_lowercase					       =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															_lowercase					       =					True
															check_hidden_states_output(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  )

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

															check_hidden_states_output(__UpperCamelCase				,			__UpperCamelCase				,			__UpperCamelCase  )






			def    UpperCamelCase_				(      self  ):
									_lowercase       ,						_lowercase					       =					self.model_tester.prepare_config_and_inputs_for_common()

									_lowercase					       =					_config_zero_init(__UpperCamelCase  )
									_lowercase					       =					_config_zero_init(configs_no_init.backbone_config  )
									for model_class in self.all_model_classes:
															_lowercase					       =					model_class(config=__UpperCamelCase  )
															for name, param in model.named_parameters():
																					if param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1E9).round() / 1E9).item()				,			[0.0, 1.0]				,			msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""				,			)






			@unittest.skip(reason="""UperNet does not have tied weights"""  )
			def    UpperCamelCase_				(      self  ):
									pass






			@slow
			def    UpperCamelCase_				(      self  ):
									for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained(__UpperCamelCase  )
															self.assertIsNotNone(__UpperCamelCase  )







def 	UpperCamelCase__  (     )  ->     str:
						_lowercase					       =					hf_hub_download(
						    repo_id="""hf-internal-testing/fixtures_ade20k"""		,   repo_type="""dataset"""		,   filename="""ADE_val_00000001.jpg"""       )
						_lowercase					       =					Image.open(SCREAMING_SNAKE_CASE_       ).convert("""RGB"""       )
						return image



@require_torch
@require_vision
@slow
class    a_ (			unittest.TestCase    ):






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""  )
									_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""  ).to(__UpperCamelCase  )

									_lowercase					       =					prepare_img()
									_lowercase					       =					processor(images=__UpperCamelCase				,			return_tensors="""pt"""  ).to(__UpperCamelCase  )

									with torch.no_grad():
															_lowercase					       =					model(**__UpperCamelCase  )

									_lowercase					       =					torch.Size((1, model.config.num_labels, 512, 512)  )
									self.assertEqual(outputs.logits.shape				,			__UpperCamelCase  )

									_lowercase					       =					torch.tensor(
									    [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]  ).to(__UpperCamelCase  )
									self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,			__UpperCamelCase				,			atol=1E-4  )  )






			def    UpperCamelCase_				(      self  ):
									_lowercase					       =					AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""  )
									_lowercase					       =					UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""  ).to(__UpperCamelCase  )

									_lowercase					       =					prepare_img()
									_lowercase					       =					processor(images=__UpperCamelCase				,			return_tensors="""pt"""  ).to(__UpperCamelCase  )

									with torch.no_grad():
															_lowercase					       =					model(**__UpperCamelCase  )

									_lowercase					       =					torch.Size((1, model.config.num_labels, 512, 512)  )
									self.assertEqual(outputs.logits.shape				,			__UpperCamelCase  )

									_lowercase					       =					torch.tensor(
									    [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]  ).to(__UpperCamelCase  )
									self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]				,			__UpperCamelCase				,			atol=1E-4  )  )