import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, 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 CvtForImageClassification, CvtModel
	from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor





class UpperCAmelCase		(   __A    ):


				'''simple docstring'''






				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Union[str, Any]      = self.config_class(**self.inputs_dict   )
						self.parent.assertTrue(hasattr(lowercase						,      'embed_dim'   )   )
						self.parent.assertTrue(hasattr(lowercase						,      'num_heads'   )   )





class UpperCAmelCase		:


				'''simple docstring'''






				def __init__(		self						,      lowercase						,      lowercase=1_3						,      lowercase=6_4						,      lowercase=3						,      lowercase=[1_6, 4_8, 9_6]						,      lowercase=[1, 3, 6]						,      lowercase=[1, 2, 1_0]						,      lowercase=[7, 3, 3]						,      lowercase=[4, 2, 2]						,      lowercase=[2, 1, 1]						,      lowercase=[2, 2, 2]						,      lowercase=[False, False, True]						,      lowercase=[0.0, 0.0, 0.0]						,      lowercase=0.02						,      lowercase=1E-12						,      lowercase=True						,      lowercase=True						,      lowercase=2						,      ):



						"""simple docstring"""





						A_						:							Optional[int]      = parent
						A_						:							Optional[Any]      = batch_size
						A_						:							int      = image_size
						A_						:							Union[str, Any]      = patch_sizes
						A_						:							Optional[int]      = patch_stride
						A_						:							str      = patch_padding
						A_						:							List[Any]      = is_training
						A_						:							str      = use_labels
						A_						:							Any      = num_labels
						A_						:							Optional[int]      = num_channels
						A_						:							int      = embed_dim
						A_						:							str      = num_heads
						A_						:							List[str]      = stride_kv
						A_						:							Optional[Any]      = depth
						A_						:							List[str]      = cls_token
						A_						:							Optional[Any]      = attention_drop_rate
						A_						:							Optional[int]      = initializer_range
						A_						:							str      = layer_norm_eps
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[int]      = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

						A_						:							List[str]      = None
						if self.use_labels:
								A_						:							Union[str, Any]      = ids_tensor([self.batch_size]						,      self.num_labels   )

						A_						:							Union[str, Any]      = self.get_config()
						return config, pixel_values, labels
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						return CvtConfig(
						    image_size=self.image_size						,      num_labels=self.num_labels						,      num_channels=self.num_channels						,      embed_dim=self.embed_dim						,      num_heads=self.num_heads						,      patch_sizes=self.patch_sizes						,      patch_padding=self.patch_padding						,      patch_stride=self.patch_stride						,      stride_kv=self.stride_kv						,      depth=self.depth						,      cls_token=self.cls_token						,      attention_drop_rate=self.attention_drop_rate						,      initializer_range=self.initializer_range						,      )
				def     lowerCAmelCase_  (		self						,      lowercase						,      lowercase						,      lowercase   ):



						"""simple docstring"""





						A_						:							Tuple      = CvtModel(config=lowercase   )
						model.to(lowercase   )
						model.eval()
						A_						:							Tuple      = model(lowercase   )
						A_						:							Any      = (self.image_size, self.image_size)
						A_  ,     A_						:							List[str]      = image_size[0], image_size[1]
						for i in range(len(self.depth   )   ):
								A_						:							int      = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
								A_						:							Any      = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1   )
						self.parent.assertEqual(result.last_hidden_state.shape						,      (self.batch_size, self.embed_dim[-1], height, width)   )
				def     lowerCAmelCase_  (		self						,      lowercase						,      lowercase						,      lowercase   ):



						"""simple docstring"""





						A_						:							Optional[Any]      = self.num_labels
						A_						:							Any      = CvtForImageClassification(lowercase   )
						model.to(lowercase   )
						model.eval()
						A_						:							List[Any]      = model(lowercase						,      labels=lowercase   )
						self.parent.assertEqual(result.logits.shape						,      (self.batch_size, self.num_labels)   )







				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Any      = self.prepare_config_and_inputs()
						A_  ,     A_  ,     A_						:							Union[str, Any]      = config_and_inputs
						A_						:							Tuple      = {'pixel_values': pixel_values}
						return config, inputs_dict





@require_torch
class UpperCAmelCase		(   __A   ,			__A   ,			unittest.TestCase    ):


				'''simple docstring'''






				lowerCamelCase_        =   (CvtModel, CvtForImageClassification) if is_torch_available() else ()
				lowerCamelCase_        =   (
				    {'''feature-extraction''': CvtModel, '''image-classification''': CvtForImageClassification}
				    if is_torch_available()
				    else {}
				)

				lowerCamelCase_        =   False
				lowerCamelCase_        =   False
				lowerCamelCase_        =   False
				lowerCamelCase_        =   False
				lowerCamelCase_        =   False
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Tuple      = CvtModelTester(self   )
						A_						:							Optional[int]      = ConfigTester(self						,      config_class=lowercase						,      has_text_modality=lowercase						,      hidden_size=3_7   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						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     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						return
				@unittest.skip(reason='Cvt does not output attentions'   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						pass
				@unittest.skip(reason='Cvt does not use inputs_embeds'   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						pass
				@unittest.skip(reason='Cvt does not support input and output embeddings'   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						pass
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





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

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

								A_						:							List[Any]      = ['pixel_values']
								self.assertListEqual(arg_names[:1]						,      lowercase   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[Any]      = self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowercase   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						def check_hidden_states_output(lowercase						,      lowercase						,      lowercase   ):
								A_						:							Optional[int]      = model_class(lowercase   )
								model.to(lowercase   )
								model.eval()

								with torch.no_grad():
										A_						:							Union[str, Any]      = model(**self._prepare_for_class(lowercase						,      lowercase   )   )

								A_						:							Optional[int]      = outputs.hidden_states

								A_						:							Dict      = len(self.model_tester.depth   )
								self.assertEqual(len(lowercase   )						,      lowercase   )

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

						A_  ,     A_						:							str      = self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
								A_						:							Union[str, Any]      = True
								check_hidden_states_output(lowercase						,      lowercase						,      lowercase   )

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

								check_hidden_states_output(lowercase						,      lowercase						,      lowercase   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							List[str]      = self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowercase   )
				@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						pass







				@slow
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								A_						:							Union[str, Any]      = CvtModel.from_pretrained(lowercase   )
								self.assertIsNotNone(lowercase   )




def 							UpperCamelCase		(			):
		'''simple docstring'''




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





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


				'''simple docstring'''






				@cached_property
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )







				@slow
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[int]      = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(lowercase   )

						A_						:							List[str]      = self.default_image_processor
						A_						:							Any      = prepare_img()
						A_						:							Optional[int]      = image_processor(images=lowercase						,      return_tensors='pt'   ).to(lowercase   )

						# forward pass
						with torch.no_grad():
								A_						:							Union[str, Any]      = model(**lowercase   )

						# verify the logits
						A_						:							Optional[Any]      = torch.Size((1, 1_0_0_0)   )
						self.assertEqual(outputs.logits.shape						,      lowercase   )

						A_						:							Optional[int]      = torch.tensor([0.9285, 0.9015, -0.3150]   ).to(lowercase   )

						self.assertTrue(torch.allclose(outputs.logits[0, :3]						,      lowercase						,      atol=1E-4   )   )







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
)
_UpperCAmelCase          =						logging.getLogger(__name__)




def 							UpperCamelCase		(			__lowercase		:					Any		,__lowercase		:					List[str]      ):
		'''simple docstring'''




		A_						:							str      = np.argmax(__lowercase		,axis=1      )
		return np.sum(outputs == labels      )




def 							UpperCamelCase		(			__lowercase		:					Optional[int]      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			__lowercase		:					str		,__lowercase		:					str		,__lowercase		:					int		,__lowercase		:					str		,__lowercase		:					Optional[Any]		,__lowercase		:					List[Any]      ):
		'''simple docstring'''




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




def 							UpperCamelCase		(			):
		'''simple docstring'''




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

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

		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=__lowercase      )
				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_						:							Tuple      = torch.device('cuda' if torch.cuda.is_available() else 'cpu'      )
		A_						:							Dict      = torch.cuda.device_count()
		logger.info('device: {}, n_gpu {}'.format(__lowercase		,__lowercase      )      )

		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_						:							Tuple      = ['_start_', '_delimiter_', '_classify_']
		A_						:							Optional[int]      = OpenAIGPTTokenizer.from_pretrained(args.model_name      )
		tokenizer.add_tokens(__lowercase      )
		A_						:							Any      = tokenizer.convert_tokens_to_ids(__lowercase      )
		A_						:							Tuple      = OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name      )
		model.resize_token_embeddings(len(__lowercase      )      )
		model.to(__lowercase      )

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

		logger.info('Encoding dataset...'      )
		A_						:							Any      = load_rocstories_dataset(args.train_dataset      )
		A_						:							Any      = load_rocstories_dataset(args.eval_dataset      )
		A_						:							Dict      = (train_dataset, eval_dataset)
		A_						:							str      = tokenize_and_encode(__lowercase      )

		# Compute the max input length for the Transformer
		A_						:							Tuple      = model.config.n_positions // 2 - 2
		A_						:							Optional[Any]      = 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_						:							str      = min(__lowercase		,model.config.n_positions      )  # Max size of input for the pre-trained model

		# Prepare inputs tensors and dataloaders
		A_						:							List[str]      = pre_process_datasets(__lowercase		,__lowercase		,__lowercase		,*__lowercase      )
		A_  ,     A_						:							List[str]      = tensor_datasets[0], tensor_datasets[1]

		A_						:							str      = TensorDataset(*__lowercase      )
		A_						:							Optional[Any]      = RandomSampler(__lowercase      )
		A_						:							Optional[int]      = DataLoader(__lowercase		,sampler=__lowercase		,batch_size=args.train_batch_size      )

		A_						:							Optional[Any]      = TensorDataset(*__lowercase      )
		A_						:							Union[str, Any]      = SequentialSampler(__lowercase      )
		A_						:							List[str]      = DataLoader(__lowercase		,sampler=__lowercase		,batch_size=args.eval_batch_size      )

		# Prepare optimizer
		if args.do_train:
				if args.max_steps > 0:
						A_						:							List[Any]      = args.max_steps
						A_						:							List[str]      = args.max_steps // (len(__lowercase      ) // args.gradient_accumulation_steps) + 1
				else:
						A_						:							int      = len(__lowercase      ) // args.gradient_accumulation_steps * args.num_train_epochs

				A_						:							List[Any]      = list(model.named_parameters()      )
				A_						:							int      = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
				A_						:							Optional[int]      = [
				    {
				        '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_						:							int      = AdamW(__lowercase		,lr=args.learning_rate		,eps=args.adam_epsilon      )
				A_						:							str      = get_linear_schedule_with_warmup(
				    __lowercase		,num_warmup_steps=args.warmup_steps		,num_training_steps=__lowercase      )

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

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

				# If we save using the predefined names, we can load using `from_pretrained`
				A_						:							Tuple      = os.path.join(args.output_dir		,__lowercase      )
				A_						:							str      = os.path.join(args.output_dir		,__lowercase      )

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

				# Load a trained model and vocabulary that you have fine-tuned
				A_						:							Optional[int]      = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir      )
				A_						:							List[str]      = OpenAIGPTTokenizer.from_pretrained(args.output_dir      )
				model.to(__lowercase      )

		if args.do_eval:
				model.eval()
				A_  ,     A_						:							List[str]      = 0, 0
				A_  ,     A_						:							Dict      = 0, 0
				for batch in tqdm(__lowercase		,desc='Evaluating'      ):
						A_						:							List[str]      = tuple(t.to(__lowercase      ) for t in batch      )
						A_  ,     A_  ,     A_  ,     A_						:							Tuple      = batch
						with torch.no_grad():
								A_  ,     A_  ,     A_  ,     A_						:							List[str]      = model(
								    __lowercase		,mc_token_ids=__lowercase		,lm_labels=__lowercase		,mc_labels=__lowercase      )

						A_						:							str      = mc_logits.detach().cpu().numpy()
						A_						:							Optional[int]      = mc_labels.to('cpu'      ).numpy()
						A_						:							int      = accuracy(__lowercase		,__lowercase      )

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

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

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

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


if __name__ == "__main__":
	main()






