




import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
						from transformers import (
						    FlaxBertModel,
						    FlaxCLIPVisionModel,
						    FlaxVisionTextDualEncoderModel,
						    FlaxViTModel,
						    VisionTextDualEncoderConfig,
						    VisionTextDualEncoderProcessor,
						)
						from transformers.modeling_flax_pytorch_utils import (
						    convert_pytorch_state_dict_to_flax,
						    load_flax_weights_in_pytorch_model,
						)


if is_torch_available():
						import torch

						from transformers import VisionTextDualEncoderModel

if is_vision_available():
						from PIL import Image





def        __UpperCAmelCase						(							lowerCamelCase_ :     List[str]  )       ->  Dict:







			"""simple docstring"""





			if isinstance(lowerCamelCase_  ,							collections.abc.Iterable  ):
						return x
			return (x, x)







@require_flax
class 				lowerCAmelCase_       :






				def 		snake_case	(			self      ,snake_case__      ,snake_case__ ):
							pass






				def 		snake_case	(			self ):
							pass






				def 		snake_case	(			self ):
							pass






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : int					  =      np.abs((a - b) ).max()
							self.assertLessEqual(snake_case__      ,snake_case__      ,F'Difference between torch and flax is {diff} (>= {tol}).' )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__=None      ,**snake_case__ ):
							SCREAMING_SNAKE_CASE_   : Dict					  =      VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : str					  =      FlaxVisionTextDualEncoderModel(snake_case__ )

							SCREAMING_SNAKE_CASE_   : int					  =      model(input_ids=snake_case__      ,pixel_values=snake_case__      ,attention_mask=snake_case__ )

							self.assertEqual(output['text_embeds'].shape      ,(input_ids.shape[0], config.projection_dim) )
							self.assertEqual(output['image_embeds'].shape      ,(pixel_values.shape[0], config.projection_dim) )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__=None      ,**snake_case__ ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : int					  =      self.get_vision_text_model(snake_case__      ,snake_case__ )
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      {'vision_model': vision_model, 'text_model': text_model}
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      model(input_ids=snake_case__      ,pixel_values=snake_case__      ,attention_mask=snake_case__ )

							self.assertEqual(output['text_embeds'].shape      ,(input_ids.shape[0], model.config.projection_dim) )
							self.assertEqual(output['image_embeds'].shape      ,(pixel_values.shape[0], model.config.projection_dim) )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__=None      ,**snake_case__ ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      self.get_vision_text_model(snake_case__      ,snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      {'vision_model': vision_model, 'text_model': text_model}
							SCREAMING_SNAKE_CASE_   : str					  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

							SCREAMING_SNAKE_CASE_   : Any					  =      model(input_ids=snake_case__      ,pixel_values=snake_case__      ,attention_mask=snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      output[0]

							with tempfile.TemporaryDirectory() as tmpdirname:
										model.save_pretrained(snake_case__ )
										SCREAMING_SNAKE_CASE_   : str					  =      FlaxVisionTextDualEncoderModel.from_pretrained(snake_case__ )

										SCREAMING_SNAKE_CASE_   : int					  =      model(input_ids=snake_case__      ,pixel_values=snake_case__      ,attention_mask=snake_case__ )
										SCREAMING_SNAKE_CASE_   : int					  =      after_output[0]
										SCREAMING_SNAKE_CASE_   : Tuple					  =      np.amax(np.abs(out_a - out_a ) )
										self.assertLessEqual(snake_case__      ,1E-3 )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__      ,snake_case__=None      ,**snake_case__ ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      self.get_vision_text_model(snake_case__      ,snake_case__ )
							SCREAMING_SNAKE_CASE_   : Any					  =      {'vision_model': vision_model, 'text_model': text_model}
							SCREAMING_SNAKE_CASE_   : int					  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[str]					  =      model(
							    input_ids=snake_case__      ,pixel_values=snake_case__      ,attention_mask=snake_case__      ,output_attentions=snake_case__ )

							SCREAMING_SNAKE_CASE_   : int					  =      output.vision_model_output.attentions
							self.assertEqual(len(snake_case__ )      ,vision_config.num_hidden_layers )

							# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
							SCREAMING_SNAKE_CASE_   : Tuple					  =      to_atuple(vision_model.config.image_size )
							SCREAMING_SNAKE_CASE_   : int					  =      to_atuple(vision_model.config.patch_size )
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
							SCREAMING_SNAKE_CASE_   : str					  =      num_patches + 1
							self.assertEqual(vision_attentions[0].shape[-3:]      ,(vision_config.num_attention_heads, seq_len, seq_len) )

							SCREAMING_SNAKE_CASE_   : str					  =      output.text_model_output.attentions
							self.assertEqual(len(snake_case__ )      ,text_config.num_hidden_layers )

							self.assertEqual(
							    text_attentions[0].shape[-3:]      ,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])      ,)






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							pt_model.to(snake_case__ )
							pt_model.eval()

							# prepare inputs
							SCREAMING_SNAKE_CASE_   : int					  =      inputs_dict
							SCREAMING_SNAKE_CASE_   : Tuple					  =      {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()}

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_   : List[str]					  =      pt_model(**snake_case__ ).to_tuple()

							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      fx_model(**snake_case__ ).to_tuple()
							self.assertEqual(len(snake_case__ )      ,len(snake_case__ )      ,'Output lengths differ between Flax and PyTorch' )
							for fx_output, pt_output in zip(fx_outputs[:4]      ,pt_outputs[:4] ):
										self.assert_almost_equals(snake_case__      ,pt_output.numpy()      ,4E-2 )

							# PT -> Flax
							with tempfile.TemporaryDirectory() as tmpdirname:
										pt_model.save_pretrained(snake_case__ )
										SCREAMING_SNAKE_CASE_   : Any					  =      FlaxVisionTextDualEncoderModel.from_pretrained(snake_case__      ,from_pt=snake_case__ )

							SCREAMING_SNAKE_CASE_   : Tuple					  =      fx_model_loaded(**snake_case__ ).to_tuple()
							self.assertEqual(len(snake_case__ )      ,len(snake_case__ )      ,'Output lengths differ between Flax and PyTorch' )
							for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]      ,pt_outputs[:4] ):
										self.assert_almost_equals(snake_case__      ,pt_output.numpy()      ,4E-2 )

							# Flax -> PT
							with tempfile.TemporaryDirectory() as tmpdirname:
										fx_model.save_pretrained(snake_case__ )
										SCREAMING_SNAKE_CASE_   : str					  =      VisionTextDualEncoderModel.from_pretrained(snake_case__      ,from_flax=snake_case__ )

							pt_model_loaded.to(snake_case__ )
							pt_model_loaded.eval()

							with torch.no_grad():
										SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      pt_model_loaded(**snake_case__ ).to_tuple()

							self.assertEqual(len(snake_case__ )      ,len(snake_case__ )      ,'Output lengths differ between Flax and PyTorch' )
							for fx_output, pt_output_loaded in zip(fx_outputs[:4]      ,pt_outputs_loaded[:4] ):
										self.assert_almost_equals(snake_case__      ,pt_output_loaded.numpy()      ,4E-2 )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : List[str]					  =      VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : int					  =      VisionTextDualEncoderModel(snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      FlaxVisionTextDualEncoderModel(snake_case__ )

							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      convert_pytorch_state_dict_to_flax(pt_model.state_dict()      ,snake_case__ )
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      fx_state

							self.check_pt_flax_equivalence(snake_case__      ,snake_case__      ,snake_case__ )






				def 		snake_case	(			self      ,snake_case__      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : Dict					  =      VisionTextDualEncoderConfig.from_vision_text_configs(snake_case__      ,snake_case__ )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      VisionTextDualEncoderModel(snake_case__ )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      FlaxVisionTextDualEncoderModel(snake_case__ )

							SCREAMING_SNAKE_CASE_   : Tuple					  =      load_flax_weights_in_pytorch_model(snake_case__      ,fx_model.params )

							self.check_pt_flax_equivalence(snake_case__      ,snake_case__      ,snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      self.prepare_config_and_inputs()
							self.check_model_from_pretrained_configs(**snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      self.prepare_config_and_inputs()
							self.check_vision_text_dual_encoder_from_pretrained(**snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Tuple					  =      self.prepare_config_and_inputs()
							self.check_save_load(**snake_case__ )






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : int					  =      self.prepare_config_and_inputs()
							self.check_vision_text_output_attention(**snake_case__ )






				@is_pt_flax_cross_test
				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : str					  =      self.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      config_inputs_dict.pop('vision_config' )
							SCREAMING_SNAKE_CASE_   : Tuple					  =      config_inputs_dict.pop('text_config' )

							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      config_inputs_dict

							self.check_equivalence_pt_to_flax(snake_case__      ,snake_case__      ,snake_case__ )
							self.check_equivalence_flax_to_pt(snake_case__      ,snake_case__      ,snake_case__ )






				@slow
				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      self.get_pretrained_model_and_inputs()

							SCREAMING_SNAKE_CASE_   : Any					  =      model_a(**snake_case__ )
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      outputs[0]

							with tempfile.TemporaryDirectory() as tmp_dirname:
										model_a.save_pretrained(snake_case__ )
										SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      FlaxVisionTextDualEncoderModel.from_pretrained(snake_case__ )

										SCREAMING_SNAKE_CASE_   : List[str]					  =      model_a(**snake_case__ )
										SCREAMING_SNAKE_CASE_   : int					  =      after_outputs[0]
										SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      np.amax(np.abs(out_a - out_a ) )
										self.assertLessEqual(snake_case__      ,1E-5 )







@require_flax
class 				lowerCAmelCase_       (					lowerCamelCase_						,     unittest.TestCase							):






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Dict					  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
							    'hf-internal-testing/tiny-random-vit'      ,'hf-internal-testing/tiny-bert'      ,vision_from_pt=snake_case__      ,text_from_pt=snake_case__      ,)
							SCREAMING_SNAKE_CASE_   : List[Any]					  =      13
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      floats_tensor(
							    [
							        batch_size,
							        model.config.vision_config.num_channels,
							        model.config.vision_config.image_size,
							        model.config.vision_config.image_size,
							    ] )
							SCREAMING_SNAKE_CASE_   : Any					  =      ids_tensor([batch_size, 4]      ,model.config.text_config.vocab_size )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      random_attention_mask([batch_size, 4] )
							SCREAMING_SNAKE_CASE_   : Tuple					  =      {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

							return model, inputs






				def 		snake_case	(			self      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : int					  =      FlaxViTModel(snake_case__ )
							SCREAMING_SNAKE_CASE_   : str					  =      FlaxBertModel(snake_case__ )
							return vision_model, text_model






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Dict					  =      FlaxViTModelTester(self )
							SCREAMING_SNAKE_CASE_   : int					  =      FlaxBertModelTester(self )
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      vit_model_tester.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_   : List[str]					  =      bert_model_tester.prepare_config_and_inputs()

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Tuple					  =      vision_config_and_inputs

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      text_config_and_inputs

							# make sure that cross attention layers are added
							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": attention_mask,
							    "input_ids": input_ids,
							    "token_type_ids": token_type_ids,
							}







@require_torch
class 				lowerCAmelCase_       (					lowerCamelCase_						,     unittest.TestCase							):






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Tuple					  =      FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
							    'hf-internal-testing/tiny-random-clip'      ,'hf-internal-testing/tiny-bert'      ,vision_from_pt=snake_case__      ,text_from_pt=snake_case__      ,)
							SCREAMING_SNAKE_CASE_   : Any					  =      13
							SCREAMING_SNAKE_CASE_   : str					  =      floats_tensor(
							    [
							        batch_size,
							        model.config.vision_config.num_channels,
							        model.config.vision_config.image_size,
							        model.config.vision_config.image_size,
							    ] )
							SCREAMING_SNAKE_CASE_   : Dict					  =      ids_tensor([batch_size, 4]      ,model.config.text_config.vocab_size )
							SCREAMING_SNAKE_CASE_   : int					  =      random_attention_mask([batch_size, 4] )
							SCREAMING_SNAKE_CASE_   : Any					  =      {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

							return model, inputs






				def 		snake_case	(			self      ,snake_case__      ,snake_case__ ):
							SCREAMING_SNAKE_CASE_   : int					  =      FlaxCLIPVisionModel(snake_case__ )
							SCREAMING_SNAKE_CASE_   : Dict					  =      FlaxBertModel(snake_case__ )
							return vision_model, text_model






				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : Tuple					  =      FlaxCLIPVisionModelTester(self )
							SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      FlaxBertModelTester(self )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      clip_model_tester.prepare_config_and_inputs()
							SCREAMING_SNAKE_CASE_   : Tuple					  =      bert_model_tester.prepare_config_and_inputs()

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : Optional[Any]					  =      vision_config_and_inputs

							SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_  ,    SCREAMING_SNAKE_CASE_   : str					  =      text_config_and_inputs

							# make sure that cross attention layers are added
							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": attention_mask,
							    "input_ids": input_ids,
							    "token_type_ids": token_type_ids,
							}







@require_flax
@require_vision
class 				lowerCAmelCase_       (					unittest.TestCase							):






				@slow
				def 		snake_case	(			self ):
							SCREAMING_SNAKE_CASE_   : int					  =      FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'      ,logit_scale_init_value=1.0 )
							SCREAMING_SNAKE_CASE_   : Union[str, Any]					  =      VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
							SCREAMING_SNAKE_CASE_   : Optional[int]					  =      processor(
							    text=['una foto di un gatto', 'una foto di un cane']      ,images=snake_case__      ,padding=snake_case__      ,return_tensors='np' )

							SCREAMING_SNAKE_CASE_   : List[Any]					  =      model(**snake_case__ )

							# verify the logits
							self.assertEqual(outputs.logits_per_image.shape      ,(inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) )
							self.assertEqual(
							    outputs.logits_per_text.shape      ,(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])      ,)

							SCREAMING_SNAKE_CASE_   : Dict					  =      np.array([[1.2284727, 0.3104122]] )

							self.assertTrue(np.allclose(outputs.logits_per_image      ,snake_case__      ,atol=1E-3 ) )






"""simple docstring"""





import inspect
import tempfile
import unittest

from huggingface_hub import hf_hub_download

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


__UpperCamelCase    : Optional[Any]				 =						1e-4

if is_torch_available():
							import torch

							from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel
							from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder







@require_torch
class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							str  ,lowercase_     :							Optional[Any]  ,lowercase_     :							Optional[Any]=1_6  ,lowercase_     :							int=1_3  ,lowercase_     :							Optional[int]=7  ,lowercase_     :							int=1_4  ,lowercase_     :							str=1_0  ,lowercase_     :							List[Any]=1_9  ,lowercase_     :							Any=5  ,lowercase_     :							Any=4  ,lowercase_     :							List[str]=True  ,lowercase_     :							Union[str, Any]=1_6  ,lowercase_     :							Tuple=2  ,lowercase_     :							str=4  ,lowercase_     :							Tuple=4  ,lowercase_     :							int="gelu"  ,lowercase_     :							Any=0.1  ,lowercase_     :							int=0.1  ,lowercase_     :							Optional[int]=[1, 2, 3, 4, 5]  ,lowercase_     :							List[Any]=2_5  ,lowercase_     :							Union[str, Any]=5  ,):
						lowerCAmelCase__      :		List[str]    							=      d_model
						lowerCAmelCase__      :		Optional[Any]    							=      parent
						lowerCAmelCase__      :		Dict    							=      batch_size
						lowerCAmelCase__      :		Any    							=      prediction_length
						lowerCAmelCase__      :		str    							=      context_length
						lowerCAmelCase__      :		int    							=      cardinality
						lowerCAmelCase__      :		Dict    							=      num_time_features
						lowerCAmelCase__      :		str    							=      lags_sequence
						lowerCAmelCase__      :		int    							=      embedding_dimension
						lowerCAmelCase__      :		Dict    							=      is_training
						lowerCAmelCase__      :		Optional[Any]    							=      hidden_size
						lowerCAmelCase__      :		Optional[int]    							=      num_hidden_layers
						lowerCAmelCase__      :		List[str]    							=      num_attention_heads
						lowerCAmelCase__      :		int    							=      intermediate_size
						lowerCAmelCase__      :		List[str]    							=      hidden_act
						lowerCAmelCase__      :		Dict    							=      hidden_dropout_prob
						lowerCAmelCase__      :		Optional[int]    							=      attention_probs_dropout_prob

						lowerCAmelCase__      :		Tuple    							=      context_length
						lowerCAmelCase__      :		Optional[Any]    							=      prediction_length + label_length
						lowerCAmelCase__      :		Union[str, Any]    							=      label_length

						lowerCAmelCase__      :		Optional[int]    							=      moving_average
						lowerCAmelCase__      :		Dict    							=      autocorrelation_factor







					def 			__lowerCAmelCase					(			self     :							Tuple						):
						return AutoformerConfig(
						    d_model=self.d_model  ,encoder_layers=self.num_hidden_layers  ,decoder_layers=self.num_hidden_layers  ,encoder_attention_heads=self.num_attention_heads  ,decoder_attention_heads=self.num_attention_heads  ,encoder_ffn_dim=self.intermediate_size  ,decoder_ffn_dim=self.intermediate_size  ,dropout=self.hidden_dropout_prob  ,attention_dropout=self.attention_probs_dropout_prob  ,prediction_length=self.prediction_length  ,context_length=self.context_length  ,label_length=self.label_length  ,lags_sequence=self.lags_sequence  ,num_time_features=self.num_time_features  ,num_static_categorical_features=1  ,cardinality=[self.cardinality]  ,embedding_dimension=[self.embedding_dimension]  ,moving_average=self.moving_average  ,)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]  ,lowercase_     :							str						):
						lowerCAmelCase__      :		str    							=      config.context_length + max(config.lags_sequence						)

						lowerCAmelCase__      :		Optional[int]    							=      ids_tensor([self.batch_size, 1]  ,config.cardinality[0]						)
						lowerCAmelCase__      :		int    							=      floats_tensor([self.batch_size, _past_length, config.num_time_features]						)
						lowerCAmelCase__      :		Any    							=      floats_tensor([self.batch_size, _past_length]						)
						lowerCAmelCase__      :		List[str]    							=      floats_tensor([self.batch_size, _past_length]						) > 0.5

						# decoder inputs
						lowerCAmelCase__      :		List[str]    							=      floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]						)
						lowerCAmelCase__      :		Tuple    							=      floats_tensor([self.batch_size, config.prediction_length]						)

						lowerCAmelCase__      :		Optional[int]    							=      {
						    '''past_values''': past_values,
						    '''static_categorical_features''': static_categorical_features,
						    '''past_time_features''': past_time_features,
						    '''past_observed_mask''': past_observed_mask,
						    '''future_time_features''': future_time_features,
						    '''future_values''': future_values,
						}
						return inputs_dict







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		Dict    							=      self.get_config()
						lowerCAmelCase__      :		Dict    							=      self.prepare_autoformer_inputs_dict(lowercase_						)
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      self.prepare_config_and_inputs()
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							Optional[int]  ,lowercase_     :							Union[str, Any]						):
						lowerCAmelCase__      :		Any    							=      AutoformerModel(config=lowercase_						).to(lowercase_						).eval()
						lowerCAmelCase__      :		Tuple    							=      model(**lowercase_						)

						lowerCAmelCase__      :		Any    							=      outputs.encoder_last_hidden_state
						lowerCAmelCase__      :		str    							=      outputs.last_hidden_state

						with tempfile.TemporaryDirectory() as tmpdirname:
							lowerCAmelCase__      :		List[Any]    							=      model.get_encoder()
							encoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerEncoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      model.create_network_inputs(**lowercase_						)
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[int]    							=      model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]						)

						lowerCAmelCase__      :		int    							=      torch.cat(
						    (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])  ,dim=-1  ,)
						lowerCAmelCase__      :		Dict    							=      encoder(inputs_embeds=lowercase_						)[0]
						self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3						)

						lowerCAmelCase__      :		Optional[int]    							=      (
						    torch.mean(transformer_inputs[:, : config.context_length, ...]  ,dim=1						)
						    .unsqueeze(1						)
						    .repeat(1  ,config.prediction_length  ,1						)
						)
						lowerCAmelCase__      :		Optional[Any]    							=      torch.zeros(
						    [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]]  ,device=enc_input.device  ,)

						lowerCAmelCase__      :		List[Any]    							=      torch.cat(
						    (
						        torch.cat((seasonal_input[:, -config.label_length :, ...], zeros)  ,dim=1						),
						        feature[:, config.context_length - config.label_length :, ...],
						    )  ,dim=-1  ,)
						lowerCAmelCase__      :		Any    							=      torch.cat(
						    (
						        torch.cat((trend_input[:, -config.label_length :, ...], mean)  ,dim=1						),
						        feature[:, config.context_length - config.label_length :, ...],
						    )  ,dim=-1  ,)

						with tempfile.TemporaryDirectory() as tmpdirname:
							lowerCAmelCase__      :		Optional[int]    							=      model.get_decoder()
							decoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Tuple    							=      AutoformerDecoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      decoder(
						    trend=lowercase_  ,inputs_embeds=lowercase_  ,encoder_hidden_states=lowercase_  ,)[0]

						self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3						)







@require_torch
class 							SCREAMING_SNAKE_CASE   (						a_       ,				a_       ,				unittest.TestCase			):






					"""simple docstring"""



					lowercase__												=			(AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
					lowercase__												=			(AutoformerForPrediction,) if is_torch_available() else ()
					lowercase__												=			{"feature-extraction": AutoformerModel} if is_torch_available() else {}
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False







					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		int    							=      AutoformerModelTester(self						)
						lowerCAmelCase__      :		Optional[int]    							=      ConfigTester(self  ,config_class=lowercase_  ,has_text_modality=lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						self.config_tester.run_common_tests()







					def 			__lowerCAmelCase					(			self     :							str						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Union[str, Any]    							=      self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(lowercase_						)
								lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      model_class.from_pretrained(lowercase_  ,output_loading_info=lowercase_						)
							self.assertEqual(info['''missing_keys''']  ,[]						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		Tuple    							=      self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*lowercase_						)







					@unittest.skip(reason='''Model has no tokens embeddings'''						)
					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						pass







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		List[str]    							=      inspect.signature(getattr(lowercase_  ,'''forward'''						)						)
						# The main input is the name of the argument after `self`
						lowerCAmelCase__      :		Any    							=      list(model_signature.parameters.keys()						)[1]
						self.assertEqual(AutoformerModel.main_input_name  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[Any]    							=      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		int    							=      model_class(lowercase_						)
							lowerCAmelCase__      :		Optional[Any]    							=      inspect.signature(model.forward						)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							lowerCAmelCase__      :		int    							=      [*signature.parameters.keys()]

							lowerCAmelCase__      :		Optional[int]    							=      [
							    '''past_values''',
							    '''past_time_features''',
							    '''past_observed_mask''',
							    '''static_categorical_features''',
							    '''static_real_features''',
							    '''future_values''',
							    '''future_time_features''',
							]

							if model.__class__.__name__ in ["AutoformerForPrediction"]:
								expected_arg_names.append('''future_observed_mask'''						)

							expected_arg_names.extend(
							    [
							        '''decoder_attention_mask''',
							        '''head_mask''',
							        '''decoder_head_mask''',
							        '''cross_attn_head_mask''',
							        '''encoder_outputs''',
							        '''past_key_values''',
							        '''output_hidden_states''',
							        '''output_attentions''',
							        '''use_cache''',
							        '''return_dict''',
							    ]						)

							self.assertListEqual(arg_names[: len(lowercase_						)]  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      self.model_tester.prepare_config_and_inputs_for_common()
						lowerCAmelCase__      :		List[str]    							=      True

						lowerCAmelCase__      :		int    							=      getattr(self.model_tester  ,'''seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''decoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Tuple    							=      getattr(self.model_tester  ,'''encoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		List[Any]    							=      getattr(self.model_tester  ,'''d_model'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''num_attention_heads'''  ,lowercase_						)
						lowerCAmelCase__      :		str    							=      d_model // num_attention_heads

						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		List[str]    							=      True
							lowerCAmelCase__      :		Optional[int]    							=      False
							lowerCAmelCase__      :		Optional[Any]    							=      True
							lowerCAmelCase__      :		Any    							=      model_class(lowercase_						)
							model.to(lowercase_						)
							model.eval()
							with torch.no_grad():
								lowerCAmelCase__      :		str    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)
							lowerCAmelCase__      :		Optional[Any]    							=      outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)

							# check that output_attentions also work using config
							del inputs_dict["output_attentions"]
							lowerCAmelCase__      :		List[str]    							=      True
							lowerCAmelCase__      :		Union[str, Any]    							=      model_class(lowercase_						)
							model.to(lowercase_						)
							model.eval()
							with torch.no_grad():
								lowerCAmelCase__      :		Dict    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)
							lowerCAmelCase__      :		int    							=      outputs.encoder_attentions
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)

							self.assertListEqual(
							    list(attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, encoder_seq_length, dim]  ,)
							lowerCAmelCase__      :		Tuple    							=      len(lowercase_						)

							lowerCAmelCase__      :		List[str]    							=      7

							if "last_hidden_state" in outputs:
								correct_outlen += 1

							if "trend" in outputs:
								correct_outlen += 1

							if "past_key_values" in outputs:
								correct_outlen += 1  # past_key_values have been returned

							if "loss" in outputs:
								correct_outlen += 1

							if "params" in outputs:
								correct_outlen += 1

							self.assertEqual(lowercase_  ,lowercase_						)

							# decoder attentions
							lowerCAmelCase__      :		str    							=      outputs.decoder_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
							self.assertListEqual(
							    list(decoder_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, decoder_seq_length, dim]  ,)

							# cross attentions
							lowerCAmelCase__      :		Any    							=      outputs.cross_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
							self.assertListEqual(
							    list(cross_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, decoder_seq_length, dim]  ,)

						# Check attention is always last and order is fine
						lowerCAmelCase__      :		str    							=      True
						lowerCAmelCase__      :		Tuple    							=      True
						lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)
						model.to(lowercase_						)
						model.eval()
						with torch.no_grad():
							lowerCAmelCase__      :		Optional[Any]    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)

						self.assertEqual(out_len + 2  ,len(lowercase_						)						)

						lowerCAmelCase__      :		Optional[Any]    							=      outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions

						self.assertEqual(len(lowercase_						)  ,self.model_tester.num_hidden_layers						)
						self.assertListEqual(
						    list(self_attentions[0].shape[-3:]						)  ,[self.model_tester.num_attention_heads, encoder_seq_length, dim]  ,)







					@is_flaky()
					def 			__lowerCAmelCase					(			self     :							str						):
						super().test_retain_grad_hidden_states_attentions()

def     __SCREAMING_SNAKE_CASE    ( A_="train-batch.pt"					):
	lowerCAmelCase__      :		Any    							=      hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch'''		,	filename=A_		,	repo_type='''dataset'''					)
	lowerCAmelCase__      :		Union[str, Any]    							=      torch.load(A_		,	map_location=A_					)
	return batch







@require_torch
@slow
class 							SCREAMING_SNAKE_CASE   (						unittest.TestCase			):






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		int    							=      prepare_batch()

						with torch.no_grad():
							lowerCAmelCase__      :		Any    							=      model(
							    past_values=batch['''past_values''']  ,past_time_features=batch['''past_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,static_categorical_features=batch['''static_categorical_features''']  ,future_values=batch['''future_values''']  ,future_time_features=batch['''future_time_features''']  ,)[0]

						lowerCAmelCase__      :		Dict    							=      torch.Size(
						    (6_4, model.config.prediction_length + model.config.label_length, model.config.feature_size)						)
						self.assertEqual(output.shape  ,lowercase_						)

						lowerCAmelCase__      :		Optional[int]    							=      torch.tensor(
						    [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]]  ,device=lowercase_						)
						self.assertTrue(torch.allclose(output[0, :3, :3]  ,lowercase_  ,atol=lowercase_						)						)







					def 			__lowerCAmelCase					(			self     :							Dict						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Optional[int]    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		str    							=      model(
							    past_values=batch['''past_values''']  ,past_time_features=batch['''past_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,static_categorical_features=batch['''static_categorical_features''']  ,).encoder_last_hidden_state
						lowerCAmelCase__      :		Any    							=      torch.Size((6_4, model.config.context_length, model.config.d_model)						)
						self.assertEqual(output.shape  ,lowercase_						)

						lowerCAmelCase__      :		Optional[int]    							=      torch.tensor(
						    [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]]  ,device=lowercase_						)
						self.assertTrue(torch.allclose(output[0, :3, :3]  ,lowercase_  ,atol=lowercase_						)						)







					def 			__lowerCAmelCase					(			self     :							List[str]						):
						lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Dict    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		int    							=      model.generate(
							    static_categorical_features=batch['''static_categorical_features''']  ,past_time_features=batch['''past_time_features''']  ,past_values=batch['''past_values''']  ,future_time_features=batch['''future_time_features''']  ,past_observed_mask=batch['''past_observed_mask''']  ,)
						lowerCAmelCase__      :		List[Any]    							=      torch.Size((6_4, model.config.num_parallel_samples, model.config.prediction_length)						)
						self.assertEqual(outputs.sequences.shape  ,lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      torch.tensor([3130.6763, 4056.5293, 7053.0786]  ,device=lowercase_						)
						lowerCAmelCase__      :		Dict    							=      outputs.sequences.mean(dim=1						)
						self.assertTrue(torch.allclose(mean_prediction[0, -3:]  ,lowercase_  ,rtol=1E-1						)						)




