



import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


UpperCAmelCase_									=							logging.getLogger(__name__)
def 							UpperCAmelCase__		(				)->Dict:
       _lowerCAmelCase 			=  argparse.ArgumentParser(
           description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.'''				)
       parser.add_argument(
           '''--dataset_name'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default='''wikitext'''     ,				help='''Name of the training. Explore datasets at: hf.co/datasets.'''     ,				)
       parser.add_argument(
           '''--dataset_config'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default='''wikitext-103-raw-v1'''     ,				help='''Configuration name of the dataset.'''				)
       parser.add_argument(
           '''--tokenizer_name_or_path'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default='''sayakpaul/unigram-tokenizer-wikitext'''     ,				help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.'''     ,				)
       parser.add_argument(
           '''--shard_size'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default=1_0_0_0     ,				help='''Number of entries to go in a single shard.'''     ,				)
       parser.add_argument('''--split'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default='''train'''     ,				choices=['''train''', '''test''', '''validation''']				)
       parser.add_argument(
           '''--limit'''     ,				default=_SCREAMING_SNAKE_CASE     ,				type=_SCREAMING_SNAKE_CASE     ,				help='''Limit the number of shards (used for debugging).'''     ,				)
       parser.add_argument(
           '''--max_length'''     ,				type=_SCREAMING_SNAKE_CASE     ,				default=5_1_2     ,				help='''Maximum sequence length. For training on TPUs, it helps to have a maximum'''
           ''' sequence length that is a multiple of 8.'''     ,				)
       parser.add_argument(
           '''--output_dir'''     ,				default='''tf-tpu'''     ,				type=_SCREAMING_SNAKE_CASE     ,				help='''Output directory where the TFRecord shards will be saved. If the'''
           ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'''
           ''' shards will be directly saved to a Google Cloud Storage bucket.'''     ,				)

       _lowerCAmelCase 			=  parser.parse_args()
       return args
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Tuple				)->Optional[Any]:


       def fn(_SCREAMING_SNAKE_CASE   :	int				):
              return tokenizer(examples['''text''']				)

       return fn
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	int				)->int:
       _lowerCAmelCase 			=  []
       for i in range(len(tokenized_data['''input_ids''']				)				):
              _lowerCAmelCase 			=  {
                  '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i]				)				),
                  '''attention_mask''': tf.train.Feature(
                      intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i]				)				),
              }
              _lowerCAmelCase 			=  tf.train.Features(feature=_SCREAMING_SNAKE_CASE				)
              _lowerCAmelCase 			=  tf.train.Example(features=_SCREAMING_SNAKE_CASE				)
              _lowerCAmelCase 			=  example.SerializeToString()
              records.append(_SCREAMING_SNAKE_CASE				)
       return records
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	Union[str, Any]				)->List[Any]:
       _lowerCAmelCase 			=  datasets.load_dataset(args.dataset_name     ,				args.dataset_config     ,				split=args.split				)

       if args.limit is not None:
              _lowerCAmelCase 			=  min(len(_SCREAMING_SNAKE_CASE				)     ,				args.limit				)
              _lowerCAmelCase 			=  dataset.select(range(_SCREAMING_SNAKE_CASE				)				)
              print(f'''Limiting the dataset to {args.limit} entries.'''				)

       _lowerCAmelCase 			=  AutoTokenizer.from_pretrained(args.tokenizer_name_or_path				)

       # Handle output directory creation.
       # For serializing into a Google Cloud Storage Bucket, one needs to first
       # create a bucket.
       if "gs" not in args.output_dir:
              if not os.path.exists(args.output_dir				):
                     os.makedirs(args.output_dir				)
              _lowerCAmelCase 			=  os.path.join(args.output_dir     ,				args.split				)
              if not os.path.exists(_SCREAMING_SNAKE_CASE				):
                     os.makedirs(_SCREAMING_SNAKE_CASE				)
       else:
              _lowerCAmelCase 			=  os.path.join(args.output_dir     ,				args.split				)

       # Tokenize the whole dataset at once.
       _lowerCAmelCase 			=  tokenize_function(_SCREAMING_SNAKE_CASE				)
       _lowerCAmelCase 			=  dataset.map(_SCREAMING_SNAKE_CASE     ,				batched=_SCREAMING_SNAKE_CASE     ,				num_proc=4     ,				remove_columns=['''text''']				)

       # We need to concatenate all our texts together, and then split the result
       # into chunks of a fixed size, which we will call block_size. To do this, we
       # will use the map method again, with the option batched=True. When we use batched=True,
       # the function we pass to map() will be passed multiple inputs at once, allowing us
       # to group them into more or fewer examples than we had in the input.
       # This allows us to create our new fixed-length samples. The advantage of this
       # method is that we don't lose a whole lot of content from the dataset compared to the
       # case where we simply tokenize with a pre-defined max_length.

       def group_texts(_SCREAMING_SNAKE_CASE   :	Any				):
              # Concatenate all texts.
              _lowerCAmelCase 			=  {k: sum(examples[k]     ,				[]				) for k in examples.keys()}
              _lowerCAmelCase 			=  len(concatenated_examples[list(examples.keys()				)[0]]				)
              # We drop the small remainder, though you could add padding instead if the model supports it
              # In this, as in all things, we advise you to follow your heart 🫀
              _lowerCAmelCase 			=  (total_length // args.max_length) * args.max_length
              # Split by chunks of max_len.
              _lowerCAmelCase 			=  {
                  k: [t[i : i + args.max_length] for i in range(0     ,				_SCREAMING_SNAKE_CASE     ,				args.max_length				)]
                  for k, t in concatenated_examples.items()
              }
              return result

       _lowerCAmelCase 			=  dataset_tokenized.map(_SCREAMING_SNAKE_CASE     ,				batched=_SCREAMING_SNAKE_CASE     ,				batch_size=1_0_0_0     ,				num_proc=4				)

       _lowerCAmelCase 			=  0
       _lowerCAmelCase 			=  0
       for shard in range(0     ,				len(_SCREAMING_SNAKE_CASE				)     ,				args.shard_size				):
              _lowerCAmelCase 			=  grouped_dataset[shard : shard + args.shard_size]
              _lowerCAmelCase 			=  len(dataset_snapshot['''input_ids''']				)
              _lowerCAmelCase 			=  os.path.join(_SCREAMING_SNAKE_CASE     ,				f'''dataset-{shard_count}-{records_containing}.tfrecord'''				)
              _lowerCAmelCase 			=  get_serialized_examples(_SCREAMING_SNAKE_CASE				)

              with tf.io.TFRecordWriter(_SCREAMING_SNAKE_CASE				) as out_file:
                     for i in range(len(_SCREAMING_SNAKE_CASE				)				):
                            _lowerCAmelCase 			=  serialized_examples[i]
                            out_file.write(_SCREAMING_SNAKE_CASE				)
                     print('''Wrote file {} containing {} records'''.format(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE				)				)

              shard_count += 1
              total_records += records_containing

       with open(f'''split-{args.split}-records-count.txt'''     ,				'''w'''				) as f:
              print(f'''Total {args.split} records: {total_records}'''     ,				file=_SCREAMING_SNAKE_CASE				)


if __name__ == "__main__":
    UpperCAmelCase_									=							parse_args()
    main(args)




import argparse
import pathlib

import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version

from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.models.roberta.modeling_roberta import RobertaAttention
from transformers.utils import logging


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

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

UpperCAmelCase_									=							"Hello world! cécé herlolip"
def 							UpperCAmelCase__		(				_SCREAMING_SNAKE_CASE   :	str     ,				_SCREAMING_SNAKE_CASE   :	str     ,				_SCREAMING_SNAKE_CASE   :	bool				)->List[Any]:
      _lowerCAmelCase 			=  FairseqRobertaModel.from_pretrained(_SCREAMING_SNAKE_CASE				)
      roberta.eval()  # disable dropout
      _lowerCAmelCase 			=  roberta.model.encoder.sentence_encoder
      _lowerCAmelCase 			=  XLMRobertaConfig(
          vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings     ,				hidden_size=roberta.cfg.model.encoder_embed_dim     ,				num_hidden_layers=roberta.cfg.model.encoder_layers     ,				num_attention_heads=roberta.cfg.model.encoder_attention_heads     ,				intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim     ,				max_position_embeddings=5_1_4     ,				type_vocab_size=1     ,				layer_norm_eps=1e-5     ,				)
      if classification_head:
            _lowerCAmelCase 			=  roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

      print('''Our RoBERTa config:'''     ,				_SCREAMING_SNAKE_CASE				)

      _lowerCAmelCase 			=  XLMRobertaXLForSequenceClassification(_SCREAMING_SNAKE_CASE				) if classification_head else XLMRobertaXLForMaskedLM(_SCREAMING_SNAKE_CASE				)
      model.eval()

      # Now let's copy all the weights.
      # Embeddings
      _lowerCAmelCase 			=  roberta_sent_encoder.embed_tokens.weight
      _lowerCAmelCase 			=  roberta_sent_encoder.embed_positions.weight
      _lowerCAmelCase 			=  torch.zeros_like(
          model.roberta.embeddings.token_type_embeddings.weight				)  # just zero them out b/c RoBERTa doesn't use them.

      _lowerCAmelCase 			=  roberta_sent_encoder.layer_norm.weight
      _lowerCAmelCase 			=  roberta_sent_encoder.layer_norm.bias

      for i in range(config.num_hidden_layers				):
            # Encoder: start of layer
            _lowerCAmelCase 			=  model.roberta.encoder.layer[i]
            _lowerCAmelCase 			=  roberta_sent_encoder.layers[i]

            _lowerCAmelCase 			=  layer.attention
            _lowerCAmelCase 			=  roberta_layer.self_attn_layer_norm.weight
            _lowerCAmelCase 			=  roberta_layer.self_attn_layer_norm.bias

            # self attention
            _lowerCAmelCase 			=  layer.attention.self
            assert (
                roberta_layer.self_attn.k_proj.weight.data.shape
                == roberta_layer.self_attn.q_proj.weight.data.shape
                == roberta_layer.self_attn.v_proj.weight.data.shape
                == torch.Size((config.hidden_size, config.hidden_size)				)
            )

            _lowerCAmelCase 			=  roberta_layer.self_attn.q_proj.weight
            _lowerCAmelCase 			=  roberta_layer.self_attn.q_proj.bias
            _lowerCAmelCase 			=  roberta_layer.self_attn.k_proj.weight
            _lowerCAmelCase 			=  roberta_layer.self_attn.k_proj.bias
            _lowerCAmelCase 			=  roberta_layer.self_attn.v_proj.weight
            _lowerCAmelCase 			=  roberta_layer.self_attn.v_proj.bias

            # self-attention output
            _lowerCAmelCase 			=  layer.attention.output
            assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
            _lowerCAmelCase 			=  roberta_layer.self_attn.out_proj.weight
            _lowerCAmelCase 			=  roberta_layer.self_attn.out_proj.bias

            # this one is final layer norm
            _lowerCAmelCase 			=  roberta_layer.final_layer_norm.weight
            _lowerCAmelCase 			=  roberta_layer.final_layer_norm.bias

            # intermediate
            _lowerCAmelCase 			=  layer.intermediate
            assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
            _lowerCAmelCase 			=  roberta_layer.fca.weight
            _lowerCAmelCase 			=  roberta_layer.fca.bias

            # output
            _lowerCAmelCase 			=  layer.output
            assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
            _lowerCAmelCase 			=  roberta_layer.fca.weight
            _lowerCAmelCase 			=  roberta_layer.fca.bias
            # end of layer

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

      # Let's check that we get the same results.
      _lowerCAmelCase 			=  roberta.encode(_SCREAMING_SNAKE_CASE				).unsqueeze(0				)  # batch of size 1

      _lowerCAmelCase 			=  model(_SCREAMING_SNAKE_CASE				)[0]
      if classification_head:
            _lowerCAmelCase 			=  roberta.model.classification_heads['''mnli'''](roberta.extract_features(_SCREAMING_SNAKE_CASE				)				)
      else:
            _lowerCAmelCase 			=  roberta.model(_SCREAMING_SNAKE_CASE				)[0]
      print(our_output.shape     ,				their_output.shape				)
      _lowerCAmelCase 			=  torch.max(torch.abs(our_output - their_output				)				).item()
      print(f'''max_absolute_diff = {max_absolute_diff}'''				)  # ~ 1e-7
      _lowerCAmelCase 			=  torch.allclose(_SCREAMING_SNAKE_CASE     ,				_SCREAMING_SNAKE_CASE     ,				atol=1e-3				)
      print('''Do both models output the same tensors?'''     ,				'''🔥''' if success else '''💩'''				)
      if not success:
            raise Exception('''Something went wRoNg'''				)

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


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