




'''simple docstring'''







import random
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						import PIL

						from transformers import FlavaImageProcessor
						from transformers.image_utils import PILImageResampling
						from transformers.models.flava.image_processing_flava import (
						    FLAVA_CODEBOOK_MEAN,
						    FLAVA_CODEBOOK_STD,
						    FLAVA_IMAGE_MEAN,
						    FLAVA_IMAGE_STD,
						)
else:
						_lowerCamelCase							:						Any								=  None





class      lowerCamelCase_							(       unittest.TestCase							):




					'''simple docstring'''






					def __init__(    self,  __UpperCamelCase,  __UpperCamelCase=7,  __UpperCamelCase=3,  __UpperCamelCase=30,  __UpperCamelCase=400,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=1 / 255,  __UpperCamelCase=True,  __UpperCamelCase=FLAVA_IMAGE_MEAN,  __UpperCamelCase=FLAVA_IMAGE_STD,  __UpperCamelCase=14,  __UpperCamelCase=75,  __UpperCamelCase=None,  __UpperCamelCase=16,  __UpperCamelCase=0.3,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=None,  __UpperCamelCase=True,  __UpperCamelCase=True,  __UpperCamelCase=FLAVA_CODEBOOK_MEAN,  __UpperCamelCase=FLAVA_CODEBOOK_STD,  ):
							_snake_case	       =       size if size is not None else {"height": 224, "width": 224}
							_snake_case	       =       crop_size if crop_size is not None else {"height": 224, "width": 224}
							_snake_case	       =       codebook_size if codebook_size is not None else {"height": 112, "width": 112}
							_snake_case	       =       codebook_crop_size if codebook_crop_size is not None else {"height": 112, "width": 112}

							_snake_case	       =       parent
							_snake_case	       =       batch_size
							_snake_case	       =       num_channels
							_snake_case	       =       do_resize
							_snake_case	       =       do_rescale
							_snake_case	       =       rescale_factor
							_snake_case	       =       min_resolution
							_snake_case	       =       max_resolution
							_snake_case	       =       size
							_snake_case	       =       resample if resample is not None else PILImageResampling.BICUBIC
							_snake_case	       =       do_normalize
							_snake_case	       =       image_mean
							_snake_case	       =       image_std
							_snake_case	       =       do_center_crop
							_snake_case	       =       crop_size

							_snake_case	       =       input_size_patches
							_snake_case	       =       total_mask_patches
							_snake_case	       =       mask_group_max_patches
							_snake_case	       =       mask_group_min_patches
							_snake_case	       =       mask_group_min_aspect_ratio
							_snake_case	       =       mask_group_max_aspect_ratio

							_snake_case	       =       codebook_do_resize
							_snake_case	       =       codebook_size
							_snake_case	       =       codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
							_snake_case	       =       codebook_do_center_crop
							_snake_case	       =       codebook_crop_size
							_snake_case	       =       codebook_do_map_pixels
							_snake_case	       =       codebook_do_normalize
							_snake_case	       =       codebook_image_mean
							_snake_case	       =       codebook_image_std






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							return {
							    "image_mean": self.image_mean,
							    "image_std": self.image_std,
							    "do_normalize": self.do_normalize,
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "resample": self.resample,
							    "do_rescale": self.do_rescale,
							    "rescale_factor": self.rescale_factor,
							    "do_center_crop": self.do_center_crop,
							    "crop_size": self.crop_size,
							    "input_size_patches": self.input_size_patches,
							    "total_mask_patches": self.total_mask_patches,
							    "mask_group_max_patches": self.mask_group_max_patches,
							    "mask_group_min_patches": self.mask_group_min_patches,
							    "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
							    "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
							    "codebook_do_resize": self.codebook_do_resize,
							    "codebook_size": self.codebook_size,
							    "codebook_resample": self.codebook_resample,
							    "codebook_do_center_crop": self.codebook_do_center_crop,
							    "codebook_crop_size": self.codebook_crop_size,
							    "codebook_do_map_pixels": self.codebook_do_map_pixels,
							    "codebook_do_normalize": self.codebook_do_normalize,
							    "codebook_image_mean": self.codebook_image_mean,
							    "codebook_image_std": self.codebook_image_std,
							}






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							return (self.size["height"], self.size["width"])






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							return (
							    (self.input_size_patches, self.input_size_patches)
							    if not isinstance(self.input_size_patches,  __UpperCamelCase )
							    else self.input_size_patches
							)






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							return (self.codebook_size["height"], self.codebook_size["width"])





@require_torch
@require_vision
class      lowerCamelCase_							(       UpperCAmelCase_,       unittest.TestCase							):




					'''simple docstring'''






					lowercase__    = FlavaImageProcessor if is_vision_available() else None
					lowercase__    = None






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							_snake_case	       =       FlavaImageProcessingTester(self )






					@property
					def 				__SCREAMING_SNAKE_CASE	(    self ):
							return self.image_processor_tester.prepare_image_processor_dict()






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							_snake_case	       =       self.image_processing_class(**self.image_processor_dict )
							self.assertTrue(hasattr(__UpperCamelCase,  "image_mean" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "image_std" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "do_normalize" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "do_resize" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "resample" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "crop_size" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "do_center_crop" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "do_rescale" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "rescale_factor" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "masking_generator" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_do_resize" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_size" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_resample" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_do_center_crop" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_crop_size" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_do_map_pixels" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_do_normalize" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_image_mean" ) )
							self.assertTrue(hasattr(__UpperCamelCase,  "codebook_image_std" ) )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							_snake_case	       =       self.image_processing_class.from_dict(self.image_processor_dict )
							self.assertEqual(image_processor.size,  {"height": 224, "width": 224} )
							self.assertEqual(image_processor.crop_size,  {"height": 224, "width": 224} )
							self.assertEqual(image_processor.codebook_size,  {"height": 112, "width": 112} )
							self.assertEqual(image_processor.codebook_crop_size,  {"height": 112, "width": 112} )

							_snake_case	       =       self.image_processing_class.from_dict(
							    self.image_processor_dict,  size=42,  crop_size=84,  codebook_size=33,  codebook_crop_size=66 )
							self.assertEqual(image_processor.size,  {"height": 42, "width": 42} )
							self.assertEqual(image_processor.crop_size,  {"height": 84, "width": 84} )
							self.assertEqual(image_processor.codebook_size,  {"height": 33, "width": 33} )
							self.assertEqual(image_processor.codebook_crop_size,  {"height": 66, "width": 66} )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							pass






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							# Initialize image_processing
							_snake_case	       =       self.image_processing_class(**self.image_processor_dict )
							# create random PIL images
							_snake_case	       =       prepare_image_inputs(self.image_processor_tester,  equal_resolution=__UpperCamelCase )
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  PIL.Image.Image )

							# Test not batched input
							_snake_case	       =       image_processing(image_inputs[0],  return_tensors="pt" )

							# Test no bool masked pos
							self.assertFalse("bool_masked_pos" in encoded_images )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()

							self.assertEqual(
							    encoded_images.pixel_values.shape,  (1, self.image_processor_tester.num_channels, expected_height, expected_width),  )

							# Test batched
							_snake_case	       =       image_processing(__UpperCamelCase,  return_tensors="pt" )
							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()

							# Test no bool masked pos
							self.assertFalse("bool_masked_pos" in encoded_images )

							self.assertEqual(
							    encoded_images.pixel_values.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    ),  )






					def 				__SCREAMING_SNAKE_CASE	(    self,  __UpperCamelCase,  __UpperCamelCase ):
							# Initialize image_processing
							_snake_case	       =       self.image_processing_class(**self.image_processor_dict )
							# create random tensors
							_snake_case	       =       prepare_image_inputs(self.image_processor_tester,  equal_resolution=__UpperCamelCase,  **__UpperCamelCase )
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  __UpperCamelCase )

							# Test not batched input
							_snake_case	       =       image_processing(image_inputs[0],  return_tensors="pt" )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape,  (1, self.image_processor_tester.num_channels, expected_height, expected_width),  )

							_snake_case	       =       image_processing(__UpperCamelCase,  return_image_mask=__UpperCamelCase,  return_tensors="pt" )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    ),  )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_mask_size()
							self.assertEqual(
							    encoded_images.bool_masked_pos.shape,  (
							        self.image_processor_tester.batch_size,
							        expected_height,
							        expected_width,
							    ),  )

							# Test batched
							_snake_case	       =       image_processing(__UpperCamelCase,  return_tensors="pt" ).pixel_values

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    ),  )

							# Test masking
							_snake_case	       =       image_processing(__UpperCamelCase,  return_image_mask=__UpperCamelCase,  return_tensors="pt" )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_image_size()
							self.assertEqual(
							    encoded_images.pixel_values.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    ),  )

							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_mask_size()
							self.assertEqual(
							    encoded_images.bool_masked_pos.shape,  (
							        self.image_processor_tester.batch_size,
							        expected_height,
							        expected_width,
							    ),  )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							self._test_call_framework(np.ndarray,  prepare_kwargs={"numpify": True} )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							self._test_call_framework(torch.Tensor,  prepare_kwargs={"torchify": True} )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							# Initialize image_processing
							random.seed(1_234 )
							_snake_case	       =       self.image_processing_class(**self.image_processor_dict )
							_snake_case	       =       prepare_image_inputs(self.image_processor_tester,  equal_resolution=__UpperCamelCase,  torchify=__UpperCamelCase )

							# Test not batched input
							_snake_case	       =       image_processing(image_inputs[0],  return_image_mask=__UpperCamelCase,  return_tensors="pt" )
							self.assertEqual(encoded_images.bool_masked_pos.sum().item(),  75 )






					def 				__SCREAMING_SNAKE_CASE	(    self ):
							# Initialize image_processing
							_snake_case	       =       self.image_processing_class(**self.image_processor_dict )
							# create random PIL images
							_snake_case	       =       prepare_image_inputs(self.image_processor_tester,  equal_resolution=__UpperCamelCase )
							for image in image_inputs:
									self.assertIsInstance(__UpperCamelCase,  PIL.Image.Image )

							# Test not batched input
							_snake_case	       =       image_processing(image_inputs[0],  return_codebook_pixels=__UpperCamelCase,  return_tensors="pt" )
							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_codebook_image_size()
							self.assertEqual(
							    encoded_images.codebook_pixel_values.shape,  (1, self.image_processor_tester.num_channels, expected_height, expected_width),  )

							# Test batched
							_snake_case	       =       image_processing(__UpperCamelCase,  return_codebook_pixels=__UpperCamelCase,  return_tensors="pt" )
							_snake_case       ,    _snake_case	       =       self.image_processor_tester.get_expected_codebook_image_size()
							self.assertEqual(
							    encoded_images.codebook_pixel_values.shape,  (
							        self.image_processor_tester.batch_size,
							        self.image_processor_tester.num_channels,
							        expected_height,
							        expected_width,
							    ),  )












"""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		)
