





"""simple docstring"""




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
   from PIL import Image

   from transformers import AutoImageProcessor

class  _UpperCAmelCase  :



      '''simple docstring'''

      def __init__(     self					,      snake_case_					,      snake_case_=3					,      snake_case_=3_2					,      snake_case_=3					,      snake_case_=1_0					,      snake_case_=[1_0, 2_0, 3_0, 4_0]					,      snake_case_=[1, 1, 2, 1]					,      snake_case_=True					,      snake_case_=True					,      snake_case_="relu"					,      snake_case_=3					,      snake_case_=None					,      ):

        """simple docstring"""

        A_  :       Any										=  parent
        A_  :       Union[str, Any]										=  batch_size
        A_  :       List[str]										=  image_size
        A_  :       Dict										=  num_channels
        A_  :       List[str]										=  embeddings_size
        A_  :       List[Any]										=  hidden_sizes
        A_  :       List[Any]										=  depths
        A_  :       Dict										=  is_training
        A_  :       Union[str, Any]										=  use_labels
        A_  :       Union[str, Any]										=  hidden_act
        A_  :       List[str]										=  num_labels
        A_  :       List[str]										=  scope
        A_  :       Any										=  len(__snake_case  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

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

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

        A_  :       Dict										=  self.get_config()
        return config, pixel_values, labels

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return RegNetConfig(
            num_channels=self.num_channels					,      embeddings_size=self.embeddings_size					,      hidden_sizes=self.hidden_sizes					,      depths=self.depths					,      hidden_act=self.hidden_act					,      num_labels=self.num_labels					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       Dict										=  TFRegNetModel(config=__snake_case  )
        A_  :       int										=  model(__snake_case					,      training=__snake_case  )
        # expected last hidden states: B, C, H // 32, W // 32
        self.parent.assertEqual(
            result.last_hidden_state.shape					,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)					,      )

      def 					lowerCamelCase_			(     self					,      snake_case_					,      snake_case_					,      snake_case_  ):

        """simple docstring"""

        A_  :       List[str]										=  self.num_labels
        A_  :       int										=  TFRegNetForImageClassification(__snake_case  )
        A_  :       Union[str, Any]										=  model(__snake_case					,      labels=__snake_case					,      training=__snake_case  )
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.num_labels)  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

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


@require_tf
class  _UpperCAmelCase  (   lowerCAmelCase_			,   lowerCAmelCase_			,   unittest.TestCase		):



      '''simple docstring'''
      lowercase_      : Tuple	    =   (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
      lowercase_      : Optional[int]	    =   (
          {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
          if is_tf_available()
          else {}
      )

      lowercase_      : Union[str, Any]	    =   False
      lowercase_      : Dict	    =   False
      lowercase_      : Tuple	    =   False
      lowercase_      : List[str]	    =   False
      lowercase_      : str	    =   False

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Tuple										=  TFRegNetModelTester(self  )
        A_  :       Union[str, Any]										=  ConfigTester(self					,      config_class=__snake_case					,      has_text_modality=__snake_case  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return

      @unittest.skip(reason='RegNet does not use inputs_embeds'  )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('GPU'  )  ) == 0					,      reason='TF does not support backprop for grouped convolutions on CPU.'					,      )
      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        super().test_keras_fit()

      @unittest.skip(reason='RegNet does not support input and output embeddings'  )
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        pass

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

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

        for model_class in self.all_model_classes:
          A_  :       Optional[Any]										=  model_class(__snake_case  )
          A_  :       Optional[Any]										=  inspect.signature(model.call  )
          # signature.parameters is an OrderedDict => so arg_names order is deterministic
          A_  :       Any										=  [*signature.parameters.keys()]

          A_  :       List[str]										=  ['pixel_values']
          self.assertListEqual(arg_names[:1]					,      __snake_case  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       List[Any]										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__snake_case  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        def check_hidden_states_output(snake_case_					,      snake_case_					,      snake_case_  ):
          A_  :       Optional[Any]										=  model_class(__snake_case  )
          A_  :       Union[str, Any]										=  model(**self._prepare_for_class(__snake_case					,      __snake_case  )					,      training=__snake_case  )

          A_  :       List[Any]										=  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          A_  :       Tuple										=  self.model_tester.num_stages
          self.assertEqual(len(__snake_case  )					,      expected_num_stages + 1  )

          # RegNet'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 // 2, self.model_tester.image_size // 2]					,      )

        A_						,       A_  :       str										=  self.model_tester.prepare_config_and_inputs_for_common()
        A_  :       Union[str, Any]										=  ['basic', 'bottleneck']
        for model_class in self.all_model_classes:
          for layer_type in layers_type:
            A_  :       List[str]										=  layer_type
            A_  :       Any										=  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_  :       Any										=  True

            check_hidden_states_output(__snake_case					,      __snake_case					,      __snake_case  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_						,       A_  :       List[Any]										=  self.model_tester.prepare_config_and_inputs_for_common()

        def check_equivalence(snake_case_					,      snake_case_					,      snake_case_					,      snake_case_={}  ):
          A_  :       Optional[int]										=  model(__snake_case					,      return_dict=__snake_case					,      **__snake_case  )
          A_  :       Tuple										=  model(__snake_case					,      return_dict=__snake_case					,      **__snake_case  ).to_tuple()

          def recursive_check(snake_case_					,      snake_case_  ):
            if isinstance(__snake_case					,      (List, Tuple)  ):
              for tuple_iterable_value, dict_iterable_value in zip(__snake_case					,      __snake_case  ):
                recursive_check(__snake_case					,      __snake_case  )
            elif tuple_object is None:
              return
            else:
              self.assertTrue(
                  all(tf.equal(__snake_case					,      __snake_case  )  )					,      msg=(
                      'Tuple and dict output are not equal. Difference:'
                      F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object  )  )}"""
                  )					,      )

            recursive_check(__snake_case					,      __snake_case  )

        for model_class in self.all_model_classes:
          A_  :       Tuple										=  model_class(__snake_case  )

          A_  :       int										=  self._prepare_for_class(__snake_case					,      __snake_case  )
          A_  :       Dict										=  self._prepare_for_class(__snake_case					,      __snake_case  )
          check_equivalence(__snake_case					,      __snake_case					,      __snake_case  )

          A_  :       List[Any]										=  self._prepare_for_class(__snake_case					,      __snake_case					,      return_labels=__snake_case  )
          A_  :       Any										=  self._prepare_for_class(__snake_case					,      __snake_case					,      return_labels=__snake_case  )
          check_equivalence(__snake_case					,      __snake_case					,      __snake_case  )

          A_  :       Any										=  self._prepare_for_class(__snake_case					,      __snake_case  )
          A_  :       str										=  self._prepare_for_class(__snake_case					,      __snake_case  )
          check_equivalence(__snake_case					,      __snake_case					,      __snake_case					,      {'output_hidden_states': True}  )

          A_  :       List[str]										=  self._prepare_for_class(__snake_case					,      __snake_case					,      return_labels=__snake_case  )
          A_  :       Any										=  self._prepare_for_class(__snake_case					,      __snake_case					,      return_labels=__snake_case  )
          check_equivalence(__snake_case					,      __snake_case					,      __snake_case					,      {'output_hidden_states': True}  )

      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__snake_case  )

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          A_  :       Optional[int]										=  TFRegNetModel.from_pretrained(__snake_case  )
          self.assertIsNotNone(__snake_case  )





def 						UpperCAmelCase__		(     ):






  """simple docstring"""





  A_  :       Optional[Any]										=  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
  return image





@require_tf
@require_vision
class  _UpperCAmelCase  (   unittest.TestCase		):



      '''simple docstring'''

      @cached_property
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        return (
            AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )
            if is_vision_available()
            else None
        )

      @slow
      def 					lowerCamelCase_			(     self  ):

        """simple docstring"""

        A_  :       Union[str, Any]										=  TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

        A_  :       List[str]										=  self.default_image_processor
        A_  :       Tuple										=  prepare_img()
        A_  :       Dict										=  image_processor(images=__snake_case					,      return_tensors='tf'  )

        # forward pass
        A_  :       Optional[int]										=  model(**__snake_case					,      training=__snake_case  )

        # verify the logits
        A_  :       Union[str, Any]										=  tf.TensorShape((1, 1_0_0_0)  )
        self.assertEqual(outputs.logits.shape					,      __snake_case  )

        A_  :       Any										=  tf.constant([-0.41_80, -1.50_51, -3.48_36]  )

        tf.debugging.assert_near(outputs.logits[0, :3]					,      __snake_case					,      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
)
_lowerCAmelCase					:			List[Any]  				=			logging.getLogger(__name__)






def        UpperCamelCase_(							_snake_case   :  Optional[Any]       ,     _snake_case   :  Any	):




			"""simple docstring"""






			__a        =np.argmax(_snake_case       ,     axis=1	)
			return np.sum(outputs == labels	)






def        UpperCamelCase_(							_snake_case   :  List[str]	):




			"""simple docstring"""






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






def        UpperCamelCase_(							_snake_case   :  Union[str, Any]       ,     _snake_case   :  Any       ,     _snake_case   :  Dict       ,     _snake_case   :  Any       ,     _snake_case   :  Union[str, Any]       ,     _snake_case   :  Tuple	):




			"""simple docstring"""






			__a        =[]
			for dataset in encoded_datasets:
						__a        =len(_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(_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(_snake_case	) - 1
									__a        =len(_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(_snake_case	) for t in all_inputs	)	)
			return tensor_datasets






def        UpperCamelCase_(							):




			"""simple docstring"""






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

			parser.add_argument('--server_ip'       ,     type=_snake_case       ,     default=''       ,     help='Can be used for distant debugging.'	)
			parser.add_argument('--server_port'       ,     type=_snake_case       ,     default=''       ,     help='Can be used for distant debugging.'	)
			__a        =parser.parse_args()
			print(_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=_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(_snake_case       ,     _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(_snake_case	)
			__a        =tokenizer.convert_tokens_to_ids(_snake_case	)
			__a        =OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name	)
			model.resize_token_embeddings(len(_snake_case	)	)
			model.to(_snake_case	)

			# Load and encode the datasets
			def tokenize_and_encode(_snake_case   :  int	):
						if isinstance(_snake_case       ,     _snake_case	):
									return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_snake_case	)	)
						elif isinstance(_snake_case       ,     _snake_case	):
									return obj
						return [tokenize_and_encode(_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(_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(_snake_case       ,     model.config.n_positions	)  # Max size of input for the pre-trained model

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

			__a        =TensorDataset(*_snake_case	)
			__a        =RandomSampler(_snake_case	)
			__a        =DataLoader(_snake_case       ,     sampler=_snake_case       ,     batch_size=args.train_batch_size	)

			__a        =TensorDataset(*_snake_case	)
			__a        =SequentialSampler(_snake_case	)
			__a        =DataLoader(_snake_case       ,     sampler=_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(_snake_case	) // args.gradient_accumulation_steps) + 1
						else:
									__a        =len(_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(_snake_case       ,     lr=args.learning_rate       ,     eps=args.adam_epsilon	)
						__a        =get_linear_schedule_with_warmup(
						    _snake_case       ,     num_warmup_steps=args.warmup_steps       ,     num_training_steps=_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(_snake_case       ,     desc='Training'	)
									for step, batch in enumerate(_snake_case	):
												__a        =tuple(t.to(_snake_case	) for t in batch	)
												__a      ,    __a      ,    __a      ,    __a        =batch
												__a        =model(_snake_case       ,     mc_token_ids=_snake_case       ,     lm_labels=_snake_case       ,     mc_labels=_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(_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(_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       ,     _snake_case	)
						__a        =os.path.join(args.output_dir       ,     _snake_case	)

						torch.save(model_to_save.state_dict()       ,     _snake_case	)
						model_to_save.config.to_json_file(_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(_snake_case	)

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

									__a        =mc_logits.detach().cpu().numpy()
									__a        =mc_labels.to('cpu'	).numpy()
									__a        =accuracy(_snake_case       ,     _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(_snake_case       ,     'w'	) as writer:
									logger.info('***** Eval results *****'	)
									for key in sorted(result.keys()	):
												logger.info('  %s = %s'       ,     _snake_case       ,     str(result[key]	)	)
												writer.write('%s = %s\n' % (key, str(result[key]	))	)


if __name__ == "__main__":
						main()






