



"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
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.models.swin.modeling_tf_swin import (
						    TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFSwinForImageClassification,
						    TFSwinForMaskedImageModeling,
						    TFSwinModel,
						)


if is_vision_available():
						from PIL import Image

						from transformers import AutoImageProcessor
class 							lowerCamelCase    :






					'''simple docstring'''





					def __init__(			self:				Optional[int]		,	snake_case:				List[Any]		,	snake_case:				List[Any]=13		,	snake_case:				str=32		,	snake_case:				Optional[int]=2		,	snake_case:				int=3		,	snake_case:				Union[str, Any]=16		,	snake_case:				Any=[1, 2, 1]		,	snake_case:				Optional[int]=[2, 2, 4]		,	snake_case:				Tuple=2		,	snake_case:				Any=2.0		,	snake_case:				Dict=True		,	snake_case:				int=0.0		,	snake_case:				Optional[Any]=0.0		,	snake_case:				Any=0.1		,	snake_case:				Optional[Any]="gelu"		,	snake_case:				List[str]=False		,	snake_case:				Tuple=True		,	snake_case:				Tuple=0.0_2		,	snake_case:				List[str]=1E-5		,	snake_case:				Dict=True		,	snake_case:				Optional[int]=None		,	snake_case:				Optional[Any]=True		,	snake_case:				List[Any]=10		,	snake_case:				Optional[int]=8		,	)  ->      None:
											snake_case_					:List[Any]		=     parent
											snake_case_					:Optional[Any]		=     batch_size
											snake_case_					:Any		=     image_size
											snake_case_					:Any		=     patch_size
											snake_case_					:List[str]		=     num_channels
											snake_case_					:Union[str, Any]		=     embed_dim
											snake_case_					:str		=     depths
											snake_case_					:Dict		=     num_heads
											snake_case_					:Optional[int]		=     window_size
											snake_case_					:Dict		=     mlp_ratio
											snake_case_					:Optional[Any]		=     qkv_bias
											snake_case_					:List[Any]		=     hidden_dropout_prob
											snake_case_					:List[str]		=     attention_probs_dropout_prob
											snake_case_					:str		=     drop_path_rate
											snake_case_					:List[Any]		=     hidden_act
											snake_case_					:List[Any]		=     use_absolute_embeddings
											snake_case_					:Dict		=     patch_norm
											snake_case_					:List[Any]		=     layer_norm_eps
											snake_case_					:Optional[int]		=     initializer_range
											snake_case_					:Dict		=     is_training
											snake_case_					:Union[str, Any]		=     scope
											snake_case_					:Dict		=     use_labels
											snake_case_					:str		=     type_sequence_label_size
											snake_case_					:List[Any]		=     encoder_stride






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      int:
											snake_case_					:List[str]		=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

											snake_case_					:Optional[Any]		=     None
											if self.use_labels:
																	snake_case_					:Optional[Any]		=     ids_tensor([self.batch_size]		,	self.type_sequence_label_size		)

											snake_case_					:Dict		=     self.get_config()

											return config, pixel_values, labels






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      Tuple:
											return SwinConfig(
											    image_size=self.image_size		,	patch_size=self.patch_size		,	num_channels=self.num_channels		,	embed_dim=self.embed_dim		,	depths=self.depths		,	num_heads=self.num_heads		,	window_size=self.window_size		,	mlp_ratio=self.mlp_ratio		,	qkv_bias=self.qkv_bias		,	hidden_dropout_prob=self.hidden_dropout_prob		,	attention_probs_dropout_prob=self.attention_probs_dropout_prob		,	drop_path_rate=self.drop_path_rate		,	hidden_act=self.hidden_act		,	use_absolute_embeddings=self.use_absolute_embeddings		,	path_norm=self.patch_norm		,	layer_norm_eps=self.layer_norm_eps		,	initializer_range=self.initializer_range		,	encoder_stride=self.encoder_stride		,	)






					def   lowerCAmelCase_							(			self:				int		,	snake_case:				Optional[Any]		,	snake_case:				int		,	snake_case:				Optional[int]		)  ->      Optional[int]:
											snake_case_					:int		=     TFSwinModel(config=snake_case		)
											snake_case_					:Optional[int]		=     model(snake_case		)

											snake_case_					:Optional[int]		=     ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths		) - 1))
											snake_case_					:str		=     int(config.embed_dim * 2 ** (len(config.depths		) - 1)		)

											self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, expected_seq_len, expected_dim)		)






					def   lowerCAmelCase_							(			self:				Optional[int]		,	snake_case:				Union[str, Any]		,	snake_case:				str		,	snake_case:				Union[str, Any]		)  ->      Optional[int]:
											snake_case_					:Optional[Any]		=     TFSwinForMaskedImageModeling(config=snake_case		)
											snake_case_					:Union[str, Any]		=     model(snake_case		)
											self.parent.assertEqual(
											    result.logits.shape		,	(self.batch_size, self.num_channels, self.image_size, self.image_size)		)

											# test greyscale images
											snake_case_					:str		=     1
											snake_case_					:int		=     TFSwinForMaskedImageModeling(snake_case		)

											snake_case_					:List[str]		=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
											snake_case_					:Optional[Any]		=     model(snake_case		)
											self.parent.assertEqual(result.logits.shape		,	(self.batch_size, 1, self.image_size, self.image_size)		)






					def   lowerCAmelCase_							(			self:				Optional[Any]		,	snake_case:				int		,	snake_case:				str		,	snake_case:				Optional[int]		)  ->      Optional[int]:
											snake_case_					:Union[str, Any]		=     self.type_sequence_label_size
											snake_case_					:Optional[int]		=     TFSwinForImageClassification(snake_case		)
											snake_case_					:Tuple		=     model(snake_case		,	labels=snake_case		)
											self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)		)

											# test greyscale images
											snake_case_					:int		=     1
											snake_case_					:Optional[int]		=     TFSwinForImageClassification(snake_case		)
											snake_case_					:Dict		=     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
											snake_case_					:Union[str, Any]		=     model(snake_case		)
											self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)		)






					def   lowerCAmelCase_							(			self:				List[str]		)  ->      Optional[Any]:
											snake_case_					:Union[str, Any]		=     self.prepare_config_and_inputs()
											snake_case_,			snake_case_,			snake_case_					:List[Any]		=     config_and_inputs
											snake_case_					:str		=     {"""pixel_values""": pixel_values}
											return config, inputs_dict

@require_tf
class 							lowerCamelCase    (     _lowerCAmelCase       ,		_lowerCAmelCase       ,		unittest.TestCase							):






					'''simple docstring'''





					_A						:     Any		=	(
					    (
					        TFSwinModel,
					        TFSwinForImageClassification,
					        TFSwinForMaskedImageModeling,
					    )
					    if is_tf_available()
					    else ()
					)
					_A						:     Optional[int]		=	(
					    {"""feature-extraction""": TFSwinModel, """image-classification""": TFSwinForImageClassification}
					    if is_tf_available()
					    else {}
					)

					_A						:     int		=	False
					_A						:     Optional[Any]		=	False
					_A						:     str		=	False
					_A						:     Any		=	False






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      Tuple:
											snake_case_					:int		=     TFSwinModelTester(self		)
											snake_case_					:List[str]		=     ConfigTester(self		,	config_class=snake_case		,	embed_dim=37		)






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      Any:
											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   lowerCAmelCase_							(			self:				List[str]		)  ->      str:
											return






					def   lowerCAmelCase_							(			self:				Dict		)  ->      str:
											snake_case_					:Union[str, Any]		=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case		)






					def   lowerCAmelCase_							(			self:				Any		)  ->      Dict:
											snake_case_					:int		=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_image_modeling(*snake_case		)






					def   lowerCAmelCase_							(			self:				List[Any]		)  ->      Union[str, Any]:
											snake_case_					:Tuple		=     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*snake_case		)






					@unittest.skip(reason="""Swin does not use inputs_embeds"""		)
					def   lowerCAmelCase_							(			self:				List[str]		)  ->      List[Any]:
											pass






					def   lowerCAmelCase_							(			self:				str		)  ->      Tuple:
											snake_case_,			snake_case_					:List[Any]		=     self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	snake_case_					:str		=     model_class(snake_case		)
																	self.assertIsInstance(model.get_input_embeddings()		,	tf.keras.layers.Layer		)
																	snake_case_					:int		=     model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(snake_case		,	tf.keras.layers.Dense		)		)






					def   lowerCAmelCase_							(			self:				List[str]		)  ->      Dict:
											snake_case_,			snake_case_					:Optional[Any]		=     self.model_tester.prepare_config_and_inputs_for_common()

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

																	snake_case_					:Optional[Any]		=     ["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]		,	snake_case		)






					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      int:
											snake_case_,			snake_case_					:List[str]		=     self.model_tester.prepare_config_and_inputs_for_common()
											snake_case_					:Dict		=     True

											for model_class in self.all_model_classes:
																	snake_case_					:Union[str, Any]		=     True
																	snake_case_					:Union[str, Any]		=     False
																	snake_case_					:int		=     True
																	snake_case_					:int		=     model_class(snake_case		)
																	snake_case_					:Optional[int]		=     model(**self._prepare_for_class(snake_case		,	snake_case		)		)
																	snake_case_					:Dict		=     outputs.attentions
																	snake_case_					:Optional[int]		=     len(self.model_tester.depths		)
																	self.assertEqual(len(snake_case		)		,	snake_case		)

																	# check that output_attentions also work using config
																	del inputs_dict["output_attentions"]
																	snake_case_					:List[str]		=     True
																	snake_case_					:Optional[Any]		=     config.window_size**2
																	snake_case_					:Any		=     model_class(snake_case		)
																	snake_case_					:Optional[Any]		=     model(**self._prepare_for_class(snake_case		,	snake_case		)		)
																	snake_case_					:Optional[int]		=     outputs.attentions
																	self.assertEqual(len(snake_case		)		,	snake_case		)

																	self.assertListEqual(
																	    list(attentions[0].shape[-3:]		)		,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,	)
																	snake_case_					:str		=     len(snake_case		)

																	# Check attention is always last and order is fine
																	snake_case_					:str		=     True
																	snake_case_					:Dict		=     True
																	snake_case_					:Optional[int]		=     model_class(snake_case		)
																	snake_case_					:List[str]		=     model(**self._prepare_for_class(snake_case		,	snake_case		)		)

																	if hasattr(self.model_tester		,	"""num_hidden_states_types"""		):
																							snake_case_					:Any		=     self.model_tester.num_hidden_states_types
																	else:
																							# also another +1 for reshaped_hidden_states
																							snake_case_					:Dict		=     2
																	self.assertEqual(out_len + added_hidden_states		,	len(snake_case		)		)

																	snake_case_					:Optional[int]		=     outputs.attentions

																	self.assertEqual(len(snake_case		)		,	snake_case		)

																	self.assertListEqual(
																	    list(self_attentions[0].shape[-3:]		)		,	[self.model_tester.num_heads[0], window_size_squared, window_size_squared]		,	)






					def   lowerCAmelCase_							(			self:				Optional[int]		,	snake_case:				Optional[int]		,	snake_case:				List[str]		,	snake_case:				Tuple		,	snake_case:				str		)  ->      Any:
											snake_case_					:List[Any]		=     model_class(snake_case		)
											snake_case_					:Any		=     model(**self._prepare_for_class(snake_case		,	snake_case		)		)
											snake_case_					:Optional[int]		=     outputs.hidden_states

											snake_case_					:int		=     getattr(
											    self.model_tester		,	"""expected_num_hidden_layers"""		,	len(self.model_tester.depths		) + 1		)
											self.assertEqual(len(snake_case		)		,	snake_case		)

											# Swin has a different seq_length
											snake_case_					:List[Any]		=     to_atuple(config.patch_size		)

											snake_case_					:Any		=     (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

											self.assertListEqual(
											    list(hidden_states[0].shape[-2:]		)		,	[num_patches, self.model_tester.embed_dim]		,	)

											snake_case_					:Union[str, Any]		=     outputs.reshaped_hidden_states
											self.assertEqual(len(snake_case		)		,	snake_case		)

											snake_case_,			snake_case_,			snake_case_,			snake_case_					:Union[str, Any]		=     reshaped_hidden_states[0].shape

											snake_case_					:Dict		=     tf.reshape(reshaped_hidden_states[0]		,	(batch_size, num_channels, height * width)		)
											snake_case_					:List[str]		=     tf.transpose(snake_case		,	(0, 2, 1)		)

											self.assertListEqual(
											    list(reshaped_hidden_states.shape[-2:]		)		,	[num_patches, self.model_tester.embed_dim]		,	)






					def   lowerCAmelCase_							(			self:				Optional[int]		)  ->      str:
											snake_case_,			snake_case_					:List[Any]		=     self.model_tester.prepare_config_and_inputs_for_common()

											snake_case_					:Optional[Any]		=     to_atuple(self.model_tester.image_size		)

											for model_class in self.all_model_classes:
																	snake_case_					:Dict		=     True
																	self.check_hidden_states_output(snake_case		,	snake_case		,	snake_case		,	snake_case		)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	snake_case_					:List[Any]		=     True

																	self.check_hidden_states_output(snake_case		,	snake_case		,	snake_case		,	snake_case		)






					def   lowerCAmelCase_							(			self:				Tuple		)  ->      Tuple:
											snake_case_,			snake_case_					:List[str]		=     self.model_tester.prepare_config_and_inputs_for_common()
											snake_case_					:Tuple		=     3

											snake_case_					:Union[str, Any]		=     to_atuple(self.model_tester.image_size		)
											snake_case_					:List[Any]		=     to_atuple(config.patch_size		)

											snake_case_					:int		=     image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
											snake_case_					:Dict		=     image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

											for model_class in self.all_model_classes:
																	snake_case_					:Any		=     True
																	self.check_hidden_states_output(snake_case		,	snake_case		,	snake_case		,	(padded_height, padded_width)		)

																	# check that output_hidden_states also work using config
																	del inputs_dict["output_hidden_states"]
																	snake_case_					:str		=     True
																	self.check_hidden_states_output(snake_case		,	snake_case		,	snake_case		,	(padded_height, padded_width)		)






					@slow
					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      Optional[int]:
											for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	snake_case_					:Optional[Any]		=     TFSwinModel.from_pretrained(snake_case		)
																	self.assertIsNotNone(snake_case		)

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






					'''simple docstring'''





					@cached_property
					def   lowerCAmelCase_							(			self:				Optional[Any]		)  ->      Any:
											return (
											    AutoImageProcessor.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""		)
											    if is_vision_available()
											    else None
											)






					@slow
					def   lowerCAmelCase_							(			self:				List[str]		)  ->      Optional[Any]:
											snake_case_					:str		=     TFSwinForImageClassification.from_pretrained("""microsoft/swin-tiny-patch4-window7-224"""		)
											snake_case_					:List[str]		=     self.default_image_processor

											snake_case_					:List[str]		=     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
											snake_case_					:List[str]		=     image_processor(images=snake_case		,	return_tensors="""tf"""		)

											# forward pass
											snake_case_					:List[Any]		=     model(snake_case		)

											# verify the logits
											snake_case_					:List[str]		=     tf.TensorShape((1, 1_000)		)
											self.assertEqual(outputs.logits.shape		,	snake_case		)
											snake_case_					:Optional[int]		=     tf.constant([-0.0_9_4_8, -0.6_4_5_4, -0.0_9_2_1]		)
											self.assertTrue(np.allclose(outputs.logits[0, :3]		,	snake_case		,	atol=1E-4		)		)

'''simple docstring'''
import tempfile
import unittest

import numpy as np

import transformers
from transformers import GPTaConfig, GPTaTokenizer, is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax, slow

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


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

  from transformers.modeling_flax_pytorch_utils import (
      convert_pytorch_state_dict_to_flax,
      load_flax_weights_in_pytorch_model,
  )
  from transformers.models.gpta.modeling_flax_gpta import FlaxGPTaLMHeadModel, FlaxGPTaModel

if is_torch_available():
  import torch






class       __lowercase		:







     """simple docstring"""






     def __init__(		self  ,      _lowerCamelCase  ,      _lowerCamelCase=1_4  ,      _lowerCamelCase=7  ,      _lowerCamelCase=True  ,      _lowerCamelCase=True  ,      _lowerCamelCase=False  ,      _lowerCamelCase=True  ,      _lowerCamelCase=9_9  ,      _lowerCamelCase=3_2  ,      _lowerCamelCase=5  ,      _lowerCamelCase=4  ,      _lowerCamelCase=3_7  ,      _lowerCamelCase="gelu"  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=5_1_2  ,      _lowerCamelCase=0.0_2  ,      ):
         __UpperCamelCase						:						int		     =	parent
         __UpperCamelCase						:						Union[str, Any]		     =	batch_size
         __UpperCamelCase						:						Tuple		     =	seq_length
         __UpperCamelCase						:						Tuple		     =	is_training
         __UpperCamelCase						:						str		     =	use_input_mask
         __UpperCamelCase						:						int		     =	use_token_type_ids
         __UpperCamelCase						:						List[Any]		     =	use_labels
         __UpperCamelCase						:						Tuple		     =	vocab_size
         __UpperCamelCase						:						Any		     =	hidden_size
         __UpperCamelCase						:						int		     =	num_hidden_layers
         __UpperCamelCase						:						List[Any]		     =	num_attention_heads
         __UpperCamelCase						:						str		     =	intermediate_size
         __UpperCamelCase						:						Any		     =	hidden_act
         __UpperCamelCase						:						Tuple		     =	hidden_dropout_prob
         __UpperCamelCase						:						Any		     =	attention_probs_dropout_prob
         __UpperCamelCase						:						Union[str, Any]		     =	max_position_embeddings
         __UpperCamelCase						:						Optional[int]		     =	initializer_range
         __UpperCamelCase						:						str		     =	None
         __UpperCamelCase						:						Dict		     =	vocab_size - 1
         __UpperCamelCase						:						Tuple		     =	vocab_size - 1
         __UpperCamelCase						:						int		     =	vocab_size - 1







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      self.vocab_size     )

         __UpperCamelCase						:						str		     =	None
         if self.use_input_mask:
             __UpperCamelCase						:						List[Any]		     =	random_attention_mask([self.batch_size, self.seq_length]     )

         __UpperCamelCase						:						Optional[Any]		     =	GPTaConfig(
             vocab_size=self.vocab_size  ,      n_embd=self.hidden_size  ,      n_layer=self.num_hidden_layers  ,      n_head=self.num_attention_heads  ,      n_positions=self.max_position_embeddings  ,      use_cache=_lowerCamelCase  ,      bos_token_id=self.bos_token_id  ,      eos_token_id=self.eos_token_id  ,      pad_token_id=self.pad_token_id  ,      )

         return (config, input_ids, input_mask)







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Union[str, Any]		     =	self.prepare_config_and_inputs()
         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	config_and_inputs
         __UpperCamelCase						:						Optional[Any]		     =	{'input_ids': input_ids, 'attention_mask': attention_mask}
         return config, inputs_dict







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.prepare_config_and_inputs()

         __UpperCamelCase						:						Optional[Any]		     =	floats_tensor([self.batch_size, self.seq_length, self.hidden_size]     )
         __UpperCamelCase						:						List[Any]		     =	ids_tensor([self.batch_size, self.seq_length]  ,      vocab_size=2     )

         return (
             config,
             input_ids,
             attention_mask,
             encoder_hidden_states,
             encoder_attention_mask,
         )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         __UpperCamelCase						:						str		     =	2_0
         __UpperCamelCase						:						List[Any]		     =	model_class_name(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	model.init_cache(input_ids.shape[0]  ,      _lowerCamelCase     )
         __UpperCamelCase						:						Union[str, Any]		     =	jnp.ones((input_ids.shape[0], max_decoder_length)  ,      dtype='i4'     )

         __UpperCamelCase						:						List[str]		     =	jnp.broadcast_to(
             jnp.arange(input_ids.shape[-1] - 1     )[None, :]  ,      (input_ids.shape[0], input_ids.shape[-1] - 1)     )
         __UpperCamelCase						:						List[Any]		     =	model(
             input_ids[:, :-1]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						int		     =	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]  ,      dtype='i4'     )
         __UpperCamelCase						:						Tuple		     =	model(
             input_ids[:, -1:]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=outputs_cache.past_key_values  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						List[str]		     =	model(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[int]		     =	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
         self.parent.assertTrue(diff < 1E-3  ,      msg=f"""Max diff is {diff}"""     )







     def lowerCAmelCase  (		self  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         __UpperCamelCase						:						Optional[Any]		     =	2_0
         __UpperCamelCase						:						Any		     =	model_class_name(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	jnp.concatenate(
             [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1])     )]  ,      axis=-1  ,      )

         __UpperCamelCase						:						Any		     =	model.init_cache(input_ids.shape[0]  ,      _lowerCamelCase     )
         __UpperCamelCase						:						Optional[Any]		     =	jnp.broadcast_to(
             jnp.arange(input_ids.shape[-1] - 1     )[None, :]  ,      (input_ids.shape[0], input_ids.shape[-1] - 1)     )

         __UpperCamelCase						:						List[Any]		     =	model(
             input_ids[:, :-1]  ,      attention_mask=_lowerCamelCase  ,      past_key_values=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )
         __UpperCamelCase						:						Any		     =	jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]  ,      dtype='i4'     )
         __UpperCamelCase						:						Dict		     =	model(
             input_ids[:, -1:]  ,      past_key_values=outputs_cache.past_key_values  ,      attention_mask=_lowerCamelCase  ,      position_ids=_lowerCamelCase  ,      )

         __UpperCamelCase						:						Optional[Any]		     =	model(_lowerCamelCase  ,      attention_mask=_lowerCamelCase     )

         __UpperCamelCase						:						Any		     =	np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])     )     )
         self.parent.assertTrue(diff < 1E-3  ,      msg=f"""Max diff is {diff}"""     )






@require_flax
class       __lowercase		(    _lowerCamelCase      ,				_lowerCamelCase      ,				unittest.TestCase    ):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		 =    (FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
     SCREAMING_SNAKE_CASE__		 =    (FlaxGPTaLMHeadModel,) if is_flax_available() else ()







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	FlaxGPTaModelTester(self     )







     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Union[str, Any]		     =	self.model_tester.prepare_config_and_inputs()
             self.model_tester.check_use_cache_forward(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase     ,       __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs()
             self.model_tester.check_use_cache_forward_with_attn_mask(
                 _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )







     @slow
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[int]		     =	GPTaTokenizer.from_pretrained('gpt2'  ,      pad_token='</s>'  ,      padding_side='left'     )
         __UpperCamelCase						:						str		     =	tokenizer(['Hello this is a long string', 'Hey']  ,      return_tensors='np'  ,      padding=_lowerCamelCase  ,      truncation=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	FlaxGPTaLMHeadModel.from_pretrained('gpt2'     )
         __UpperCamelCase						:						Union[str, Any]		     =	False
         __UpperCamelCase						:						Optional[Any]		     =	model.config.eos_token_id

         __UpperCamelCase						:						List[str]		     =	jax.jit(model.generate     )

         __UpperCamelCase						:						List[str]		     =	jit_generate(inputs['input_ids']  ,      attention_mask=inputs['attention_mask']     ).sequences

         __UpperCamelCase						:						Optional[int]		     =	tokenizer.batch_decode(_lowerCamelCase  ,      skip_special_tokens=_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	[
             'Hello this is a long string of words. I\'m going to start with the first one.\n',
             'Hey, I\'m not sure if I\'m going to be able to do',
         ]

         self.assertListEqual(_lowerCamelCase  ,      _lowerCamelCase     )







     @is_pt_flax_cross_test
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__     ):
                 # prepare inputs
                 __UpperCamelCase						:						Tuple		     =	self._prepare_for_class(_lowerCamelCase  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						Dict		     =	{k: torch.tensor(v.tolist()     ) for k, v in prepared_inputs_dict.items()}

                 # load corresponding PyTorch class
                 __UpperCamelCase						:						Union[str, Any]		     =	model_class.__name__[4:]  # Skip the "Flax" at the beginning
                 __UpperCamelCase						:						List[str]		     =	getattr(_lowerCamelCase  ,      _lowerCamelCase     )

                 __UpperCamelCase     ,       __UpperCamelCase						:						Tuple		     =	pt_inputs['input_ids'].shape
                 __UpperCamelCase						:						int		     =	np.random.randint(0  ,      seq_length - 1  ,      size=(batch_size,)     )
                 for batch_idx, start_index in enumerate(_lowerCamelCase     ):
                     __UpperCamelCase						:						int		     =	0
                     __UpperCamelCase						:						Tuple		     =	1
                     __UpperCamelCase						:						Optional[int]		     =	0
                     __UpperCamelCase						:						List[Any]		     =	1
                 __UpperCamelCase						:						str		     =	pt_model_class(_lowerCamelCase     ).eval()
                 __UpperCamelCase						:						Union[str, Any]		     =	model_class(_lowerCamelCase  ,      dtype=jnp.floataa     )

                 __UpperCamelCase						:						Optional[int]		     =	convert_pytorch_state_dict_to_flax(pt_model.state_dict()  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						List[str]		     =	fx_state

                 with torch.no_grad():
                     __UpperCamelCase						:						List[Any]		     =	pt_model(**_lowerCamelCase     ).to_tuple()

                 __UpperCamelCase						:						str		     =	fx_model(**_lowerCamelCase     ).to_tuple()
                 self.assertEqual(len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )

                 with tempfile.TemporaryDirectory() as tmpdirname:
                     pt_model.save_pretrained(_lowerCamelCase     )
                     __UpperCamelCase						:						Any		     =	model_class.from_pretrained(_lowerCamelCase  ,      from_pt=_lowerCamelCase     )

                 __UpperCamelCase						:						Union[str, Any]		     =	fx_model_loaded(**_lowerCamelCase     ).to_tuple()
                 self.assertEqual(
                     len(_lowerCamelCase     )  ,      len(_lowerCamelCase     )  ,      'Output lengths differ between Flax and PyTorch'     )
                 for fx_output_loaded, pt_output in zip(_lowerCamelCase  ,      _lowerCamelCase     ):
                     self.assert_almost_equals(fx_output_loaded[:, -1]  ,      pt_output[:, -1].numpy()  ,      4E-2     )







     @is_pt_flax_cross_test
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[Any]		     =	self.model_tester.prepare_config_and_inputs_for_common()
         for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__     ):
                 # prepare inputs
                 __UpperCamelCase						:						Tuple		     =	self._prepare_for_class(_lowerCamelCase  ,      _lowerCamelCase     )
                 __UpperCamelCase						:						int		     =	{k: torch.tensor(v.tolist()     ) for k, v in prepared_inputs_dict.items()}

                 # load corresponding PyTorch class
                 __UpperCamelCase						:						Optional[Any]		     =	model_class.__name__[4:]  # Skip the "Flax" at the beginning
                 __UpperCamelCase						:						int		     =	getattr(_lowerCamelCase  ,      _lowerCamelCase     )

                 __UpperCamelCase						:						Optional[Any]		     =	pt_model_class(_lowerCamelCase     ).eval()
                 __UpperCamelCase						:						List[Any]		     =	model_class(_lowerCamelCase  ,      dtype=jnp.floataa     )

                 __UpperCamelCase						:						str		     =	load_flax_weights_in_pytorch_model(_lowerCamelCase  ,      fx_model.params     )
                 __UpperCamelCase     ,       __UpperCamelCase						:						int		     =	pt_inputs['input_ids'].shape
                 __UpperCamelCase						:						Dict		     =	np.random.randint(0  ,      seq_length - 1  ,      size=(batch_size,)     )
                 for batch_idx, start_index in enumerate(_lowerCamelCase     ):
                     __UpperCamelCase						:						Union[str, Any]		     =	0
                     __UpperCamelCase						:						List[str]		     =	1
                     __UpperCamelCase						:						Optional[int]		     =	0
                     __UpperCamelCase						:						Optional[int]		     =	1

                 # make sure weights are tied in PyTorch
                 pt_model.tie_weights()

                 with torch.no_grad():
                     __UpperCamelCase						:						Any		     =	pt_model(**_lowerCamelCase     ).to_tuple()

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

                 with tempfile.TemporaryDirectory() as tmpdirname:
                     fx_model.save_pretrained(_lowerCamelCase     )
                     __UpperCamelCase						:						int		     =	pt_model_class.from_pretrained(_lowerCamelCase  ,      from_flax=_lowerCamelCase     )

                 with torch.no_grad():
                     __UpperCamelCase						:						Dict		     =	pt_model_loaded(**_lowerCamelCase     ).to_tuple()

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







     @slow
     def lowerCAmelCase  (		self     ):
         for model_class_name in self.all_model_classes:
             __UpperCamelCase						:						Union[str, Any]		     =	model_class_name.from_pretrained('gpt2'  ,      from_pt=_lowerCamelCase     )
             __UpperCamelCase						:						List[str]		     =	model(np.ones((1, 1)     )     )
             self.assertIsNotNone(_lowerCamelCase     )



