





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
			import jax
			import jaxlib

_a						=   get_logger()

_a						=   None






class       __A					(					TensorFormatter[Mapping, """jax.Array""", Mapping]				):

			'''simple docstring'''







			def __init__(					self ,						__lowerCAmelCase=None ,						__lowerCAmelCase=None ,						**__lowerCAmelCase							):



				'''simple docstring'''







				super().__init__(features=SCREAMING_SNAKE_CASE_							)
				import jax
				from jaxlib.xla_client import Device

				if isinstance(SCREAMING_SNAKE_CASE_ ,						SCREAMING_SNAKE_CASE_							):
					raise ValueError(
					    F'Expected {device} to be a `str` not {type(SCREAMING_SNAKE_CASE_							)}, as `jaxlib.xla_extension.Device` '
					    '''is not serializable neither with `pickle` nor with `dill`. Instead you can surround '''
					    '''the device with `str()` to get its string identifier that will be internally mapped '''
					    '''to the actual `jaxlib.xla_extension.Device`.'''							)
				lowerCamelCase__              =	device if isinstance(SCREAMING_SNAKE_CASE_ ,						SCREAMING_SNAKE_CASE_							) else str(jax.devices()[0]							)
				# using global variable since `jaxlib.xla_extension.Device` is not serializable neither
				# with `pickle` nor with `dill`, so we need to use a global variable instead
				global DEVICE_MAPPING
				if DEVICE_MAPPING is None:
					lowerCamelCase__              =	self._map_devices_to_str()
				if self.device not in list(DEVICE_MAPPING.keys()							):
					logger.warning(
					    F'Device with string identifier {self.device} not listed among the available '
					    F'devices: {list(DEVICE_MAPPING.keys()							)}, so falling back to the default '
					    F'device: {str(jax.devices()[0]							)}.'							)
					lowerCamelCase__              =	str(jax.devices()[0]							)
				lowerCamelCase__              =	jnp_array_kwargs





			@staticmethod
			def 	__lowerCamelCase       (					):



				'''simple docstring'''







				import jax

				return {str(SCREAMING_SNAKE_CASE_							): device for device in jax.devices()}





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				import jax
				import jax.numpy as jnp

				if isinstance(SCREAMING_SNAKE_CASE_ ,						SCREAMING_SNAKE_CASE_							) and column:
					if all(
					    isinstance(SCREAMING_SNAKE_CASE_ ,						jax.Array							) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column							):
						return jnp.stack(SCREAMING_SNAKE_CASE_ ,						axis=0							)
				return column





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				import jax
				import jax.numpy as jnp

				if isinstance(SCREAMING_SNAKE_CASE_ ,						(str, bytes, type(SCREAMING_SNAKE_CASE_							))							):
					return value
				elif isinstance(SCREAMING_SNAKE_CASE_ ,						(np.character, np.ndarray)							) and np.issubdtype(value.dtype ,						np.character							):
					return value.tolist()

				lowerCamelCase__              =	{}

				if isinstance(SCREAMING_SNAKE_CASE_ ,						(np.number, np.ndarray)							) and np.issubdtype(value.dtype ,						np.integer							):
					# the default int precision depends on the jax config
					# see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
					if jax.config.jax_enable_xaa:
						lowerCamelCase__              =	{'''dtype''': jnp.intaa}
					else:
						lowerCamelCase__              =	{'''dtype''': jnp.intaa}
				elif isinstance(SCREAMING_SNAKE_CASE_ ,						(np.number, np.ndarray)							) and np.issubdtype(value.dtype ,						np.floating							):
					lowerCamelCase__              =	{'''dtype''': jnp.floataa}
				elif config.PIL_AVAILABLE and "PIL" in sys.modules:
					import PIL.Image

					if isinstance(SCREAMING_SNAKE_CASE_ ,						PIL.Image.Image							):
						lowerCamelCase__              =	np.asarray(SCREAMING_SNAKE_CASE_							)

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
				global DEVICE_MAPPING
				if DEVICE_MAPPING is None:
					lowerCamelCase__              =	self._map_devices_to_str()

				with jax.default_device(DEVICE_MAPPING[self.device]							):
					# calling jnp.array on a np.ndarray does copy the data
					# see https://github.com/google/jax/issues/4486
					return jnp.array(SCREAMING_SNAKE_CASE_ ,						**{**default_dtype, **self.jnp_array_kwargs}							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				import jax

				# support for torch, tf, jax etc.
				if config.TORCH_AVAILABLE and "torch" in sys.modules:
					import torch

					if isinstance(SCREAMING_SNAKE_CASE_ ,						torch.Tensor							):
						return self._tensorize(data_struct.detach().cpu().numpy()[()]							)
				if hasattr(SCREAMING_SNAKE_CASE_ ,						'''__array__'''							) and not isinstance(SCREAMING_SNAKE_CASE_ ,						jax.Array							):
					lowerCamelCase__              =	data_struct.__array__()
				# support for nested types like struct of list of struct
				if isinstance(SCREAMING_SNAKE_CASE_ ,						np.ndarray							):
					if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
						return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_							) for substruct in data_struct]							)
				elif isinstance(SCREAMING_SNAKE_CASE_ ,						(list, tuple)							):
					return self._consolidate([self.recursive_tensorize(SCREAMING_SNAKE_CASE_							) for substruct in data_struct]							)
				return self._tensorize(SCREAMING_SNAKE_CASE_							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				return map_nested(self._recursive_tensorize ,						SCREAMING_SNAKE_CASE_ ,						map_list=SCREAMING_SNAKE_CASE_							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	self.numpy_arrow_extractor().extract_row(SCREAMING_SNAKE_CASE_							)
				lowerCamelCase__              =	self.python_features_decoder.decode_row(SCREAMING_SNAKE_CASE_							)
				return self.recursive_tensorize(SCREAMING_SNAKE_CASE_							)





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	self.numpy_arrow_extractor().extract_column(SCREAMING_SNAKE_CASE_							)
				lowerCamelCase__              =	self.python_features_decoder.decode_column(SCREAMING_SNAKE_CASE_ ,						pa_table.column_names[0]							)
				lowerCamelCase__              =	self.recursive_tensorize(SCREAMING_SNAKE_CASE_							)
				lowerCamelCase__              =	self._consolidate(SCREAMING_SNAKE_CASE_							)
				return column





			def 	__lowerCamelCase       (					self ,						__lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__              =	self.numpy_arrow_extractor().extract_batch(SCREAMING_SNAKE_CASE_							)
				lowerCamelCase__              =	self.python_features_decoder.decode_batch(SCREAMING_SNAKE_CASE_							)
				lowerCamelCase__              =	self.recursive_tensorize(SCREAMING_SNAKE_CASE_							)
				for column_name in batch:
					lowerCamelCase__              =	self._consolidate(batch[column_name]							)
				return batch








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

import os
from pathlib import Path





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case							)       ->   Any:







	'''simple docstring'''







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

	# BLUE scores as follows:
	# "pair": [fairseq, transformers]
	lowerCamelCase__              =	{
	    '''wmt16-en-de-dist-12-1''': [2_8.3, 2_7.5_2],
	    '''wmt16-en-de-dist-6-1''': [2_7.4, 2_7.1_1],
	    '''wmt16-en-de-12-1''': [2_6.9, 2_5.7_5],
	}
	lowerCamelCase__              =	F'{src_lang}-{tgt_lang}'

	lowerCamelCase__              =	F'\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = "allenai/{model_name}"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = "{texts[src_lang]}"\ninput_ids = tokenizer.encode(input, return_tensors="pt")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel   | fairseq | transformers\n-------|---------|----------\n{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH="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\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n    year={{2020}},\n    eprint={{2006.10369}},\n    archivePrefix={{arXiv}},\n    primaryClass={{cs.CL}}\n}}\n```\n\n'
	model_card_dir.mkdir(parents=__snake_case ,exist_ok=__snake_case							)
	lowerCamelCase__              =	os.path.join(__snake_case ,'''README.md'''							)
	print(F'Generating {path}'							)
	with open(__snake_case ,'''w''' ,encoding='''utf-8'''							) as f:
		f.write(__snake_case							)


# make sure we are under the root of the project
_a						=   Path(__file__).resolve().parent.parent.parent
_a						=   repo_dir / "model_cards"

for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
			_a						=   model_cards_dir / "allenai" / model_name
			write_model_card(model_card_dir, src_lang="en", tgt_lang="de", model_name=model_name)



