




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
)
lowercase__ :     Union[str, Any]			       =   logging.getLogger(__name__)

def    SCREAMING_SNAKE_CASE				(  __UpperCamelCase						,   __UpperCamelCase)     ->	List[Any]:
     a           = np.argmax(UpperCAmelCase__						,   axis=1)
     return np.sum(outputs == labels)

def    SCREAMING_SNAKE_CASE				(  __UpperCamelCase)     ->	Any:
     with open(UpperCAmelCase__						,   encoding="utf_8") as f:
          a           = csv.reader(UpperCAmelCase__)
          a           = []
          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    SCREAMING_SNAKE_CASE				(  __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase						,   __UpperCamelCase)     ->	int:
     a           = []
     for dataset in encoded_datasets:
          a           = len(UpperCAmelCase__)
          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=-1_00						,   dtype=np.intaa)
          a           = np.zeros((n_batch,)						,   dtype=np.intaa)
          for (
              i,
              (story, conta, conta, mc_label),
          ) in enumerate(UpperCAmelCase__):
               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(UpperCAmelCase__) - 1
               a           = len(UpperCAmelCase__) - 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(UpperCAmelCase__) for t in all_inputs))
     return tensor_datasets

def    SCREAMING_SNAKE_CASE				(  )     ->	Tuple:
     a           = 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=3_74)

     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.")
     a           = 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)

     a           = torch.device("cuda" if torch.cuda.is_available() else "cpu")
     a           = 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
     a           = ["_start_", "_delimiter_", "_classify_"]
     a           = OpenAIGPTTokenizer.from_pretrained(args.model_name)
     tokenizer.add_tokens(UpperCAmelCase__)
     a           = tokenizer.convert_tokens_to_ids(UpperCAmelCase__)
     a           = 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...")
     a           = load_rocstories_dataset(args.train_dataset)
     a           = load_rocstories_dataset(args.eval_dataset)
     a           = (train_dataset, eval_dataset)
     a           = tokenize_and_encode(UpperCAmelCase__)

     # 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(UpperCAmelCase__						,   model.config.n_positions)  # Max size of input for the pre-trained model

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

     a           = TensorDataset(*UpperCAmelCase__)
     a           = RandomSampler(UpperCAmelCase__)
     a           = DataLoader(UpperCAmelCase__						,   sampler=UpperCAmelCase__						,   batch_size=args.train_batch_size)

     a           = TensorDataset(*UpperCAmelCase__)
     a           = SequentialSampler(UpperCAmelCase__)
     a           = DataLoader(UpperCAmelCase__						,   sampler=UpperCAmelCase__						,   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(UpperCAmelCase__) // args.gradient_accumulation_steps) + 1
          else:
               a           = len(UpperCAmelCase__) // 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(UpperCAmelCase__						,   lr=args.learning_rate						,   eps=args.adam_epsilon)
          a           = get_linear_schedule_with_warmup(
              UpperCAmelCase__						,   num_warmup_steps=args.warmup_steps						,   num_training_steps=UpperCAmelCase__)

     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(UpperCAmelCase__						,   desc="Training")
               for step, batch in enumerate(UpperCAmelCase__):
                    a           = tuple(t.to(UpperCAmelCase__) for t in batch)
                    a    , a    , a    , a           = batch
                    a           = model(UpperCAmelCase__						,   mc_token_ids=UpperCAmelCase__						,   lm_labels=UpperCAmelCase__						,   mc_labels=UpperCAmelCase__)
                    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(UpperCAmelCase__						,   scheduler.get_lr()[0])

    # Save a trained model
     if args.do_train:
          # Save a trained model, configuration and tokenizer
          a           = 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`
          a           = os.path.join(args.output_dir						,   UpperCAmelCase__)
          a           = 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
          a           = OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir)
          a           = OpenAIGPTTokenizer.from_pretrained(args.output_dir)
          model.to(UpperCAmelCase__)

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

               a           = mc_logits.detach().cpu().numpy()
               a           = mc_labels.to("cpu").numpy()
               a           = 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

          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(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()




'''simple docstring'''







import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          DistilBertForMaskedLM,
          DistilBertForMultipleChoice,
          DistilBertForQuestionAnswering,
          DistilBertForSequenceClassification,
          DistilBertForTokenClassification,
          DistilBertModel,
      )


class        A__   (   _snake_case      ):



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=13		,					UpperCamelCase__=7		,					UpperCamelCase__=True		,					UpperCamelCase__=True		,					UpperCamelCase__=False		,					UpperCamelCase__=True		,					UpperCamelCase__=99		,					UpperCamelCase__=32		,					UpperCamelCase__=5		,					UpperCamelCase__=4		,					UpperCamelCase__=37		,					UpperCamelCase__="gelu"		,					UpperCamelCase__=0.1		,					UpperCamelCase__=0.1		,					UpperCamelCase__=512		,					UpperCamelCase__=16		,					UpperCamelCase__=2		,					UpperCamelCase__=0.02		,					UpperCamelCase__=3		,					UpperCamelCase__=4		,					UpperCamelCase__=None		,					)    ->   Dict:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   seq_length
           A_						       =   is_training
           A_						       =   use_input_mask
           A_						       =   use_token_type_ids
           A_						       =   use_labels
           A_						       =   vocab_size
           A_						       =   hidden_size
           A_						       =   num_hidden_layers
           A_						       =   num_attention_heads
           A_						       =   intermediate_size
           A_						       =   hidden_act
           A_						       =   hidden_dropout_prob
           A_						       =   attention_probs_dropout_prob
           A_						       =   max_position_embeddings
           A_						       =   type_vocab_size
           A_						       =   type_sequence_label_size
           A_						       =   initializer_range
           A_						       =   num_labels
           A_						       =   num_choices
           A_						       =   scope



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.vocab_size							)

           A_						       =   None
           if self.use_input_mask:
                  A_						       =   random_attention_mask([self.batch_size, self.seq_length]							)

           A_						       =   None
           A_						       =   None
           A_						       =   None
           if self.use_labels:
                  A_						       =   ids_tensor([self.batch_size]		,					self.type_sequence_label_size							)
                  A_						       =   ids_tensor([self.batch_size, self.seq_length]		,					self.num_labels							)
                  A_						       =   ids_tensor([self.batch_size]		,					self.num_choices							)

           A_						       =   self.get_config()

           return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           return DistilBertConfig(
               vocab_size=self.vocab_size		,					dim=self.hidden_size		,					n_layers=self.num_hidden_layers		,					n_heads=self.num_attention_heads		,					hidden_dim=self.intermediate_size		,					hidden_act=self.hidden_act		,					dropout=self.hidden_dropout_prob		,					attention_dropout=self.attention_probs_dropout_prob		,					max_position_embeddings=self.max_position_embeddings		,					initializer_range=self.initializer_range		,					)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   DistilBertModel(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(UpperCamelCase__		,					UpperCamelCase__							)
           A_						       =   model(UpperCamelCase__							)
           self.parent.assertEqual(result.last_hidden_state.shape		,					(self.batch_size, self.seq_length, self.hidden_size)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   DistilBertForMaskedLM(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					labels=UpperCamelCase__							)
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.vocab_size)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Dict:





           '''simple docstring'''
           A_						       =   DistilBertForQuestionAnswering(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					start_positions=UpperCamelCase__		,					end_positions=UpperCamelCase__							)
           self.parent.assertEqual(result.start_logits.shape		,					(self.batch_size, self.seq_length)							)
           self.parent.assertEqual(result.end_logits.shape		,					(self.batch_size, self.seq_length)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   self.num_labels
           A_						       =   DistilBertForSequenceClassification(UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					labels=UpperCamelCase__							)
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   Any:





           '''simple docstring'''
           A_						       =   self.num_labels
           A_						       =   DistilBertForTokenClassification(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()

           A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					labels=UpperCamelCase__							)
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.seq_length, self.num_labels)							)



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__		,					UpperCamelCase__							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.num_choices
           A_						       =   DistilBertForMultipleChoice(config=UpperCamelCase__							)
           model.to(UpperCamelCase__							)
           model.eval()
           A_						       =   input_ids.unsqueeze(1							).expand(-1		,					self.num_choices		,					-1							).contiguous()
           A_						       =   input_mask.unsqueeze(1							).expand(-1		,					self.num_choices		,					-1							).contiguous()
           A_						       =   model(
               UpperCamelCase__		,					attention_mask=UpperCamelCase__		,					labels=UpperCamelCase__		,					)
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_choices)							)







    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   self.prepare_config_and_inputs()
           ((A_)       ,      (A_)       ,      (A_)       ,      (A_)       ,      (A_)       ,      (A_))						       =   config_and_inputs
           A_						       =   {"""input_ids""": input_ids, """attention_mask""": input_mask}
           return config, inputs_dict


@require_torch
class        A__   (   _snake_case    ,    _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		(
        (
            DistilBertModel,
            DistilBertForMaskedLM,
            DistilBertForMultipleChoice,
            DistilBertForQuestionAnswering,
            DistilBertForSequenceClassification,
            DistilBertForTokenClassification,
        )
        if is_torch_available()
        else None
    )
    lowercase						       =		(
        {
            "feature-extraction": DistilBertModel,
            "fill-mask": DistilBertForMaskedLM,
            "question-answering": DistilBertForQuestionAnswering,
            "text-classification": DistilBertForSequenceClassification,
            "token-classification": DistilBertForTokenClassification,
            "zero-shot": DistilBertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    lowercase						       =		True
    lowercase						       =		True
    lowercase						       =		True
    lowercase						       =		True



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   DistilBertModelTester(self							)
           A_						       =   ConfigTester(self		,					config_class=UpperCamelCase__		,					dim=37							)



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           self.config_tester.run_common_tests()



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_model(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_for_masked_lm(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_for_question_answering(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_for_sequence_classification(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_for_token_classification(*UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           A_						       =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_distilbert_for_multiple_choice(*UpperCamelCase__							)



    @slow
    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  A_						       =   DistilBertModel.from_pretrained(UpperCamelCase__							)
                  self.assertIsNotNone(UpperCamelCase__							)







    @slow
    @require_torch_gpu
    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_       ,      A_						       =   self.model_tester.prepare_config_and_inputs_for_common()
           for model_class in self.all_model_classes:
                  # BertForMultipleChoice behaves incorrectly in JIT environments.
                  if model_class == DistilBertForMultipleChoice:
                         return

                  A_						       =   True
                  A_						       =   model_class(config=UpperCamelCase__							)

                  A_						       =   self._prepare_for_class(UpperCamelCase__		,					UpperCamelCase__							)
                  A_						       =   torch.jit.trace(
                      UpperCamelCase__		,					(inputs_dict["""input_ids"""].to("""cpu"""							), inputs_dict["""attention_mask"""].to("""cpu"""							))							)

                  with tempfile.TemporaryDirectory() as tmp:
                         torch.jit.save(UpperCamelCase__		,					os.path.join(UpperCamelCase__		,					"""traced_model.pt"""							)							)
                         A_						       =   torch.jit.load(os.path.join(UpperCamelCase__		,					"""traced_model.pt"""							)		,					map_location=UpperCamelCase__							)
                         loaded(inputs_dict["""input_ids"""].to(UpperCamelCase__							)		,					inputs_dict["""attention_mask"""].to(UpperCamelCase__							)							)


@require_torch
class        A__   (   unittest.TestCase      ):



    @slow
    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   DistilBertModel.from_pretrained("""distilbert-base-uncased"""							)
           A_						       =   torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]							)
           A_						       =   torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
           with torch.no_grad():
                  A_						       =   model(UpperCamelCase__		,					attention_mask=UpperCamelCase__							)[0]
           A_						       =   torch.Size((1, 11, 768)							)
           self.assertEqual(output.shape		,					UpperCamelCase__							)
           A_						       =   torch.tensor(
               [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]							)

           self.assertTrue(torch.allclose(output[:, 1:4, 1:4]		,					UpperCamelCase__		,					atol=1e-4							)							)
