






'''simple docstring'''







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()
_A			:    Tuple					  =logging.get_logger(__name__)

_A			:    Dict					  ='Hello world! cécé herlolip'





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase   )   -> str:
							lowerCamelCase__      :			Optional[Any] 						= FairseqRobertaModel.from_pretrained(lowerCAmelCase_   )
							roberta.eval()  # disable dropout
							lowerCamelCase__      :			Optional[int] 						= roberta.model.encoder.sentence_encoder
							lowerCamelCase__      :			Optional[Any] 						= 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=514       ,    type_vocab_size=1       ,    layer_norm_eps=1E-5       ,    )
							if classification_head:
														lowerCamelCase__      :			Dict 						= roberta.model.classification_heads['''mnli'''].out_proj.weight.shape[0]

							print("""Our RoBERTa config:"""       ,    lowerCAmelCase_   )

							lowerCamelCase__      :			List[str] 						= XLMRobertaXLForSequenceClassification(lowerCAmelCase_   ) if classification_head else XLMRobertaXLForMaskedLM(lowerCAmelCase_   )
							model.eval()

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

							lowerCamelCase__      :			List[Any] 						= roberta_sent_encoder.layer_norm.weight
							lowerCamelCase__      :			List[Any] 						= roberta_sent_encoder.layer_norm.bias

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

														lowerCamelCase__      :			RobertaAttention 						= layer.attention
														lowerCamelCase__      :			Optional[Any] 						= roberta_layer.self_attn_layer_norm.weight
														lowerCamelCase__      :			List[str] 						= roberta_layer.self_attn_layer_norm.bias

														# self attention
														lowerCamelCase__      :			BertSelfAttention 						= 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__      :			Optional[Any] 						= roberta_layer.self_attn.q_proj.weight
														lowerCamelCase__      :			int 						= roberta_layer.self_attn.q_proj.bias
														lowerCamelCase__      :			Optional[int] 						= roberta_layer.self_attn.k_proj.weight
														lowerCamelCase__      :			Any 						= roberta_layer.self_attn.k_proj.bias
														lowerCamelCase__      :			List[Any] 						= roberta_layer.self_attn.v_proj.weight
														lowerCamelCase__      :			Any 						= roberta_layer.self_attn.v_proj.bias

														# self-attention output
														lowerCamelCase__      :			BertSelfOutput 						= layer.attention.output
														assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
														lowerCamelCase__      :			Optional[Any] 						= roberta_layer.self_attn.out_proj.weight
														lowerCamelCase__      :			Union[str, Any] 						= roberta_layer.self_attn.out_proj.bias

														# this one is final layer norm
														lowerCamelCase__      :			str 						= roberta_layer.final_layer_norm.weight
														lowerCamelCase__      :			Optional[Any] 						= roberta_layer.final_layer_norm.bias

														# intermediate
														lowerCamelCase__      :			BertIntermediate 						= layer.intermediate
														assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
														lowerCamelCase__      :			str 						= roberta_layer.fca.weight
														lowerCamelCase__      :			List[Any] 						= roberta_layer.fca.bias

														# output
														lowerCamelCase__      :			BertOutput 						= layer.output
														assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
														lowerCamelCase__      :			Optional[int] 						= roberta_layer.fca.weight
														lowerCamelCase__      :			Any 						= roberta_layer.fca.bias
														# end of layer

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

							# Let's check that we get the same results.
							lowerCamelCase__      :			torch.Tensor 						= roberta.encode(lowerCAmelCase_   ).unsqueeze(0   )  # batch of size 1

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

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


if __name__ == "__main__":
			_A			:    Optional[int]					  =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.'''
			)
			_A			:    Dict					  =parser.parse_args()
			convert_xlm_roberta_xl_checkpoint_to_pytorch(
			    args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
			)









'''simple docstring'''







import argparse
import os
import re

import packaging.version


_A			:    List[str]					  ='''examples/'''
_A			:    Any					  ={
    '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''),
    '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
_A			:    int					  ={
    '''init''': '''src/transformers/__init__.py''',
    '''setup''': '''setup.py''',
}
_A			:    int					  ='''README.md'''





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase   )   -> str:
							with open(UpperCamelCase       ,    """r"""       ,    encoding="""utf-8"""       ,    newline="""\n"""   ) as f:
														lowerCamelCase__      :			List[str] 						= f.read()
							lowerCamelCase__						,	lowerCamelCase__      :			Optional[int] 						= REPLACE_PATTERNS[pattern]
							lowerCamelCase__      :			Dict 						= replace.replace("""VERSION"""       ,    UpperCamelCase   )
							lowerCamelCase__      :			str 						= re_pattern.sub(UpperCamelCase       ,    UpperCamelCase   )
							with open(UpperCamelCase       ,    """w"""       ,    encoding="""utf-8"""       ,    newline="""\n"""   ) as f:
														f.write(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase   )   -> str:
							for folder, directories, fnames in os.walk(UpperCamelCase   ):
														# Removing some of the folders with non-actively maintained examples from the walk
														if "research_projects" in directories:
																					directories.remove("""research_projects"""   )
														if "legacy" in directories:
																					directories.remove("""legacy"""   )
														for fname in fnames:
																					if fname.endswith(""".py"""   ):
																												update_version_in_file(os.path.join(UpperCamelCase       ,    UpperCamelCase   )       ,    UpperCamelCase       ,    pattern="""examples"""   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase       ,    UpperCamelCase=False   )   -> List[Any]:
							for pattern, fname in REPLACE_FILES.items():
														update_version_in_file(UpperCamelCase       ,    UpperCamelCase       ,    UpperCamelCase   )
							if not patch:
														update_version_in_examples(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ ()   -> Optional[Any]:
							lowerCamelCase__      :			Dict 						= """🤗 Transformers currently provides the following architectures"""
							lowerCamelCase__      :			Dict 						= """1. Want to contribute a new model?"""
							with open(UpperCamelCase       ,    """r"""       ,    encoding="""utf-8"""       ,    newline="""\n"""   ) as f:
														lowerCamelCase__      :			int 						= f.readlines()

							# Find the start of the list.
							lowerCamelCase__      :			Optional[int] 						= 0
							while not lines[start_index].startswith(_start_prompt   ):
														start_index += 1
							start_index += 1

							lowerCamelCase__      :			Optional[Any] 						= start_index
							# Update the lines in the model list.
							while not lines[index].startswith(_end_prompt   ):
														if lines[index].startswith("""1."""   ):
																					lowerCamelCase__      :			List[Any] 						= lines[index].replace(
																					    """https://huggingface.co/docs/transformers/main/model_doc"""       ,    """https://huggingface.co/docs/transformers/model_doc"""       ,    )
														index += 1

							with open(UpperCamelCase       ,    """w"""       ,    encoding="""utf-8"""       ,    newline="""\n"""   ) as f:
														f.writelines(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ ()   -> Optional[Any]:
							with open(REPLACE_FILES["""init"""]       ,    """r"""   ) as f:
														lowerCamelCase__      :			int 						= f.read()
							lowerCamelCase__      :			Optional[Any] 						= REPLACE_PATTERNS["""init"""][0].search(UpperCamelCase   ).groups()[0]
							return packaging.version.parse(UpperCamelCase   )





def 				SCREAMING_SNAKE_CASE_ (UpperCamelCase=False   )   -> List[Any]:
							lowerCamelCase__      :			Union[str, Any] 						= get_version()
							if patch and default_version.is_devrelease:
														raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""   )
							if default_version.is_devrelease:
														lowerCamelCase__      :			List[str] 						= default_version.base_version
							elif patch:
														lowerCamelCase__      :			Any 						= f'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}'''
							else:
														lowerCamelCase__      :			List[Any] 						= f'''{default_version.major}.{default_version.minor + 1}.0'''

							# Now let's ask nicely if that's the right one.
							lowerCamelCase__      :			Any 						= input(f'''Which version are you releasing? [{default_version}]'''   )
							if len(UpperCamelCase   ) == 0:
														lowerCamelCase__      :			Optional[int] 						= default_version

							print(f'''Updating version to {version}.'''   )
							global_version_update(UpperCamelCase       ,    patch=UpperCamelCase   )
							if not patch:
														print("""Cleaning main README, don't forget to run `make fix-copies`."""   )
														clean_main_ref_in_model_list()





def 				SCREAMING_SNAKE_CASE_ ()   -> List[str]:
							lowerCamelCase__      :			Optional[int] 						= get_version()
							lowerCamelCase__      :			Any 						= f'''{current_version.major}.{current_version.minor + 1}.0.dev0'''
							lowerCamelCase__      :			Any 						= current_version.base_version

							# Check with the user we got that right.
							lowerCamelCase__      :			List[Any] 						= input(f'''Which version are we developing now? [{dev_version}]'''   )
							if len(UpperCamelCase   ) == 0:
														lowerCamelCase__      :			Dict 						= dev_version

							print(f'''Updating version to {version}.'''   )
							global_version_update(UpperCamelCase   )
							print("""Cleaning main README, don't forget to run `make fix-copies`."""   )
							clean_main_ref_in_model_list()


if __name__ == "__main__":
			_A			:    List[Any]					  =argparse.ArgumentParser()
			parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
			parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
			_A			:    List[str]					  =parser.parse_args()
			if not args.post_release:
						pre_release_work(patch=args.patch)
			elif args.patch:
						print('''Nothing to do after a patch :-)''')
			else:
						post_release_work()

