






"""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      UpperCamelCase_			(enum.Enum	):
	__magic_name__       =							0
	__magic_name__       =							1
	__magic_name__       =							2







@add_end_docstrings(__A	)
class      UpperCamelCase_			(__A	):
	__magic_name__       =							'''
    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   :					List[Any]      ,      *lowerCAmelCase_   :					List[str]      ,      **lowerCAmelCase_   :					List[Any]		)		->     Optional[int]:
				super().__init__(*lowerCAmelCase_      ,      **lowerCAmelCase_		)
				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.
							UpperCAmelCase_	:					Any     	=   None
							if self.model.config.prefix is not None:
										UpperCAmelCase_	:					Any     	=   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.
										UpperCAmelCase_	:					Optional[int]     	=   self.XL_PREFIX
							if prefix is not None:
										# Recalculate some generate_kwargs linked to prefix.
										UpperCAmelCase_	,      UpperCAmelCase_	,      UpperCAmelCase_	:					List[str]     	=   self._sanitize_parameters(prefix=lowerCAmelCase_      ,      **self._forward_params		)
										UpperCAmelCase_	:					List[Any]     	=   {**self._preprocess_params, **preprocess_params}
										UpperCAmelCase_	:					Optional[int]     	=   {**self._forward_params, **forward_params}





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      lowerCAmelCase_   :					int=None      ,      lowerCAmelCase_   :					Optional[Any]=None      ,      lowerCAmelCase_   :					int=None      ,      lowerCAmelCase_   :					Optional[int]=None      ,      lowerCAmelCase_   :					List[Any]=None      ,      lowerCAmelCase_   :					Dict=None      ,      lowerCAmelCase_   :					Tuple=None      ,      lowerCAmelCase_   :					List[str]=None      ,      **lowerCAmelCase_   :					Optional[Any]      ,      )		->     int:
				UpperCAmelCase_	:					Union[str, Any]     	=   {}
				if prefix is not None:
							UpperCAmelCase_	:					Tuple     	=   prefix
				if prefix:
							UpperCAmelCase_	:					Optional[Any]     	=   self.tokenizer(
							    lowerCAmelCase_      ,      padding=lowerCAmelCase_      ,      add_special_tokens=lowerCAmelCase_      ,      return_tensors=self.framework		)
							UpperCAmelCase_	:					List[str]     	=   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']"		)
							UpperCAmelCase_	:					Dict     	=   handle_long_generation

				preprocess_params.update(lowerCAmelCase_		)
				UpperCAmelCase_	:					Dict     	=   generate_kwargs

				UpperCAmelCase_	:					Dict     	=   {}
				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`"		)
							UpperCAmelCase_	:					Tuple     	=   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`"		)
							UpperCAmelCase_	:					int     	=   ReturnType.TENSORS
				if return_type is not None:
							UpperCAmelCase_	:					int     	=   return_type
				if clean_up_tokenization_spaces is not None:
							UpperCAmelCase_	:					Tuple     	=   clean_up_tokenization_spaces

				if stop_sequence is not None:
							UpperCAmelCase_	:					Union[str, Any]     	=   self.tokenizer.encode(lowerCAmelCase_      ,      add_special_tokens=lowerCAmelCase_		)
							if len(lowerCAmelCase_		) > 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."		)
							UpperCAmelCase_	:					Optional[int]     	=   stop_sequence_ids[0]

				return preprocess_params, forward_params, postprocess_params





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      *lowerCAmelCase_   :					Dict      ,      **lowerCAmelCase_   :					Dict		)		->     Union[str, Any]:
				# Parse arguments
				if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
							kwargs.update({"add_space_before_punct_symbol": True}		)

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





	def __call__( self   :					List[Any]      ,      lowerCAmelCase_   :					Any      ,      **lowerCAmelCase_   :					Union[str, Any]		)		->     Dict:
				return super().__call__(lowerCAmelCase_      ,      **lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[int]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					List[str]=""      ,      lowerCAmelCase_   :					Any=None      ,      **lowerCAmelCase_   :					Optional[Any]		)		->     Dict:
				UpperCAmelCase_	:					Tuple     	=   self.tokenizer(
				    prefix + prompt_text      ,      padding=lowerCAmelCase_      ,      add_special_tokens=lowerCAmelCase_      ,      return_tensors=self.framework		)
				UpperCAmelCase_	:					Any     	=   prompt_text

				if handle_long_generation == "hole":
							UpperCAmelCase_	:					Optional[Any]     	=   inputs["input_ids"].shape[-1]
							if "max_new_tokens" in generate_kwargs:
										UpperCAmelCase_	:					Dict     	=   generate_kwargs["max_new_tokens"]
							else:
										UpperCAmelCase_	:					List[str]     	=   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:
										UpperCAmelCase_	:					Tuple     	=   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"		)

										UpperCAmelCase_	:					Dict     	=   inputs["input_ids"][:, -keep_length:]
										if "attention_mask" in inputs:
													UpperCAmelCase_	:					Union[str, Any]     	=   inputs["attention_mask"][:, -keep_length:]

				return inputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					Union[str, Any]      ,      **lowerCAmelCase_   :					str		)		->     Dict:
				UpperCAmelCase_	:					Optional[Any]     	=   model_inputs["input_ids"]
				UpperCAmelCase_	:					str     	=   model_inputs.get("attention_mask"      ,      lowerCAmelCase_		)
				# Allow empty prompts
				if input_ids.shape[1] == 0:
							UpperCAmelCase_	:					List[str]     	=   None
							UpperCAmelCase_	:					Union[str, Any]     	=   None
							UpperCAmelCase_	:					str     	=   1
				else:
							UpperCAmelCase_	:					Union[str, Any]     	=   input_ids.shape[0]
				UpperCAmelCase_	:					Any     	=   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.
				UpperCAmelCase_	:					Any     	=   generate_kwargs.pop("prefix_length"      ,      0		)
				if prefix_length > 0:
							UpperCAmelCase_	:					str     	=   "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:
										UpperCAmelCase_	:					Tuple     	=   generate_kwargs.get("max_length"		) or self.model.config.max_length
										generate_kwargs["max_length"] += prefix_length
							UpperCAmelCase_	:					Optional[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
				UpperCAmelCase_	:					int     	=   self.model.generate(input_ids=lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_      ,      **lowerCAmelCase_		)
				UpperCAmelCase_	:					Dict     	=   generated_sequence.shape[0]
				if self.framework == "pt":
							UpperCAmelCase_	:					Optional[int]     	=   generated_sequence.reshape(lowerCAmelCase_      ,      out_b // in_b      ,      *generated_sequence.shape[1:]		)
				elif self.framework == "tf":
							UpperCAmelCase_	:					List[Any]     	=   tf.reshape(lowerCAmelCase_      ,      (in_b, out_b // in_b, *generated_sequence.shape[1:])		)
				return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}





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

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

										if return_type == ReturnType.FULL_TEXT:
													UpperCAmelCase_	:					Union[str, Any]     	=   prompt_text + text[prompt_length:]
										else:
													UpperCAmelCase_	:					Dict     	=   text[prompt_length:]

										UpperCAmelCase_	:					int     	=   {"generated_text": all_text}
							records.append(lowerCAmelCase_		)

				return records




"""simple docstring"""



from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


_UpperCamelCase								=		logging.get_logger(__name__)

_UpperCamelCase								=		{
    "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json",
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class 						__UpperCAmelCase    (__A     ):







			'''simple docstring'''
			_UpperCamelCase  :						Tuple					     =				'gpt_neo'
			_UpperCamelCase  :						Optional[Any]					     =				['past_key_values']
			_UpperCamelCase  :						int					     =				{'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}





			def __init__(			self   ,      snake_case_=50_257   ,      snake_case_=2_048   ,      snake_case_=2_048   ,      snake_case_=24   ,      snake_case_=[[["global", "local"], 12]]   ,      snake_case_=16   ,      snake_case_=None   ,      snake_case_=256   ,      snake_case_="gelu_new"   ,      snake_case_=0.0   ,      snake_case_=0.0   ,      snake_case_=0.0   ,      snake_case_=0.1   ,      snake_case_=1E-5   ,      snake_case_=0.02   ,      snake_case_=True   ,      snake_case_=50_256   ,      snake_case_=50_256   ,      **snake_case_   ,      ):







										'''simple docstring'''


										A__       :     int								=			vocab_size
										A__       :     Optional[Any]								=			max_position_embeddings
										A__       :     int								=			hidden_size
										A__       :     List[Any]								=			num_layers
										A__       :     Any								=			num_heads
										A__       :     List[str]								=			intermediate_size
										A__       :     Dict								=			window_size
										A__       :     Optional[int]								=			activation_function
										A__       :     Optional[int]								=			resid_dropout
										A__       :     List[str]								=			embed_dropout
										A__       :     str								=			attention_dropout
										A__       :     List[str]								=			classifier_dropout
										A__       :     str								=			layer_norm_epsilon
										A__       :     str								=			initializer_range
										A__       :     Any								=			use_cache

										A__       :     List[str]								=			bos_token_id
										A__       :     Any								=			eos_token_id

										A__       :     Optional[Any]								=			attention_types
										A__       :     List[Any]								=			self.expand_attention_types_params(snake_case_							)

										if len(self.attention_layers							) != self.num_layers:
																	raise ValueError(
																	    """Configuration for convolutional module is incorrect. """
																	    """It is required that `len(config.attention_layers)` == `config.num_layers` """
																	    F'''but is `len(config.attention_layers) = {len(self.attention_layers							)}`, '''
																	    F'''`config.num_layers = {self.num_layers}`. '''
																	    """`config.attention_layers` is prepared using `config.attention_types`. """
																	    """Please verify the value of `config.attention_types` argument."""							)

										super().__init__(bos_token_id=snake_case_   ,      eos_token_id=snake_case_   ,      **snake_case_							)





			@staticmethod
			def 		lowerCamelCase					(			snake_case_							):







										'''simple docstring'''


										A__       :     Optional[Any]								=			[]
										for item in attention_types:
																	for _ in range(item[1]							):
																								attentions.extend(item[0]							)
										return attentions





def  _A(		lowerCAmelCase			,  lowerCAmelCase			,  lowerCAmelCase			,  lowerCAmelCase							):
							import torch

							A__       :     Union[str, Any]								=			input.size()
							A__       :     str								=			len(lowerCAmelCase							)
							A__       :     Union[str, Any]								=			shape[dimension]

							A__       :     Dict								=			torch.arange(0			,  lowerCAmelCase			,  lowerCAmelCase							)
							A__       :     Dict								=			torch.div(sizedim - size			,  lowerCAmelCase			,  rounding_mode="""floor"""							) + 1
							A__       :     str								=			torch.arange(lowerCAmelCase							) + low_indices[:min_length][:, None]

							A__       :     str								=			[slice(lowerCAmelCase							)] * rank
							A__       :     Optional[Any]								=			indices
							A__       :     Tuple								=			input[s]

							A__       :     List[str]								=			list(range(0			,  rank + 1							)							)
							perm.append(perm.pop(dimension + 1							)							)

							return sliced.permute(lowerCAmelCase							)

def  _A(		lowerCAmelCase			,  lowerCAmelCase							):
							import torch

							A__       :     Optional[Any]								=			torch.arange(1			,  lowerCAmelCase							)
							A__       :     int								=			torch.remainder(lowerCAmelCase			,  lowerCAmelCase							)
							A__       :     str								=			remainders == 0
							A__       :     Tuple								=			candidates[divisor_indices]
							A__       :     Any								=			torch.max(lowerCAmelCase							)
							return largest_divisor, torch.div(lowerCAmelCase			,  lowerCAmelCase			,  rounding_mode="""floor"""							)



class 						__UpperCAmelCase    (__A     ):







			'''simple docstring'''





			@property
			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


										A__       :     Any								=			OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}							)
										if self.use_past:
																	self.fill_with_past_key_values_(snake_case_   ,      direction="""inputs"""							)
																	A__       :     str								=			{0: """batch""", 1: """past_sequence + sequence"""}
										else:
																	A__       :     Optional[Any]								=			{0: """batch""", 1: """sequence"""}

										return common_inputs





			@property
			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


										return self._config.num_heads





			def 		lowerCamelCase					(			self   ,      snake_case_   ,      snake_case_ = -1   ,      snake_case_ = -1   ,      snake_case_ = False   ,      snake_case_ = None   ,      ):







										'''simple docstring'''


										A__       :     Optional[int]								=			super(snake_case_   ,      self							).generate_dummy_inputs(
										    snake_case_   ,      batch_size=snake_case_   ,      seq_length=snake_case_   ,      is_pair=snake_case_   ,      framework=snake_case_							)

										# We need to order the input in the way they appears in the forward()
										A__       :     List[Any]								=			OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}							)

										# Need to add the past_keys
										if self.use_past:
																	if not is_torch_available():
																								raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""							)
																	else:
																								import torch

																								A__				,							A__       :     Dict								=			common_inputs["""input_ids"""].shape
																								# Not using the same length for past_key_values
																								A__       :     Any								=			seqlen + 2
																								A__       :     Any								=			(
																								    batch,
																								    self.num_attention_heads,
																								    past_key_values_length,
																								    self._config.hidden_size // self.num_attention_heads,
																								)
																								A__       :     List[Any]								=			[
																								    (torch.zeros(snake_case_							), torch.zeros(snake_case_							)) for _ in range(self.num_layers							)
																								]

										A__       :     Tuple								=			common_inputs["""attention_mask"""]
										if self.use_past:
																	A__       :     List[Any]								=			ordered_inputs["""attention_mask"""].dtype
																	A__       :     Optional[Any]								=			torch.cat(
																	    [ordered_inputs["""attention_mask"""], torch.ones(snake_case_   ,      snake_case_   ,      dtype=snake_case_							)]   ,      dim=1							)

										return ordered_inputs





			@property
			def 		lowerCamelCase					(			self							):







										'''simple docstring'''


										return 13





