



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  _snake_case	:




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




				def 							A__					(  self    :  int  ):
							lowercase__         = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

							lowercase__         = self.get_config()

							return config, pixel_values, labels




				def 							A__					(  self    :  Union[str, Any]  ):
							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 							A__					(  self    :  List[str],    __lowercase    :  Dict,    __lowercase    :  Dict,    __lowercase    :  Optional[int]  ):
							lowercase__         = TFSwinModel(config=__a  )
							lowercase__         = model(__a  )

							lowercase__         = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths  ) - 1))
							lowercase__         = 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 							A__					(  self    :  Optional[int],    __lowercase    :  Optional[int],    __lowercase    :  int,    __lowercase    :  Optional[Any]  ):
							lowercase__         = TFSwinForMaskedImageModeling(config=__a  )
							lowercase__         = model(__a  )
							self.parent.assertEqual(
							    result.logits.shape,    (self.batch_size, self.num_channels, self.image_size, self.image_size)  )

							# test greyscale images
							lowercase__         = 1
							lowercase__         = TFSwinForMaskedImageModeling(__a  )

							lowercase__         = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
							lowercase__         = model(__a  )
							self.parent.assertEqual(result.logits.shape,    (self.batch_size, 1, self.image_size, self.image_size)  )




				def 							A__					(  self    :  List[str],    __lowercase    :  Optional[int],    __lowercase    :  Union[str, Any],    __lowercase    :  List[str]  ):
							lowercase__         = self.type_sequence_label_size
							lowercase__         = TFSwinForImageClassification(__a  )
							lowercase__         = model(__a,    labels=__a  )
							self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.type_sequence_label_size)  )

							# test greyscale images
							lowercase__         = 1
							lowercase__         = TFSwinForImageClassification(__a  )
							lowercase__         = floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
							lowercase__         = model(__a  )
							self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.type_sequence_label_size)  )




				def 							A__					(  self    :  Tuple  ):
							lowercase__         = self.prepare_config_and_inputs()
							lowercase__         = config_and_inputs
							lowercase__         = {"pixel_values": pixel_values}
							return config, inputs_dict
@require_tf
class  _snake_case	(    _UpperCamelCase			,		_UpperCamelCase			,		unittest.TestCase):
				UpperCamelCase__ :    List[str]   						=(
				    (
				        TFSwinModel,
				        TFSwinForImageClassification,
				        TFSwinForMaskedImageModeling,
				    )
				    if is_tf_available()
				    else ()
				)
				UpperCamelCase__ :    List[str]   						=(
				    {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCamelCase__ :    Union[str, Any]   						=False
				UpperCamelCase__ :    str   						=False
				UpperCamelCase__ :    Dict   						=False
				UpperCamelCase__ :    Optional[Any]   						=False




				def 							A__					(  self    :  List[str]  ):
							lowercase__         = TFSwinModelTester(self  )
							lowercase__         = ConfigTester(self,    config_class=__a,    embed_dim=37  )




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




				def 							A__					(  self    :  int  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__a  )




				def 							A__					(  self    :  Tuple  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*__a  )




				def 							A__					(  self    :  Optional[int]  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__a  )




				@unittest.skip(reason="Swin does not use inputs_embeds"  )
				def 							A__					(  self    :  str  ):
							pass




				def 							A__					(  self    :  List[Any]  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs_for_common()

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




				def 							A__					(  self    :  Tuple  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs_for_common()

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

										lowercase__         = ["pixel_values"]
										self.assertListEqual(arg_names[:1],    __a  )




				def 							A__					(  self    :  Dict  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs_for_common()
							lowercase__         = True

							for model_class in self.all_model_classes:
										lowercase__         = True
										lowercase__         = False
										lowercase__         = True
										lowercase__         = model_class(__a  )
										lowercase__         = model(**self._prepare_for_class(__a,    __a  )  )
										lowercase__         = outputs.attentions
										lowercase__         = len(self.model_tester.depths  )
										self.assertEqual(len(__a  ),    __a  )

										# check that output_attentions also work using config
										del inputs_dict["output_attentions"]
										lowercase__         = True
										lowercase__         = config.window_size**2
										lowercase__         = model_class(__a  )
										lowercase__         = model(**self._prepare_for_class(__a,    __a  )  )
										lowercase__         = outputs.attentions
										self.assertEqual(len(__a  ),    __a  )

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

										# Check attention is always last and order is fine
										lowercase__         = True
										lowercase__         = True
										lowercase__         = model_class(__a  )
										lowercase__         = model(**self._prepare_for_class(__a,    __a  )  )

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

										lowercase__         = outputs.attentions

										self.assertEqual(len(__a  ),    __a  )

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




				def 							A__					(  self    :  Optional[int],    __lowercase    :  Dict,    __lowercase    :  int,    __lowercase    :  Optional[Any],    __lowercase    :  List[str]  ):
							lowercase__         = model_class(__a  )
							lowercase__         = model(**self._prepare_for_class(__a,    __a  )  )
							lowercase__         = outputs.hidden_states

							lowercase__         = getattr(
							    self.model_tester,    "expected_num_hidden_layers",    len(self.model_tester.depths  ) + 1  )
							self.assertEqual(len(__a  ),    __a  )

							# Swin has a different seq_length
							lowercase__         = to_atuple(config.patch_size  )

							lowercase__         = (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],    )

							lowercase__         = outputs.reshaped_hidden_states
							self.assertEqual(len(__a  ),    __a  )

							lowercase__         = reshaped_hidden_states[0].shape

							lowercase__         = tf.reshape(reshaped_hidden_states[0],    (batch_size, num_channels, height * width)  )
							lowercase__         = tf.transpose(__a,    (0, 2, 1)  )

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




				def 							A__					(  self    :  List[str]  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs_for_common()

							lowercase__         = to_atuple(self.model_tester.image_size  )

							for model_class in self.all_model_classes:
										lowercase__         = True
										self.check_hidden_states_output(__a,    __a,    __a,    __a  )

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

										self.check_hidden_states_output(__a,    __a,    __a,    __a  )




				def 							A__					(  self    :  Optional[int]  ):
							lowercase__         = self.model_tester.prepare_config_and_inputs_for_common()
							lowercase__         = 3

							lowercase__         = to_atuple(self.model_tester.image_size  )
							lowercase__         = to_atuple(config.patch_size  )

							lowercase__         = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
							lowercase__         = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

							for model_class in self.all_model_classes:
										lowercase__         = True
										self.check_hidden_states_output(__a,    __a,    __a,    (padded_height, padded_width)  )

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										lowercase__         = True
										self.check_hidden_states_output(__a,    __a,    __a,    (padded_height, padded_width)  )




				@slow
				def 							A__					(  self    :  Any  ):
							for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowercase__         = TFSwinModel.from_pretrained(__a  )
										self.assertIsNotNone(__a  )
@require_vision
@require_tf
class  _snake_case	(    unittest.TestCase):




				@cached_property
				def 							A__					(  self    :  str  ):
							return (
							    AutoImageProcessor.from_pretrained("microsoft/swin-tiny-patch4-window7-224"  )
							    if is_vision_available()
							    else None
							)




				@slow
				def 							A__					(  self    :  Tuple  ):
							lowercase__         = TFSwinForImageClassification.from_pretrained("microsoft/swin-tiny-patch4-window7-224"  )
							lowercase__         = self.default_image_processor

							lowercase__         = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
							lowercase__         = image_processor(images=__a,    return_tensors="tf"  )

							# forward pass
							lowercase__         = model(__a  )

							# verify the logits
							lowercase__         = tf.TensorShape((1, 1000)  )
							self.assertEqual(outputs.logits.shape,    __a  )
							lowercase__         = tf.constant([-0.0948, -0.6454, -0.0921]  )
							self.assertTrue(np.allclose(outputs.logits[0, :3],    __a,    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    __SCREAMING_SNAKE_CASE			:







  '''simple docstring'''


  def __init__(						self      :				Any    ,      __a      :				Dict    ,      __a      :				Optional[Any]=14    ,      __a      :				Tuple=7    ,      __a      :				Dict=True    ,      __a      :				str=True    ,      __a      :				int=False    ,      __a      :				Optional[Any]=True    ,      __a      :				Any=99    ,      __a      :				int=32    ,      __a      :				Any=5    ,      __a      :				Dict=4    ,      __a      :				List[Any]=37    ,      __a      :				List[Any]="gelu"    ,      __a      :				List[Any]=0.1    ,      __a      :				Any=0.1    ,      __a      :				Optional[int]=512    ,      __a      :				Dict=0.02    ,      )						-> Union[str, Any]:
        _UpperCamelCase					:		Union[str, Any]  =				parent
        _UpperCamelCase					:		Any  =				batch_size
        _UpperCamelCase					:		Optional[int]  =				seq_length
        _UpperCamelCase					:		Tuple  =				is_training
        _UpperCamelCase					:		Optional[int]  =				use_input_mask
        _UpperCamelCase					:		Any  =				use_token_type_ids
        _UpperCamelCase					:		List[str]  =				use_labels
        _UpperCamelCase					:		List[str]  =				vocab_size
        _UpperCamelCase					:		Any  =				hidden_size
        _UpperCamelCase					:		Dict  =				num_hidden_layers
        _UpperCamelCase					:		str  =				num_attention_heads
        _UpperCamelCase					:		List[str]  =				intermediate_size
        _UpperCamelCase					:		Optional[Any]  =				hidden_act
        _UpperCamelCase					:		Tuple  =				hidden_dropout_prob
        _UpperCamelCase					:		str  =				attention_probs_dropout_prob
        _UpperCamelCase					:		Tuple  =				max_position_embeddings
        _UpperCamelCase					:		str  =				initializer_range
        _UpperCamelCase					:		List[str]  =				None
        _UpperCamelCase					:		str  =				vocab_size - 1
        _UpperCamelCase					:		Any  =				vocab_size - 1
        _UpperCamelCase					:		Dict  =				vocab_size - 1

  def       __SCREAMING_SNAKE_CASE (						self      :				List[Any]		)						-> Union[str, Any]:
        _UpperCamelCase					:		int  =				ids_tensor([self.batch_size, self.seq_length]    ,      self.vocab_size		)

        _UpperCamelCase					:		List[Any]  =				None
        if self.use_input_mask:
              _UpperCamelCase					:		int  =				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=__a    ,      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       __SCREAMING_SNAKE_CASE (						self      :				List[str]		)						-> List[Any]:
        _UpperCamelCase					:		Optional[Any]  =				self.prepare_config_and_inputs()
        _UpperCamelCase,     _UpperCamelCase,     _UpperCamelCase					:		Union[str, Any]  =				config_and_inputs
        _UpperCamelCase					:		Optional[int]  =				{"input_ids": input_ids, "attention_mask": attention_mask}
        return config, inputs_dict

  def       __SCREAMING_SNAKE_CASE (						self      :				int		)						-> List[Any]:
        _UpperCamelCase,     _UpperCamelCase,     _UpperCamelCase					:		int  =				self.prepare_config_and_inputs()

        _UpperCamelCase					:		Tuple  =				floats_tensor([self.batch_size, self.seq_length, self.hidden_size]		)
        _UpperCamelCase					:		Optional[int]  =				ids_tensor([self.batch_size, self.seq_length]    ,      vocab_size=2		)

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

  def       __SCREAMING_SNAKE_CASE (						self      :				Tuple    ,      __a      :				Any    ,      __a      :				int    ,      __a      :				List[str]    ,      __a      :				List[Any]		)						-> List[Any]:
        _UpperCamelCase					:		List[str]  =				20
        _UpperCamelCase					:		Tuple  =				model_class_name(__a		)

        _UpperCamelCase					:		Optional[Any]  =				model.init_cache(input_ids.shape[0]    ,      __a		)
        _UpperCamelCase					:		Union[str, Any]  =				jnp.ones((input_ids.shape[0], max_decoder_length)    ,      dtype="i4"		)

        _UpperCamelCase					:		Optional[Any]  =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1		)[None, :]    ,      (input_ids.shape[0], input_ids.shape[-1] - 1)		)
        _UpperCamelCase					:		Optional[int]  =				model(
            input_ids[:, :-1]    ,      attention_mask=__a    ,      past_key_values=__a    ,      position_ids=__a    ,      )

        _UpperCamelCase					:		Dict  =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]    ,      dtype="i4"		)
        _UpperCamelCase					:		Optional[Any]  =				model(
            input_ids[:, -1:]    ,      attention_mask=__a    ,      past_key_values=outputs_cache.past_key_values    ,      position_ids=__a    ,      )

        _UpperCamelCase					:		Optional[Any]  =				model(__a		)

        _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       __SCREAMING_SNAKE_CASE (						self      :				Optional[Any]    ,      __a      :				Dict    ,      __a      :				str    ,      __a      :				Any    ,      __a      :				Dict		)						-> int:
        _UpperCamelCase					:		Optional[Any]  =				20
        _UpperCamelCase					:		Tuple  =				model_class_name(__a		)

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

        _UpperCamelCase					:		str  =				model.init_cache(input_ids.shape[0]    ,      __a		)
        _UpperCamelCase					:		str  =				jnp.broadcast_to(
            jnp.arange(input_ids.shape[-1] - 1		)[None, :]    ,      (input_ids.shape[0], input_ids.shape[-1] - 1)		)

        _UpperCamelCase					:		Tuple  =				model(
            input_ids[:, :-1]    ,      attention_mask=__a    ,      past_key_values=__a    ,      position_ids=__a    ,      )
        _UpperCamelCase					:		Any  =				jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]]    ,      dtype="i4"		)
        _UpperCamelCase					:		List[Any]  =				model(
            input_ids[:, -1:]    ,      past_key_values=outputs_cache.past_key_values    ,      attention_mask=__a    ,      position_ids=__a    ,      )

        _UpperCamelCase					:		Tuple  =				model(__a    ,      attention_mask=__a		)

        _UpperCamelCase					:		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}'''		)





@require_flax
class    __SCREAMING_SNAKE_CASE			(  _UpperCamelCase						,     _UpperCamelCase						,     unittest.TestCase      ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:Tuple		   =    (FlaxGPTaModel, FlaxGPTaLMHeadModel) if is_flax_available() else ()
  SCREAMING_SNAKE_CASE__							:List[str]		   =    (FlaxGPTaLMHeadModel,) if is_flax_available() else ()

  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]		)						-> Optional[int]:
        _UpperCamelCase					:		str  =				FlaxGPTaModelTester(self		)

  def       __SCREAMING_SNAKE_CASE (						self      :				int		)						-> Optional[Any]:
        for model_class_name in self.all_model_classes:
              _UpperCamelCase,     _UpperCamelCase,     _UpperCamelCase					:		List[str]  =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward(__a    ,      __a    ,      __a    ,      __a		)

  def       __SCREAMING_SNAKE_CASE (						self      :				int		)						-> int:
        for model_class_name in self.all_model_classes:
              _UpperCamelCase,     _UpperCamelCase,     _UpperCamelCase					:		int  =				self.model_tester.prepare_config_and_inputs()
              self.model_tester.check_use_cache_forward_with_attn_mask(
                  __a    ,      __a    ,      __a    ,      __a		)

  @slow
  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[Any]		)						-> Dict:
        _UpperCamelCase					:		Optional[int]  =				GPTaTokenizer.from_pretrained("gpt2"    ,      pad_token="</s>"    ,      padding_side="left"		)
        _UpperCamelCase					:		Optional[int]  =				tokenizer(["Hello this is a long string", "Hey"]    ,      return_tensors="np"    ,      padding=__a    ,      truncation=__a		)

        _UpperCamelCase					:		Tuple  =				FlaxGPTaLMHeadModel.from_pretrained("gpt2"		)
        _UpperCamelCase					:		Optional[Any]  =				False
        _UpperCamelCase					:		str  =				model.config.eos_token_id

        _UpperCamelCase					:		Any  =				jax.jit(model.generate		)

        _UpperCamelCase					:		Optional[Any]  =				jit_generate(inputs["input_ids"]    ,      attention_mask=inputs["attention_mask"]		).sequences

        _UpperCamelCase					:		Tuple  =				tokenizer.batch_decode(__a    ,      skip_special_tokens=__a		)

        _UpperCamelCase					:		Any  =				[
            "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(__a    ,      __a		)

  @is_pt_flax_cross_test
  def       __SCREAMING_SNAKE_CASE (						self      :				Optional[int]		)						-> List[str]:
        _UpperCamelCase,     _UpperCamelCase					:		List[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					:		Optional[Any]  =				self._prepare_for_class(__a    ,      __a		)
                    _UpperCamelCase					:		int  =				{k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

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

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

                    _UpperCamelCase					:		int  =				convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,      __a		)
                    _UpperCamelCase					:		List[Any]  =				fx_state

                    with torch.no_grad():
                          _UpperCamelCase					:		List[str]  =				pt_model(**__a		).to_tuple()

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

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

                    _UpperCamelCase					:		Tuple  =				fx_model_loaded(**__a		).to_tuple()
                    self.assertEqual(
                        len(__a		)    ,      len(__a		)    ,      "Output lengths differ between Flax and PyTorch"		)
                    for fx_output_loaded, pt_output in zip(__a    ,      __a		):
                          self.assert_almost_equals(fx_output_loaded[:, -1]    ,      pt_output[:, -1].numpy()    ,      4e-2		)

  @is_pt_flax_cross_test
  def       __SCREAMING_SNAKE_CASE (						self      :				Union[str, Any]		)						-> Dict:
        _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					:		Union[str, Any]  =				self._prepare_for_class(__a    ,      __a		)
                    _UpperCamelCase					:		Optional[Any]  =				{k: torch.tensor(v.tolist()		) for k, v in prepared_inputs_dict.items()}

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

                    _UpperCamelCase					:		Dict  =				pt_model_class(__a		).eval()
                    _UpperCamelCase					:		Tuple  =				model_class(__a    ,      dtype=jnp.floataa		)

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

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

                    with torch.no_grad():
                          _UpperCamelCase					:		Optional[int]  =				pt_model(**__a		).to_tuple()

                    _UpperCamelCase					:		List[Any]  =				fx_model(**__a		).to_tuple()
                    self.assertEqual(len(__a		)    ,      len(__a		)    ,      "Output lengths differ between Flax and PyTorch"		)
                    for fx_output, pt_output in zip(__a    ,      __a		):
                          self.assert_almost_equals(fx_output[:, -1]    ,      pt_output[:, -1].numpy()    ,      4e-2		)

                    with tempfile.TemporaryDirectory() as tmpdirname:
                          fx_model.save_pretrained(__a		)
                          _UpperCamelCase					:		Tuple  =				pt_model_class.from_pretrained(__a    ,      from_flax=__a		)

                    with torch.no_grad():
                          _UpperCamelCase					:		int  =				pt_model_loaded(**__a		).to_tuple()

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


  @slow
  def       __SCREAMING_SNAKE_CASE (						self      :				List[Any]		)						-> int:
        for model_class_name in self.all_model_classes:
              _UpperCamelCase					:		Union[str, Any]  =				model_class_name.from_pretrained("gpt2"    ,      from_pt=__a		)
              _UpperCamelCase					:		List[str]  =				model(np.ones((1, 1)		)		)
              self.assertIsNotNone(__a		)
