




import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


lowercase__    :					Optional[Any]					=						"1.5.0"

lowercase__    :					str					=						["vision-encoder-decoder"]


def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	if is_optimum_available():
		from optimum.version import __version__ as optimum_version

		snake_case_		   =					version.parse(_A							)
		if parsed_optimum_version < version.parse(_A							):
			raise RuntimeError(
			    f"transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You "
			    "can upgrade optimum by running: pip install -U optimum[exporters]"							)
	else:
		raise RuntimeError(
		    "transformers.onnx requires optimum to run, you can install the library by running: pip install "
		    "optimum[exporters]"							)
	snake_case_		   =					[
	    sys.executable,
	    "-m",
	    "optimum.exporters.onnx",
	    f"--model {args.model}",
	    f"--task {args.feature}",
	    f"--framework {args.framework}" if args.framework is not None else "",
	    f"{args.output}",
	]
	snake_case_		   =					subprocess.Popen(" ".join(_A							)					,     stdout=subprocess.PIPE					,     shell=_A							)
	proc.wait()

	logger.info(
	    "The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as "
	    "transformers.onnx is deprecated, and will be removed in v5. You can find more information here: "
	    "https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."							)


def 						lowerCamelCase__   (		_A							):







	'''simple docstring'''





	snake_case_		   =					args.output if args.output.is_file() else args.output.joinpath("model.onnx"							)
	if not args.output.parent.exists():
		args.output.parent.mkdir(parents=_A							)

	# Allocate the model
	snake_case_		   =					FeaturesManager.get_model_from_feature(
	    args.feature					,     args.model					,     framework=args.framework					,     cache_dir=args.cache_dir							)

	snake_case_   ,				snake_case_		   =					FeaturesManager.check_supported_model_or_raise(_A					,     feature=args.feature							)
	snake_case_		   =					model_onnx_config(model.config							)

	if model_kind in ENCODER_DECODER_MODELS:
		snake_case_		   =					model.get_encoder()
		snake_case_		   =					model.get_decoder()

		snake_case_		   =					onnx_config.get_encoder_config(encoder_model.config							)
		snake_case_		   =					onnx_config.get_decoder_config(
		    encoder_model.config					,     decoder_model.config					,     feature=args.feature							)

		if args.opset is None:
			snake_case_		   =					max(encoder_onnx_config.default_onnx_opset					,     decoder_onnx_config.default_onnx_opset							)

		if args.opset < min(encoder_onnx_config.default_onnx_opset					,     decoder_onnx_config.default_onnx_opset							):
			raise ValueError(
			    f"Opset {args.opset} is not sufficient to export {model_kind}. At least "
			    f" {min(encoder_onnx_config.default_onnx_opset					,     decoder_onnx_config.default_onnx_opset							)} is required."							)

		snake_case_		   =					AutoFeatureExtractor.from_pretrained(args.model							)

		snake_case_   ,				snake_case_		   =					export(
		    _A					,     _A					,     _A					,     args.opset					,     args.output.parent.joinpath("encoder_model.onnx"							)					,     )

		validate_model_outputs(
		    _A					,     _A					,     _A					,     args.output.parent.joinpath("encoder_model.onnx"							)					,     _A					,     args.atol if args.atol else encoder_onnx_config.atol_for_validation					,     )

		snake_case_		   =					AutoTokenizer.from_pretrained(args.model							)

		snake_case_   ,				snake_case_		   =					export(
		    _A					,     _A					,     _A					,     args.opset					,     args.output.parent.joinpath("decoder_model.onnx"							)					,     )

		validate_model_outputs(
		    _A					,     _A					,     _A					,     args.output.parent.joinpath("decoder_model.onnx"							)					,     _A					,     args.atol if args.atol else decoder_onnx_config.atol_for_validation					,     )
		logger.info(
		    f"All good, model saved at: {args.output.parent.joinpath('encoder_model.onnx'							).as_posix()},"
		    f" {args.output.parent.joinpath('decoder_model.onnx'							).as_posix()}"							)

	else:
		# Instantiate the appropriate preprocessor
		if args.preprocessor == "auto":
			snake_case_		   =					get_preprocessor(args.model							)
		elif args.preprocessor == "tokenizer":
			snake_case_		   =					AutoTokenizer.from_pretrained(args.model							)
		elif args.preprocessor == "image_processor":
			snake_case_		   =					AutoImageProcessor.from_pretrained(args.model							)
		elif args.preprocessor == "feature_extractor":
			snake_case_		   =					AutoFeatureExtractor.from_pretrained(args.model							)
		elif args.preprocessor == "processor":
			snake_case_		   =					AutoProcessor.from_pretrained(args.model							)
		else:
			raise ValueError(f"Unknown preprocessor type '{args.preprocessor}'"							)

		# Ensure the requested opset is sufficient
		if args.opset is None:
			snake_case_		   =					onnx_config.default_onnx_opset

		if args.opset < onnx_config.default_onnx_opset:
			raise ValueError(
			    f"Opset {args.opset} is not sufficient to export {model_kind}. "
			    f"At least  {onnx_config.default_onnx_opset} is required."							)

		snake_case_   ,				snake_case_		   =					export(
		    _A					,     _A					,     _A					,     args.opset					,     args.output					,     )

		if args.atol is None:
			snake_case_		   =					onnx_config.atol_for_validation

		validate_model_outputs(_A					,     _A					,     _A					,     args.output					,     _A					,     args.atol							)
		logger.info(f"All good, model saved at: {args.output.as_posix()}"							)
		warnings.warn(
		    "The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"
		    " using optimum.exporters.onnx in future. You can find more information here:"
		    " https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."					,     _A					,     )


def 						lowerCamelCase__   (		):







	'''simple docstring'''





	snake_case_		   =					ArgumentParser("Hugging Face Transformers ONNX exporter"							)
	parser.add_argument(
	    "-m"					,     "--model"					,     type=_A					,     required=_A					,     help="Model ID on huggingface.co or path on disk to load model from."							)
	parser.add_argument(
	    "--feature"					,     default="default"					,     help="The type of features to export the model with."					,     )
	parser.add_argument("--opset"					,     type=_A					,     default=_A					,     help="ONNX opset version to export the model with."							)
	parser.add_argument(
	    "--atol"					,     type=_A					,     default=_A					,     help="Absolute difference tolerance when validating the model."							)
	parser.add_argument(
	    "--framework"					,     type=_A					,     choices=["pt", "tf"]					,     default=_A					,     help=(
	        "The framework to use for the ONNX export."
	        " If not provided, will attempt to use the local checkpoint's original framework"
	        " or what is available in the environment."
	    )					,     )
	parser.add_argument("output"					,     type=_A					,     help="Path indicating where to store generated ONNX model."							)
	parser.add_argument("--cache_dir"					,     type=_A					,     default=_A					,     help="Path indicating where to store cache."							)
	parser.add_argument(
	    "--preprocessor"					,     type=_A					,     choices=["auto", "tokenizer", "feature_extractor", "image_processor", "processor"]					,     default="auto"					,     help="Which type of preprocessor to use. 'auto' tries to automatically detect it."					,     )
	parser.add_argument(
	    "--export_with_transformers"					,     action="store_true"					,     help=(
	        "Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be "
	        "useful when exporting a model supported in transformers but not in optimum, otherwise it is not "
	        "recommended."
	    )					,     )

	snake_case_		   =					parser.parse_args()
	if args.export_with_transformers or not is_optimum_available():
		export_with_transformers(_A							)
	else:
		export_with_optimum(_A							)


if __name__ == "__main__":
		lowercase__    :					Optional[int]					=						logging.get_logger("transformers.onnx")  # pylint: disable=invalid-name
		logger.setLevel(logging.INFO)
		main()






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 RobertaConfig, RobertaForMaskedLM, RobertaForSequenceClassification
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertSelfAttention,
    BertSelfOutput,
)
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__    :					Dict					=						logging.get_logger(__name__)

lowercase__    :					Any					=						"Hello world! cécé herlolip"


def 						lowerCamelCase__   (		_A					,     _A					,     _A							):







	'''simple docstring'''





	snake_case_		   =					FairseqRobertaModel.from_pretrained(_A							)
	roberta.eval()  # disable dropout
	snake_case_		   =					roberta.model.encoder.sentence_encoder
	snake_case_		   =					RobertaConfig(
	    vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings					,     hidden_size=roberta.args.encoder_embed_dim					,     num_hidden_layers=roberta.args.encoder_layers					,     num_attention_heads=roberta.args.encoder_attention_heads					,     intermediate_size=roberta.args.encoder_ffn_embed_dim					,     max_position_embeddings=514					,     type_vocab_size=1					,     layer_norm_eps=1E-5					,     )
	if classification_head:
		snake_case_		   =					roberta.model.classification_heads["mnli"].out_proj.weight.shape[0]
	print("Our BERT config:"					,     _A							)

	snake_case_		   =					RobertaForSequenceClassification(_A							) if classification_head else RobertaForMaskedLM(_A							)
	model.eval()

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

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

		# self attention
		snake_case_		   =					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)							)
		)

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

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

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

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

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

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

	snake_case_		   =					model(_A							)[0]
	if classification_head:
		snake_case_		   =					roberta.model.classification_heads["mnli"](roberta.extract_features(_A							)							)
	else:
		snake_case_		   =					roberta.model(_A							)[0]
	print(our_output.shape					,     their_output.shape							)
	snake_case_		   =					torch.max(torch.abs(our_output - their_output							)							).item()
	print(f"max_absolute_diff = {max_absolute_diff}"							)  # ~ 1e-7
	snake_case_		   =					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__    :					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."
		)
		lowercase__    :					Optional[Any]					=						parser.parse_args()
		convert_roberta_checkpoint_to_pytorch(
		    args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
		)
