





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				:					Any						=			0
      _lowercase				:					str						=			1
      _lowercase				:					str						=			2







@add_end_docstrings(UpperCamelCase__)
class 				__lowerCAmelCase       (    UpperCamelCase__):
      _lowercase				:					Dict						=			"""
    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__							)   ->						Optional[Any]:



        '''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.
          a__	:					Optional[Any]										=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__	:					Any										=self.XL_PREFIX
          if prefix is not None:
            # Recalculate some generate_kwargs linked to prefix.
            a__					,							a__					,							a__	:					Tuple										=self._sanitize_parameters(prefix=lowerCAmelCase__		,      **self._forward_params							)
            a__	:					List[str]										={**self._preprocess_params, **preprocess_params}
            a__	:					Tuple										={**self._forward_params, **forward_params}







      def    _lowercase  (    self		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      lowerCAmelCase__=None		,      **lowerCAmelCase__		,      )   ->						Tuple:



        '''simple docstring'''




        a__	:					Tuple										={}
        if prefix is not None:
          a__	:					Optional[Any]										=prefix
        if prefix:
          a__	:					Optional[Any]										=self.tokenizer(
              lowerCAmelCase__		,      padding=lowerCAmelCase__		,      add_special_tokens=lowerCAmelCase__		,      return_tensors=self.framework							)
          a__	:					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']"							)
          a__	:					List[Any]										=handle_long_generation

        preprocess_params.update(lowerCAmelCase__							)
        a__	:					Tuple										=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__	:					str										=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__	:					Any										=ReturnType.TENSORS
        if return_type is not None:
          a__	:					Dict										=return_type
        if clean_up_tokenization_spaces is not None:
          a__	:					int										=clean_up_tokenization_spaces

        if stop_sequence is not None:
          a__	:					Optional[int]										=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."							)
          a__	:					Optional[Any]										=stop_sequence_ids[0]

        return preprocess_params, forward_params, postprocess_params







      def    _lowercase  (    self		,      *lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						int:



        '''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__							)   ->						Any:



        '''simple docstring'''




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







      def    _lowercase  (    self		,      lowerCAmelCase__		,      lowerCAmelCase__=""		,      lowerCAmelCase__=None		,      **lowerCAmelCase__							)   ->						Optional[Any]:



        '''simple docstring'''




        a__	:					Optional[Any]										=self.tokenizer(
            prefix + prompt_text		,      padding=lowerCAmelCase__		,      add_special_tokens=lowerCAmelCase__		,      return_tensors=self.framework							)
        a__	:					Optional[Any]										=prompt_text

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

            a__	:					Tuple										=inputs["input_ids"][:, -keep_length:]
            if "attention_mask" in inputs:
              a__	:					List[Any]										=inputs["attention_mask"][:, -keep_length:]

        return inputs







      def    _lowercase  (    self		,      lowerCAmelCase__		,      **lowerCAmelCase__							)   ->						List[str]:



        '''simple docstring'''




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



        '''simple docstring'''




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

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

            a__	:					str										={"generated_text": all_text}
          records.append(lowerCAmelCase__							)

        return records













import argparse
import os

import torch

from transformers import (
    XLNetConfig,
    XLNetForQuestionAnswering,
    XLNetForSequenceClassification,
    XLNetLMHeadModel,
    load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


UpperCAmelCase	:	int		     =       {
    """cola""": 2,
    """mnli""": 3,
    """mrpc""": 2,
    """sst-2""": 2,
    """sts-b""": 1,
    """qqp""": 2,
    """qnli""": 2,
    """rte""": 2,
    """wnli""": 2,
}


logging.set_verbosity_info()
def      _A       (		SCREAMING_SNAKE_CASE     :   List[Any]       ,       SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Dict       ,       SCREAMING_SNAKE_CASE     :   Union[str, Any]=None						):





  """simple docstring"""



  a__	:					Optional[int]										=XLNetConfig.from_json_file(SCREAMING_SNAKE_CASE						)

  a__	:					Dict										=finetuning_task.lower() if finetuning_task is not None else ""
  if finetuning_task in GLUE_TASKS_NUM_LABELS:
    print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}'''						)
    a__	:					List[str]										=finetuning_task
    a__	:					Tuple										=GLUE_TASKS_NUM_LABELS[finetuning_task]
    a__	:					List[Any]										=XLNetForSequenceClassification(SCREAMING_SNAKE_CASE						)
  elif "squad" in finetuning_task:
    a__	:					Optional[int]										=finetuning_task
    a__	:					Dict										=XLNetForQuestionAnswering(SCREAMING_SNAKE_CASE						)
  else:
    a__	:					List[Any]										=XLNetLMHeadModel(SCREAMING_SNAKE_CASE						)

  # Load weights from tf checkpoint
  load_tf_weights_in_xlnet(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)

  # Save pytorch-model
  a__	:					Dict										=os.path.join(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)
  a__	:					Dict										=os.path.join(SCREAMING_SNAKE_CASE       ,       SCREAMING_SNAKE_CASE						)
  print(f'''Save PyTorch model to {os.path.abspath(SCREAMING_SNAKE_CASE						)}'''						)
  torch.save(model.state_dict()       ,       SCREAMING_SNAKE_CASE						)
  print(f'''Save configuration file to {os.path.abspath(SCREAMING_SNAKE_CASE						)}'''						)
  with open(SCREAMING_SNAKE_CASE       ,       "w"       ,       encoding="utf-8"						) as f:
    f.write(config.to_json_string()						)


if __name__ == "__main__":
     UpperCAmelCase	:	List[str]		     =       argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
     )
     parser.add_argument(
         """--xlnet_config_file""",
         default=None,
         type=str,
         required=True,
         help=(
             """The config json file corresponding to the pre-trained XLNet model. \n"""
             """This specifies the model architecture."""
         ),
     )
     parser.add_argument(
         """--pytorch_dump_folder_path""",
         default=None,
         type=str,
         required=True,
         help="""Path to the folder to store the PyTorch model or dataset/vocab.""",
     )
     parser.add_argument(
         """--finetuning_task""",
         default=None,
         type=str,
         help="""Name of a task on which the XLNet TensorFlow model was fine-tuned""",
     )
     UpperCAmelCase	:	int		     =       parser.parse_args()
     print(args)

     convert_xlnet_checkpoint_to_pytorch(
         args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
     )






