


import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
							import torch

							from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer

@require_torch
class   A__							(						unittest.TestCase					):




						@slow
						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       List[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=XLMProphetNetForConditionalGeneration.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased'''					)
										model.to(_a					)

										# encoder-decoder outputs
										_SCREAMING_SNAKE_CASE     					=torch.tensor([[17, 9_6208, 10_3471, 2]]					).to(_a					)
										_SCREAMING_SNAKE_CASE     					=torch.tensor(
										    [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]					).to(_a					)
										_SCREAMING_SNAKE_CASE     					=model(
										    input_ids=_a			,      attention_mask=_a			,      encoder_outputs=_a			,      decoder_input_ids=_a					)
										_SCREAMING_SNAKE_CASE     					=output[0]
										_SCREAMING_SNAKE_CASE     					=torch.Size((1, 14, 25_0012)					)
										self.assertEqual(output_predited_logis.shape			,      _a					)
										_SCREAMING_SNAKE_CASE     					=torch.tensor(
										    [[[-6.39_86, -8.23_91, 12.51_89], [-6.32_89, -8.08_64, 12.62_11], [-6.24_18, -8.04_45, 12.79_68]]]					).to(_a					)
										self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]			,      _a			,      atol=1E-4					)					)

										# encoder outputs
										_SCREAMING_SNAKE_CASE     					=model.prophetnet.encoder(_a					)[0]
										_SCREAMING_SNAKE_CASE     					=torch.tensor(
										    [[[-1.42_60, -0.76_28, 0.84_53], [-1.47_19, -0.13_91, 0.78_07], [-1.76_78, 0.01_14, 0.46_46]]]					).to(_a					)
										_SCREAMING_SNAKE_CASE     					=torch.Size((1, 4, 1024)					)
										self.assertEqual(encoder_outputs.shape			,      _a					)
										self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]			,      _a			,      atol=1E-4					)					)

										# decoder outputs
										_SCREAMING_SNAKE_CASE     					=model.prophetnet.decoder(
										    _a			,      encoder_hidden_states=_a			,      )
										_SCREAMING_SNAKE_CASE     					=decoder_outputs[1].view(1			,      model.config.ngram			,      14			,      -1					)
										_SCREAMING_SNAKE_CASE     					=model.lm_head(_a					)
										_SCREAMING_SNAKE_CASE     					=predicting_streams_logits[:, 0]
										self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]			,      _a			,      atol=1E-4					)					)




						@slow
						def 							__UpperCamelCase			(    self   : Any					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=XLMProphetNetForConditionalGeneration.from_pretrained(
										    '''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''					)
										model.to(_a					)

										_SCREAMING_SNAKE_CASE     					=torch.tensor([[17, 9_6208, 10_3471, 2]]					).to(_a					)
										_SCREAMING_SNAKE_CASE     					=torch.tensor(
										    [[2, 250, 9953, 34, 6_9489, 1620, 32, 11_8424, 624, 210, 105, 2913, 1032, 351]]					).to(_a					)
										_SCREAMING_SNAKE_CASE     					=model(
										    input_ids=_a			,      attention_mask=_a			,      encoder_outputs=_a			,      decoder_input_ids=_a					)
										_SCREAMING_SNAKE_CASE     					=output[0]
										_SCREAMING_SNAKE_CASE     					=torch.Size((1, 14, 25_0012)					)
										self.assertEqual(output_predited_logis.shape			,      _a					)
										# compare the actual values for a slice.
										_SCREAMING_SNAKE_CASE     					=torch.tensor(
										    [[[-9.22_53, -9.71_73, -6.35_29], [-7.67_01, -9.01_45, -1.93_82], [-8.01_95, -7.00_04, -0.15_23]]]					).to(_a					)

										self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]			,      _a			,      atol=1E-4					)					)




						@slow
						def 							__UpperCamelCase			(    self   : Any					)							->       Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=XLMProphetNetForConditionalGeneration.from_pretrained(
										    '''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''					)
										model.to(_a					)
										_SCREAMING_SNAKE_CASE     					=512

										_SCREAMING_SNAKE_CASE     					=XLMProphetNetTokenizer.from_pretrained('''microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'''					)

										_SCREAMING_SNAKE_CASE     					=(
										    '''Microsoft Corporation intends to officially end free support for the Windows 7 operating system after'''
										    ''' January 14, 2020, according to the official portal of the organization. From that day, users of this'''
										    ''' system will not be able to receive security updates, which could make their computers vulnerable to'''
										    ''' cyber attacks.'''
										)
										_SCREAMING_SNAKE_CASE     					=(
										    '''орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7'''
										    ''' после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи'''
										    ''' этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми'''
										    ''' к кибератакам.'''
										)
										_SCREAMING_SNAKE_CASE     					=(
										    '''根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。'''
										)

										_SCREAMING_SNAKE_CASE     					=tokenizer(
										    [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]			,      padding=_a			,      max_length=255			,      return_tensors='''pt'''					).input_ids
										_SCREAMING_SNAKE_CASE     					=input_ids.to(_a					)

										_SCREAMING_SNAKE_CASE     					=model.generate(
										    _a			,      num_beams=10			,      length_penalty=1.0			,      no_repeat_ngram_size=3			,      early_stopping=_a					)
										_SCREAMING_SNAKE_CASE     					=[tokenizer.decode(_a			,      skip_special_tokens=_a					) for g in summary_ids]
										_SCREAMING_SNAKE_CASE     					='''Microsoft to end Windows 7 free support after January 14, 2020'''
										_SCREAMING_SNAKE_CASE     					='''Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года'''
										_SCREAMING_SNAKE_CASE     					='''微软打算终止对Windows 7操作系统的免费支持'''
										self.assertListEqual(
										    [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]			,      _a			,      )

										_SCREAMING_SNAKE_CASE     					=model.generate(
										    _a			,      num_beams=1			,      length_penalty=1.0			,      no_repeat_ngram_size=3			,      early_stopping=_a					)
										_SCREAMING_SNAKE_CASE     					=[
										    tokenizer.convert_ids_to_tokens(_a			,      skip_special_tokens=_a					) for g in summary_ids_beama
										]
										_SCREAMING_SNAKE_CASE     					='''▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7'''.split(''' '''					)
										_SCREAMING_SNAKE_CASE     					='''▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года'''.split(
										    ''' '''					)
										_SCREAMING_SNAKE_CASE     					='''微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持'''.split(''' '''					)
										self.assertListEqual(
										    [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]			,      _a			,      )



import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class   A__							(						unittest.TestCase					):




						def __init__(    self   : List[Any]			,      _a   : Optional[Any]			,      _a   : int=3			,      _a   : int=32			,      _a   : str=3			,      _a   : List[str]=10			,      _a   : Optional[Any]=[10, 20, 30, 40]			,      _a   : Tuple=[1, 1, 2, 1]			,      _a   : Optional[Any]=True			,      _a   : Optional[int]=True			,      _a   : Any="relu"			,      _a   : Any=3			,      _a   : Tuple=None			,      )							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=parent
										_SCREAMING_SNAKE_CASE     					=batch_size
										_SCREAMING_SNAKE_CASE     					=image_size
										_SCREAMING_SNAKE_CASE     					=num_channels
										_SCREAMING_SNAKE_CASE     					=embeddings_size
										_SCREAMING_SNAKE_CASE     					=hidden_sizes
										_SCREAMING_SNAKE_CASE     					=depths
										_SCREAMING_SNAKE_CASE     					=is_training
										_SCREAMING_SNAKE_CASE     					=use_labels
										_SCREAMING_SNAKE_CASE     					=hidden_act
										_SCREAMING_SNAKE_CASE     					=num_labels
										_SCREAMING_SNAKE_CASE     					=scope
										_SCREAMING_SNAKE_CASE     					=len(_a					)




						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       str:


										"""simple docstring"""





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

										_SCREAMING_SNAKE_CASE     					=self.get_config()

										return config, pixel_values




						def 							__UpperCamelCase			(    self   : List[str]					)							->       Dict:


										"""simple docstring"""





										return ResNetConfig(
										    num_channels=self.num_channels			,      embeddings_size=self.embeddings_size			,      hidden_sizes=self.hidden_sizes			,      depths=self.depths			,      hidden_act=self.hidden_act			,      num_labels=self.num_labels			,      image_size=self.image_size			,      )




						def 							__UpperCamelCase			(    self   : Optional[Any]			,      _a   : Union[str, Any]			,      _a   : List[Any]					)							->       Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModel(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)

										# Output shape (b, c, h, w)
										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   : int			,      _a   : str			,      _a   : str					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.num_labels
										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)
										self.parent.assertEqual(result.logits.shape			,      (self.batch_size, self.num_labels)					)




						def 							__UpperCamelCase			(    self   : Tuple					)							->       Optional[Any]:


										"""simple docstring"""





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

@require_flax
class   A__							(						UpperCamelCase__				,       unittest.TestCase					):
						UpperCAmelCase     =  (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False




						def 							__UpperCamelCase			(    self   : str					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModelTester(self					)
										_SCREAMING_SNAKE_CASE     					=ConfigTester(self			,      config_class=_a			,      has_text_modality=_a					)




						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       int:


										"""simple docstring"""





										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()




						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       Union[str, Any]:


										"""simple docstring"""





										return




						def 							__UpperCamelCase			(    self   : int					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a					)




						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a					)




						@unittest.skip(reason='''ResNet does not use inputs_embeds'''					)
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       List[Any]:


										"""simple docstring"""





										pass




						@unittest.skip(reason='''ResNet does not support input and output embeddings'''					)
						def 							__UpperCamelCase			(    self   : Dict					)							->       Dict:


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : Any					)							->       int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

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

														_SCREAMING_SNAKE_CASE     					=['''pixel_values''']
														self.assertListEqual(arg_names[:1]			,      _a					)




						def 							__UpperCamelCase			(    self   : Dict					)							->       Union[str, Any]:


										"""simple docstring"""





										def check_hidden_states_output(_a   : Optional[Any]			,      _a   : Tuple			,      _a   : Optional[Any]					):
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)

														_SCREAMING_SNAKE_CASE     					=model(**self._prepare_for_class(_a			,      _a					)					)

														_SCREAMING_SNAKE_CASE     					=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

														_SCREAMING_SNAKE_CASE     					=self.model_tester.num_stages
														self.assertEqual(len(_a					)			,      expected_num_stages + 1					)




						@unittest.skip(reason='''ResNet does not use feedforward chunking'''					)
						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       Dict:


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : List[Any]					)							->       Any:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__					):
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(_a			,      _a					)
																		_SCREAMING_SNAKE_CASE     					=model_class(_a					)

																		@jax.jit
																		def model_jitted(_a   : Optional[Any]			,      **_a   : Any					):
																						return model(pixel_values=_a			,      **_a					)

																		with self.subTest('''JIT Enabled'''					):
																						_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		with self.subTest('''JIT Disabled'''					):
																						with jax.disable_jit():
																										_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		self.assertEqual(len(_a					)			,      len(_a					)					)
																		for jitted_output, output in zip(_a			,      _a					):
																						self.assertEqual(jitted_output.shape			,      output.shape					)







def   lowerCamelCase(				):
				_SCREAMING_SNAKE_CASE     					=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image


@require_flax
class   A__							(						unittest.TestCase					):




						@cached_property
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       Any:


										"""simple docstring"""





										return AutoImageProcessor.from_pretrained('''microsoft/resnet-50'''					) if is_vision_available() else None




						@slow
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification.from_pretrained('''microsoft/resnet-50'''					)

										_SCREAMING_SNAKE_CASE     					=self.default_image_processor
										_SCREAMING_SNAKE_CASE     					=prepare_img()
										_SCREAMING_SNAKE_CASE     					=image_processor(images=_a			,      return_tensors='''np'''					)

										_SCREAMING_SNAKE_CASE     					=model(**_a					)

										# verify the logits
										_SCREAMING_SNAKE_CASE     					=(1, 1000)
										self.assertEqual(outputs.logits.shape			,      _a					)

										_SCREAMING_SNAKE_CASE     					=jnp.array([-11.10_69, -9.78_77, -8.37_77]					)

										self.assertTrue(jnp.allclose(outputs.logits[0, :3]			,      _a			,      atol=1E-4					)					)