






'''simple docstring'''

from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


A:   Tuple						=					logging.get_logger(__name__)

A:   Dict						=					{
    "gpt2": "https://huggingface.co/gpt2/resolve/main/config.json",
    "gpt2-medium": "https://huggingface.co/gpt2-medium/resolve/main/config.json",
    "gpt2-large": "https://huggingface.co/gpt2-large/resolve/main/config.json",
    "gpt2-xl": "https://huggingface.co/gpt2-xl/resolve/main/config.json",
    "distilgpt2": "https://huggingface.co/distilgpt2/resolve/main/config.json",
}






class 				__magic_name__  (						UpperCAmelCase_					):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_       :   Tuple   =	'gpt2'
	SCREAMING_SNAKE_CASE_       :   Tuple   =	['past_key_values']
	SCREAMING_SNAKE_CASE_       :   List[Any]   =	{
	    'hidden_size': 'n_embd',
	    'max_position_embeddings': 'n_positions',
	    'num_attention_heads': 'n_head',
	    'num_hidden_layers': 'n_layer',
	}
	def __init__(				self	,   _lowercase=5_0257	,   _lowercase=1024	,   _lowercase=768	,   _lowercase=12	,   _lowercase=12	,   _lowercase=None	,   _lowercase="gelu_new"	,   _lowercase=0.1	,   _lowercase=0.1	,   _lowercase=0.1	,   _lowercase=1E-5	,   _lowercase=0.02	,   _lowercase="cls_index"	,   _lowercase=True	,   _lowercase=None	,   _lowercase=True	,   _lowercase=0.1	,   _lowercase=True	,   _lowercase=True	,   _lowercase=5_0256	,   _lowercase=5_0256	,   _lowercase=False	,   _lowercase=False	,   **_lowercase	,   )    ->	List[Any]:
							lowercase_   : Optional[Any]   	=      vocab_size
							lowercase_   : Union[str, Any]   	=      n_positions
							lowercase_   : Any   	=      n_embd
							lowercase_   : Tuple   	=      n_layer
							lowercase_   : Optional[int]   	=      n_head
							lowercase_   : Any   	=      n_inner
							lowercase_   : Tuple   	=      activation_function
							lowercase_   : List[Any]   	=      resid_pdrop
							lowercase_   : str   	=      embd_pdrop
							lowercase_   : Tuple   	=      attn_pdrop
							lowercase_   : Optional[Any]   	=      layer_norm_epsilon
							lowercase_   : List[str]   	=      initializer_range
							lowercase_   : str   	=      summary_type
							lowercase_   : int   	=      summary_use_proj
							lowercase_   : Dict   	=      summary_activation
							lowercase_   : Tuple   	=      summary_first_dropout
							lowercase_   : List[str]   	=      summary_proj_to_labels
							lowercase_   : List[str]   	=      scale_attn_weights
							lowercase_   : List[Any]   	=      use_cache
							lowercase_   : Optional[Any]   	=      scale_attn_by_inverse_layer_idx
							lowercase_   : Dict   	=      reorder_and_upcast_attn

							lowercase_   : str   	=      bos_token_id
							lowercase_   : Optional[Any]   	=      eos_token_id

							super().__init__(bos_token_id=_lowercase	,   eos_token_id=_lowercase	,   **_lowercase							)






class 				__magic_name__  (						UpperCAmelCase_					):







	"""simple docstring"""



	def __init__(				self	,   _lowercase	,   _lowercase = "default"	,   _lowercase = None	,   _lowercase = False	,   )    ->	Union[str, Any]:
							super().__init__(_lowercase	,   task=_lowercase	,   patching_specs=_lowercase	,   use_past=_lowercase							)
							if not getattr(self._config	,   'pad_token_id'	,   _lowercase							):
													# TODO: how to do that better?
													lowercase_   : str   	=      0
	@property
	def 							lowerCamelCase__		(				self							)    ->	Mapping[str, Mapping[int, str]]:
							lowercase_   : int   	=      OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}							)
							if self.use_past:
													self.fill_with_past_key_values_(_lowercase	,   direction='inputs'							)
													lowercase_   : Optional[int]   	=      {0: 'batch', 1: 'past_sequence + sequence'}
							else:
													lowercase_   : List[Any]   	=      {0: 'batch', 1: 'sequence'}

							return common_inputs
	@property
	def 							lowerCamelCase__		(				self							)    ->	int:
							return self._config.n_layer
	@property
	def 							lowerCamelCase__		(				self							)    ->	int:
							return self._config.n_head
	def 							lowerCamelCase__		(				self	,   _lowercase	,   _lowercase = -1	,   _lowercase = -1	,   _lowercase = False	,   _lowercase = None	,   )    ->	Mapping[str, Any]:
							lowercase_   : Union[str, Any]   	=      super(_lowercase	,   self							).generate_dummy_inputs(
							    _lowercase	,   batch_size=_lowercase	,   seq_length=_lowercase	,   is_pair=_lowercase	,   framework=_lowercase							)

							# We need to order the input in the way they appears in the forward()
							lowercase_   : str   	=      OrderedDict({'input_ids': common_inputs['input_ids']}							)

							# Need to add the past_keys
							if self.use_past:
													if not is_torch_available():
																			raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'							)
													else:
																			import torch

																			lowercase_	,   lowercase_   : List[str]   	=      common_inputs['input_ids'].shape
																			# Not using the same length for past_key_values
																			lowercase_   : List[str]   	=      seqlen + 2
																			lowercase_   : Any   	=      (
																			    batch,
																			    self.num_attention_heads,
																			    past_key_values_length,
																			    self._config.hidden_size // self.num_attention_heads,
																			)
																			lowercase_   : List[str]   	=      [
																			    (torch.zeros(_lowercase							), torch.zeros(_lowercase							)) for _ in range(self.num_layers							)
																			]

							lowercase_   : Union[str, Any]   	=      common_inputs['attention_mask']
							if self.use_past:
													lowercase_   : Dict   	=      ordered_inputs['attention_mask'].dtype
													lowercase_   : Union[str, Any]   	=      torch.cat(
													    [ordered_inputs['attention_mask'], torch.ones(_lowercase	,   _lowercase	,   dtype=_lowercase							)]	,   dim=1							)

							return ordered_inputs







	@property
	def 							lowerCamelCase__		(				self							)    ->	int:
							return 13








'''simple docstring'''

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


A:   List[str]						=					"1.5.0"

A:   Any						=					["vision-encoder-decoder"]






def 						_UpperCAmelCase     (	a		:						int				)      ->      List[str]:





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

												lowercase_   : List[Any]   	=      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]'				)
						lowercase_   : List[Any]   	=      [
						    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}",
						]
						lowercase_   : Tuple   	=      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 						_UpperCAmelCase     (	a		:						Dict				)      ->      Optional[Any]:





						"""simple docstring"""
						lowercase_   : Optional[int]   	=      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
						lowercase_   : int   	=      FeaturesManager.get_model_from_feature(
						    args.feature    ,      args.model    ,      framework=args.framework    ,      cache_dir=args.cache_dir				)

						lowercase_	,   lowercase_   : List[Any]   	=      FeaturesManager.check_supported_model_or_raise(a    ,      feature=args.feature				)
						lowercase_   : List[str]   	=      model_onnx_config(model.config				)

						if model_kind in ENCODER_DECODER_MODELS:
												lowercase_   : List[Any]   	=      model.get_encoder()
												lowercase_   : Any   	=      model.get_decoder()

												lowercase_   : List[str]   	=      onnx_config.get_encoder_config(encoder_model.config				)
												lowercase_   : int   	=      onnx_config.get_decoder_config(
												    encoder_model.config    ,      decoder_model.config    ,      feature=args.feature				)

												if args.opset is None:
																		lowercase_   : int   	=      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."				)

												lowercase_   : str   	=      AutoFeatureExtractor.from_pretrained(args.model				)

												lowercase_	,   lowercase_   : str   	=      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    ,      )

												lowercase_   : Optional[Any]   	=      AutoTokenizer.from_pretrained(args.model				)

												lowercase_	,   lowercase_   : Union[str, Any]   	=      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":
																		lowercase_   : List[Any]   	=      get_preprocessor(args.model				)
												elif args.preprocessor == "tokenizer":
																		lowercase_   : List[str]   	=      AutoTokenizer.from_pretrained(args.model				)
												elif args.preprocessor == "image_processor":
																		lowercase_   : Optional[Any]   	=      AutoImageProcessor.from_pretrained(args.model				)
												elif args.preprocessor == "feature_extractor":
																		lowercase_   : Tuple   	=      AutoFeatureExtractor.from_pretrained(args.model				)
												elif args.preprocessor == "processor":
																		lowercase_   : Optional[int]   	=      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:
																		lowercase_   : List[str]   	=      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."				)

												lowercase_	,   lowercase_   : str   	=      export(
												    a    ,      a    ,      a    ,      args.opset    ,      args.output    ,      )

												if args.atol is None:
																		lowercase_   : Dict   	=      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 						_UpperCAmelCase     (	)      ->      List[Any]:





						"""simple docstring"""
						lowercase_   : Optional[int]   	=      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.'
						    )    ,      )

						lowercase_   : int   	=      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__":
						A:   Union[str, Any]						=					logging.get_logger("transformers.onnx")  # pylint: disable=invalid-name
						logger.setLevel(logging.INFO)
						main()
