



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


SCREAMING_SNAKE_CASE__     : Optional[Any]				=   """1.5.0"""

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







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

				SCREAMING_SNAKE_CASE_						:Any										=      version.parse(SCREAMING_SNAKE_CASE     )
				if parsed_optimum_version < version.parse(SCREAMING_SNAKE_CASE     ):
						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]'     )
		SCREAMING_SNAKE_CASE_						:Optional[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}',
		]
		SCREAMING_SNAKE_CASE_						:Tuple										=      subprocess.Popen(' '.join(SCREAMING_SNAKE_CASE     ) ,		stdout=subprocess.PIPE ,		shell=SCREAMING_SNAKE_CASE     )
		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  SCREAMING_SNAKE_CASE__ (				SCREAMING_SNAKE_CASE     ):
		SCREAMING_SNAKE_CASE_						: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=SCREAMING_SNAKE_CASE     )

		# Allocate the model
		SCREAMING_SNAKE_CASE_						:Any										=      FeaturesManager.get_model_from_feature(
		    args.feature ,		args.model ,		framework=args.framework ,		cache_dir=args.cache_dir     )

		SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:Optional[Any]										=      FeaturesManager.check_supported_model_or_raise(SCREAMING_SNAKE_CASE ,		feature=args.feature     )
		SCREAMING_SNAKE_CASE_						:Tuple										=      model_onnx_config(model.config     )

		if model_kind in ENCODER_DECODER_MODELS:
				SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      model.get_encoder()
				SCREAMING_SNAKE_CASE_						:Optional[Any]										=      model.get_decoder()

				SCREAMING_SNAKE_CASE_						:Dict										=      onnx_config.get_encoder_config(encoder_model.config     )
				SCREAMING_SNAKE_CASE_						:str										=      onnx_config.get_decoder_config(
				    encoder_model.config ,		decoder_model.config ,		feature=args.feature     )

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

				SCREAMING_SNAKE_CASE_						:Dict										=      AutoFeatureExtractor.from_pretrained(args.model     )

				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:str										=      export(
				    SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		args.opset ,		args.output.parent.joinpath('encoder_model.onnx'     ) ,		)

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

				SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      AutoTokenizer.from_pretrained(args.model     )

				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:List[Any]										=      export(
				    SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		args.opset ,		args.output.parent.joinpath('decoder_model.onnx'     ) ,		)

				validate_model_outputs(
				    SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		args.output.parent.joinpath('decoder_model.onnx'     ) ,		SCREAMING_SNAKE_CASE ,		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":
						SCREAMING_SNAKE_CASE_						:Dict										=      get_preprocessor(args.model     )
				elif args.preprocessor == "tokenizer":
						SCREAMING_SNAKE_CASE_						:int										=      AutoTokenizer.from_pretrained(args.model     )
				elif args.preprocessor == "image_processor":
						SCREAMING_SNAKE_CASE_						:Any										=      AutoImageProcessor.from_pretrained(args.model     )
				elif args.preprocessor == "feature_extractor":
						SCREAMING_SNAKE_CASE_						:Optional[Any]										=      AutoFeatureExtractor.from_pretrained(args.model     )
				elif args.preprocessor == "processor":
						SCREAMING_SNAKE_CASE_						:Union[str, Any]										=      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:
						SCREAMING_SNAKE_CASE_						:Tuple										=      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.'     )

				SCREAMING_SNAKE_CASE_						,		SCREAMING_SNAKE_CASE_						:str										=      export(
				    SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		args.opset ,		args.output ,		)

				if args.atol is None:
						SCREAMING_SNAKE_CASE_						:Tuple										=      onnx_config.atol_for_validation

				validate_model_outputs(SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		SCREAMING_SNAKE_CASE ,		args.output ,		SCREAMING_SNAKE_CASE ,		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.' ,		SCREAMING_SNAKE_CASE ,		)







def  SCREAMING_SNAKE_CASE__ (				):
		SCREAMING_SNAKE_CASE_						:Dict										=      ArgumentParser('Hugging Face Transformers ONNX exporter'     )
		parser.add_argument(
		    '-m' ,		'--model' ,		type=SCREAMING_SNAKE_CASE ,		required=SCREAMING_SNAKE_CASE ,		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=SCREAMING_SNAKE_CASE ,		default=SCREAMING_SNAKE_CASE ,		help='ONNX opset version to export the model with.'     )
		parser.add_argument(
		    '--atol' ,		type=SCREAMING_SNAKE_CASE ,		default=SCREAMING_SNAKE_CASE ,		help='Absolute difference tolerance when validating the model.'     )
		parser.add_argument(
		    '--framework' ,		type=SCREAMING_SNAKE_CASE ,		choices=['pt', 'tf'] ,		default=SCREAMING_SNAKE_CASE ,		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=SCREAMING_SNAKE_CASE ,		help='Path indicating where to store generated ONNX model.'     )
		parser.add_argument('--cache_dir' ,		type=SCREAMING_SNAKE_CASE ,		default=SCREAMING_SNAKE_CASE ,		help='Path indicating where to store cache.'     )
		parser.add_argument(
		    '--preprocessor' ,		type=SCREAMING_SNAKE_CASE ,		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.'
		    ) ,		)

		SCREAMING_SNAKE_CASE_						:List[str]										=      parser.parse_args()
		if args.export_with_transformers or not is_optimum_available():
				export_with_transformers(SCREAMING_SNAKE_CASE     )
		else:
				export_with_optimum(SCREAMING_SNAKE_CASE     )


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








# Usage:
# ./gen-card-allenai-wmt19.py

import os
from pathlib import Path



def      UpperCAmelCase						( lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__					,     lowerCAmelCase__	):


		'''simple docstring'''

		__A    =							{
		    "en": "Machine learning is great, isn't it?",
		    "ru": "Машинное обучение - это здорово, не так ли?",
		    "de": "Maschinelles Lernen ist großartig, nicht wahr?",
		}

		# BLUE scores as follows:
		# "pair": [fairseq, transformers]
		__A    =							{
		    "wmt19-de-en-6-6-base": [0, 38.37],
		    "wmt19-de-en-6-6-big": [0, 39.90],
		}
		__A    =							F"""{src_lang}-{tgt_lang}"""

		__A    =							F"""
---

language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt19
- allenai
license: apache-2.0
datasets:
- wmt19
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt19 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.

For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).

2 models are available:

* [wmt19-de-en-6-6-big](https://huggingface.co/allenai/wmt19-de-en-6-6-big)
* [wmt19-de-en-6-6-base](https://huggingface.co/allenai/wmt19-de-en-6-6-base)


## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = \"allenai/{model_name}\"
tokenizer = FSMTTokenizer.from_pretrained(mname)
model = FSMTForConditionalGeneration.from_pretrained(mname)

input = \"{texts[src_lang]}\"
input_ids = tokenizer.encode(input, return_tensors=\"pt\")
outputs = model.generate(input_ids)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded) # {texts[tgt_lang]}

```

#### Limitations and bias


## Training data

Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).

## Eval results

Here are the BLEU scores:

model   |  transformers
-------|---------
{model_name}  |  {scores[model_name][1]}

The score was calculated using this code:

```bash
git clone https://github.com/huggingface/transformers
cd transformers
export PAIR={pair}
export DATA_DIR=data/$PAIR
export SAVE_DIR=data/$PAIR
export BS=8
export NUM_BEAMS=5
mkdir -p $DATA_DIR
sacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
```

## Data Sources

- [training, etc.](http://www.statmt.org/wmt19/)
- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)


### BibTeX entry and citation info

```
@misc{{kasai2020deep,
    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
    year={{2020}},
    eprint={{2006.10369}},
    archivePrefix={{arXiv}},
    primaryClass={{cs.CL}}
}}
```

"""
		model_card_dir.mkdir(parents=lowerCAmelCase__					,     exist_ok=lowerCAmelCase__	)
		__A    =							os.path.join(lowerCAmelCase__					,     "README.md"	)
		print(F"""Generating {path}"""	)
		with open(lowerCAmelCase__					,     "w"					,     encoding="utf-8"	) as f:
				f.write(lowerCAmelCase__	)


# make sure we are under the root of the project
snake_case_   :	Optional[int]							      =Path(__file__).resolve().parent.parent.parent
snake_case_   :	Dict							      =repo_dir / '''model_cards'''

for model_name in ["wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big"]:
					snake_case_   :	Union[str, Any]							      =model_cards_dir / '''allenai''' / model_name
					write_model_card(model_card_dir, src_lang='''de''', tgt_lang='''en''', model_name=model_name)

