


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  ):
       lowercase_					:      int       					=     0
       lowercase_					:      str       					=     1
       lowercase_					:      Optional[Any]       					=     2






@add_end_docstrings(_a  )
class _lowerCamelCase(		_a  ):
       lowercase_					:      List[str]       					=     """
    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, *lowerCamelCase, **lowerCamelCase)			->  int:




           """simple docstring"""

           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.
               _lowercase			:				int 						=						None
               if self.model.config.prefix is not None:
                   _lowercase			:				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.
                   _lowercase			:				str 						=						self.XL_PREFIX
               if prefix is not None:
                   # Recalculate some generate_kwargs linked to prefix.
                   _lowercase						,							_lowercase						,							_lowercase			:				Optional[Any] 						=						self._sanitize_parameters(prefix=lowerCamelCase, **self._forward_params)
                   _lowercase			:				Dict 						=						{**self._preprocess_params, **preprocess_params}
                   _lowercase			:				str 						=						{**self._forward_params, **forward_params}
       def      UpperCamelCase	(   self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, **lowerCamelCase, )			->  int:




           """simple docstring"""

           _lowercase			:				List[str] 						=						{}
           if prefix is not None:
               _lowercase			:				str 						=						prefix
           if prefix:
               _lowercase			:				Dict 						=						self.tokenizer(
                   lowerCamelCase, padding=lowerCamelCase, add_special_tokens=lowerCamelCase, return_tensors=self.framework)
               _lowercase			:				Any 						=						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\']')
               _lowercase			:				str 						=						handle_long_generation

           preprocess_params.update(lowerCamelCase)
           _lowercase			:				Optional[int] 						=						generate_kwargs

           _lowercase			:				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`')
               _lowercase			:				Union[str, 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`')
               _lowercase			:				List[str] 						=						ReturnType.TENSORS
           if return_type is not None:
               _lowercase			:				Tuple 						=						return_type
           if clean_up_tokenization_spaces is not None:
               _lowercase			:				Optional[Any] 						=						clean_up_tokenization_spaces

           if stop_sequence is not None:
               _lowercase			:				List[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.')
               _lowercase			:				Optional[Any] 						=						stop_sequence_ids[0]

           return preprocess_params, forward_params, postprocess_params
       def      UpperCamelCase	(   self, *lowerCamelCase, **lowerCamelCase)			->  Tuple:




           """simple docstring"""

           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, lowerCamelCase, **lowerCamelCase)			->  int:




           """simple docstring"""

           return super().__call__(lowerCamelCase, **lowerCamelCase)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase="", lowerCamelCase=None, **lowerCamelCase)			->  Dict:




           """simple docstring"""

           _lowercase			:				List[str] 						=						self.tokenizer(
               prefix + prompt_text, padding=lowerCamelCase, add_special_tokens=lowerCamelCase, return_tensors=self.framework)
           _lowercase			:				Optional[int] 						=						prompt_text

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

                   _lowercase			:				Tuple 						=						inputs['input_ids'][:, -keep_length:]
                   if "attention_mask" in inputs:
                       _lowercase			:				Optional[int] 						=						inputs['attention_mask'][:, -keep_length:]

           return inputs
       def      UpperCamelCase	(   self, lowerCamelCase, **lowerCamelCase)			->  Dict:




           """simple docstring"""

           _lowercase			:				Any 						=						model_inputs['input_ids']
           _lowercase			:				str 						=						model_inputs.get('attention_mask', lowerCamelCase)
           # Allow empty prompts
           if input_ids.shape[1] == 0:
               _lowercase			:				List[str] 						=						None
               _lowercase			:				int 						=						None
               _lowercase			:				str 						=						1
           else:
               _lowercase			:				Dict 						=						input_ids.shape[0]
           _lowercase			:				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.
           _lowercase			:				Optional[int] 						=						generate_kwargs.pop('prefix_length', 0)
           if prefix_length > 0:
               _lowercase			:				int 						=						'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:
                   _lowercase			:				Union[str, Any] 						=						generate_kwargs.get('max_length') or self.model.config.max_length
                   generate_kwargs["max_length"] += prefix_length
               _lowercase			:				str 						=						'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
           _lowercase			:				Dict 						=						self.model.generate(input_ids=lowerCamelCase, attention_mask=lowerCamelCase, **lowerCamelCase)
           _lowercase			:				int 						=						generated_sequence.shape[0]
           if self.framework == "pt":
               _lowercase			:				Optional[Any] 						=						generated_sequence.reshape(lowerCamelCase, out_b // in_b, *generated_sequence.shape[1:])
           elif self.framework == "tf":
               _lowercase			:				Optional[int] 						=						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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase=ReturnType.FULL_TEXT, lowerCamelCase=True)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Tuple 						=						model_outputs['generated_sequence'][0]
           _lowercase			:				str 						=						model_outputs['input_ids']
           _lowercase			:				Any 						=						model_outputs['prompt_text']
           _lowercase			:				str 						=						generated_sequence.numpy().tolist()
           _lowercase			:				Union[str, Any] 						=						[]
           for sequence in generated_sequence:
               if return_type == ReturnType.TENSORS:
                   _lowercase			:				Dict 						=						{'generated_token_ids': sequence}
               elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
                   # Decode text
                   _lowercase			:				Union[str, Any] 						=						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:
                       _lowercase			:				Union[str, Any] 						=						0
                   else:
                       _lowercase			:				Dict 						=						len(
                           self.tokenizer.decode(
                               input_ids[0], skip_special_tokens=lowerCamelCase, clean_up_tokenization_spaces=lowerCamelCase, ))

                   if return_type == ReturnType.FULL_TEXT:
                       _lowercase			:				int 						=						prompt_text + text[prompt_length:]
                   else:
                       _lowercase			:				List[str] 						=						text[prompt_length:]

                   _lowercase			:				Dict 						=						{'generated_text': all_text}
               records.append(lowerCamelCase)

           return records








import operator as op


__UpperCamelCase   :			Optional[Any]          = "scaler.pt"
__UpperCamelCase   :			Optional[Any]          = "pytorch_model"
__UpperCamelCase   :			str          = "random_states"
__UpperCamelCase   :			Optional[int]          = "optimizer"
__UpperCamelCase   :			Optional[int]          = "scheduler"
__UpperCamelCase   :			str          = "pytorch_model.bin"
__UpperCamelCase   :			List[str]          = "pytorch_model.bin.index.json"
__UpperCamelCase   :			List[str]          = "model.safetensors"
__UpperCamelCase   :			Optional[int]          = "model.safetensors.index.json"
__UpperCamelCase   :			List[str]          = "1.10.2"
__UpperCamelCase   :			Dict          = "py38"
__UpperCamelCase   :			List[str]          = "4.17.0"
__UpperCamelCase   :			Any          = ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"]
__UpperCamelCase   :			Any          = ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"]
__UpperCamelCase   :			int          = ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"]
__UpperCamelCase   :			Dict          = ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"]
__UpperCamelCase   :			str          = ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"]
__UpperCamelCase   :			List[Any]          = "2.0.1"
__UpperCamelCase   :			int          = ["pdsh", "standard", "openmpi", "mvapich"]
__UpperCamelCase   :			List[str]          = ["default", "reduce-overhead", "max-autotune"]

__UpperCamelCase   :			List[Any]          = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
__UpperCamelCase   :			List[Any]          = [
    "nnodes",
    "nproc_per_node",
    "rdzv_backend",
    "rdzv_endpoint",
    "rdzv_id",
    "rdzv_conf",
    "standalone",
    "max_restarts",
    "monitor_interval",
    "start_method",
    "role",
    "module",
    "m",
    "no_python",
    "run_path",
    "log_dir",
    "r",
    "redirects",
    "t",
    "tee",
    "node_rank",
    "master_addr",
    "master_port",
]

__UpperCamelCase   :			List[str]          = ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM"]
__UpperCamelCase   :			int          = ["DEEPSPEED", "MULTI_XPU", "FSDP"]

