


"""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     ):
   __UpperCAmelCase			:	List[Any]							  =  0
   __UpperCAmelCase			:	Union[str, Any]							  =  1
   __UpperCAmelCase			:	List[Any]							  =  2







@add_end_docstrings(snake_case_     )
class _lowerCAmelCase    (				snake_case_     ):
   __UpperCAmelCase			:	List[Any]							  =  '''
    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						,     *UpperCamelCase__						,     **UpperCamelCase__						)     ->		Dict:

       '''simple docstring'''




       super().__init__(*UpperCamelCase__						,     **UpperCamelCase__						)
       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.
           snake_case   :				Union[str, Any]				 =   None
           if self.model.config.prefix is not None:
               snake_case   :				int				 =   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.
               snake_case   :				Optional[int]				 =   self.XL_PREFIX
           if prefix is not None:
               # Recalculate some generate_kwargs linked to prefix.
               snake_case ,snake_case ,snake_case   :				List[Any]				 =   self._sanitize_parameters(prefix=UpperCamelCase__						,     **self._forward_params						)
               snake_case   :				Optional[Any]				 =   {**self._preprocess_params, **preprocess_params}
               snake_case   :				Optional[Any]				 =   {**self._forward_params, **forward_params}







   def 			lowerCamelCase		(     self						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     UpperCamelCase__=None						,     **UpperCamelCase__						,     )     ->		Union[str, Any]:

       '''simple docstring'''




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

       preprocess_params.update(UpperCamelCase__						)
       snake_case   :				List[Any]				 =   generate_kwargs

       snake_case   :				Tuple				 =   {}
       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`"						)
           snake_case   :				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`"						)
           snake_case   :				Union[str, Any]				 =   ReturnType.TENSORS
       if return_type is not None:
           snake_case   :				Optional[int]				 =   return_type
       if clean_up_tokenization_spaces is not None:
           snake_case   :				str				 =   clean_up_tokenization_spaces

       if stop_sequence is not None:
           snake_case   :				List[str]				 =   self.tokenizer.encode(UpperCamelCase__						,     add_special_tokens=UpperCamelCase__						)
           if len(UpperCamelCase__						) > 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."						)
           snake_case   :				List[Any]				 =   stop_sequence_ids[0]

       return preprocess_params, forward_params, postprocess_params







   def 			lowerCamelCase		(     self						,     *UpperCamelCase__						,     **UpperCamelCase__						)     ->		List[Any]:

       '''simple docstring'''




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

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







   def __call__(     self						,     UpperCamelCase__						,     **UpperCamelCase__						)     ->		Dict:

       '''simple docstring'''




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







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__=""						,     UpperCamelCase__=None						,     **UpperCamelCase__						)     ->		int:

       '''simple docstring'''




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

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

               snake_case   :				List[str]				 =   inputs["input_ids"][:, -keep_length:]
               if "attention_mask" in inputs:
                   snake_case   :				Tuple				 =   inputs["attention_mask"][:, -keep_length:]

       return inputs







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     **UpperCamelCase__						)     ->		List[Any]:

       '''simple docstring'''




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







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__=ReturnType.FULL_TEXT						,     UpperCamelCase__=True						)     ->		str:

       '''simple docstring'''




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

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

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

               snake_case   :				Any				 =   {"generated_text": all_text}
           records.append(UpperCamelCase__						)

       return records









"""simple docstring"""



import argparse
import json
import os
from collections import OrderedDict

import torch

from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer
from transformers.tokenization_utils_base import AddedToken







@torch.no_grad()
def   __lowerCAmelCase						(						lowercase  :  List[str]						,							lowercase  :  int						,							lowercase  :  Dict						,							lowercase  :  Dict						,							lowercase  :  int			)     ->						int:


    """simple docstring"""





    with open(lowercase			) as metadata_file:
        snake_case   :				str				 =   json.load(lowercase			)
    snake_case   :				Optional[Any]				 =   LukeConfig(use_entity_aware_attention=lowercase						,							**metadata["model_config"]			)

    # Load in the weights from the checkpoint_path
    snake_case   :				Tuple				 =   torch.load(lowercase						,							map_location="cpu"			)["module"]

    # Load the entity vocab file
    snake_case   :				Optional[Any]				 =   load_original_entity_vocab(lowercase			)
    # add an entry for [MASK2]
    snake_case   :				Dict				 =   max(entity_vocab.values()			) + 1
    config.entity_vocab_size += 1

    snake_case   :				Union[str, Any]				 =   XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"]			)

    # Add special tokens to the token vocabulary for downstream tasks
    snake_case   :				Tuple				 =   AddedToken("<ent>"						,							lstrip=lowercase						,							rstrip=lowercase			)
    snake_case   :				str				 =   AddedToken("<ent2>"						,							lstrip=lowercase						,							rstrip=lowercase			)
    tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]}			)
    config.vocab_size += 2

    print(F'Saving tokenizer to {pytorch_dump_folder_path}'			)
    tokenizer.save_pretrained(lowercase			)
    with open(os.path.join(lowercase						,							"tokenizer_config.json"			)						,							"r"			) as f:
        snake_case   :				str				 =   json.load(lowercase			)
    snake_case   :				List[str]				 =   "MLukeTokenizer"
    with open(os.path.join(lowercase						,							"tokenizer_config.json"			)						,							"w"			) as f:
        json.dump(lowercase						,							lowercase			)

    with open(os.path.join(lowercase						,							MLukeTokenizer.vocab_files_names["entity_vocab_file"]			)						,							"w"			) as f:
        json.dump(lowercase						,							lowercase			)

    snake_case   :				Dict				 =   MLukeTokenizer.from_pretrained(lowercase			)

    # Initialize the embeddings of the special tokens
    snake_case   :				Tuple				 =   tokenizer.convert_tokens_to_ids(["@"]			)[0]
    snake_case   :				str				 =   tokenizer.convert_tokens_to_ids(["#"]			)[0]

    snake_case   :				Union[str, Any]				 =   state_dict["embeddings.word_embeddings.weight"]
    snake_case   :				str				 =   word_emb[ent_init_index].unsqueeze(0			)
    snake_case   :				Union[str, Any]				 =   word_emb[enta_init_index].unsqueeze(0			)
    snake_case   :				Union[str, Any]				 =   torch.cat([word_emb, ent_emb, enta_emb]			)
    # add special tokens for 'entity_predictions.bias'
    for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]:
        snake_case   :				Tuple				 =   state_dict[bias_name]
        snake_case   :				Optional[Any]				 =   decoder_bias[ent_init_index].unsqueeze(0			)
        snake_case   :				Optional[Any]				 =   decoder_bias[enta_init_index].unsqueeze(0			)
        snake_case   :				Any				 =   torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias]			)

    # Initialize the query layers of the entity-aware self-attention mechanism
    for layer_index in range(config.num_hidden_layers			):
        for matrix_name in ["query.weight", "query.bias"]:
            snake_case   :				Optional[int]				 =   F'encoder.layer.{layer_index}.attention.self.'
            snake_case   :				Optional[Any]				 =   state_dict[prefix + matrix_name]
            snake_case   :				Optional[Any]				 =   state_dict[prefix + matrix_name]
            snake_case   :				Any				 =   state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
    snake_case   :				List[Any]				 =   state_dict["entity_embeddings.entity_embeddings.weight"]
    snake_case   :				str				 =   entity_emb[entity_vocab["[MASK]"]].unsqueeze(0			)
    snake_case   :				Tuple				 =   torch.cat([entity_emb, entity_mask_emb]			)
    # add [MASK2] for 'entity_predictions.bias'
    snake_case   :				Optional[int]				 =   state_dict["entity_predictions.bias"]
    snake_case   :				Optional[int]				 =   entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0			)
    snake_case   :				Union[str, Any]				 =   torch.cat([entity_prediction_bias, entity_mask_bias]			)

    snake_case   :				Union[str, Any]				 =   LukeForMaskedLM(config=lowercase			).eval()

    state_dict.pop("entity_predictions.decoder.weight"			)
    state_dict.pop("lm_head.decoder.weight"			)
    state_dict.pop("lm_head.decoder.bias"			)
    snake_case   :				Tuple				 =   OrderedDict()
    for key, value in state_dict.items():
        if not (key.startswith("lm_head"			) or key.startswith("entity_predictions"			)):
            snake_case   :				Any				 =   state_dict[key]
        else:
            snake_case   :				Tuple				 =   state_dict[key]

    snake_case ,snake_case   :				Optional[Any]				 =   model.load_state_dict(lowercase						,							strict=lowercase			)

    if set(lowercase			) != {"luke.embeddings.position_ids"}:
        raise ValueError(F'Unexpected unexpected_keys: {unexpected_keys}'			)
    if set(lowercase			) != {
        "lm_head.decoder.weight",
        "lm_head.decoder.bias",
        "entity_predictions.decoder.weight",
    }:
        raise ValueError(F'Unexpected missing_keys: {missing_keys}'			)

    model.tie_weights()
    assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all()
    assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all()

    # Check outputs
    snake_case   :				Optional[Any]				 =   MLukeTokenizer.from_pretrained(lowercase						,							task="entity_classification"			)

    snake_case   :				List[str]				 =   "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)."
    snake_case   :				str				 =   (0, 9)
    snake_case   :				Union[str, Any]				 =   tokenizer(lowercase						,							entity_spans=[span]						,							return_tensors="pt"			)

    snake_case   :				int				 =   model(**lowercase			)

    # Verify word hidden states
    if model_size == "large":
        raise NotImplementedError
    else:  # base
        snake_case   :				int				 =   torch.Size((1, 33, 768)			)
        snake_case   :				str				 =   torch.tensor([[0.0892, 0.0596, -0.2819], [0.0134, 0.1199, 0.0573], [-0.0169, 0.0927, 0.0644]]			)

    if not (outputs.last_hidden_state.shape == expected_shape):
        raise ValueError(
            F'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}'			)
    if not torch.allclose(outputs.last_hidden_state[0, :3, :3]						,							lowercase						,							atol=1e-4			):
        raise ValueError

    # Verify entity hidden states
    if model_size == "large":
        raise NotImplementedError
    else:  # base
        snake_case   :				Any				 =   torch.Size((1, 1, 768)			)
        snake_case   :				List[Any]				 =   torch.tensor([[-0.1482, 0.0609, 0.0322]]			)

    if not (outputs.entity_last_hidden_state.shape == expected_shape):
        raise ValueError(
            F'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is'
            F' {expected_shape}'			)
    if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3]						,							lowercase						,							atol=1e-4			):
        raise ValueError

    # Verify masked word/entity prediction
    snake_case   :				List[str]				 =   MLukeTokenizer.from_pretrained(lowercase			)
    snake_case   :				List[Any]				 =   "Tokyo is the capital of <mask>."
    snake_case   :				Optional[Any]				 =   (24, 30)
    snake_case   :				List[str]				 =   tokenizer(lowercase						,							entity_spans=[span]						,							return_tensors="pt"			)

    snake_case   :				Any				 =   model(**lowercase			)

    snake_case   :				int				 =   encoding["input_ids"][0].tolist()
    snake_case   :				str				 =   input_ids.index(tokenizer.convert_tokens_to_ids("<mask>"			)			)
    snake_case   :				Tuple				 =   outputs.logits[0][mask_position_id].argmax(dim=-1			)
    assert "Japan" == tokenizer.decode(lowercase			)

    snake_case   :				Tuple				 =   outputs.entity_logits[0][0].argmax().item()
    snake_case   :				Optional[int]				 =   [
        entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id
    ]
    assert [e for e in multilingual_predicted_entities if e.startswith("en:"			)][0] == "en:Japan"

    # Finally, save our PyTorch model and tokenizer
    print("Saving PyTorch model to {}".format(lowercase			)			)
    model.save_pretrained(lowercase			)







def   __lowerCAmelCase						(						lowercase  :  Union[str, Any]			)     ->						Dict:


    """simple docstring"""





    snake_case   :				Tuple				 =   ["[MASK]", "[PAD]", "[UNK]"]

    snake_case   :				Optional[Any]				 =   [json.loads(lowercase			) for line in open(lowercase			)]

    snake_case   :				Any				 =   {}
    for entry in data:
        snake_case   :				Union[str, Any]				 =   entry["id"]
        for entity_name, language in entry["entities"]:
            if entity_name in SPECIAL_TOKENS:
                snake_case   :				Union[str, Any]				 =   entity_id
                break
            snake_case   :				Dict				 =   F'{language}:{entity_name}'
            snake_case   :				str				 =   entity_id
    return new_mapping


if __name__ == "__main__":
  __snake_case             =   argparse.ArgumentParser()
  # Required parameters
  parser.add_argument("""--checkpoint_path""", type=str, help="""Path to a pytorch_model.bin file.""")
  parser.add_argument(
      """--metadata_path""", default=None, type=str, help="""Path to a metadata.json file, defining the configuration."""
  )
  parser.add_argument(
      """--entity_vocab_path""",
      default=None,
      type=str,
      help="""Path to an entity_vocab.tsv file, containing the entity vocabulary.""",
  )
  parser.add_argument(
      """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to where to dump the output PyTorch model."""
  )
  parser.add_argument(
      """--model_size""", default="""base""", type=str, choices=["""base""", """large"""], help="""Size of the model to be converted."""
  )
  __snake_case             =   parser.parse_args()
  convert_luke_checkpoint(
      args.checkpoint_path,
      args.metadata_path,
      args.entity_vocab_path,
      args.pytorch_dump_folder_path,
      args.model_size,
  )





