





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      _SCREAMING_SNAKE_CASE		(			enum.Enum					):







	'''simple docstring'''
	lowercase_	=    0
	lowercase_	=    1
	lowercase_	=    2



@add_end_docstrings(__SCREAMING_SNAKE_CASE					)
class      _SCREAMING_SNAKE_CASE		(			__SCREAMING_SNAKE_CASE					):







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

	def __init__(self       :     Tuple ,				*UpperCAmelCase_       :     List[str] ,				**UpperCAmelCase_       :     Dict) ->str:



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

	def 							SCREAMING_SNAKE_CASE_      (self       :     Tuple ,				UpperCAmelCase_       :     List[str]=None ,				UpperCAmelCase_       :     str=None ,				UpperCAmelCase_       :     Union[str, Any]=None ,				UpperCAmelCase_       :     Any=None ,				UpperCAmelCase_       :     List[Any]=None ,				UpperCAmelCase_       :     Dict=None ,				UpperCAmelCase_       :     Union[str, Any]=None ,				UpperCAmelCase_       :     Optional[Any]=None ,				**UpperCAmelCase_       :     str ,				) ->List[str]:



			'''simple docstring'''



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

			preprocess_params.update(__lowerCAmelCase)
			lowerCamelCase__:   Optional[int]    						=generate_kwargs

			lowerCamelCase__:   Optional[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`")
					lowerCamelCase__:   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`")
					lowerCamelCase__:   str    						=ReturnType.TENSORS
			if return_type is not None:
					lowerCamelCase__:   Any    						=return_type
			if clean_up_tokenization_spaces is not None:
					lowerCamelCase__:   Tuple    						=clean_up_tokenization_spaces

			if stop_sequence is not None:
					lowerCamelCase__:   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.")
					lowerCamelCase__:   List[str]    						=stop_sequence_ids[0]

			return preprocess_params, forward_params, postprocess_params

	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[Any] ,				*UpperCAmelCase_       :     Tuple ,				**UpperCAmelCase_       :     List[str]) ->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       :     List[Any] ,				UpperCAmelCase_       :     List[Any] ,				**UpperCAmelCase_       :     int) ->Any:



			'''simple docstring'''



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

	def 							SCREAMING_SNAKE_CASE_      (self       :     Optional[int] ,				UpperCAmelCase_       :     Optional[Any] ,				UpperCAmelCase_       :     Any="" ,				UpperCAmelCase_       :     str=None ,				**UpperCAmelCase_       :     Tuple) ->Dict:



			'''simple docstring'''



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

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

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

			return inputs

	def 							SCREAMING_SNAKE_CASE_      (self       :     int ,				UpperCAmelCase_       :     int ,				**UpperCAmelCase_       :     Union[str, Any]) ->str:



			'''simple docstring'''



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



			'''simple docstring'''



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

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

							lowerCamelCase__:   Tuple    						={"generated_text": all_text}
					records.append(__lowerCAmelCase)

			return records








import argparse
from pathlib import Path

import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version

from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging


if version.parse(fairseq.__version__) < version.parse("0.12.2"):
     raise Exception("requires fairseq >= 0.12.2")
if version.parse(fairseq.__version__) > version.parse("2"):
     raise Exception("requires fairseq < v2")

logging.set_verbosity_info()
__A             =       logging.get_logger(__name__)

__A             =       "Hello, World!"
__A             =       "en_XX"





def   lowerCAmelCase_				( __a			,					__a			,					__a	)  ->	List[Any]:







  """simple docstring"""





  lowerCamelCase__:   Any    						=Path("data_bin"	)
  lowerCamelCase__:   int    						=FairseqXmodModel.from_pretrained(
      model_name_or_path=str(Path(__a	).parent	)			,					checkpoint_file=Path(__a	).name			,					_name="xmod_base"			,					arch="xmod_base"			,					task="multilingual_masked_lm"			,					data_name_or_path=str(__a	)			,					bpe="sentencepiece"			,					sentencepiece_model=str(Path(__a	).parent / "sentencepiece.bpe.model"	)			,					src_dict=str(data_dir / "dict.txt"	)			,					)
  xmod.eval()  # disable dropout
  print(__a	)

  lowerCamelCase__:   Optional[int]    						=xmod.model.encoder.sentence_encoder
  lowerCamelCase__:   Tuple    						=XmodConfig(
      vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings			,					hidden_size=xmod.cfg.model.encoder_embed_dim			,					num_hidden_layers=xmod.cfg.model.encoder_layers			,					num_attention_heads=xmod.cfg.model.encoder_attention_heads			,					intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim			,					max_position_embeddings=514			,					type_vocab_size=1			,					layer_norm_eps=1e-5			,					pre_norm=xmod.cfg.model.encoder_normalize_before			,					adapter_reduction_factor=getattr(xmod.cfg.model			,					"bottleneck"			,					2	)			,					adapter_layer_norm=xmod.cfg.model.adapter_layer_norm			,					adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm			,					ln_before_adapter=xmod.cfg.model.ln_before_adapter			,					languages=xmod.cfg.model.languages			,					)
  if classification_head:
    lowerCamelCase__:   Optional[Any]    						=xmod.model.classification_heads["mnli"].out_proj.weight.shape[0]

  print("Our X-MOD config:"			,					__a	)

  lowerCamelCase__:   Tuple    						=XmodForSequenceClassification(__a	) if classification_head else XmodForMaskedLM(__a	)
  model.eval()

  # Now let's copy all the weights.
  # Embeddings
  lowerCamelCase__:   Any    						=xmod_sent_encoder.embed_tokens.weight
  lowerCamelCase__:   List[Any]    						=xmod_sent_encoder.embed_positions.weight
  lowerCamelCase__:   Any    						=torch.zeros_like(
      model.roberta.embeddings.token_type_embeddings.weight	)  # just zero them out b/c xmod doesn't use them.

  lowerCamelCase__:   List[Any]    						=xmod_sent_encoder.layernorm_embedding.weight
  lowerCamelCase__:   Union[str, Any]    						=xmod_sent_encoder.layernorm_embedding.bias

  for i in range(config.num_hidden_layers	):
    # Encoder: start of layer
    lowerCamelCase__:   List[Any]    						=model.roberta.encoder.layer[i]
    lowerCamelCase__:   Union[str, Any]    						=xmod_sent_encoder.layers[i]

    # self attention
    lowerCamelCase__:   Any    						=layer.attention.self
    if not (
        xmod_layer.self_attn.k_proj.weight.data.shape
        == xmod_layer.self_attn.q_proj.weight.data.shape
        == xmod_layer.self_attn.v_proj.weight.data.shape
        == torch.Size((config.hidden_size, config.hidden_size)	)
    ):
      raise AssertionError("Dimensions of self-attention weights do not match."	)

    lowerCamelCase__:   List[str]    						=xmod_layer.self_attn.q_proj.weight
    lowerCamelCase__:   Any    						=xmod_layer.self_attn.q_proj.bias
    lowerCamelCase__:   Any    						=xmod_layer.self_attn.k_proj.weight
    lowerCamelCase__:   Tuple    						=xmod_layer.self_attn.k_proj.bias
    lowerCamelCase__:   Optional[int]    						=xmod_layer.self_attn.v_proj.weight
    lowerCamelCase__:   List[str]    						=xmod_layer.self_attn.v_proj.bias

    # self-attention output
    lowerCamelCase__:   Optional[int]    						=layer.attention.output
    if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
      raise AssertionError("Dimensions of self-attention output weights do not match."	)
    lowerCamelCase__:   Dict    						=xmod_layer.self_attn.out_proj.weight
    lowerCamelCase__:   Optional[Any]    						=xmod_layer.self_attn.out_proj.bias
    lowerCamelCase__:   List[Any]    						=xmod_layer.self_attn_layer_norm.weight
    lowerCamelCase__:   Dict    						=xmod_layer.self_attn_layer_norm.bias

    # intermediate
    lowerCamelCase__:   Optional[Any]    						=layer.intermediate
    if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of intermediate weights do not match."	)
    lowerCamelCase__:   int    						=xmod_layer.fca.weight
    lowerCamelCase__:   List[str]    						=xmod_layer.fca.bias

    # output
    lowerCamelCase__:   str    						=layer.output
    if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
      raise AssertionError("Dimensions of feed-forward weights do not match."	)
    lowerCamelCase__:   Optional[Any]    						=xmod_layer.fca.weight
    lowerCamelCase__:   int    						=xmod_layer.fca.bias
    lowerCamelCase__:   List[str]    						=xmod_layer.final_layer_norm.weight
    lowerCamelCase__:   List[Any]    						=xmod_layer.final_layer_norm.bias
    if bert_output.adapter_layer_norm is not None:
      lowerCamelCase__:   Tuple    						=xmod_layer.adapter_layer_norm.weight
      lowerCamelCase__:   List[str]    						=xmod_layer.adapter_layer_norm.bias

    if sorted(bert_output.adapter_modules.keys()	) != sorted(xmod_layer.adapter_modules.keys()	):
      raise AssertionError("Lists of language adapters do not match."	)
    for lang_code, adapter in xmod_layer.adapter_modules.items():
      lowerCamelCase__:   Optional[int]    						=bert_output.adapter_modules[lang_code]
      lowerCamelCase__:   Optional[int]    						=xmod_layer.adapter_modules[lang_code]
      lowerCamelCase__:   Any    						=from_adapter.fca.weight
      lowerCamelCase__:   Tuple    						=from_adapter.fca.bias
      lowerCamelCase__:   Optional[Any]    						=from_adapter.fca.weight
      lowerCamelCase__:   Optional[int]    						=from_adapter.fca.bias

    # end of layer

  if xmod_sent_encoder.layer_norm is not None:
    lowerCamelCase__:   Tuple    						=xmod_sent_encoder.layer_norm.weight
    lowerCamelCase__:   Dict    						=xmod_sent_encoder.layer_norm.bias

  if classification_head:
    lowerCamelCase__:   List[Any]    						=xmod.model.classification_heads["mnli"].dense.weight
    lowerCamelCase__:   int    						=xmod.model.classification_heads["mnli"].dense.bias
    lowerCamelCase__:   List[str]    						=xmod.model.classification_heads["mnli"].out_proj.weight
    lowerCamelCase__:   Dict    						=xmod.model.classification_heads["mnli"].out_proj.bias
  else:
    # LM Head
    lowerCamelCase__:   Tuple    						=xmod.model.encoder.lm_head.dense.weight
    lowerCamelCase__:   int    						=xmod.model.encoder.lm_head.dense.bias
    lowerCamelCase__:   List[Any]    						=xmod.model.encoder.lm_head.layer_norm.weight
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.layer_norm.bias
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.weight
    lowerCamelCase__:   str    						=xmod.model.encoder.lm_head.bias

  # Let's check that we get the same results.
  lowerCamelCase__:   List[str]    						=xmod.encode(__a	).unsqueeze(0	)  # batch of size 1
  model.roberta.set_default_language(__a	)

  lowerCamelCase__:   List[Any]    						=model(__a	)[0]
  if classification_head:
    lowerCamelCase__:   Union[str, Any]    						=xmod.model.classification_heads["mnli"](xmod.extract_features(__a	)	)
  else:
    lowerCamelCase__:   Dict    						=xmod.model(__a			,					lang_id=[SAMPLE_LANGUAGE]	)[0]
  print(our_output.shape			,					their_output.shape	)
  lowerCamelCase__:   Optional[int]    						=torch.max(torch.abs(our_output - their_output	)	).item()
  print(F"""max_absolute_diff = {max_absolute_diff}"""	)  # ~ 1e-7
  lowerCamelCase__:   Tuple    						=torch.allclose(__a			,					__a			,					atol=1e-3	)
  print("Do both models output the same tensors?"			,					"🔥" if success else "💩"	)
  if not success:
    raise Exception("Something went wRoNg"	)

  Path(__a	).mkdir(parents=__a			,					exist_ok=__a	)
  print(F"""Saving model to {pytorch_dump_folder_path}"""	)
  model.save_pretrained(__a	)


if __name__ == "__main__":
     __A             =       argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         "--xmod_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump."
     )
     parser.add_argument(
         "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
     )
     parser.add_argument(
         "--classification_head", action="store_true", help="Whether to convert a final classification head."
     )
     __A             =       parser.parse_args()
     convert_xmod_checkpoint_to_pytorch(
         args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
     )

