






from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
		from PIL import Image

		from transformers import ConvNextImageProcessor





class __lowerCamelCase			:





	"""simple docstring"""






	def __init__(							self	,   UpperCAmelCase	,   UpperCAmelCase=13	,   UpperCAmelCase=32	,   UpperCAmelCase=3	,   UpperCAmelCase=4	,   UpperCAmelCase=[10, 20, 30, 40]	,   UpperCAmelCase=[2, 2, 3, 2]	,   UpperCAmelCase=True	,   UpperCAmelCase=True	,   UpperCAmelCase=37	,   UpperCAmelCase="gelu"	,   UpperCAmelCase=10	,   UpperCAmelCase=0.02	,   UpperCAmelCase=3	,   UpperCAmelCase=None	,   ):
							"""simple docstring"""







							_UpperCAmelCase     =      parent
							_UpperCAmelCase     =      batch_size
							_UpperCAmelCase     =      image_size
							_UpperCAmelCase     =      num_channels
							_UpperCAmelCase     =      num_stages
							_UpperCAmelCase     =      hidden_sizes
							_UpperCAmelCase     =      depths
							_UpperCAmelCase     =      is_training
							_UpperCAmelCase     =      use_labels
							_UpperCAmelCase     =      intermediate_size
							_UpperCAmelCase     =      hidden_act
							_UpperCAmelCase     =      type_sequence_label_size
							_UpperCAmelCase     =      initializer_range
							_UpperCAmelCase     =      scope

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							_UpperCAmelCase     =      None
							if self.use_labels:
													_UpperCAmelCase     =      ids_tensor([self.batch_size]	,   self.type_sequence_label_size   )

							_UpperCAmelCase     =      self.get_config()

							return config, pixel_values, labels

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							return ConvNextConfig(
							    num_channels=self.num_channels	,   hidden_sizes=self.hidden_sizes	,   depths=self.depths	,   num_stages=self.num_stages	,   hidden_act=self.hidden_act	,   is_decoder=UpperCAmelCase	,   initializer_range=self.initializer_range	,   )

	def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
							"""simple docstring"""







							_UpperCAmelCase     =      TFConvNextModel(config=UpperCAmelCase   )
							_UpperCAmelCase     =      model(UpperCAmelCase	,   training=UpperCAmelCase   )
							# expected last hidden states: B, C, H // 32, W // 32
							self.parent.assertEqual(
							    result.last_hidden_state.shape	,   (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,   )

	def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
							"""simple docstring"""







							_UpperCAmelCase     =      self.type_sequence_label_size
							_UpperCAmelCase     =      TFConvNextForImageClassification(UpperCAmelCase   )
							_UpperCAmelCase     =      model(UpperCAmelCase	,   labels=UpperCAmelCase	,   training=UpperCAmelCase   )
							self.parent.assertEqual(result.logits.shape	,   (self.batch_size, self.type_sequence_label_size)   )

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      self.prepare_config_and_inputs()
							_UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase     =      config_and_inputs
							_UpperCAmelCase     =      {'pixel_values': pixel_values}
							return config, inputs_dict





@require_tf
class __lowerCamelCase			(				snake_case__					,	snake_case__					,	unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=				(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
	UpperCamelCase__								=				(
	    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
	    if is_tf_available()
	    else {}
	)

	UpperCamelCase__								=				False
	UpperCamelCase__								=				False
	UpperCamelCase__								=				False
	UpperCamelCase__								=				False
	UpperCamelCase__								=				False

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      TFConvNextModelTester(self   )
							_UpperCAmelCase     =      ConfigTester(
							    self	,   config_class=UpperCAmelCase	,   has_text_modality=UpperCAmelCase	,   hidden_size=37	,   )

	@unittest.skip(reason='ConvNext does not use inputs_embeds'   )
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							pass

	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0	,   reason='TF does not support backprop for grouped convolutions on CPU.'	,   )
	@slow
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							super().test_keras_fit()

	@unittest.skip(reason='ConvNext does not support input and output embeddings'   )
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							pass

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase ,			_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCAmelCase     =      model_class(UpperCAmelCase   )
													_UpperCAmelCase     =      inspect.signature(model.call   )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													_UpperCAmelCase     =      [*signature.parameters.keys()]

													_UpperCAmelCase     =      ['pixel_values']
													self.assertListEqual(arg_names[:1]	,   UpperCAmelCase   )

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCAmelCase   )

	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0	,   reason='TF does not support backprop for grouped convolutions on CPU.'	,   )
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							super().test_dataset_conversion()

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							def check_hidden_states_output(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													_UpperCAmelCase     =      model_class(UpperCAmelCase   )

													_UpperCAmelCase     =      model(**self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase   )   )
													_UpperCAmelCase     =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													_UpperCAmelCase     =      self.model_tester.num_stages
													self.assertEqual(len(UpperCAmelCase   )	,   expected_num_stages + 1   )

													# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
													self.assertListEqual(
													    list(hidden_states[0].shape[-2:]   )	,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]	,   )

							_UpperCAmelCase ,			_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													_UpperCAmelCase     =      True
													check_hidden_states_output(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   )

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													_UpperCAmelCase     =      True

													check_hidden_states_output(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   )

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase ,			_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs_for_common()

							def check_equivalence(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase={}   ):
													_UpperCAmelCase     =      model(UpperCAmelCase	,   return_dict=UpperCAmelCase	,   **UpperCAmelCase   )
													_UpperCAmelCase     =      model(UpperCAmelCase	,   return_dict=UpperCAmelCase	,   **UpperCAmelCase   ).to_tuple()

													def recursive_check(UpperCAmelCase	,   UpperCAmelCase   ):
																			if isinstance(UpperCAmelCase	,   (List, Tuple)   ):
																									for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase	,   UpperCAmelCase   ):
																															recursive_check(UpperCAmelCase	,   UpperCAmelCase   )
																			elif tuple_object is None:
																									return
																			else:
																									self.assertTrue(
																									    all(tf.equal(UpperCAmelCase	,   UpperCAmelCase   )   )	,   msg=(
																									        'Tuple and dict output are not equal. Difference:'
																									        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object   )   )}"""
																									    )	,   )

																			recursive_check(UpperCAmelCase	,   UpperCAmelCase   )

							for model_class in self.all_model_classes:
													_UpperCAmelCase     =      model_class(UpperCAmelCase   )

													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase   )
													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase   )
													check_equivalence(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   )

													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase	,   return_labels=UpperCAmelCase   )
													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase	,   return_labels=UpperCAmelCase   )
													check_equivalence(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   )

													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase   )
													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase   )
													check_equivalence(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   {'output_hidden_states': True}   )

													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase	,   return_labels=UpperCAmelCase   )
													_UpperCAmelCase     =      self._prepare_for_class(UpperCAmelCase	,   UpperCAmelCase	,   return_labels=UpperCAmelCase   )
													check_equivalence(UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   {'output_hidden_states': True}   )

	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase   )

	@slow
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'   )
							self.assertIsNotNone(UpperCAmelCase   )



def __A   (				)->  Optional[int]:





						"""simple docstring"""



						_UpperCAmelCase     =      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
						return image





@require_tf
@require_vision
class __lowerCamelCase			(				unittest.TestCase):





	"""simple docstring"""






	@cached_property
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'   ) if is_vision_available() else None

	@slow
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'   )

							_UpperCAmelCase     =      self.default_image_processor
							_UpperCAmelCase     =      prepare_img()
							_UpperCAmelCase     =      image_processor(images=UpperCAmelCase	,   return_tensors='tf'   )

							# forward pass
							_UpperCAmelCase     =      model(**UpperCAmelCase   )

							# verify the logits
							_UpperCAmelCase     =      tf.TensorShape((1, 1000)   )
							self.assertEqual(outputs.logits.shape	,   UpperCAmelCase   )

							_UpperCAmelCase     =      tf.constant([-0.02_60, -0.47_39, 0.19_11]   )

							tf.debugging.assert_near(outputs.logits[0, :3]	,   UpperCAmelCase	,   atol=1e-4   )












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

import os
from pathlib import Path


def __A   (				__lowerCAmelCase			,		__lowerCAmelCase			,		__lowerCAmelCase			,		__lowerCAmelCase     )->  List[Any]:





						"""simple docstring"""



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

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

						_UpperCAmelCase     =      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     )
						_UpperCAmelCase     =      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
_a				     =  Path(__file__).resolve().parent.parent.parent
_a				     =  repo_dir / '''model_cards'''

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