



'''simple docstring'''





import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
lowercase_			=  logging.getLogger(__name__)

lowercase_			=  int(10_000)  # Hardcoded max length to avoid infinite loop

lowercase_			=  {
    "gpt2": (GPTaLMHeadModel, GPTaTokenizer),
    "ctrl": (CTRLLMHeadModel, CTRLTokenizer),
    "openai-gpt": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    "xlnet": (XLNetLMHeadModel, XLNetTokenizer),
    "transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    "xlm": (XLMWithLMHeadModel, XLMTokenizer),
    "gptj": (GPTJForCausalLM, AutoTokenizer),
    "bloom": (BloomForCausalLM, BloomTokenizerFast),
    "llama": (LlamaForCausalLM, LlamaTokenizer),
    "opt": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
lowercase_			=  "In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>"




def lowerCAmelCase  (__A):



     """simple docstring"""



     np.random.seed(args.seed)
     torch.manual_seed(args.seed)
     if args.n_gpu > 0:
          torch.cuda.manual_seed_all(args.seed)




def lowerCAmelCase  (__A  ,     __A  ,     __A  ,     __A):



     """simple docstring"""



     if args.temperature > 0.7:
          logger.info('''CTRL typically works better with lower temperatures (and lower top_k).''')

     _a     =  tokenizer.encode(__A  ,     add_special_tokens=__A)
     if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()):
          logger.info('''WARNING! You are not starting your generation from a control code so you won\'t get good results''')
     return prompt_text




def lowerCAmelCase  (__A  ,     __A  ,     __A  ,     __A):



     """simple docstring"""



     _a     =  hasattr(model.config  ,     '''use_lang_emb''') and model.config.use_lang_emb
     if hasattr(model.config  ,     '''lang2id''') and use_lang_emb:
          _a     =  model.config.langaid.keys()
          if args.xlm_language in available_languages:
               _a     =  args.xlm_language
          else:
               _a     =  None
               while language not in available_languages:
                    _a     =  input('''Using XLM. Select language in ''' + str(list(__A)) + ''' >>> ''')

          _a     =  model.config.langaid[language]
          # kwargs["language"] = tokenizer.lang2id[language]

     # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
     # XLM masked-language modeling (MLM) models need masked token
     # is_xlm_mlm = "mlm" in args.model_name_or_path
     # if is_xlm_mlm:
     #     kwargs["mask_token_id"] = tokenizer.mask_token_id

     return prompt_text




def lowerCAmelCase  (__A  ,     __A  ,     __A  ,     __A):



     """simple docstring"""



     _a     =  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _a     =  prefix + prompt_text
     return prompt_text




def lowerCAmelCase  (__A  ,     __A  ,     __A  ,     __A):



     """simple docstring"""



     _a     =  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _a     =  prefix + prompt_text
     return prompt_text


lowercase_			=  {
    "ctrl": prepare_ctrl_input,
    "xlm": prepare_xlm_input,
    "xlnet": prepare_xlnet_input,
    "transfo-xl": prepare_transfoxl_input,
}




def lowerCAmelCase  (__A  ,     __A):



     """simple docstring"""



     if length < 0 and max_sequence_length > 0:
          _a     =  max_sequence_length
     elif 0 < max_sequence_length < length:
          _a     =  max_sequence_length  # No generation bigger than model size
     elif length < 0:
          _a     =  MAX_LENGTH  # avoid infinite loop
     return length




def lowerCAmelCase  (__A):



     """simple docstring"""



     _a     =  None
     if hasattr(__A  ,     '''hidden_size'''):
          _a     =  model_config.hidden_size
     elif hasattr(__A  ,     '''n_embed'''):
          _a     =  model_config.n_embed
     elif hasattr(__A  ,     '''n_embd'''):
          _a     =  model_config.n_embd

     _a     =  None
     if hasattr(__A  ,     '''num_attention_heads'''):
          _a     =  model_config.num_attention_heads
     elif hasattr(__A  ,     '''n_head'''):
          _a     =  model_config.n_head

     if embedding_size is None or num_head is None or num_head == 0:
          raise ValueError('''Check the model config''')

     _a     =  int(embedding_size / num_head)
     if hasattr(__A  ,     '''n_layer'''):
          _a     =  model_config.n_layer
     elif hasattr(__A  ,     '''num_hidden_layers'''):
          _a     =  model_config.num_hidden_layers
     else:
          raise ValueError('''Number of hidden layers couldn\'t be determined from the model config''')

     return num_layer, num_head, num_embedding_size_per_head




def lowerCAmelCase  (__A  ,     __A  ,     __A):



     """simple docstring"""



     _a  ,   _a  ,   _a     =  sparse_model_config(model.config)
     if model.config.model_type == "bloom":
          _a     =  tuple(
              (
                  torch.empty(int(num_attention_heads * batch_size)  ,     __A  ,     __A)
                  .to(model.dtype)
                  .to(model.device),
                  torch.empty(int(num_attention_heads * batch_size)  ,     __A  ,     __A)
                  .to(model.dtype)
                  .to(model.device),
              )
              for _ in range(__A))
     else:
          _a     =  tuple(
              (
                  torch.empty(__A  ,     __A  ,     __A  ,     __A)
                  .to(model.dtype)
                  .to(model.device),
                  torch.empty(__A  ,     __A  ,     __A  ,     __A)
                  .to(model.dtype)
                  .to(model.device),
              )
              for _ in range(__A))
     return past_key_values




def lowerCAmelCase  (__A  ,     __A  ,     __A):



     """simple docstring"""



     _a     =  len(__A)
     _a     =  tokenizer.batch_encode_plus(__A  ,     return_tensors='''pt''')
     _a     =  dummy_input.to(model.device)
     if model.config.use_cache:
          _a     =  generate_past_key_values(__A  ,     __A  ,     1)
     _a     =  torch.cat(
         [
             torch.zeros(dummy_input['''attention_mask'''].shape[0]  ,     1)
             .to(dummy_input['''attention_mask'''].dtype)
             .to(model.device),
             dummy_input['''attention_mask'''],
         ]  ,     -1  ,     )
     return dummy_input






class __A      (  A						):



 '''simple docstring'''







 __lowerCamelCase   :	Tuple										=	('_optimized', '_default')



 def __init__(self			,       A			,       A	)   ->					Optional[int]:


      """simple docstring"""



      _a     =  optimized
      _a     =  default



 def __call__(self			,       *A			,       **A	)   ->					int:


      """simple docstring"""



      if kwargs["past_key_values"] is None and self._default.config.use_cache:
           _a     =  generate_past_key_values(self._default			,       kwargs['''input_ids'''].shape[0]			,       0	)
      kwargs.pop('''position_ids'''			,       A	)
      for k in list(kwargs.keys()	):
           if kwargs[k] is None or isinstance(kwargs[k]			,       A	):
                kwargs.pop(A	)
      _a     =  self._optimized(**A	)
      _a     =  outputs[0]
      _a     =  outputs[1]
      _a     =  CausalLMOutputWithPast(
          loss=A			,       logits=A			,       past_key_values=A			,       hidden_states=A			,       attentions=A			,       )
      return fixed_output



 def __getattr__(self			,       A	)   ->					int:


      """simple docstring"""



      return getattr(self._default			,       A	)



 def  a__  (self			,       A			,       A=None			,       A=None			,       A=None			,       **A	)   ->					List[Any]:


      """simple docstring"""



      return self._default.prepare_inputs_for_generation(
          A			,       past_key_values=A			,       inputs_embeds=A			,       use_cache=A			,       **A	)



 def  a__  (self			,       A			,       A	)   ->					Tuple[Tuple[torch.Tensor]]:


      """simple docstring"""



      return self._default._reorder_cache(A			,       A	)





def lowerCAmelCase  ():



     """simple docstring"""



     _a     =  argparse.ArgumentParser()
     parser.add_argument(
         '''--model_type'''  ,     default=__A  ,     type=__A  ,     required=__A  ,     help='''Model type selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys())  ,     )
     parser.add_argument(
         '''--model_name_or_path'''  ,     default=__A  ,     type=__A  ,     required=__A  ,     help='''Path to pre-trained model or shortcut name selected in the list: ''' + ''', '''.join(MODEL_CLASSES.keys())  ,     )

     parser.add_argument('''--prompt'''  ,     type=__A  ,     default='''''')
     parser.add_argument('''--length'''  ,     type=__A  ,     default=20)
     parser.add_argument('''--stop_token'''  ,     type=__A  ,     default=__A  ,     help='''Token at which text generation is stopped''')

     parser.add_argument(
         '''--temperature'''  ,     type=__A  ,     default=1.0  ,     help='''temperature of 1.0 has no effect, lower tend toward greedy sampling'''  ,     )
     parser.add_argument(
         '''--repetition_penalty'''  ,     type=__A  ,     default=1.0  ,     help='''primarily useful for CTRL model; in that case, use 1.2''')
     parser.add_argument('''--k'''  ,     type=__A  ,     default=0)
     parser.add_argument('''--p'''  ,     type=__A  ,     default=0.9)

     parser.add_argument('''--prefix'''  ,     type=__A  ,     default=''''''  ,     help='''Text added prior to input.''')
     parser.add_argument('''--padding_text'''  ,     type=__A  ,     default=''''''  ,     help='''Deprecated, the use of `--prefix` is preferred.''')
     parser.add_argument('''--xlm_language'''  ,     type=__A  ,     default=''''''  ,     help='''Optional language when used with the XLM model.''')

     parser.add_argument('''--seed'''  ,     type=__A  ,     default=42  ,     help='''random seed for initialization''')
     parser.add_argument('''--no_cuda'''  ,     action='''store_true'''  ,     help='''Avoid using CUDA when available''')
     parser.add_argument('''--num_return_sequences'''  ,     type=__A  ,     default=1  ,     help='''The number of samples to generate.''')
     parser.add_argument(
         '''--fp16'''  ,     action='''store_true'''  ,     help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'''  ,     )
     parser.add_argument('''--jit'''  ,     action='''store_true'''  ,     help='''Whether or not to use jit trace to accelerate inference''')
     _a     =  parser.parse_args()

     _a     =  torch.device('''cuda''' if torch.cuda.is_available() and not args.no_cuda else '''cpu''')
     _a     =  0 if args.no_cuda else torch.cuda.device_count()

     logger.warning(F'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}''')

     set_seed(__A)

     # Initialize the model and tokenizer
     try:
          _a     =  args.model_type.lower()
          _a  ,   _a     =  MODEL_CLASSES[args.model_type]
     except KeyError:
          raise KeyError('''the model {} you specified is not supported. You are welcome to add it and open a PR :)''')

     _a     =  tokenizer_class.from_pretrained(args.model_name_or_path)
     if tokenizer.pad_token is None:
          _a     =  tokenizer.eos_token
     _a     =  model_class.from_pretrained(args.model_name_or_path)
     model.to(args.device)

     if args.fpaa:
          model.half()
     _a     =  getattr(model.config  ,     '''max_position_embeddings'''  ,     0)
     _a     =  adjust_length_to_model(args.length  ,     max_sequence_length=__A)
     logger.info(__A)

     _a     =  args.prompt if args.prompt else input('''Model prompt >>> ''')

     # Different models need different input formatting and/or extra arguments
     _a     =  args.model_type in PREPROCESSING_FUNCTIONS.keys()
     if requires_preprocessing:
          _a     =  PREPROCESSING_FUNCTIONS.get(args.model_type)
          _a     =  prepare_input(__A  ,     __A  ,     __A  ,     __A)

          if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
               _a     =  {'''add_space_before_punct_symbol''': True}
          else:
               _a     =  {}

          _a     =  tokenizer.encode(
              __A  ,     add_special_tokens=__A  ,     return_tensors='''pt'''  ,     **__A)
     else:
          _a     =  args.prefix if args.prefix else args.padding_text
          _a     =  tokenizer.encode(prefix + prompt_text  ,     add_special_tokens=__A  ,     return_tensors='''pt''')
     _a     =  encoded_prompt.to(args.device)

     if encoded_prompt.size()[-1] == 0:
          _a     =  None
     else:
          _a     =  encoded_prompt

     if args.jit:
          _a     =  ['''enable jit''']
          _a     =  prepare_jit_inputs(__A  ,     __A  ,     __A)
          torch._C._jit_set_texpr_fuser_enabled(__A)
          _a     =  False
          if hasattr(__A  ,     '''forward'''):
               _a     =  inspect.signature(model.forward)
          else:
               _a     =  inspect.signature(model.__call__)
          _a     =  tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(__A  ,     __A) is not None)
          _a     =  torch.jit.trace(__A  ,     __A  ,     strict=__A)
          _a     =  torch.jit.freeze(traced_model.eval())
          traced_model(*__A)
          traced_model(*__A)

          _a     =  _ModelFallbackWrapper(__A  ,     __A)

     _a     =  model.generate(
         input_ids=__A  ,     max_length=args.length + len(encoded_prompt[0])  ,     temperature=args.temperature  ,     top_k=args.k  ,     top_p=args.p  ,     repetition_penalty=args.repetition_penalty  ,     do_sample=__A  ,     num_return_sequences=args.num_return_sequences  ,     )

     # Remove the batch dimension when returning multiple sequences
     if len(output_sequences.shape) > 2:
          output_sequences.squeeze_()

     _a     =  []

     for generated_sequence_idx, generated_sequence in enumerate(__A):
          print(F'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ===''')
          _a     =  generated_sequence.tolist()

          # Decode text
          _a     =  tokenizer.decode(__A  ,     clean_up_tokenization_spaces=__A)

          # Remove all text after the stop token
          _a     =  text[: text.find(args.stop_token) if args.stop_token else None]

          # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
          _a     =  (
              prompt_text + text[len(tokenizer.decode(encoded_prompt[0]  ,     clean_up_tokenization_spaces=__A)) :]
          )

          generated_sequences.append(__A)
          print(__A)

     return generated_sequences


if __name__ == "__main__":
  main()








'''simple docstring'''





import argparse
import os
import pathlib

import fairseq
import torch
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import (
    DataaVecTextConfig,
    DataaVecTextForMaskedLM,
    DataaVecTextForSequenceClassification,
    DataaVecTextModel,
)
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)

# IMPORTANT: In order for this script to run, please make sure to download the dictionary: `dict.txt` from wget https://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz
# File copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_text.py
from transformers.utils import logging


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


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

lowercase_			=  "Hello world! cécé herlolip"




def lowerCAmelCase  (__A  ,     __A  ,     __A):



     """simple docstring"""



     _a  ,   _a     =  os.path.split(__A)
     _a     =  DataaVecTextModel.from_pretrained(
         __A  ,     checkpoint_file=__A)
     dataavec.eval()  # disable dropout
     _a     =  dataavec.models[0]
     _a     =  dataavec_model.encoder.sentence_encoder
     _a     =  DataaVecTextConfig(
         vocab_size=dataavec_sent_encoder.embed_tokens.num_embeddings  ,     hidden_size=dataavec_model.args.encoder_embed_dim  ,     num_hidden_layers=dataavec_model.args.encoder_layers  ,     num_attention_heads=dataavec_model.args.encoder_attention_heads  ,     intermediate_size=dataavec_model.args.encoder_ffn_embed_dim  ,     max_position_embeddings=514  ,     type_vocab_size=1  ,     layer_norm_eps=1e-5  ,     )
     if classification_head:
          _a     =  dataavec.model.classification_heads['''mnli'''].out_proj.weight.shape[0]
     print('''Our BERT config:'''  ,     __A)

     _a     =  DataaVecTextForSequenceClassification(__A) if classification_head else DataaVecTextForMaskedLM(__A)
     model.eval()

     # Now let's copy all the weights.
     # Embeddings
     _a     =  dataavec_sent_encoder.embed_tokens.weight
     _a     =  dataavec_sent_encoder.embed_positions.weight
     _a     =  torch.zeros_like(
         model.dataavec_text.embeddings.token_type_embeddings.weight)  # just zero them out b/c data2vec doesn't use them.
     _a     =  dataavec_sent_encoder.layernorm_embedding.weight
     _a     =  dataavec_sent_encoder.layernorm_embedding.bias

     for i in range(config.num_hidden_layers):
          # Encoder: start of layer
          _a     =  model.dataavec_text.encoder.layer[i]
          _a     =  dataavec_sent_encoder.layers[i]

          # self attention
          _a     =  layer.attention.self
          assert dataavec_layer.self_attn.k_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.k_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )
          assert dataavec_layer.self_attn.q_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.q_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )
          assert dataavec_layer.self_attn.v_proj.weight.data.shape == torch.Size(
              (config.hidden_size, config.hidden_size)), (
              "Shape for data2vec_layer.self_attn.v_proj.weight.data should be"
              F''' {torch.Size((config.hidden_size, config.hidden_size))}'''
          )

          _a     =  dataavec_layer.self_attn.q_proj.weight
          _a     =  dataavec_layer.self_attn.q_proj.bias
          _a     =  dataavec_layer.self_attn.k_proj.weight
          _a     =  dataavec_layer.self_attn.k_proj.bias
          _a     =  dataavec_layer.self_attn.v_proj.weight
          _a     =  dataavec_layer.self_attn.v_proj.bias

          # self-attention output
          _a     =  layer.attention.output
          assert (
              self_output.dense.weight.shape == dataavec_layer.self_attn.out_proj.weight.shape
          ), F'''Shape for self_output.dense.weight should be {dataavec_layer.self_attn.out_proj.weight.shape}'''
          _a     =  dataavec_layer.self_attn.out_proj.weight
          _a     =  dataavec_layer.self_attn.out_proj.bias
          _a     =  dataavec_layer.self_attn_layer_norm.weight
          _a     =  dataavec_layer.self_attn_layer_norm.bias

          # intermediate
          _a     =  layer.intermediate
          assert (
              intermediate.dense.weight.shape == dataavec_layer.fca.weight.shape
          ), F'''Shape for intermediate.dense.weight should be {dataavec_layer.fca.weight.shape}'''
          _a     =  dataavec_layer.fca.weight
          _a     =  dataavec_layer.fca.bias

          # output
          _a     =  layer.output
          assert (
              bert_output.dense.weight.shape == dataavec_layer.fca.weight.shape
          ), F'''Shape for bert_output.dense.weight should be {dataavec_layer.fca.weight.shape}'''
          _a     =  dataavec_layer.fca.weight
          _a     =  dataavec_layer.fca.bias
          _a     =  dataavec_layer.final_layer_norm.weight
          _a     =  dataavec_layer.final_layer_norm.bias
          # end of layer

     if classification_head:
          _a     =  dataavec.model.classification_heads['''mnli'''].dense.weight
          _a     =  dataavec.model.classification_heads['''mnli'''].dense.bias
          _a     =  dataavec.model.classification_heads['''mnli'''].out_proj.weight
          _a     =  dataavec.model.classification_heads['''mnli'''].out_proj.bias
     else:
          # LM Head
          _a     =  dataavec_model.encoder.lm_head.dense.weight
          _a     =  dataavec_model.encoder.lm_head.dense.bias
          _a     =  dataavec_model.encoder.lm_head.layer_norm.weight
          _a     =  dataavec_model.encoder.lm_head.layer_norm.bias
          _a     =  dataavec_model.encoder.lm_head.weight
          _a     =  dataavec_model.encoder.lm_head.bias

     # Let's check that we get the same results.
     _a     =  dataavec.encode(__A).unsqueeze(0)  # batch of size 1

     _a     =  model(__A)[0]
     if classification_head:
          _a     =  dataavec.model.classification_heads['''mnli'''](dataavec.extract_features(__A))
     else:
          _a     =  dataavec_model(__A)[0]
     print(our_output.shape  ,     their_output.shape)
     _a     =  torch.max(torch.abs(our_output - their_output)).item()
     print(F'''max_absolute_diff = {max_absolute_diff}''')  # ~ 1e-7
     _a     =  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''')

     pathlib.Path(__A).mkdir(parents=__A  ,     exist_ok=__A)
     print(F'''Saving model to {pytorch_dump_folder_path}''')
     model.save_pretrained(__A)


if __name__ == "__main__":
  lowercase_			=  argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      "--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."
  )
  lowercase_			=  parser.parse_args()
  convert_dataavec_checkpoint_to_pytorch(
      args.checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
  )



