'''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


lowercase_  		=			'''1.5.0'''

lowercase_  		=			['''vision-encoder-decoder''']



def 				UpperCamelCase__      (      a__   ):


						'''simple docstring'''






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

												_lowerCAmelCase					    =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]'   )
						_lowerCAmelCase					    =[
						    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}''',
						]
						_lowerCAmelCase					    =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__   ):


						'''simple docstring'''






						_lowerCAmelCase					    =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
						_lowerCAmelCase					    =FeaturesManager.get_model_from_feature(
						    args.feature      ,   args.model      ,   framework=args.framework      ,   cache_dir=args.cache_dir   )

						_lowerCAmelCase    ,					_lowerCAmelCase					    =FeaturesManager.check_supported_model_or_raise(a__      ,   feature=args.feature   )
						_lowerCAmelCase					    =model_onnx_config(model.config   )

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

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

												if args.opset is None:
																		_lowerCAmelCase					    =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.'''   )

												_lowerCAmelCase					    =AutoFeatureExtractor.from_pretrained(args.model   )

												_lowerCAmelCase    ,					_lowerCAmelCase					    =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      ,   )

												_lowerCAmelCase					    =AutoTokenizer.from_pretrained(args.model   )

												_lowerCAmelCase    ,					_lowerCAmelCase					    =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":
																		_lowerCAmelCase					    =get_preprocessor(args.model   )
												elif args.preprocessor == "tokenizer":
																		_lowerCAmelCase					    =AutoTokenizer.from_pretrained(args.model   )
												elif args.preprocessor == "image_processor":
																		_lowerCAmelCase					    =AutoImageProcessor.from_pretrained(args.model   )
												elif args.preprocessor == "feature_extractor":
																		_lowerCAmelCase					    =AutoFeatureExtractor.from_pretrained(args.model   )
												elif args.preprocessor == "processor":
																		_lowerCAmelCase					    =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:
																		_lowerCAmelCase					    =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.'''   )

												_lowerCAmelCase    ,					_lowerCAmelCase					    =export(
												    a__      ,   a__      ,   a__      ,   args.opset      ,   args.output      ,   )

												if args.atol is None:
																		_lowerCAmelCase					    =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__      (      ):


						'''simple docstring'''






						_lowerCAmelCase					    =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.'
						    )      ,   )

						_lowerCAmelCase					    =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_  		=			logging.get_logger('''transformers.onnx''')  # pylint: disable=invalid-name
							logger.setLevel(logging.INFO)
							main()










import json
import os
from collections.abc import Mapping
from typing import Dict, List, Optional, Union

import numpy as np
import torch

from .imports import is_safetensors_available


def 						_UpperCAmelCase							( snake_case      ,		snake_case      ,		snake_case      ,		snake_case=None     ):





					"""simple docstring"""

					_lowerCAmelCase         =       None
					# Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16.
					if str(weight.dtype     ) == "torch.bfloat16":
										# Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s.
										_lowerCAmelCase         =       weight.view(torch.intaa     )
										_lowerCAmelCase         =       """bfloat16"""
					_lowerCAmelCase         =       weight.cpu().numpy()
					_lowerCAmelCase         =       os.path.join(snake_case      ,		F'{weight_name}.dat'     )
					if index is not None:
										if dtype is None:
															_lowerCAmelCase         =       str(array.dtype     )
										_lowerCAmelCase         =       {"""dtype""": dtype, """shape""": list(array.shape     )}
					if array.ndim == 0:
										_lowerCAmelCase         =       array[None]
					_lowerCAmelCase         =       np.memmap(snake_case      ,		dtype=array.dtype      ,		mode="""w+"""      ,		shape=array.shape     )
					_lowerCAmelCase         =       array[:]
					file_array.flush()
					return index


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					_lowerCAmelCase         =       tuple(weight_info["""shape"""]     )
					if shape == ():
										# NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor
										_lowerCAmelCase         =       (1,)

					_lowerCAmelCase         =       weight_info["""dtype"""]
					if dtype == "bfloat16":
										# NumPy does not support bfloat16 so this was saved as a int16
										_lowerCAmelCase         =       """int16"""

					_lowerCAmelCase         =       np.memmap(snake_case      ,		dtype=snake_case      ,		shape=snake_case      ,		mode="""r"""     )

					if len(weight_info["""shape"""]     ) == 0:
										_lowerCAmelCase         =       weight[0]
					_lowerCAmelCase         =       torch.tensor(snake_case     )
					if weight_info["dtype"] == "bfloat16":
										_lowerCAmelCase         =       weight.view(torch.bfloataa     )

					return weight


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					if index is None or len(snake_case     ) == 0:
										# Nothing to save
										return

					_lowerCAmelCase         =       os.path.join(snake_case      ,		"""index.json"""     )
					if os.path.isfile(snake_case     ):
										with open(snake_case      ,		"""r"""      ,		encoding="""utf-8"""     ) as f:
															_lowerCAmelCase         =       json.load(snake_case     )
					else:
										_lowerCAmelCase         =       {}
					current_index.update(snake_case     )

					with open(snake_case      ,		"""w"""      ,		encoding="""utf-8"""     ) as f:
										json.dump(snake_case      ,		snake_case      ,		indent=2     )


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					os.makedirs(snake_case      ,		exist_ok=snake_case     )
					_lowerCAmelCase         =       {}
					for name, parameter in state_dict.items():
										_lowerCAmelCase         =       offload_weight(snake_case      ,		snake_case      ,		snake_case      ,		index=snake_case     )

					# Update index
					save_offload_index(snake_case      ,		snake_case     )





class    __lowerCAmelCase					(	lowerCamelCase__			):




				def __init__(				self		,							_snake_case		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       dataset
									_lowerCAmelCase         =       prefix




				def __getitem__(				self		,							_snake_case						):



									"""simple docstring"""





									return self.dataset[F'{self.prefix}{key}']




				def __iter__(				self						):



									"""simple docstring"""





									return iter([key for key in self.dataset if key.startswith(self.prefix						)]						)




				def __len__(				self						):



									"""simple docstring"""





									return len(self.dataset						)





class    __lowerCAmelCase					(	lowerCamelCase__			):




				def __init__(				self		,							_snake_case = None		,							_snake_case = None		,							_snake_case = None		,							_snake_case=None		,							):



									"""simple docstring"""





									if state_dict is None and save_folder is None:
														raise ValueError("""Need either a `state_dict` or a `save_folder` containing offloaded weights."""						)

									_lowerCAmelCase         =       {} if state_dict is None else state_dict
									_lowerCAmelCase         =       save_folder
									if index is None and save_folder is not None:
														with open(os.path.join(_snake_case		,							"""index.json"""						)						) as f:
																			_lowerCAmelCase         =       json.load(_snake_case						)
									_lowerCAmelCase         =       {} if index is None else index
									_lowerCAmelCase         =       list(self.state_dict.keys()						)
									self.all_keys.extend([key for key in self.index if key not in self.all_keys]						)
									_lowerCAmelCase         =       device




				def __getitem__(				self		,							_snake_case						):



									"""simple docstring"""





									if key in self.state_dict:
														return self.state_dict[key]
									_lowerCAmelCase         =       self.index[key]
									if weight_info.get("""safetensors_file"""						) is not None:
														if not is_safetensors_available():
																			raise ImportError("""These offloaded weights require the use of safetensors: `pip install safetensors`."""						)

														from safetensors import safe_open

														_lowerCAmelCase         =       """cpu""" if self.device is None else self.device
														with safe_open(weight_info["""safetensors_file"""]		,							framework="""pt"""		,							device=_snake_case						) as f:
																			_lowerCAmelCase         =       f.get_tensor(weight_info.get("""weight_name"""		,							_snake_case						)						)

														if "dtype" in weight_info:
																			return tensor.to(getattr(_snake_case		,							weight_info["""dtype"""]						)						)
														else:
																			return tensor

									_lowerCAmelCase         =       os.path.join(self.save_folder		,							F'{key}.dat'						)
									return load_offloaded_weight(_snake_case		,							_snake_case						)




				def __iter__(				self						):



									"""simple docstring"""





									return iter(self.all_keys						)




				def __len__(				self						):



									"""simple docstring"""





									return len(self.all_keys						)


def 						_UpperCAmelCase							( snake_case      ,		snake_case     ):





					"""simple docstring"""

					_lowerCAmelCase         =       {}
					for module_name in submodule_names:
										# We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the
										# submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance)
										result.update(
										    {
										        key: param
										        for key, param in state_dict.items()
										        if key == module_name or key.startswith(module_name + """."""     )
										    }     )
					return result



