
import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
          OpenAIGPTConfig,
          OpenAIGPTDoubleHeadsModel,
          OpenAIGPTForSequenceClassification,
          OpenAIGPTLMHeadModel,
          OpenAIGPTModel,
      )
class 		UpperCamelCase__  :
   def __init__(self			: List[Any] ,    snake_case_			: List[str] ,    snake_case_			: Any=1_3 ,    snake_case_			: Optional[int]=7 ,    snake_case_			: Any=True ,    snake_case_			: Dict=True ,    snake_case_			: Dict=True ,    snake_case_			: Any=9_9 ,    snake_case_			: Optional[Any]=3_2 ,    snake_case_			: List[str]=5 ,    snake_case_			: Tuple=4 ,    snake_case_			: List[Any]=3_7 ,    snake_case_			: Dict="gelu" ,    snake_case_			: Any=0.1 ,    snake_case_			: Tuple=0.1 ,    snake_case_			: int=5_1_2 ,    snake_case_			: str=1_6 ,    snake_case_			: Tuple=2 ,    snake_case_			: int=0.02 ,    snake_case_			: List[str]=3 ,    snake_case_			: Optional[int]=4 ,    snake_case_			: List[Any]=None ,    ):
    __a			:  Tuple		    =  parent
    __a			:  Any		    =  batch_size
    __a			:  int		    =  seq_length
    __a			:  Tuple		    =  is_training
    __a			:  Tuple		    =  use_token_type_ids
    __a			:  Optional[int]		    =  use_labels
    __a			:  Dict		    =  vocab_size
    __a			:  Tuple		    =  hidden_size
    __a			:  Optional[int]		    =  num_hidden_layers
    __a			:  List[Any]		    =  num_attention_heads
    __a			:  int		    =  intermediate_size
    __a			:  List[str]		    =  hidden_act
    __a			:  Optional[int]		    =  hidden_dropout_prob
    __a			:  Any		    =  attention_probs_dropout_prob
    __a			:  Optional[Any]		    =  max_position_embeddings
    __a			:  Dict		    =  type_vocab_size
    __a			:  Tuple		    =  type_sequence_label_size
    __a			:  Dict		    =  initializer_range
    __a			:  Any		    =  num_labels
    __a			:  Tuple		    =  num_choices
    __a			:  List[Any]		    =  scope
    __a			:  int		    =  self.vocab_size - 1
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  str		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.vocab_size       )

    __a			:  Any		    =  None
    if self.use_token_type_ids:
     __a			:  List[str]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.type_vocab_size       )

    __a			:  List[str]		    =  None
    __a			:  Any		    =  None
    __a			:  str		    =  None
    if self.use_labels:
     __a			:  List[Any]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )
     __a			:  Union[str, Any]		    =  ids_tensor([self.batch_size, self.seq_length] ,    self.num_labels       )
     __a			:  Optional[Any]		    =  ids_tensor([self.batch_size] ,    self.num_choices       )

    __a			:  Any		    =  OpenAIGPTConfig(
        vocab_size=self.vocab_size ,    n_embd=self.hidden_size ,    n_layer=self.num_hidden_layers ,    n_head=self.num_attention_heads ,    n_positions=self.max_position_embeddings ,    pad_token_id=self.pad_token_id ,    )

    __a			:  Union[str, Any]		    =  ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,    2       )

    return (
        config,
        input_ids,
        head_mask,
        token_type_ids,
        sequence_labels,
        token_labels,
        choice_labels,
    )
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: List[Any] ,    snake_case_			: str ,    snake_case_			: Any ,    snake_case_			: List[Any] ,    *snake_case_			: Dict       ):
    __a			:  List[Any]		    =  OpenAIGPTModel(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  List[Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    head_mask=snake_case_       )
    __a			:  str		    =  model(snake_case_ ,    token_type_ids=snake_case_       )
    __a			:  List[str]		    =  model(snake_case_       )

    self.parent.assertEqual(result.last_hidden_state.shape ,    (self.batch_size, self.seq_length, self.hidden_size)       )
   def 				lowerCAmelCase      (self			: Optional[int] ,    snake_case_			: int ,    snake_case_			: List[Any] ,    snake_case_			: Union[str, Any] ,    snake_case_			: List[Any] ,    *snake_case_			: List[Any]       ):
    __a			:  Any		    =  OpenAIGPTLMHeadModel(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  int		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.loss.shape ,    ()       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.seq_length, self.vocab_size)       )
   def 				lowerCAmelCase      (self			: Optional[int] ,    snake_case_			: List[Any] ,    snake_case_			: Optional[int] ,    snake_case_			: Dict ,    snake_case_			: List[str] ,    *snake_case_			: Dict       ):
    __a			:  Any		    =  OpenAIGPTDoubleHeadsModel(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  List[Any]		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.loss.shape ,    ()       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.seq_length, self.vocab_size)       )
   def 				lowerCAmelCase      (self			: Union[str, Any] ,    snake_case_			: Tuple ,    snake_case_			: Optional[int] ,    snake_case_			: Dict ,    snake_case_			: Dict ,    *snake_case_			: Tuple       ):
    __a			:  Tuple		    =  self.num_labels
    __a			:  List[str]		    =  OpenAIGPTForSequenceClassification(snake_case_       )
    model.to(snake_case_       )
    model.eval()

    __a			:  Optional[int]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )
    __a			:  str		    =  model(snake_case_ ,    token_type_ids=snake_case_ ,    labels=snake_case_       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.num_labels)       )







   def 				lowerCAmelCase      (self			: str       ):
    __a			:  List[str]		    =  self.prepare_config_and_inputs()
    (
        __a	
    )			:  int		    =  config_and_inputs
    __a			:  str		    =  {
        '''input_ids''': input_ids,
        '''token_type_ids''': token_type_ids,
        '''head_mask''': head_mask,
    }

    return config, inputs_dict





@require_torch
class 		UpperCamelCase__  (	__lowercase   ,__lowercase   ,__lowercase   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				(
       (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE				:							Any     	=				(
       (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
   )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
   _SCREAMING_SNAKE_CASE				:							Tuple     	=				(
       {
           "feature-extraction": OpenAIGPTModel,
           "text-classification": OpenAIGPTForSequenceClassification,
           "text-generation": OpenAIGPTLMHeadModel,
           "zero-shot": OpenAIGPTForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   def 				lowerCAmelCase      (self			: List[Any] ,    snake_case_			: str ,    snake_case_			: List[str] ,    snake_case_			: Dict ,    snake_case_			: List[str] ,    snake_case_			: List[Any]       ):
    if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
     # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
     # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
     # tiny config could not be created.
     return True

    return False
   def 				lowerCAmelCase      (self			: Tuple ,    snake_case_			: Any ,    snake_case_			: str ,    snake_case_			: int=False       ):
    __a			:  List[str]		    =  super()._prepare_for_class(snake_case_ ,    snake_case_ ,    return_labels=snake_case_       )

    if return_labels:
     if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
      __a			:  str		    =  torch.zeros(
          (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) ,    dtype=torch.long ,    device=snake_case_ ,    )
      __a			:  List[str]		    =  inputs_dict['''labels''']
      __a			:  Dict		    =  inputs_dict['''labels''']
      __a			:  int		    =  torch.zeros(
          (self.model_tester.batch_size, self.model_tester.num_choices) ,    dtype=torch.long ,    device=snake_case_ ,    )
      __a			:  List[Any]		    =  torch.zeros(
          self.model_tester.batch_size ,    dtype=torch.long ,    device=snake_case_       )
    return inputs_dict
   def 				lowerCAmelCase      (self			: List[str]       ):
    __a			:  List[str]		    =  OpenAIGPTModelTester(self       )
    __a			:  Optional[int]		    =  ConfigTester(self ,    config_class=snake_case_ ,    n_embd=3_7       )
   def 				lowerCAmelCase      (self			: str       ):
    self.config_tester.run_common_tests()
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  int		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_openai_gpt_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[int]       ):
    __a			:  Optional[Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_lm_head_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  Optional[Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_double_lm_head_model(*snake_case_       )
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  Union[str, Any]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*snake_case_       )







   @slow
   def 				lowerCAmelCase      (self			: str       ):
    for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a			:  List[Any]		    =  OpenAIGPTModel.from_pretrained(snake_case_       )
     self.assertIsNotNone(snake_case_       )





@require_torch
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @slow
   def 				lowerCAmelCase      (self			: Tuple       ):
    __a			:  Any		    =  OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''       )
    model.to(snake_case_       )
    __a			:  str		    =  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]] ,    dtype=torch.long ,    device=snake_case_       )  # the president is
    __a			:  Dict		    =  [
        4_8_1,
        4_7_3_5,
        5_4_4,
        2_4_6,
        9_6_3,
        8_7_0,
        7_6_2,
        2_3_9,
        2_4_4,
        4_0_4_7_7,
        2_4_4,
        2_4_9,
        7_1_9,
        8_8_1,
        4_8_7,
        5_4_4,
        2_4_0,
        2_4_4,
        6_0_3,
        4_8_1,
    ]  # the president is a very good man. " \n " i\'m sure he is, " said the

    __a			:  List[str]		    =  model.generate(snake_case_ ,    do_sample=snake_case_       )
    self.assertListEqual(output_ids[0].tolist() ,    snake_case_       )


import unicodedata
from dataclasses import dataclass
from typing import Optional, Union

import numpy as np

from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase




def        __UpperCamelCase					(    lowerCAmelCase__							:    Union[str, Any]  ,       lowerCAmelCase__							:    int  ,       lowerCAmelCase__							:    List[str]  ,       lowerCAmelCase__							:    Any  ):
 if isinstance(lowerCAmelCase__  ,       lowerCAmelCase__  ):
  __a			:  Union[str, Any]		    =  np.full((len(lowerCAmelCase__  ), sequence_length, 2)  ,       lowerCAmelCase__  )
 else:
  __a			:  str		    =  np.full((len(lowerCAmelCase__  ), sequence_length)  ,       lowerCAmelCase__  )

 for i, tensor in enumerate(lowerCAmelCase__  ):
  if padding_side == "right":
   if isinstance(lowerCAmelCase__  ,       lowerCAmelCase__  ):
    __a			:  Any		    =  tensor[:sequence_length]
   else:
    __a			:  List[Any]		    =  tensor[:sequence_length]
  else:
   if isinstance(lowerCAmelCase__  ,       lowerCAmelCase__  ):
    __a			:  Dict		    =  tensor[:sequence_length]
   else:
    __a			:  int		    =  tensor[:sequence_length]

 return out_tensor.tolist()




def        __UpperCamelCase					(    lowerCAmelCase__							:    Optional[Any]  ):
 __a			:  str		    =  ord(lowerCAmelCase__  )
 if (cp >= 3_3 and cp <= 4_7) or (cp >= 5_8 and cp <= 6_4) or (cp >= 9_1 and cp <= 9_6) or (cp >= 1_2_3 and cp <= 1_2_6):
  return True
 __a			:  List[str]		    =  unicodedata.category(lowerCAmelCase__  )
 if cat.startswith('''P'''  ):
  return True
 return False



@dataclass
class 		UpperCamelCase__  (	__lowercase   ):
   _SCREAMING_SNAKE_CASE				:							PreTrainedTokenizerBase
   _SCREAMING_SNAKE_CASE				:							Union[bool, str, PaddingStrategy]     	=				True
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				None
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				None
   _SCREAMING_SNAKE_CASE				:							int     	=				-100
   _SCREAMING_SNAKE_CASE				:							str     	=				"pt"
   def 				lowerCAmelCase      (self			: str ,    snake_case_			: Tuple       ):
    import torch

    __a			:  Union[str, Any]		    =  '''label''' if '''label''' in features[0].keys() else '''labels'''
    __a			:  Tuple		    =  [feature[label_name] for feature in features] if label_name in features[0].keys() else None
    __a			:  Union[str, Any]		    =  self.tokenizer.pad(
        snake_case_ ,    padding=self.padding ,    max_length=self.max_length ,    pad_to_multiple_of=self.pad_to_multiple_of ,    return_tensors='''pt''' if labels is None else None ,    )

    if labels is None:
     return batch

    __a			:  List[str]		    =  torch.tensor(batch['''entity_ids''']       ).shape[1]
    __a			:  Tuple		    =  self.tokenizer.padding_side
    if padding_side == "right":
     __a			:  Union[str, Any]		    =  [
         list(snake_case_       ) + [self.label_pad_token_id] * (sequence_length - len(snake_case_       )) for label in labels
     ]
    else:
     __a			:  Dict		    =  [
         [self.label_pad_token_id] * (sequence_length - len(snake_case_       )) + list(snake_case_       ) for label in labels
     ]

    __a			:  Dict		    =  [feature['''ner_tags'''] for feature in features]
    __a			:  Optional[Any]		    =  padding_tensor(snake_case_ ,    -1 ,    snake_case_ ,    snake_case_       )
    __a			:  Union[str, Any]		    =  [feature['''original_entity_spans'''] for feature in features]
    __a			:  Optional[int]		    =  padding_tensor(snake_case_ ,    (-1, -1) ,    snake_case_ ,    snake_case_       )
    __a			:  List[str]		    =  {k: torch.tensor(snake_case_ ,    dtype=torch.intaa       ) for k, v in batch.items()}

    return batch
