


'''simple docstring'''


import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
     import tensorflow as tf



class 	__lowerCAmelCase		(							enum.Enum    ):


       '''simple docstring'''







       a_  					=							0
       a_  					=							1
       a_  					=							2







@add_end_docstrings(_snake_case    )
class 	__lowerCAmelCase		(							_snake_case    ):


       '''simple docstring'''







       a_  					=							"""
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    """






       def __init__(							self :       int	,*_a :       Optional[int]	,**_a :       int ):

             '''simple docstring'''




             super().__init__(*snake_case_	,**snake_case_ )
             self.check_model_type(
                 TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING )
             if "prefix" not in self._preprocess_params:
                   # This is very specific. The logic is quite complex and needs to be done
                   # as a "default".
                   # It also defines both some preprocess_kwargs and generate_kwargs
                   # which is why we cannot put them in their respective methods.
                   A_						:  int          =				None
                   if self.model.config.prefix is not None:
                         A_						:  str          =				self.model.config.prefix
                   if prefix is None and self.model.__class__.__name__ in [
                       "XLNetLMHeadModel",
                       "TransfoXLLMHeadModel",
                       "TFXLNetLMHeadModel",
                       "TFTransfoXLLMHeadModel",
                   ]:
                         # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
                         A_						:  Optional[Any]          =				self.XL_PREFIX
                   if prefix is not None:
                         # Recalculate some generate_kwargs linked to prefix.
                         A_						:  str          =				self._sanitize_parameters(prefix=snake_case_	,**self._forward_params )
                         A_						:  str          =				{**self._preprocess_params, **preprocess_params}
                         A_						:  Optional[int]          =				{**self._forward_params, **forward_params}






       def        _a							(							self :       str	,_a :       Union[str, Any]=None	,_a :       Optional[Any]=None	,_a :       str=None	,_a :       List[str]=None	,_a :       Optional[Any]=None	,_a :       Tuple=None	,_a :       Optional[int]=None	,_a :       Any=None	,**_a :       str	,):

             '''simple docstring'''




             A_						:  Optional[int]          =				{}
             if prefix is not None:
                   A_						:  List[str]          =				prefix
             if prefix:
                   A_						:  Dict          =				self.tokenizer(
                       snake_case_	,padding=snake_case_	,add_special_tokens=snake_case_	,return_tensors=self.framework )
                   A_						:  Dict          =				prefix_inputs["input_ids"].shape[-1]

             if handle_long_generation is not None:
                   if handle_long_generation not in {"hole"}:
                         raise ValueError(
                             f'{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected'
                             """ [None, 'hole']""" )
                   A_						:  Any          =				handle_long_generation

             preprocess_params.update(snake_case_ )
             A_						:  int          =				generate_kwargs

             A_						:  Union[str, Any]          =				{}
             if return_full_text is not None and return_type is None:
                   if return_text is not None:
                         raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""" )
                   if return_tensors is not None:
                         raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""" )
                   A_						:  Optional[Any]          =				ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
             if return_tensors is not None and return_type is None:
                   if return_text is not None:
                         raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""" )
                   A_						:  str          =				ReturnType.TENSORS
             if return_type is not None:
                   A_						:  List[str]          =				return_type
             if clean_up_tokenization_spaces is not None:
                   A_						:  Dict          =				clean_up_tokenization_spaces

             if stop_sequence is not None:
                   A_						:  List[str]          =				self.tokenizer.encode(snake_case_	,add_special_tokens=snake_case_ )
                   if len(snake_case_ ) > 1:
                         warnings.warn(
                             """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
                             """ the stop sequence will be used as the stop sequence string in the interim.""" )
                   A_						:  Optional[int]          =				stop_sequence_ids[0]

             return preprocess_params, forward_params, postprocess_params






       def        _a							(							self :       List[Any]	,*_a :       Tuple	,**_a :       Tuple ):

             '''simple docstring'''




             if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
                   kwargs.update({"""add_space_before_punct_symbol""": True} )

             return super()._parse_and_tokenize(*snake_case_	,**snake_case_ )






       def __call__(							self :       Tuple	,_a :       Union[str, Any]	,**_a :       List[Any] ):

             '''simple docstring'''




             return super().__call__(snake_case_	,**snake_case_ )






       def        _a							(							self :       Tuple	,_a :       Optional[Any]	,_a :       int=""	,_a :       List[Any]=None	,**_a :       List[Any] ):

             '''simple docstring'''




             A_						:  Dict          =				self.tokenizer(
                 prefix + prompt_text	,padding=snake_case_	,add_special_tokens=snake_case_	,return_tensors=self.framework )
             A_						:  Any          =				prompt_text

             if handle_long_generation == "hole":
                   A_						:  Dict          =				inputs["input_ids"].shape[-1]
                   if "max_new_tokens" in generate_kwargs:
                         A_						:  Union[str, Any]          =				generate_kwargs["max_new_tokens"]
                   else:
                         A_						:  int          =				generate_kwargs.get("""max_length"""	,self.model.config.max_length ) - cur_len
                         if new_tokens < 0:
                               raise ValueError("""We cannot infer how many new tokens are expected""" )
                   if cur_len + new_tokens > self.tokenizer.model_max_length:
                         A_						:  List[str]          =				self.tokenizer.model_max_length - new_tokens
                         if keep_length <= 0:
                               raise ValueError(
                                   """We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
                                   """ models max length""" )

                         A_						:  Optional[Any]          =				inputs["input_ids"][:, -keep_length:]
                         if "attention_mask" in inputs:
                               A_						:  int          =				inputs["attention_mask"][:, -keep_length:]

             return inputs






       def        _a							(							self :       List[str]	,_a :       int	,**_a :       str ):

             '''simple docstring'''




             A_						:  str          =				model_inputs["input_ids"]
             A_						:  Optional[Any]          =				model_inputs.get("""attention_mask"""	,snake_case_ )
             # Allow empty prompts
             if input_ids.shape[1] == 0:
                   A_						:  List[Any]          =				None
                   A_						:  str          =				None
                   A_						:  Tuple          =				1
             else:
                   A_						:  Optional[Any]          =				input_ids.shape[0]
             A_						:  Optional[int]          =				model_inputs.pop("""prompt_text""" )

             # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
             # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
             A_						:  Union[str, Any]          =				generate_kwargs.pop("""prefix_length"""	,0 )
             if prefix_length > 0:
                   A_						:  Any          =				"max_new_tokens" in generate_kwargs or (
                       "generation_config" in generate_kwargs
                       and generate_kwargs["generation_config"].max_new_tokens is not None
                   )
                   if not has_max_new_tokens:
                         A_						:  Optional[int]          =				generate_kwargs.get("""max_length""" ) or self.model.config.max_length
                         generate_kwargs["max_length"] += prefix_length
                   A_						:  int          =				"min_new_tokens" in generate_kwargs or (
                       "generation_config" in generate_kwargs
                       and generate_kwargs["generation_config"].min_new_tokens is not None
                   )
                   if not has_min_new_tokens and "min_length" in generate_kwargs:
                         generate_kwargs["min_length"] += prefix_length

                   # BS x SL
             A_						:  Optional[int]          =				self.model.generate(input_ids=snake_case_	,attention_mask=snake_case_	,**snake_case_ )
             A_						:  int          =				generated_sequence.shape[0]
             if self.framework == "pt":
                   A_						:  List[Any]          =				generated_sequence.reshape(snake_case_	,out_b // in_b	,*generated_sequence.shape[1:] )
             elif self.framework == "tf":
                   A_						:  Union[str, Any]          =				tf.reshape(snake_case_	,(in_b, out_b // in_b, *generated_sequence.shape[1:]) )
             return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}






       def        _a							(							self :       Optional[int]	,_a :       List[Any]	,_a :       Any=ReturnType.FULL_TEXT	,_a :       Union[str, Any]=True ):

             '''simple docstring'''




             A_						:  str          =				model_outputs["generated_sequence"][0]
             A_						:  int          =				model_outputs["input_ids"]
             A_						:  Optional[int]          =				model_outputs["prompt_text"]
             A_						:  List[Any]          =				generated_sequence.numpy().tolist()
             A_						:  Union[str, Any]          =				[]
             for sequence in generated_sequence:
                   if return_type == ReturnType.TENSORS:
                         A_						:  int          =				{"generated_token_ids": sequence}
                   elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                         # Decode text
                         A_						:  int          =				self.tokenizer.decode(
                             snake_case_	,skip_special_tokens=snake_case_	,clean_up_tokenization_spaces=snake_case_	,)

                         # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
                         if input_ids is None:
                               A_						:  Dict          =				0
                         else:
                               A_						:  Any          =				len(
                                   self.tokenizer.decode(
                                       input_ids[0]	,skip_special_tokens=snake_case_	,clean_up_tokenization_spaces=snake_case_	,) )

                         if return_type == ReturnType.FULL_TEXT:
                               A_						:  str          =				prompt_text + text[prompt_length:]
                         else:
                               A_						:  Tuple          =				text[prompt_length:]

                         A_						:  List[Any]          =				{"generated_text": all_text}
                   records.append(snake_case_ )

             return records




'''simple docstring'''


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 	__lowerCAmelCase		:


  '''simple docstring'''







  def __init__(							self :       Optional[int]	,_a :       List[Any]	,_a :       Dict=13	,_a :       List[Any]=7	,_a :       Optional[Any]=True	,_a :       Any=True	,_a :       Optional[int]=True	,_a :       Union[str, Any]=99	,_a :       Union[str, Any]=32	,_a :       List[str]=5	,_a :       List[str]=4	,_a :       Dict=37	,_a :       List[Any]="gelu"	,_a :       int=0.1	,_a :       Optional[int]=0.1	,_a :       Tuple=512	,_a :       Union[str, Any]=16	,_a :       Optional[Any]=2	,_a :       Optional[Any]=0.02	,_a :       Optional[int]=3	,_a :       str=4	,_a :       Optional[Any]=None	,):

        '''simple docstring'''




        A_						:  Optional[Any]          =				parent
        A_						:  str          =				batch_size
        A_						:  int          =				seq_length
        A_						:  Union[str, Any]          =				is_training
        A_						:  Optional[Any]          =				use_token_type_ids
        A_						:  int          =				use_labels
        A_						:  Dict          =				vocab_size
        A_						:  List[Any]          =				hidden_size
        A_						:  Tuple          =				num_hidden_layers
        A_						:  Optional[int]          =				num_attention_heads
        A_						:  int          =				intermediate_size
        A_						:  Tuple          =				hidden_act
        A_						:  int          =				hidden_dropout_prob
        A_						:  Dict          =				attention_probs_dropout_prob
        A_						:  Any          =				max_position_embeddings
        A_						:  Optional[Any]          =				type_vocab_size
        A_						:  Tuple          =				type_sequence_label_size
        A_						:  int          =				initializer_range
        A_						:  Optional[Any]          =				num_labels
        A_						:  str          =				num_choices
        A_						:  Optional[Any]          =				scope
        A_						:  List[Any]          =				self.vocab_size - 1






  def        _a							(							self :       Any ):

        '''simple docstring'''




        A_						:  List[Any]          =				ids_tensor([self.batch_size, self.seq_length]	,self.vocab_size )

        A_						:  List[Any]          =				None
        if self.use_token_type_ids:
              A_						:  Optional[int]          =				ids_tensor([self.batch_size, self.seq_length]	,self.type_vocab_size )

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

        A_						:  List[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_						:  Tuple          =				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        _a							(							self :       Optional[int]	,_a :       List[str]	,_a :       str	,_a :       int	,_a :       int	,*_a :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  Optional[Any]          =				OpenAIGPTModel(config=_a )
        model.to(_a )
        model.eval()

        A_						:  Optional[int]          =				model(_a	,token_type_ids=_a	,head_mask=_a )
        A_						:  str          =				model(_a	,token_type_ids=_a )
        A_						:  Dict          =				model(_a )

        self.parent.assertEqual(result.last_hidden_state.shape	,(self.batch_size, self.seq_length, self.hidden_size) )






  def        _a							(							self :       Dict	,_a :       Optional[int]	,_a :       Union[str, Any]	,_a :       Dict	,_a :       List[str]	,*_a :       str ):

        '''simple docstring'''




        A_						:  str          =				OpenAIGPTLMHeadModel(_a )
        model.to(_a )
        model.eval()

        A_						:  Any          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.loss.shape	,() )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.seq_length, self.vocab_size) )






  def        _a							(							self :       Any	,_a :       Dict	,_a :       List[Any]	,_a :       Dict	,_a :       Union[str, Any]	,*_a :       str ):

        '''simple docstring'''




        A_						:  Any          =				OpenAIGPTDoubleHeadsModel(_a )
        model.to(_a )
        model.eval()

        A_						:  Optional[int]          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.loss.shape	,() )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.seq_length, self.vocab_size) )






  def        _a							(							self :       List[str]	,_a :       str	,_a :       Tuple	,_a :       Dict	,_a :       Tuple	,*_a :       Dict ):

        '''simple docstring'''




        A_						:  List[str]          =				self.num_labels
        A_						:  int          =				OpenAIGPTForSequenceClassification(_a )
        model.to(_a )
        model.eval()

        A_						:  Dict          =				ids_tensor([self.batch_size]	,self.type_sequence_label_size )
        A_						:  Optional[Any]          =				model(_a	,token_type_ids=_a	,labels=_a )
        self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels) )






  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        A_						:  Union[str, Any]          =				self.prepare_config_and_inputs()
        (
            (
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					(
            A_
        )   ,					
        )						:  str          =				config_and_inputs
        A_						:  int          =				{
            """input_ids""": input_ids,
            """token_type_ids""": token_type_ids,
            """head_mask""": head_mask,
        }

        return config, inputs_dict







@require_torch
class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE  , unittest.TestCase    ):


  '''simple docstring'''







  a_  					=							(
      (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
      if is_torch_available()
      else ()
  )
  a_  					=							(
      (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
  )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
  a_  					=							(
      {
          """feature-extraction""": OpenAIGPTModel,
          """text-classification""": OpenAIGPTForSequenceClassification,
          """text-generation""": OpenAIGPTLMHeadModel,
          """zero-shot""": OpenAIGPTForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )






  def        _a							(							self :       Tuple	,_a :       Optional[int]	,_a :       str	,_a :       List[str]	,_a :       List[str]	,_a :       Any ):

        '''simple docstring'''




        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        _a							(							self :       Optional[int]	,_a :       str	,_a :       Dict	,_a :       Optional[int]=False ):

        '''simple docstring'''




        A_						:  Any          =				super()._prepare_for_class(_a	,_a	,return_labels=_a )

        if return_labels:
              if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                    A_						:  Union[str, Any]          =				torch.zeros(
                        (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)	,dtype=torch.long	,device=_a	,)
                    A_						:  Any          =				inputs_dict["""labels"""]
                    A_						:  Any          =				inputs_dict["""labels"""]
                    A_						:  Tuple          =				torch.zeros(
                        (self.model_tester.batch_size, self.model_tester.num_choices)	,dtype=torch.long	,device=_a	,)
                    A_						:  int          =				torch.zeros(
                        self.model_tester.batch_size	,dtype=torch.long	,device=_a )
        return inputs_dict






  def        _a							(							self :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  Tuple          =				OpenAIGPTModelTester(self )
        A_						:  Optional[int]          =				ConfigTester(self	,config_class=_a	,n_embd=37 )






  def        _a							(							self :       Any ):

        '''simple docstring'''




        self.config_tester.run_common_tests()






  def        _a							(							self :       Optional[Any] ):

        '''simple docstring'''




        A_						:  int          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_model(*_a )






  def        _a							(							self :       Tuple ):

        '''simple docstring'''




        A_						:  Dict          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_lm_head_model(*_a )






  def        _a							(							self :       List[Any] ):

        '''simple docstring'''




        A_						:  str          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_double_lm_head_model(*_a )






  def        _a							(							self :       Union[str, Any] ):

        '''simple docstring'''




        A_						:  List[Any]          =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_a )






  @slow
  def        _a							(							self :       List[Any] ):

        '''simple docstring'''




        for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              A_						:  Union[str, Any]          =				OpenAIGPTModel.from_pretrained(_a )
              self.assertIsNotNone(_a )







@require_torch
class 	__lowerCAmelCase		(							unittest.TestCase    ):


  '''simple docstring'''







  @slow
  def        _a							(							self :       List[str] ):

        '''simple docstring'''




        A_						:  Dict          =				OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt""" )
        model.to(_a )
        A_						:  Dict          =				torch.tensor([[481, 4735, 544]]	,dtype=torch.long	,device=_a )  # the president is
        A_						:  Dict          =				[
            481,
            4735,
            544,
            246,
            963,
            870,
            762,
            239,
            244,
            40477,
            244,
            249,
            719,
            881,
            487,
            544,
            240,
            244,
            603,
            481,
        ]  # the president is a very good man. " \n " i\'m sure he is, " said the

        A_						:  int          =				model.generate(_a	,do_sample=_a )
        self.assertListEqual(output_ids[0].tolist()	,_a )
